symfony2表单复选框已分组(扩展和多项选择) [英] symfony2 form checkbox grouped (expanded and multiple choice)

查看:48
本文介绍了symfony2表单复选框已分组(扩展和多项选择)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

in my form type i have this :

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

choices是一个数组:

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',
     ],
];

所以我想要下面的结果

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

what is the best way to achieve this?

推荐答案

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

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

这篇关于symfony2表单复选框已分组(扩展和多项选择)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