Skip to content

Commit 8612bab

Browse files
committed
feature #18599 [Form] Support Translatable Enum (Seb33300)
This PR was squashed before being merged into the 6.4 branch. Discussion ---------- [Form] Support Translatable Enum Documentation for symfony/symfony#50931 Commits ------- 5f59527 [Form] Support Translatable Enum
2 parents 73a67c0 + 5f59527 commit 8612bab

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

reference/forms/types/enum.rst

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,38 @@ these values as ``<input type="checkbox">`` or ``<input type="radio">``.
5151

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

57-
->add('textAlign', EnumType::class, [
58-
'class' => TextAlign::class,
59-
'choice_label' => fn ($choice) => match ($choice) {
60-
TextAlign::Left => 'text_align.left.label',
61-
TextAlign::Center => 'text_align.center.label',
62-
TextAlign::Right => 'text_align.right.label',
63-
},
64-
]);
57+
// src/Config/TextAlign.php
58+
namespace App\Config;
59+
60+
use Symfony\Contracts\Translation\TranslatableInterface;
61+
use Symfony\Contracts\Translation\TranslatorInterface;
62+
63+
enum TextAlign: string implements TranslatableInterface
64+
{
65+
case Left = 'Left aligned';
66+
case Center = 'Center aligned';
67+
case Right = 'Right aligned';
68+
69+
public function trans(TranslatorInterface $translator, string $locale = null): string
70+
{
71+
// Translate enum from name (Left, Center or Right)
72+
return $translator->trans($this->name, locale: $locale);
73+
74+
// Translate enum using custom labels
75+
return match ($this) {
76+
self::Left => $translator->trans('text_align.left.label', locale: $locale),
77+
self::Center => $translator->trans('text_align.center.label', locale: $locale),
78+
self::Right => $translator->trans('text_align.right.label', locale: $locale),
79+
};
80+
}
81+
}
82+
83+
.. versionadded:: 6.4
84+
85+
Support for ``TranslatableInterface`` was introduced in Symfony 6.4.
6586

6687
Field Options
6788
-------------

0 commit comments

Comments
 (0)