zend-frameworkzend-formzend-form-element

Zend Framework: Working with Form elements in array notation


I would like to be able to add a hidden form field using array notation to my form. I can do this with HTML like this:

<input type="hidden" name="contacts[]" value="123" />
<input type="hidden" name="contacts[]" value="456" />

When the form gets submitted, the $_POST array will contain the hidden element values grouped as an array:

array(
    'contacts' => array(
        0 => '123'
        1 => '456'
    )
)

I can add a hidden element to my form, and specify array notation like this:

$form->addElement('hidden', 'contacts', array('isArray' => true));

Now if I populate that element with an array, I expect that it should store the values as an array, and render the elements as the HTML shown above:

$form->populate($_POST);

However, this does not work. There may be a bug in the version of Zend Framework that I am using. Am I doing this right? What should I do differently? How can I achieve the outcome above? I am willing to create a custom form element if I have to. Just let me know what I need to do.


Solution

  • To use array notation, you need to specify that the element "belongs to" a parent array:

    $form->addElement('hidden', 'contact123', array('belongsTo' => 'contacts', 'value' => '123'));
    $form->addElement('hidden', 'contact456', array('belongsTo' => 'contacts', 'value' => '456'));