首页 > 解决方案 > 教义生命周期回调不适用于 EasyAdminBundle

问题描述

我正在使用带有 EasyAdminBundle 的 Symfony 4 来创建一个简单的管理界面。我在尝试自动设置createdAtupdatedAt列的值时遇到了一些问题。在 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 生命周期回调?

我知道有文档可以做类似的事情AdminControllerhttps ://symfony.com/doc/master/bundles/EasyAdminBundle/book/complex-dynamic-backends.html#update-some-properties-for-all-entities

但是,当我们已经有 Doctrine 生命周期回调时,为什么我需要这样做。我使用AdminController和扩展各种方法的另一个问题,persistEntity()AdminController从未被调用过。

我错过了什么?

任何帮助将不胜感激!干杯!

标签: phpsymfonydoctrine-orm

解决方案


推荐阅读