Zend_Form has a feature for this named setElementsBelongTo
. See
http://framework.zend.com/manual/1.12/en/zend.form.advanced.html
The way of use this is setting to the Zend_Form object the prefix with setElementsBelongTo
, if you want iterate over each field then you can use subforms to encapsulate each group of fields
You can call to setElementsBelongTo
in your controller or in the init()
method of your form class:
$mainForm = new Zend_Form();
$phoneForm = new Zend_Form_Subform();
$element = $phoneForm->createElement('text', '1'); // 1 is the element inside of the brackets
$phoneForm->addElement($element);
$phoneForm->setElementsBelongTo('phone'); // phone is the part leading the brackets
$mainForm->addSubform($phoneForm, 'phone_form');
$phoneForm = new Zend_Form_Subform();
$element = $phoneForm->createElement('text', '2'); // 1 is the element inside of the brackets
$phoneForm->addElement($element);
$phoneForm->setElementsBelongTo('phone'); // phone is the part leading the brackets
$mainForm->addSubform($phoneForm, 'phone_form2');
$addressForm = new Zend_Form_Subform();
$element = $addressForm->createElement('text', '1');
$addressForm->addElement($element);
$addressForm->setElementsBelongTo('address');
$mainForm->addSubform($addressForm, 'address_form');
echo $mainForm;
var_dump($mainForm->getValues());
gives
array(2) {
["phone"]=> array(2) { [1]=> NULL [2]=> NULL }
["address"]=> array(1) { [1]=> NULL } }
To get your expected result you will need remove some decorators (Form, dt, etc):
<input type="text" name="phone[1]" value="" />
<input type="text" name="address[2]" value="" />
Then when you retrieve the values with $form->getValues()
the result is:
Array(
'phone' = Array(
'1' => <value>,
),
'address' = Array(
'1' => <value>,
)
);