问题
[SETTINGS]
- Symfony 3.4
- Logged user (FosUserBundle)
Projet
Entity (below)
src/AppBundle/Entity/Projet.php
class Projet {
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="titre", type="string", length=50)
*/
private $titre;
/**
* @var \DateTime
*
* @ORM\Column(name="creation", type="datetime")
*/
private $creation;
/**
* @var \DateTime
*
* @ORM\Column(name="modification", type="datetime")
*/
private $modification;
/**
* @var
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="projet")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function updatedTimestamps() {
$this->setModification(new \DateTime());
if($this->getCreation() == null) {
$this->setCreation(new \DateTime());
$this->setSupprime(false);
}
}
}
[PROBLEM]
As is, I'm setting creation
and modification
on PrePersit
/PreUpdate
.
I would like to also set the id of the current logged user, how can I do it?
回答1:
To do this, you need to have access to the security.token_storage
service and call $tokenStorage->getToken()->getUser()
to retrieve the current user. Since it is not really recommended to inject a service into an entity, you should create an entity listener as described in this section of the doctrine documentation.
Then, by declaring your entity listener as a service and adding the security.token_storage
to its constructor arguments like this (in your services.yml
):
listener.projet:
class: AppBundle\Listener\ProjetListener
arguments: [ "@security.token_storage" ]
tags:
- { name: doctrine.orm.entity_listener, lazy: true }
You would be able to access the currently logged in user inside your prePersist
and preUpdate
methods.
Edit: Here is how your listener should look like
AppBundle/Listener/ProjetListener.php
namespace AppBundle\Listener;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use AppBundle\Entity\Projet;
class ProjetListener
{
private $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function prePersist(Projet $projet, LifecycleEventArgs $args)
{
// Assigning the current user to the Projet instance being persisted
$projet->setUser($this->tokenStorage->getToken()->getUser());
/* .. other actions of prePersist .. */
}
public function preUpdate(Projet $projet, PreUpdateEventArgs $args)
{
/* .. actions of preUpdate .. */
}
}
回答2:
I think you have to do this in a subscriber, listening on prepersist and preupdate doctrine event. You will be able to get the currentn user by injecting the security.token_storage service
来源:https://stackoverflow.com/questions/48522686/prepersit-current-user