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?
Ok, I've debbuged a while and found a solution, it lies in the guts of BaseHtml.php at line 1359 in activeCheckbox() function
It checks for the default value of the model variable:
And the same value (with the same type) must be assigned to the 'value' option in
I would say it's overcomplicated as for such trivial feature.
See, in my code
status
is either 0 or 1.So, for checked checkbox., I declared
<?php $model->status = 1; ?>
For example, if you are having 2 values for checkbox name i.e. PHP or Java. Then, declare it as
<?php $model->name = 'Java'; ?>
for getting Java aschecked
If I want to have a checked checkbox on create I do something like this in a view:
I know it's not an elegant solution, but it is working.