Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony (3.2)'s ChoiceType - flipping key/values?

I've been wrecking my brain, going from 2.7.x docs all up onto 3.2 which I am on and I fail to see why they removed choices_as_values. It is exactly what I require.

At this time I've got an input (don't ask why) with 3 values, 2 of which have the same name/label. It's what the customer wants and after much discussing I simply had to agree. So, i.e. I've got the following:

1 => Name
2 => Name
3 => Other Name

However, Symfony wants it received like this:

Name => 1
Name => 2
Other Name => 3

You can see the problem, the resulting array would become:

Name => 2
Other Name => 3

I'd be missing ONE value. So, what is the right way to go about this? I've tried numerous solutions, none of them worked. Keep in mind that the resulting value after submit must still be 1, 2 or 3.

like image 840
ReSpawN Avatar asked Oct 16 '25 16:10

ReSpawN


1 Answers

The reason for flipping was that PHP only allows integers and strings to be array keys while actual choice values could be arbitrary PHP types. Usually, labels however are unique as duplicate keys will likely confuse users so it's easy to have them as the keys of the choices option value.

Anyway, if you need labels to be duplicated, you can pass a callback to the choice_label that will return the label to be displayed:

$builder->add(ChoiceType::class, null, [
    'choices' => [
        1,
        2,
        3,
    ],
    'choice_label' => function ($value) {
        switch ($value) {
            case 1:
                return 'Name';
            case 2:
                return 'Name';
            case 3:
                return 'Other Name';
            default:
                return '';
        }
    },
]);
like image 135
xabbuh Avatar answered Oct 18 '25 09:10

xabbuh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!