Accessibility
 
Home / Developer Center / ColdFusion MX Application Developer Center /

ColdFusion Article

Icon or Spacer Icon or Spacer Icon or Spacer
Matt Brown
 
Matt Brown
An easier way to create and consume ColdFusion components and web services with Dreamweaver MX


Macromedia ColdFusion MX has a new set of features for you to create more powerful Internet applications than you ever have before. Chief among these features is the ability to create components and to consume web services. ColdFusion components (CFCs) are ColdFusion files that encapsulate application functionality and make that functionality available to browsers, other applications, Macromedia Flash Players and web services. They provide a simple and flexible way to maintain and reuse your code as you work, and they separate the logic from your pages. Macromedia Dreamweaver MX makes it easy to create and consume components and web services for ColdFusion MX.

 

Table of contents

Prerequisites
Creating a CFC through code view
Using your CFC
Passing variables into your CFC
Creating a CFC with Dreamweaver MX
Testing your CFC
Testing your application
Consuming a web service
Where to get more information on CFCs and web services

In this tutorial, you'll learn how to create simple ColdFusion Components (CFCs) through manual coding in the Dreamweaver MX code view and through the Dreamweaver MX Create Components Dialog. You will see how to consume them, and how to consume a .Net web service.

Web services are similar to CFCs in that they are applications into which you feed data and then receive some information back. They allow you to add functionality to your site without having to create the back end for those pieces of your application. For instance, if you were creating an online store and needed to have instant currency conversions, you could use web services. Or, you may want to be able to tell someone how far they are from your location. Or, you may want to be able to access the Federal Express package tracking system. There are a wide variety of services available for consumption on the web through ColdFusion MX.

Prerequisites
For this tutorial, you are going to need to have the following installed and running on your computer:

Macromedia ColdFusion MX
Dreamweaver MX
The sample data sources that were setup in the ColdFusion MX Administrator during your ColdFusion MX installation. If you aren't running ColdFusion MX on a Windows platform, the installation includes the example database information in a CSV file, so you can import the table structure and data into the database of your choice. This tutorial requires the use of the sample data sources.


Creating a simple CFC through code
The simplest form of a CFC is simply some ColdFusion code that you have abstracted to a separate ColdFusion page, that you can invoke from other ColdFusion pages. One simple application is to create the footer or copyright information for a particular page. You could do this same thing a number of ways in ColdFusion without CFCs, as developers have done in the past, but this is an easy example to apply CFCs.

To start creating a CFC, use the following steps:

1
Create a folder named "myCFC" in your ColdFusion MX webroot. You can either put the CFC and ColdFusion pages in a separate folder, like an asset, or, in the same folder with the group of CFML pages that use the CFC. Regardless, Dreamweaver MX will locate them and make all CFCs in your defined site available to all other CFML pages in the website. You can store CFCs anywhere in your webroot, but it is a best practice to keep them in a separate folder.
2
Open Dreamweaver MX and select File > New.
3
In the New Document dialog, select Dynamic Page from the Category column and ColdFusion Component from the Dynamic Page column. Click Create.
4
Choose Save from the File menu. Save the CFC in the myCFC folder with a name of TestCFC.cfc. Note that the file extension is CFC and not CFM.


In Dreamweaver, view the code. You may need to click Show Code View.

Since you chose "ColdFusion Component" when you chose which type of file to create, the CFC you created has the following code:

 <cfcomponent>
    <cffunction name="myFunction" access="public"  returntype="string">
       <cfargument name="myArgument"  type="string" required="true">
       <cfset myResult="foo">
       <cfreturn myresult>
    </cffunction>
 </cfcomponent> 

Although this has the simplicity of one large nested tag in a file with nothing else in it, CFCs are much more. They can provide web services and can be used in any of your ColdFusion MX and Macromedia Flash MX applications. Read more about how to use CFCs with Macromedia Flash MX and Flash Remoting in the other articles in the ColdFusion MX Application Developer Center.

The cfcomponent tag indicates the CFC much like the HTML tag indicates the beginning and end of an HTML page.

