• 8

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Symfony2 redirect for event listener?

I have a kernel event listener setup (kernel.controller) to redirect the user if hes not logged in. The event listener is succefully getting called, however im having trouble figuring out how to redirect. Here's what i got:

$cont = $event->getController('testpost');

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);
  • 95
Reply Report

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')) {

$url = $this->router->generate($route);
$response = new RedirectResponse($url);
  • 52
Reply Report
      • 1
    • Oh interesting. Im still getting the call to undefined method setResponse, is there a class/file i should be including?
      • 2
    • Have you changed the parameter type to GetResponseEvent? And do you reallly listen for kernel.request? Please double-check it.
    • Ok turns out i was on kernal.controller, so i switched it kernal.request and it redirects with error ErrorException: Catchable Fatal Error: Argument 1 passed to... must be an instance of SymfonyComponentHttpKernelEventFilterControllerEvent, instance of SymfonyComponentHttpKernelEventGetResponseEvent

More ore less clear way to redirect on 'kernel.controller' event

public function onKernelController(FilterControllerEvent $event)
    /* @var $controller \Symfony\Bundle\FrameworkBundle\Controller\Controller */
    $controller = $event->getController()[0]; // PHP 5.4 or $controller = $controller[0];

    throw new HttpException(307, null, null, array('Location' => $controller->generateUrl('homepage')));
  • 4
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions