Interacting with component methods

The vast majority of ColdFusion applications require data to be passed back and forth between a number of pages. For example, a typical web shopping cart application uses multiple ColdFusion pages to gather user data, access databases, and confirm credit card information.

ColdFusion components support passing and returning simple and complex values using the cfinvoke tag, URL and form controls, CFScript, the Macromedia Flash Remoting service, and web services. Whether you are receiving registration information from a simple HTML page or passing a query object back to a sophisticated web service, interacting with ColdFusion components means that you must be able to pass data into and out of a component.

Interacting with components consists of the following operations:

Invoking component methods

To interact with ColdFusion components, you invoke component methods from the client. Components support many client types, including web pages, ColdFusion pages, Flash movies, web services, and other components. The invocation process depends on what type of client invokes a component method.

The following table displays the different ways to invoke component methods:
Invocation
Description
For more information
cfinvoke tag
The cfinvoke tag instantiates and invokes component methods from within ColdFusion pages and components.
cfobject tag
The cfobject tag instantiates a component. However, you must still use the cfinvoke tag or CFScript to invoke component methods, pass parameters, and return results.
URL control
(HTTP GET)
You use the component and method names in the URL string to invoke component methods.
Form control
(HTTP POST)
HTML and ColdFusion forms invoke component methods using the HTML form and input tags and their attributes.
CFScript
CFScript instantiates component methods using the createObject function. The component method can then be called using componentName.componetMethod() syntax.
Flash Remoting
In client-side ActionScript, you use the NetServices functions to invoke component methods.
Web services
You use the cfinvoke tag and CFScript to consume web services in ColdFusion.

Note:   To restrict component method invocation, you use the access and roles attributes of the cffunction tag. For more information, see "Using web server authentication".

Note:   To invoke components within the component method definition, you use the cfinvoke tag with its method attribute. In CFScript, you use the method name in standard function syntax, such as methodName().

Invoking component methods using the cfinvoke tag

In ColdFusion pages or components, use the cfinvoke tag to invoke component methods. You can place multiple cfinvoke tags in a ColdFusion page to invoke multiple component methods.

Syntax for the cfinvoke tag

<cfinvoke component="componentName" method="methodName"
returnVariable="variableName" argumentCollection="argumentStruct">

The following table displays the tag attribute, data type, and description:
Attribute
Type
Required
Description
For more information
component
string
yes
Name of component

method
string
yes
Name of component method
returnVariable
string
no
Creates a variable by the name entered and assigns the component method results into that variable
argumentCollection
structure
no
Passes structure to component method as parameters

To invoke a component method using the cfinvoke tag:

  1. Open the tellTime.cfc file, and modify the code so that it appears as follows:
    <cfcomponent>
      <cffunction name="getLocalTime">
         <cfscript>
          serverTime=now();
          localStruct=structNew();
          localStruct.Hour=DatePart("h", serverTime);
          localStruct.Minute=DatePart("n", serverTime);
        </cfscript>
        <cfoutput>#localStruct.Hour#:#localStruct.Minute#</cfoutput>  
      </cffunction>
      <cffunction name="getUTCTime">
        <cfscript>
          serverTime=now();
          utcTime=GetTimeZoneInfo();
          utcStruct=structNew();
          utcStruct.Hour=DatePart("h", serverTime);
          utcStruct.Minute=DatePart("n", serverTime);
          utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet;
          utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet;
        </cfscript>
        <cfoutput>#utcStruct.Hour#:#utcStruct.Minute#</cfoutput>  
      </cffunction>
    </cfcomponent>
    

    The example defines two component methods, getLocalTime and getUTCTime.

  2. Create a new ColdFusion page, and save it as timeDisplay.cfm in the same directory as the tellTime component.
  3. Modify the ColdFusion page so that is appears as follows:
    <h3>Time Display Page</h3>
    <b>Server's Local Time:</b>
    <cfinvoke component="tellTime" method="getLocalTime"><br>
    <b>Calculated UTC Time:</b>
    <cfinvoke component="tellTime" method="getUTCTime">
    

    Using the cfinvoke tag, the example invokes the getLocalTime and getUTCTime component methods.

  4. The following figure shows the results when you execute timeDisplay.cfm in a web browser:

    Shows results when you execute timeDisplay.cfm in a web browser

Invoking component methods using the cfobject tag

To separate the instantiation of the component and the invocation of the component method, use the cfobject tag. First, use the cfobject tag to instantiate the component and assign the component to a variable; for example:

<cfobject name="tellTimeComp" component="tellTime">

To invoke component methods, use the cfinvoke tag. The cfinvoke tag's name attribute references the variable name in the cfobject tag's name attribute; for example:

