Calling a function by Using CF Invoke

an article added by: Jack Irwingston at 04042008


In: Root » Programming » ColdFusion MX » Calling a function by Using CF Invoke

 French | Spanish | Portuguese | Italian | German | Japanese | Chinese | Korean | Russian | Arabic Bookmark and Share

You can call functions by using two CFML tags: CFINVOKE and CFINVOKEARGUMENT. The following code is a function:

<cfscript>
   function add2(firstNumber, secondNumber) {
   return firstNumber + secondNumber;
   }
 </cfscript>

Following is how we would call that function by using the standard syntax:

<cfoutput>#add2(1,2)#</cfoutput>

If we call that function by using CFINVOKE, it looks as follows:

<cfinvoke method=”add2” returnvariable=”theSum”>
   <cfinvokeargument name=”firstNumber” value=”7”>
   <cfinvokeargument name=”secondNumber” value=”3”>
   </cfinvoke>
   <cfoutput>#theSum#</cfoutput>

Notice that, in using CFINVOKE, we specify the name of the variable in the calling template into which the result of the function is returned. This is necessary because we are not simply outputting an inline function call: Some container must be there for the result that is external to the tag-based function invocation code. CFINVOKEARGUMENT also enables you to conditionally include or modify arguments, because it is a tag-based construction, as the following example shows:

<cfinvoke method=”add2” returnvariable=”theSum”>
   <cfinvokeargument name=”firstNumber” value=”7”>
   <cfif secNum GT 100>
   <cfinvokeargument name=”secondNumber” value=”100”>
   <cfelse>
   <cfinvokeargument name=”secondNumber” value=”#secNum#”>
   </cfif>
   </cfinvoke>
   <cfoutput>#theSum#</cfoutput>

Note that when using CFINVOKEARGUMENT, you must always provide a name for every parameter, so you can’t use positional notation with CFINVOKEARGUMENT. You have another option for calling a function by using CFINVOKE. You can put the function’s arguments into a structure named argumentcollection and pass the structure to CFINVOKE, as follows:

<cfset myStruct = StructNew()>
   <cfset myStruct[“firstNumber”] = 7>
   <cfset myStruct[“secondNumber”] = 3>
   <cfinvoke method=”SumArgs” returnvariable=”theSum”
   argumentcollection=”#myStruct#”>

All the keys in myStruct become the arguments to the SumArgs() function; in essence, myStruct becomes the function’s Arguments collection. The advantage to this method is that you can assemble the arguments into the structure well before the function is called and then just pass the single structure to the function. The disadvantage is that you must always use named notation; you can have no unnamed arguments. You have yet another option for calling CFINVOKE. The arguments to the function can be passed as extra attributes to CFINVOKE, as follows:

<cfinvoke method=”SumArgs” returnvariable=”theSum” firstNumber=”7”
   secondNumber=”3”>

You face one caveat in using CFINVOKE. Attempting to pass argumentcollection and separate argument attributes at the same time causes CFINVOKE to ignore the argumentcollection, causing some of your function’s arguments to be undefined. Strangely enough, changing argumentcollection to attributecollection corrects the problem. This has been verified by Macromedia and may be changed in the future, so don’t rely on this behavior. Not all functions must return a value. The function in the following code, for example, converts all the values in an array to uppercase:

<cfscript>
   function UCaseArray(arArray) {
   for(i = 1; i LTE ArrayLen(arArray); i = i + 1) {
   arArray[i] = UCase(arArray[i]);
   }
   return arArray;
   }
 </cfscript>
 <cfset myArray = ArrayNew(1)>
 <cfset myArray[1] = “My String”>
 <cfset myArray[2] = “Your String”>
 <cfset myArray[3] = “Our String”>
 <cfscript>
 myArray = UCaseArray(myArray);
 </cfscript>
 <cfdump var=”#myArray#”>

In this case, we needed to return myArray because we had modified the elements in a copy of the original array. If we write the function to modify the keys of a structure, however, we don’t need to return a value, as the following example shows:

<cfscript>
   function UCaseStruct(myStruct) {
   for(item in myStruct) {
   myStruct[item] = UCase(myStruct[item]);
   }
   return;
   }
 </cfscript>
 <cfset myStruct[“Mine”] = “My String”>
 <cfset myStruct[“Yours”] = “Your String”>
 <cfset myStruct[“Ours”] = “Our String”>
 <cfscript>
 UCaseStruct(myStruct);
 </cfscript>
 <cfdump var=”#myStruct#”>

