Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean values and choice symfony type

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.

like image 504
mlwacosmos Avatar asked Sep 01 '16 13:09

mlwacosmos


1 Answers

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.

like image 50
mlwacosmos Avatar answered Sep 28 '22 04:09

mlwacosmos