Sonata bundle, how can I get current logged in user?
sonata-admin, sonata-user-bundle, symfony, symfony-sonata
Solution
You can get logged user using `$this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser()`. In your case you need to do something like this:
public function setUpdatedByAttribute($car)
{
$user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
$car->setUpdatedBy($user);
}
public function prePersist($car)
{
$this->setUpdatedByAttribute($car);
}
public function preUpdate($car)
{
$this->setUpdatedByAttribute($car);
}
Problem
Lets say I have a Car Entity. Other than typical Car properties I have updatedBy attribute In sonata I created a CRUD admin page using AppBundle\Admin\CarAdmin.php Inside the class CarAdmin I have the required methods like configureListFields, configureFormFields, etc... I'm guessing I need to add updatedBy using the method prePersist($object) but I'm facing that $this->getUser() is not available The question is, how can I get the logged in user to populate updateBy attribute?