src/EventSubscriber/HideActionEasyAdminSubscriber.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Company;
  4. use App\Entity\Station;
  5. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class HideActionEasyAdminSubscriber implements EventSubscriberInterface
  9. {
  10.     public const TARGET_CLASS = [Company::class, Station::class];
  11.     public function onBeforeCrudActionEvent(BeforeCrudActionEvent $event): void
  12.     {
  13.         if (!$adminContext $event->getAdminContext()) {
  14.             return;
  15.         }
  16.         if (!$crudDto $adminContext->getCrud()) {
  17.             return;
  18.         }
  19.         if (!in_array($crudDto->getEntityFqcn(), self::TARGET_CLASS)) {
  20.             return;
  21.         }
  22.         $targetInstance $adminContext->getEntity()->getInstance();
  23.         // disable action entirely delete on pages : detail, edit
  24.         if (null !== $targetInstance and !$targetInstance?->isAllowedDeleteAction()) {
  25.             $crudDto->getActionsConfig()->disableActions([Action::DELETE]);
  26.         }
  27.         $actions $crudDto->getActionsConfig()->getActions();
  28.         // If there is no delete action for some reason...
  29.         if (!$deleteAction $actions[Action::DELETE] ?? null) {
  30.             return;
  31.         }
  32.         // disable action entirely delete on page : index
  33.         $deleteAction->setDisplayCallable(function (object $entity) {
  34.             return $entity->isAllowedDeleteAction();
  35.         });
  36.     }
  37.     public static function getSubscribedEvents(): array
  38.     {
  39.         return [
  40.             // This event is dispatched before every single CRUD action.
  41.             BeforeCrudActionEvent::class => 'onBeforeCrudActionEvent',
  42.         ];
  43.     }
  44. }