You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EasyAdmin增改实体:adjustings为空置indicationPostAdjusting为null

实现逻辑说明

你拿到的adjustings是Doctrine的Collection类型对象,不需要直接读取内部的elements数组判断是否为空,直接调用集合自带的isEmpty()方法就能准确判断关联内容是否存在。
另外注意:你当前只监听了BeforeEntityPersistedEvent,这个事件仅在新建实体时触发,编辑更新实体时触发的是BeforeEntityUpdatedEvent,需要同时监听两个事件才能覆盖新建、编辑两个操作场景。


方案1:事件订阅器实现(全局生效)

修改原有事件订阅器代码如下:

<?php

namespace App\EventSubscriber;

use App\Entity\Indication;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class EasyAdminSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            BeforeEntityPersistedEvent::class => ['resetPostAdjustingWhenNoAdjustings'],
            BeforeEntityUpdatedEvent::class => ['resetPostAdjustingWhenNoAdjustings'],
        ];
    }

    public function resetPostAdjustingWhenNoAdjustings($event)
    {
        $entity = $event->getEntityInstance();
        if (!($entity instanceof Indication)) {
            return;
        }

        if ($entity->getAdjustings()->isEmpty()) {
            $entity->setIndicationPostAdjusting(null);
        }
    }
}

方案2:CRUD控制器内直接实现(仅当前控制器生效)

如果不需要全局处理,也可以直接在IndicationCrudController中重写EasyAdmin提供的持久化、更新方法,不需要单独创建事件订阅类:

// 在IndicationCrudController类中添加以下两个方法
public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
    if ($entityInstance instanceof Indication && $entityInstance->getAdjustings()->isEmpty()) {
        $entityInstance->setIndicationPostAdjusting(null);
    }

    parent::persistEntity($entityManager, $entityInstance);
}

public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
    if ($entityInstance instanceof Indication && $entityInstance->getAdjustings()->isEmpty()) {
        $entityInstance->setIndicationPostAdjusting(null);
    }

    parent::updateEntity($entityManager, $entityInstance);
}

注意:两种方案都不需要手动调用$entityManager->persist()或者$entityManager->flush(),EasyAdmin会自动完成后续的实体持久化操作。


内容的提问来源于stack exchange,提问作者Noé Femeland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 07:48:27