Boolean values and choice symfony type

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.


Another solution is to use Doctrine Lifecycle Callbacks and php Type Casting.

With this FormType:

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

//...

$builder->add('active', ChoiceType::class, [
    'choices' => [
        'active' => true,
        'inactive' => false
    ]
])

And Entity like this :

//...
use Doctrine\ORM\Mapping as ORM;

/**
 * ...
 * @ORM\HasLifecycleCallbacks()                      /!\ Don't forget this!
 * ...
 */
class MyEntity {

    //..

    /**
     * @var bool
     *
     * @ORM\Column(name="active", type="boolean")
     */
    private $active;

    //...

    /**
     * @ORM\PrePersist()
     */
    public function prePersist()
    {
        $this->active = (bool) $this->active; //Force using boolean value of $this->active
    }

    /**
     * @ORM\PreUpdate()
     */
    public function preUpdate()
    {
        $this->active = (bool) $this->active;
    }    

    //...
}