vendredi 19 février 2016

Symfony2 form unchecked checkbox not taken into account, why?

When I send a form with an unchecked checkbox, if the related entity property equals true, then it does not change to false.

The other way round (setting property to true when the form is sent with a checked checkbox) works fine, as well as all the forms other fields saving.

Here is how I build the form and declare the related property:

// --- Form creation function EntityType::buildForm() ---
$builder->add('secret', 'checkbox', array( 'required' => false ));

// --- Entity related property, Entity.php file ---
/** @ORM\Column(name="secret", type="boolean") */
protected $secret;

I have noticed on Symfony's Profiler that, after a first form submission with a checked checkbox, then on subsequent submissions, the 'Default data' field for secret is set to true:

// First submission, checkbox checked
secret [checkbox]
Default Data
Model Format:   same as normalized format
Normalized Format: false
View Format: null

// Second submission, checkbox unchecked
secret [checkbox]
Default Data
Model Format: same as normalized format
Normalized Format: true
View Format: 1

I'm unsure of what this Default Data is, but this might explain why, when the checkbox is sent unchecked (so no POST data received on Symfony's end), this true default value is used. But if this is the case, why is this default value automatically set even though I ask no such thing?


NB. I have exactly the same issue with an array of checkboxes using a choice field type (with multiple and extended to true) linked to a Doctrine Simple Array property: as soon as a given checkbox has been sent once as checked, it is impossible to set back the related property to false with subsequent unchecked submissions. Idem, the 'Default data' for the field (as read on the Profiler) is set after each submission to the list of sent checked checkboxes.




Aucun commentaire:

Enregistrer un commentaire