user3507525 user3507525 - 7 months ago 16
PHP Question

Yii required checkbox with condition

I have an ActiveForm with four checkboxes:

<?= $form->field($model, 'admin')->checkbox() ?>

<?= $form->field($model, 'newsletterAccess')->checkbox() ?>

<?= $form->field($model, 'groupAccess')->checkbox() ?>

<?= $form->field($model, 'templateAccess')->checkbox() ?>


and when the first checkbox is checked (admin), the form can only be submitted when all four checkboxes are checked.
What should my rule look like? I tried something like this:

[['newsletterAccess', 'groupAccess', 'templateAccess'], 'compare', 'compareValue' => true,
'when' => function ($model) {
return $model->admin == 1;
}


but it didn't work.
Thanks for help.

Answer

You need operator too

[['newsletterAccess', 'groupAccess', 'templateAccess'], 'compare', 
      'compareValue' => true,  
      'operator' => '==' 
        'when' => function ($model) {
            return $model->admin == 1;
        }
Comments