Getting struct data with variables in Coldfusion

Posted on Saturday, January 2nd, 2010 at 4:48 pm

I thought I’d write a quick post about something that I thought might trip people up every now and then.  And that is getting data from a struct by passing in a variable that represents some portion of the struct holding the data.  I’ll just give a few quick lines of code to represent what I’m talking about.

<!--- CREATE A STRUCT --->
<cfset VARIABLES.myStruct = structnew()>

<!--- SET A MESSAGE INTO OUR STRUCT --->
<cfset VARIABLES.myStruct.message = "This is my message.">

<!--- SET A VAR TO REPRESENT THE MESSAGE PORTION OF OUR STRUCT --->
<cfset VARIABLES.the_message = "message">

<!--- GET MESSAGE USING THE VARIABLE --->
<cfdump var="#VARIABLES.myStruct[VARIABLES.the_message]#">

All we’re doing here is creating a struct with a message stored in it. I think it’s pretty common for Coldfusion developers to use dot syntax to retrieve data from structs. But this creates a little bit of a problem when the portion of the struct that we need to get data back from is represented by a variable that we have set. I find this happening most often when I use loops to get or set data into a struct.

Nonetheless, in the above I’m retrieving my message from the struct.  Yes the easiest way to get the message is with dot syntax.  To use it this way we would write <cfdump var=”#VARIABLES.myStruct.message#”>.  But let’s just say that for whatever reason we’re not at liberty to write message directly.  Instead we need to represent ‘message’ with a variable set for whatever reason be it looping, reusability, or just generally passing data.  So I’ve set a variable to hold a string equal to ‘message’.  To get the message from the struct using this variable we need to write it as <cfdump var=”#VARIABLES.myStruct[VARIABLES.the_message]#”>

So to get data from a struct using a var just mix your dot syntax with some square brackets and voila you get the message.

Tags
CategoryColdfusion

Leave a Reply

*
(Won't be published) *