2

I was working on Yii2 and would like to dynamically validate the field, like validate if another field is not selected.

I found below code on Yii2 documentation:

['state', 'required', 'when' => function($model) {
    return $model->country == 'USA';
}]

But the thing is that I am using Yii2 dynamic model. How could I achieve the same thing shown above in dynamic model.

1
  • 1
    not clear how are you initializing the dynamic model you need to call addRule on the dynamic model like, $model->addRule(['field_name','string',['max'=>255]]) , and then call the validate $model->validate(), this will call the validation and show you the errors, you need to show the code. you are working on. Commented Nov 9, 2018 at 13:15

1 Answer 1

3

As usual model:

$model = new \yii\base\DynamicModel([
    'name', 'country', 'state'
]);

$model->addRule(
    'state', 'required', ['when' => function($model) {
        return $model->country == 'USA';
    }
]);
Sign up to request clarification or add additional context in comments.

1 Comment

Your parameters in addRule are incorrect. addRule requires at least 2 arguments. Should be ->addRule('state', 'required', ['when'...]);. See yiiframework.com/doc/api/2.0/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.