5

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?

0

1 Answer 1

7

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, just what i wanted, perfect ! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.