[英]Get the current logged in user in any sonata admin class
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我希望使用将当前用户设置为消息发送者的命令来获取 MessageAdmin 类中的当前登录用户
$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这是我的 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.自 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.