Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fa2dfc8

Browse files
committed
minor #17149 [Form] Example of customizing EnumType labels (robinbrisa)
This PR was submitted for the 6.1 branch but it was merged into the 5.4 branch instead. Discussion ---------- [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. Commits ------- 65ece3e [Form] Example of customizing EnumType labels
2 parents f1c80b8 + 65ece3e commit fa2dfc8

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
@@ -56,6 +56,40 @@ This will display a ``<select>`` tag with the three possible values defined in
5656
the ``TextAlign`` enum. Use the `expanded`_ and `multiple`_ options to display
5757
these values as ``<input type="checkbox">`` or ``<input type="radio">``.
5858

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

0 commit comments

Comments
 (0)