8000 minor #17708 [Form] Add `group_by` option for `EnumType` (alexandre-d… · symfony/symfony-docs@730070c · GitHub
[go: up one dir, main page]

Skip to content

Commit 730070c

Browse files
committed
minor #17708 [Form] Add group_by option for EnumType (alexandre-daubois)
This PR was submitted for the 6.2 branch but it was merged into the 5.4 branch instead. Discussion ---------- [Form] Add `group_by` option for `EnumType` Resolves #17707 Commits ------- 32e93ba [Form] Add `group_by` option for EnumType
2 parents 3062a15 + 32e93ba commit 730070c

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

reference/forms/types/enum.rst

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,59 @@ These options inherit from the :doc:`ChoiceType </reference/forms/types/choice>`
9292

9393
.. include:: /reference/forms/types/options/expanded.rst.inc
9494

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

97150
.. include:: /reference/forms/types/options/placeholder.rst.inc

0 commit comments

Comments
 (0)
0