jeudi 4 octobre 2018

Symfony checkbox checked by default, but not if unchecked after persisted

Spoiler alert : this question has been asked numerous times over the years but sofar i've seen no working solutions. here for instance

I'm developping an application based on a Symfony 2.8 version.

I have an entity with a boolean that i map in the formType with a CheckboxType.

What i need is :

  • if this is a new Entity, the checkbox is checked
  • if the user has unchecked the checkbox, then persisted, i want the checkbox unchecked
  • if i reopen the form if the user has checked the checkbox, then persisted, i want the checkbox checked if i reopen the form

This said, i've tried many "solutions" that have been suggested over the topics

1) In the Entity

i've set my boolean attribute to true => FAIL : the checkbox is not checked by default

class MyEntity
{
  /**
   * @ORM\Column(name="enabled", type="boolean")
   */
  private $enabled = true;

  public function __construct()
  {
    $this->enabled = true;
  }
}

2) In the FormType

  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
      ->add('enabled', CheckboxType::class, [
        'required' => false,
        'empty_data' => true,
      ]);
  }

This 'empty_data' => true (or 'empty_data' => 1, or whatever) works "partially" : It displays the correct checkbox state AFTER a persistance, but does not check the checkbox by default => FAIL

  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
      ->add('enabled', CheckboxType::class, [
        'required' => false,
        'data' => true,
      ])
  }

It does check the checkbox by default, BUT if a user uncheck the checkbox and persists, the reloaded form still shows the checkbox checked, even if the persisted state is unchecked => FAIL this is expected as stated in the docs

Since this entity is not the main form entity : a subform (in a Collection), i also tried to set the compound attribute to true in the CheckboxType, with no effect.

3) Setting the value in the controller when instanciating the form

this is not a possible option since the checkbox is not in the main Entity/FormType

=> My method

Sofar, the only "working solution" i found is to check the checkbox when adding a new block of this Collection using javascript :

$(element).prop('checked', true)

This is less than optimal...

Do you have a solution for this with SF >=2.8 (2.8 is my version) ? The solution being Symfony side.




Aucun commentaire:

Enregistrer un commentaire