jeudi 4 février 2016

Symfony form setting default checkbox value in many-to-many entity collection

I am having an issue setting default values for checkboxes displayed for a many t many relationship.

I have a User entity and Options entity with a many-to-many relationship, mapped b a user_option table.

In a user form, I display the list of options in a checkbox.

The options entity contains a default field that indicated if the checkbox is set or unset for a new user. If the user has selected, then the user selection must be displayed.

class User {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="name", type="string", length=64, nullable=true)
     */
    protected $name;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Bundle\Entity\Option", inversedBy="users")
     * @ORM\JoinTable(name="user_options")
     */
    protected $userOptions;
}

class CommunicationOption {

   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=50)
     */
    protected $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="default_state", type="boolean")
     */

}

The form load the options

public function buildForm(FormBuilderInterface $builderInterface, array $options)
{
    $builderInterface
        ->add('userOptions', 'entity', array(
            'class' => 'Bundle\Entity\Option',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            'query_builder' => function (EntityRepository $repository) {
                return $repository->getFindAllQueryBuilder();
            },
            'by_reference' => true,
        ))
    ;
}

This displays all options. However, all checkboxes are unchecked. If a user saves data in the user_options table, then the checkbox is correctly displayed.

    {% for element in form.userOptions %}
       {{ form_widget(element, {'attr': {'class': 'col-xs-1' }}) }}
       {{ element.vars.label|raw }}
    {% endfor %}

I require that for new entries, the default field is considered. Setting the value in the constructor did not change the checkbox value, and in any case will set the default for all fields to true, which is not what I want.




Aucun commentaire:

Enregistrer un commentaire