<cfobject name="tellTimeComp" component="tellTime">
<cfinvoke component="#tellTimeComp#" method="getLocalTime">
<cfinvoke component="#tellTimeComp#" method="getUTCTime">

Invoking component methods using a URL

To invoke a component method using a URL, you must append the method name to the URL in the standard URL query-string, name-value syntax. You can only invoke one component method per URL request; for example:

http://localhost:8500/tellTime.cfc?method=getLocalTime

Note:   To use URL invocation, you must set the cffunction tag's access attribute to remote.

Invoking component methods using a form

To invoke a method using a ColdFusion or an HTML form, you must enter the file path to the ColdFusion component in the action attribute and the method name as a form variable that is submitted.

Note:   To use form invocation, you must set the cffunction tag's access attribute to remote.

To invoke component methods using a form:

  1. Open timeDisplay.cfm, and modify the page so that it appears as follows:
    <h3>Time Display Page</h3>
    <p>Make your selection and press the Got the time? button:</p>
    <cfform action="tellTime.cfc" method="POST">
    <cfselect name="Method" required="Yes">
      <option value="getLocalTime" selected>Local Time</option>
      <option value="getUTCTime">UTC Time</option>
    </cfselect>
    <input type="submit" value="Got the time?">
    </cfform>
    

    In the example, the cfform tag's action attribute points toward the tellTime component file. The cfselect statement passes the component method name.

  2. Save your work.
  3. Start your web browser, and browse to the following URL:
    http://localhost:8500/timeDisplay.cfm
    

    The following figure shows the results:

    Web browser display of timeDisplay.cfm

    Make a selection from the drop-down box, and click the Got the Time? button. Depending on your selection, the server's local or UTC time displays.

Invoking component methods with CFScript

To invoke a a component method using CFScript, use the createObject function or cfobject tag to instantiate the component. After you instantiate the component, you use normal function syntax to invoke component methods; for example:

<!--- instantiate once and reuse the instance--->
<cfscript>
  tellTimeCFC=createObject("component","tellTime");
</cfscript>
<b>Server's Local Time:</b>
  <cfscript>
    tellTimeCFC.getLocalTime();
</cfscript>
<br>
<b>Calculated UTC Time:</b>
<cfscript>
  tellTimeCFC.getUTCTime();
</cfscript

In the example, the two CFScript statements assign the tellTimeCFC variable to the tellTime component using the createObject function. Next, you use normal function syntax to invoke the component method.

Passing parameters to component methods

To perform conditional processing in ColdFusion components based on data sent from the client, you pass parameters to component methods. In ColdFusion applications, parameters typically consist of user name and password information, session state data, keywords for database queries, and so on.

To pass parameters in ColdFusion components:

  1. Define the parameter in the component method definition using the cfargument tag. For more information, see "Defining the parameter in the component method definition".
  2. Choose your parameter-passing technique. Use the parameter-passing technique best suited for your client type. For more information, see "Choosing a parameter-passing technique".

Defining the parameter in the component method definition

In the component method, you create parameter definitions using the cfargument tag within the component method definition. You define multiple parameter with multiple cfargument tags. To access the parameter values in the component method definition, you use structure- or array-like notation with the argument variable.

Syntax for the cfargument tag

<cfargument name="parameterName" type="dataType"
required="true/false"default="defaultValue">

The following table displays the tag attribute, data type, and description:
Attribute
Type
Required
Description
name
string
yes
Name of parameter
type
data type
no
Validates all valid data types
required
Boolean
no
Specifies whether the parameter is required to execute the component method
argumentCollection
all types
no
Provides a default value when a parameter is not passed

Also, if the required attribute is not set to true, you can specify a default value for the parameter value using the default attribute. The following example defines two parameters and references the parameter values in the component method definition.

Note:   For the following procedures to work, you must have the example applications installed with ColdFusion. For more information, see CFML Reference.

