phpzend-frameworkcheckboxzend-formzend-form-element

Zend checkbox array with key value issue


I have a question about the zend_form_element_checkbox from zend.

I have a form with multiple checkboxes. And when I send this form, I logically receive an array of params that look like that :

array("controller" => my_controller, ...., "checkbox_name" => array ("0" => firstCheckedValue, "1" => secondCheckedValue, ...) )

I create each element this way :

$checkbox = new Zend_Form_Element_Checkbox('checkbox_name');
$checkbox->setCheckedValue($valueVar)->setIsArray(true);
$this->addElement($checkbox);

And I display each one like that :

$this->form->checkbox_name->renderViewHelper();

But I would like to have the received params format this way :

array("controller" => my_controller, ...., "checkbox_name" => array ("firstCheckedValue" => false, "secondCheckedValue" => true, ...) )

In other words, I want the HTML checkboxes look like that :

<input type="checkbox" value="true" name="checkbox_name[firstCheckedValue]">
<input type="checkbox" value="false" name="checkbox_name[secondCheckedValue]">
...

(the boolean value is not for the checked state of the checkbox).

How can I do that?


Solution

  • Try:

    $checkbox = new Zend_Form_Element_Checkbox('first');
    $checkbox->setCheckedValue($valueVar)->setIsArray(true)->setBelongsTo('checkbox_name');
    $this->addElement($checkbox);
    $checkbox = new Zend_Form_Element_Checkbox('second');
    $checkbox->setCheckedValue($valueVar)->setIsArray(true)->setBelongsTo('checkbox_name');
    $this->addElement($checkbox);
    

    Docs: http://framework.zend.com/manual/en/zend.form.advanced.html

    Zend_Form::setElementsBelongTo($array): Using this method, you can specify the name of an array to which all elements of the form belong. You can determine the name using the getElementsBelongTo() accessor.