Skip to content

[Form] Support Translatable Enum #18599

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
Jul 27, 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
41 changes: 31 additions & 10 deletions reference/forms/types/enum.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,38 @@ these values as ``<input type="checkbox">`` or ``<input type="radio">``.

The label displayed in the ``<option>`` elements of the ``<select>`` is the enum
name. PHP defines some strict rules for these names (e.g. they can't contain
dots or spaces). If you need more flexibility for these labels, use the
``choice_label`` option and define a function that returns the custom label::
dots or spaces). If you need more flexibility for these labels, your enum can
implement ``TranslatableInterface`` to translate or display custom labels::

->add('textAlign', EnumType::class, [
'class' => TextAlign::class,
'choice_label' => fn ($choice) => match ($choice) {
TextAlign::Left => 'text_align.left.label',
TextAlign::Center => 'text_align.center.label',
TextAlign::Right => 'text_align.right.label',
},
]);
// src/Config/TextAlign.php
namespace App\Config;

use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

enum TextAlign: string implements TranslatableInterface
{
case Left = 'Left aligned';
case Center = 'Center aligned';
case Right = 'Right aligned';

public function trans(TranslatorInterface $translator, string $locale = null): string
{
// Translate enum from name (Left, Center or Right)
return $translator->trans($this->name, locale: $locale);

// Translate enum using custom labels
return match ($this) {
self::Left => $translator->trans('text_align.left.label', locale: $locale),
self::Center => $translator->trans('text_align.center.label', locale: $locale),
self::Right => $translator->trans('text_align.right.label', locale: $locale),
};
}
}

.. versionadded:: 6.4

Support for ``TranslatableInterface`` was introduced in Symfony 6.4.

Field Options
-------------
Expand Down