symfony2表单复选框分组(扩展和多选)
问题描述:
in my form type i have this :
$builder
->add('options', 'choice', [
'choices' => $choices,
'multiple' => true,
'expanded' => true,
'label' => false
])
;
choices is an array :
$choices = [
'val1' => 'val1',
'val2' => 'val2',
'val3' => 'val3'
];
Great ! now i want to categorized my choices with an array like this:
$choices = [
'label1' => [
'val1' => 'val1',
'val2' => 'val2',
],
'label2' => [
'val3' => 'val3',
'val4' => 'val4',
],
'label3' => [
'val5' => 'val5',
'val6' => 'val6',
],
];
So i want result like below
what is the best way to achieve this?
在我的表单类型中我有: p>
$ builder
- > add('options','choice',[
'choices'=> $ choices,
'multiple'=> true,
'expanded'=> true,
' label'=> false
])
;
code> pre>
选项是一个数组: p>
$ choices = [
'val1'=> 'val1',
'val2'=> 'val2',
'val3'=> 'val3'
];
code> pre>
太棒了! 现在我想用这样的数组对我的选择进行分类: p>
$ choices = [
'label1'=> [
'val1'=> 'val1',
'val2'=> 'val2',
],
'label2'=> [
'val3'=> 'val3',
'val4'=> 'val4',
],
'label3'=> [
'val5'=> 'val5',
'val6'=> 'val6',
],
];
code> pre>
所以我想要下面的结果 p>
p>
达到此目的的最佳方法是什么? p>
div>
答
You can override a widget for this choice field and manually render labels
Like this (in your form tamplate):
{% form_theme putYourFormNameHere _self %}
{% block _putYourFormNameHere_options_widget %}
<div {{ block('widget_container_attributes') }}>
{% for group_label, group in choices %}
{%- if group is iterable -%}
<div>
<label><b>{{ group_label|trans({}, translation_domain) }}</b></label>
{% for key, choice in group %}
<div>
{{- form_widget(form[key]) -}}
{{- form_label(form[key]) -}}
<div>
{% endfor %}
</div>
{%- endif -%}
{% endfor %}
{% endblock %}