src/EventSubscriber/ContactEventSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\Contact;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class ContactEventSubscriber implements EventSubscriberInterface
  9. {
  10.     private EntityManagerInterface $entityManager;
  11.     public function __construct(EntityManagerInterface $entityManager)
  12.     {
  13.         $this->entityManager $entityManager;
  14.     }
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             BeforeCrudActionEvent::class => ['beforeCrudActionEvent'],
  19.         ];
  20.     }
  21.     /**
  22.      * Set as "already read" the message when the user accesses the show page
  23.      * of the contact entity.
  24.      */
  25.     public function beforeCrudActionEvent(BeforeCrudActionEvent $event): void
  26.     {
  27.         $context $event->getAdminContext();
  28.         if ($context === null) {
  29.             return;
  30.         }
  31.         // Entity is null on the "new action".
  32.         $contact $context->getEntity()->getInstance();
  33.         if (!$contact instanceof Contact) {
  34.             return;
  35.         }
  36.         $contact->setAlreadyRead(true);
  37.         $this->entityManager->flush();
  38.     }
  39. }