undefined method named "render" in Listener Symfony

Good morning,

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 AppEvents;

use ApiPlatformCoreEventListenerEventPriorities;
use AppEntityUser;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelEventViewEvent;
use SymfonyComponentHttpKernelKernelEvents;

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.

Thx !

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *