1

This is part of my Post entity:

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="post")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
 private $user;

and from the User entity:

/**
 * @ORM\OneToMany(targetEntity="Post", mappedBy="user")
 */
 private $post;

my controller looks like this:

$post = new Post();

$form = $this->createForm('FreeCycler\UserBundle\Form\PostType', $post);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $post->setUser($this->getUser());

    // also tried this:
    //$post->setUser($this->getUser()->getId());

    $em = $this->getDoctrine()->getManager();
    $em->persist($post);
    $em->flush($post);

    return $this->redirectToRoute('my_post_show', array('id' => $post->getId()));
}  

The post gets saved to the orm but the user is empty or null. The $this->getUser(), however isn't null and it's shows the user object if I dump it.

7
  • very strange, try moving the line $post->setUser($this->getUser()); after the object creation $post = new Post(); Commented Dec 24, 2016 at 7:36
  • I have tried this but got the same problem. Commented Dec 24, 2016 at 8:53
  • Could you show us the Post::setUser() method? and try to rename name="user" to name="user_id" and update your DB schema. Commented Dec 24, 2016 at 13:09
  • Are you using the User entity as the security user in your SecurityUserProvider? Commented Dec 24, 2016 at 14:49
  • In your relation between post and user, you have affect many users to one post, I think you may convert the relation. Commented Dec 24, 2016 at 23:19

1 Answer 1

1

Remove the $post parameter from the flush method. Doctrine won't flush the user object otherwise. Providing an entity forces Doctrine to only flush that entity and no others. Further, your relationship is bidirectional so without flushing the $user as well it won't work. In fact, the flush() method will likely have this functionality removed from Doctrine in the future.

Just do $em->flush().

Discussion of this issue on Doctrine's Github repo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.