yii2 checkbox and hidden input value always 0

yii2 checkbox and hidden input value 0 when I update my record.

<input type="hidden" value="0" name="Model[active]">

<?= $form->field($model, ‘active’)->checkBox([‘label’ => ‘’,‘data-size’=>‘small’, ‘class’=>‘bs_switch’

				,'style'=&gt;'margin-bottom:4px;', 'id'=&gt;'active']) ?&gt;

why not this hidden filed value set from db, where active is 1.

Value is 0 because you are writing it in "value" attribute of hidden field.

I’m not writing it 0,it is by default 0. How I can change it value?

You should put value of hidden field from model:




<?php $model->active = 0; ?>

<?= $form->field($model, 'active')->checkBox(['label' => '','data-size'=>'small', 'class'=>'bs_switch'

,'style'=>'margin-bottom:4px;', 'id'=>'active']) ?>



Your problem is not very clear but I try to guess…

As Fabrizio stated you should set the value for the hidden filed from the model.

But I see another problem:




<input type="hidden" value="0" name="Model[active]">


<?= $form->field($model, 'active')->checkBox(['label' => '','data-size'=>'small', 'class'=>'bs_switch'

,'style'=>'margin-bottom:4px;', 'id'=>'active']) ?>

This code generate 2 form field with the same name (also if you generate the hidden filed form the model), when you submit the value of the last one will overwrite the first in $_POST.

If you want to keep the original value you should use a different name for the hidden one or better use ActiverRecord during save to check original value.

If you explain the reason you need this maybe we can help you to find the optimal solution.

the hidden field automatic generates…

The hidden input is automatically generated by default.

See "uncheck" option in the API documentation.

http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#checkbox()-detail

(The doc says “radio”, but it should be “checkbox”. ;) )

By this trick, Yii ensures that the form will always submit the value of the boolean attribute, whether it may be true or false.

Without the hidden input, the submitted post data will not contain the boolean field if the checkbox is not checked.

yeah. it is a good solution for this problem