Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get User in a Doctrine EventListener

Tags:

symfony

when I register a new Plasmid Entity, I want give him an automatic name (like: p0001, p0002, p0003), to do this, I need to select in the database the last Plasmid entity for a specific User, get its autoName, and use this previous name to define the new one.

But, when I inject the token_storage in my listener, the token is null... In the controller, I can have the user, it's work.

The service.yml

    app.event_listener.plasmid:
    class: AppBundle\EventListener\PlasmidListener
    arguments: ["@security.token_storage"]
    tags:
        - { name: doctrine.event_listener, event: prePersist }

And, the PlasmidListener

class PlasmidListener
{
private $user;

public function __construct(TokenStorage $tokenStorage)
{
    $this->user = $tokenStorage->getToken()->getUser();
}

public function prePersist(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    // If the entity is not a Plasmid, return
    if (!$entity instanceof Plasmid) {
        return;
    }

    // Else, we have a Plasmid, get the entity manager
    $em = $args->getEntityManager();

    // Get the last plasmid Name
    $lastPlasmid = $em->getRepository('AppBundle:Plasmid')->findLastPlasmid($this->user);

    // Do something with the last plasmid in the database
}
}

If someone know why I can get the actual user in the Doctrine Listener ?

Thanks

like image 982
mpiot Avatar asked Oct 17 '16 13:10

mpiot


2 Answers

I think that you should store pointer to tokenStorage class in your service instead of user object:

class PlasmidListener
 {
    private $tokenStorage;

    public function __construct(TokenStorage $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        //...
    }
}
like image 180
malcolm Avatar answered Nov 15 '22 21:11

malcolm


To avoid error in Symfony4 and above, use TokenStorageInterface instead of TokenStorage

For example

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

And in your constructor :

public function __construct(TokenStorageInterface $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
}

To get the user and its details in prePersist :

$user = $this->tokenStorage->getToken()->getUser();
like image 31
Bhola Singh Avatar answered Nov 15 '22 22:11

Bhola Singh