问题
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?
回答1:
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.
回答2:
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]',
))
回答3:
Also you can ovveride field in TWIG. Example:
{{ form_row(form[field_name],{ 'full_name': 'attribute[' ~ step ~ ']' })}}
Where step is your index.
来源:https://stackoverflow.com/questions/13258352/create-array-input-field-with-form-builder-symfony2