4

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?

CookieMonster
  • 73
  • 1
  • 9

1 Answers1

6

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);
}
cezar
  • 11,616
  • 6
  • 48
  • 84
Fatih Kahveci
  • 430
  • 4
  • 14
  • I have various entities, is there a way I can create a controller and add the controller in the CarAdmin.php? This way I can do all the user stuff in the controller and return what I need. – CookieMonster May 04 '17 at 14:19
  • @CookieMonster What you could do, is create a service which can populate such fields. Then have a interface which your entities implement. Add the service to your admin service and call the method in your service. – Neodork May 04 '17 at 16:25
  • 4
    Good answer! However using Symfony 4 it didn't work for me. I could get the user though by using another service: `->get('security.token_storage')` instead of `->get('security.context')`. – cezar Oct 29 '18 at 11:09
  • what could be the case if ->get('security.token_storage')->getToken() in any variant returns null? https://stackoverflow.com/questions/63297123/symfony-sonata-entityadmin-get-logged-in-user-missing-security-token – netzding Aug 07 '20 at 11:38