繁体   English   中英

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

[英]Get the current logged in user in any sonata admin class

我希望使用将当前用户设置为消息发送者的命令来获取 MessageAdmin 类中的当前登录用户

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

但它不起作用,我收到一条错误消息

[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)"} []

这是我的 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);
}
}

我很惊讶这种常见的东西没有很好的记录。

自 Sonata Admin v4 以来,其他类无法访问配置池的容器。 它仅用于获取可用的管理员,不能再用于其他目的。

要获取登录用户,您需要以其他方式访问令牌存储。

你可以做的是:

  1. 在服务 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. 在 Admin 类中,存储令牌存储:
    private $ts;
    
    public function __construct($ts)
    {
        $this->ts = $ts;
    }
  1. 每当您需要时,您都可以访问用户:
    $user = $this->ts->getToken()->getUser();

暂无
暂无

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

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