The cffunction tag indicates the functionality of the component. There can be multiple cffunction tags in a single component. When you invoke the CFC from your ColdFusion page, you can call any one of the functions. This is especially useful if you have sets of related functionality when you want to remove to a separate file for maintainability of the code. Inside the cffunction tag, you can process as much ColdFusion code as you like.

The cffunction tag has five attributes. Dreamweaver MX inserts three attributes as a default:

name - The name of the function needs to be unique in the CFC page so that you can call each function individually. There should be no spaces in the name, similar to the way that Javascript should not have spaces in names.
access - This determines who can access the component method by client type. Leave the access set to public which means that any other CFML page on the ColdFusion Server can access the CFC.
returntype - This attribute gives data type validation for returned values. Leave this attribute in your code.


Note: For more information about the cffunction tag in CFCs, refer to the CFML documentation installed with ColdFusion MX.

By default, when you create a CFC in Dreamweaver MX, it adds the cfargument tag, sets a result, and returns the result in a variable.

The cfargument tag informs the function that the CFML page calling the function is passing information to the function. This example will not use the cfargument tag, so you can delete it for now. We are going to talk about how to use that in the next example. Within the cffunction tag, you will use the cfset tag to creates a variable or variables that will hold the function result.

This example will create a date for the CFC to return to the calling CFML page:

1
Open TestCFC.cfc if you don't already have it open in Dreamweaver MX.
2

Change the cffunction name attribute to myDateFunction:

<cffunction name="myDateFunction">

3

Place your cursor before the the following line:

<cfset myResult="foo">

4
Press the Enter key to insert a line.
5

Create a cfset tag with a variable named mydate that creates a date, as follows:

<cfset mydate = CreateODBCDate(now())>

6

Format the date created with the mydate variable in the previous step. Change the cfset for the variable myResult, so that it uses the dateformat() function to format the date:

Change the following:

<cfset myResult="foo">

to the following:

<cfset myResult = DateFormat(mydate, "mmm-dd-yyyy")>

Your function should look like the following:

<cffunction name="myDateFunction" returntype="string">
   <cfset mydate = CreateODBCDate(now())>
   <cfset myResult = DateFormat(mydate, "mmm-dd-yyyy")>
   <cfreturn myResult>
</cffunction>

7
Save the TestCFC.cfc file.

You could test this CFC now, but before you do, you'll add another function to the CFC. By doing this, you can call either or both functions from the ColdFusion calling page:

1
After the closing cffunction tag, press return to insert a new line.
2
Start typing <cffunction>. As you type the tag, Dreamweaver's auto-complete feature displays tags for you to choose from. When you have typed "<cffun" you can see that the auto-complete feature selects the <cffunction> tag. Press Enter to select the cffunction tag and display it as code on your page.
3
Note that the cffunction tag is not complete. There is no closing bracket for it. This indicates that attribute are missing. Press the space bar in the cffunction tag, and notice that tag insight displays five attribute choices appropriate for the cffunction tag. Press the down arrow on your keypad to select an attribute to enter for the tag. In this case, select the name attribute and click Enter. Note that the name="" attribute has been inserted in the cffunction tag, and your cursor is located between the quotes for name attribute value.
4
Name your new function, "myTextFunction" and place your cursor after the closing quotation.
5
Press the space bar and select the returntype attribute from the attribute list. Press enter and insert the returntype attribute into the cffunction tag. Notice that your cursor is located between the quotes for the returntype attribute value. Select "string" for the returntype attribute value.
6
Type a closing bracket ">" to close the cffunction tag. This will close the opening cffunction tag, and insert a closing </cffunction> tag.
7
Place your cursor between the <cffunction> and </cffunction> tags to enter your new function. Press return several times to create blank lines.
8
In the blank lines, type the following:
<b>The date is: </b>
9
Press return.Your function should look like the following snippet:
<cffunction name="myTextFunction" returntype="string"> 
 <b>The date is: </b> 
</cffunction> 
10
Save your TestCFC.cfc file.

Using your CFC
Now that you have created a simple CFC with a couple of functions, you are ready to use it. Calling a CFC is easy. In the ColdFusion page where you want to call the CFC, use the cfinvoke tag. In the cfinvoke tag, you can call individual functions inside of the CFC, and you can specify the name of the return variable that is returned from the CFC.

