php - 教义生命周期回调不适用于 EasyAdminBundle
问题描述
我正在使用带有 EasyAdminBundle 的 Symfony 4 来创建一个简单的管理界面。我在尝试自动设置createdAt
和updatedAt
列的值时遇到了一些问题。在 EasyAdmin 中创建/更新实体时,不会调用配置的 Doctrine 生命周期回调。例如,这是一个使用 EasyAdmin 管理的简单实体,请注意生命周期回调挂钩:
<?php
namespace App\Entity;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
* @ORM\HasLifecycleCallbacks
*/
class Product
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
// Additional column configuration removed for brevity
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
// Additional getters/setters removed for brevity
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(?\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* @ORM\PrePersist
*/
public function onPrePersist(): void
{
$this->createdAt = new \DateTime();
}
/**
* @ORM\PreUpdate
*/
public function onPreUpdate(): void
{
$this->updatedAt = new \DateTime();
}
}
当我在 EasyAdmin 中创建新产品时,onPrePersist()
不会调用,当我使用 EasyAdmin 编辑现有产品时,onPreUpdate()
不会调用。
如果我以“传统”方式创建新产品,生命周期回调将完全按预期工作。例如:
<?php
$product = new Product();
$product->setTitle('Test Product');
$product->setDescription('Test description');
// Doctrine lifecycle callbacks work as expected
$this->getDoctrine()->getManager()->persist($product);
EasyAdminBundle 是否绕过了 Doctrine 生命周期回调?如果是这样,为什么?如何在 EasyAdminBundle 管理的 Doctrine 实体中使用 Doctrine 生命周期回调?
我知道有文档可以做类似的事情AdminController
:
https ://symfony.com/doc/master/bundles/EasyAdminBundle/book/complex-dynamic-backends.html#update-some-properties-for-all-entities
但是,当我们已经有 Doctrine 生命周期回调时,为什么我需要这样做。我使用AdminController
和扩展各种方法的另一个问题,persistEntity()
也AdminController
从未被调用过。
我错过了什么?
任何帮助将不胜感激!干杯!
解决方案
推荐阅读
- ios - 如何将委托和数据源链接到一个 ViewController 中的多个表视图?
- python - 未找到“pip”和“python”命令,但 python3 和 pip3 工作正常
- c# - 如何动态改变标签的颜色?赛马林
- r - R Studio/AWS 内存要求
- google-apps-script - GAS 函数的输出不是单个单元格值,而是整列值
- javascript - 在 Javascript 函数中访问嵌套数组
- python - 如何为我的转化创建函数
- python - 将 dask 数据帧保存到 csv 时如何更正错误?
- node.js - 在 Angular、Node.js、NestJS 和 Firebase 中开发应用程序
- c++ - 关于类模板的构造函数重载