To define parameters in the component method definition:

  1. Create a new component, and save it as corpQuery.cfc in a directory under your web root directory.
  2. Modify the code in corpQuery.cfc so that it appears as follows:
    <cfcomponent>
      <cffunction name="getEmp">
        <cfargument name="lastName" required="true"> 
         <cfquery name="empQuery" datasource="ExampleApps" dbtype="ODBC">
           SELECT LASTNAME, FIRSTNAME, EMAIL
           FROM tblEmployees
          WHERE LASTNAME LIKE '#arguments.lastName#'
         </cfquery>
         <cfoutput>Results filtered by #arguments.lastName#:</cfoutput><br>
         <cfdump var=#empQuery#>
      </cffunction>
      <cffunction name="getCat">
      <cfargument name="cost" required="true"> 
        <cfquery name="catQuery" datasource="ExampleApps" dbtype="ODBC">
           SELECT ItemName, ItemDescription, ItemCost
           FROM tblItems
          WHERE ItemCost <= #arguments.cost#
         </cfquery>
         <cfoutput>Results filtered by #arguments.cost#:</cfoutput><br>
         <cfdump var=#catQuery#>
      </cffunction>
    </cfcomponent>
    

    In the example, the cfargument tag's name attribute defines the parameter's name. The required attribute indicates that the parameter is required or an exception will be thrown. The arguments variable scope provides access to the parameter values.

    Note:   You can also reference multiple parameter values using array- and structure-like syntax. For example, arguments.cost is the same as argument[1]. Array and structure-like notation also lets you loop over multiple parameters. In addition, you can access arguments directly using pound signs, such as #cost#.

  3. Save your work.

Choosing a parameter-passing technique

Like ColdFusion pages, you can pass parameters using a URL or the HTTP GET and POST form methods with ColdFusion components. Components also accept passing parameters using the cfinvoke tag.

The following table describes your parameter-passing options:
Parameter type
Description
For more information
cfinvoke tag
Specify the parameters as cfinvoke tag attributes or the argumentsCollection attribute.
cfinvokeargument tag
Specify parameter name and values using the cfinvokeargument tag.
URL
Specify the parameters in the standard URL query-string, name-value pair syntax.
Form
Specify the parameters as form input values.
CFScript
Specify the parameters as ordered arguments or named arguments.
Flash Remoting
Specify the parameters in client-side ActionScript.
Web services
Specify the parameters as cfinvoke tag attributes or the argumentsCollection attribute.

Passing parameters using the cfinvoke tag

You can pass a single or multiple parameters in one cfinvoke tag as tag attribute name-value pairs. The following example passes a single parameter:

<cfinvoke component="authQuery" method="getAuth" lastName=session.username>

In the example, the lastName attribute passes the value of the session scope variable to the component method. To pass multiple parameters, use an attribute name-value pair for each parameter; for example:

<cfinvoke component="authQuery" method="getAuthSecure"
lastName=session.username password=#url.password# >

In the example, the parameters are passed as the lastName and password attributes. Notice that different variable scopes are used in the attribute values.

Note:   The cfinvoke tag attribute names are reserved and cannot be used for parameter names. The reserved attribute names are component, method, argumentCollection, and returnVariable. For more information, see CFML Reference.

If you save attributes to a structure, you can directly pass the structure using the cfinvoke tag's argumentCollection attribute.

The following example invokes a component that performs simple addition and subtraction:

<cfscript>
  exampleStruct = StructNew();
  exampleStruct[1] = 1;
  exampleStruct[2] = 2;
</cfscript>
<cfinvoke component="arithCFC" method="add" argumentCollection=exampleStruct>

This example passes two parameters to the component method as a structure. Notice the use of the argumentCollection attribute of the cfinvoke tag.

Passing parameters using the cfinvokeargument tag

To pass parameters independently of the cfinvoke tag, use the cfinvokeargument tag. Using the cfinvokergument tag, for example, you can build conditional processing that passes a different parameter based on user input.

Syntax for the cfinvokeargument tag

<cfinvokeargument name="parameterName" value="anyValue">

The following table displays the tag attribute, data type, and description:
Attribute
Type
Required
Description
name
string
yes
Name of parameter
value
all types
yes
Value of parameter

The following example invokes the corpQuery component:

<cfinvoke component="corpQuery" method="getEmp">
<cfinvokeargument name="lastName" value="camden">

Notice that the cfinvokeargument tag passes the lastName parameter to the component method.

Note:   For more information about parameter precedence, see CFML Reference.

Passing parameters using a URL

To pass parameters to component methods using a URL, append the parameters to the URL in standard URL query-string, name-value pair syntax. For example:

http://localhost:8500/corpQuery.cfc?method=getEmp&lastName=camden

To pass multiple parameters within a URL, use the ampersand (&) character to delimit the name-value pairs. Here is an example:

http://localhost:8500/corpQuerySecure.cfc?method=getAuth&store=women&dept=shoes

Note:   Due to security concerns, Macromedia strongly recommends that you do not pass sensitive information over the web using URL strings. Potentially sensitive information includes all personal user information, including passwords, addresses, telephone numbers, and so on.

Passing parameters using a form

To pass parameters to components using an HTML or ColdFusion form, the names of the client input controls must match the names of the parameter definition in the component file.

