diff --git a/reference/forms/types/enum.rst b/reference/forms/types/enum.rst index b2e960a21ec..4c9d3eeb8a5 100644 --- a/reference/forms/types/enum.rst +++ b/reference/forms/types/enum.rst @@ -56,6 +56,40 @@ This will display a ``<select>`` tag with the three possible values defined in the ``TextAlign`` enum. Use the `expanded`_ and `multiple`_ options to display these values as ``<input type="checkbox">`` or ``<input type="radio">``. +Since the label displayed in the ``<select>`` options is the enum name, you might sometimes +want more flexibility as PHP strongly restricts the usable characters for those. +You could do this by implementing a function in your enum class which returns a label +or even a translation string for each possible enum:: + + // src/Config/TextAlign.php + namespace App\Config; + + enum TextAlign: string + { + case Left = 'Left/Start aligned'; + case Center = 'Center/Middle aligned'; + case Right = 'Right/End aligned'; + + public function label(): string + { + return match ($this) { + self::Left => 'text_align.left.label', + self::Center => 'text_align.center.label', + self::Right => 'text_align.right.label', + }; + } + } + +You can then use the ``choice_label`` option of ``EnumType`` with a function that +returns the label:: + + ->add('textAlign', EnumType::class, [ + 'class' => TextAlign::class, + 'choice_label' => static function (TextAlign $choice): string { + return $choice->label(); + }, + ]) + Field Options -------------