Yii 1.1: childrenrequiredvalidator

Validator to ensure that children of a field are required when the field is set.
7 followers

This is a very simple validator which adds the ability to set a rule which will link attributes to a parent attribute and validate them as required only when the parent attribute requirement is met.

Requirements

Built on Yii 1.1.8

Usage

Copy the validator to your extensions or validators folder.

Add a rule to the CModel/CFormModel/CActiveRecord for the attributes you wish to validate.

By default, it will look for a true/false resolution of the parentAttribute, so if any value for it is set, then it will chain to the children. You can alternately provide an exact match string which will trigger the validation so that if you're looking for a specific drop down selection (for example) then it will be possible to do so.

If you need more functionality out of the match, you could set a magic method to the model which will return the value that you need to check. (See Example 3)

...
 
  public function rules()
  {
    return array(
        array('optionalValueOne', 'safe'),
        array('childValueOne,childValueTwo',
                 'application.components.validators.ChildrenRequiredValidator', 
                 'parentAttribute'=>'optionalValueOne'
       ),
    );
  }
  ...

Or, if you want to be more complex and require a specific value:

...
 
  public function rules()
  {
    return array(
        array('optionalValueOne', 'safe'),
        array('childValueOne,childValueTwo',
                 'application.components.validators.ChildrenRequiredValidator', 
                 'parentAttribute'=>'optionalValueOne',
                 'match'=>'Selected String',
                 'message'=>'You indicated that you use Selected String, please complete this data as well.'
       ),
    );
  }
  ...

Or, if using a magic method to determine if the parent requirement is met:

...
 
  public function rules()
  {
    return array(
        array('optionalValueOne', 'safe'),
        array('childValueOne,childValueTwo',
                 'application.components.validators.ChildrenRequiredValidator', 
                 'parentAttribute'=>'interpretedReq',
                 'message'=>'Please specify both childValueOne and childValueTwo'
       ),
    );
  }
 
  /**
   * Run some complex procedure that determines if the children fields should be
   * submitted
   * @return boolean
   */
  public function getInterpretedReq()
  {
     // some complex business logic here
     return true;
  }
  ...

Resources

Forum Discussion: http://www.yiiframework.com/forum/index.php?/topic/22458-extension-childrenrequiredvalidator/

Be the first person to leave a comment

Please to leave your comment.

Create extension