Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat two strings and use the result as a variable name in coldfusion?

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>">
like image 773
d.lanza38 Avatar asked Apr 02 '13 17:04

d.lanza38


People also ask

How do you concatenate strings and variables?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate strings in ColdFusion?

ColdFusion already supports string concatenation using “&” operator. ColdFusion 8 introduces a new string operator “&=” for compound concatenation. <! --- &= Compound concatenation.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

What is concatenation of string which operator is used for this purpose?

Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.


2 Answers

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>
like image 102
Joe C Avatar answered Sep 28 '22 02:09

Joe C


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>
like image 35
imthepitts Avatar answered Sep 28 '22 03:09

imthepitts