ColdFusion MX 7 Getting Started Experience

AMInternet and Web Development

Nov 30, 2011 (2 years and 5 months ago)

896 views

This document introduces you to the community application built for the Macromedia ColdFusion MX 7 Getting Started Experience. You will browse the application and also explore the code. All code pages are heavily commented to let you easily discern what code you can reuse in your own applications. As you evaluate the power of ColdFusion as a development tool, it will become clear why ColdFusion MX 7 is the easiest, fastest, and smartest tool for building Internet-based applications.

ColdFusion MX 7 Getting Started Experience – Community Application Features Page 1 of 22

ColdFusion MX 7 Getting Started Experience – Community Application Features
Purpose
This document introduces you to the community application built for the Macromedia ColdFusion MX 7 Getting Started
Experience. You will browse the application and also explore the code. All code pages are heavily commented to let you
easily discern what code you can reuse in your own applications.

As you evaluate the power of ColdFusion as a development tool, it will become clear why ColdFusion MX 7 is the easiest,
fastest, and smartest tool for building Internet-based applications.
About the application
The Blackstone Book Club meets once a week at a book store in Denver, Colorado. To keep the members informed of
upcoming events and meetings, the website lists scheduled meeting times and lets members access some information
using their mobile telephones. Members can create their own blogs and download coupons from participating local
retailers. The website is maintained by the site administrator, or super user, who can update all areas of the site, including
the site-wide searching features and rotating advertisements that entice users to join the club.


Figure 1. Home page for the
Blackstone Book Club
community application


ColdFusion features in the Blackstone Book Club community application
The following is a list of ColdFusion features implemented in this application:
• User-specific content based on login
• Enhanced application framework
• Verity category searching
• Mobile phone gateway
• Dynamic document generation
• Enhanced Flash, XML, and HTML forms
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 2 of 22

How to use this document
Browse the features and explore the ColdFusion code using the directions in this document. Each feature is explored in a
browser, and then the code files are evaluated.

