Coldfusion Redirect & Location with Session data

Let's say you have a form that handles products.
If someone shows up to the form without an ?id=##, you're sure they must mean to create one. If there is an id, they mean to update. In the end though, all the user cares about is the "Save" button. "Create" and "Update" are your job to worry about. So you've created a wonderful cfc that does the work on the form, sets a message about the result in the session, and want to display it.

You can't simply reload the page after creating the product, your page needs the newly created product's id in the url, and that breaks the back button. So, you try cflocation, and figure on outputting the message there. No dice. The message you put in the session is gone when you get there. That is because when you do cflocation, the cookie that carries session information to the client is never sent along to them. Cookies have to be sent back to the user, and cflocation is a server side redirect. So instead, you use this trick:

  1. <cfset variables.url = cgi.script_filename & '?id=' & product.id>
  2. <cfheader statuscode="301" statustext="Moved permanently">
  3. <cfheader name="Location" value="#variables.url#">
  4. <cfabort>
  5. <coldfusion>
  6.  
  7. Note that you <em>must</em> include the cfabort in your code. While the user is correctly redirected using the cfheader, the page it sits on finishes processing!
Tags: 

Comments

There's now a cflocation tag support for statuscode arguments. Just pop that to 301 or 302 and you're solid.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.