PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 6, 2022

[FIXED] Symfony2 redirect for event listener?

 February 06, 2022     php, symfony     No comments   

Issue

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() 

Solution

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


Answered By - Elnur Abdurrakhimov
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing