A while back I wrote a post about accessing form fields in ColdFusion as an array. This is useful when you have several fields with the same name, and there is a chance they could contain a comma. Working with the data as an array is much more robust.

But after updating to CF10 I realized this didn’t work anymore! I was surprised, since I thought the getPageContext() stuff was pretty standard, and not undocumented. So anyway I’ve rewritten my function to work in CF10. The code is much simpler now.

<cffunction name="formFieldAsArray" returntype="array" output="false" hint="Returns a Form/URL variable as an array.">
	<cfargument name="fieldName" required="true" type="string" hint="Name of the Form or URL field" />
	
	<cfset var content = getHTTPRequestData().content />
	<cfset var returnArray = arrayNew(1) />
	
	<cfloop list="#content#" delimiters="&" index="local.parameter">
		<cfif listFirst(local.parameter,"=") EQ arguments.fieldName>
			<cfif ListLen(local.parameter,"=") EQ 2>
				<cfset arrayAppend(returnArray,URLDecode(listLast(local.parameter,"="))) />
			<cfelse>
				<cfset arrayAppend(returnArray,"") />
			</cfif>
		</cfif>
	</cfloop>
	
	<cfreturn returnArray />

</cffunction>

You may have heard about the new sameformfieldsasarray setting in CF10. This is another option. But it is application-wide. That is, anytime you have form fields with the same name they will come through as an array. This may or may not work for you. In my application, enabling that would break a lot of code so I wrote this separate function to handle when I need the values as an array.

Leave a Reply

You must be logged in to post a comment.