@@ -95,23 +95,31 @@ method::
95
95
new Category('Cat3'),
96
96
new Category('Cat4'),
97
97
],
98
- 'choice_label' => function(Category $category, $key, $value) {
99
- return strtoupper($category->getName());
98
+ // a property path can by used to define the options below
99
+ 'choice_value' => 'name',
100
+ // the empty value can be passed if there is a placeholder
101
+ 'choice_label' => function(?Category $category) {
102
+ return $category ? strtoupper($category->getName()) : '';
100
103
},
101
- 'choice_attr' => function(Category $category, $key, $value ) {
102
- return ['class' => 'category_'.strtolower($category->getName())];
104
+ 'choice_attr' => function(? Category $category) {
105
+ return $category ? ['class' => 'category_'.strtolower($category->getName())] : [ ];
103
106
},
104
- 'group_by' => function(Category $category, $key, $value ) {
107
+ 'group_by' => function() {
105
108
// randomly assign things into 2 groups
106
109
return rand(0, 1) == 1 ? 'Group A' : 'Group B';
107
110
},
108
- 'preferred_choices' => function(Category $category, $key, $value) {
109
- return $category->getName() == 'Cat2' || $category->getName() == 'Cat3';
111
+ // the empty value maybe passed if a placeholder is used
112
+ 'preferred_choices' => function(?Category $category) {
113
+ if (null === $category) {
114
+ return false;
115
+ }
116
+
117
+ return in_array($category->getName(), ['Cat2', 'Cat3'], true);
110
118
},
111
119
]);
112
120
113
- You can also customize the `choice_name `_ and ` choice_value `_ of each choice if
114
- you need further HTML customization .
121
+ You can also customize the `choice_name `_ of each choice. You can learn more
122
+ about all of them in the sections below .
115
123
116
124
.. _forms-reference-choice-tags :
117
125
@@ -151,7 +159,7 @@ by passing a multi-dimensional ``choices`` array::
151
159
.. image :: /_images/reference/form/choice-example4.png
152
160
:align: center
153
161
154
- To get fancier, use the `group_by `_ option.
162
+ To get fancier, use the `group_by `_ option instead .
155
163
156
164
Field Options
157
165
-------------
@@ -169,7 +177,10 @@ is the item's label and the array value is the item's value::
169
177
// ...
170
178
171
179
$builder->add('inStock', ChoiceType::class, [
172
- 'choices' => ['In Stock' => true, 'Out of Stock' => false],
180
+ 'choices' => [
181
+ 'In Stock' => true,
182
+ 'Out of Stock' => false,
183
+ ],
173
184
]);
174
185
175
186
If there are choice values that are not scalar or the stringified
0 commit comments