Zend_Form 对此命名有一个特性setElementsBelongTo
。请参阅
http://framework.zend.com/manual/1.12/en/zend.form.advanced.html
使用方法是为 Zend_Form 对象设置前缀setElementsBelongTo
,如果你想遍历每个字段,那么你可以使用子表单来封装每组字段
您可以setElementsBelongTo
在控制器或init()
表单类的方法中调用:
$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());
给
array(2) {
["phone"]=> array(2) { [1]=> NULL [2]=> NULL }
["address"]=> array(1) { [1]=> NULL } }
要获得预期的结果,您需要删除一些装饰器(Form、dt 等):
<input type="text" name="phone[1]" value="" />
<input type="text" name="address[2]" value="" />
然后,当您检索值时$form->getValues()
,结果是:
Array(
'phone' = Array(
'1' => <value>,
),
'address' = Array(
'1' => <value>,
)
);