
175
DEVELOPING
COLDFUSION 9 APPLICATIONS
Building Blocks of ColdFusion Applications
Las
t
upda
te
d 8/5/2010
<cfscript>
function binop(operation, operand1, operand2)
{ return (operation(operand1, operand2)); }
function sum(addend1, addend2)
{ return a addend2;}
x = binop(sum, 3, 5);
writeoutput(x);
</cfscript>
Handling query results using UDFs
When you call a UDF in the body of a tag that has a
query
attribute, such as a
cfloop
tag, any function argument that
is a query column name passes a single element of the column, not the entire column. Therefore, the function must
manipulate a single query element.
For example, the following code defines a function to combine a single first name and last name to make a full name.
It queries the cfdocexamples database to get the first and last names of all employees, and then it uses a
cfoutput
tag
to loop through the query and call the function on each row in the query.
<cfscript>
function FullName(aFirstName, aLastName)
{ return aFirstName & " " & aLastName; }
</cfscript>
<cfquery name="GetEmployees" datasource="cfdocexamples">
SELECT FirstName, LastName
FROM Employee
</cfquery>
<cfoutput query="GetEmployees">
#FullName(FirstName, LastName)#<br>
</cfoutput>
You generally use functions that manipulate many rows of a query
outside
tags that loop over queries. Pass the query
to the function and loop over it inside the function. For example, the following function changes text in a query column
to uppercase. It takes a query name as an argument.
function UCaseColumn(myquery, colName) {
var currentRow = 1;
for (; currentRow lte myquery.RecordCount; currentRow = curr 1)
{
myquery[colName][currentRow] = UCase(myquery[colName][currentRow]);
}
Return "";
}
The following code uses a script that calls the
UCaseColumn
function to convert all the last names in the GetEmployees
query to uppercase. It then uses
cfoutput
to loop over the query and display the contents of the column.
<cfscript>
UCaseColumn(GetEmployees, "LastName");
</cfscript>
<cfoutput query="GetEmployees">
#LastName#<br>
</cfoutput>