The app: A JavaScript function listens for changes on form elements (input & select), and posts the data to a CFC method that assigns them to a Session struct. The struct is returned, making the form data usable for the life of the session. The app is adapted from code at Raymond Camden's Using a server, or session storage, to persist form values.
Issue: The original CFC code is written in CFScript. Because we're on ColdFusion 8, I get an error when the method is called. So, I translated the method into ColdFusion tag syntax and stopped getting that error. In Chrome's Dev Tools, I can see data passing to the CFC via the JSON object each time I enter something into a form element. So I know the JavaScript function is working. And even though I'm not getting any return errors, there are some behaviors that lead me to believe that my translation is incorrect. E.g., the dump of the session struct only displays the last input element entered, rather than all of them (as is the case in Ray's demo).
Here's the original CFScript version and then my tag translation. In addition to any comments about where my translation is wrong, I'd love to have an explanation of this line, <cfset s.name = [s[name]] />
, particularly the [s[name]]
construct, since I'm not able to articulate what's happening there. Thanks.
script syntax:
component {
remote void function preserveSession(string awardData) {
if(!isJSON(arguments.awardData)) return;
arguments.awardData = deserializeJSON(arguments.awardData);
//convert the array into a name based struct
var s = {};
for(var i=1; i<=arrayLen(arguments.awardData); i++) {
var name = arguments.awardData[i].name;
if(!structKeyExists(s, name)) {
s[name] = arguments.awardData[i].value;
} else {
//convert into an array
if(!isArray(s[name])) {
s[name] = [s[name]];
}
arrayAppend(s[name], arguments.awardData[i].value);
}
}
session.awardFormData = s;
}
}
tag syntax:
<cfcomponent>
<cffunction name="preserveSession" access="remote" returntype="void" output="no">
<cfargument name="awardData" type="string" />
<cfset var s = {} />
<cfif NOT isJSON(arguments.awardData)>
<cfreturn />
</cfif>
<cfset arguments.awardData = #deserializeJSON(arguments.awardData)# />
<cfloop index="i" from="1" to="#arrayLen(arguments.awardData)#">
<cfset name = #arguments.awardData[i].name# />
<cfif NOT structKeyExists(s, name)>
<cfset s.name = #arguments.awardData[i].value# />
<cfelse>
<cfif NOT isArray(s.name) >
<cfset s.name = [s[name]] />
</cfif>
<cfset arrayAppend(s.name, arguments.awardData[i].value) />
</cfif>
</cfloop>
<cfset session.awardFormData = s />
<cfreturn />
</cffunction>
</cfcomponent>