Skip to content

Commit ca038d5

Browse files
authored
[Form] Example of customizing EnumType labels
Default behavior when creating a EnumType form element is that the choice labels displayed to the user are the enum names. This PR adds an example of how to use a function inside an enum to return labels and how to bind this function to the form element.
1 parent 2df5d9d commit ca038d5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

reference/forms/types/enum.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,40 @@ This will display a ``<select>`` tag with the three possible values defined in
5252
the ``TextAlign`` enum. Use the `expanded`_ and `multiple`_ options to display
5353
these values as ``<input type="checkbox">`` or ``<input type="radio">``.
5454

55+
Since the label displayed in the ``<select>`` options is the enum name, you might sometimes
56+
want more flexibility as PHP strongly restricts the usable characters for those.
57+
You could do this by implementing a function in your enum class which returns a label
58+
or even a translation string for each possible enum::
59+
60+
// src/Config/TextAlign.php
61+
namespace App\Config;
62+
63+
enum TextAlign: string
64+
{
65+
case Left = 'Left/Start aligned';
66+
case Center = 'Center/Middle aligned';
67+
case Right = 'Right/End aligned';
68+
69+
public function label(): string
70+
{
71+
return match ($this) {
72+
self::Left => 'text_align.left.label',
73+
self::Center => 'text_align.center.label',
74+
self::Right => 'text_align.right.label',
75+
};
76+
}
77+
}
78+
79+
You can then use the ``choice_label`` option of ``EnumType`` with a function that
80+
returns the label::
81+
82+
->add('textAlign', EnumType::class, [
83+
'class' => TextAlign::class,
84+
'choice_label' => static function (TextAlign $choice): string {
85+
return $choice->label();
86+
},
87+
])
88+
5589
Field Options
5690
-------------
5791

0 commit comments

Comments
 (0)