<?php
namespace App\EventSubscriber;
use App\Entity\Company;
use App\Entity\Station;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HideActionEasyAdminSubscriber implements EventSubscriberInterface
{
public const TARGET_CLASS = [Company::class, Station::class];
public function onBeforeCrudActionEvent(BeforeCrudActionEvent $event): void
{
if (!$adminContext = $event->getAdminContext()) {
return;
}
if (!$crudDto = $adminContext->getCrud()) {
return;
}
if (!in_array($crudDto->getEntityFqcn(), self::TARGET_CLASS)) {
return;
}
$targetInstance = $adminContext->getEntity()->getInstance();
// disable action entirely delete on pages : detail, edit
if (null !== $targetInstance and !$targetInstance?->isAllowedDeleteAction()) {
$crudDto->getActionsConfig()->disableActions([Action::DELETE]);
}
$actions = $crudDto->getActionsConfig()->getActions();
// If there is no delete action for some reason...
if (!$deleteAction = $actions[Action::DELETE] ?? null) {
return;
}
// disable action entirely delete on page : index
$deleteAction->setDisplayCallable(function (object $entity) {
return $entity->isAllowedDeleteAction();
});
}
public static function getSubscribedEvents(): array
{
return [
// This event is dispatched before every single CRUD action.
BeforeCrudActionEvent::class => 'onBeforeCrudActionEvent',
];
}
}