Conditional Validates

From Achievo/ATK Wiki

Jump to: navigation, search

ATK Howto: Conditional Validates

Complexity: Easy
Author: Ivo Jansch <ivo@achievo.org>

List of other Howto's

Intro

If you've worked with ATK a bit, you surely know when and how to use the AF_OBLIGATORY flag.

If you're developing a larger application in ATK, you might at some point in time get a situation where a field is required, but only in specific situations. For example, field B is only required if field A has a certain value.

This can be accomplished with only a small amount of code. This howto explains how to accomplish this.

Writing the code

Usually, you add an AF_OBLIGATORY flag directly to the attribute, to make it a required field. However, if you do that, it will be required at all times.

The solution comes down to overriding an atkNode method in your own node. By adding the AF_OBLIGATORY flag before the validation happens, but with the record in memory, we can add conditions for when to apply AF_OBLIGATORY and when not.

The method that is called on your node by the framework when validating data, is validate(). The default implementation of this method validates if obligatory fields are filled in, if fields are unique, etc.

Overriding this method is a matter of copying its signature to your node, and adding your own implementation.

Let's take an example. Say, for example, that you have a node for entering employees, and users can select an 'identification method' from a dropdown box. They can also enter a 'passport number'. But they only need to fill in the passport number, if 'identification method' is set to 'passport'. Here's what the validate() method would look like in this case:

  public function validate(&$record, $mode, $ignoreList = array())
  { 
      // Evaluate a condition
      if ($record["identification_method"]=='passport') {  
 
          // Retrieve the passport id attribute
          $passportAttr = &$this->getAttribute("passport_number");
  
          // Make the passport number obligatory
          $passportAttr->addFlag(AF_OBLIGATORY);
      }
  
      // Call the original validate method
      return parent::validate($record, $mode, $ignoreList);
  }

The last line is very important: the original validate method is called to perform the actual validation.

Note how we don't validate the data itself. Instead, we evaluate the condition, and if we want the field to be required, we add the AF_OBLIGATORY flag. We could have written our own validation here, but this approach is much easier. Complex attributes have different ways of validating if a value is considered empty or not. By only manipulating the flag, we let the framework handle the gory details of checking whether values are actually empty.

Personal tools
Navigation