Sending email in LifeCycle method

Viewed 31

I'm having troubles sending an email in a PrePersist method.

I tried to add call the interface inside the method

/**
 * @ORM\PrePersist
 */
public function sendPersistNotification(\Symfony\Component\Mailer\MailerInterface $mailer): void {

    $email = (new \Symfony\Bridge\Twig\Mime\TemplatedEmail())
            ->from(new \Symfony\Component\Mime\Address('noreply@email.fr', 'Bot'))
            ->to($this->getEmail())
            ->subject('Object')
            ->htmlTemplate('email/new_user.html.twig')
    ;
        
    $mailer->send($email);
}

But the argument must be of type Doctrine\ORM\Event\LifecycleEventArgs . I get the following error message :

App\Entity\User::sendPersistNotification(): Argument #1 ($mailer) must be of type Symfony\Component\Mailer\MailerInterface, Doctrine\ORM\Event\LifecycleEventArgs given, called in /Users/randyarnold/Desktop/Dev/bnk-studio_back/vendor/doctrine/orm/lib/Doctrine/ORM/Event/ListenersInvoker.php on line 83

I also tried adding the MailerInterface in the constructor of the entity, like so :

private MailerInterface $mailer;
    
public function __construct(MailerInterface $mailer) {
    $this->mailer = $mailer;
}
    
/**
 * @ORM\PrePersist
 */
public function sendPersistNotification(): void {

    $email = (new \Symfony\Bridge\Twig\Mime\TemplatedEmail())
            ->from(new \Symfony\Component\Mime\Address('noreply@email.fr', 'Bot'))
            ->to($this->getEmail())
            ->subject('Object')
            ->htmlTemplate('email/new_user.html.twig')
    ;
        
    $this->mailer->send($email);
}

But apparently I have to add the argument to the constructor :

Too few arguments to function App\Entity\User::__construct(), 0 passed in /Users/randyarnold/Desktop/Dev/bnk-studio_back/vendor/easycorp/easyadmin-bundle/src/Controller/AbstractCrudController.php on line 503 and exactly 1 expected

What am I missing here ?

0 Answers
Related