Because the structure is passed by reference, we can just modify the values in the original structure, and we don’t need to return anything, because referencing the same structure after the function is called yields the newly modified key values. This is not the case in ColdFusion 5, however, where all functions must return a value. UDFs can be separately placed in each template that requires them, but this isn’t exactly efficient coding. A better technique is to place related UDFs in a single template by themselves and then CFINCLUDE that template wherever one or more of its functions are needed. Building a library of related functions is a better practice than placing all UDFs in a single template, as ColdFusion must still process these functions as they are included, and this process takes time. Including a library containing 127 UDFs when you need to use only one of them doesn’t make sense. A much better practice is to have one UDF library template for each category of UDFs, so you may create a library template named StringUDFs.cfm that contains all UDFs related to string manipulation and another library template named FinancialUDFs.cfm that contains all financially-oriented UDFs. This way, you create a healthy balance between ease of code maintenance and time wasted processing unneeded UDFs. User-defined functions enable you to extend ColdFusion’s built-in library of functions with your own. If you use the new CFFUNCTION syntax, your functions can do anything from simple string or number operations to database calls. You see how truly useful functions are and you can probably already imagine good uses for them in your existing code. In this article you learned how to create functions with both CFSCRIPT and CFFUNCTION. You also learned how to call functions with positional and named notation, and you learned about some of the caveats that occur when you use CFINVOKE and CFINVOKEARGUMENT.

legal disclaimer

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

related articles

1. Cfml and JavaScript
One concept that many ColdFusion developers take for granted is the relationship and differences between a client (your Web browser) and a server (ColdFusion). In this article, you learn what clients and servers are, how they interact, and how they don’t. You might be surprised at how many developers remain confused about the interactions that are possible and impossible between ColdFusion (a server technology) and JavaScript (a client technology) —even after developing ColdFusion applications for a year or ...

2. An Overview of Structured Query Language
SQL, or Structured Query Language, is a common language for querying and manipulating data. As have all standards, SQL has gone through a number of revisions to take advantage of new functionality and to incorporate better methods. Some database server products support the very latest standards, but most don’t. The standard that we explain here is the SQL- 92 Standard, which is currently in use—at least to some extent—by the majority of database products on the market as of this writing. If your database produc...

3. Insert Statements
Data is inserted into tables by using INSERT statements. The code shows a typical INSERT statement. INSERT INTO Company ( CompanyName, Address, City, State, ZipCode ) VALUES ( ‘Fast Like Bunny’, ‘99 Mulberry Lane’, ‘Reston’, ‘VA’, ‘20194’ ) The code inserts a single row into the Company table with the values shown in the code. As you can see, the values must be specified in the same order that the colum...

4. Delete Statements
You delete data from tables by using DELETE statements. The basic form of a DELETE statement specifies a set of rows to be deleted from a single table. The set of rows is defined by the criteria specified in the DELETE statement’s WHERE clause. As in using the UPDATE statement, you must be very careful to specify exactly which row or rows that you want to delete, or you can permanently delete the wrong data. If you forget to include the WHERE clause, you delete all the rows in the table, so be careful. Use the code to delete an em...

5. Where you cannot use CFINPUT
The Submit button is a simple version of the INPUT tag because it doesn’t need a Name attribute. It looks as follows: <input type=”submit” value=”Update Database”> No form variable is created for this Submit button, because we don’t give the INPUT tag a name. The Value attribute contains the text that appears on the button. The Reset button is another type of INPUT tag. Its code looks much like that of the Submit button, as follows: <input type=”reset&rdq...

6. CFtext Input
CFTEXTINPUT implements a text-input field (as does CFINPUT) by using a Java applet. You have no reason whatsoever to use CFTEXTINPUT. It performs the same purpose as <cfinput type=”text”> but with an unacceptable increase in overhead. The only attributes of CFTEXTINPUT that aren’t part of CFINPUT involve font and background styling and colors, all of which can be accomplished by using style sheets. CFTREE is slightly more complicated than CFSLIDER because, in addition to configuring the tree control by ...

7. Development Testing
Rigorous testing is often overlooked to the peril of a development project. Testing can be an aggravating process, but it doesn’t need to be. In this article, you learn how to create a realistic testing plan to make sure that your code works under all conditions, and then you learn useful debugging techniques to help you find out why your code is breaking. Testing an application involves two phases: development testing and application testing. Development testing ensures that individual snippets of your code wor...

8. Browser settings
If your application breaks, don’t blame the browser settings! This sort of thing happens often: You test your code, find a problem, make a change, and it still doesn’t work. You spend an hour tracking the problem down, and then you discover that you never refreshed the form, or you find out that you needed to delete your temporary Internet files. Automatically blaming the browser settings for your problem is a waste of time. Most users have no idea what their browser settings are, let alone how to change them. So i...

9. Describing relationships
Something else that gives us good insight into how the software works with the database is identifying which attributes are absolutely necessary to describe each entity. If an attribute must be present to effectively describe an entity, that attribute cannot contain a NULL value. NULL values have wider significance than may first come to mind; if an attribute cannot be NULL, its value must be acquired during all business processes that create those entities. You may find that significant changes to business processes become ne...

10. Check constraints
Now we come to one of the most useful yet underutilized features of databases: the capability to restrict or constrain the values that can go in table columns. Why is this capability important? Because your database must diligently safeguard against receiving incorrect data, and the database cannot rely on its client applications for this safeguard. A check constraint is a declaration that only certain data may be stored in a database column. Like all declarations, check constraints are made in the DDL (Data Description Langua...