elixireu
elixireu

Reputation: 275

coldfusion 9 VAR issue whilst using <cfset>

I am getting very confused.

I have a set of variables...

<cfset cataloge_menu_1 = "menu item 1">
<cfset cataloge_menu_2 = "menu item 2">
<cfset cataloge_menu_3 = "menu item 3">

I have a URL ID so what i'm trying to do is output the above variable base on the URL ID, so I have the following...

<cfset cathead = "cataloge_menu_"&url.typeID>

and the following output...

<cfoutput>#cathead#</cfoutput>

But instead of outputting "menu item 1" or menu item 2" depending on the URL ID, it outputs "cataloge_menu_1" or "cataloge_menu_2".

What I need to output is the "menu item X" not the "cataloge_menu_X".

Any help would be most appreciated.

Upvotes: 1

Views: 115

Answers (3)

osekmedia
osekmedia

Reputation: 683

Why not just try this:

<cfset cathead = VARIABLES["cataloge_menu_" & url.typeID]>
<cfoutput>#cathead#</cfoutput>

Or you could just output the dynamic variable:

<cfoutput>#VARIABLES["cataloge_menu_" & url.typeID]#</cfoutput>

Upvotes: 1

Pankaj
Pankaj

Reputation: 1741

You can accomplish it using Evaluate() function. This is how it works:

<cfset cataloge_menu_1 = "menu item 1">
<cfset cataloge_menu_2 = "menu item 2">
<cfset cataloge_menu_3 = "menu item 3">
<cfset url.typeID=2 />

<cfset cathead = Evaluate("cataloge_menu_"&url.typeID) />
<cfoutput>#cathead#</cfoutput>

Upvotes: 1

Adam Cameron
Adam Cameron

Reputation: 29870

What this is doing:

<cfset cathead = "cataloge_menu_"&url.typeID>

Is simply making a string containing "cataloge_menu_1" (etc). And the this:

<cfoutput>#cathead#</cfoutput>

Is simply outputting that string.

If you want to access a variable called cataloge_menu_1 then you can't simply output a string containing that variable name and expect CF to guess you mean "look for a variable with that name and output that instead of just the string". You need to tell it to output that variable.

Unscoped variables are - by default - put in the variables scope. So to fetch a dynamically named variable from the variables scope, you use associative array notation to reference the variable via a string containing its name:

<cfoutput>#variables[cathead]#</cfoutput>

PS: it's perhaps a language thing (ie: the code is not in English), but do you mean cataloge or catalogue (or I s'pose catalog if you must)?

Upvotes: 8

Related Questions