Yii ActiveForm sends 0 for unchecked checkbox fields

A checkbox input field that is not checked should not send any values to the server, but I see that Yii’s ActiveForm sends a value of 0 which is not what I want. Inspecting generated markup in developer tools I see that Yii creates a hidden input field with value 0 for my checkbox. Why is Yii acting against web standards? And how can I setup my checkbox so this hidden field does not get inserted into the page?

<?= $form->field($model, 'mock_recall_user')->checkbox([
	'label' => Yii::t('app', 'Mock recall'),
	'checked' => false
]); ?>

Hi @smohadjer,

You can use uncheck option like the following:

<?= $form->field($model, 'mock_recall_user')->checkbox([
	'label' => Yii::t('app', 'Mock recall'),
	'checked' => false,
	'uncheck' => null,
]); ?>

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

Thanks a lot. Not sure why I didn’t check documentation first! :astonished:

That’s because you need to distinguish two common cases: “checkbox was unchecked, turn option off” and “there was no checkbox on form, don’t change state”.

1 Like

But you can distinguish whether a checkbox was unchecked or not by verifying on server if you have received the parameter for the checkbox or not. That’s why W3C doesn’t define a value for unchecked checkboxes. I think Yii should have set the default value for “uncheck” option to null rather than to 0 as that’s more compliant with standards.

Yes, you can. As long as you are sure that there’s a checkbox in the form, you can distinguish whether it is checked or not. But you can’t distinguish whether the checkbox is in the form or not in the first place.

IMO the W3C’s specification is not very well designed. Yii’s trick helps to make the server side code much simpler and cleaner.

1 Like