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

此生再无相见时 提交于 2019-12-01 18:07:51

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.

Nana Partykar

See, in my code status is either 0 or 1.

So, for checked checkbox., I declared <?php $model->status = 1; ?>

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

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 as checked

//Your Code

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

If I want to have a checked checkbox on create I do something like this in a view:

if ($model->isNewRecord) {
    $model->status = TRUE;
}

I know it's not an elegant solution, but it is working.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!