9

I am using Yii2 framework and I'd like to generate an html code like this

<input type="checkbox" id="queue-order" name="Queue[order]" value="1" checked>

in a view which uses ActiveForm.

I've tried

echo $form->field($model, 'order')
          ->checkBox(['label' => ..., 'uncheck' => null, 'checked' => true]); 

as well as

echo $form->field($model, 'order')
          ->checkBox(['label' => ..., 'uncheck' => null, 'checked' => 'checked']); 

but desired string "checked" does not appear in the generated html code.

Strangely enough, if I substitute "checked" with "selected"

echo $form->field($model, 'order')
          ->checkBox(['label' => ..., 'uncheck' => null, 'selected' => true]); 

then generated html code contains attribute "selected":

<input type="checkbox" id="queue-order" name="Queue[order]" value="1" selected>

So, how can I generate html code for a checkbox with attribute "checked"?

Andrew
  • 2,148
  • 5
  • 23
  • 34

4 Answers4

6

I guess this checkbox will be checked only if $model->order property take true value and if it has false (0 or null or false etc) value - field will be unchecked.

Goodnickoff
  • 2,267
  • 1
  • 15
  • 14
  • 1
    So you mean that Yii always sets status of checkbox (checked or unchecked) based on the value of the corresponding property? And I can not change the status of the chekbox? Seems strange if I've got it right... – Andrew Jun 01 '14 at 19:48
  • 1
    @Mario You confuse different ways of receiving the item: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#checkbox()-detail and http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#checkbox()-detail If you use `ActiveForm` then status of checkbox based on the value of the corresponding property of model. – Goodnickoff Jun 01 '14 at 19:52
  • @Mario if you want to generate input not based on model you should use `Html` helper (http://www.yiiframework.com/doc-2.0/yii-helpers-html.html) : `Html::checkbox( $name, $checked, $options))` – Goodnickoff Jun 01 '14 at 20:01
  • Thanks, now I've got it. You are right, I should better use Html helper class as you mentioned and not ActiveForm methods to generate the checkbox I need (moreover my checkbox corresponds to a property from an associated table/model). Thanks! – Andrew Jun 01 '14 at 20:07
2

if your are setting an external value in checkbox.

<?php $model->order = "02256"; ?>
<?= $form->field($model, "order")->checkbox(['value' => "02256"]); ?>
shivansh
  • 450
  • 4
  • 8
0
echo $form->field($model, 'Status')->checkbox(['uncheck' => 'Disabled', 'value' => 'Active']);
Rohit Suthar
  • 3,528
  • 1
  • 42
  • 48
Maxim Colesnic
  • 408
  • 1
  • 4
  • 12
0

You can use checked attribute to mark it as checked

<?= $form->field($model, 'agent_email_verification')->checkbox(['checked' => $model->agent_email_verification > 0, 'value' => true]) ?>