I am trying create , html collection for colors input field .. which will dynamically added using javascript
My ColorFieldset
code is
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,
)
);
}
}
and added it into form
$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'
)
)
));
and in my view file .. colors.phtml
<div id="colors_container" class="">
<?php echo $this->formCollection( $form->get('colors')); ?>
</div>
it printing output like
<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>
It supposed to print like .. which explained in zf2 manual 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>
I expected html input name as colors[__index__][hash]
. But it printing name as <input type="text" value="" class="input-mini" required="required" name="hash">
.
In above case .I will only get one color name in post $_POST['hash']
.
why zf2 not print <input type="text" value="" class="input-mini" required="required" name="colors[0][hash]">
? Please advice what is wrong in my code .
Ohh finally found answer by myself . I have to call
$form->prepare();
before rendering anything in the view . now it works