Coldfusion is an extremely powerful programming language, especially it’s use of scoped variables and structures (or Associative Arrays).  This is especially true of the arguments scope within a cffunction.  The arguments scope is a struct that with the key equal to the argument’s name attribute, and the value is arguments current value.  Pretty simple huh?

Well, this lets us do all sorts to cool things.  I wanted to work with the arguments listing of a function programmatically, by looping through the arguments struct and assigning their values into another struct to be used throughout the component:

<cfscript>
//loop through arguments and setup this.personprofile object (dont include formscope,eventcode,showalum args)
args = structcopy(arguments);
structdelete(args,"formscope");
structdelete(args,"eventcode");
structdelete(args,"showalum");
argnames = structkeyarray(args);
for (i=1;i lte ArrayLen(args); i=IncrementValue(i)){
    this.personprofile[argnames[i]] = args[argnames[i]];
}
</cfscript>

As you can see from this example, its relatively easy to work with the arguments to a function in coldfusion.

Let me explain what is going on here.  As you can see in the comment, I have several (3 to be exact) arguments that I don’t want to inject into my personprofile structure.  To avoid this, I put these 3 arguments at the end of the argument listing for the function. 

First, I copy the arguments struct to the args variable.  Keep in mind, that when you perform a structcopy, it copies all simple values but any nested complex variables (strucs, arrays, queries) are copied by reference (so if you change the value in the copy, it will be changed in the original).  Therefore, before this code block, I copy the formscope, eventcode, and showalum variables into the this.formscope, this.eventcode, and this.showalum variables respectively (to be accessed throughout the component).  Then, I delete the un-needed arguments from the args struct so that they are not included in my new struct.

Secondly, I use the function StructKeyArray to get an array of the structure’s keys, in order to assign these same key values into my other struct.  Then, I loop over my args variable (notice I can treat the arguments struct as an array as well), and assign the name/value pairs of the argument structure into my existing structure.  Pretty simple and rather straight-forward.

For more info about the arguments scope, refer to Working with arguments and variables in functions on Adobe’s Coldfusion documentation site.

This entry was posted on Thursday, October 12th, 2006 at 11:30 am.
Categories: Uncategorized.

No Comments, Comment or Ping

Reply to “Programmatically manipulate function arguments in ColdFusion”