Closed
Description
With 2.7, the way of creating choice fields with duplicate labels has changed. When before (with choices_as_values
set to false
) it was possible to have choices in different choice groups that shared the same labels, this is not possible anymore:
$builder->add('country', 'choice', [
'choices' => [
'Top' => [
'FR' => 'France',
'DE' => 'Germany',
],
'All' => [
'AT' => 'Austria',
// ...
'DE' => 'Germany',
// ...
],
],
]);
This won't work. The reason is that the choice keys (i.e. the LHS of the array) must be unique. You can solve this use case by setting choice_label
to a closure. This closure accepts the choice, the choice key and the choice value as arguments. You can convert the unique keys to non-unique labels in there:
$countries = [
'Austria' => 'AT',
// ...
'Germany' => 'DE',
// ...
];
$builder->add('country', 'choice', [
'choices' => [
'Top' => [
'Top_France' => 'FR',
'Top_Germany' => 'DE',
],
'All' => [
'Austria' => 'AT',
// ...
'Germany' => 'DE',
// ...
];,
],
'choices_as_values' => true,
'choice_label' => function ($choice, $key) {
if ('Top_' === substr($key, 0, 4)) {
// Strip "Top_"
return substr($key, 4);
}
// Return unchanged
return $key;
},
]);