Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

A Weird Thing Happened To Me Today When Submitting A Form

Apparently With ColdFusion You Can't Always Rely On form.fieldnames

I've been using ColdFusion for a long, long time and today I came across something that just totally stumped me. When submitting a form, you could always, and I mean ALWAYS, use ColdFusion's "form.fieldnames" field to get a list of all of the names of the submitted form's fields. At least that's what I thought.

I have a little JSON hack I use to handle form error's. Whenever a user submits a form, I loop through all the fieldnames and make sure they exist in the object. Something like this:

<cfset formJSON = StructNew() />
<cfloop index="key" list="#form.fieldnames#">
<cfif Left(key, 1) neq "_">
<cfset formJSON[LCase(key)] = StructNew() />
<cfset formJSON[LCase(key)].val = form[key] />
</cfif>
</cfloop>

Since the "fieldnames" field is just a list, I was just looping through it. Nothing fancy, but then one of my client's was mentioning how he was getting error's on a form. As I looked into it, sure enough it was throwing an error. Something along the lines of:

key [XYZ] doesn't exist in struct (keys: A,B,C,D…)

So I started sifting through the code to see if I had made a typo or perhaps didn't define the NAME on the form element. Everything checked out, so I did a dump of the form and formJSON and took a gander. Low and behold, that's when I saw it. The form name wasn't being listed in the list. Gotta say, this is a first. I wound up changing my loop to this:

<cfset formJSON = StructNew() />
<cfloop collection="#form#" item="key">
<cfif Left(key, 1) neq "_" and key neq "fieldnames">
<cfset formJSON[LCase(key)] = StructNew() />
<cfset formJSON[LCase(key)].val = form[key] />
</cfif>
</cfloop>

This took care of the problem, but I'm still not 100% sure why this failed in the first place. I just thought I would share. If anyone has any insight I would love to hear it.

 

Update: Sneiland informed me about ColdFusion's reserved words for form field names. You can check that out here: Reserved words in forms. I suspected as much, but I really didn't have a lot of time to dig into the reasons.

For those of you curious, the field name that was causing the error was named inc_date. But I had other field names, apparently violating this "reserved word" rule, inc_report_date, inc_start_time, inc_end_time that displayed fine. I'm guessing if the field only has one underscore, it throws an error, but any names with more than one are ok. I haven't had time to test, but that's my best guess.

Why Adobe choose to have reserved words for FORM fields is beyond me, but as Sneiland points out, it might have something to do with Java.