How to make checkbox check by default in yii when using a single form to create and update

I use a single form to create and update the form. I need to check the default box in the following form

<div class="row" style='float:left;;margin-left:5px'> <?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?> <?php echo $form->checkBox($model,'label_name',array('value'=>1,'uncheckValue'=>0,'checked'=>'checked','style'=>'margin-top:7px;')); ?> <?php echo $form->error($model,'label_name'); ?> </div> 

I use the code above to achieve the same goal. I am not getting the result as expected. When updating the form, it displays a check box, even if it is not selected.

+6
source share
5 answers

I got a solution that I worked with the code itself, please look

 <div class="row" style='float:left;;margin-left:5px'> <?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?> <?php echo $form->checkBox($model,'label_name',array('value'=>1,'uncheckValue'=>0,'checked'=>($model->id=="")?true:$model->label_name),'style'=>'margin-top:7px;')); ?> <?php echo $form->error($model,'label_name'); ?> </div 
+8
source

A better solution would be to set the value in the controller:

 public function actionCreate() { $model = new ModelName(); if (isset($_POST[$model])) { // ... save code here } else { // checkboxes for label 'label_name' with value '1' // will be checked by default on first load $model->label_name = true; // or 1 } $this->render('create', array( 'model' => $model, )); } 

Or even better, in the afterConstruct() function in the model:

 protected function afterConstruct() { parent::afterConstruct(); $this->label_name = true; // or 1 } 
+4
source

Follow the link below

http://www.bsourcecode.com/2013/03/yii-chtml-checkboxlist

I hope the link is helpful.

+2
source

All you need to do is set a default value in the model:

 public $label_name = true; 
+1
source

Your requirement is to keep the checkbox checked for both creation and updating. checked = checked will serve the purpose when creating the form, but when updating you will have to process it using code

0
source

Source: https://habr.com/ru/post/943679/


All Articles