@@ -95,23 +95,31 @@ method::
9595 new Category('Cat3'),
9696 new Category('Cat4'),
9797 ],
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()) : '';
100103 },
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())] : [ ];
103106 },
104- 'group_by' => function(Category $category, $key, $value ) {
107+ 'group_by' => function() {
105108 // randomly assign things into 2 groups
106109 return rand(0, 1) == 1 ? 'Group A' : 'Group B';
107110 },
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);
110118 },
111119 ]);
112120
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 .
115123
116124.. _forms-reference-choice-tags :
117125
@@ -151,7 +159,7 @@ by passing a multi-dimensional ``choices`` array::
151159.. image :: /_images/reference/form/choice-example4.png
152160 :align: center
153161
154- To get fancier, use the `group_by `_ option.
162+ To get fancier, use the `group_by `_ option instead .
155163
156164Field Options
157165-------------
@@ -169,7 +177,10 @@ is the item's label and the array value is the item's value::
169177 // ...
170178
171179 $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+ ],
173184 ]);
174185
175186If there are choice values that are not scalar or the stringified
0 commit comments