Symfony2 - Twig:HTML <optgroup> 标签
Symfony2 - Twig : HTML <optgroup> Tag
我需要创建一个带有标签的 select。
这是我填写的代码 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');
},
))
这是我在 html.twig
中的代码
<div class="form-group">
{{ form_label(form.city, 'Ville') }}
<div class="col-sm-8">
{{ form_widget(form.city) }}
</div>
</div>
这是我想要得到的结果:
<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>
有什么想法吗?谢谢你。
作为 entity
字段类型的 gp_sflover said , you can use the group_by
option:
This is a property path (e.g. author.name
) used to organize the
available choices in groups. It only works when rendered as a select
tag and does so by adding optgroup
elements around options. Choices
that do not return a value for this property path are rendered
directly under the select tag, without a surrounding optgroup.
因此,假设 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',
))
我需要创建一个带有标签的 select。
这是我填写的代码 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');
},
))
这是我在 html.twig
中的代码 <div class="form-group">
{{ form_label(form.city, 'Ville') }}
<div class="col-sm-8">
{{ form_widget(form.city) }}
</div>
</div>
这是我想要得到的结果:
<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>
有什么想法吗?谢谢你。
作为 entity
字段类型的 gp_sflover said group_by
option:
This is a property path (e.g.
author.name
) used to organize the available choices in groups. It only works when rendered as a select tag and does so by addingoptgroup
elements around options. Choices that do not return a value for this property path are rendered directly under the select tag, without a surrounding optgroup.
因此,假设 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',
))