How to set Yii2's ActiveForm checkbox in checked state?

Bartosz Wójcik picture Bartosz Wójcik · May 6, 2015 · Viewed 19.2k times · Source

I'm looking for a simple solution for a "checked" state for the Yii2 ActiveForm checkbox control and I can't find a solution how to set it. I cant find any examples in the documentation.

I've tried to manipulate the rendering code

<?= $form->field($model, 'name')->checkbox()->label('Hi'); ?>

But it seems I need to modify the ActiveForm itself. How to make checkbox checked by default?

Answer

Bartosz W&#243;jcik picture Bartosz Wójcik · May 7, 2015

Ok, I've debbuged a while and found a solution, it lies in the guts of BaseHtml.php at line 1359 in activeCheckbox() function

$checked = "$value" === "{$options['value']}";

It checks for the default value of the model variable:

class SomeForm extends Model
{
    public $name = true;

And the same value (with the same type) must be assigned to the 'value' option in

<?= $form->field($model, 'name')->checkbox(['value' => true])->label('Hi'); ?>

I would say it's overcomplicated as for such trivial feature.