David Declercq February 2016

FOSUserBundle and persisting in database

I have a User entity class that inherits from FOSUserBundle BaseUser class. On the other side an Avis entity class.

/**
 * Avis
 *
 * @ORM\Table()
 * @ORM\Entity
 */
 class Avis
 {
   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
     private $id;

     /**
      * @var integer
      *
      * @Assert\NotBlank(message = "Merci d'attribuer une note", groups = {"Default"})
      *
      * @ORM\Column(name="note", type="smallint")
      */
      private $note;

    /**
      * @var string
      *
      * @Assert\NotBlank(message = "Merci d'entrer un message", groups = {"Default"})
      * @Assert\Length(max = 500, maxMessage = "Votre message doit contenir au maximum {{ limit }} caractères de longueur", groups = {"Default"})
      *
      * @ORM\Column(name="message", type="string", length=500)
      */
      private $message;

    /**
      * @Assert\Type(type="LeJardinEbene\Bundle\Entity\User")
      *
      * @ORM\OneToOne(targetEntity="LeJardinEbene\Bundle\Entity\User", cascade={"persist"}, inversedBy="avis")
      * @ORM\JoinColumn(nullable=true)
      */
      private $user;



/**
  * User
  *
  * @ORM\Table(name="fos_user")
  * @ORM\Entity
  */
  class User extends BaseUser
  {
   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
     protected $id;

   /**
     * @Assert\Type(type="LeJardinEbene\Bundle\Entity\Avis")
     *
     * @ORM\OneToOne(targetEntity="LeJardinEbene\Bundle\Entity\Avis", mappedBy="user")
     * @ORM\JoinColumn(nullable=true)
     */
     protected $avis;

So Avis is the owner of this bidirectional relation. In my form I display Avis object fields and when validating the form I would like :

  • Avis to be persisted in the database (that already works)
  • Relation to be persisted also => user_id in Av

Answers


Frankbeen February 2016

With a one-to-one and a many-to-many only one table gets a foreign-index column. In your case the "avis" table will get a column user_id. So you will only have to set the $user property before you persist. Doctrine will set the $avis property in the User class automatically after (re)loading.

 $user = $this->getUser();
 $avis = new Avis();
 $form = $this->createForm('avis', $avis);

 $form->handleRequest($request);
 if ($form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();

        $avis->setUser($user);

        $entityManager->persist($avis);
        $entityManager->flush();

 }

Post Status

Asked in February 2016
Viewed 1,909 times
Voted 14
Answered 1 times

Search




Leave an answer