This tip is a quick one for newbies. The Symfony book has some great tips as to when you would want to use a Symfony forward, vs a Symfony redirect. This quick post will show you the difference between the two and give you some guidelines to know when to use redirect or forward.

So what’s the main difference?

Symfony Redirect: This simply does a HTTP header(”location: “)
Symfony Forward:
This is complete custom code that comes with the Symfony framework that forwards you within the Symfony application.

Use Symfony Forward if:

  • If the action needs to forward a call to another action
    This will mean you can keep all the action class’ objects in scope and still have access to them
  • You want to forward the user to an action within the application, and keep it transparent to the user.
    From a users perspective - the displayed URL stays the same.

Use a Symfony Redirect if:

  • You need to go to an external website (http://google.com for example)
  • You don’t want the user to re-submit a form (if you are doing a form POST)
    It is generally good practice to do a redirect after a POST to ensure the user does not re-submit the form.

Conditional Forwarding/redirect
Quite often you need to forward or redirect if a condition has been met. Be sure to checkout the other Symfony functions that help you do this (forwardIf(), forwardUnless(), forward404If(), forward404Unless(), redirectIf(), and redirectUnless())

What about AJAX calls?
You can check if a HTTP request is an AJAX call before deciding what to do with it by calling calling  $request->isXmlHttpRequest() in your actions class. Once you have done this you can choose what you want to do; redirect or forward.