Search code examples
yii2yii2-modelyii2-validation

yii2 modal attribute as required dynamically


I have a case where a field is mandatory, but not always mandatory. If I write the attribute as required in modal rules() like: [['my_attribute'], 'required'] then it would make the field required in every case.

can I make a specific modal's attribute as required? in controller's or modal's custom function (i.e the place where I need the field to be mandatory).

P.S: i want to avoid jQuery and JavaScript. Please answer if there is a way in Yii2 to get it done :) thanks.


Solution

  • You could use when from here So, it will be look like that:

    public function rules()
    {
        return [
            ['password', 'required', 'when' => function($model) {
                return $model->role === 'user'; // boolean should be returned
            }]
        ];
    }
    

    It will check the attribute on required condition only when $model s role is user