Search code examples
phpformsvalidationyii

Yii Conditional Validation


I have a question about Yii validation. I have a dropdown whose options are Y and N. If the user select Y the user must explain why he chose Y hence a textArea box will become required.

My code for the rule looks at follows.

array('explain', 'check', 'trigger'=>'med_effects'),

Check is my function used for validation

public function check($attribute, $params)
    {
        if($this->$params['trigger'] == 0 && $this->$attribute == '') {
            $this->addError($attribute, 'Explain the effects of the medicine');
        }
    }

The value for $this->$params['trigger'] does not change. I'm assuming because the saved value was 0(Y) and does not change even if the user choose N. How am I supposed to determine which option the user chose when he sumbits the form?

Thanks.


Solution

  • Create a property inside your model:

    public $isDropDownChecked;
    

    In your view, create a dropdown wired to new property created.

    And return a array of rules inside the method rules() like this:

    public function rules()
    {
       $rules[] = array(); 
    
       if ($this->isDropDownChecked == 'Y')
            $rules[] = array('explain', 'check', 'trigger'=>'med_effects');    
    
    
       return $rules;
    }