This manual, as well as the software described in it, is furnished under license and may
be used or copied only in accordance with the terms of such license. The content of
this manual is furnished for informational use only, is subject to change without
notice, and should not be construed as a commitment by Allaire Corporation. Allaire
Corporation assumes no responsibility or liability for any errors or inaccuracies that
may appear in this book.
Except as permitted by such license, no part of this publication may be reproduced,
stored in a retrieval system, or transmitted in any form or by any means, electronic,
mechanical, recording, or otherwise, without the prior written permission of Allaire
Corporation.
ColdFusion and HomeSite are federally registered trademarks of Allaire Corporation.
HomeSite, the ColdFusion logo and the Allaire logo are trademarks of Allaire
Corporation in the USA and other countries. Microsoft, Windows, Windows NT,
Windows 95, Microsoft Access, and FoxPro are registered trademarks of Microsoft
Corporation. All other products or name brands are the trademarks of their respective
holders. Solaris is a trademark of Sun Microsystems Inc. UNIX is a trademark of The
Open Group. PostScript is a trademark of Adobe Systems Inc.
Part number: AA-45WEB-RK
Contents
Preface: Welcome to ColdFusion ..................................................................xv
Index ..............................................................................................................349
xivDeveloping Web Applications with ColdFusion
Preface Welcome to ColdFusion
This manual describes the process of developing Web applications using
ColdFusion. In the first six chapters, you can follow the instructions presented to
learn how to create basic ColdFusion applications. Then, chapters seven through 17
cover various topics of interest in enhancing your applications. Finally, chapters 18
through 21 explain how to extend ColdFusion’s capabilities.
Because of the power and flexibility of ColdFusion, you can create many different
types of Web applications of varying complexity. As you become more familiar with
the material presented in this manual, and begin to develop your own applications,
you will want to refer to the CFML Language Reference for details about various tags
and functions.
Contents
•Intended Audience.......................................................................................... xvi
•Welcome to the ColdFusion 4.5 Web Application Server............................. xvi
•Products and System Requirements............................................................. xvii
•New Features in ColdFusion 4.5................................................................... xviii
•Developer Resources....................................................................................... xxi
This manual is particularly useful for Web application developers who are new to
ColdFusion. In particular, Chapters 1 through 6 provide instructions for creating a
basic ColdFusion application. If you are somewhat familiar with ColdFusion, but want
to learn more about a particular topic such as sending and receiving email, refer to
Chapters 7 through 17. Finally, if you want to extend ColdFusion’s capabilities with
CFML scripting or creating custom tags, Chapters 18 through 21 will be helpful.
Welcome to the ColdFusion 4.5 Web Application Server
The ColdFusion 4.5 release focuses on fundamentals — the fundamentals of delivering
your e-business: faster development, better reliability, enhanced scalability, expanded
integration, and stronger security.
At the center of the ColdFusion 4.5 release is an application server platform that's been
highly optimized with new functionality and native support for UNIX. As a result, your
e-business systems will run better and do more. With this release we're launching a
new edition of ColdFusion Server for Linux so you can take advantage of the reliability
and performance of the hottest new Internet server operating system.
While optimizing the core server, we also enhanced fundamental features including
email integration, server-side FTP and HTTP, advanced security, scheduling, and
database connectivity — again giving you more reliability and new functionality.
The focus on fundamentals extends to new features. As part of a broad new
commitment to Java, ColdFusion 4.5 has a range of new Java integration options from
Java CFXs to Java Servlet support to Java object and EJB connectivity. In ColdFusion
Studio 4.5, we added new tools to make you more productive including a flexible new
project architecture that makes managing and deploying complex Web applications a
snap. On the server, we focused on reliability, performance and security with features
such as service-level fail-over, Cisco Local Director integration, and OS security
integration.
Whether you're revolutionizing your company's HR operations, building the next
generation of your firm's global intranet, or launching the next killer .COM company,
you'll find the speed, scalability, connectivity, and security you need in ColdFusion 4.5.
Prefacexvii
Products and System Requirements
ColdFusion has been fully tested on the following platforms and with the following
configurations.
ColdFusion Server 4.5 Enterprise Edition for Windows
• Windows NT 4.0 SP4+
• Intel Pentium or above
• 150 MB hard disk space
• 128 MB RAM (256 MB recommended for clustering)
ColdFusion Server 4.5 Enterprise Edition for Solaris
• SPARC Solaris 2.5.1, 2.6, or 7 (patch 103582-1B or higher)
• 128 MB RAM (256 MB recommended for clustering)
• 200 MB hard disk space
ColdFusion Server 4.5 Enterprise Edition for Linux
• Red Hat Linux 6.0 or 6.1
• Intel Pentium or above
• 128 MB RAM (256 MB recommended for clustering)
• 150 MB hard disk space
ColdFusion Server 4.5 Professional Edition for Windows
• Windows 95/98 or Windows NT 4.0
• Intel Pentium or above
• 50 MB hard disk space
• 32 MB RAM (128 MB recommended)
ColdFusion Server 4.5 Professional Edition for Linux
• Red Hat Linux 6.0 or 6.1
• Intel Pentium or above
• 64 MB RAM (128 MB recommended)
• 100 MB hard disk space
xviiiDeveloping Web Applications with ColdFusion
ColdFusion Studio 4.5
• Windows 95/98/NT4
• Intel Pentium or above
• 35 MB hard disk space
• 32 MB RAM (64 MB recommended)
New Features in ColdFusion 4.5
A wide range of new features are available in ColdFusion 4.5.
New visual tools
Universal File Browser — Access all your files from a single explorer that integrates
access to the Windows file system, ColdFusion RDS servers, and FTP servers. Dragand-drop between any of these services all in an integrated file browser.
Advanced Project Management — Manage your complex Web application
development projects with a new project architecture that gives you more flexibility
and control using physical, virtual, and auto-inclusive project folders as well as project
resource browsing.
Scriptable Deployment — Deploy applications to complex server configurations with
FTP or ColdFusion Remote Development Services (RDS). Use VBScript or Java Script to
fully script deployment of projects with granular control over how files uploaded.
Setup deployment scripts using a powerful wizard and save scripts for re-use.
Collapsible Code — Work with large, complex scripts and pages more easily by
collapsing sections of the code in the editor so you can build sophisticated
applications more quickly.
Function Insight — Find the parameters and format for functions instantly and inline
as you code.
Image Map Editor — Create image maps right in ColdFusion Studio with a new easyto-use visual tool.
Configuration Wizard — Setup your work environment so it meets all your needs
using any of more than dozen common configurations.
TopStyle CSS Editor — Create and edit standards-compliant cascading style sheets to
easily control the look and feel of your web applications.
WML Support — Build wireless Web applications quickly and easily with the complete
set of Wireless Markup Language (WML) visual tools.
Prefacexix
Enhancements to CFML
Object Scripting — Instantiate and script objects using CFML script in addition to the
CFOBJECT tag easier integration with distributed object middleware such as COM and
CORBA.
Structured Exception Handling — Exception handling now offers hierarchical
exception handling that supports both greater customization and greater access to
internal exceptions.
String Conversion Functions — Convert strings quickly and easily to be compatible
with Java Script and XML standards.
Better reliability
Server Probes — Guarantee high availability by automatically detecting when a
ColdFusion Server or Web server hangs or stops, failing-over to a new machine in a
ColdFusion cluster, and restarting the server with problems. (Enterprise Edition only)
Improved Automatic Server Recovery — Monitor and automatically restart server
process in case of failures or critical errors on individual servers not deployed in a
cluster.
Clustering Support for Apache — Setup ColdFusion clusters on Linux and Solaris
using the Apache Web Server. (Enterprise Edition only)
Automatic Shared Variable Locking — Lock user and session variable reads
automatically at the server level to prevent destabilizing conflicts and control thread
write contentions. Configure variable locking to meet the specific needs of your
applications.
Individual Data Source Control — Enable and disable individual data sources
individually without affecting server availability for runtime data source maintenance
without server restarts.
Improved performance
Cisco Local Director Integration — Deliver very large scale sites with Cisco Local
Director intelligently balancing load based on the load metrics provided by the
ColdFusion Servers in a cluster. (Enterprise Edition only)
Client-Side Page Caching — Leverage browser page caching to avoid unnecessary
downloads of unchanged pages and improve overall site performance.
Programmatically control refresh of client-side cache to ensure users see most up-todate output.
White Space Removal — Reduce white space left by processed code in application
pages to make the pages smaller and faster. Control white space removal
programmatically or administratively.
xxDeveloping Web Applications with ColdFusion
Scriptable Performance Metrics — Track key server metrics at run time through your
own scripts for intelligent diagnosis of performance bottlenecks of stability problems
in your applications.
Performance Debugging Data — Access detailed debugging information on the
performance of each individual page included in an application page that is being
debugged.
Enterprise connectivity features
Transaction Commit and Rollback — Control database transactions with
programmable commit and rollback support for more reliable and better-managed
database interactions.
Java Object and EJB Connectivity — Connect to any Java object or Enterprise JavaBean
(EJB) hosted by any major EJB server to extend ColdFusion and access complex
business logic or third party distributed components.
Java Servlets — Call Java Servlets hosted by a Servlet Engine such as Allaire JRun from
within a ColdFusion application to access extended functionality
Java-based ColdFusion Extensions (CFX) — Extend ColdFusion with new
functionality through CFXs created with Java.
Binary Object Support — Use Character Large Binary Object (CLOB) support to
encoded binary objects, transmit them via XML, and store them in databases or files.
SQL Bind Parameters — Improve query performance, security and flexibility with
explicitly typed query parameters.
WDDX 1.0 — Exchange complex data, including encoded images, between servers and
with other programming environments even faster using the latest version of Web
Distributed Data Exchange (WDDX).
OS Command Execution — Execute OS shell scripts, services, executables and batch
files from within ColdFusion applications.
LDAP 3.0 — Use all the power of LDAP 3.0 for directory access including file filtering,
SSL encryption, and Microsoft Active Directory integration.
Enhanced Mail Integration — Develop more sophisticated and robust email
applications with new support for controlling mail headers, BCC, and multiple file
attachments.
Improved Server-Side HTTP — Use URL redirection, SSL, cookies, return headers, and
more robust server-side HTTP support for building distributed Web applications.
Security enhancements
General OS Security Integration — Secure entire Web applications and control access
to files and objects through your existing Windows NT security architecture.
Authenticated users in your applications can be limited to privileges authorized
through Windows security. (Windows NT Only)
Prefacexxi
OS Server Sandbox Security — Secure shared hosting environments more easily by
creating Server Sandboxes with Windows NT security. OS Server Sandboxes process all
requests under the privileges of a designated Windows NT user account (Enterprise
Edition for Windows only).
Enhanced Advanced Security — Secure CFML functions and enable CFML code
segments to be executed using the run-time security permissions of a designated user.
New Advanced Security Interface — Manage Advanced Security configuration more
quickly and easily with a completely redesigned browser-based resource view.
Scriptable Advanced Security Administration — Configure ColdFusion Advanced
Security through your own CFML scripts for easier maintenance of ColdFusion
Servers.
Developer Resources
Allaire Corporation is committed to setting the standard for customer support in
developer education, technical support, and professional services. Our Web site is
designed to give you quick access to the entire range of online resources.
Allaire Developer Services
ResourceDescription
Allaire Web site
www.allaire.com
Technical Support
www.allaire.com/support
Training and Consulting
www.allaire.com/services
Developer Community
www.allaire.com/developer
Allaire Partners
www.allaire.com/partners
General information about Allaire products and
services.
Allaire offers a wide range of professional support
programs. This page explains all of the available
options.
Information about training classes, online
courses, and consulting services offered by
Allaire.
All of the resources you need to stay on the
cutting edge of ColdFusion development,
including online discussion groups, Knowledge
Base, Component Exchange, Resource Library,
technical papers and more.
The Allaire Alliance is a network of solution
providers, application developers, resellers, and
hosting services creating solutions with
ColdFusion.
xxiiDeveloping Web Applications with ColdFusion
About ColdFusion Documentation
ColdFusion documentation is designed to provide support for all components of the
ColdFusion development system. Both the print and online versions are organized to
allow you to quickly locate the information you need.
In addition to the book set, the documentation is provided in two other formats:
• HTML — Browser-based Help references.
• Adobe Acrobat (PDF) — Available from the root level on the product CD-ROM
and from the Developer area of Allaire’s Web site at http://www.allaire.com/
developer
Documentation updates
Late additions and corrections to ColdFusion printed documentation are listed in the
Documentation Updates page. To reach this page, open the Welcome to ColdFusion
page installed with ColdFusion, where you’ll find links to the update page as well as
links to other pages containing useful information about ColdFusion, Allaire support
options, and Allaire products and services.
For ColdFusion Studio users, you can access the documentation update page by
clicking on the Help resource tab and browsing your way through the online help tree
to the Allaire Support folder.
.
ColdFusion manuals
The core ColdFusion documentation set consists of the following titles.
Administering ColdFusion Server
Includes instructions for installing ColdFusion Server. Describes configuration options
for maximizing performance, managing data sources, setting security levels, and a
range of development and site management tasks. If you are administering a
ColdFusion site, you’ll need this book to help plan and implement ColdFusion
security, load balancing, and for details about tuning the ColdFusion application
server.
Developing Web Applications with ColdFusion
Presents the fundamentals of ColdFusion application development and deployment.
Also includes detailed information about ColdFusion data sources, user interfaces,
and Web technologies.
CFML Language Reference
Provides the complete syntax, with example code, of all CFML tags and functions.
Prefacexxiii
Using ColdFusion Studio
Documents everything you need to know about using ColdFusion Studio, including
features like projects, source control integration, as well as the Studio workspace and
interface.
ColdFusion Quick Reference Guide
A valuable quick reference to CFML tags, functions, and variables.
ColdFusion Server online documentation
To view the HTML documentation, open the following URL: http://127.0.0.1/
cfdocs/dochome.htm
Note that because the Verity search libraries are not available on Linux for this release,
the online documentation search facility is not functional on Linux. If you try to open
the search page, a message box opens to explain why the facility is not available.
Acrobat versions of all ColdFusion documentation are available from the root level on
the product CD. If you don’t have a product CD, you can download ColdFusion
documentation from the Allaire web site by visiting
developer
and clicking the Documentation link.
.
http://www.allaire.com/
ColdFusion Studio online documentation
Click the Help resource tab in ColdFusion Studio to view online Help pages. The help
tree contains ColdFusion documentation and a number of additional developer
resources. Studio online documentation is searchable and individual pages can be
bookmarked.
Printing ColdFusion documentation
If you are working with an evaluation version of ColdFusion and would like printed
documentation, access the Adobe Acrobat files found from the root level on the
product CD. If you do not have access to a product CD, you can download the Acrobat
files from the Allaire web site:
Documentation link.
The Acrobat files offer excellent print output. You can print an entire manual,
individual sections, or page ranges of your choice. To get the Acrobat reader, visit:
http://www.acrobat.com.
http://www.allaire.com/developer, click the
xxivDeveloping Web Applications with ColdFusion
Documentation conventions
When reading, please be aware of these formatting cues:
• Code samples, filenames, and URLs are set in a
• Notes and tips are identified by bold type
• Bulleted lists present options and features
• Numbered steps indicate procedures
• Tool button icons are generally shown with procedure steps
• Menu levels are separated by the greater than (>) sign
• Text for you to type in is set in italics
monospaced font
Getting Answers
One of the best ways to solve particular programming problems is to tap into the vast
expertise of the ColdFusion developer community on the Allaire Forums. Other
ColdFusion developers on the forum can help you figure out how to do just about
anything with ColdFusion. The search facility can also help you search messages going
back 12 months, allowing you to learn how others have solved a problem you may be
facing. The Forums is a great resource for learning ColdFusion, but it’s also a great
place to see the ColdFusion developer community in action.
Contacting Allaire
Corporate headquarters
Allaire Corporation
One Alewife Center
Cambridge, MA 02140
Tel: 617.761.2000
Fax: 617.761.2001
http://www.allaire.com
Prefacexxv
Technical support
Telephone support is available Monday through Friday 8 A.M. to 8 P.M. Eastern time
(except holidays)
Toll Free: 888.939.2545 (U.S. and Canada)
Tel: 617.761.2100 (outside U.S. and Canada)
For complete details about Allaire Product Support options, please refer to the Allaire
Support pages on the Allaire web site:
Postings to the ColdFusion Support Forum (
made any time.
http://www.allaire.com/support.
http://forums.allaire.com) can be
Sales
Toll Free: 888.939.2545
Tel: 617.761.2100
Fax: 617.761.2101
Email: sales@allaire.com
Web:
http://www.allaire.com/store
xxviDeveloping Web Applications with ColdFusion
C HAPTER 1
Chapter 1Introduction to ColdFusion
This chapter explains the difference between creating static Web pages with HTML
and creating dynamic applications with ColdFusion. It also describes what
ColdFusion is and how it works.
Contents
•A Quick Web Overview....................................................................................... 2
•What You Should Already Know........................................................................ 2
•What is ColdFusion?...........................................................................................3
•How ColdFusion Server Works.......................................................................... 7
2Developing Web Applications with ColdFusion
A Quick Web Overview
Over the last few years, the Web has changed from being simply a collection of static
HTML pages to an application development platform. Rather than offering a space
where organizations can merely advertise goods and services, similar to traditional
yellow pages directories, companies conduct business ranging from ecommerce to
managing internal business processes. For example, a static HTML page would allow a
bookstore to publish its location, list services such as the ability to place special orders,
and advertise upcoming events like book signings. A dynamic site for the same
bookstore would allow customers to order books online, write reviews of books they’ve
read, and even get suggestions for purchasing books based on their reading
preferences.
ColdFusion is a rapid application development environment that lets you build
dynamic sites. You can use the Web to handle business transactions, and even to
conduct the day to day business of your organization.
What You Should Already Know
Before you begin using ColdFusion to create your Web applications, you should be
familiar with the following topics:
HTML
You’ll find that ColdFusion tags (CFML) are similar in syntax to HTML tags, yet, unlike
HTML, they enable you to create dynamic Web pages. You should understand how to
create a basic HTML page, put information into tables, gather data in forms, and create
links.
Relational Database Design and Management
If you plan on creating applications that use data from existing data sources, you
should understand how the data is organized. In most cases, this means
understanding how tables are organized to prevent unnecessary duplication of data.
For example, if you have data about employees, rather than repeating the department
number and name in each employee’s record, you would most likely have a separate
table that lists each department number and name just once.
SQL
Familiarity with some Structured Query Language (SQL) will be helpful as you develop
your ColdFusion applications. In particular, you should be able to use the SELECT,
UPDATE, INSERT, and DELETE statements, as well as WHERE clauses and boolean
logic operators.
Chapter 1: Introduction to ColdFusion3
What is ColdFusion?
ColdFusion lets you create page-based Web applications using ColdFusion Markup
Language (CFML), the tag-based language you use to create server-side scripts that
dynamically control data integration, application logic, and user interface generation.
ColdFusion Web applications can contain XML, HTML, and other client technologies
such as CSS and JavaScript.
ColdFusion application pages are different from static HTML pages in the following
ways:
• They are saved and referenced with a specific file extension.
• The default ColdFusion file extension is CFM.
• They contain ColdFusion Markup Language.
Editions of ColdFusion
There are three editions of ColdFusion: Enterprise, Professional, and Express. Using
ColdFusion Enterprise and Professional editions and ColdFusion Studio, you can build
Web applications that leverage existing technologies and business systems such as
RDBMS, messaging servers, file repositories, directory servers, and distributed object
middleware. ColdFusion Enterprise also offers advanced security features, load
balancing, server fail-over, and visual cluster administration. Using ColdFusion
Express, you can build Web applications that interact with desktop databases that
support the ODBC standard.
ColdFusion Features
ColdFusion provides a comprehensive set of features that enable:
• Rapid development
• Scalable deployment
• Open integration
• Complete security
4Developing Web Applications with ColdFusion
Rapid development
The ColdFusion development platform enhances the speed and ease of development
through the following features:
• A tag-based server scripting language that is powerful and intuitive.
• Two-way visual programming and database tools.
• Remote interactive debugging for quickly identifying and fixing problems.
• Web application wizards to automate common development tasks.
• Source control integration to enable team development.
• Secure file and database access via HTTP for remote development.
• A tag-based component architecture for flexible code reuse.
Scalable deployment
ColdFusion delivers a high-performance platform for application deployment through
the following features:
• A multi-threaded service architecture that scales across processors.
• Database connection pooling to optimize database performance.
• Just-in-time page compilation and caching to accelerate page request
processing.
• Dynamic load balancing for scalable performance in a cluster environment
(Enterprise Edition only).
• Automatic server recovery and fail-over for high availability (Enterprise Edition
only).
Open integration
ColdFusion integrates with new and legacy technologies through the following
features:
• Database connectivity using native database drivers (Enterprise Edition only),
ODBC, or OLE-DB.
• Embedded support for full text indexing and searching.
• Standards-based integration with directory, mail, HTTP, FTP, and file servers.
• Connectivity to distributed object technologies including CORBA (Enterprise
Edition only), COM (Windows Enterprise Edition only), Java objects and EJBs.
• Open extensibility with C/C++ and Java.
Chapter 1: Introduction to ColdFusion5
Complete security
ColdFusion provides a foundation for building secure applications through the
following features:
• Integration with existing authentication systems including Windows NT
domain and LDAP directory servers, and proprietary user and group databases.
• Advanced access control so that server administrators can control developers’
access to files and data sources.
• Support for existing database security.
• Server sandbox security for protecting multiple applications on a single server
(Enterprise Edition only).
• Support for existing Web server authentication, security, and encryption.
For detailed information on security, refer to Administering ColdFusion Server. Also, for
the latest publications from Allair on security, visit the Security Zone at http://
www.allaire.com/developer/securityzone/. For a complete feature list and more
detailed information, refer to the ColdFusion product pages, http://www.allaire.com/
coldfusion.
ColdFusion Components
ColdFusion applications rely on several core components:
• ColdFusion Studio
• ColdFusion application pages
• ColdFusion Server
• ColdFusion Administrator
• ODBC data sources and other data sources
ColdFusion application pages look somewhat like HTML pages, but, as you will see, are
much more dynamic and powerful. You will probably want to use ColdFusion Studio to
create the application pages, although you can use the editor of your choice.
ColdFusion Server processes the ColdFusion application pages. For example, you may
access a data source from your application pages.
In addition to the core components, as you become more familiar with ColdFusion
and build more complex applications, you can use ColdFusion Extensions to extend its
capabilities.
6Developing Web Applications with ColdFusion
ColdFusion Studio
ColdFusion Studio is the development environment for ColdFusion Server. It offers
visual development tools, including dynamic page previews using your Web browser,
an interactive debugger, a query builder, an expression builder, project management
and source control tools, and many other productivity enhancements. To learn more
about ColdFusion Studio, see Using ColdFusion Studio.
ColdFusion application pages
Application pages are the functional parts of a ColdFusion application, including the
user interface pages and forms that handle data input and format data output. They
can contain ColdFusion tags (CFML), HTML tags, CFScript, JavaScript, and anything
else you can normally embed in an ordinary HTML page. The default file extension
used for ColdFusion application pages is .CFM.
CFML
CFML is a tag-based server scripting language that encapsulates complex processes
such as connecting to databases and LDAP servers, and sending email. The core of the
ColdFusion development platform language is more than 70 server-side tags and more
than 200 functions.
ColdFusion Server
ColdFusion Server listens for requests from the Web server to process ColdFusion
application pages. It runs as a service under Windows NT and as a process under
UNIX. For information on installing and configuring ColdFusion Server, refer to
Administering ColdFusion Server.
ColdFusion Administrator
You use the Administrator to configure various ColdFusion Server options, including:
• ColdFusion data sources
• Debugging output
• Server settings
• Application security
• Server clustering
• Scheduling page execution
• Directory mapping
See Administering ColdFusion Server for details on using the Administrator.
Chapter 1: Introduction to ColdFusion7
Data sources
ColdFusion applications may interact with any database that supports the ODBC
standard. However, ColdFusion is not limited to ODBC data sources. You can also
retrieve data using OLE-DB, native database drivers, or directory servers that support
the Lightweight Directory Access Protocol (LDAP). Data can also be retrieved from
mail servers that support the Post Office Protocol (POP), and which is indexed in Verity
collections.
How ColdFusion Server Works
Regardless of which ColdFusion Server you have installed, ColdFusion application
pages are processed on the server at runtime, each time they are requested by a
browser.
A page request happens when you click on a Web site link to open a Web page in your
browser. When you request a ColdFusion application page, ColdFusion server
processes the request, retrieves any data if necessary, routes the data through the Web
server, back to your browser.
In more detail, here’s what happens when a Coldfusion page is opened:
1.The client requests a page that contains CFML tags.
2.The Web server passes files to ColdFusion Server if a page request contains a
ColdFusion file extension.
3.ColdFusion Server scans the page and processes all CFML tags.
4.ColdFusion Server then returns only HTML and other client-side technologies to
the Web server.
5.The Web server passes the page back to the browser
.
8Developing Web Applications with ColdFusion
C HAPTER 2
Chapter 2Writing Your First ColdFusion
Application
This chapter guides you through the ColdFusion development process as you create
a ColdFusion application page, save it, and view it in a browser.
Contents
•The Development Process............................................................................... 10
Whether you are creating a static HTML page or a ColdFusion application page, you
follow the same iterative process:
• Write some code.
• Save the code to a document or page.
• View the page in a browser.
• Modify the page.
• Save the page again.
• View it in a browser.
• and so on...
Writing Code
Although you can code your application pages using NotePad or any HTML editor, this
manual will use ColdFusion Studio because it affords many features that make
ColdFusion development easier. See Using ColdFusion Studiofor details. If you haven’t
already done so, you should install ColdFusion Studio.
From a coding perspective, the major difference between a static HTML page and a
ColdFusion application page is that ColdFusion pages contain ColdFusion Markup
Language (CFML). CFML is a markup language that's very similar in syntax to HTML
so Web developers find it intuitive.
Unlike HTML which defines how things are displayed and formatted on the client,
CFML identifies specific operations that are performed by ColdFusion Server.
To create a ColdFusion application page:
1.Open ColdFusion Studio.
2.Select File > New and select the Default Template for your new page.
I’d like to talk to someone in #Department#.
</CFOUTPUT>
</BODY>
</HTML>
Chapter 2: Writing Your First ColdFusion Application11
Saving Application Pages
Instead of saving pages with an HTM or HTML file extension, you save ColdFusion
application pages with a CFM or CFML extension. By default, the Web server knows to
pass a page that contains a CFM extension to the ColdFusion Server when it is
requested by a browser.
Save ColdFusion application pages underneath the Web root or another Web server
mapping so that the Web server can publish these pages to the Internet. For example,
you might want to create a directory
myapps and save your practice pages there.
To save the page:
1.Select File > Save.
2.Save your page as
For example, the directory path on your machine may be:
c:/inetpub/wwwroot/myapps on Windows NT or
<mywebserverdocroot>/myapps on UNIX
calldept.cfm in myapps under the Web root directory.
Viewing Application Pages
You view the application page on the Web server to ensure that the code is working as
expected. Presently, your page is very simple. But, as you add more code, you will want
to ensure that the page continues to work.
To view the page in a local browser:
1.Open a Web browser on your local machine and enter the following URL:
http://127.0.0.1/myapps/calldept.cfm
Where 127.0.0.1 refers to the localhost and is only valid when you are viewing
pages locally.
2.Use the Web browser facility that allows you to view a page’s source code to
examine the code that the browser uses for rendering.
Note that only HTML and text is returned to the browser.
12Developing Web Applications with ColdFusion
Compare the code that was returned to the browser with what you originally
created. Notice that the ColdFusion comments and CFML tags are processed, but
do not appear in the HTML file that’s returned to the browser.
Original ColdFusion pageHTML file returned by Web server
<HTML>
<HEAD>
<TITLE>Call Department</TITLE>
</HEAD>
<BODY>
<STRONG>Call Department</STRONG>
<!--- Set all variables --->
<CFSET Department="Sales">
<CFOUTPUT>
I’d like to talk to someone in
#Department#.
<!--- Display results --->
</CFOUTPUT>
</BODY>
</HTML>
The application page that you just created contains both HTML and CFML. You used
the CFML tag CFSET to define a variable, Department, and set its value to be "Sales."
You then used the CFML tag CFOUTPUT to display text and the value of the variable.
CodeDescription
<!--- Set all variables --->
<CFSET Department="Sales">
CFML comment, which is not returned in
the HTML page.
Creates a variable named Department and
sets the value equal to Sales.
<!--- Display results --->
<CFOUTPUT>
I’d like to talk to someone in
#Department#.
</CFOUTPUT>
CFML comment, which is not returned in
the HTML page.
Displays whatever appears between the
opening and closing CFOUTPUT tags, in
this case the text "I’d like to talk to
someone in" followed by the value of the
variable Department, which is "Sales."
Chapter 2: Writing Your First ColdFusion Application13
Variables
A Web application page is different from a static Web page because it can publish data
dynamically. This involves creating, manipulating, and outputting variables.
A variable stores data that can be used in applications. As with other programming
languages, you’ll set variables in ColdFusion to store data that you want to access later.
And you’ll reference a range of variables to perform different types of application
processing.
There are a variety of variable types that you can create and reference in your
ColdFusion applications. Also, ColdFusion variables are typeless, which means that
you don’t need to define whether or not the variable value is numeric, text, or timedate. See the CFML Language Reference for a complete list of variable types
The primary differences between variable types are where they exist, how long they
exist, and where their values are stored. These considerations are referred to as a
variable’s scope.
You will learn more about scope as needed throughout this book.
For example, you would store a user’s preferences in a variable in order to use that data
to customize the page that’s returned to the browser.
You don’t use pound signs when you create the variable. However, when you want to
display the value that a variable is set to, enclose the variable name in pound signs (#).
The following table illustrates the use of pound signs and variable names.
CFML CodeResults
<CFSET Department="Sales">
<CFOUTPUT>
I’d like to talk to someone in
Department.
</CFOUTPUT>
<CFOUTPUT>
I’d like to talk to someone in
#Department#.
</CFOUTPUT>
The variable named Department is created
and the value is set to Sales.
ColdFusion doesn’t treat Department as a
variable because it isn’t surrounded by
pound signs. The HTML page will display:
I’d like to talk to someone in Department.
ColdFusion replaces the variable Department
with its value. The HTML page will display:
I’d like to talk to someone in Sales.
14Developing Web Applications with ColdFusion
Adding More Variables to the Application
Applications can use many different variables. For example, the calldept.cfm
application page can set and display values for department, city, and salary.
To modify the application:
1.Return to the file calldept.cfm in ColdFusion Studio,
4I’d like to talk to someone in #Department# in #city# who earns at
least #Salary#.
</CFOUTPUT>
</BODY>
</HTML>
3.Save the file.
4.View the page in your Web browser by entering the following URL:
http://127.0.0.1/myapps/calldept.cfm
Development Considerations
The same development rules that apply for any programming environment apply to
ColdFusion. You should also follow the same programming conventions that you
would with any other language:
• Comment your code as you go.
HTML comments use this syntax: <!-- html comment -->
CFML comments add an extra dash: <!--- cfml comment --->
• File names should be all one word, begin with a letter and can contain only
letters, numbers and the underscore.
• File names should not contain special characters.
C HAPTER 3
Chapter 3Querying a Database
This chapter describes how to retrieve data from a database, work with query data,
and enable debugging in ColdFusion applications. You will learn how to use the
ColdFusion Administrator to set up a data source and enable debugging, use the
CFQUERY tag to query a data source, and use the CFOUTPUT tag to output the query
results to a Web page.
•Getting Information About Query Results..................................................... 27
16Developing Web Applications with ColdFusion
Publishing Dynamic Data
A Web application page is different from a static Web page because it can publish data
dynamically. This can involve querying databases, connecting to LDAP or mail servers,
and leveraging COM, DCOM, CORBA, or Java objects to retrieve, update, insert, and
delete data at runtime — as your users interact with pages in their browsers.
For ColdFusion developers, the term "data source" can refer to a number of different
types of structured content accessible locally or across a network. You can query Web
sites, LDAP servers, POP mail servers, and documents in a variety of formats.
Most commonly though, a database will drive your applications, and for this
discussion a data source is defined as the entry point for database operations.
During this chapter, you will build a query to retrieve data from
Access database. In subsequent chapters in this book, you will insert and update data
in this database.
To build a query, you will need to use:
• ColdFusion data sources
• The CFQUERY tag
• SQL commands
company.mdb, an
Database Basics
You don't need a thorough knowledge of databases to develop a data-driven
ColdFusion application, but you will need to learn some basic concepts and
techniques.
A database is a structure for storing information. Databases are organized in tables,
which are collections of related items. For example, a table might contain the names,
street addresses, and phone numbers of individuals. Think of a table as a grid of
columns and rows. In this case, one column contains names, a second column
contains street addresses, and the third column contains phone numbers. Each row
constitutes one data record because the data in that row applies to a unique item, in
this case, one individual. Rows are also referred to as records. Columns are also
referred to as fields.
Chapter 3: Querying a Database17
Data can be organized in multiple tables. This type of data structure is known as a
relational database and is the type used for all but the simplest data sets.
From this basic description, a few database design rules emerge:
• Each record should contain a unique identifier, known as the primary key.
This could be an employee ID, a part number, or a customer number. This is
typically the column used to maintain each record’s unique identity among the
tables in a relational database.
• Once a column has been defined to contain a specific type of information, the
data must be entered in that column in a consistent way.
This is accomplished by defining a data type for the column, such as allowing
only numeric values to be entered in the salary column.
• Assessing user needs and incorporating those needs in the database design is
essential to a successful implementation. A well-designed database
accommodates the changing data needs within an organization.
The best way to familiarize yourself with the capabilities of your database product or
DBMS is to review the product documentation.
18Developing Web Applications with ColdFusion
Understanding Data Sources
A database is a file or server that contains a collection of data. A data source is a pointer
from ColdFusion to a specific database. You add data sources to your ColdFusion
Server so that you can point to the databases that you want to connect to from your
ColdFusion applications.
Open Database Connectivity (ODBC)
ODBC is a standard interface for connecting to a database from an application.
Applications that use ODBC must have an ODBC driver installed and configured for
each data source.
On Windows, you can check your system’s installed drivers by opening the ODBC Data
Source Manager in the Windows Control Panel.
On Windows, the installed set of ColdFusion ODBC drivers includes:
• Microsoft SQL Server
• Microsoft Access and FoxPro databases
• Borland dBase-compliant databases
• Microsoft Excel worksheet data ranges
• Delimited text files
On UNIX, look in the ODBC page of the ColdFusion Administrator for a list of avalable
ODBC drivers.
A good source of information on ODBC is the ODBC Programmer’s Reference at http://
www.microsoft.com/data/odbc.
Chapter 3: Querying a Database19
Adding Data Sources
You add data sources in the ColdFusion Administrator to define connection
requirements for database access.
When you add a data source, you assign it a name so that you can reference it within
tags such as CFQUERY on application pages to query databases. During a query, the
data source tells ColdFusion which database to connect to and what parameters to use
for the connection.
To add a data source:
1.Start the ColdFusion Administrator. On Windows, Select Start > Programs >
ColdFusion Server > ColdFusion Administrator. On UNIX, enter the URL
hostname/CFIDE/administrator in your browser.
The Administrator prompts you for a password if you assigned one to the
ColdFusion Server during install.
2.Enter a password to gain access to the Administrator.
3.Choose ODBC under the Data Sources heading on the left menu.
4.Name the data source
5.Select Microsoft Access Driver (*.mdb) from the dropdown box to describe the
ODBC driver.
6.Choose Add.
7.In the Database File field, enter the full path of the company.mdb Access database
and click OK.
8.Choose Create to create the CompanyInfo data source.
CompanyInfo.
20Developing Web Applications with ColdFusion
The data source is added to the data source list.
9.Locate
10. Choose Verify to run the verification test on the data source.
For more information about managing data sources, See Administering ColdFusion
Server.
CompanyInfo in the data source list.
If the data source was created, you should see this message:
The connection to the data source was verified successfully.
Data Source Notes and Considerations
When adding data sources to ColdFusion Server, keep these guidelines in mind:
• Data source names should be all one word and begin with a letter.
• Data source names can contain only letters, numbers and the underscore.
• Data source names should not contain special characters.
• Although data source names are not case-sensitive, you should use a consistent
capitalization scheme.
• A data source must exist in the ColdFusion Administrator before you use it on
an application page to retrieve data.
Retrieving Data
You can query databases to retrieve data at runtime. When retrieving data from a
database:
• You use the CFQUERY tag on a page to tell ColdFusion how to connect to a
database and how to store the retrieved data.
• You write SQL commands inside the CFQUERY block to specify the data that
you want to retrieve from the database.
• The retrieved data is stored on that page as a query variable.
• You can reference the query variable data on that page in a CFOUTPUT block to
use its values.
The CFQUERY Tag
The CFQUERY tag is one of the most frequently used CFML tags. You use it in
conjunction with the CFOUTPUT tag so that you can retrieve and reference the data
returned from a query.
When ColdFusion encounters a CFQUERY tag on a page, it does the following:
• Connects to the specified data source.
Chapter 3: Querying a Database21
• Performs SQL commands that are enclosed within the block.
• Returns query variable values to the page.
CFQUERY tag syntax
<CFQUERY NAME="EmpList" DATASOURCE="CompanyInfo">
You’ll type SQL here
</CFQUERY>
In this example, the query code tells ColdFusion to:
• Use the
• Store the retrieved data in the query variable EmpList.
In general, you should follow these guidelines:
• The CFQUERY tag is a block tag, that is, it has an opening <CFQUERY> and
ending </CFQUERY> tag.
• Use the NAME attribute to name the query variable so that you can reference it
later on the page.
• Use the DATASOURCE attribute to name an existing data source that should be
used to connect to a specific database.
• Always surround attribute values with double quotes (").
• Place SQL statements inside the CFQUERY block to tell the database what to
process during the query.
• When referencing text literals in SQL, use single quotes (’). For example, Select
* from mytable WHERE FirstName=’Russ’
in which the first name is Russ.
CompanyInfo data source to connect to the company.mdb database.
selects every record from mytable
NoteThe data source must exist in order to perform a successful query.
Writing SQL
In between the begin and end CFQUERY tags, write the SQL that you want the
database to execute.
For example, to retrieve data from a database:
TipIf you are using ColdFusion Studio, you can use the Query Builder to
• Write a SELECT statement that lists the fields or columns that you want to
select for the query.
• Follow the SELECT statement with a FROM clause that specifies the database
tables that contain the columns.
build SQL statements by graphically selecting the tables, and records
within those tables you want to retrieve. See Using ColdFusion Studio for
details.
22Developing Web Applications with ColdFusion
When the database processes the SQL, it creates a data set that is returned to
ColdFusion Server. ColdFusion places the data set in memory and assigns it the name
that you defined for the query in the begin CFQUERY tag.
You may reference that data set by name using the CFOUTPUT tag further down on the
page.
Basic SQL Syntax elements
The following sections present brief descriptions of the main SQL command elements.
Statements
These keywords identify commonly-used SQL commands:
Basic SQL Statements
KeywordDescription
SELECTRetrieves the specified records
INSERTAdds a new row
UPDATEChanges values in the specified rows
DELETERemoves the specified rows
Statement clauses
These keywords are used to refine SQL statements:
Basic SQL Clauses
KeywordDescription
FROMNames the data source for the operation
WHERESets one or more conditions for the operation
ORDER BYSorts the result set in the specified order.
GROUP BYGroups the result set by the specified select list items.
Chapter 3: Querying a Database23
Operators
These specify conditions and perform logical and numeric functions:
Basic SQL Operators
OperatorDescription
ANDBoth conditions must be met, such as Paris AND Texas
ORAt least one condition must be met, such as Smith OR Smyth
NOTExclude the condition following, such as Paris NOT France
=Equal to
<>Not equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to
+Addition
-Subtraction
/Division
*Multiplication
SQL Notes and Considerations
Keep the following in mind when writing SQL in ColdFusion:
• There is a lot more to SQL than what is covered here. It’s a good idea to
purchase one or several SQL guides that you can refer to.
• The data source, columns, and tables that you reference must exist in order to
perform a successful query.
• Some DBMS vendors use non-standard SQL syntax (known as a dialect) in their
products. ColdFusion does not validate the SQL in a CFQUERY, so you are free
to use any syntax that is supported by your data source. Check your DBMS
documentation for non-standard SQL usage.
24Developing Web Applications with ColdFusion
Building Queries
As discussed earlier in this chapter, you build queries using the CFQUERY tag and SQL.
3.Save the page as emplist.cfm in myapps under the Web root directory. For
example, the directory path on your machine may be:
C:\INETPUB\WWWROOT\myapps on Windows NT
4.Return to your browser and enter the following URL to view
http://127.0.0.1/myapps/emplist.cfm
5.View source in the browser.
The ColdFusion EmpList data set is created by ColdFusion Server, but only HTML
and text is sent back to the browser. To display the data set on the page, you must
code tags and variables to output the data.
EmpList.cfm:
Code Review
The query you just created retrieves data from the CompanyInfo database.
CodeDescription
<CFQUERY NAME="EmpList"
DATASOURCE="CompanyInfo">
SELECT FirstName, LastName,
Salary, Contract
FROM Employees
</CFQUERY>
Query the database specified in the
CompanyInfo datasource
Get information from the FirstName,
LastName, Salary, and Contract fields in
the Employees table
End the CFQUERY block
Chapter 3: Querying a Database25
Query Notes and Considerations
When creating queries to retrieve data, keep these guidelines in mind:
• Enter the query NAME and DATASOURCE attributes in the begin CFQUERY tag.
• Surround attribute settings with double quotes(").
• Reference the query data by naming the query in the CFOUTPUT tag later on
the page.
• Make sure that a data source exists in the ColdFusion Administrator before you
reference iit n a CFQUERY tag.
• The SQL that you write is sent to the database and performs the actual data
retrieval.
• Columns and tables that you refer to in your SQL statement must exist,
otherwise the query will fail.
Outputting Query Data
After you have defined a query on a page, you can use the CFOUTPUT tag with the
QUERY attribute to define the query variable that you want to output to a page. When
you use the QUERY attribute:
• ColdFusion loops over all the code contained within the CFOUTPUT block,
once for each row returned from a database.
• Reference specific column names within the CFOUTPUT block to output the
data to the page.
• You can place text and HTML tags inside or surrounding the CFOUTPUT block
to format the data on the page.
The CFOUTPUT tag accepts a variety of optional attributes but, ordinarily, you will use
the QUERY attribute to define the name of an existing query.
4.View the page in a browser.
A list of employees appears in the browser, with each line displaying one row of
data.
You have created a ColdFusion application page that retrieves and displays data from a
database. At present, the output is raw. You will learn how to format the data in the
next chapter.
Code Review
You now display the results of the query on the page.
CodeDescription
<CFOUTPUT QUERY="EmpList">
Display information retrieved in the
EmpList query
#FirstName#, #LastName#,
#Salary#, #Contract#
Display the value of the FirstName,
LastName, Salary, Contract
fields of the first record
<BR>
Insert a line break (go to the next line
Then, keep displaying the fields
you’ve specified for each record,
followed by a line break, until you run
out of records.
</CFOUTPUT>
End the CFOUTPUT block
Query Output Notes and Considerations
When outputting query results, keep these guidelines in mind:
• Run a CFQUERY before referencing its results using a CFOUTPUT with a
QUERY attribute.
• It’s a good idea to run all queries before all output blocks.
• A query name must exist on the page in order to successfully output its data.
• Surround variable references with pound signs to output their current values to
a page.
• Prefix variables with their variable type — in the case of a query variable, it's the
name of the query.
Chapter 3: Querying a Database27
• When outputting the data itself, you define the variable name using the QUERY
attribute.
• When outputting query properties variables, don’t use the QUERY attribute;
instead, prefix the variable reference with the name of the query, for example,
EmpList.RecordCount.
• Columns must exist and be retrieved to the application in order to output their
values.
• As with other attributes, surround the QUERY value with double quotes (").
• As with any variables that you reference for output, surround column names
with pound signs (#) to tell ColdFusion to output the column’s current values.
• Add a <BR> tag to the end of the variable references so that ColdFusion will
start a new line for each row that is returned from the query.
Getting Information About Query Results
Each time you query a database with the CFQUERY tag, you get not only the data itself,
but also query properties, as described in the following table::
Query Properties
PropertyDescription
RecordCountThe total number of records returned by the query.
ColumnListReturns a comma-delimited list of the query columns.
CurrentRowThe current row of the query being processed by CFOUTPUT.
4 <CFOUTPUT>
4 The query returned #EmpList.RecordCount# records.
4 </CFOUTPUT>
</BODY>
</HTML>
3.Save the file as emplist.cfm.
4.View the page in a browser.
The number of employees now appears below the list of employees.
Code Review
You now display the number of records retrieved in the query.
CodeDescription
<CFOUTPUT>
The query returned
#EmpList.RecordCount#
Display what follows
Display the text "The query returned"
Display the number of records
retrieved in the EmpList query
records.
</CFOUTPUT>
Display the text "records"
End the CFOUTPUT block.
Query Properties Notes and Considerations
Keep the following in mind when using query properties:
• Prefix the property with its type — in this case — prefix the property with the
name of the query.
• Reference the query property within a CFOUTPUT block so that ColdFusion
will output the query variable value to the page.
• Surround the query property reference with pound signs (#) so that ColdFusion
knows to replace the property name with its current value.
C HAPTER 4
Chapter 4Retrieving and Formatting the
Data You Want
This chapter explains how to select the data to display in a dynamic Web page. It also
describes how to populate an HTML table with query results and how to use
ColdFusion functions to format and manipulate data.
Contents
•Using Forms to Specify the Data to Retrieve.................................................. 30
•Processing Form Variables on Action Pages................................................... 34
•Returning Query Results to the User .............................................................. 42
30Developing Web Applications with ColdFusion
Using Forms to Specify the Data to Retrieve
Until now, you’ve retrieved all of the records from a table. However, there are many
instances when you’ll want to retrieve data based on certain criteria. For example, you
may want to see records for everyone in a particular department, everyone in a
particular town whose last name is Smith, or books by a certain author.
You can use forms in ColdFusion applications to allow users to specify what data they
want to retrieve in a query.
When you submit a form, you pass the variables to an associated page, called an action
page, where some type of processing takes place.
NoteBecause forms are not ColdFusion-specific, the syntax and examples that
follow provide you with just enough detail to get going with ColdFusion.
FORM tag syntax
<FORM ACTION="actionpage.cfm" METHOD="Post">
...
</FORM>
• Use the ACTION attribute to specify an action page to which you pass form
variables for processing.
• Use the METHOD attribute to specify how the variables are submitted from the
browser to the action page on the server.
All ColdFusion forms must be submitted with an attribute setting of
METHOD="Post".
Form Controls
Within the form, you’ll describe the form controls needed to gather and submit user
input. There are a variety of form controls types available. You choose form control
input types based on the type of input the user should provide.
Chapter 4: Retrieving and Formatting the Data You Want31
<HTML>
<HEAD>
<TITLE>Input form</TITLE>
</HEAD>
<BODY>
<!--- define the action page in the form tag. The form variables will
pass to this page when the form is submitted --->
<form action="actionpage.cfm" method="post">
<!-- text box -->
<p>
First Name: <INPUT TYPE="Text" NAME="FirstName" SIZE="20"
MAXLENGTH="35"><br>
Last Name: <INPUT TYPE="Text" NAME="LastName" SIZE="20"
MAXLENGTH="35"><br>
Salary: <INPUT TYPE="Text" NAME="Salary" SIZE="10" MAXLENGTH="10">
</P>
Create a reset button to allow users to clear
the form. Put the text "Clear Form" on the
button.
Create a submit button to send the values
users enter to the action page for processing.
Put the text "Submit" on the button.
34Developing Web Applications with ColdFusion
Form Notes and Considerations
• To make the coding process easy to follow, name form controls the same as
target database fields.
• Limit radio buttons to three-to-five mutually exclusive options.
If you need more than that many options, consider a dropdown select box.
• Use select boxes to allow the user to choose multiple items.
• All the data that you collect on a form is automatically passed as form variables
to the associated action page.
• Checkboxes and radio buttons do not pass to action pages unless they are
selected on a form. In fact, if you try to reference these variables on the action
page, you will receive an error if they are not present.
• You can dynamically populate dropdown select boxes using query data. See
“Dynamically Populating Select Boxes” on page 46 for details.
Processing Form Variables on Action Pages
A ColdFusion action page is just like any other application page except that you can
use the form variables that are passed to it from an associated form. A form variable is
passed for every form control that contains a value when the form is submitted.
NoteIf multiple controls have the same name, one form variable is passed to
the action page. It contains a comma delimited list.
A form variable's name is the name that you assigned to the form control on the form
page. Refer to form variable by name within tags, functions and other expressions on
an action page.
Because form variables extend beyond the local page — their scope is the action page
— prefix them with "form." to explicitly tell ColdFusion that you are referring to a form
variable. For example this code references the LastName form variable for output on
an action page:
<CFOUTPUT>
#Form.LastName#
</CFOUTPUT>
Dynamically Generating SQL Statements
As you've already learned, you can retrieve a record for every employee in a database
table by composing a query like this:
SELECT FirstName, LastName, Contract
FROM Employees
</CFQUERY>
Chapter 4: Retrieving and Formatting the Data You Want35
But when you want to return information about employees that match user search
criteria, you use the SQL WHERE clause with a SQL SELECT statement to compare a
value against a character string field. When the WHERE clause is processed, it filters
the query data based on the results of the comparison.
For example, to return employee data for only employees with the last name of Allaire,
you would build a query that looks like this:
WHERE LastName=’#Form.LastName#’
</CFQUERY>
<H4>Employee Data Based on Criteria from Form</H4>
<CFOUTPUT query="GetEmployees">
#FirstName#
#LastName#
#Salary#<BR>
</CFOUTPUT>
</BODY>
</HTML>
3.Save the page as actionpage.cfm within the myapps directory.
4.View
formpage.cfm in your browser.
36Developing Web Applications with ColdFusion
5.Enter data for the LastName form control and submit it.
6.Return to the form in your browser.
7.Reset the values.
8.Do not check the checkbox and submit the form again.
An error occurs when the checkbox does not pass to the action page.
You will receive errors if you submit the form without checking the checkbox form
controls. You will learn how to apply conditional logic to your action page to
compensate for this HTML limitation in “Testing for a variable's existence” on
SELECT FirstName, LastName, Salary
FROM Employees
WHERE LastName=’#Form.LastName#’
<CFOUTPUT query="GetEmployees">
#FirstName#
#LastName#
#Salary#<BR>
</CFOUTPUT>
Form Variable Notes and Considerations
When using form variables, keep the following guidelines in mind:
• A form variable's scope is the action page.
• Prefix form variables with "form." when referencing them on the action page.
• Surround variable values with pound signs (#) for output.
• Checkboxes and radio buttons are only passed to the action page if an option is
selected.
Query the datasource CompanyInfo and name
the query GetEmployees.
Retrieve the FirstName, LastName, and Salary
fields from the Employees table, but only if the
value of the LastName field matches what the
user entered in the LastName text box in the
form on
formpage.cfm.
Display results of the GetEmployees query.
Display the value of the FirstName, LastName,
and Salary fields for a record, starting with the
first record, then go to the next line. Keep
displaying the records that match the criteria
you specified in the SELECT statement,
followed by a line break, until you run out of
records
Close the CFOUTPUT block
Chapter 4: Retrieving and Formatting the Data You Want37
• Form variables for checkboxes and radio buttons generate errors on action
pages if nothing is selected for the form controls.
Using HTML Tables to Layout Query Results
You have displayed each row of data from the Employees table, but the information
was unformatted. You can use HTML tables to control the layout of information on the
page. In addition, you can use CFML functions to format individual pieces of data such
as dates and numeric values.
You can use HTML tables to specify how the results of a query appear on a page. To do
so, you put the CFOUTPUT tag inside the table tags. You can also use the HTML TH tag
to put column labels in a header row. To create a row in the table for each row in the
query results, put the TR block inside the CFOUTPUT tag.
To put the query results in a table:
1.Return to the file emplist.cfm in Studio.
2.Modify the page so that it appears as follows:
<HTML>
<HEAD>
<TITLE>Retrieving Employee Data Based on Criteia from Form</TITLE>
</HEAD>
You may want to format individual data items. For example, you can format the Salary
field as a monetary value.
To format the Salary using the dollar format, you use the CFML expression
DollarFormat(number).
Put data into a table.
In the first row of the table, include three
columns, with the headings: First Name, Last
Name, and Salary.
Get ready to display the results of the
GetEmployees query.
Create a new row in the table, with three
columns. For a record, put the value of the
FirstName field, the value of the LastName field,
and the value of the Salary field.
Keep getting records that matches the criteria,
and display each row in a new table row until
you run out of records.
End of table.
To change the format of the Salary:
1.Return to actionpage.cfm in Studio.
2.Change the line
<TD>#Salary#</TD> to <TD>#DollarFormat(Salary)#</TD>
Chapter 4: Retrieving and Formatting the Data You Want39
Performing Pattern Matching
Use the SQL LIKE operator and SQL wildcard strings in a SQL WHERE clause when you
want to compare a value against a character string field so that the query returns
database information based on commonalities. This is known as pattern matching and
often used to query databases.
For example, to return data for employees whose last name starts with AL and ends
with anything, you would build a query that looks like this:
SELECT FirstName, LastName
StartDate, Salary, Contract
FROM Employees
WHERE Contract = ’Yes’
AND Salary > 50000
</CFQUERY>
40Developing Web Applications with ColdFusion
Creating Table Joins
Many times, the data that you want to retrieve is maintained in multiple tables. For
example, in the database that you’re working with:
• Department information is maintained in the Departments table. This includes
department ID numbers.
• Employee information is maintained in the Employees table. This also includes
department ID numbers.
To compare and retrieve data from more than one table during a query, use the
WHERE clause to join two tables through common information.
For example, to return employee names, start dates, department names, and salaries
for employees that work for the HR department, you would build a query that looks
like this:
SELECT Departments.Department.Name,
Employees.FirstName,
Employees.LastName,
Employees.StartDate,
Employees.Salary
FROM Departments, Employees
WHERE Departments.Department_ID = Employees.Department_ID
AND Departments.Department_Name = ’HR’
</CFQUERY>
• Prefix each column in the SELECT statement to explicitly state which table the
data should be retrieved from.
• The Department_ID field is the primary key of the Departments table and the
Foreign Key of the Employees table.
Building Flexible Search Interfaces
Frequently, you will want users to optionally enter multiple search criteria.
Wrap conditional logic around the SQL AND clause to build a flexible search interface.
To test for multiple conditions, wrap additional CFIF tags around additional AND
clauses.
For example, to allow users to search for employees by last name, department, or both,
you would build a query that looks like this:
4.Test the search interface in your browser.
The returned records will not be displayed because you have not entered that code
yet, however, you will see the number of records returned if you have debugging
enabled.
Returning Query Results to the User
When you build search interfaces, keep in mind that there won’t always be a record
returned. If there is at least one record returned from a query, you will usually format
that data using an HTML table. But to make sure that a search has retrieved records,
you will need to test if any records have been returned using the recordcount variable
in a conditional logic expression in order to display search results appropriately to
users.
For example, to inform the user that no records were found if the number of records
returned for the GetEmployees query is 0, insert the following code before displaying
the data:
<CFIF GetEmployees.RecordCount IS "0">
No records match your search criteria. <BR>
<CFELSE>
• Prefix RecordCount with the queryname.
• Add a true procedure that displays a message to the user.
• Add a not true procedure after the CFELSE tag to format the returned data
using an HTML table.
To return search results to users:
1.Return to actionpage.cfm in Studio.
2.Add the code indicated.
<HTML>
<HEAD>
<TITLE>Retrieving Employee Data Based on Criteia from Form</TITLE>
</HEAD>
Chapter 4: Retrieving and Formatting the Data You Want43
In the previous chapter, you hard-coded a form’s select box options.
Instead of manually entering the information on a form, you can dynamically populate
a select box with database fields. When you code this way, changes that you make to a
database are automatically reflected on the form page.
To dynamically populate a select box:
• Use the CFQUERY tag to retrieve the column data from a database table.
• Use the CFOUTPUT tag with the QUERY attribute within the SELECT tag to
dynamically populate the OPTIONS of this form control.
The changes that you just made appear in the form.
Remember that you need an action page to submit values.
Creating Dynamic Checkboxes and Multiple Select Boxes
When an HTML form contains either a list of checkboxes with the same name or a
multiple select box, the user’s entries are made available as a comma-delimited list
with the selected values. These lists can be very useful for a wide range of inputs.
NoteIf no value is entered for a checkbox or multiple select lists, no variable is
created.The SQL INSERT statement will not work correctly if there are no
values. To correct this problem, make the form fields required, use
Dynamic SQL, or use CFPARAM to establish a default value for the form
field..
Checkboxes
When you put a series of checkboxes with the same name in an HTML form, the
variable that is created contains a comma-delimited list of values. The values can be
either numeric values or alphanumeric strings. These two types of values are treated
slightly differently.
48Developing Web Applications with ColdFusion
Searching numeric values
Suppose you want a user to select one or more departments using checkboxes. You
query the database to retrieve detailed information on the selected department(s).
Select one or more departments to get information on:
<INPUT TYPE="checkbox"
NAME="SelectedDept"
VALUE="1">
Training<BR>
<INPUT TYPE="checkbox"
NAME="SelectedDept"
VALUE="2">
Marketing<BR>
<INPUT TYPE="checkbox"
NAME="SelectedDept"
VALUE="3">
HR<BR>
<INPUT TYPE="checkbox"
NAME="SelectedDept"
VALUE="4">
Sales<BR>
<INPUT TYPE="hidden"
NAME="SelectedDepts_required"
VALUE="You must select at least one organization.">
The text displayed to the user is the name of the department, but the VALUE attribute
of each checkbox corresponds to the underlying database primary key for the
department’s record.
If the user checked the Marketing and Sales items, the value of the SelectedDept form
field would be "2,4." If this parameter were used, the following would be the resulting
SQL statement:
SELECT *
FROM Departments
WHERE Department_ID IN ( #form.SelectedDept# )
The statement sent to the database would be:
SELECT *
FROM Departments
WHERE Department_ID IN ( 2,4 )
Searching string values
To search for a database field containing string values (instead of numeric), you must
modify both the checkbox and CFQUERY syntax.
Chapter 5: Making Variables Dynamic49
The first example searched for department information based on a numeric primary
key field called "Department_ID." Suppose, instead, that the primary key is a database
field called "DepartmentName" that contains string values. In that case, it’s necessary
to make the following modifications:
• Make the value attribute of the checkboxes equal to the string value.
NAME="SelectedDepts_required"
VALUE="You must select at least one organization.">
If the user checked Marketing and Sales, the value of the SelectedDepts form field
would be ’Marketing’,’Sales’.
NoteYou must use the ColdFusion PreserveSingleQuotes function in the SQL
statement to prevent ColdFusion from escaping the single quotes in the
form field value:
SELECT *
FROM Departments
WHERE DepartmentName IN
(#PreserveSingleQuotes(form.SelectedDepts)#)
The statement sent to the database would be:
SELECT *
FROM Departments
WHERE DepartmentName IN (’Marketing’,’Sales’)
Multiple select lists
ColdFusion treats multiple select lists (HTML input type SELECT with attribute
MULTIPLE) just like checkboxes. The data made available to your page from any
50Developing Web Applications with ColdFusion
multiple select list is a comma-delimited list of the entries selected by the user. For
example, a multiple select list contains four entries: Training, Marketing, HR, and
Sales. The user selects Marketing and Sales. The value of the form field variable is then
’Marketing’, ’Sales’.
Just as you can with checkboxes, you can also query with multiple select lists by
searching a database field that contains either numeric values or string values.
Searching numeric values
For example, suppose you want the user to select departments from a multiple select
box. The query retrieves detailed information on the selected department(s):
Select one or more companies to get more information on:
<SELECT Name="SelectDepts" MULTIPLE>
NAME="SelectDepts_required"
VALUE="You must select at least one department.">
If the user selected the Marketing and Sales items, the value of the SelectDepts form
field would be 2,4.
If this parameter were used in the following SQL statement:
SELECT *
FROM Departments
WHERE Department_ID IN (#form.SelectDepts#)
the statement sent to the database would be:
SELECT *
FROM Departments
WHERE Department_ID IN (2,4)
Searching string values
Suppose you want the user to select departments from a multiple select list. The
database field search is a string field. The query retrieves detailed information on the
selected department(s):
Select one or more departments to get
more information on:
<SELECT Name="SelectDepts" MULTIPLE>
NAME="SelectDepts_required"
VALUE="You must select at least one department.">
If the user selected the Marketing and Sales items, the value of the SelectDepts form
field would be ’Marketing’,’Sales’.
Just as you did when using checkboxes to search database fields containing string
values, use the ColdFusion PreserveSingleQuotes function with multiple select boxes:
SELECT *
FROM Departments
WHERE DepartmentName IN (#PreserveSingleQuotes(form.SelectDepts)#)
The statement sent to the database would be:
SELECT *
FROM Departments
WHERE DepartmentName IN (’Marketing’, ’Sales’)
Testing for a variable’s existence
Before relying on a variable’s existence in an application page, you can test to see if it
exists using the IsDefined function. For example, the following code checks to see if a
Form variable named Order_ID exists:
<CFIF Not IsDefined("FORM.Order_ID")>
<CFLOCATION URL="previous_page.cfm">
</CFIF>
The argument passed to the IsDefined function must always be enclosed in double
quotes. See the CFML Language Reference for more information on the IsDefined
function.
If you attempt to evaluate a variable that has not been defined, ColdFusion will not be
able to process the page. To help diagnose such problems, use the interactive debugger
in ColdFusion Studio or turn debugging on in the ColdFusion Administrator. The
Administrator debugging information shows which variables are being passed to your
application pages.
Creating Default Variables with CFPARAM
Another way to create a variable is to test for its existence and optionally supply a
default value if the variable does not already exist. The following shows the syntax of
the CFPARAM tag:
<CFPARAM NAME="
TYPE="
DEFAULT="
VariableName
data_type
DefaultValue
"
"
">
52Developing Web Applications with ColdFusion
There are two ways to use the CFPARAM tag, depending on how you want the
validation test to proceed.
• Use CFPARAM with only the NAME attribute to test that a required variable
exists. If it does not exist, the ColdFusion server stops processing the page.
• Use CFPARAM with both the NAME and DEFAULT attributes to test for the
existence of an optional variable. If the variable exists, processing continues
and the value is not changed. If the variable does not exist, it is created and set
to the value of the DEFAULT attribute.
The following example shows how to use the CFPARAM tag to check for the existence
of an optional variable and to set a default value if the variable does not already exist:
<CFPARAM NAME="Form.Contract" DEFAULT="Yes">
Example: Testing for variables
Using CFPARAM with the NAME variable is a way to clearly define the variables that a
page or a custom tag expects to receive before processing can proceed. This can make
your code more readable, as well as easier to maintain and to debug.
For example, the following series of CFPARAM tags indicates that this page expects two
form variables named StartRow and RowsToFetch:
If the page with these tags is called without either one of the form variables, an error
occurs and the page stops processing.
Example: Setting default values
In this example, CFPARAM is used to see if optional variables exist. If they do exist,
processing continues. If they do not exist, they are created and set to the DEFAULT
value.
Embedding SQL queries that use dynamic parameters is a powerful mechanism for
linking variable inputs to database queries. However, in more sophisticated
applications, you will often want user inputs to determine not only the content of
queries but also the structure of queries.
Dynamic SQL allows you to dynamically determine (based on runtime parameters)
which parts of a SQL statement are sent to the database. So if a user leaves a search
field empty, for example, you could simply omit the part of the WHERE clause that
refers to that field. Or, if a user does not specify a sort order, the entire ORDER BY
clause could be omitted.
Dynamic SQL is implemented in ColdFusion by using CFIF, CFELSE, CFELSEIF tags to
control how the SQL statement is constructed, for example:
54Developing Web Applications with ColdFusion
<CFQUERY NAME="
DATASOURCE="
...
Base SQL statement
<CFIF value operator value >
additional SQL
...
</CFIF>
</CFQUERY>
queryname
datasourcename">
"
First, you need to create an input form, which asks for information about several fields
in the Employees table. Instead of entering information in each field, a user may want
to search on certain fields, or even on only one field. To search for data based on only
the fields the user enters in the form, you use CFIF statements in the SQL statement.
To create the input form:
1.Create a new application page in Studio.
2.Enter the following code:
<HTML>
<HEAD>
<TITLE>Input form</TITLE>
</HEAD>
<BODY>
<!--- Query the Employees table to be able to populate the form --->
<CFQUERY NAME="AskEmployees" DATASOURCE="CompanyInfo">
SELECT
FirstName,
LastName,
Salary,
Contract
FROM Employees
</CFQUERY>
<!--- define the action page in the form tag. The form variables will
pass to this page when the form is submitted --->
<FORM ACTION="getemp.cfm" METHOD="post">
<!-- text box -->
<P>
First Name: <INPUT TYPE="Text" NAME="FirstName" SIZE="20"
MAXLENGTH="35"><BR>
Last Name: <INPUT TYPE="Text" NAME="LastName" SIZE="20"
MAXLENGTH="35"><BR>
Salary: <INPUT TYPE="Text" NAME="Salary" SIZE="10" MAXLENGTH="10">
</P>
askemp.cfm in your browser and enter criteria into any fields, then
submit the form.
5.The results should meet the criteria you specify.
Code Review
The action page getemp.cfm build a SQL statement dynamically based on what the
user enters in the form page AskEmp.cfm.
CFML CodeDescription
SELECT *
FROM Employees
WHERE 0=0
<CFIF #Form.FirstName# is not "">
AND Employees.FirstName LIKE
’#form.FirstName#%’
</CFIF>
Get all the records from the Employees
table as long as 0=0.
The WHERE 0=0 clause has no impact on
the query submitted to the database. But
if none of the conditions is true, it ensures
that the WHERE clause does not result in a
SQL syntax error.
If the user entered anything in the
FirstName text box in the form, add "AND
Employees.FirstName LIKE ‘[what the user
entered in the FirstName text box]%'" to the
SQL statement.
Chapter 5: Making Variables Dynamic57
CFML CodeDescription
<CFIF #Form.LastName# is not "">
AND Employees.LastName LIKE
’#form.LastName#%’
</CFIF>
<CFIF #Form.Salary# is not "">
AND Employees.Salary >=
#form.Salary#
</CFIF>
<CFIF isDefined("Form.Contract") IS
"YES">
AND Employees.Contract = ’Yes’
<CFELSE>
AND Employees.Contract = ’No’
</CFIF>
If the user entered anything in the
LastName text box in the form, add "AND
Employees.LastName LIKE ‘[what the user
entered in the LastName text box]%'" to the
SQL statement.
If the user entered anything in the Salary
text box in the form, add "AND
Employees.Salary >= [what the user entered in the Salary text box]" to the SQL
statement.
If the user checked the Contractor check
box, get data for the employees who are
contractors, otherwise, get data for
employees who are not contractors.
58Developing Web Applications with ColdFusion
C HAPTER 6
Chapter 6Updating Your Data
This chapter describes how to insert, update, and delete data in a database with
ColdFusion.
•Requiring Users to Enter Values in Form Fields ............................................ 67
•Validating the Data That Users Enter in Form Fields.................................... 68
60Developing Web Applications with ColdFusion
Inserting Data
Inserting data into a database is usually done with two application pages:
• An insert form
• An insert action page
You can create an insert form with CFFORM tags (see “Creating Forms with the
CFFORM Tag” on page 124) or with standard HTML form tags. When the form is
submitted, form variables are passed to a ColdFusion action page that performs an
insert operation (and whatever else is called for) on the specified data source. The
insert action page can contain either a CFINSERT tag or a CFQUERY tag with a SQL
INSERT statement. The insert action page should also contain a message for the end
user.
Creating an HTML Insert Form
To create an insert form:
1.Create a new application page in Studio.
2.Edit the page so that it appears as follows:
<HTML>
<HEAD>
<TITLE>Insert Data Form</TITLE>
</HEAD>
<BODY>
<H2>Insert Data Form</H2>
<FORM ACTION="insertdata.cfm" METHOD="Post">
Employee ID:
<INPUT TYPE="text" NAME="Employee_ID" SIZE="4" MAXLENGTH="4"><BR>
First Name:
<INPUT TYPE="text" NAME="FirstName" SIZE="35" MAXLENGTH="50"><BR>
Last Name:
<INPUT TYPE="text" NAME="LastName" SIZE="10" MAXLENGTH="10"><BR>
Department Number:
<INPUT TYPE="text" NAME="Department_ID" SIZE="4"
3.Save the file as insertform.cfm in the myapps directory.
4.View
insertform.cfm in a browser.
Data Entry Form Notes and Considerations
Creating data entry fields for an HTML form is very simple:
• You need only create the HTML form fields for each database field into which
you want to insert data.
• The names of your form fields must be identical to the names of your database
fields.
• You can use the full range of HTML input controls, including list boxes, radio
buttons, checkboxes, and multi-line text boxes in your forms.
• ColdFusion uses the NAME attribute to map HTML form fields to the
corresponding database fields and inserts the data entered by the user into the
appropriate database fields.
Creating an Action Page to Insert Data
There are two ways to create an action page to insert data into a database.
The CFINSERT tag is the easiest way to handle simple inserts from either a CFFORM or
an HTML form.
For more complex inserts from a form submittal you can use a SQL INSERT statement
in a CFQUERY tag instead of a CFINSERT tag. The SQL INSERT statement is more
flexible because you can insert information selectively or use functions within the
statement.
<TITLE>Input Form</TITLE>
</HEAD>
<BODY>
<H1>Employee Added</H1>
<CFOUTPUT>
You have added #Form.FirstName# #Form.LastName# to the Employees
database.
</CFOUTPUT>
</BODY>
</HTML>
62Developing Web Applications with ColdFusion
3.Save the page. as insertpage.cfm.
4.View
insertform.cfm in a browser, enter values, and click the Submit button.
5.The data is inserted into the Employees table and the message appears.
To create an insert page with CFQUERY:
1.Create a new application page in Studio.
2.Enter the following code:
4<CFQUERY NAME="AddEmployee"
4DATASOURCE="CompanyInfoB">
4INSERT INTO Employees (Fi’, ’#Form.LastName#’,
4’#Form.Phone#’)
4</CFQUERY>
<HTML>
<HEADER>
<TITLE>Insert Action Page</TITLE>
</HEADER>
<BODY>
<H1>Employee Added</H1>
<CFOUTPUT>
You have added #Form.FirstName# #Form.LastName# to the Employees
database.
</CFOUTPUT>
</BODY>
</HTML>
3.Save the page. as insertpage.cfm.
4.View
5.The data is inserted into the Employees table and the message appears.
isertform.cfm in a browser, enter values, and click the Submit button.
Updating Data
Updating data in a database is usually done with two pages:
• An update form
• An update action page
You can create an update form with CFFORM tags or HTML form tags. The update
form calls an update action page, which can contain either a CFUPDATE tag or a
CFQUERY tag with a SQL UPDATE statement. The update action page should also
contain a message for the end user that reports on the update completion.
Chapter 6: Updating Your Data63
Creating an Update Form
An update form is similar to an insert form, but there are two key differences:
• An update form contains a reference to the primary key of the record that is
being updated.
A primary key is a field or combination of fields in a database table that
uniquely identifies each record in the table. For example, in a table of employee
names and addresses, only the Employee_ID would be unique to each record.
• Because the purpose of an update form is to update existing data, the update
form is usually populated with existing record data.
The easiest way to designate the primary key in an update form is to include a hidden
input field with the value of the primary key for the record you want to update. The
hidden field indicates to ColdFusion which record to update.
Query the CompanyInfo
datasource and return the records
in which the employee ID matches
what was entered in the URL.
Display the results of the
GetRecordtoUpdate query.
Create a form whose variables will
be process on the
EmployeeUpdate.cfm action page.
Use a hidden input field to pass the
employee ID to the action page.
Populate the fields of the update
form.
Chapter 6: Updating Your Data65
Creating an Action Page to Update Data
You can create an action page to update data with either the CFUPDATE tag or
CFQUERY with the UPDATE statement.
The CFUPDATE tag is the easiest way to handle simple updates from a front end form.
The CFUPDATE tag has an almost identical syntax to the CFINSERT tag.
To use CFUPDATE, you must include all of the fields that make up the primary key in
your form submittal. The CFUPDATE tag automatically detects the primary key fields
in the table you are updating and looks for them in the submitted form fields.
ColdFusion uses the primary key field(s) to select the record to update. It then updates
the appropriate fields in the record using the remaining form fields submitted.
For more complicated updates, you can use a SQL UPDATE statement in a CFQUERY
tag instead of a CFUPDATE tag. The SQL update statement is more flexible for
complicated updates.
To create an update page with CFUPDATE:
1.Create a new application page in Studio.
2.Enter the following code:
4<CFUPDATE DATASOURCE="CompanyInfo"
TABLENAME="Employees">
<HTML>
<HEAD>
<TITLE>Update Employee</TITLE>
</HEAD>
<BODY>
<H1>Employee Added</H1>
<CFOUTPUT>
You have updated the information for #Form.FirstName# #Form.LastName#
in the Employees database.
</CFOUTPUT>
</BODY>
</HTML>
3.Save the page. as updatepage.cfm.
4.View
updateform.cfm in a browser, enter values, and click the Submit button.
5.The data is updated in the Employees table and the message appears.
Deleting data in a database can be done with a single delete page. The delete page
contains a CFQUERY tag with a SQL delete statement.
To delete one record from a database:
1.Open the file updateform.cfm in Studio.
2.Modify the file by changing the FORM tag so that it appears as follows:
<FORM ACTION="deletepage.cfm" METHOD="Post">
3.Save the modified file as deleteform.cfm.
4.Create a new application page in Studio.
After the SET clause, you must name a table column.
Then, you indicate a constant or expression as the
value for the column.
Be sure to remember the WHERE statement. If you
do not use it, If you do not use it, the SQL UPDATE
statement will apply the new information to every
row in the database.
Chapter 6: Updating Your Data67
5.Enter the following code:
<CFQUERY NAME="DeleteEmployee"
DATASOURCE="CompanyInfo">
DELETE FROM Employees
WHERE Employee_ID = #URL.EmployeeID#
</CFQUERY>
<HTML>
<HEAD>
<TITLE>Delete Employee Record</TITLE>
</HEAD>
<BODY>
<H3>The employee record has been deleted.</H3>
</BODY>
</HTML>
6.Save the page. as deletepage.cfm.
7.View
deleteform.cfm in a browser, enter values, and click the Submit button.
The employee is deleted from the Employees table and the message appears.
To delete several records, you would specify a condition. The following example
demonstrates deleting the records for everyone in the Sales department from the
Employee table. The example assumes that there are several Employees in the sales
department.
DELETE FROM Employees
WHERE Department = ’Sales’
To delete all the records from the Employees table, you would use the following:
DELETE FROM Employees
NoteDeleting records from a database is not reversible. Use delete statements
carefully.
Requiring Users to Enter Values in Form Fields
One of the limitations of HTML forms is the inability to define input fields as required.
Because this is a particularly important requirement for database applications,
ColdFusion provides a server-side mechanism for requiring users to enter data in
fields.
To define an input field as required, use a hidden field that has a NAME attribute
composed of the field name and the suffix "_required." For example, to require that the
user enter a value in the FirstName field, use the syntax:
<INPUT TYPE="hidden" NAME="FirstName_required">
If the user leaves the FirstName field empty, ColdFusion rejects the form submittal and
returns a message informing the user that the field is required. You can customize the
contents of this error message using the VALUE attribute of the hidden field. For
68Developing Web Applications with ColdFusion
example, if you want the error message to read "You must enter your first name," use
the syntax:
<INPUT TYPE="hidden"
NAME="FirstName_required"
VALUE="You must enter your first name.">
Validating the Data That Users Enter in Form Fields
Another limitation of HTML forms is that you cannot validate that users input the type
or range of data you expect. ColdFusion enables you to do several types of data
validation by adding hidden fields to forms. The hidden field suffixes you can use to do
validation are as follows:
Form Field Validation Using Hidden Fields
Field SuffixValue AttributeDescription
_integer
Custom error
message
Verifies that the user enters a number. If the
user enters a floating point value, it is
rounded to an integer.
_float
_range
Custom error
message
MIN=MinValue
MAX=MaxValue
Verifies that the user enters a number. Does
not do any rounding of floating point values.
Verifies that the numeric value entered is
within the specified boundaries. You can
specify one or both of the boundaries
separated by a space.
_date
Custom error
message
Verifies that a date has been entered and
converts the date into the proper ODBC date
format. Will accept most common date forms,
for example, 9/1/98; Sept. 9, 1998).
_time
Custom error
message
Verifies that a time has been correctly entered
and converts the time to the proper ODBC
time format.
_eurodate
Custom error
message
Verifies that a date has been entered in a
standard European date format and converts
into the proper ODBC date format.
NoteAdding a validation rule to a field does not make it a required field. You
need to add a separate
entry.
_required hidden field if you want to ensure user
Chapter 6: Updating Your Data69
To validate the data users enter in the Insert Form
1.Open the file insertform.cfm in Studio.
2.Modify the file so that it appears as follows:
<HTML>
<HEAD>
<TITLE>Insert Data Form</TITLE>
</HEAD>
<BODY>
<H2>Insert Data Form</H2>
<FORM ACTION="insertdata.cfm" METHOD="Post">
<INPUT TYPE="hidden"
NAME="DeptID_integer"
VALUE="The department ID must be a number.">
<INPUT TYPE="hidden"
NAME="StartDate_date"
VALUE="Enter a valid date as the start date.">
<INPUT TYPE="hidden"
NAME="Salary_float"
VALUE="The salary must be a number.">
Employee ID:
<INPUT TYPE="text"
NAME="Employee_ID"
SIZE="4"
MAXLENGTH="4"><BR>
First Name:
<INPUT TYPE="text"
NAME="FirstName"
SIZE="35"
MAXLENGTH="50"><BR>
Last Name:
<INPUT TYPE="text"
NAME="LastName"
SIZE="10"
MAXLENGTH="10"><BR>
Department Number:
<INPUT TYPE="text"
The VALUE attribute is optional. A default message displays if no value is supplied.
When the form is submitted, ColdFusion scans the form fields to find any validation
rules you specified. The rules are then used to analyze the user’s input. If any of the
input rules are violated, ColdFusion sends an error message to the user that explains
the problem. The user then must go back to the form, correct the problem and
resubmit the form. ColdFusion will not accept form submission until the entire form is
entered correctly.
Because numeric values often contain commas and dollar signs, these characters are
automatically stripped out of fields with
_integer, _float, or _range rules before they
are validated and saved to the database.
NoteIf you use CFINSERT or CFUPDATE and you specified columns in your
database that are numeric, date, or time, form fields that insert data into
these fields are automatically validated. You can use the hidden field
validation functions for these fields to display a custom error message.
C HAPTER 7
Chapter 7Reusing Code
This chapter describes how to reuse common code with CFINCLUDE, and create
custom CFML tags that encapsulate common code.
Contents
•Ways to Reuse Code ......................................................................................... 72
•Reusing Common Code with CFINCLUDE.................................................... 72
•About Custom Tags in CFML........................................................................... 73
ColdFusion provides several different ways to reuse code. If you are using ColdFusion
Studio, you can write code snippets, which you can copy into templates. For more
information on writing code snippets, see Using ColdFusion Studio. You can include a
template within another template with the CFINCLUDE tag. In addition, you can
create custom tags in CFML. Unlike included templates, these custom tags act as other
tags do, allowing you to pass parameters to them. Included templates, on the other
hand, behave just as though you typed the included code directly into the calling page.
Reusing Common Code with CFINCLUDE
Often times, you’ll use some of the same elements in multiple pages; for example,
navigation, headers, and footer code.
Instead of copying and maintaining the same code from page to page, ColdFusion
allows you to store the code in one page and then refer to it in many pages. This way,
you can modify one file; the changes appear throughout an entire application.
Use the CFINCLUDE tag to automatically include an existing file in the current page.
The file to include is the template. The page that calls the template is also known as the
calling page. Each time the calling page is requested, the template’s file contents are
included in that page for processing.
Refer to the CFML Language Reference for CFINCLUDE syntax.
To reference code in a calling page:
1.Open the file askemp.cfm in Studio.
2.Include
<CFINCLUDE TEMPLATE="logo.cfm">
3.Save the page.
4.Open
5.Include
<CFINCLUDE TEMPLATE="Logo.cfm">
6.View askemp.cfm in a browser, then submit the form so that you display
getemp.cfm.
The logo should appear on both pages.
logo.cfm in this page:
getemp.cfm in Studio.
logo.cfm file in this page:
NoteThe file logo.cfm must be in the same directory where you saved
askemp.cfm and getemp.cfm. If it isn’t, make sure it is in a directory that
has a mapping defined in ColdFusion Administrator, or move it to the
appropriate directory.
Chapter 7: Reusing Code73
About Custom Tags in CFML
Custom tags wrap functionality in a page that can be called from a ColdFusion
application page. ColdFusion custom tags built in CFML allow for rapid application
development and code re-use while offering off-the-shelf solutions to many
programming chores.
An online RealVideo title called "Creating Custom Tags" is available at the Allaire Alive
section of our Web site. It presents an overview of custom tags as a component
architecture for the emerging Web platform and outlines the creation and use of CFML
custom tags.
Using Existing Custom Tags
Before creating a custom tag in CFML, you will probably want to visit the Custom Tag
section of the Allaire Developer Exchange at . Tags are grouped in several broad
categories and are downloadable as freeware, shareware, or commercial software. You
can quickly view each tag’s syntax and usage information. The Gallery contains a
wealth of background information on custom tags and an online discussion forum for
tag topics.
Tag names with the CF_ preface are CFML custom tags; those with the CFX_ preface
are ColdFusion Extensions written in C++. For more information about the CFX tags,
see Chapter 18, “Building Custom CFAPI Tags,” on page 275.
If you don't find a tag that meets your specific needs, you want to create your own
custom tags in CFML.
Writing Custom CFML Tags
Writing a custom tag in CFML is no different from writing any CFML template. You can
use all CFML constructs, as well as HTML.
Custom tags are stored either in the current directory or under the customtags
directory. You call them using the CF_ prefix. Beyond that, you are free to use any
naming convention that fits your development practice. Unique descriptive names
make it easy for you and others to find the right tag. For example, the tag name
CF_getweather invokes the file getweather.cfm
If you are concerned about possible name conflicts when invoking a custom tag or if
the application must use a variable to dynamically call a custom tag at runtime, the
CFMODULE element provides a solution.
NoteWhile tag names in templates are case-insensitive, custom tag file names
must be lower case on UNIX.
74Developing Web Applications with ColdFusion
Defining attributes
CFML custom tags support both required and optional attributes. Attributes are
defined as name-value pairs. Custom tag attributes conform to CFML coding
standards:
• ColdFusion passes any attributes in the ATTRIBUTES scope.
• Use the CFPARAM tag at the top of a custom tag to test for and assign defaults
for each attribute that may be passed from a calling template.
• Use the ATTRIBUTES.attribute_name syntax when initializing passed attributes
to distinguish them from local ones.
• Attributes are case-insensitive.
• Attributes may be listed in any order within a tag.
• Attribute = value pairs for a tag must be separated by a space.
• Passed values that contain spaces must be enclosed in double-quotes.
Passing Attribute Values between Custom Tags
Because custom tags are individual templates, variables and other data aren’t
automatically shared between a custom tag and the calling template. To pass data, you
define attributes for the custom tag, just as in standard CFML coding.
To pass data from the calling template to the custom tag, use the ATTRIBUTES scope.
Conversely, to pass values back to the calling template, use the CALLER scope. You can
also access variables already set on the calling page in the custom tag by simply
prefixing the variable with the ’CALLER.’ prefix.
To create a custom tag:
1.Create a new application page (the calling page) in Studio.
2.Modify the file so that it appears as follows:
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.