user1018146
user1018146

Reputation:

The good way to persist a FOSUser entity in cascade

I want to persist a User entity extends FOSUserBundle entity but an error occured :

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username_canonical' cannot be null

How can I overload the persist function of my User entity to give the informations it needs ?

My User entity :

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

     /**
      *
      * @ORM\OneToOne(targetEntity="MyApp\MainBundle\Entity\Project")
      */
     private $project;
...
}

My Project entity:

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

    /**
     * @var integer $master
     *
     * @ORM\OneToOne(targetEntity="Uriae\UserBundle\Entity\User", cascade={"persist"})
     *
     * @Assert\NotBlank()
     * @Assert\Type(type="Uriae\UserBundle\Entity\User")
     */
    private $master;
...
}

EDIT TO RESPONSE FractalizeR :

Do you mean i must set manually the usernameCanonical property after the persist ?

Actyally i have that after the form is sent in my controller :

$structure = new \Uriae\MainBundle\Entity\Structure();
if ($request->getMethod() == 'POST')
{
    $form->bindRequest($request);

    if ($form->isValid())
    {
       $em = $this->getDoctrine()->getEntityManager();
       $em->persist($structure);
       $em->flush();

       ...
    }
}

Do you mean I have to set manually the usernameCanonical property after the persist ? Or where/when ? But especially how ?

Upvotes: 2

Views: 1358

Answers (1)

JamesHalsall
JamesHalsall

Reputation: 13485

When you're creating an instance of Structure and then trying to persist/flush... Doctrine2 is:

  1. Realising that there is a relationship on Structure with User (each Stucture instance must have a User instance)
  2. Because there is no User explicitly bound to the Structure instance, it tries to create an empty one.
  3. The save operation on the User fails, because there is no data (in this case, usernameCanonical string is empty)

What you must do is...

Before you save the Structure, add an instance of User to it... if you want to use the current user then use this

$user = $this->get('security.context')->getToken()->getUser();
$structure->setMaster($user);
$em->persist($structure);
$em->flush();

Remember to include the User entity in your controller class (with the use statement).

Upvotes: 2

Related Questions