Yii2 selection of one or more FormBuilder checkboxes

I have a registration form created in "Yii2 krajee FormBuilder". It contains two checkboxes. You must select at least one of them. Validation should be done on the client side so as not to overload the page. Everything would be easy if Yii2 contains the ability to assign the required rules and whenClient to the checkboxes - unfortunately, this is not possible. For other fields (textboxes, selectboxes, you can for example use this code:

Model:

$public $module1;
$public $module2;

  'module1'=>[
                'type'=>Form::INPUT_CHECKBOX,
                'name'=>'ak1',
                'label'=>'<b>'.Yii::t('app','register.module1').'</b>' ],

  'module2'=>[
                'type'=>Form::INPUT_CHECKBOX,
                'name'=>'ak2',
                'label'=>'<b>'.Yii::t('app','register.module2').'</b>' ]

'textbox1'=>[
                    'type'=>Form::INPUT_TEXTBOX,
                    'name'=>'tx1',
                    'label'=>'<b>'.Yii::t('app','register.tx1').'</b>' ]
[...]


     [[  'textbox1', 'texbox2', ],'required','whenClient'=> "function (attribute, value) { return  $('#registerform-textbox1').is(':checked') == false && $('#registerform-textbox2').is(':checked') == false;}" 
],

      

It works .. but for texboxes. Checbox cannot be assigned to required

I used this, but in this case the page reloads

['module1',function ($attribute, $params) {
                if ($this->module1 == 0 && $this->module2 == 0) {
                    $this->addError($attribute, 'you have to select at least one option');
                }
            }], 

      

Usually checkbox checking is done with

public function rules () 
     {
         array ['checboxname', 'compare', 'compareValue' => true, 
               'message' => 'You must agree to the terms and conditions'], 
         ... 
     } 

      

but in this case, you cannot match the rule comparison with the whenClient rule, which is responsible for the validation specified by the client-side function. How can I solve this problem?

+3


source to share


1 answer


I'm not really sure what you are trying, but I think you would do:



['checkbox1', 'required', 'when' => function($model) {
    return $model->checkbox2 == false;  
  }
],
['checkbox2', 'required', 'when' => function($model) {
    return $model->checkbox1 == false;  
  }
],

      

+1


source







All Articles