Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array input field with form builder symfony2

I'm having a trouble with using Form builder in Symfony2. To be exact, I need input field that is html array, but I can't create it with createFormBuilder->add. Here is what I tried:

$attributesForm = $this->createFormBuilder()
        ->add('attribute[0]', 'text') ...

And so on, but I get the following exception:

The name "attribute[0]" contains illegal characters. Names should start with a letter, >digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens >("-") and colons (":").

Is there any nice solution or I have to create fields manually?

Thanks in advance!

EDIT: to clarify this further... I want something like this to be generated:

<div id="msoft_adminbundle_offertype">
<div>Name <input type="text" name="name"></div>
<div>...</div>
<div>Attribute 0 <input type="text" name="attribute[0]"></div>
<div>Attribute 1 <input type="text" name="attribute[1]"></div>
<div>Attribute 3 <input type="text" name="attribute[3]"></div>
<ul>
    </ul>
<p>
    <button type="submit">Edit</button>
</p>

Help?

like image 673
markoub Avatar asked Nov 06 '12 19:11

markoub


2 Answers

As the previous answer states, use the collection type or a nested form, where each field corresponds to one entry of the array. And in cases where you can't/don't want to do that, you can do the following:

->add('attribute_0', 'text', array(
    'property_path' => 'attribute[0]',
))
like image 55
Bernhard Schussek Avatar answered Sep 24 '22 06:09

Bernhard Schussek


You can create an array of input fields using the 'collection'-field type.

Documentation about how to use it can be found here:

Collection documentation

If that isn't clear enough or you still have questions I will gladly help you with them.

like image 25
Mats Rietdijk Avatar answered Sep 22 '22 06:09

Mats Rietdijk