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

好久不见. 提交于 2019-12-19 19:52:21

问题


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?


回答1:


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.




回答2:


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'); ?>



回答3:


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.



来源:https://stackoverflow.com/questions/30088175/how-to-set-yii2s-activeform-checkbox-in-checked-state

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