Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 856 Vote(s) - 3.53 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get User in a Doctrine EventListener

#1
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
Reply

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

#3
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();
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through