Boolean values and choice symfony type

mlwacosmos picture mlwacosmos · Sep 1, 2016 · Viewed 17k times · Source

Using the choice type of Symfony framwork, we can decide de display lists, radio buttons or checkboxes playing with those two keys:

'multiple' => false,
'expanded' => true,  //example for radio buttons

Let's say that instead of strings the value of the different choices given as an array in the 'choices' key are booleans :

$builder->add('myproperty', 'choice', array(
    'choices' => array(
        'Yes' => true,
        'No' => false
     ),
     'label' => 'My Property',
     'required' => true,
     'empty_value' => false,
     'choices_as_values' => true
 )); 

Using a list (select) to display the differnet choices there is no problem and when the form is displayed the right choice in the list is selected.

If I add the two keys(multiple and expanded) I talked about before to replace the list by radio buttons, there is no selected button for my field (though it worked with the select).

Somebody knows why ?

How to easily make it work ?

Thank you

Note : in fact I thought it would not works with any of then as the values are booleans and finally become strings but as it works for the list, I wonder why it does not work for the others.

Answer

mlwacosmos picture mlwacosmos · Sep 2, 2016

I add a data transformer;

$builder->add('myproperty', 'choice', array(
    'choices' => array(
        'Yes' => '1',
        'No' => '0'
     ),
     'label' => 'My Property',
     'required' => true,
     'empty_value' => false,
     'choices_as_values' => true
 )); 

 $builder->get('myProperty')
    ->addModelTransformer(new CallbackTransformer(
        function ($property) {
            return (string) $property;
        },
        function ($property) {
            return (bool) $property;
        }
  ));

It is magical : Now I have the right radio button checked and the right values in the entity.