The Problem
Ray Camden posted a Q&A today about how to test for a form submit using Coldfusion. He offered a couple of great solutions. Unfortunately, a fatal flaw was pointed out in my favorite method:
<cfif stuctKeyExists(form, "submit")>
...fails in Internet Explorer when you press enter. For some reason IE doesn't pass the 'submit' value unless you actually click the button. Running some tests, I determined that behavior is unique to IE. It was a nice method because it's concise and doesn't require modification of the form.
Looking for a new solution:
Based on the article I tested the following method by submitting a form pressing enter and clicking on the submit button.
The browsers:
- Firefox 3
- Safari 4 (Windows)
- Chrome 1
- IE 6
- IE 7
The Methods:
1: <cfif structKeyExists(form, "submit")>
Fails in IE 6 & 7 when you press the "Enter" key to submit.
2: <cfif NOT StructIsEmpty(form)>
Fails in all browsers if you cfparam any form fields. I would recommend against this as it will be easy to break the form during future maintenance.
3. Test for an existing form field OTHER than 'submit': structKeyExists(form, "hiddenfield") or isDefined("form.hiddenfield")
This method works fine in all browsers, but unfortunately requires a specific field name. You should know the fields since you're processing the form anyway, but sometimes, that logic is abstracted away. For example:
<cfif structKeyExists(form, "hiddenfield")>
<cfset application.formwizard.save(form)>
</cfif>
If the hidden field wasn't required this code could be reused without concern.
4: isDefined("form.fieldNames") and len(form.fieldNames)
I'd never heard of this method, but after testing, it works reliably in all browsers when a form is submitted by clicking "submit" or pressing "enter". To my surprise, it even worked when form fields were param'd.
4b. isDefined("form.fieldNames")
This shortened version also appears to work reliably in all tested browsers when clicking 'submit' or pressing 'enter'.
Result:
After these tests, I plan to switch over to option 4, and preferably 4b. I plan to do more testing on 4b to determine if there are any cases where a browser creates this field before the form was posted.