SaidbakR
SaidbakR

Reputation: 13544

Yii2 Active field checkbox checked by default in create

My problem here is different than other problems addresses in other questions. My problem is that the active field value is taken from another model than the creation model. It looks like the following:

...
foreach ($section->cavities as $cavity) {
      $tr[$i] .= '<td>'.$form->field($cavityJob[$j], "[$j]cavity_id")->checkbox(['value' => $cavity->id, 'label' => $cavity->title.$section->title]).'</td>';
      $i++;
      $j++;
    } 
...

Notice here there are two models:

  1. $cavityJob: the creation of field model
  2. $cavity: which supply the value of the field through its id property

On create action I got the checkbox unchecked and I want them to be checked by default. I tried to place 'checked' => 'checked' in the options array of the field but it did not succeed in make checkbox checked by default.

Upvotes: 0

Views: 2304

Answers (2)

Nageen
Nageen

Reputation: 1759

Try this

$model->myAttribute = true; // or 1, or '1'

echo $form->field($model, 'myAttribute')->checkbox(); // checked ckeckbox

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133370

Yoiu should assign true to the field

$model->cavity_id = true;  

and you can assign the default value in model rule

 ['cavity_id', 'default', 'value' =>true],

Upvotes: 0

Related Questions