Zend_Form数组表示法和空元素名称

5

I'want to render:

<input type="text" value="" name="foo[]" />
<input type="text" value="" name="bar[]" />

但是 Zend_Form_Element 需要一个(字符串)名称,所以我需要这样做:

$this->addElement('text', '1', array(
    'belongsTo' => 'foo'
));

$this->addElement('text', '2', array(
    'belongsTo' => 'bar'
));

但是输出结果为:
<input id="foo-1" type="text" value="" name="foo[1]" />
<input id="bar-2"  type="text" value="" name="bar[2]" />

我也可以接受以下输出:

<input id="foo-1" type="text" value="" name="foo[1]" />
<input id="bar-1"  type="text" value="" name="bar[1]" />

但是Zend_Form_Element会重写相同名称的元素,有没有办法做到我需要的呢?

我也想要一样的!如果你解决了,请告诉我。 - Keyne Viana
2个回答

7

对于多个值:

$foo = new Zend_Form_Element_Text('foo');
// Other parameters
$foo->setIsArray(TRUE);
$this->addElement($foo);

生成:name="foo[]"

--

如果你需要使用给定的键,例如name="foo[bar]",请使用:

$bar= new Zend_Form_Element_Text('bar');
// Other parameters
$bar->setBelongsTo('foo');
$this->addElement($bar);

--

测试过ZF 1.11.5版本


0

类 MyFooForm 扩展自 Zend_Form { public function init() { $fullNameOpts = array( 'required'=>false, 'label'=>'全名', 'isArray'=>true, 'validators' => array( array('stringLength', false, array(1, 250) ) ) ); $this->addElement('text' ,'fullName',$fullNameOpts); // 其余元素、表单等在此处添加 } }

这样就创建了一个表单

<dd id="fullName-element"><input type="text" class="inputAccesible" value="" id="fullName"name="fullName[]"></dd>

它在Element.php中,在Form中,第512行的"isArray"检查。

我正在使用常规的zend_form,与自定义验证器进行交叉验证,并推送子表单以复制主表单,因为用户可以多次添加相同的表单。 此外,我懒得研究自定义装饰器,我创建了一个,但它会破坏子表单和数组符号,所以我只使用常规的装饰器,这样就解决了问题。

我在Zf 1.10。


但通常情况下,当我们使用空数组符号时,我们会有许多具有相同名称的字段。如果您尝试创建一个带有相同名称的新元素,期望一个新的fullName[]字段,这是行不通的。 - Keyne Viana
发一些代码,我会帮你解决的 :) 我制作了一个库来处理这个问题,我的下一个目标就是这个。 你有一个表单,想要复制其中的一个元素。 - Jorge Omar Vázquez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接