Saving Form Variables as Session Variables the Wrong Way
A student approached me the other day. She were gathering search criteria in a form and wanted to save the criteria to a session variable. But when she moved from page to page, her session variable lost its values.
<cfset session.saveformvars = structnew()>
<cfset session.saveformvars = form>
</cfif>
The issue is with the the variable scoping that takes place on a form structure. Forms have a local "non-persistent" variable scope (they are only specific to that page, or the page called from the form and don't hang around).
Session variables are by nature persistent, or can exist beyond a single page, lasting for the user's session length.
When the entire form structure was saved as a session variable structure as above, that session structure received the same scoping as the form structure.
So...
<!--- makes session.saveformvars now a local scoped variable and not a session scoped variable --->
Since this student wanted to only save those form fields that were had been completed and do some data tweaking on the information, I had her rewrite the snipped of code to loop through the form, pick out the variables to keep, then save those to the session variable.
<cfloop collection="#form#" item='key'>
<!--- pick out null fields, and son't save the submit button or the "FieldNames" key from the form struct --->
<cfif form[key] neq '' and form[key] gt 0 and key neq 'fieldnames' and key neq 'submit'>
<cfset "session.plansearch.#key#" = form[key]>
</cfif>
</cfloop>
Now this student had her trimmed form list saved as a structure in the format she wanted.