1
Ensure that you have a ColdFusion Site defined in Dreamweaver MX on your machine.
2
Create a new CFML page in Dreamweaver MX. Select File > New. Select Dynamic Page in the Category column, and ColdFusion in the Dynamic Page column.  
3
Save your file as Test.cfm
4
If you are not in Code view mode, switch to code view. Note that you could insert CFCs into your page in the Design view mode, but the code will not visually display. This makes it difficult to call the CFC within your CFML code. It is preferable to create your CFC in the Code View mode.
5
From the Window Menu, select Components (or click Ctrl-F7) or click on the component tab in the palette if it is visible in your workspace already.
6 If you don't see any components listed, click the refresh button and the components will appear.
Component Explorer
7
Under the entry for TestCFC, two functions appear. The first function, myDateFunction(), gets the date, and the second function, myTextFunction(), prints "The date is: ".
8
Select myTextFunction(), and click on the insert button to insert the call to this function in your ColdFusion Page.
You should see code that looks like this:

<cfinvoke
component="myCFC.TestCFC"
method="myTextFunction"
> </cfinvoke>
9
Save your page as test.cfm and press F12 to preview in the browser to test your page.
10
The following displays in your browser, "The date is: "


You have successfully called a CFC from your page. You have called some content that does not reside in the calling page. This is simple because the information is in a separate file. When test.cfm page is processed, the ColdFusion Application Server processes the myTextFunction() function in TestCFC.cfc and inserts it in the calling page (test.cfm), where the <cfinvoke> tag is located.

The other function in TestCFC, myDateFunction(), requires a little more work to display because it creates the date. This is the most common sort of CFC. Typically you will want your CFC to perform a function, access the result, and present the information on your calling page. The instructions for doing so are below:

1
Open test.cfm page in Dreamweaver MX.
2
Switch to Code view if you aren't there already.
3
Enter a few blank lines after the closing cfinvoke tag.
4
In the Dreamweaver Components Palette, click Refresh. Select myDateFunction() from the TestCFC in the Components panel and click Insert.

The following code appears in test.cfm:

<cfinvoke
component="myCFC.TestCFC"
method="myDateFunction"
returnvariable="myDateFunctionRet"
>
</cfinvoke>
5
Notice that the myDateFunction() function has an additional attribute, named returnvariable. The returnvariable stores the result of the function.
6
In Code view, insert a few blank lines after the second </cfinvoke> tag, and type the following line:
<cfoutput>#myDateFunctionRet#</cfoutput>

This prints the information returned by the function in the user's browser.
7
The whole file should look like the following:
<html>
 <head>
 <title>Untitled Document</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 </head> 
 <body>
      <cfinvoke 
         component="myCFC.TestCFC"
         method="myTextFunction"
         > 
      </cfinvoke>
      <cfinvoke 
         component="myCFC.TestCFC"
         method="myDateFunction"
         returnvariable="myDateFunctionRet"
         >
      </cfinvoke>
      <cfoutput>#myDateFunctionRet#</cfoutput>
 </body>
</html>
8 Save the page and press the F12 key to preview your page in the browser. Your browser should display something similar to the following:
The date should display


Passing Variables into a CFC
Once you have created a simple CFC, you may want to create a CFC that provides a more functionality. In this example, you'll build a CFC that finds an employee and lists the results a few different ways. This CFC will enable you to to save find and search capabilities on any number of pages, but only generate the code in one place. If you need to change the code later, you only need to change it in one place, rather than on numerous ColdFusion pages. Additionally, you can access the functionality from other clients, such as Macromedia Flash MX through Macromedia Flash Remoting.

In the previous steps, you manually created a CFC. This time, you'll create them using the new Components and Web Services interface in Dreamweaver MX.

Creating the CFC in Dreamweaver MX

