System information
Exercise 4: Writing structured, reusable code 65
Copying the query to the CFC
To copy the query to the CFC, you copy the CFML to the CFC, between the opening and
closing
cffunction tags.
To copy the query to the CFC:
1.
Highlight the following code on the triplisting.cfm page:
<cfquery name="TripList" datasource="CompassTravel">
SELECT trips.tripName FROM trips
</cfquery>
2.
Cut the highlighted code and copy it to the gettrips.cfc page so that it appears as follows:
<cfcomponent displayName="Get Trips" hint="Get trip information">
<cffunction name="basicList"
displayName="List all trips" hint="List trips in same order as in table"
access="public" returnType="query" output="false">
<cfquery name="TripList" datasource="CompassTravel">
SELECT trips.tripName FROM trips
</cfquery>
<cfreturn>
</cffunction>
</cfcomponent>
3.
Modify the code by adding the following text so that the method returns the results of the query
to the triplisting.cfm page:
<cfreturn TripList>
4.
Save the gettrips.cfc file.
Calling the query method
To perform the query that is now in a method in a ColdFusion component, you have to call
(invoke) the method. To do so, you can use the
cfinvoke tag. Within the cfinvoke tag, you
specify the name of the ColdFusion component, the method to call, and the query to return to
the calling page. The name of the component includes the package,
"cfdocs.getting_started.my_app.components." The package looks very similar to the path, except
that it contains periods instead of slashes. Like a path, it specifies the location of the component.
To invoke the method:
1.
Go to the top of the triplisting.cfm file.
2.
Enter the following code, or do the steps listed in the “Let Dreamweaver do it” section.
<cfinvoke
component="cfdocs.getting_started.my_app.components.gettrips"
method="basicList"
returnvariable="TripList">
</cfinvoke>
3.
Save the file.
4.
View the triplisting.cfm page in a browser and notice that the page lists the trip names, just as
it did previously.