Search code examples
phpformssymfonytwig

symfony2 form checkbox grouped (expanded and multiple choice)


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

enter image description here

what is the best way to achieve this?


Solution

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