PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 1, 2022

[FIXED] Symfony ChoiceType $choices - labels and values swapped

 February 01, 2022     symfony, symfony-forms     No comments   

Issue

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?


Solution

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)



Answered By - René Höhle
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing