Symfony ChoiceType $choices - labels and values swapped

◇◆丶佛笑我妖孽 提交于 2019-12-10 17:45:16

问题


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:

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


回答1:


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)



来源:https://stackoverflow.com/questions/44630752/symfony-choicetype-choices-labels-and-values-swapped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!