1
In Dreamweaver MX ensure that you are located in the ColdFusion MX webroot Site Definition.
2
Click on the Components tab. If you can't see the Components tab, go to the Window menu and select Components.
3
In the Components tab, click on the "+" sign to create a new CFC through the Create Component Dialog.
4
In the dialog, for the Display Name, type: "FindEmployee". This is the component name that you'll reference when you call the CFC.
5
In the Name field, type: "FindEmployee". This will be the name of the file in the file system.
6
For the Component Directory, it isn't necessary to pick any one place. Both Dreamweaver MX and ColdFusion MX search for all the components in your site and make those available to you when you author anything in a ColdFusion site. However, it is a best practice to keep them all in the same place, so select the myCFC directory.
7 Your screen should have the following entries:
  Create FindEmployee Component dialog

Please note that the Component Directory location will be different based on where you created your myCFC folder.

8
Leave the other fields empty. For more information on these fields, refer to the ColdFusion MX documentation.
9
Click on Function under the Section area. From the Function view, click the "+" sign to add a function.
10
Name the function "FindEmployeeSort." Set the access to "remote" and set the return type to "query." You can select several returntypes depending on what you wish to return to the calling CFML page.
11
Add the FindEmployeeSort function
  Click OK. This creates the CFC.

If you were to look at the code for the CFC, it would have the following code:
<!--- Generated by Dreamweaver MX 6.0.1681 [en] (Win32) - Tue Apr 09 18:51:44   
      GMT-0700 (Pacific Daylight Time) 2002 --->
  <cfcomponent displayName="FindEmployee">
     <cffunction name="FindEmployeeSort" 
                 access="remote" 
                 returnType="query"    
                 output="false">
     </cffunction>
  </cfcomponent>

Dreamweaver MX created the necessary framework for the CFC. Now you're ready to add code to the function, and to make it do something. In this case, you'll create a query that you can access in a few different ways. First, you'll call all the employee's information from the database and sort it. Second, you'll want to create a function where you can search for an employee by name. By using a CFC, you can call the query from any ColdFusion pages or application on your ColdFusion server. You can even add more features to the query over time, if necessary.


1
Open FindEmployee.cfc in Code view in Dreamweaver MX.
2
Enter a few blank lines after the opening cffunction tag.
3
Type in the following code on the blank lines:
<cfquery name="employeeQuery" datasource="CompanyInfo">
   SELECT * FROM Employee 
   <cfif IsDefined('LastName')>
      WHERE LastName LIKE '%#form.LastName#%'
   </cfif>
   ORDER BY LastName ASC
</cfquery>

This query selects all of the information in the Employee table from the CompanyInfo data source. The CompanyInfo data source is part of the example applications that were installed with your copy of ColdFusion MX. The query checks whether a value called LastName was passed into the ColdFusion page from a form on the referring page.

If the referring page passed the form.LastName variable, the query uses the WHERE clause. The WHERE clause filters the query results, returning any last name that matches a combination of letters passed in the form.LastName variable. If the referring page does not pass form.LastName, the query returns a recordset for the employees, and sorts them in ascending order by their last name.

There are several ways to pass variables and values into a CFC. This way is the simplest. If you want to find out more about the other ways to pass information into a CFC, refer to the ColdFusion documentation.

4

Now you'll specify what the CFC returns to your ColdFusion page. Modify the cfreturn tag after the query so that before the closing cffunction tag to:

<cfreturn employeeQuery />

The cfreturn tag will return the employeeQuery so that you can loop through the returned data, as if the query were on a regular ColdFusion page.

5

Your FindEmployee.cfc should look like the following:

<cfcomponent displayName="FindEmployee" >
   <cffunction name="FindEmployeeSort" access="remote"          
               returnType="query" output="false">
      
       <!--- FindEmployeeSort body --->
       <cfquery name="employeeQuery" datasource="CompanyInfo">
           Select * from Employee
          <cfif isdefined('form.LastName')>
           WHERE LastName LIKE '%#form.LastName#%'
          </cfif>
           Order by LastName asc 
        </cfquery>
         
        <cfreturn employeeQuery />
         
    </cffunction>
</cfcomponent>
6

Save FindEmployee.cfc.


Testing your CFC

To test the CFC, create an HTML form and a CFML action page. Your CFML action page will call the CFC.

Create an HTML form where the end-user will enter a search criteria (in this case, a last name). Create a file named employeename1.cfm and save it in your ColdFusion webroot. The file should have the following code:

 <html>
   <head>
   <title>employeename1</title>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   </head>
