symfony redirect vs forward

I’ve found the distinction between redirect() and forward() a little tricky to draw. It always seems to sound obvious until you need to use them. I found a nice article here http://firebird84vn.wordpress.com/category/symfony/. To quote:

The choice between a redirect or a forward is sometimes tricky. To choose the best solution, keep in mind that a forward is internal to the application and transparent to the user. As far as the user is concerned, the displayed URL is the same as the one requested. In contrast, a redirect is a message to the user’s browser, involving a new request from it and a change in the final resulting URL.

If the action is called from a submitted form with method="post", you should always do a redirect. The main advantage is that if the user refreshes the resulting page, the form will not be submitted again; in addition, the back button works as expected by displaying the form and not an alert asking the user if he wants to resubmit a POST request.

OK, so basically a submitted form should be redirected by the action (as opposed to doing a forward). In other situations where you’re calling part of your own application, just use a forward(). Maybe I’ve missed something, but this seems pretty straightforward (pun unintended) after all.

7 thoughts on “symfony redirect vs forward

  1. Pingback: rpsblog.com » A week of symfony #71 (5->11 may 2008)

  2. So redirect after a post method. Otherwise a forward generally seems the way to go.
    I’ve certainly found the forward404 etc methods very useful too.

  3. I don’t think it’s that straight forward when you involve Ajax call. Using redirect means Symfony is unable to detect if a request is initiated via Ajax or not.

    So in addition to that rule of thumb, if it is a post, but an Ajax call (use $request->isXmlHttpRequest() for detection), use forward instead of redirect.

    Use forward as much as you can and only redirect if you really really have to.

    I think that’s better rules, but correct me if I’m wrong.

  4. well heres one normal case where you would need to use a forward i think…
    if you are handling form submission in another action, then the handleError for that action, will need to forward back to original form(action) so the form has orig request variables to display the error messages i believe. or you could submit the form to itself (i choose against this recently on 1 form as there are a few buttons to submit, and it was easier to just set validation yml files for each action [versus do custom validation with validateActioname() and check which button was pressed]).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>