felixmind felixmind - 4 months ago 28
PHP Question

Zend Framework 2 Checkbox setValue for unchecked not work

I tried set checkbox value in false:

$form->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'test_checkbox',
'options' => array(
'label' => 'Test checkbox',
'use_hidden_element' => false,
'checked_value' => 1,
'unchecked_value' => 0,
),
'attributes' => array(
'value' => 0,
),
));


But as a result of this page contains:

<input type="checkbox" name="test_checkbox" value="1">


The value does not change and I can not understand why.

Other PHP and JS script not change this value.

Maybe I misunderstood how "checked_value", "unchecked_value" and "value" works?

Answer

The code you have is almost correct. It should be:

$form->add(array(
    'type' => 'Zend\Form\Element\Checkbox',
    'name' => 'test_checkbox',
    'options' => array(
        'label' => 'Test checkbox',
        'use_hidden_element' => false,
        'checked_value' => 1,
        'unchecked_value' => 0,
    )
));

But I think you misunderstand how HTML checkboxes work. The value attribute should always contain only the checked value. Browsers only submit this value if the checkbox is ticked. So when the page loads, the checkbox will appear in the source as:

<input type="checkbox" name="test_checkbox" value="1">

This is correct.

To achieve the unchecked value, ZF (and all other frameworks I know) add it to a hidden form field above the checkbox. If the checkbox is not ticked, the browser will submit the hidden form field instead.

Comments