简体   繁体   English

在任何奏鸣曲管理类中获取当前登录用户

[英]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:你可以做的是:

  1. In the services yaml file, add the token storage in arguments:在服务 yaml 文件中,在参数中添加令牌存储:
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:在 Admin 类中,存储令牌存储:
    private $ts;
    
    public function __construct($ts)
    {
        $this->ts = $ts;
    }
  1. Whenever you need, you can access the user:每当您需要时,您都可以访问用户:
    $user = $this->ts->getToken()->getUser();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM