Create array input field with form builder symfony2

markoub picture markoub · Nov 6, 2012 · Viewed 25.3k times · Source

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?

Answer

Bernhard Schussek picture Bernhard Schussek · Nov 7, 2012

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]',
))