@@ -88,6 +88,59 @@ These options inherit from the :doc:`ChoiceType </reference/forms/types/choice>`
8888
8989.. include :: /reference/forms/types/options/expanded.rst.inc
9090
91+ ``group_by ``
92+ ~~~~~~~~~~~~
93+
94+ **type **: ``string `` or ``callable `` or :class: `Symfony\\ Component\\ PropertyAccess\\ PropertyPath ` **default **: ``null ``
95+
96+ You can group the ``<option> `` elements of a ``<select> `` into ``<optgroup> ``
97+ by passing a multi-dimensional array to ``choices ``. See the
98+ :ref: `Grouping Options <form-choices-simple-grouping >` section about that.
99+
100+ The ``group_by `` option is an alternative way to group choices, which gives you
101+ a bit more flexibility.
102+
103+ Let's add a few cases to our ``TextAlign `` enumeration::
104+
105+ // src/Config/TextAlign.php
106+ namespace App\Config;
107+
108+ enum TextAlign: string
109+ {
110+ case UpperLeft = 'Upper Left aligned';
111+ case LowerLeft = 'Lower Left aligned';
112+
113+ case Center = 'Center aligned';
114+
115+ case UpperRight = 'Upper Right aligned';
116+ case LowerRight = 'Lower Right aligned';
117+ }
118+
119+ We can now group choices by the enum case value::
120+
121+ use App\Config\TextAlign;
122+ use Symfony\Component\Form\Extension\Core\Type\EnumType;
123+ // ...
124+
125+ $builder->add('alignment', EnumType::class, [
126+ 'class' => TextAlign::class,
127+ 'group_by' => function(TextAlign $choice, int $key, string $value): ?string {
128+ if (str_starts_with($value, 'Upper')) {
129+ return 'Upper';
130+ }
131+
132+ if (str_starts_with($value, 'Lower')) {
133+ return 'Lower';
134+ }
135+
136+ return 'Other';
137+ }
138+ ]);
139+
140+ This callback will group choices in 3 categories: ``Upper ``, ``Lower `` and ``Other ``.
141+
142+ If you return ``null ``, the option won't be grouped.
143+
91144.. include :: /reference/forms/types/options/multiple.rst.inc
92145
93146.. include :: /reference/forms/types/options/placeholder.rst.inc
0 commit comments