src/EventSubscriber/HideActionSubscriber.php line 12

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Question;
  4. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  7. class HideActionSubscriber implements EventSubscriberInterface
  8. {
  9.     public function onBeforeCrudActionEvent(BeforeCrudActionEvent $event)
  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 for delete, detail & edit page
  21.         $question $adminContext->getEntity()->getInstance();
  22.         if ($question instanceof Question && $question->getIsApproved()) {
  23.             $crudDto->getActionsConfig()->disableActions([Action::DELETE]);
  24.         }
  25.         // returns the array of actual actions that will be enabled
  26.         // for the current page
  27.         $actions $crudDto->getActionsConfig()->getActions();
  28.         if (!$deleteAction $actions[Action::DELETE] ?? null) {
  29.             return;
  30.         }
  31.         $deleteAction->setDisplayCallable(function (Question $question) {
  32.             return !$question->getIsApproved();
  33.         });
  34.     }
  35.     public static function getSubscribedEvents()
  36.     {
  37.         return [
  38.             BeforeCrudActionEvent::class => 'onBeforeCrudActionEvent',
  39.         ];
  40.     }
  41. }