Search code examples
phpsymfonysymfony2-easyadmin

Symfony 3 - How to set currently logged user as entity "author"


Let's assume, that I have two entity classes:
\AppBundle\Entity\User - user provider;
\AppBundle\Entity\Article - simple article.

The Article class also have these properties:
author - indicating on user which created this particular entity;
updatedBy - indicating on user which lately updated content of particular article.

How to pass currently logged user object to Article entity to set specific values on author and/or updatedBy properties on backend generated by EasyAdminBundle on Symfony 3.0.1?


Solution

  • If you are in a Controller you just do that

    $article->setAuthor($this->getUser());
    $article->setUpdatedBy($this->getUser());
    

    Or

    If you want that this is automatic

    You need to declare a listener on Doctrine event. In your case I guess on preUpdate by including the current user.

    There is a very nice documentation here http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html

    I edit here to answer at your comment

    Don't worry you can inject the user entity when you declare your listener as Service

    For example :

    services:
        your_listener:
            class:     App\AppBundle\Your_Listener
            arguments: ["@security.token_storage"]
    

    Your listener :

    private $current_user;
    
    public function __construct($security_context) {
            if ($security_context->getToken() != null) {
                $this->current_user = $security_context->getToken()->getUser();
            }
        } 
    

    Now you can do

    $entity= $args->getEntity(); // get your Article
    
    if (!$entity instanceof Article) {
            return;
    }
    
    $entity->setAuthor($this->current_user);
    $entity->setUpdatedBy($this->current_user);