user3507525 user3507525 - 1 year ago 120
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 Source

You need operator too

[['newsletterAccess', 'groupAccess', 'templateAccess'], 'compare', 
      'compareValue' => true,  
      'operator' => '==' 
        'when' => function ($model) {
            return $model->admin == 1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download