0
votes

I have problem with Symfony2 form choice field (checkbox). It is always false after submit even if I check it to true.

Entity class:

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

Form builder class:

...->add('isActive')

And var_dump when I submit form with field unchecked or checked, result is still the same:

private 'isActive' => boolean false

When I change the form builder class like this:

...->add('isActive', 'choice', ['choices' => [true => 'Yes', false => 'No']])

it works then with integer value:

private 'isActive' => int 1

Does anybody know what am I doing bad?

2

2 Answers

0
votes

This is not exactly a Symfony2 issue. It is a PHP issue.

You are using an array that has boolean values as keys, but PHP doesn't support that. PHP is automatically casting those boolean values to integers.

So, when you are defining your choices you are in fact defining them like this:

$arr = [true => 'Yes', false => 'No'];
var_dump($arr);

This code block would return:

array(2) {
    [1] =>
    string(4) "Yes"
    [0] =>
    string(5) "No"
  }

You could try to automatically cast to boolean in the setIsActive method, but I don't know if it would work.

0
votes

Solution found. I added nullable=false to my entity class.

/**
 * @var boolean
 *
* @ORM\Column(name="isActive", type="boolean", nullable=false)
 */
private $isActive;

Now it works.