Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 requirement selection one or more checkboxes FormBuilder

I have a registration form created in the "Yii2 krajee FormBuilder". It contains two checkboxes. At least one of them must be selected. Validation must be carried out on the client side, in order not to overload the page. Everything would be easy if the Yii2 contain the option to assign the rules required and whenClient to checkboxes - unfortunately that 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 can not be assigned to required

I used this but in this case, the page is reloaded

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

Typically checkboxes validation is carried out by this

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

but in this case you can not combine rule compare with the rule whenClient - which is responsible for the function-specifed validation on the client side. How can I solve this problem?

like image 456
Marcin_Linux Avatar asked Jan 21 '26 04:01

Marcin_Linux


1 Answers

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

['checkbox1', 'required', 'when' => function($model) {
    return $model->checkbox2 == false;  
  }
],
['checkbox2', 'required', 'when' => function($model) {
    return $model->checkbox1 == false;  
  }
],
like image 155
hesselek Avatar answered Jan 23 '26 20:01

hesselek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!