我对表单呈现有疑问: 我想定义一些相似的表单字段(在数组中传递它们或在循环中创建),然后在像这样的循环中在树枝中渲染它们:
{% for field in form.collection %}
<li>
{{ form_label(field) }}
{{ form_widget(field) }}
</li>
{% endfor %}
原因:我需要在循环渲染它的同时访问每个字段的标签和小部件(不知道每个字段的名称)。我似乎,唯一的方法是拥有CollectionType。 这不是基于任何实体。我看过带有实体示例的文档,但是可以手动添加字段吗?
类似的东西:
class FormcollectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('collection', CollectionType::class, [
// each entry in the array will be an "ChoiceType" field
'entry_type' => ChoiceType::class,
// these options are passed to each "collection" type
'entry_options' => [
'attr' => ['class' => 'someclass'],
],
// How to define few ChoiceType fields in CollectionType here, manually ?
]);
谢谢您的帮助:)
答案 0 :(得分:1)
$builder->add('favoriteCities', CollectionType::class, [
'entry_type' => ChoiceType::class,
'entry_options' => [
'choices' => [
'Nashville' => 'nashville',
'Paris' => 'paris',
'Berlin' => 'berlin',
'London' => 'london',
],
],
]);
答案 1 :(得分:0)
谢谢
实际上,诀窍是“数据”字段...。
如此:
$builder->add('collection', CollectionType::class, [
'entry_type' => ChoiceType::class,
'entry_options' => [
'attr' => ['class' => 'someclass'],
'choices' => [
'Nashville' => 'nashville',
'Paris' => 'paris',
'Berlin' => 'berlin',
'London' => 'london',
],
],
'data' => ['choice1Field' => 'choice1',
'choice2Field' => 'choice2' ]
]);