Display CFLoop Items in Order from Form

Mike picture Mike · Oct 30, 2013 · Viewed 8.3k times · Source

I have the following form on the page form.html and it submits to cfpage.cfm. The first name, last name, address, and age all show up, but not in a consistent order. Sometimes it will show last name, first name, address, and age. In another instance it may show address, first name, age, and then last name.

How can I display the CFLoop items - with the text the user inputs in the text boxes - in the order they are shown in the form? I have multiple generic forms so I have to use a bit of generic code on cfpage.cfm to capture whatever the feeding form is submitting.

<form id="theform" name="theform" action="cfpage.cfm" method="post">
First Name
<input type="text" name="first name">

Last Name
<input type="text" name="last name">

 Address
<input type="text" name="address">

Age
<input type="text" name="age">
</form>

Code on cfpage.cfm

<cfloop collection="#form#" item="theField">
<cfif theField is not "fieldNames">
#theField# = #form[theField]#<br>
</cfif>
</cfloop>

Answer

David Fleeman picture David Fleeman · Oct 30, 2013

If you want them in the same order they appear on the form, then you must loop using this mechanism:

<cfloop index="i" list="#Form.FieldNames#" delimiters=",">
    #Form[i]#
</cfloop>

Here is code that validates the problem you are seeing, and that shows the loop above works -- save as stacktest.cfm:

<form id="theform" name="theform" action="stacktest.cfm" method="post">
First Name <input type="text" name="first name">
Last Name <input type="text" name="last name">
Address <input type="text" name="address">
Age <input type="text" name="age">
<input type="submit" value="submit"/>
</form>

<cfoutput>
<cfloop collection="#form#" item="theField">
<cfif theField is not "fieldNames">
    #theField# = #form[theField]#<br>
</cfif>
</cfloop>

<cfloop index="i" list="#Form.FieldNames#" delimiters=",">
    #i# = #Form[i]#<br>
</cfloop>
</cfoutput>

Update: Second loop provides same output as first loop now, only in order. Updated by request of user who asked question.