-2

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.

Bananaapple
  • 2,984
  • 2
  • 25
  • 38
  • 4
    What did you try so far? https://symfony.com/doc/current/event_dispatcher.html is an excellent starting point for creating your own Events in Symfony. – Jeroen Oct 21 '19 at 13:56
  • I now how to create an Event but how to send to a event listener that the article is deleted. Because I made an listener when creating an Article, then I take that article with getObject ("$article = $args->getObject();") . But I don't have an idea how to trigger the Listener when I delete an article. – Ivan MIhael Čergar Oct 21 '19 at 14:27
  • 1
    See https://symfony.com/doc/current/components/event_dispatcher.html for dispatching an event. If you are unable to make it work, please add some code samples to your question. – Jeroen Oct 21 '19 at 14:32
  • 1
    Don't use Doctrine event's for this, trigger your own event and create your own listener – Wouter J Oct 21 '19 at 14:43

1 Answers1

0

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('send@example.com')
            ->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' }