Article
ColdFusion Components - An Introduction
Use and Call Your CFC
So there you have it! You’ve just built your first component and function. But now you need to know how to use and call it. For this we need to create a new page and save it as users.cfml or users.cfm. Once this page is opened, saved, and ready to go, insert the following line at the top of the page, before any HTML code:
<cfinvoke component="cfc.users" method="get_all_users" returnvariable="u"></cfinvoke>
The above line is our cfinvoke tag, which is used to invoke a method within a component. The break down of this is rather simple. The component="cfc.users" tells the server what component you want to grab, and where to find it. As I saved my CFC in a folder named "cfc", I had to use dot notation to tell the server the location, and which file I wanted. If you named your directory "components", your code would read: component="components.users". If you had a more complex directory structure, such as /components/users/general/, your code would resemble this: component="compontents.users.general.users"
The next part, method="get_all_users", tells the server which method we want to use. Finally we need to specify how the returned data will be referred to. For this case we have chosen a simple “u”, as in user, which we’ve specified using returnvariable="u".
Next, we want to create the following bit of HTML and ColdFusion code to output our data:
<table width="100%" border="1" cellspacing="0" cellpadding="3">
<tr>
<td>Users Name</td>
<td>Users Login</td>
<td>Users Email</td>
<td>Users Status</td>
</tr>
<cfoutput query="u">
<tr>
<td>#name#</td>
<td>#login#</td>
<td>#email#</td>
<td>#status#</td>
</tr>
</cfoutput>
</table>
This will output a nice little table with a row of headings for each column in the table, and a new row for each corresponding row/user in the table.
You’ll notice that we used the <cfoutput query=”u”> tag. This allows us to quickly output the data in a query without having to use loops. The CF server will know that it needs to execute the cfoutput tag, and the code it contains, until the query reaches the end of the output.
So there you have it! You’ve successfully created a component and a function, invoked that method in a separate page, and output the data.
It’s my hope that this article has helped you to better understand CFCs and that it has sparked your interest in learning more. This is by no means a complete overview of CFCs -- there are many topics that were hinted at, but not expanded on here. I suggest that you read the documentation found on the Macromedia Website or on your server, and check out the Macromedia Coldfusion DevNet for some great CF and CFC-specific articles. Also if you feel so inclined, drop me a note or comment here with your questions or ideas for future articles.