Can someone give me an Idea, how to make an event that is triggered onDelete(remove) in Symfony4

93 Views Asked by At

I'd like to make an event that is triggered on delete.

When someone deletes an article I take the user email from the article and send an email with information which article is deleted and when.

I work with the Symfony 4 framework.

I have no idea how to start?

I have in Article controller for CRUD.

1

There are 1 best solutions below

0
On BEST ANSWER

My solution for this problem that works.

<?php


namespace App\EventListener;


use App\Entity\Article;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Twig\Environment;

class ArticleDeleteListener implements EventSubscriber
{
    private $mailer;
    private $twig;

    public function __construct(\Swift_Mailer $mailer, Environment $twig)
    {
        $this->twig = $twig;
        $this->mailer = $mailer;
    }

    public function getSubscribedEvents()
    {
        return [
            Events::preRemove,
        ];
    }

    public function preRemove(LifecycleEventArgs $args)
    {
        $article = $args->getEntity();

        if (!$article instanceof Article) {
            return;
        }

        $emailAddress = $article->getAuthor()->getEmail();
        $email = (new \Swift_Message())
            ->setFrom('[email protected]')
            ->setTo($emailAddress)
            ->setBody(
                $this->twig->render('layouts/article/onDeleteEmail.html.twig', [
                        'article' => $article,
                        'author' => $article->getAuthor(),]
                )
            );
        $this->mailer->send($email);
    }
}

Services.yaml

App\EventListener\ArticleDeleteListener:
        tags:
            - { name: 'doctrine.event_listener', event: 'preRemove' }