具有相同索引的数组的zend形式

时间:2012-09-20 09:23:09

标签: zend-framework zend-form

我需要在zend中获得类似的东西

<input type="text" name="phone[1]" value="" />
<input type="text" name="address[1]" value="" />
<input type="text" name="banana[1]" value="whatever" />

注意它们在括号内有相同的ID! (我不需要name="phone[]"name="phone[phone1]"

我已经尝试过了 https://stackoverflow.com/a/3673034/579646https://stackoverflow.com/a/406268/579646https://stackoverflow.com/a/7061713/579646

问题在于ZendFramework我最终必须命名3个具有相同名称“1”的元素,最后一个覆盖前一个元素。即使我创建3个子表单,我也会得到相同的效果。

不同的示例显示如何获取具有不同索引或没有索引([])的数组,但我需要不同的数组以具有相同的索引。

由于

2 个答案:

答案 0 :(得分:4)

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>,
   )
);

答案 1 :(得分:0)

我不明白,为什么你需要这个特例,但我认为唯一可能的解决方案就是使用自定义模板。

class YourForm extends Zend_Form
{
    public function init()
    {
        $this->setDecorators(array(
            array(
                'ViewScript',
                array(
                    'viewScript' => 'path/to/your/phtml/file',
                    'possibleOtherParamYouWantToPass' => 'value',
                    ...
                )
            )
        ));
    }
}

所以你做的是,你说你想要使用一个模板文件,你可以自己声明一切。也是你的banana[1]

但是你将失去简单的验证和其他好处。