By Rob Brooks-Bilson
Book Price: $54.95 USD
£38.95 GBP
PDF Price: $43.99
Cover | Table of Contents | Colophon
http://www.autobytel.com/),
Williams-Sonoma's storefront application
(http://www.williams-sonoma.com/), and the
online reservation system at the Broadmoor Hotel's
web site (http://www.broadmoor.com/).
http://www.autobytel.com/),
Williams-Sonoma's storefront application
(http://www.williams-sonoma.com/), and the
online reservation system at the Broadmoor Hotel's
web site (http://www.broadmoor.com/).
http://www.macromedia.com (as of this
writing, the latest release is ColdFusion MX
6.1):
<html> <head> <title>CFML Example</title> </head> <body> <cfoutput> <h2>Today's date is #DateFormat(Now( ),'mm/dd/yyyy')#</h2> </cfoutput> </body> </html>
<html> <head> <title>CFML Example</title> </head> <body> <cfoutput> <h2>Today's date is #DateFormat(Now( ),'mm/dd/yyyy')#</h2> </cfoutput> </body> </html>
<cfoutput>) and two functions
(DateFormat( ) and Now( )) to
output the current date to the browser. We'll get to
what this tag and the functions do in a bit. For now,
we're just concerned with running the template and
understanding how CFML and HTML coexist.
http://www.oreilly.com/catalog/coldfusion/).
You should put the file in a directory accessible under the root
directory of your particular web server. For example, if the root
directory for your web server is
c:\inetpub\wwwroot, you can create a
subdirectory two levels down such as
c:\inetpub\wwwroot\examples\chapter2 and save
the template there as 2-1.cfm. Now if you use
your web browser to view this file
(true or false. In numeric
operations, Boolean values evaluate to 1 for
true and 0 for
false. When dealing with strings, Boolean values
are set to Yes for true and
No for false. Note that no
quotes are necessary to delimit Boolean values, nor are Boolean
values case sensitive.
"This is a string."
and 'So is this!' are both strings.
"1000" and '1000' are also
strings so long as the numbers are delimited by a set of quotes. The
empty string can be written as either '' or
"". There are certain special characters that must
be escaped within strings. These special characters are the single
quote ('), double quote ("),
and pound sign (#). These characters may be
escaped by doubling up on them as in the following
examples:
<cfset String1 = "This is a ""good"" use of escaped double quotes"> <cfset String2 = "This is a ''good'' use of escaped single quotes"> <cfset String3 = "What is the ##1 team in the league?">
<cfset> is a CFML tag you use to set a
variable to a particular value.
$)
and can contain only letters, numbers, underscores, and Unicode
currency symbols. Variable names can't contain
spaces. For example, Test,
MyVariable, My_variable,
MyVariable1, and
MyDescriptive_var2 are all valid ColdFusion
variables, while 4C, My
Variable, Phone#, and
A/P aren't. Note that the
addition of the Unicode currency symbol is new in ColdFusion MX.
Employee.Name. In previous versions of ColdFusion,
compound variable names were allowed. In ColdFusion MX, the same
syntax is used to automatically create a structure with a specific
key and assign a value to that key. For example, <cfset
Employee.Name="Pere Money"> creates a structure named
Employee and assigns "Pere
Money" to a key called Name.
There are two exceptions to this rule: cookie names and client
variable names may contain periods.
1, test,
MyVar, or Chr(54). Compound
expressions let you to evaluate data that is acted upon by operators.
For example, 1*10 is a mathematical expression
that evaluates to 10. The values
1 and 10 are both data, while
the asterisk (*) is considered an operator. On the
other end of the spectrum, expressions can be complex, consisting of
one or more subexpressions:
<cfset x = 1+(10 mod (3 * (11 - acos(-1))))>
<cfset x =
10*(3+2)> uses the asterisk (*) as an
operator to multiply 10 by the sum of another expression that uses
the plus (+) operator to add 3 and 2. There are
four types of operators available in ColdFusion:
true/false.
&) concatenates strings.
true/false values.
<cfoutput> tag. cfoutput
is a paired tag, which means that it has both start and end tags.
cfoutput tells ColdFusion to parse any text found
between the tag pairs for variables and expressions that need to be
evaluated. We'll use the cfoutput
tag in a variety of ways throughout the book; it is one of the most
commonly used CFML tags. For now, let's focus on how
the cfoutput tag outputs simple variable values.
cfset tags and then outputs the values of the
variables within cfoutput tags:
<!--- Assign values to variables ---> <cfset x = 1> <cfset y = x+2> <cfset Name = "Rob"> <cfset z = Name> <cfset Authenticated = true> <cfset TheDate = DateFormat(Now( ),'mm/dd/yyyy')> <!--- Output the variable values ---> <h2>Writing Output</h2> <cfoutput> x = #x#<br> y = #y#<br> Name = #Name#<br> z = #z#<br> TheDate = #TheDate#<br> Authenticated = #Authenticated#<br> </cfoutput>
#) in this example.
ColdFusion uses pound signs to separate expressions from literal
text. When ColdFusion encounters an expression surrounded by pound
signs, it attempts to evaluate it.
cfoutput tags. Use pound signs around
variable names when you want to substitute the
variable's value within your
output:
<cfoutput> Hello #Name#, how are you today? </cfoutput>
<cfoutput> Hello #FirstName# #LastName#, how are you today? </cfoutput>
<cfif>,
<cfelseif>, and
<cfelse> tags; a C-style switch statement
with the <cfswitch>,
<cfcase>, and
<cfdefaultcase> tags; and the IIF(
) function for inline conditionals.
<cfif expression> HTML and CFML... <cfelseif expression> HTML and CFML... <cfelse> HTML and CFML... </cfif>
cfif statement can evaluate any expression
capable of returning a Boolean value. If the statement evaluates
true, ColdFusion processes the code associated
with the cfif statement. The
cfelseif statement provides an alternate
expression in the event that the expression in the
cfif statement evaluates false.
Any number of cfelseif statements can provide
additional decision-making options. The cfelse
statement provides a default option in the event that both the
cfif statement and any cfelseif
statements all evaluate false. The following
example uses if/elseif/else logic to evaluate a URL variable called
Action:
<cfif URL.Action IS "Add"> <cfinclude template="AddRecord.cfm"> <cfelseif URL.Action IS "Edit"> <cfinclude template="EditRecord.cfm"> <cfelseif URL.Action IS "Delete"> <cfinclude template="DeleteRecord.cfm"> <cfelse> You have chosen an invalid action! </cfif>
Action, one of three
additional templates is called via a
<cfinclude> tag (which
we'll discuss shortly). If the value of the URL
variable doesn't match one of the values in the
<cfloop> tag, including index
(for) loops, conditional
(while) loops, collection loops, list loops, and
query loops. For now, we are just going to cover basic index and
conditional loops. Query loops are covered in Chapter 4, while collection and list loops are covered
in Chapter 6.
for loop, an index loop repeats a number of times
specified as a range of values:
<cfloop index="index_name" from="number" to="number" step="increment"> HTML and CFML... </cfloop>
index attribute of the loop specifies a variable
name to hold the value corresponding to the current iteration of the
loop. The from attribute initializes the starting
value for the loop. The to attribute refers to the
value at which iteration should stop. step
specifies the increment value for each iteration of the loop.
step may be either a positive or a negative
number. Here is an example that uses an index loop to output all the
numbers between 10 and 100 in
increments of 10, with each number on its own
line:
<h2>Calling the loop...</h2> <cfoutput> <cfloop index="i" from="10" to="100" step="10"> #i#<br> </cfloop> </cfoutput> <h2>We are now outside of the loop</h2>
index is set to i. Since
we want to begin the count at 10, we assign that
value to the from attribute. The
to attribute is set to 100
because that is where we want the loop to stop iterating. In order to
get the loop to increment by multiples of 10, the
step attribute is set to 10.
Executing the template results in the output shown in Figure 2-4.
<cfinclude> tag.
cfinclude is the ColdFusion equivalent of Server
Side Includes (SSI). cfinclude takes a single
attribute, template, which specifies a logical
path to the file to be included. The logical path must be either a
virtual directory or a directory that has been explicitly mapped in
the ColdFusion Administrator:
<cfinclude template="MyIncludedFile.cfm">
<cfinclude template="/MyDirectory/MyIncludedFile.txt">
<!--- Set the title for the page ---> <cfset Title="My Page"> <!--- Include the header for the page ---> <cfinclude template="_header.cfm"> <h2>Hello World!</h2> I'm just some regular text. <!--- Include the footer ---> <cfinclude template="_footer.cfm">
Title. Next, a template called
_header.cfm is included using the
cfinclude tag. I use the underscore as the first
character of any include files so that I can differentiate include
files from other templates. The next part of the template constitutes
the body of the page. In this example, we just output some simple
text. The last line of code in the template uses another
filename.cfm?param1=value1¶m2=value2¶m3=value3
filename.cfm?param1=value1¶m2=value2¶m3=value3
<!--- Set variables to be passed to another template ---> <cfset x=1> <cfset color="green"> <cfset Pass = True> <h2>Passing Data via URL Parameters</h2> <!--- Create a hyperlink containing URL parameters ---> <cfoutput> <a href="receiveurlparameters.cfm?x=#x#&color=#color#&pass=#pass#">Click this link to pass the URL parameters</a> </cfoutput>
http://myserver.com/receiveurlparameters.cfm?x=1&color=green&Pass=Trueaction attribute of the form
tag. Within the receiving template, each form field can be referenced
by prefixing the field name with form, as in
form.
MyField. To see
just how this works, let's look at an example. The
contactform.cfm template, shown in Example 3-6, creates a simple HTML form that collects
basic contact information and posts it to the
displaycontactinfo.cfm template, shown in Example 3-7.
<html>
<head>
<title>Passing Variables via Form Fields</title>
</head>
<body>
<h2>Employee Contact Information</h2>
<form action="displaycontactinfo.cfm" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="Name" size="25" maxlength="50"></td>
</tr>
<tr>
<td>Title:</td>
<td><input type="text" name="Title" size="25" maxlength="50"></td>
</tr>
<tr>
<td>Department:</td>
<td><input type="text" name="Department" size="25" maxlength="50"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="Email" size="25" maxlength="255"></td>
</tr>
<tr>
<td>Phone Ext.:</td>
<td><input type="text" name="PhoneExt" size="6" maxlength="4"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
cfparam tag to assign a default value to any
parameters expected by your application template. That way, if an
expected parameter isn't passed, a default value is
automatically assigned, and the application can continue processing.
If you remember, the cfparam tag was covered
earlier in Chapter 2. Additional information on
the cfparam tag can be found in Appendix A.
cfparam tag is
great for assigning a default value if one doesn't
exist; however, it doesn't allow you to display an
error message or perform an alternate action if an expected variable
doesn't exist. The next method uses the
IsDefined( ) function to check for the existence
of a variable before allowing processing of the template to continue.
If the expected variable exists, the template is processed. If not,
an error message is written to the browser. For example, if you have
a template that is expecting a URL parameter named
ArticleID to be passed in, you can use the
following code to output an error message if the parameter
isn't present:
<!--- If the parameter is present, output it to the screen --->
<cfif IsDefined('URL.ArticleID')>
<cfoutput>
The article ID is: #URL.ArticleID#
</cfoutput>
Additional program code...
<!--- Otherwise, output an error message --->
<cfelse>
A required parameter, <b>ArticleID</b> was not supplied!
</cfif>
IsDefined( ) function checks
for the existence of a URL parameter called
ArticleID. If it is present, its value is output
to the browser, and any additional program code for the page is
executed. If the parameter isn't present, an error
message to that effect is written to the browser.
cfquery tag is the
main tag used by ColdFusion to interact with databases. Using
cfquery, you can pass any Structured Query
Language (SQL) statement to a data source registered with the
ColdFusion Administrator. The content of your SQL statements
determines what action is performed against the data source. The next
section provides a quick primer on SQL.
cfquery tag works by establishing a connection
with the specified data source, passing a series of SQL commands, and
returning query variables that contain information about the
operation. The basic syntax for using the cfquery
tag is as follows:
<cfquery name="query_name"
datasource="datasource_name">
SQL statements
</cfquery>
cfquery tag specifies information about the data
source and how ColdFusion should access it. The
name attribute assigns a name to the query. Valid
query names must begin with a letter and can contain only letters,
numbers, and underscore characters. name is
required when passing an SQL SELECT statement and
is optional for all other SQL operations.
The datasource attribute is required in all
circumstances except when dbtype is
Query (covered later in Chapter 11) and specifies the name of the data source (as
it appears in the ColdFusion Administrator) to connect to when
executing the query. There are a number of additional attributes that
can be used with the cfquery tag. For a complete
list, see its tag reference in Appendix A.
cfquery
tag. If you don't completely understand everything
we are about to cover, don't worry. Every aspect
(and more) of the SQL we cover in the primer is covered in more
detail throughout this and the next chapter.
SELECT,
INSERT, UPDATE, and
DELETE, respectively:
SELECT
INSERT
UPDATE
ProgrammingCF that
contains several database tables including one called
EmployeeDirectory. The schema and sample data for
this database are listed in Appendix C. For
simplicity, I've chosen to use a Microsoft Access
database for all the examples; you can download the sample Access
database from O'Reilly's catalog
page for this book (http://www.oreilly.com/catalog/coldfusion2/).
Of course, you can use any database you choose. To get started, you
need to create a new database and save it as
ProgrammingCF. Next, create a new table and add
the fields shown in Table 4-2.
|
Field name
|
Field type
|
Max length
|
|---|---|---|
ID (primary key) |
AutoNumber
|
N/A
|
Name |
Text
|
255
|
SELECT statement to retrieve
records from a database, those records are returned in the order in
which they are stored. If you want to change the order in which the
records are displayed (which you probably do), you need to use an
ORDER BY clause, as shown in Example 4-2.
<cfquery name="GetEmployeeInfo" datasource="ProgrammingCF">
SELECT Name, Title, Department, Email, PhoneExt
FROM EmployeeDirectory
ORDER BY Name ASC
</cfquery>
<html>
<head>
<title>Sorting Query Results Using the SQL ORDER Clause</title>
<style type="text/css">
th {
background-color : #888888;
font-weight : bold;
text-align : center;
}
td {
background-color : #C0C0C0;
}
</style>
</head>
<body>
<table cellpadding="3" cellspacing="1">
<tr>
<th>Name</th>
<th>Title</th>
<th>Department</th>
<th>E-mail</th>
<th>Phone Extension</th>
</tr>
<cfoutput query="GetEmployeeInfo">
<tr>
<td>#Name#</td>
<td>#Title#</td>
<td>#Department#</td>
<td><a href="Mailto:#Email#">#Email#</a></td>
<td>#PhoneExt#</td>
</tr>
</cfoutput>
</table>
</body>
</html>
ORDER BY clause specifies which column or
columns to use in ordering the query results. Sorting can be either
ASC (ascending) or DESC
(descending). Example 4-2 sorts the result set by
name column, in ascending order. The output is
shown in Figure 4-1.
ORDER
BY clause as in:
<cfquery name="GetEmployeeInfo" datasource="ProgrammingCF"> SELECT Name, Title, Department, Email, PhoneExt FROM EmployeeDirectory ORDER BY Title ASC, Name ASC </cfquery>
cfoutput tag has
an attribute called group that lets you to group
output from your record sets before displaying it to the browser.
There are two ways to use the group attribute of
the cfoutput tag. The first method uses
group to remove any duplicate rows from the query
result set. This
is useful in situations where the result set you return from a query
contains duplicate rows of data but you want to display only unique
records.
group attribute of the
cfoutput tag.
<cfquery name="GetDepartment" datasource="ProgrammingCF">
SELECT Department
FROM EmployeeDirectory
ORDER BY Department
</cfquery>
<html>
<head>
<title>Failing to Use the group Attribute Results in Duplicate Values in the
Output </title>
</head>
<body>
<h2>Departments:</h2>
<cfoutput query="GetDepartment">
#Department#<br>
</cfoutput>
</body>
<