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

[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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
OskarStark merged 1 commit intosymfony:6.4fromSeb33300:patch-3
Jul 27, 2023
Merged
Changes fromall 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 deletionsreference/forms/types/enum.rst
View file
Open in desktop
Original file line numberDiff line numberDiff 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 thecustomlabel::
dots or spaces). If you need more flexibility for these labels,your enum can
implement ``TranslatableInterface``to translate or displaycustomlabels::

->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

[8]ページ先頭

©2009-2025 Movatter.jp