问题
Attempting to use squarebracket notation to reference a dynamic variable. (I'm looping through a set of product created by a query, creating fields for each tied to their unique SKU, if you're wondering about application)
I've narrowed it down to this chunk of code, which throws an "Invalid Expression" error when I try and run it.
<cfif FORM["QTY_" & SKU] NEQ ''>
<div class="sopQty"><input type="number" min="0" name="QTY_#SKU#" value = "#FORM['QTY_' & SKU]#" /></div>
<cfelse>
<div class="sopQty"><input type="number" name="QTY_#SKU#" /></div>
</cfif>
The goal is to pass the value on from the previous page if there is one, else leave the field blank. I'm thinking there's some quirk of syntax in this case that I haven't been able to figure out. Error in block below:
Type: Template
Message: Invalid Expression
Tag: CFIF
Position Line=62; Column=17
Detail Bad Expression [#FORM['QTY_' & SKU])#]
Source
60: <div class="sopSearch"><p>#SearchAlias#</p></div> 61: <div class="sopPrice"><p>#ISBNupc#</p></div> 62: <cfif FORM["QTY_" & SKU] NEQ ''> 63: <div class="sopQty"><input type="number" min="0" name="QTY_#SKU#" value = "#FORM['QTY_' & SKU])#" /></div> 64: <cfelse>
^ Snippet from underlying CFML source
Any suggestions?
回答1:
This is just an example,because I do not know where you are setting your variables, but try something like the following on your action page:
<cfset SKU = "123">
<cfset dynamic_Var = "QTY_" & variables.SKU>
<cfif IsDefined("form[dynamic_Var]")>
<cfoutput>#form[dynamic_Var]#</cfoutput>
<cfelse>
fail
</cfif>
Here is the submitting form:
<form name="test" action="test.cfm">
<input type="text" name="QTY_123" value="test">
<input type="submit" name="submit" value="submit">
</form>
回答2:
Below is also possible (and wont cause an error if the key is not defined).
<cfset key = "QTY_" & sku/>
<cfif structKeyExists(form, key) && len(form[key])>
<!--- do something --->
</cfif>
来源:https://stackoverflow.com/questions/12425794/calling-a-variable-with-a-variable-in-its-name-coldfusion