php 使用表单生成器 symfony2 创建数组输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13258352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:03:22  来源:igfitidea点击:

Create array input field with form builder symfony2

phpsymfonyformbuilder

提问by markoub

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:

我在 Symfony2 中使用表单构建器时遇到问题。确切地说,我需要输入字段是 html 数组,但我无法使用 createFormBuilder->add 创建它。这是我尝试过的:

$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 (":").

名称“attribute[0]”包含非法字符。名称应以字母、> 数字或下划线开头,并且仅包含字母、数字、数字、下划线 ("_")、连字符 >("-") 和冒号 (":")。

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?

帮助?

采纳答案by Mats Rietdijk

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.

如果这还不够清楚,或者您仍有疑问,我将很乐意为您提供帮助。

回答by Bernhard Schussek

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

回答by user1156168

Also you can ovveride field in TWIG. Example:

您也可以在 TWIG 中覆盖字段。例子:

   {{ form_row(form[field_name],{ 'full_name':  'attribute[' ~ step ~ ']' })}} 

Where step is your index.

其中 step 是您的索引。