Issues with jQuery and ZendFormElementCheckbox

In addition to the more obvious backwards compatibility breaks encountered when migrating from ZF1 to ZF2, there are also more nuanced changes.  In this particular instance, the migration to ZendForm broke the standard code used to determine whether a checkbox input is checked.  The resultant value was always false.

The code we used to determine the a checkbox’s state was extremely simple.

var value = $('input[name="my_element"]').prop('checked') ? 1 : 0;

Next, the ZendForm code responsible for instantiating the element object:

namespace ApplicationForm;

class MyCheckboxForm extends Form
{
    public function __construct($name = null)
    {
        $this->add(array(
            'name' => 'my_checkbox',
            'type' => 'Checkbox',
            'options' => array(
                'label' => 'My Checkbox',
            ),
        ));
    }
}

Under ZendForm, the standard resultant HTML for the checkbox element looks like this:

<input name="my_checkbox" value="0" type="hidden">
<input name="my_checkbox" value="1" type="checkbox">

Gasp… a hidden element! The first input element, which is most certainly not a checkbox, receives priority using the aforementioned selector query. There are a few simple ways to fix this…

Fix #1

It seems as though the creators of Zend Framework had some foresight, and gave programmers the option to disable the hidden element.

$this->add(array(
    'name' => 'my_checkbox',
    'type' => 'Checkbox',
    'options' => array(
        'label' => 'My Checkbox',
        'use_hidden_element' => false,
    ),
));

Fix #2: With Hidden Element

If you wish to retrain the hidden element, you can update the selector query as follows.

var value = $('input[name="my_element"]:checkbox').prop('checked') ? 1 : 0;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>