Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony ChoiceType $choices - labels and values swapped

Symfony 2.8.2

According to the Symfony docs "The choices option is an array, where the array key is the item's label and the array value is the item's value"

http://symfony.com/doc/2.8/reference/forms/types/choice.html#choices

But with the following form I'm seeing the exact opposite:

        $filterForm = $this->createFormBuilder()
        ->add('vendorName', ChoiceType::class, array(
            'expanded' => true,
            'multiple' => true,
            'choices'  => array('label' => 'value') // <-- HERE
        ))
        ->add('filter', SubmitType::class, array('label' => 'Filter'))
        ->getForm();

Renders like this:

Label is value and the value is label

Is the documentation wrong? Or am I not getting it right?

like image 781
Stas Parshin Avatar asked Nov 30 '25 06:11

Stas Parshin


2 Answers

In newer Symfony versions die Option choices_as_values is deprecated.

https://github.com/symfony/symfony/issues/14951

here is an explanation. I think in your case you have to switch it or use the option so long you can.

Set choices_as_values to true. If you upgrade you have to change that.

@Soullivaneuh choices_as_values is not directly to choice_label. So you are talking about a different topic. choices_as_values controls where the choices are the keys or the values in the choices option. Symfony 2.0 shipped with choices as keys (and labels as values), which means that the easy syntax only works when your choices are integers or strings. Any other case (boolean choices for instance) required passing a ChoiceList object instead, making the usage more complex (especially for people forgetting that booleans cannot be used as keys as PHP just casts them to string silently). This is the reason why this option has been introduced in 2.7 to be able to flip the array (while maintaining BC). the advantage is that any type of data can be used in this way (strings, integers, floats, booleans, objects, arrays)

like image 105
René Höhle Avatar answered Dec 03 '25 04:12

René Höhle


As of Symfony 4 "choices_as_values" is no longer supported: https://github.com/symfony/symfony/issues/14951

You would have to use this to achieve the same:

            'choice_label' => function ($value) {
                return $value;
            },
like image 29
DasBen Avatar answered Dec 03 '25 06:12

DasBen



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!