Reputation: 123
I'm working on sending mail (Swift mailer) from a listener on Symfony, only I have an error when using renderView (try with render too)...
Undefined method 'renderView'.
Here my listener :
<?php
namespace App\Events;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class UserSubscriber implements EventSubscriberInterface {
private $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendMail', EventPriorities::POST_VALIDATE],
];
}
public function sendMail(ViewEvent $event): void
{
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$user instanceof User || Request::METHOD_POST !== $method) {
return;
}
$message = (new \Swift_Message('A new book has been added'))
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody(
$this->renderView(
// templates/emails/registration.html.twig
'emails/registration.html.twig',
['userPseudo' => $user->getPseudo()]
),
'text/html'
);
$this->mailer->send($message);
}
}
I understand that the templating service is not available in the listener, but I don't understand how to inject it.
Upvotes: 0
Views: 908
Reputation: 2302
Dependency Injection - read about it
You need pass Twig to this class (just like you did with Swift Mailer)
at the beginning :
use Twig\Environment;
class UserSubscriber implements EventSubscriberInterface {
private $mailer;
private $twig;
public function __construct(\Swift_Mailer $mailer, Environment $environment)
{
$this->mailer = $mailer;
$this->twig = $environment;
}
and in code (in methods) you use it this way :
$this->twig->render()
NOT
$this->renderView()
Upvotes: 1