我使用sonata-admin包。我与PageEntity中的用户(FOSUserBundle)有关系。我想保存创建或更改页面的当前用户。
我的猜测是在admin类的postUpdate和postPersist方法中获取user对象,并在setUser方法中传输此对象。
但是如何实现这一点呢?
在我看到的谷歌群组上
public function setSecurityContext($securityContext) {
$this->securityContext = $securityContext;
}
public function getSecurityContext() {
return $this->securityContext;
}
public function prePersist($article) {
$user = $this->getSecurityContext()->getToken()->getUser();
$appunto->setOperatore($user->getUsername());
}但这不管用
发布于 2014-02-27 21:50:56
在admin类中,您可以获得当前登录的用户,如下所示:
$this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser()基于反馈的编辑
你要这样做吗?因为这应该行得通。
/**
* {@inheritdoc}
*/
public function prePersist($object)
{
$user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
$object->setUser($user);
}
/**
* {@inheritdoc}
*/
public function preUpdate($object)
{
$user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
$object->setUser($user);
}发布于 2016-04-12 17:54:43
从symfony 2.8开始,您应该使用security.token_storage而不是security.context来检索用户。使用构造函数注入在您的管理中获取它:
public function __construct(
$code,
$class,
$baseControllerName,
TokenStorageInterface $tokenStorage
) {
parent::__construct($code, $class, $baseControllerName);
$this->tokenStorage = $tokenStorage;
}admin.yml:
arguments:
- ~
- Your\Entity
- ~
- '@security.token_storage'然后使用$this->tokenStorage->getToken()->getUser()获取当前用户。
发布于 2021-12-09 08:24:46
我在symfony的5.3.10版本和sonata的4.2版本上处理了这个问题。来自greg0ire的答案真的很有帮助,也来自symfony docs的this info,这是我的方法:
在我的例子中,我试图根据用户的属性设置一个自定义查询。
// ...
use Symfony\Component\Security\Core\Security;
final class YourClassAdmin extends from AbstractAdmin {
// ...
private $security;
public function __construct($code, $class, $baseControllerName, Security $security)
{
parent::__construct($code, $class, $baseControllerName);
// Avoid calling getUser() in the constructor: auth may not
// be complete yet. Instead, store the entire Security object.
$this->security = $security;
}
// customize the query used to generate the list
protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
{
$query = parent::configureQuery($query);
$rootAlias = current($query->getRootAliases());
// ..
$user = $this->security->getUser();
// ...
return $query;
}
}https://stackoverflow.com/questions/22069541
复制相似问题