2

我需要在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 中,我最终不得不用相同的名称“1”命名 3 个元素,最后一个元素覆盖了前一个元素。即使我创建 3 个子表单,我也会得到相同的效果。

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

谢谢

4

2 回答 2

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>,
   )
);
于 2012-09-25T20:41:54.450 回答
0

i do not understand, why you need this special case, but the only possible solution in my opinion is, to use a custom template.

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

So what you do is, you say that you want to use a template file, where you can declare everything by yourself. Also your banana[1].

But you will lose simple validation and other benefits.

于 2012-09-24T10:27:27.770 回答