PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 18, 2022

[FIXED] Get User in a Doctrine EventListener

 January 18, 2022     symfony     No comments   

Issue

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


Solution

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


Answered By - malcolm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing