Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrading from Symfony 2.6 to 2.7: In a ChoiceType, what does the "choices_as_values" do?

Tags:

forms

php

symfony

I am currently upgrading a Symfony project from version 2.6 to 2.7. I am doing that using the Symfony 2.6-2.7 upgrade guide. It says:

You should flip the keys and values of the "choices" option in ChoiceType and set the "choices_as_values" option to true. The default value of that option will be switched to true in Symfony 3.0.

I have done that. But my forms do not work as expected anymore: there are no default values set for any expanded choice fields anymore (ie with expanded = true and multiple = false). Before, with a field defined as:

$builder->add('handwork', 'choice', array(
    'multiple' => false,
    'expanded' => true,
    'choices' => array(
        1 => 'Yes',
        0 => 'No',
    ),
)

The No choice was selected by default (or was that because of a PHP cast from '' or null to 0?).

So I went to the Symfony docs on the choice form field to understand what choices_as_values does. But it is not documented there.

What am I doing wrong ? And how come this choices_as_values option is not documented?

Edit 1: After reading some more Github issues, it seems like the doc update is not yet ready, which would explain why I was not finding what I needed in the docs. It would seem that previously, in 2.6, my forms automatically casted empty values like null or "" to 0, which made them work as needed. I've yet to figure out how null or "" ends up in my field.

Edit 2: It seems like adding the option 'choice_value' => function($v) { return $v; }, helps get back my default values. This is because in SF 2.7, the value attributes of radio inputs are generated from scratch. They are an integer instead the value provided in the choices array.

like image 523
conradkleinespel Avatar asked Dec 10 '25 22:12

conradkleinespel


1 Answers

I would recommend to keep 'choices_as_values' => false.

$builder->add('handwork', 'choice', array(
    'multiple' => false,
    'expanded' => true,
    'choices' => array(
        1 => 'Yes',
        0 => 'No',
    ),
    'choices_as_values' => false
)

Changing it to 'true' introduces BC-break and is scheduled to v3. It's been added to handle more complex objects, and does not play well with arrays yet: https://github.com/symfony/symfony/issues/14377

Set default values in the form builder, e.g for default 'No':

$builder = $this->createFormBuilder(['handwork' => 0]);

Documentation update is due: https://github.com/symfony/symfony-docs/issues/5179

like image 107
Alex Blex Avatar answered Dec 13 '25 11:12

Alex Blex



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!