symfony2表单复选框分组(扩展和多选)

时间:2015-03-12 13:42:54

标签: php forms symfony twig

在我的表单类型中我有这个:

    $builder
        ->add('options', 'choice', [
            'choices'  => $choices,
            'multiple' => true,
            'expanded' => true,
            'label'    => false
        ])
    ;

选择是一个数组:

$choices = [
     'val1' => 'val1',
     'val2' => 'val2',
     'val3' => 'val3'
];

太棒了!现在我想用这样的数组对我的选择进行分类:

$choices = [
     'label1' => [
        'val1' => 'val1',
        'val2' => 'val2',
     ],
     'label2' => [
        'val3' => 'val3',
        'val4' => 'val4',
     ],
     'label3' => [
        'val5' => 'val5',
        'val6' => 'val6',
     ],
];

所以我想要下面的结果

enter image description here

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:5)

您可以覆盖此选择字段的窗口小部件并手动呈现标签

像这样(以你的形式填写):

{% 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 %}