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

  1. Requirements
  2. Usage
  3. Resources

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/

6 0
7 followers
434 downloads
Yii Version: 1.1
License: BSD-2-Clause
Category: Validation
Developed by: Dana
Created on: Aug 9, 2011
Last updated: 12 years ago

Downloads

show all

Related Extensions