7

I have a form which has many fields in the format of

  • name="field-1"
  • name="field-2"
  • name="field-3"
  • name="field-4"
  • etc....

On the form action page, I would like to be able to use a loop and be able to use the index of the loop to concat with a string prefix like this <cfset newField = "field-" & #index#> and then use the #Variables.newField# to access the form field on the previous page.

I've been playing around with the Evaluate() function, but no luck. I don't use ColdFusion much, so I may just be a little off on the syntax.

An example of how I am using it is:

<cfset newField = "form.field-" & #index#>
<input type="hidden" 
      name="field-<cfoutput>#index#</cfoutput>" 
      value="<cfoutput>Evaluate(Variables.newField)</cfoutput>">
user229044
  • 232,980
  • 40
  • 330
  • 338
d.lanza38
  • 2,525
  • 7
  • 30
  • 52
  • It just outputs form.field-1, form.field-2 and so on. I need the value stored in form.field-1, not the text "form.field-1". – d.lanza38 Apr 02 '13 at 17:24

2 Answers2

9

You don't have to use evaluate at all for this case. Just access the variables struct by key name.

<cfset newField = "form.field-" & index>
<cfset value = variables[newField]>

or just

<cfset value = variables["form.field-#index#"]>

or if you don't want to use an intermediary variable

<cfoutput>#variables["form.field-" & index]#</cfoutput>
Joe C
  • 3,506
  • 2
  • 21
  • 32
  • 1
    Bingo, I just had to change it to ``. Thank you very much, and I have to wait another 5 minutes before I can give you credit, but I will. :-). – d.lanza38 Apr 02 '13 at 17:27
  • Awesome. Obviously, it works with any struct object - I was just using the structures you mentioned/used in the question. – Joe C Apr 02 '13 at 17:29
4

There's no need to set it to the variables scope. Within your loop, you can simply access the form field values using associative array notation directly from the form scope like this:

<input type="hidden" name="field-<cfoutput>#index#</cfoutput>" 
value="<cfoutput>#form['field-' & index]#</cfoutput>">

For extra safety, it would be wise to check for the existence of each form field before trying to display it:

<cfif structKeyExists(form, 'field-' & index)>
    <!--- display field --->
</cfif>
imthepitts
  • 1,647
  • 10
  • 9