Monday, August 20, 2018

Why setUserId method not work in entity symfony2?

Why my methid setUserId not work? It's my Post entity:

id;
    }

    /**
     * Set user_id
     *
     * @param integer $userId
     * @return Post
     */
    public function setUserId($userId)
    {
        $this->user_id = $userId;

        return $this;
    }

    /**
     * Get user_id
     *
     * @return integer 
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    public function getText()
    {
        return $this->text;
    }

    public function __construct() {
        $this->date = new \DateTime();
    }
    //...

}

And my User entity:

posts = new ArrayCollection();

    }


}

I'm saving in the database via my controller:

 public function createAction(Request $request)
    {
        $post = new Post();

        $form = $this->createFormBuilder($post)
                     ->add('text')
                     ->add('address')
                     ->getForm();
        $post->setUserId($this->getUser()->getId());

        $form->handleRequest($request);

        if($form->isValid()){
            $em = $this->getDoctrine()->getManager();
            $em->persist($post);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('home'));    
    }

And i throw this error:

Integrity constraint violation: 1048 Column 'user_id' cannot be null Why? My $this->getUser()->getId() is not null, i tried return new Response($this->getUser()->getId()) and get my id

Solved

You dont need user_id field because you have user relation on field:

 /**
 * @ORM\ManyToOne(targetEntity="Acme\PostBundle\Entity\User", inversedBy="posts")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;
/**

Look in you database, doctrine already created user_id for you.


As the others stated its not possible to set $userId on its own if you have also defined an $user property as entity using the same database column.

Instead change your setters and keep everything else as it is:

class Post
{
    // ...

    /**
     * Set user_id
     *
     * @param integer $userId
     * @throws \Exception
     */
    public function setUserId($userId)
    {
        throw new \Exception('Post->userId can not be set directly');
    }

    /**
     * Set user
     *
     * @param User $user
     * @return Post
     */
    public function setUser($user)
    {
        $this->user    = $user;
        $this->user_id = $user->getId();

        return $this;
    }

    // ...
}

Now the $userId is automatically updated when you use setUser(...). Throwing an exception in setUserId helps you preventing bugs in your code. Of course you could also just delete the setter, but it then would be recreated everytime you run another doctrine:generate:entities for your post entity.


No comments:

Post a Comment