Wednesday, September 16, 2009

Fixing ColdFusion's issues with method="get" and multiple select boxes

ColdFusion doesn't seem to like forms with method="get".
I've been developing a simple search tool with a multiple select box to specify some of the search criteria. Because I wanted to make the results linkable I used method="get" in the form.
The browser with return the multiple select values like so:
?select1=val1&select1=val2
But ColdFusion will see it as url.select1 = "val2". Only the last select will be present in the url scope.
To solve this problem we've got to bypass the url scope and grab the values directly from the CGI.QUERY_STRING like so:

<cfset get=StructNew()>
<cfloop index="keyvalpair" list="#CGI.QUERY_STRING#" delimiters="&">
<cfset key=ListFirst(keyvalpair, "=")>
<cfset keyval=URLDecode(ListLast(keyvalpair, "="))>
<cfif not StructKeyExists(get, key)>
<cfset get[key]="">
</cfif>
<cfset get[key]=ListAppend(get[key], keyval)>
</cfloop>


Now the get structure will contain everything in the url scope plus a comma separated list of values from the multiple select boxes.
From our example above: get.select1 = "val1,val2".

No comments: