Quick & Dirty: Carrying Form Variables on Multi=page Forms

Since HTML is a 'stateless' environment (meaning that once you go to a new page, the information on the old page isn't saved on its own merit), multi-page forms can be a pain.

You could make either a LOOONNNGGG form that bogs down the user and risks potential session timeouts. Or use a multi-page form, taking care to manage the variables from page to page.

In Coldfusion, this is very easy. And you don't have to even keep up with all the variable names from page to page.

You can either keep up with the values on previous form pages by re-establishing them in the current page form, or you san save them as session variables.

To re-establish them as form variables on your second (and subsequent form pages), add the following to your code after your

tag. (I used the generic HTML form tag here, but CFFORM should work as well)


<cfloop list="#form.fieldnames#" index="i">
<input type='hidden' name="#i#" id='#i#' value="#evaluate(i)#" />
</cfloop>

This will recreate the form variables as hidden fields in your form.

To save them as session variables, do the similar loop:


<cfloop list="#form.fieldnames#" index="i">
<cfset "session.formdata.#i#" = "#evaluate(i)#" />
</cfloop>
(Note, Assumption is you are working in CF7/8. If using earlier versions, remember to place a scope lock around your loop)

Or... You could do both to make absolutely sure you have the data for your user:


<cfloop list="#form.fieldnames#" index="i">
<input type='hidden' name="#i#" id='#i#' value="#evaluate(i)#" />
<cfset "session.formdata.#i#" = "#evaluate(i)#" />
</cfloop>

Of course, remember to add your data validation per page, so that the user doesn't get all the way to the end of the form to find an error on page 1 :).

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Michael E's Gravatar good tip, thanks Tami!

for those that might find it useful , I have something similar, creating cfparams for all the form variables in a simple loop, here:
http://www.miuaiga.com/index.cfm/2007/9/30/Easy-cf...
# Posted By Michael E | 9/29/08 8:54 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.002. Contact HHWD