<body>
   <!---First form: This form submits the end-user's search criteria--->
   <form name="form1" method="post" action="employeename2.cfm">
   <p>Search for employee: 
   <input type="text" name="LastName">
   </p>
   <p>
   <input type="submit" name="Submit" value="Submit">
   </p>
   </form>
<!---Second form: This form submits no search criteria--->
   <form name="form2" method="post" action="employeename2.cfm">
   <p>Return all employees: <input type="submit" name="Submit2"
      value="Submit"></p>
   </form>
   
   </body>
   </html>

Now that you have created a form that passes information to your CFML action page (and your CFC), you'll create the action page that invokes the CFC and displays the result.

1
Select File > New. In the New Document Dialog Box, select Dynamic Page from the Category column and ColdFusion from the Dynamic Page column and click Create.
2
Save the file to the ColdFusion MX webroot. Name the file employeename2.cfm.
3
From the Components palette, click Refresh and find the FindEmployee.cfc you created. Click the "+" sign for the CFC. The functions for the CFC appear.
4
Click the FindEmployeeSort function and drag it into the body of your employeename2.cfm file.

Your page should look like the following:
 <html>
 <head>
 <title>Untitled Document</title>
        
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 </head> 
 <body>
         <cfinvoke 
         component="myCFC.FindEmployee" 
         method="FindEmployeeSort"
         returnvariable="FindEmployeeSortRet">
         </cfinvoke>
</body>
</html> 
5
Save employeename2.cfm.

Now, you have a page that calls the CFC, and the CFC works, but you'll need to add code to display the results that are returned. Add the code in the Design view mode or the Code view mode, whichever you prefer. For this example, it is preferable to add the changes within the Code view mode.

1
Insert a few blank lines after the closing cfinvoke tag. Enter the following:

<cfoutput query="FindEmployeeSortRet">#FirstName# #LastName#<br></cfoutput>
2
Save employeename2.cfm.


Testing your application
Now you have a small ColdFusion application and you are ready to test it. Browse to http://localhost:8500/employeename1.cfm (please change this URL based on the port number where you're running ColdFusion MX, and where your file, employeename1.cfm, is located in your ColdFusion MX webroot).

The following form displays in your browser:

Form for testing your CFC


Click the second Submit button, next to "Return all employees." The action page displays an entire list of people from the database. Enter"al" in the form field, and click the first Submit button. The action page displays only people with "al" in their last name.

This one CFC allows you to get as many different result sets as you like. The advantage is that you can keep all of your database logic in one place in your application and not on each individual ColdFusion page. If you need to change the query, or add new functionality, you do it all in one file instead of several ColdFusion pages.

Consuming a web service
Web services are similar to CFCs in that they are encapsulated functionality that you can access in your website. For this example, you'll create a currency exchange calculator that you can use in your pages without having to create the code or maintain it by getting the daily exchange rates for hundreds of currencies. Simply create a form and pass the variables to a web service, and then use the cfoutput tag to insert the returned values into your page.

Before you start, ensure that you have a live connection to the web. It is necessary to consume a web service.

1
Create a new ColdFusion document and save it as currencycalculator.cfm in your ColdFusion MX webroot.
2
Ensure that the Component Palette is visible in Dreamweaver MX.
3
In the Component tab, select Web Services from the pop-up menu.This panel lists all of the web services to which you have subscribed and can insert.
4 Now you will subscribe to a web service. Click on the plus button. In the Add Using WSDL dialog box, set the Proxy Generator to ColdFusion MX if it is not already selected. Click the globe icon and select the xMethods UDDI site from the pop-up menu.
Add Using WSDL dialog
5

This will open the xMethods website. At the xMethods website, you can choose from many services. For this example, select Currency Exchange Rate from xmethods.net. It is near the bottom of the list.

When you click the link in the list, it displays the service's details and instructions on using it.
In this case, there is a lot of information, including what currencies are supported. If you were going to provide this as an actual service for your end user, you might include the currency types in drop-down lists to make it easy to select the currency conversion choices. For this example, look for the WSDL URL, which is highlighted in yellow.

