Giancarlo Ventura
Giancarlo Ventura

Reputation: 183

Set logged user in another entity with FOSUserBundle

I want to set the logged user in a set method for another entity. For example, I have the entities Article and User (User is an FOSUser entity). I want to set the current user as author for an article.

In the Article entity, I write:

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

   /**
     * Set user
     *
     * @param \UserBundle\Entity\User $user
     * @return Article
     */
    public function setUser(\UserBundle\Entity\User $user = null)
    {
        //This line is the problem
        $this->user = $this->container->get('security.context')->getToken()->getUser();

        return $this;
    }

I'm trying to get the user from the container, but when I perform a save, the set value is null. I test the line in a controller and I get successfully the current user. Maybe inside an entity the method for get the logged user is different?

Upvotes: 1

Views: 168

Answers (2)

cRsakaWolf
cRsakaWolf

Reputation: 95

You have to set the user with the function chalasr said

$article->setUser($this->getUser());

persist it to db and you are done :)

Upvotes: 0

chalasr
chalasr

Reputation: 13167

An Entity cannot access the service container, also you cannot use any service inside.

To make it working, call the Article::setUser() from a controller or another context that can use the container. e.g. :

$currentUser = $this->container->get('security.token_storage')->getToken()->getUser();

$article = new Article();
$article->setUser($currentUser);
// ...
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();

And the field will be correctly filled.

Upvotes: 1

Related Questions