Get the current logged in user in any sonata admin class

1.2k views Asked by At

I wish to to fetch the current logged in user in the MessageAdmin class with the command to set the current user as sender of the message

$user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser()

but it's not working, I receive an error saying

[2022-07-12T15:36:28.239716+00:00] request.CRITICAL: Uncaught PHP Exception Symfony\Component\ErrorHandler\Error\UndefinedMethodError: "Attempted to call an undefined method named "getContainer" of class "Sonata\AdminBundle\Admin\Pool"." at /var/www/symfony/src/Admin/MessageAdmin.php line 75 {"exception":"[object] (Symfony\\Component\\ErrorHandler\\Error\\UndefinedMethodError(code: 0): Attempted to call an undefined method named \"getContainer\" of class \"Sonata\\AdminBundle\\Admin\\Pool\". at /var/www/symfony/src/Admin/MessageAdmin.php:75)"} []

this is my AdminClass

<?php
namespace App\Admin;

final class MessageAdmin extends AbstractAdmin
{

protected function prePersist(object $message): void 
{
    $user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
    $date = new \DateTime();
    $message->setCreatedAt($date);
    $message->setSender($user);
}
}
1

There are 1 answers

0
Yassine Ben Hamadi On

I am surprised that something this common is not well documented.

The container of the configuration pool is becoming inaccessible from other classes since Sonata Admin v4. It's being used only to get the available Admins, and can't be used for other purposes anymore.

To get the logged in user, you need to access the token storage other way.

What you can do is:

  1. In the services yaml file, add the token storage in arguments:
admin.message:
    class: App\Admin\MessageAdmin
    arguments:
        - '@security.token_storage'
    tags:
        - { name: sonata.admin, model_class: App\Entity\Message, controller: ~, manager_type: orm, group: admin, label: Message }
  1. In the Admin class, store the token storage:
    private $ts;
    
    public function __construct($ts)
    {
        $this->ts = $ts;
    }
  1. Whenever you need, you can access the user:
    $user = $this->ts->getToken()->getUser();