我正在尝试创建,html集合的颜色输入字段..它将使用javascript
动态添加我的ColorFieldset
代码是
namespace Dashboard'Form;
use Zend'Form'Fieldset;
use Zend'InputFilter'InputFilterProviderInterface;
class ColorFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('color');
$this->add(array(
'name' => 'hash',
'options' => array(
'label' => 'Color'
),
'attributes' => array(
'required' => 'required',
'class' => 'input-mini'
)
));
}
/**
* @return array
'*/
public function getInputFilterSpecification()
{
return array(
'hash' => array(
'required' => true,
)
);
}
}
并添加到
表单中$this->add(array(
'type' => 'Zend'Form'Element'Collection',
'name' => 'colors',
'options' => array(
'count' => 2 ,
'should_create_template' => true,
'allow_add' => true,
'target_element' => array(
'type' => 'Dashboard'Form'ColorFieldset'
)
)
));
和在我的视图文件..colors.phtml
<div id="colors_container" class="">
<?php echo $this->formCollection( $form->get('colors')); ?>
</div>
输出
<div class="" id="colors_container">
<label><span>Color</span><input type="text" value="" class="input-mini" required="required" name="hash"></label>
<label><span>Color</span><input type="text" value="" class="input-mini" required="required" name="hash"></label>
<span data-template='<label><span>Color</span><input name="hash" required="required" class="input-mini" type="text" value=""></label>'></span>
</div>
它应该打印成…在zf2手册2.0
中有解释<div class="" id="colors_container">
<label><span>Color</span><input type="text" value="" class="input-mini" required="required" name="colors[0][hash]"></label>
<label><span>Color</span><input type="text" value="" class="input-mini" required="required" name="colors[1][hash]"></label>
<span data-template='<label><span>Color</span><input name="colors[__index__][hash]" required="required" class="input-mini" type="text" value=""></label>'></span>
</div>
我期望html输入名称为colors[__index__][hash]
。但印刷名称为<input type="text" value="" class="input-mini" required="required" name="hash">
。
在上面的情况下,我将只得到一个颜色名称后$_POST['hash']
。
为什么zf2不打印<input type="text" value="" class="input-mini" required="required" name="colors[0][hash]">
?
我终于自己找到了答案。我必须打电话给
$form->prepare();
,然后在视图中呈现任何内容。现在可以运行了
我可以确认。下面的代码对我有效:
// prepare form is needed to properly display Collection fields
$form->prepare();
echo $this->form()->openTag($form);
// echo other normal form fields
echo $this->formCollection($form->get('colors'));
echo $this->form()->closeTag();