Symfony 2: 302 http status and exception

I have this problem, I don't know how to solve it.

I am using a controller action method, I am doing a test, and if that test is positive, I want to redirect.

public function contentAction() {
    $response = $this->render('MyBundle:Default:content.html.twig');

    if(!is_object($agent)) {
       $response = $this->redirect($this->get('router')->generate('new_route', 
                    array('error_message_key' => $error_message)));

    return $response;    


When redirecting, I have an exception

Error when rendering "http://alternativefirst/app_dev.php/accueil/" (Status code is 302)


Can't I do this redirect? why could it be?

IMPORTANT BROADCAST: I am calling this controller action in my branch template with

{{ render(controller('MyBundle:Default:content')) }}



source to share

2 answers

Try a helper function generateUrl()

for your redirect:

$response = $this->redirect($this->generateUrl('new_route', array(
    'error_message_key' => $error_message,


Your actual problem is caused by trying to send a redirect to a Twig template .



The solution is to move the rendering and redirection logic into a controller action /accueil

, because as you are now, you are trying to redirect the PHP header to an already loaded page, perhaps. Alternatively, you can do a javascript redirect window.location

inside the content.html template you are trying to load by doing something like this:

{% if agent is not defined %}<script>window.location = '{{ path('new_route') }}';</script>{% endif %}


You will need to pass an agent object (or whatever you want to use as a trigger), but that seems like a pretty crude solution to me, which is probably an architectural issue in your code.



All Articles