Using the Flash

Using the Flash to pass data from one request to the next.

The Flash is actually a very simple concept. And no, it has nothing to do with Adobe's Flash Player.

The Flash is just a struct in the session scope with some added functionality. It is cleared at the end of the next page that the user views. This means that it's a good fit for storing messages or variables from one request to the next.

An Example of Using the Flash

The code below is commonly used in Wheels applications to store a message about an error in the Flash and then redirect to another URL, which then displays the message in its view page.

In an action that handles a form submission:

<cfset flashInsert(error="Oops! Please correct your errors and try again")>
<cfset redirectTo(action="edit")>

In the view page for the edit action:

<p class="error-message"><cfoutput>#flash("error")#</cfoutput></p>

As you can see above, you use the flashInsert() function when you want to store data in the Flash and the flash() function when you want to display the data in a view.

The key chosen above is error, but it could have been anything. Just like with a normal struct, the naming of the keys is your job.

As an example, you may choose to use one key for storing error messages and another one for storing success messages.

More Flashy Functions

Besides flash() and flashInsert() that are used to read from/insert to the Flash, there are a few other functions worth mentioning.

flashCount() is used to count how many key/value pairs there are in the Flash.

flashKeyExists() is used to check if a specific key exists. So it would make sense to make use of that function in the code listed above to avoid outputting an empty <p> tag on requests where the Flash is empty. (flash() will return an empty string when the specified key does not exist).

By the way, the name "Flash" comes from Ruby on Rails, like so many other cool things in Wheels.

^ Top
Table of Contents

Comments

Read and submit questions, clarifications, and corrections about this chapter.

There are no comments for this chapter. Be the first to comment!

Add Comment