yii2 disable the rules if a checkbox is selected

4.2k views Asked by At

In the active form, I have 3 textinput and one checkbox. All the 3 textinputs have rules that says cannot be empty. What I want is if the checkbox is clicked, It will disable the rules and will save the empty record in the database.

here is screen shot of the active form..

enter image description here

2

There are 2 answers

3
robsch On BEST ANSWER

You could define the rules that way (using when):

public function rules()
{
    return [            
        ['cancelled',   'boolean'],
        ['checkNumber', 'required'],
        ['payee',       'required', 'when' => function ($model) {return !$model->cancelled;}],
        ['particulars', 'required', 'when' => function ($model) {return !$model->cancelled;}],
    ];
}

You may want to add whenClient as well to let the browser check this before it submits the form.

1
jmwierzbicki On

You can do something like this:

$model = new SomeForm();
if ($model->load(Yii::$app->request->post())){
if ($model->checkbox == true) $model->scenario = 'checked';
}
// your model rules:
[['name', 'email', 'subject', 'body'], 'safe', 'on' => 'checked']

or alternatively You can do this:

 if ($model->checkbox == true) $model->save(false); //this will disable any validation so be carefull

edit: if You need cliend side validation switch, You have to use this:

[['name', 'email', 'subject', 'body'], 'required', 'when' => function ($model) {
                return $model->cancelled == '0';
            }, 'whenClient' => new JsExpression("function (attribute, value) {  return $('#mailform-cancelled').val() == '0';}")]