Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8612bab

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 EnumDocumentation forsymfony/symfony#50931Commits-------5f59527 [Form] Support Translatable Enum
2 parents73a67c0 +5f59527 commit8612bab

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 thecustomlabel::
54+
dots or spaces). If you need more flexibility for these labels,your enum can
55+
implement ``TranslatableInterface``to translate or displaycustomlabels::
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)

[8]ページ先頭

©2009-2025 Movatter.jp