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);
}
}
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:
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 }
private $ts;
public function __construct($ts)
{
$this->ts = $ts;
}
$user = $this->ts->getToken()->getUser();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.