To pass parameters using a form:

  1. Open the corpFind.cfm file and modify the code so that it appears as follows:
    <h2>Find People and Products</h2>
    <form action="components/corpQuery.cfc" method="post">
      <p>Enter employee's last Name:</p>
      <input type="Text" name="lastName">
      <input type="Hidden" name="method" value="getEmp">
      <input type="Submit" title="Submit Query"><br>
    </form>
    <form action="components/corpQuery.cfc" method="post">
      <p>Enter maximum product price:</p>
      <input type="Text" name="cost">
      <input type="Hidden" name="method" value="getCat">
      <input type="Submit" title="Submit Query">
    </form>
    

    In the example, the form tag action attribute points to the corpQuery component. The input tags invoke the component method.

  2. Open corpQuery.cfc and add access="remote" to each cffunction tag, as the following example shows:
    <cfcomponent>
      <cffunction name="getEmp" access="remote">
        <cfargument name="lastName" required="true"> 
         <cfquery name="empQuery" datasource="ExampleApps" dbtype="ODBC">
           SELECT LASTNAME, FIRSTNAME, EMAIL
           FROM tblEmployees
          WHERE LASTNAME LIKE '#arguments.lastName#'
         </cfquery>
         <cfoutput>Results filtered by #arguments.lastName#:</cfoutput><br>
         <cfdump var=#empQuery#>
      </cffunction>
      <cffunction name="getCat" access="remote">
      <cfargument name="cost" required="true"> 
        <cfquery name="catQuery" datasource="ExampleApps" dbtype="ODBC">
           SELECT ItemName, ItemDescription, ItemCost
           FROM tblItems
          WHERE ItemCost <= #arguments.cost#
         </cfquery>
         <cfoutput>Results filtered by #arguments.cost#:</cfoutput><br>
         <cfdump var=#catQuery#>
      </cffunction>
    </cfcomponent>
    

    In this example, the cffunction access attribute lets remote clients, such as web browsers and Flash applications, to access component methods.

  3. Save your work.
  4. Open a web browser and enter the following URL:
    http://localhost/corpFind.cfm
    

    The following figure shows the results:

    Web browser display of corpFInd.cfm

    Depending on what you enter, after you click the Submit Query button, the web browser displays the results, as shown in the following figure:

    Web browser display of corpQuery.cfc result

Passing parameters using CFScript

The following example instantiates a component, invokes the getAuth component method in three different ways, and passes parameters in each method invocation:

<cfscript>
  corpQCFC = createObject("component", "corpSecurity");
  corpQCFC.getAuth(username="skippy" password="dippy");
  tempStruct = structNew();
  tempStruct.username = "skippy"
  tempStruct.password = "dippy"
  corpQCFC.getAuth(argumentsCollention = tempStruct);
  corpQCFC.getAuth("skippy", "dippy");
</cfscript>

Returning values from component methods

In the component method definition, you return the results to the client using the cfreturn tag. The equivalent to the return CFScript statement, the cfreturn tag only accepts one variable to return at a time. Therefore, if you want to return more than one result value at a time, populate a structure with name-value pairs and return the structure using the cfreturn tag.

To access the result values returned to the client, use the variable scope specified as the value of the cfinvoke tag's returnVariable attribute.

Returning component method results to the client

To return component method results to the client, use the cfreturn tag in the component method definition. You can pass values of all data types, including strings, integers, arrays, and structures.

To prepare the component method definition to return a value:

  1. Open the corpQuery.cfc file, and modify the code so that it appears as follows:
    <cfcomponent>
      <cffunction name="getEmp">
         <cfquery name="empQuery" datasource="ExampleApps" dbtype="ODBC">
           SELECT LASTNAME, FIRSTNAME, EMAIL
           FROM tblEmployees
         </cfquery>
         <cfreturn empQuery>
      </cffunction>
      <cffunction name="getCat"> 
        <cfquery name="catQuery" datasource="ExampleApps" dbtype="ODBC">
           SELECT ItemName, ItemDescription, ItemCost
           FROM tblItems
         </cfquery>
         <cfreturn catQuery>
      </cffunction>
    </cfcomponent>
    

    In the example, the cfreturn tags return the query objects created by the component methods.

  2. Save your work.
  3. Open the corpFind.cfm file, and modify the code so that it appears as follows:
    <cfinvoke component="corpQuery" method="getEmp" returnVariable="empResult">
    <cfdump var=#empResult#>
    

    In the example, the cfinvoke tag's returnVariable attribute specifies the variable scope name that holds the component method results. The cfdump tag displays the contents of the empResult variable.

  4. Open a web browser and browse to the following URL:
    http://localhost/corpFind.cfm
    

    The following figure shows the results:

    Web browser display of corpFind.cfm

Comments