-->

How to set Yii2's ActiveForm checkbox in check

2019-02-22 09:30发布

问题:

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:

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.



回答3:

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