[英]Symfony2 - Twig : HTML <optgroup> Tag
I need to create a select with Tag. 我需要用标签创建一个选择。
this is my code to fill the select 这是我的代码来填充选择
->add('city', 'entity', array(
'empty_value' => 'Choisissez une option',
'class' => 'FrontBundle:City',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.city', 'ASC');
},
))
And this is my code in html.twig 这是我在html.twig中的代码
<div class="form-group">
{{ form_label(form.city, 'Ville') }}
<div class="col-sm-8">
{{ form_widget(form.city) }}
</div>
</div>
Here is the result I want to get: 这是我想要得到的结果:
<select>
<optgroup label="Région 1">
<option value="ville 1">Ville 1</option>
<option value="ville 2">Ville 2</option>
</optgroup>
<optgroup label="Région 2">
<option value="ville 3">Ville 3</option>
<option value="ville 4">Ville 4</option>
</optgroup>
</select>
Any idea ? 任何想法 ? Thank you.
谢谢。
As gp_sflover said in comments , you can use the group_by
option of the entity
field type : 正如gp_sflover 在评论中所说,您可以使用
entity
字段类型的group_by
选项 :
This is a property path (eg
author.name
) used to organize the available choices in groups.这是用于组织组中可用选项的属性路径(例如
author.name
)。 It only works when rendered as a select tag and does so by addingoptgroup
elements around options.它仅在呈现为选择标记时起作用,并通过在选项周围添加
optgroup
元素来实现。 Choices that do not return a value for this property path are rendered directly under the select tag, without a surrounding optgroup.不返回该属性路径值的选择将直接在select标记下呈现,而没有周围的optgroup。
So, assuming region
is a property of city
, your code should look like this: 因此,假设
region
是city
的属性,您的代码应如下所示:
->add('city', 'entity', array(
'empty_value' => 'Choisissez une option',
'class' => 'FrontBundle:City',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.city', 'ASC');
},
'group_by' => 'region',
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.