Before you explore the code of these applications, you should first review the animated slideshows in the ColdFusion and
Dreamweaver Development Overview section and the tutorial in the Steps for Building Dynamic Pages section of the
ColdFusion MX 7 Getting Started Experience website. These sections introduce new ColdFusion developers to the
development environment and to ColdFusion code, including ColdFusion components (CFCs), which this application uses
extensively.
Using Dreamweaver MX 2004 to explore code
Dreamweaver MX 2004 is recommended but not required to explore the code in this application. You can download a trial
version from the Macromedia website (http://www.macromedia.com/downloads).

Your Dreamweaver site should use the following setup information:

Site name:
Community Book Club
Server technology:
ColdFusion
Edit and test locally:
Yes
File storage location:
C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\
Test URL:
http://127.0.0.1:8500/CFIDE/gettingstarted/community/

These settings assume that you are using the built-in web server installed with ColdFusion MX 7.

For more information about configuring Dreamweaver sites and understanding these settings, see the tutorial in the Steps
for Building Dynamic Pages section of the ColdFusion MX 7 Getting Started Experience website.
User-specific content based on login
Public users to the Blackstone Book Club website can browse the reading list, member blogs, and sponsor information,
but they cannot get specific meeting information or download coupons. To access this information, they must join the book
club. Figures 2 and 3 depict the Reading List and Member Perks pages. The messages in red on the pages direct users
to log in for more detailed information.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 3 of 22


Figure 2. Public user view of
Reading List page





Figure 3. Public user view of
the Member Perks page



Book club members can log in with an e-mail address and password. Members can access more information on the site,
but they are not allowed to manage the site content.
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 4 of 22


To log in as a member, use the following information:

e-mail: user@demodata.com
password: demo

When you log in as a member, you can see additional information. Figure 4 shows the Reading List page with host and
meeting details. Notice that the login prompt on the left side of the screen was replaced with sponsor advertisements.


Figure 4. Member view of
the Reading List page



The Member Perks page also changes after a user logs in. Figure 5 shows an additional link for downloading coupons.


Figure 5. Member view of
the Member Perks page



Only the site administrator can manage site content. To log in as the administrator, click the log out link, and then log back
in using the following information:
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 5 of 22


e-mail: super@demodata.com
password: demo

When you log in as administrator, you can access a red management menu bar as Figure 6 shows:


Figure 6. Administrative
management menu



You can select from the toolbar to access management options for polls, members, sponsors, perks, meetings, authors,
and searching. The application displays user-specific information that is based on the user’s login status. The e-mail and
password that the user provides are validated against the database. Then the user’s role, which is stored in the database,
is retrieved and managed by the application using the cfloginuser tag, as the following example shows. (You can also
view this code on lines 334-371 in the bookclub.cfc file, which is in the
C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\extensions\components\ directory.)

<cfif validateUser.isAdmin>
<cfloginuser name="#formdata.email#" password="#formdata.password#" roles="Admin">
<cfelse>
<cfloginuser name="#formdata.email#" password="#formdata.password#" roles="Member">
</cfif>

Note: Validated users are assigned the Member or Admin role. Public users are not validated against the database.

The isUserInRole() function is used to distinguish which content users can see while logged in. As mentioned
previously, administrator users can see an additional menu. The following code, on lines 20-24 of the header.cfm file in
the C:\CFusionMX7\CFIDE\gettingstarted\community\webroot\shared directory, determine this menu:

<!--- menu --->
<cfif not isUserInRole("Admin")>
<cfinclude template="menubanner.cfm">
<cfelse>
<cfinclude template="adminmenubanner.cfm">
</cfif>

For more examples of the isUserInRole() function in action, view the code for the other areas of the site.
Enhanced application framework
You structure ColdFusion applications according to an application framework, which organizes the application files and
provides common services to the CFML pages in the application. ColdFusion MX 7 provides a new application framework
tool, Application.cfc, which significantly expands on the features that were provided in previous releases. The
Application.cfc file sets application characteristics, such as the application name. More importantly, the file lets you specify
methods that ColdFusion automatically calls each time events in the application lifecycle occur, including application,
session, and request startup and shutdown. ColdFusion MX 7 automatically applies the Application.cfc settings and
methods to all ColdFusion pages in the file's directory or a subdirectory.

Because the methods in Application.cfc automatically execute when each corresponding event occurs, this new tool
provides substantially more power and flexibility for structuring applications than was available in ColdFusion MX 6.1 and
earlier releases.
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 6 of 22

What happens to the Application.cfm and cfapplication tag?
Although Macromedia recommends that you use Application.cfc for new applications, Application.cfm,
OnRequestEnd.cfm, and the cfapplication tag are still supported. If both Application.cfm and Application.cfc are present,
the Application.cfc file takes precedence.


The Application.cfc file
The Application.cfc file is triggered when an application, session, or request starts or stops, and when an application
encounters an exception. The Application.cfc for the Blackstone Book Club community sample application is in the
C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\webroot directory.

Notice that lines 2-8 of the Application.cfc file set attributes that you would commonly see in the cfapplication tag.
However, this tag is not necessary when using the Application.cfc file, so you should specify its associated attributes by
using the this scope.

The following example shows lines 2-8 in the Application.cfc file:

<cfscript>
this.name="BookClub";
this.sessionmanagement=true;
this.setclientcookies=true;
this.applicationtimeout=1*60*60;
this.scriptProtect="all";
</cfscript>

The events that trigger the Application.cfc are handled by the onApplicationStart, onApplicationEnd,
onRequestStart, onRequest, onRequestEnd, onSessionStart, and onSessionEnd methods. The Blackstone
Book Club website uses only the OnRequestStart and OnRequest methods, which are discussed in the following
sections. For more information about Application.cfc and its methods, see the general ColdFusion MX 7 documentation.
The onRequestStart method

The onRequestStart method is called at the beginning of a request. The method returns true or false. If false, the
request is rejected; otherwise, the request continues uninterrupted. In this application, the onRequestStart method
(lines 10-78 in Application.cfc) verifies that the application is on the local computer. If it is not, the request is halted and a
message is displayed. The following example shows lines 13-16:

<cfif cgi.remote_addr is "" or not (CGI.REMOTE_ADDR is "localhost" or CGI.REMOTE_ADDR is
"127.0.0.1")>
<cfscript>WriteOutPut("This sample application is restricted to local
access.");</cfscript>
<cfreturn false>
</cfif>

The OnRequestStart method also sets request variables that are used throughout the application, as the following lines
19-59 show:

<!--- set global values --->
<cfset request.bookImagePath="images/books/">
<cfset request.sponsorImagePath="images/sponsor/">

You can include any user-defined functions (UDFs) or other necessary files in the method using the cfinclude tag, as
on line 70 in the Application.cfc file:

<!--- user defined functions --->
<cfinclude template="shared/udf.cfm">
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 7 of 22


The application includes the validation error page for administrator (Admin) users in the onRequestStart method on
lines 72-75:

<cfif isUserInRole("Admin")>
<!--- error template for server-validation validation --->
<cferror type="validation" template="shared/error_validation.cfm">
</cfif>

By setting these options in the onRequestStart method, you can ensure that all pages in your application have access
to these features.
The OnRequest method
The onRequest method (lines 80-93) is called to intercept the request of the target page. You can modify or overwrite the
request, so it is the perfect location to perform user authentication.

In the following code, the name of the requested page is automatically passed to the method as a string. If the user has
logged out or the session is expired, a cflocation call sends the user to the home page, and the page that the user
requested is never accessed. However, if the user is properly authenticated, a cfinclude call displays the requested
page as expected.

<cffunction name="onRequest">
<cfargument name="targetTemplate" type="String" required="true" />

<!--- log user out if they click 'logout' or if their session has expired --->
<cfif isDefined("url.logout") or (len(getAuthUser()) and not
isDefined("session.fullname"))>
<cfset structClear(session)>
<cflogout>
<cfif isDefined("url.logout")>
<cflocation url="index.cfm" addtoken="yes">
</cfif>
</cfif>

<cfinclude template="#arguments.targetTemplate#">
</cffunction>

Using the onRequest method, you can customize which pages are displayed, based on business rules.
Verity category searching
In ColdFusion MX 7, Macromedia includes the Verity K2 Server search technology. The integration of this tool with
ColdFusion MX allows ColdFusion developers to use the new Verity search features, such as category searching,
keyword highlighting, and suggestions.

Figure 7 shows the Search page for the Blackstone Book Club. Using this page, anyone can search through book
descriptions to locate books related to the book club.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 8 of 22


Figure 7. Search the book
descriptions


You can also constrain search results to categories of information. For instance, the Genre drop-down list lets the user
search based on specified genres. This feature uses the categories feature of Verity, as Figure 8 shows:


Figure 8. Search by Verity
categories



After the Verity collection is created, the administrator occasionally has to update it as more books are added to the
system. The administrator can access this feature by selecting the Search menu option, as Figure 9 shows:

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 9 of 22


Figure 9. Search
Administration page



Creating and indexing collections can be handled through the ColdFusion MX Administrator, but it isn’t always expedient
to give your users access to this interface. In the Blackstone Book Club application, creating and indexing collections are
done programmatically using the cfcollection and cfindex tags in the admin_search.cfm (in the
C:\CFusionMX7\CFIDE\gettingstarted\community\webroot directory) and VeritySearch.cfc (in the
C:\CFusionMX7\CFIDE\gettingstarted\community\extensions\components directory) pages.

The createCollection method (lines 8-33 in VeritySearch.cfc) names and creates the collection on the server, as well
as, repairs or deletes it. To use categories in your search, set the categories attribute to yes in the cfcollection
tag.

<cfcollection
collection="#arguments.collectionName#"
action="#arguments.action#"
path="#arguments.collectionPath#"
categories="yes" />

The method is called in admin_search.cfm, lines 19-23:

<cfinvoke component="#cfcSearch#" method="createCollection"
returnvariable="isSuccessful">
<cfinvokeargument name="action" value="#form.submit#" />
<cfinvokeargument name="collectionName" value="#request.collectionName#" />
<cfinvokeargument name="collectionPath" value="#request.collectionPath#" />
</cfinvoke>

After the collection is created, it must be populated with data, or indexed. The indexCollection method (lines 35-68 in
VeritySearch.cfc) refreshes, purges, or updates the collection. Refresh clears all data, and then adds new data to the
collection; purge removes all data from the collection; update adds new data to the collection, without removing old
data.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 10 of 22

Verity collections can be populated with information from documents or databases. In the Blackstone Book Club searching
feature, data from a database is included in the collection.

When you use a query to index the collection, set the type attribute to custom. The query primary key, bookID, was
used as the index key, and other query fields were used for the title, custom1, custom2, and body attributes. The
category attribute is populated from the query’s genre column (Fiction and Non-Fiction).

Note: You cannot use categories unless you set the category attribute to yes when you created the collection.

<cfindex
action="#arguments.action#"
collection="#arguments.collectionName#"
query="books"
type="custom"
key="bookID"
title="title"
custom1="firstname"
custom2="lastName"
category="genre"
body="firstname,lastname,bookdescription,bio,title,genre" />

The indexCollection method is called from admin_search.cfm, lines 32-36:

<cfinvoke component="#cfcSearch#" method="indexCollection" returnvariable="isSuccessful">
<cfinvokeargument name="action" value="#form.submit2#" />
<cfinvokeargument name="collectionName" value="#request.collectionName#" />
<cfinvokeargument name="dsn" value="#request.dsn#" />
</cfinvoke>

Now that the collection is created and indexed, it is available to be searched. The searchCollection method (lines 70-
108 of VeritySearch.cfc) returns the search results.

The cfsearch tag includes the new contextHighLightBegin and contextHighlightEnd attributes. The HTML
tags set in these attributes are used to surround the search term. For instance, if contextHighLightBegin is set to
<b> and contextHighlightEnd is set to </b>, then the search term is bold in the search results.

The cfsearch tag also includes the new category, suggestions, and status attributes. The category attribute
directs Verity to only search a specific category for results. A list of categories can be passed search multiple categories.

The suggestions attribute directs Verity to offer keyword suggestions only when certain criteria are met. You can set
the attribute value to always to offer suggestions on every search, to an integer to only offer suggestions when the
record result does not meet the number of records returned, or to never to suppress offer suggestions.

The status attribute names the structure that holds suggestion information. The name attribute names the query that
returns the results from the search.

The following code illustrates how all of these features are integrated during a search of the collection.

<cfsearch
collection="#arguments.collectionName#"
criteria="#arguments.criteria#"
suggestions="always"
contextHighlightBegin="<b>"
contextHighlightEnd="</b>"
name="results"
maxrows="#arguments.maxRows#"
status="info"
category="#arguments.category#" />

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 11 of 22

Because both results and suggestions will be passed back to the calling page, a container structure is used to hold the
result query object and the suggestions structure object. Verity may not always have suggestions; therefore the
suggestion structure is tested before it is added to the container structure.

<!--- put results in structure --->
<cfset status.result=results>

<cfif not structIsEmpty(info)>
<cfset status.info=info>
</cfif>

<cfreturn status />

You can use the getCollectionCategories method (lines 120-129 in VeritySearch.cfc) to let users search certain
categories; the method also provides a structure of categories that the collection contains. The name attribute names the
structure that contains the categories, as in the following code:

<cfcollection collection="#arguments.collectionName#" action="categorylist"
name="mycategorylist" />

Lines 44-57 in search.cfm display the category list as a select box by looping over the structure using a collection loop.
The first option lists all the categories.

<!--- only show if there are categories --->
<cfif not structIsEmpty(catlist) and not structIsEmpty(catlist.categories)>
<cfselect id="cat" title="Genre" name="category" label="Genre" size="1" >
<cfoutput>
<option value="#structKeyList(catlist.categories)#">All Genres</option>

<cfloop collection="#catlist.categories#" item="x">
<option value="#x#">#x#</option>
</cfloop>
</cfoutput>
</cfselect>
<cfelse>
<cfinput name="category" value="" type="hidden">
</cfif>

Lines 68-75 in search.cfm search the collection by calling the searchCollection method, as follows:

<cfinvoke component="#cfcSearch#" method="searchCollection" returnvariable="results">
<cfinvokeargument name="criteria" value="#form.criteria#" />
<cfinvokeargument name="maxrows" value="#form.maxrows#" />
<cfinvokeargument name="collectionName" value="#request.collectionName#" />
<cfif len(form.category)>
<cfinvokeargument name="category" value="#form.category#" />
</cfif>
</cfinvoke>

Lines 77-82 in search.cfm display the results. The search results, in this case, are returned in a container structure.

<!--- get query out of structure --->
<cfif not structIsEmpty(results)>
<cfset results=results.result>
<cfelse>
<cfset results="">
</cfif>

Lines 84-108 display the search results:

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 12 of 22

<cfif isquery(results) and results.recordcount>
<strong>Results - <cfoutput>#results.recordcount#</cfoutput> records</strong><hr
size="1" />
<table cellspacing="0" cellpadding="5" border="0" width="95%" align="center">
<cfoutput query="results">
<tr>
<td scope="row">
<a href="author_spotlight.cfm?authorID=#key#">#title# by
#custom1# #custom2#</a><br><br>
<p>#context#</p>
</td>
</tr>
</cfoutput>
</table>
<cfelse>
<cfif isDefined("results.info.suggestedQuery")>
You may have better luck with these search terms:
<p><cfoutput>#results.info.suggestedQuery#</cfoutput></p>
<cfelse>
<div align="center">
Sorry, there were no book entries that matched your query. <br>
Please try again.
</div>
</cfif>
</cfif>
Mobile phone gateway
ColdFusion developers can now extend their applications using event gateways in ColdFusion MX 7. Event gateways and
related sample code are discussed in great detail in the ColdFusion documentation. This document focuses on the SMS
gateway, which allows ColdFusion applications to communicate with wireless devices such as cell phones, PDAs, and
other hand-held devices.

The Blackstone Book Club administrator wants to make it easy for members to quickly access book lists and meeting
dates even when they are not at their computers. Using the SMS gateway, members can call a dedicated number, which
guides them through the steps for accessing this information. To test the application, you can use the SMS test server and
a phone simulator that come with ColdFusion MX 7.

To test the notification application:
1. In the ColdFusion MX Administrator, select Event Gateways > Settings.
2. Click the Start SMS Test Server button.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 13 of 22


Figure 10. Start the SMS
Test server



3. Select Event Gateways > Gateway Instances.
4. Start the Book Club - 5551212 event gateway by clicking the green play button (third button from the left in the
Actions column). If the Status does not say Running after a few seconds, click Refresh to check that the server
started.


Figure 11. Start the Book
Club event gateway



5. To start the SMS phone simulator, select Start > Program > Macromedia > ColdFusion MX 7 > SMS Client
Applications. The simulator is preconfigured by default to call the default SMS event gateway configuration.
6. Accept the login information.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 14 of 22


Figure 12. Accept login
information if necessary




7. Type any character and press Enter, or click the keypad and, click Send on the simulator. The menu application
displays the top-level menu.
8. Enter I for Book Club. Press Enter, or click Send on the simulator.
The application displays a submenu. For example, if you select I in step 5, the options are N for the next meeting
date, or L for a book list.
9. Enter your selection.
The application gets and displays the requested information.
10. (Optional) Enter M, another term, or B to return to the previous menu.


Figure 13. Use the phone
simulator


ColdFusion MX 7 Getting Started Experience – Coding Guidelines 15 of 22


11. Continue by entering menu items and detail information requests.
12. Click File > Exit in the menu bar to exit from the application.

The application files are in the C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\extensions\components\SMS
directory, as follows:

• Application.cfm — Names the application and sets sessions
• smsMain.cfc — Handles incoming messages and calls methods from smsBookclub.cfc
• smsBookclub.cfc — Returns requested information

The smsMain.cfc displays a menu of options the user can select from when events are initiated from the phone simulator
(or user's mobile phone). If the user sends an "I", a menu that lists two options is displayed to the user. If the user sends
"N" from the menu, the getNextMeeting method is called, which returns the next meeting date. If the user sends "L"
from the menu, the getBookList method is called, which returns a book list.

Lines 66-69 in smsMain.cfc process these requests:

session.m4 = session.root.addChild(name="Book Club Info", key="I");
// Setup sub-menuNodes and tie them to specific CFCs and methods

session.m4a = session.m4.addChild(name="Next Meeting", key="N",
cfc="CFIDE.gettingstarted.community.extensions.components.SMS.SMSbookclub",
method="getNextMeeting");

session.m4b = session.m4.addChild(name="Book List", key="L",
cfc="CFIDE.gettingstarted.community.extensions.components.SMS.SMSbookclub",
method="getBookList");

The getNextMeeting and getBookList methods are in the SMSBookclub.cfc.

The getNextMeeting method (lines 39-74) returns the next meeting date by querying the database for dates. Then a
query-of-query is used to list the first date as the next meeting date.

<cfset info="Next meeting: #dateFormat(getInfo.calendarDate,'mm/dd/yyyy')# at
#timeformat(getInfo.startTime,'hh:mm tt')##chr(10)##getInfo.meetingInfo#">

<cfreturn info />

The getBookList method (lines 76-95) queries the database, loops over the query, and creates a string of books as the
book list to return.

<cfloop query="list">
<cfset str=str & "#title# by #firstname# #lastname# #chr(10)#">
</cfloop>

<cfif not len(str)><cfset str="Book list not available"></cfif>

<cfreturn str />

You can use these files as the basis for developing your own SMS application. After you complete and test your
application, you must contact an SMS provider to set up an account.
Dynamic document generation
The Blackstone Book Club is sponsored by many local retailers who offer members various perks. The public is allowed to
see the perks as an incentive for joining (see Figure 3), but only members are allowed to download the coupons (see
Figure 5). After a member clicks on a coupon link, the member is presented with a FlashPaper output version of the
coupon for printing. Each coupon is generated dynamically with a unique coupon code, and validation is performed to
ensure that a user can only generate one coupon code.
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 16 of 22



Figure 14. Dynamically
generated coupon with
unique code



The code for showing the coupons is included in the memberperks.cfm file (in the
C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\webroot directory). The application queries the database to get
the list of coupons that are available, and then displays those coupons to the logged in member. Lines 44-49 show this
code:

<cfoutput query="couponList">
<li>
<cfif len(getAuthUser())>
[<a
href="javaScript:launchCoupon('#couponID#','#request.memberID#')">coupon</a>]
</cfif> &nbsp;#coupon#
</li>
</cfoutput>

After the member makes a selection, the coupon.cfm file, in the same directory, is called. All the information about the
coupon is retrieved from the sponsorCoupons method in lines 23-26, as follows:

<cfinvoke component="#request.cfcPathCoupon#" method="sponsorCoupons"
returnvariable="coupon">
<cfinvokeargument name="couponID" value="#url.id#" />
<cfinvokeargument name="dsn" value="#request.dsn#" />
</cfinvoke>

The memberCoupon method is called to validate the coupon (lines 30-34 in coupons.cfm).

<!--- checks to see if user has downloaded coupon before. if so, shows same coupon code.
--->
<cfinvoke component="#request.cfcPathCoupon#" method="memberCoupon"
returnvariable="ccode">
<cfinvokeargument name="couponID" value="#url.id#" />
<cfinvokeargument name="memberID" value="#request.memberID#" />
<cfinvokeargument name="dsn" value="#request.dsn#" />
</cfinvoke>

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 17 of 22

In Coupon.cfc (in the C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\extensions\components directory, lines
96-128), the application checks whether a user has downloaded the coupon before. If they have downloaded that coupon,
the same coupon code is used; otherwise, a new coupon code is used and recorded.

<!--- find coupon code --->
<CFQUERY NAME="cpncheck" DATASOURCE="#arguments.dsn#">
SELECT COUPONCODE
FROM #TABLES.MEMBERDOWNLOAD#
WHERE MEMBERID=<cfqueryparam cfsqltype="cf_sql_integer"
value="#arguments.memberID#" />
AND COUPONID=<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.couponID#"
/>
</CFQUERY>

<cfif not cpncheck.recordcount>
<!--- create new code --->
<cfset ccode=createUUID()>
<!--- insert record into table --->
<CFQUERY NAME="updaterecord" DATASOURCE="#arguments.dsn#">
INSERT INTO #TABLES.MEMBERDOWNLOAD#(MEMBERID,COUPONID,COUPONCODE)
VALUES (
<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.memberID#" />,
<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.couponID#" />,
<cfqueryparam cfsqltype="cf_sql_varchar" value="#ccode#" />)
</CFQUERY>
<!--- return new code --->
<cfreturn ccode />
<cfelse>
<!--- return old code --->
<cfreturn cpncheck.couponcode />
</cfif>

After the member’s login is validated, the application presents the member with a coupon as FlashPaper output format
(lines 36-60 in coupon.cfm). You can also display the coupon as PDF output format by changing the format attribute
value to PDF.

Lines 36-60 show the FlashPaper output format for the coupon:

<!--- coupon --->
<cfdocument format="FlashPaper" margintop="2" marginbottom="1" marginleft="1"
marginright="1" unit="in">
<cfdocumentitem type="header"><!--- logo --->
<img src="images/menu_people.jpg" width="244" height="69" alt="Bookclub logo
of people reading" /><br>
<img src="images/menu_logo.jpg" width="244" height="61" alt="Bookclub logo of
people reading" />
<hr />
</cfdocumentitem>

<table cellspacing="3" cellpadding="3">
<tr>
<td scope="row">
<cfoutput>
<p><strong>#coupon.coupon#</strong></p>
<p>Brought to you by #coupon.sponsorName#</p>
<p>Coupon Code: #ccode#</p>
<p>Expires: #dateFormat(coupon.expirationDate,"mmmm d, yyyy")#</p>
</cfoutput>
</td>
</tr>
</table>
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 18 of 22


<cfdocumentitem type="footer">
Date: <cfoutput>#dateformat(now(),"mmmm d, yyyy")#</cfoutput>
</cfdocumentitem>
</cfdocument>

The document has defined header and footer areas that appear on every page of the document. Use the
cfdocumentitem tag to create these areas. Any text or html that is not in either area appears in the body of the
document.

<cfdocumentitem type="header"><!--- logo --->
<img src="images/menu_people.jpg" width="244" height="69" alt="Bookclub logo of
people reading" /><br>
<img src="images/menu_logo.jpg" width="244" height="61" alt="Bookclub logo of
people reading" />
<hr />
</cfdocumentitem>

<cfdocumentitem type="footer">
Date: <cfoutput>#dateformat(now(),"mmmm d, yyyy")#</cfoutput>
</cfdocumentitem>
Enhanced Flash, XML, and HTML forms
The ColdFusion MX 7 enhancements for forms may improve your productivity the most. HTML forms are essential to any
web developer’s toolbox, but ColdFusion developers now have an immense advantage over other web developers,
because they can create forms more efficiently and more attractively than ever before with the addition of XML and Flash
forms.

With XML forms, you no longer have to struggle with table layouts. You simply create a style that you reuse to consistently
display your HTML forms. If you decide to change your layout, you can quickly do so by redefining your XML file, which
provides more power to your application development.

Flash forms in ColdFusion MX 7 introduce the immense usability advantages of Flash technology to HTML developers,
who can now create Flash forms by adding the format="flash" attribute to their code. Some of the incredible Flash
form elements that you can create include tabbed interfaces, tree structures, and calendar pickers.

As if all of this was not exciting enough, Macromedia has enhanced forms even further by improving client-side validation
and adding server-side validation options to the cfform tag. This means that ensuring your data integrity has been made
much easier.

Forms are used extensively in the administration management sections of the Blackstone Book Club application; it
contains examples of Flash and XML forms, as well as server-side and client-side validation.

Flash form
On the home page of the Blackstone Book Club website, a tabbed Flash form is used to create a polling system. The first
tab is the poll question, and the second tab lists the results.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 19 of 22


Figure 15. Flash poll



The poll is an included file called poll.cfm (in the
C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\webroot\shared directory).

Lines 22-24 in the poll.cfm file retrieve the poll data, as follows:

<!--- get current poll --->
<cfinvoke component="#cfcPoll#" method="Polls" returnvariable="poll">
<cfinvokeargument name="dsn" value="#request.dsn#" />
</cfinvoke>

Lines 28-81 use a cfform tag with format="Flash" to display the Flash form. The HTML formatting is not necessary
for Flash form layout; each tab in the form is created by using a cfformgroup> tag of type="page".

<cfform title="Poll" name="poll" action="index.cfm" method="post" format="Flash"
skin="haloBlue" width="185" height="300" timeout="20">
<cfformgroup type="tabnavigator">
<cfformgroup type="page" label="Poll">
<cfformitem type="text">
<cfoutput>#poll.question#</cfoutput>
</cfformitem>
<cfformgroup type="vbox">
...
</cfformgroup>
</cfformgroup>
<cfformgroup type="page" label="Results">
...
</cfformgroup>
</cfformgroup>
</cfform>

Macromedia ships the following skins for Flash forms with ColdFusion MX 7: haloSilver, haloBlue, haloGreen, and
haloOrange. To use one of these skins, use the skin attribute of the cfform tag to specify the skin name.

ColdFusion MX 7 Getting Started Experience – Coding Guidelines 20 of 22

What is a skin?
Applications that follow best practices separate business logic from display elements. This lets designers easily modify the
display elements without disrupting the underlying programming code. Skins, referring to the outer layer of an object, are
replaceable display elements that take advantages of this best practice.


If the user submits the poll, the submission is added to the database using the addPollResponse method, which is
invoked on lines 12-19 in poll.cfm, as follows:

<cfif isDefined("submit_poll")>
<cfparam name="form.answer" default="0">
<cfinvoke component="#cfcPoll#" method="addPollResponse"
returnvariable="isSuccessful">
<cfinvokeargument name="pollID" value="#form.pollID#" />
<cfinvokeargument name="answer" value="#form.answer#" />
<cfinvokeargument name="dsn" value="#request.dsn#" />
</cfinvoke>
</cfif>

The addPollResponse method (lines 56-76 of Poll.cfc) updates the poll response table, as follows:

<CFQUERY NAME="addResponse" DATASOURCE="#arguments.dsn#">
UPDATE #TABLES.POLLRESPONSES#
SET
A#arguments.answer# = A#arguments.answer# + 1
,TOTAL=TOTAL+1
WHERE POLLID=<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.pollID#" />
</CFQUERY>

The pollResults method retrieves the poll results for display (lines 54-57 in poll.cfm), as follows:

<cfinvoke component="#cfcPoll#" method="PollResults" returnvariable="results">
<cfinvokeargument name="pollID" value="#poll.pollID#"/>
<cfinvokeargument name="dsn" value="#request.dsn#" />
</cfinvoke>

The pollResults method (lines 40-54, in poll.cfc) queries the database to return the results, as follows:

<!--- find result --->
<CFQUERY NAME="results" DATASOURCE="#arguments.dsn#">
SELECT A.POLLID, A1,A2,A3,A4,A5,TOTAL, QUESTION,
ANSWER1,ANSWER2,ANSWER3,ANSWER4,ANSWER5, ISLIVE
FROM #TABLES.POLLRESPONSES# A, #TABLES.POLLS# B
WHERE A.POLLID=B.POLLID
AND A.POLLID=
<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.pollID#" />
</CFQUERY>

You can easily manage Flash forms. Try changing the type attribute of the cfformgroup tag from tabnavigator to
accordion to see the change in the layout of the form.

XML forms
The XML login form appears on each page of the site until the user logs in (see Figure 1). The form, loginform.cfm, is
included in the application from the C:\CFusionMX7\wwwroot\CFIDE\gettingstarted\community\webroot\shared directory.

Lines 8-31 of this file use a cfform tag of format="XML" to generate the form, as follows:

<cfform name="loginform" action="login_action.cfm" method="Post" format="XML" width="200"
height="135" skin="xsl/beige_small.xsl">
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 21 of 22

<cfinput name="pageName" value="#cgi.script_Name#" type="hidden">
<cfformitem type="HTML">
<strong style="margin-left:50px">Login</strong>
</cfformitem>
<cfformgroup type="vertical" >
<cfinput name="email" title="Email"
type="text"
required="yes"
message="An email is required"
label="email"
validate="email" width="100" />
<cfinput name="password" title="Password"
type="password"
required="yes"
message="A password is required"
label="password"
width="100" />
<cfinput name="memberID" value="0" type="hidden">
<cfinput name="submit_button" type="submit" value="login" width="100"
title="Submit" align="center"/>
<cfformitem type="HTML">
SuperUser:<br />super@demodata.com / demo<br />
User:<br />user@demodata.com / demo<br />
</cfformitem>
</cfformgroup>
</cfform>

When you use an XML form, it is not necessary to use HTML for layout. You can use the cfformgroup tag to lay out the
form. The skin attribute determines the appearance and behavior of the final form.

ColdFusion MX 7 default XSL skins
Macromedia provides the following XSL skins in ColdFusion MX 7:

• beige
• blue
• bluegray
• lightgray
• red
• silver

The XSL files are located in the C:\CFusionMX7\wwwroot\CFIDE\scripts\xsl directory, and the corresponding cascading
style sheet CSS files are located in the C:\CFusionMX7\wwwroot\CFIDE\scripts\css directory.

You can modify these skins for your own purposes or create your own.


You must contain any text that is not part of the form field in cfformitem tags; otherwise, the text does appear in the
form. You can use type="HTML" or type="text" as in the following example:

<cfformitem type="HTML">
SuperUser:<br />super@demodata.com / demo<br />
User:<br />user@demodata.com / demo<br />
</cfformitem>

Note: If you use type="HTML", you can embed HTML tags with the text. If you use type="text", however, you cannot
use HTML in the text, but you can use a style attribute to assign styles to the text.
ColdFusion MX 7 Getting Started Experience – Coding Guidelines 22 of 22

Next steps
If you have not yet reviewed the Extranet sample application, you should do so now. Also consider reviewing the “Code
Snippets by Feature” and the “Steps to Build Dynamic Pages” sections of the ColdFusion MX 7 Getting Started
Experience, which you can access by selecting Start > Programs > Macromedia > ColdFusion MX 7 > Getting Started
Experience.