簡體   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