我有一个 Post
实体和 PostType
。
帖子实体有字段 $requireModeration
这意味着必须有人检查并批准该帖子才能发布。
当我编辑帖子时,我想比较旧帖子值(value)和新帖子值(value)。如果值发生变化,我还想将 requireModeration
标志更改为 true。
我可以通过表单事件来完成吗?
像这样:
public function postSubmit(FormEvent $event)
{
$newPost = $event->getData();
$newContent = $post->getContent(); // return new contant of post
$oldPost = ... // here I want to get old post
$oldContent = $oldPost->getContent();
if($newContent != $oldContent) {
// ...
}
}
但不幸的是,我只能通过 FormEvent 对象获取刚刚发送的新数据。
最佳答案
你应该使用 Doctrine 的生命周期事件和 UnitOfWork
而不是 Form 事件(我假设你在你的项目中使用 Doctrine
)。
将 preUpdate
监听器添加到您的 Post
实体并执行以下操作:
$uow = $em->getUnitOfWork();
$changeset = $uow->getEntityChangeSet($entity);
在 $changeset
变量中,您将拥有在当前请求期间在 $entity
中更改的字段列表及其旧值和新值。
关于php - Symfony - 表单事件 - 获取新旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37022467/