Skip to content

[Form] Add group_by option for EnumType #17708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions reference/forms/types/enum.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,59 @@ These options inherit from the :doc:`ChoiceType </reference/forms/types/choice>`

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

``group_by``
~~~~~~~~~~~~

**type**: ``string`` or ``callable`` or :class:`Symfony\\Component\\PropertyAccess\\PropertyPath` **default**: ``null``

You can group the ``<option>`` elements of a ``<select>`` into ``<optgroup>``
by passing a multi-dimensional array to ``choices``. See the
:ref:`Grouping Options <form-choices-simple-grouping>` section about that.

The ``group_by`` option is an alternative way to group choices, which gives you
a bit more flexibility.

Let's add a few cases to our ``TextAlign`` enumeration::

// src/Config/TextAlign.php
namespace App\Config;

enum TextAlign: string
{
case UpperLeft = 'Upper Left aligned';
case LowerLeft = 'Lower Left aligned';

case Center = 'Center aligned';

case UpperRight = 'Upper Right aligned';
case LowerRight = 'Lower Right aligned';
}

We can now group choices by the enum case value::

use App\Config\TextAlign;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
// ...

$builder->add('alignment', EnumType::class, [
'class' => TextAlign::class,
'group_by' => function(TextAlign $choice, int $key, string $value): ?string {
if (str_starts_with($value, 'Upper')) {
return 'Upper';
}

if (str_starts_with($value, 'Lower')) {
return 'Lower';
}

return 'Other';
}
]);

This callback will group choices in 3 categories: ``Upper``, ``Lower`` and ``Other``.

If you return ``null``, the option won't be grouped.

.. include:: /reference/forms/types/options/multiple.rst.inc

.. include:: /reference/forms/types/options/placeholder.rst.inc
Expand Down