src/EventSubscriber/BeforeCrudActionEventSubscriber.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Question;
  4. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. class BeforeCrudActionEventSubscriber implements EventSubscriberInterface
  8. {
  9.     public function onBeforeCrudActionEvent(BeforeCrudActionEvent $event): void
  10.     {
  11.         if (!$adminContext $event->getAdminContext()) {
  12.             return;
  13.         }
  14.         if (!$crudDto $adminContext->getCrud()) {
  15.             return;
  16.         }
  17.         if ($crudDto->getEntityFqcn() !== Question::class) {
  18.             return;
  19.         }
  20.         // disable action entirely delete, detail, edit
  21.         $question $adminContext->getEntity()->getInstance();
  22.         if ($question instanceof Question && $question->getIsApproved()) {
  23.             $crudDto->getActionsConfig()->disableActions([Action::DELETE]);
  24.         }
  25.         // This gives you the "configuration for all the actions".
  26.         // Calling ->getActions() returns the array of actual actions that will be
  27.         // enabled for the current page... so then we can modify the one for "delete"
  28.         $actions $crudDto->getActionsConfig()->getActions();
  29.         if (!$deleteAction $actions[Action::DELETE] ?? null) {
  30.             return;
  31.         }
  32.         $deleteAction->setDisplayCallable(function(Question $question) {
  33.             return !$question->getIsApproved();
  34.         });
  35.     }
  36.     public static function getSubscribedEvents(): array
  37.     {
  38.         return [
  39.             BeforeCrudActionEvent::class => 'onBeforeCrudActionEvent',
  40.         ];
  41.     }
  42. }