假设我有两个实体类:'AppBundle'Entity'User
——用户提供者'AppBundle'Entity'Article
——简单文章。
Article
类还具有以下属性:author
-在用户上指示创建该特定实体的用户updatedBy
-指示用户最近更新了特定文章的内容。
如何将当前记录的用户对象传递给Article
实体,以在Symfony 3.0.1上的EasyAdminBundle生成的后端author
和/或updatedBy
属性上设置特定值?
如果您在控制器中,只需执行
$article->setAuthor($this->getUser());
$article->setUpdatedBy($this->getUser());
或
如果你想这是自动
您需要在Doctrine事件上声明一个监听器。在您的情况下,我想在preUpdate中包括当前用户。
这里有一个非常好的文档http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
我在这里编辑以回答您的意见
不要担心,当您将侦听器声明为Service 时,您可以注入用户实体
例如:
services:
your_listener:
class: App'AppBundle'Your_Listener
arguments: ["@security.token_storage"]
你的听众:
private $current_user;
public function __construct($security_context) {
if ($security_context->getToken() != null) {
$this->current_user = $security_context->getToken()->getUser();
}
}
现在你可以做了
$entity= $args->getEntity(); // get your Article
if (!$entity instanceof Article) {
return;
}
$entity->setAuthor($this->current_user);
$entity->setUpdatedBy($this->current_user);
如果您与作者实体有关系
$em = $this->getDoctrine()->getManager();
$user = new User();
$user->setAuthor($this->getUser());
$em->persist($user);
$em->flush();
控制器上,但这是个坏主意。使用命令或其他设计模式。