14 July 2006

CFC's - not all that object oriented

I had this cracking idea to store repopulate data in CF flash forms using a cfc and storing it in the session scope, then using a remoting function to broadcast this data so the form fields could data bind to remote service. Didn't quite work.

My cfc basically looked like this:

<cfcomponent>

<cfset this.formData = StructNew() />

<cffunction name="getValues" returntype="remote">
<cfreturn this.formData />
</cffunction>

</cfcomponent>

I instantiated the above cfc in the onSessionStart function:

Session.objFormData = CreateObject("component","formData")

I then used the onRequestStart function to populate the Session based object (as per the previous post):

<cfloop list="#form.fieldnames#" index="item">
<cfset Session.objFormData.formData[item] = Evaluate(item) />
</cfloop>

This works fine and removes the need for an "action" page - just simply copy the form into the session until you need it (a bit wasteful, yes, but really quick code if you're in a hurry!)

You'd think the value returned by "this.formData" would be the data stored in the session instance. Not so... all that was returned was an empty structure! This was essentially the uninstantiated cfc with no data. Doing a cfdump of the session showed that the object and data were still in the session scope, but "this" did not return the values of the object in the session.

Copying form scope into session scope CFMX 7

I've just noticed a weird behaviour with the form scope in CFMX 7. I was trying to copy all the data in the form to a session variable e.g.

Session.formData = StructNew()
Session.formData = form

Do a <cfdump var="#session#"> immediately after that line and you see the form structure inside the session structure. However, I noticed that when I redirect onto another page without form scope, the Session.formData structure was empty - it didn't persist, even though it was copied to the Session scope!?

What must be happening is that a reference to the form scope is copied into the Session NOT the form data. When you move to another page where the form scope does not exist, then the data is not in the Session.

You must loop though form.fieldnames and set the data explicitly, like so:
<cfloop list="#form.fieldnames#" index="item">
<cfset Session.formData[item] = Evaluate(item) />
</cfloop>


I should try and remember to start posting more!