Search code examples
ormsymfonyfosuserbundle

Symfony 3 get current user inside entity


I was wondering if there is a way that i can initialize the property owner with an entity User of FOSUserBundle so that it contains the user who created the Post

I want to do this inside the constructor as shown below.

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="post")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
 */
class Post
{
  /* here are defined some attributs */
  /**
  * @ORM\ManyToOne(targetEntity="User", inversedBy="posts")
  * @ORM\JoinColumn(name="owner", referencedColumnName="id")
  */
  private $owner;

  public function __construct()
  {
    $this->owner = /* get current user */ ;
  }

}

Is there a way to do this by replacing the comment in the constructor with something ?

Thank you for your answers


Solution

  • I think you are way over-complicating this issue. When you create a new Post in your controller, either in the controller or in the repository do something like this:

    use AppBundle\Entity\Post; //at top of controller
    
    $em = $this->getDoctrine()->getManager();
    $user = $this->container->get('security.token_storage')->getToken()->getUser();
    $post = new Post();
    $em->persist( $post );
    $post->setOwner( $user );
    // set other fields in your post entity
    $em->flush();