yii2: make checkbox to be checked
Asked Answered
H

4

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"?

Halfdan answered 1/6, 2014 at 15:50 Comment(0)
F
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.

Fibrillation answered 1/6, 2014 at 19:22 Comment(4)
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...Halfdan
@Mario You confuse different ways of receiving the item: yiiframework.com/doc-2.0/… and yiiframework.com/doc-2.0/… If you use ActiveForm then status of checkbox based on the value of the corresponding property of model.Fibrillation
@Mario if you want to generate input not based on model you should use Html helper (yiiframework.com/doc-2.0/yii-helpers-html.html) : Html::checkbox( $name, $checked, $options))Fibrillation
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!Halfdan
H
2

if your are setting an external value in checkbox.

<?php $model->order = "02256"; ?>
<?= $form->field($model, "order")->checkbox(['value' => "02256"]); ?>
Hummock answered 14/7, 2016 at 12:13 Comment(0)
M
0
echo $form->field($model, 'Status')->checkbox(['uncheck' => 'Disabled', 'value' => 'Active']);
Mendicant answered 17/5, 2016 at 13:8 Comment(0)
S
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]) ?>

Sitin answered 20/6, 2022 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.