mlwacosmos
mlwacosmos

Reputation: 4541

Symfony 2 : 302 http status and exception

I have this problem I dont know how to resolve.

I am in a controller action method , I make a test and if this 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;    
}

With the redirection, I have an exception

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

I cannot make this redirection ? why could it be ?

IMPORTANT THING : I call this controller action in a twig template with

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

Upvotes: 4

Views: 8097

Answers (2)

Leo Bedrosian
Leo Bedrosian

Reputation: 3789

The solution would be to move the rendering and redirection logic into the /accueil controller action because as it is right now, you're attempting to perform a PHP header redirect on a page that has already been loaded, which isn't possible. Alternatively, you could perform a javascript window.location redirect inside the content.html template you're trying to load by doing something like this:

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

You would have to pass along the agent object (or anything you want to use as the trigger), but that strikes me as a rather crude solution to what is likely an architectural problem in your code.

Upvotes: 1

sjagr
sjagr

Reputation: 16502

Try the generateUrl() helper function 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 within a Twig template.

Upvotes: 1

Related Questions