mpiot
mpiot

Reputation: 1522

Get User in a Doctrine EventListener

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

Upvotes: 11

Views: 9561

Answers (2)

Bhola Singh
Bhola Singh

Reputation: 41

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();

Upvotes: 2

malcolm
malcolm

Reputation: 5542

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();
        //...
    }
}

Upvotes: 9

Related Questions