Avg. Rating 5.0

Problem

You need to dynamically capture form variables, and then auto-magically generate url-friendly name value pairs of each form field. In fact, you might need to ignore certain form fields too!

Solution

Using a simple user-defined function (UDF), you can easily generate url-friendly concatenated name-value pairs of form fields.

Detailed explanation

Include the following user-defined function (UDF) on the page where you need to capture form fields and generate url-friendly concatenated name-value pairs:

<cffunction name= "formToNameValuePairs" returntype= "string" output= "false" access= "remote"
            hint= "pass me a form and i'll generate concatenated name-value pairs.">


     <cfargument name= "formStruct" type= "struct" required= "true" hint= "the form struct to parse and concatenate" />
     <cfargument name= "doNotProcessList" type= "string" required= "false" hint= "a list of form fields to ignore" default= "" />

     <cfset var local = structNew() />
     <cfset local.nameValuePairs = "" />
     <cfset local.doNotProcess = arguments.doNotProcessList />
     <cfset local.field = "" />

     <cfif structKeyExists(arguments, "formStruct") and structKeyExists(arguments.formStruct, "fieldnames")>
          <cfloop list= "#arguments.formStruct.fieldnames#" index= "local.field">
          <cfif not listFindNoCase(local.doNotProcess,local.field)>
          <cfset local.doNotProcess = listAppend(local.doNotProcess,local.field) />
          <cfset local.nameValuePairs = listAppend(local.nameValuePairs,lcase(local.field) & "=" & urlEncodedFormat(form[local.field], "utf-8"), "&") />
               </cfif>
          </cfloop>
     </cfif>    

     <cfreturn local.nameValuePairs />
</cffunction>

 Here's an example of how to use the UDF:

<cfoutput>#formToNameValuePairs(form, "SUBMIT,ISSUBMITTED")# </cfoutput>

Here's a link to the original UDF on CFLib.org: http://cflib.org/udf/formToNameValuePairs


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes