I have a kernel event listener setup (kernel.controller) to redirect the user if he's not logged in. The event listener is succesfully getting called, however I'm having trouble figuring out how to redirect. Here's what I got:
$cont = $event->getController('testpost'); $event->setResponse($cont);
Which gives me the error:
Fatal error: Call to undefined method Symfony\Component\HttpKernel\Event\FilterControllerEvent::setResponse()
If you wanna redirect from FilterControllerEvent
you should use this one:
public function onKernelController(FilterControllerEvent $event) { // do something $event->setController(function() use ($redirectUrl) { return new RedirectResponse($redirectUrl); }); }
You can't set a response to a FilterControllerEvent
object. You need to listen for the kernel.request
event because its GetResponseEvent
object has the setResponse()
method:
$route = 'route_name'; if ($route === $event->getRequest()->get('_route')) { return; } $url = $this->router->generate($route); $response = new RedirectResponse($url); $event->setResponse($response);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With