6

A URL is listed at the end of the WSDL line on the page in yellow highlighting.

http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl

Copy that and paste it in the "URL field in the WSDL file" in the Add Using WSDL dialog in Dreamweaver MX. ColdFusion uses this URL to use the web service.

7
Click OK. This adds the new Web Service to the Components palette.
8
Click on the CurrencyExchangeService entry and drag it to your page in the body.
9
Your file should look like the following:
 
<html>
 <head>
 <title>Untitled Document</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 </head> 
<body>
   <cfinvoke 
     webservice="http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl"
     method="getRate"
     returnvariable="aRate">
         <cfinvokeargument name="country1" value="enter_value_here"/>
         <cfinvokeargument name="country2" value="enter_value_here"/>
   </cfinvoke>
</body>
</html>
10

Save currencycalculator.cfm.

Now that you have invoked the service, you need to pass values for the cfinvokeargument tag, so the service has data to process in the currency conversion. Below, you'll create a way to display the rate in the ColdFusion page.

1
In currencycalculator, switch to Code view. In the first cfinvokeargument tag, replace "enter_value_here" with "#currency1#." In the second cfinvokearguments tag, replace the "enter_value_here" with "#currency2#." This passes the currencies to the web service that you're going to pass from the form calling this page.
2 Enter a few blank lines after the closing cfinvoke tag and type the following:
<cfoutput>The exchange rate between #currency1#
	       and #currency2# is #aRate#</cfoutput>
3
Your page should look like the following:
     <html>
     <head>
     <title>Untitled Document</title>
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
     </head> 
	 <body>
       <cfinvoke 
       webservice="http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl"
       method="getRate"
       returnvariable="aRate">
       <cfinvokeargument name="country1" value="#currency1#"/>
       <cfinvokeargument name="country2" value="#currency2#"/>
       </cfinvoke>
<cfoutput>The exchange rate between #currency1# and #currency2#
	        is #aRate#</cfoutput>
</body>
       </html>
4
Save currencycalculator.cfm.

You have the page that references the web service and displays the return results. Now, create an HTML form that calls currencycalculator.cfm. Ensure that your field names in the HTML form match the values in the cfinvokeargument tags. Additionally, set the form action to go to currencycalculator.cfm. Your HTML form would have the following code:

<html>
  <head>
  <title>Untitled Document</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  </head>

<body>
   <form name="form1" method="post" action="currencycalculator.cfm">
   <p>Currency 1: 
   <input type="text" name="currency1">
   <br>
   Currency 2: 
   <input type="text" name="currency2">
   </p>
   <p>
   <input type="submit" name="Submit" value="Submit">
   </p>
   </form>
</body>
</html>

Browse your form from a browser. For currency 1, enter "newzealand," and for currency 2, enter "usa." Click Submit. Your form passes the values for currency1 and currency2 to currencycalculator.cfm. Currencycalculator.cfm invokes the web service and receives the form data. The web service processes and returns a number in the variable named "aRate." Currencycalculator.cfm displays the currencies and rate.

You could use additional math functions and operations in ColdFusion to easily convert the money amounts instead of returning the rate for different countries.

Try out your currency conversion application with a few of the following countries for the currencies, such as china, germany, france, dijibouti, swaziland and canada.

Where to get more information about CFCs and web services
You can get a lot of information about CFCs on the Macromedia DevNet. Additionally, the ColdFusion MX documentation, which is installed by default, also has information to help you get started with developing ColdFusion MX applications.

For more information on web services, there are hundreds of resources. Some preferable resources are as follows:

www.xmethods.net XMethods has many publicly available web services listed.
www-3.ibm.com/services/uddi/protect/home.jsp IBM's WebServices site. Requires free registration.
/test.uddi.microsoft.com/default.aspx Microsoft's web services site.
www.webservices.org/ A great resource for web services information and tutorials.
 

About the author
Matt Brown was formerly a Community Manager for Macromedia. He has served as technical editor for more than a dozen software books. Matt has taught courses at Foothill College and San Francisco State's Multimedia Studies Program and is a regular speaker at conferences and User Groups.