Skip to content

[2.7] Add documentation for choice fields with duplicate labels #5905

Closed
@webmozart

Description

@webmozart

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;
    },
]);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions