Elby
Elby

Reputation: 1674

Check box not checked in yii2

I am using yii2, i want to checked my check box,

<?= $form->field($model, 'is_email_alerts')->checkbox(['label'=>'','checked'=>true,'uncheck'=>'0','value'=>'1']); ?>

But its not working

Upvotes: 1

Views: 4287

Answers (1)

topher
topher

Reputation: 14860

Whether or not the checkbox is checked is determined solely by the value of the attribute.

From the API page for ActiveField::checkbox()

This method will generate the "checked" tag attribute according to the model attribute value

Thus just add

$model->is_email_alerts = true;

in your controller or anywhere before this call in your view.


Just to verify that this is the actual case: from the source for BaseHtml::activeCheckbox()

public static function activeCheckbox($model, $attribute, $options = [])
{
    ...
    $value = static::getAttributeValue($model, $attribute);
    ...
    $checked = "$value" === "{$options['value']}";
    ...
    return static::checkbox($name, $checked, $options);
}

And the only line in ActiveField::checkbox() where checked is set is

public static function checkbox($name, $checked = false, $options = [])
{
    $options['checked'] = (bool) $checked;

Upvotes: 3

Related Questions