数组输入,如 name="person[]";以 Zend 形式 [英] array input like name="person[]" in zend form

查看:14
本文介绍了数组输入,如 name="person[]";以 Zend 形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在普通的 html 中,我们可以有一个像 person[]

In normal html, we could have an array field like person[]

<input name="person[]" type="text" />
<input name="person[]" type="text" />
<input name="person[]" type="text" />

据我所知,Zend_Form 没有.我阅读了另一个答案,建议可以使用将在正确位置添加 [] 的装饰器.这是该特定问题的代码

As far as I know, Zend_Form doesn't have that. I read another answer that suggested it could be done using a decorator that would add the [] at the right place. This is the code for that specific question

$html = ''; // some code html
$i = 0;
foreach ($element->getMultiOptions() as $value => $label){
    $html .= '<input type="checkbox" '
          .         'name="'.$element->getName().'[]" '
          .         'id="'$element->getName()'-'.$i.'" '
          .         'value="'.$value.'" />';
    $i++;
}
return $html;

这看起来是一个好的开始,但我想知道使用装饰器是否足够.必须正确读取返回的值并将其传送到服务器,然后在服务器端进行验证.那么装饰器是错误的想法吗?自定义元素在这里更有意义吗?我还没有看到一个很好的例子来说明如何做到这一点.

This looks like a good start, but I wonder if using a decorator is enough. The values that get returned back have to be read correctly and delivered to the server, then validated on the server side. So is a decorator the wrong idea? Would a custom element make more sense here? I haven't seen a good example that shows how this can be done.

推荐答案

我认为 ZF 不允许创建名为 person[] 的单个输入文本字段,尽管您可以为整个表格或子表格.但是,它允许类似的事情.具体来说,您可以创建名为 person[0]person[1] 等的字段.

I think that ZF does not allow for creation of individual input text fields named person[], although you could do it for the whole form or a subform. However, it allows for something similar. Specifically, you could create fields named person[0], person[1], etc.

为此,您可以执行以下操作:

To do this, you could do the following:

$in1 = $this->createElement('text', '0');
$in2 = $this->createElement('text', '1');
$in1->setBelongsTo('person');
$in2->setBelongsTo('person');

通过这种方式,您通常可以将验证器、过滤器等附加到 $in1 或 $in2 上,它们会按预期工作.在您的操作中,表单验证后,您可以获得该人的输入文本字段的数组,如下所示:

This way you could normally attach your validators, filters, etc. to $in1 or $in2 and they would work as expected. In your action, after form validation, you could get an array of the person's input text fields as:

$values = $yourForm->getValues();
var_dump($values['person']);

有趣的是,以下内容不起作用:

$in1 = $this->createElement('text', 'person[0]');
$in2 = $this->createElement('text', 'person[1]');

希望对您有所帮助.

这篇关于数组输入,如 name="person[]";以 Zend 形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