Search code examples
symfony5easyadmin

EasyAdmin - DELETE action, delete also a physical file


I am using Symfony + EasyAdmin. I have an entity called "Images" that represents some images along with some details.

Right now, by default, when someone removes an image, EasyAdmin removes it just from DB, which makes sense.

I would like to be able to remove also the physical file, not just the record without creating a custom action.

The question is: Do you know If is there any method that "catches" the DELETE action so I could use it to remove the physical file?

Like: ImagesCrudController.php public function deletedRow($id){//then I can use the $id here to remove the physical image}

Thank you


Solution

  • Here is the solution if anyone needs it. I used an Event Subscriber for AfterEntityDeletedEvent

    Thank you Flash for the instructions.

    <?php
    namespace App\EventSubscriber;
    
    use App\Entity\Images;
    use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class EasyAdminSubscriber implements EventSubscriberInterface
    {
        /**
         * @var ParameterBagInterface
         */
        private $parameterBag;
    
        public function __construct(ParameterBagInterface $parameterBag)
        {
            $this->parameterBag = $parameterBag;
        }
    
        public static function getSubscribedEvents()
        {
            return [
                AfterEntityDeletedEvent::class => ["deletePhysicalImage"],
            ];
        }
    
        public function deletePhysicalImage(AfterEntityDeletedEvent $event)
        {
            $entity = $event->getEntityInstance();
            if (!($entity instanceof Images)) {
                return;
            }
            $imgpath =
                $this->parameterBag->get("kernel.project_dir") .
                "/public_html/" .
                $entity->getPath();
            if (file_exists($imgpath)) {
                unlink($imgpath);
            }
        }
    }