Afterburner, AppletAce, Attain, Attain Enterprise Learning System, Attain Essentials, Attain Objects for Dreamweaver,
Authorware, Authorware Attain, Authorware Interactive Studio, Authorware Star, Authorware Synergy, Backstage, Backstage
Designer, Backstage Desktop Studio, Backstage Enterprise Studio, Backstage Internet Studio, ColdFusion, Design in Motion,
Director, Director Multimedia Studio, Doc Around the Clock, Dreamweaver, Dreamweaver Attain, Drumbeat, Drumbeat 2000,
Extreme 3D, Fireworks, Flash, Fontographer, FreeHand, FreeHand Graphics Studio, Generator, Generator Developer's Studio,
Generator Dynamic Graphics Server, JRun, Knowledge Objects, Knowledge Stream, Knowledge Track, Lingo, Live Effects,
Macromedia, Macromedia M Logo & Design, Macromedia Flash, Macromedia Xres, Macromind, Macromind Action, MAGIC,
Mediamaker, Object Authoring, Power Applets, Priority Access, Roundtrip HTML, Scriptlets, SoundEdit, ShockRave,
Shockmachine, Shockwave, Shockwave Remote, Shockwave Internet Studio, Showcase, Tools to Power Your Ideas, Universal
Media, Virtuoso, Web Design 101, Whirlwind and Xtra are trademarks of Macromedia, Inc. and may be registered in the United
States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words or phrases mentioned
within this publication may be trademarks, servicemarks, or tradenames of Macromedia, Inc. or other entities and may be
registered in certain jurisdictions including internationally.
This product includes code licensed from RSA Data Security.
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not
responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your
own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia
endorses or accepts any responsibility for the content on those third-party sites.
Apple Disclaimer
APPLE COMPUTER, INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE
ENCLOSED COMPUTER SOFTWARE PACKAGE, ITS MERCHANTABILITY OR ITS FITNESS FOR ANY
PARTICULAR PURPOSE. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES.
THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY PROVIDES YOU WITH SPECIFIC LEGAL
RIGHTS. THERE MAY BE OTHER RIGHTS THAT YOU MAY HAVE WHICH VARY FROM STATE TO STATE.
Developing ColdFusion MX Applications provides the tools needed to develop Internet applications
using Macromedia ColdFusion MX. This book is intended for web application programmers who
are learning ColdFusion MX or wish to extended their ColdFusion MX programming
knowledge. It provides a solid grounding in the tools that ColdFusion MX provides to develop
web applications.
Because of the power and flexibility of ColdFusion MX, 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 CFML Reference for details about various tags and functions.
This book can to help anyone with a basic understanding of HTML learn to develop ColdFusion.
However, this book is most useful if you have basic ColdFusion experience, or have read Getting Started Building ColdFusion MX Applications. The Getting Started book provides an introduction
to ColdFusion and helps you develop the basic knowledge that will make using this book easier.
Book structure and contents
The book is divided into seven parts, as follows:
PartDescription
The CFML Programming
Language
Reusing CFML CodeTechniques for writing code once and using it many times,
Developing CFML ApplicationsHow to develop a complete ColdFusion application. Includes
Accessing and Using DataMethods for accessing and using data sources, including an
Requesting and Presenting
Information
Using Web Elements and
External Objects
Using External ResourcesMethods for getting and sending e-mail, accessing remote
The elements of ColdFusion Markup Language (CFML),
including variables, expressions, dynamic code, CFScript, and
regular expressions.
including the
CFML tags, ColdFusion components, and CFXAPI tags.
information on error handling, sharing data, locking code,
securing access, internationalization, debugging, and
troubleshooting.
introduction to SQL and information on using SQL data bases,
LDAP directory services, and the Verity search engine
How to dynamically request information from users and display
results on the user’s browser, including graphing data and
providing data to Macromedia Flash clients.
How to use XML, Java objects including Enterprise JavaBeans,
JSP pages, web services (including creating web services in
ColdFusion), and COM and CORBA objects.
servers using HTTP and FTP, and accessing files and
directories.
cfinclude tag, user-defined functions, custom
Each chapter includes basic information plus detailed coverage of the topic that should be of use
to experienced ColdFusion developers.
Approaches to using this book
This section describes approaches to using this book for beginning ColdFusion developers,
developers with some experience who want to develop expertise, and advanced developers who
want to learn about the new and enhanced features of ColdFusion MX.
24Introduction
Beginning with ColdFusion
If you are learning ColdFusion, a path such as the following might be most effective:
1 Introduction to ColdFusion MX through Using Expressions and Pound Signs to learn the basics
of CFML.
2 Introduction to Databases and SQL through Updating Your Database to learn about using
databases.
3 Retrieving and Formatting Data and Building Dynamic Forms to learn about requesting data
from users.
At this point, you should have a basic understanding of the basic elements of ColdFusion and
can create simple ColdFusion applications. To learn to produce more complete and robust
applications, you could proceed with the following chapters.
4 Designing and Optimizing a ColdFusion Application through Debugging and Troubleshooting
Applications to learn how to build a complete ColdFusion application.
5 Using Query of Queries to learn how to use queries effectively.
6 Using Arrays and Structures through Building and Using ColdFusion Components to learn to
use more advanced features of CFML, including ways to reuse code.
You can then read the remaining chapters as you add new features to your ColdFusion
application.
Developing an in-depth knowledge of ColdFusion
If you have a basic understanding of ColdFusion as presented in Getting Started Building
ColdFusion MX Applications or the Fast Track to ColdFusion course, you might want to start at
Chapter 1 and work through to the end of the book, skipping any specialized chapters that you
are unlikely to need.
Learning about new and modified ColdFusion features
If you are an advanced ColdFusion developer, you might want to learn about new or changed
ColdFusion MX features. In this case, you start with Migrating ColdFusion Applications; then read
selected chapters in this book. The following chapters document features that are new or
substantially enhanced in ColdFusion MX:
• Chapter 10, Writing and Calling User-Defined Functions
• Chapter 11, Building and Using ColdFusion Components
• Chapter 16, Securing Applications
• Chapter 17, Developing Globalized Applications
• Chapter 18, Debugging and Troubleshooting Applications
• Chapter 28, Charting and Graphing Data
• Chapter 29, Using the Flash Remoting Service
• Chapter 31, Using XML and WDDX
• Chapter 32, Using Web Services
• Chapter 33, Integrating J2EE and Java Elements in CFML Applications
Using this book25
Nearly all chapters contain information that is new in ColdFusion MX, so you should also review
all other chapters for useful information. The index and the table of contents are useful tools for
finding new features or changed documentation.
About Macromedia ColdFusion MX documentation
The ColdFusion MX documentation is designed to provide support for the complete spectrum of
participants.
Documentation set
The ColdFusion MX documentation set includes the following titles:
BookDescription
Installing and Using
ColdFusion MX
Configuring and
Administering
ColdFusion MX
use for configuring the Verity K2 Server search engine, as well as creating,
managing, and troubleshooting Verity collections.
Developing ColdFusion
MX Applications
Getting Started
Building ColdFusion
MX Applications
CFML Reference
CFML Quick Reference
Viewing online documentation
All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable
Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the
Macromedia website: www.macromedia.com.
CHAPTER 1
Introduction to ColdFusion MX
This chapter describes Macromedia ColdFusion MX and the role it plays in Internet applications,
including Macromedia Flash MX based applications. This chapter also introduces the topics
discussed in this book.
Contents
About Internet applications and web application servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
ColdFusion features described in this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
27
About Internet applications and web application servers
With ColdFusion MX, you develop Internet applications that run on web application servers.
The following sections introduce Internet applications and web application servers. Later sections
explain the specific role that ColdFusion MX plays in this environment.
About web pages and Internet applications
The Internet has evolved from a collection of static HTML pages to an application deployment
platform. First, the Internet changed from consisting of static web pages to providing dynamic,
interactive content. Rather than providing unchanging content where organizations merely
advertise goods and services, dynamic pages enable companies to conduct business ranging from
e-commerce to managing internal business processes. For example, a static HTML page lets a
bookstore publish its location, list services such as the ability to place special orders, and advertise
upcoming events like book signings. A dynamic website for the same bookstore lets customers
order books online, write reviews of books they read, and even get suggestions for purchasing
books based on their reading preferences.
More recently, the Internet has become the underlying infrastructure for a wide variety of
applications. With the arrival of technologies such as XML, web services, J2EE (Java 2 Platform,
Enterprise Edition), and Microsoft .NET, the Internet has become a multifaceted tool for
integrating business activities. Now, enterprises can use the Internet to integrate distributed
activities, such as customer service, order entry, order fulfillment, and billing.
ColdFusion MX is a rapid application development environment that lets you build dynamic
websites and Internet applications quickly and easily. It lets you develop sophisticated websites
and Internet applications without knowing the details of many complex technologies, yet it lets
advanced developers take advantage of the full capabilities of many of the latest Internet
technologies.
About web application servers
To understand ColdFusion, you must first understand the role of web application servers.
Typically, web browsers make requests, and web servers, such as Microsoft Internet Information
Server (IIS) and the Apache web server, fulfill those requests by returning the requested
information to the browser. This information includes, but is not limited to, HTML and
Macromedia Flash files.
A web server’s capabilities are limited because all it does is wait for requests to arrive and attempt
to fulfill those requests as soon as possible. A web server does not let you do the following tasks:
• Interact with a database, other resource, or other application.
• Serve customized information based on user preferences or requests.
• Validate user input.
A web server, basically, locates information and returns it to a web browser.
Chapter 1: Introduction to ColdFusion MX
To extend the capabilities of a web server, you use a web application server, a software program that
extends the web server’s capabilities to do tasks such as those in the preceding list.
How a web server and web application server work together
The following steps explain how a web server and web application server work together to process
a page request:
1 The user requests a page by typing a URL in a browser, and the web server receives the request.
2 The web server looks at the file extension to determine whether a web application server must
process the page. Then, one of the following actions occur:
■ If the user requests a file that is a simple web page (often one with an HTM or HTML
extension), the web server fulfills the request and sends the file to the browser.
■ If the user requests a file that is a page that a web application server must process (one with
a CFM, CFML, or CFC extension for ColdFusion requests), the web server passes the
request to the web application server. The web application server processes the page and
sends the results to the web server, which returns those results to the browser. The following
figure shows this process:
Because web application servers interpret programming instructions and generate output that a
web browser can interpret, they let web developers build highly interactive and data-rich websites,
which can do tasks such as the following:
• Query other database applications for data.
• Dynamically populate form elements.
• Dynamically generate Flash application data.
• Provide application security.
• Integrate with other systems using standard protocols such as HTTP, FTP, LDAP, POP, and
SMTP.
• Create shopping carts and e-commerce websites.
• Respond with an e-mail message immediately after a user submits a form.
• Return the results of keyword searches.
About Internet applications and web application servers29
About ColdFusion MX
ColdFusion MX is a rapid scripting environment server for creating Rich Internet Applications.
ColdFusion Markup Language (CFML) is an easy-to-learn tag-based scripting language, with
connectivity to enterprise data and powerful built-in search and charting capabilities. ColdFusion
MX enables developers to easily build and deploy dynamic websites, content publishing systems,
self-service applications, commerce sites, and more.
ColdFusion MX consists of the following core components:
• ColdFusion scripting environment
• CFML
• ColdFusion application services
• ColdFusion MX Administrator
The following sections describe these core components in more detail.
The ColdFusion scripting environment
The ColdFusion scripting environment provides an efficient development model for Internet
applications. At the heart of the ColdFusion scripting environment is the ColdFusion Markup
Language (CFML), a tag-based programming language that encapsulates many of the low-level
details of web programming in high-level tags and functions.
ColdFusion Markup Language
ColdFusion Markup Language (CFML) is a tag-based language, similar to HTML, that uses
special tags and functions. With CFML, you can enhance standard HTML files with database
commands, conditional operators, high-level formatting functions, and other elements to rapidly
produce easy-to-maintain web applications. However, CFML is not limited to enhancing
HTML. For example, you can create Macromedia Flash MX applications that consist entirely of
Flash elements and CFML. Similarly, you can use CFML to create web services for use by other
applications.
The following sections briefly describe basic CFML elements. For more information, see Chapter
2, “Elements of CFML,” on page 39.
CFML tags
CFML looks similar to HTML—it includes starting and, in most cases, ending tags, and each tag
is enclosed in angle brackets. All ending tags are preceded with a forward slash (/) and all tag
names are preceded with
<cftagname>
tag body text and CFML
</cftagname>
cf; for example:
CFML increases productivity by providing a layer of abstraction that hides many low-level details
involved with Internet application programming. At the same time, CFML is extremely powerful
and flexible. ColdFusion lets you easily build applications that integrate files, databases, legacy
systems, mail servers, FTP servers, objects, and components.
30Chapter 1: Introduction to ColdFusion MX
CFML includes approximately one hundred tags. ColdFusion tags serve many functions. They
provide programming constructs, such as conditional processing and loop structures. They also
provide services, such as charting and graphing, full-text search, access to protocols such as FTP,
SMTP/POP, and HTTP, and much more. The following table lists a few examples of commonly
used ColdFusion tags:
TagPurpose
cfquery
cfoutput
cfset
cfmail
cfchart
cfobject
Establishes a connection to a database (if one does not exist), executes a query, and
returns results to the ColdFusion environment.
Displays output that can contain the results of processing ColdFusion functions,
variables, and expressions.
Sets the value of a ColdFusion variable.
Lets an application send SMTP mail messages using application variables, query
results, or server files. (Another tag,
Converts application data or query results into graphs, such as bar charts or pie charts,
in Flash, JPG, or PNG format.
Invokes objects written in other programming languages, including COM (Component
Object Model) components, Java objects such as Enterprise JavaBeans, or Common
CORBA (Object Request Broker Architecture) objects.
cfpop, gets mail.)
CFML Reference describes the CFML tags in detail.
CFML functions and CFScript
CFML includes approximately 270 built-in functions. These functions perform a variety of roles,
including string manipulation, data management, and system functions. CFML also includes a
built-in scripting language, CFScript, that lets you write code in a manner that is familiar to
programmers and JavaScript writers.
CFML extensions
You can extend CFML further by creating custom tags or user-defined functions (UDFs), or by
integrating COM, C++, and Java components (such as JSP tag libraries). You can also create
ColdFusion components (CFCs), which encapsulate related functions and properties and provide
a consistent interface for accessing them.
All these features let you easily create reusable functionality that is customized to the types of
applications or websites that you are building.
CFML development tools
Macromedia Dreamweaver MX helps you develop ColdFusion applications efficiently. It includes
many features that simplify and enhance ColdFusion development, including tools for debugging
CFML. Because CFML is written in an HTML-like text format, and you often use HTML in
ColdFusion pages, you can also use an HTML editor or a text editor, such as Notepad, to write
ColdFusion applications.
About ColdFusion MX31
Server-side ActionScript
Another feature of the ColdFusion scripting environment is server-side ActionScript.
ActionScript is the JavaScript-based language used to write application logic in Macromedia Flash
MX. By bringing this language to the server, ColdFusion MX enables Flash developers to use their
familiar scripting environment to connect to ColdFusion resources and deliver the results to
client-side applications using the integrated Macromedia Flash Remoting service. Using
server-side ActionScript, Flash programmers can create ColdFusion services, such as SQL queries,
for use by Flash clients.
For more information about using server-side ActionScript in ColdFusion MX, see Chapter 30,
“Using Server-Side ActionScript,” on page 651.
ColdFusion application services
ColdFusion application services are a set of built-in services that extend the capabilities of the
ColdFusion scripting environment. These services include the following:
• Charting and graphing service Generates visual data representations, including line, bar, and
pie charts.
• Full-text search service Searches documents and databases using the Verity search engine.
• Flash Remoting service Provides a high-performance protocol for exchanging data with
Flash MX clients.
ColdFusion MX Administrator
ColdFusion MX Administrator configures and manages the ColdFusion application server. It is a
secure web-based application that you can access using any web browser, from any computer with
an Internet connection.
You can manage the following options with ColdFusion MX Administrator:
• ColdFusion data sources
• Debugging and logging output
• Server settings
• Application security
For more information about ColdFusion MX Administrator, see Configuring and Administering ColdFusion MX.
Using ColdFusion MX with Macromedia Flash MX
Macromedia Flash MX is designed to overcome the many limitations of HTML and solve the
problem of providing efficient, interactive, user interfaces for Internet applications. ColdFusion
MX is designed to provide a fast, efficient environment for developing and providing data-driven
Internet applications on your server. Using the following features, ColdFusion MX and Flash MX
can work together in a seamless manner to provide complete interactive Internet applications:
MX in an efficient, secure, and reliable way. Flash MX includes ActionScript commands that
connect to ColdFusion components (CFCs) and ColdFusion pages. Flash clients communicate
with ColdFusion applications using Action Message Format protocol over HTTP, which
provides fast, lightweight, binary data transfer between the Flash client and ColdFusion.
32Chapter 1: Introduction to ColdFusion MX
• Flash MX development application debuggerLets you trace your application logic as it
executes between Flash and ColdFusion.
• ColdFusion MX server-side ActionScriptLets Flash programmers familiar with
ActionScript create ColdFusion services, such as SQL queries, for use by Flash clients.
Together, these features let developers build integrated applications that run on the Flash client
and the ColdFusion scripting environment.
For more information about using server-side ActionScript in ColdFusion MX, see Chapter 30,
“Using Server-Side ActionScript,” on page 651. For more information about developing Flash
applications in ColdFusion, see Chapter 29, “Using the Flash Remoting Service,” on page 641.
For more information about using Flash MX, go to www.macromedia.com.
About J2EE and the ColdFusion architecture
As the Internet software market has matured, the infrastructure services required by distributed
Internet applications, including ColdFusion applications, have become increasingly standardized.
The most widely adopted standard today is the Java 2 Platform, Enterprise Edition (J2EE)
specification. J2EE provides a common set of infrastructure services for accessing databases,
protocols, and operating system functionality, across multiple operating systems.
About ColdFusion MX and the J2EE platform
ColdFusion MX is implemented on the Java technology platform and uses a J2EE application
server for many of its base services, including database connectivity, naming and directory
services, and other runtime services. ColdFusion MX can be configured to use an embedded J2EE
server or it can be deployed as a J2EE application on an independent J2EE application server.
ColdFusion MX Enterprise includes a fully featured version of the Macromedia JRun J2EE
application server, or can be deployed on third-party J2EE servers such as IBM WebSphere and
BEA WebLogic.
By implementing the ColdFusion scripting environment on top of the J2EE platform,
ColdFusion MX takes advantage of the power of the J2EE platform while also providing an
easy-to-use scripting environment and built-in services. Moreover, because ColdFusion is built on
a J2EE platform, you can easily integrate J2EE and Java functionality into your ColdFusion
application. As a result, ColdFusion pages can do any of the following:
• Share session data with JSPs (Java Server Pages) and Java servlets.
• Import custom JSP tag libraries and use them like ColdFusion custom tags.
• Integrate with Java objects, including the J2EE Java API, JavaBeans, and Enterprise JavaBeans.
For more information on using J2EE features in ColdFusion, see Chapter 33, “Integrating J2EE
and Java Elements in CFML Applications,” on page 735.
About J2EE and the ColdFusion architecture33
ColdFusion features described in this book
ColdFusion provides a comprehensive set of features for developing and managing Internet
applications. These features enhance speed and ease-of-development, and let you dynamically
deploy your applications, integrate new and legacy technologies, and build secure applications.
The following table describes the primary ColdFusion features that are discussed in this book,
and lists the chapters that describe them. This table is only a summary of major CFML features;
this book also includes information about other features. Also, this table does not include features
that are described in other books.
FeatureDescriptionChapters
CFMLCFML is a fully featured tag-oriented Internet application language.
CFScriptCFScript is a server-side scripting language that provides a subset
Regular
expressions
Reusable
elements
Custom CFML
tags
User-defined
functions
(UDFs)
ColdFusion
components
ColdFusion
extension (CFX)
tags
ColdFusion
application
structure
Error handling
mechanisms
Shared and
persistent variable
scopes
Code lockingYou lock sections of code that access in-memory shared scopes or
It includes a wide range of tags, functions, variables, and
expressions.
of ColdFusion functionality in script syntax.
ColdFusion provides several functions that use regular expressions
for string manipulation. It also lets you use regular expressions in
text input tags.
ColdFusion lets you create several types of elements, such as
user-defined functions and ColdFusion components, that you write
once and can use many times.
You can create custom ColdFusion tags using CFML. These tags
can have bodies and can call other custom tags.
You can use CFScript or the
functions. These functions can incorporate all of the built-in
ColdFusion tags and functions, plus other extensions.
ColdFusion components encapsulate multiple functions and
related data in a single logical unit. ColdFusion components can
have many uses, and are particularly useful in creating web services
and Flash interfaces for your application.
You can create custom tags in Java or C++. These tags can use
features that are only available when using programming
languages. However, CFX tags cannot have tag bodies.
ColdFusion supports many ways of building an application, and
includes specific features, such as the Application.cfm page, built-in
security features, and shared scopes, that help you optimize your
application structure.
ColdFusion provides several mechanisms for handling data,
including custom error pages and exception-handling tags and
functions, such as
Using shared and persistent scopes, you can make data available to
a single user over one or many browser sessions, or to multiple
users of an application or server.
use external resources that are not safe for multiple simultaneous
access.
cftry and cfcatch.
cffunction tag to create your own
2–5
6
7, 25
8-12
9
10
11
12
13-17
14
15
15
34Chapter 1: Introduction to ColdFusion MX
FeatureDescriptionChapters
Application
security
ColdFusion provides mechanisms, including the cflogin tag, for
authenticating users and authorizing them to access specific
16
sections of your application. You can also use resource security,
which secures access to ColdFusion resources based on the
ColdFusion page location.
Application
globalization
ColdFusion supports global applications that use different
character sets and locales, and provides tags and functions
17
designed to support globalizing your applications.
Debugging toolsUsing debugging output, the
cftrace tag, logging features, and the
18
Code Analyzer, you can locate and fix coding errors.
Database access
and management
ColdFusion can access SQL databases to retrieve, add, and modify
data. This feature is one of the core functions of many dynamic
19–21
applications.
Queries of Queries You can use a subset of standard SQL within ColdFusion to
22
manipulate any data that is represented as a record set, including
database query results, LDAP (Lightweight Directory Access
Protocol) directory information, and other data.
LDAP directory
access and
management
Indexing and
searching data
Dynamic formsWith ColdFusion, you can use HTML and forms to control the data
ColdFusion applications can access and manipulate data in LDAP
directory services. These directories are often used for security
validation data and other directory-like information.
ColdFusion applications can provide full-text search capabilities for
documents and data sources using the Verity search engine.
displayed by a dynamic web page. You can also use the
cfform tag
23
24-25
26-27
to enrich your forms with sophisticated graphical controls, and
perform input data validation.
Data graphingYou can use the
Macromedia Flash
integration
You can use native Flash connectivity built into ColdFusion MX to
help build dynamic Flash user interfaces for ColdFusion
directly access Macromedia ColdFusion MX query and HTTP
XML document
processing and
creation
features through two functions:
ColdFusion applications can create, use, and manipulate XML
(Extensible Markup Language) documents. ColdFusion also
provides tools to use WDDX (Web Distributed Data Exchange), an
CF.query and CF.http.
31
XML dialect for transmitting structured data.
Web servicesColdFusion applications can use available SOAP (Simple Object
32
Access Protocol)-based web services, including Microsoft .NET
services. ColdFusion applications can also use ColdFusion
components to provide web services to other applications over the
Internet.
Java and J2EE
integration
You can integrate J2EE elements, including JSP (JavaServer
Pages) pages, JSP tag libraries, and Java objects, including EJBs
33
(Enterprise JavaBeans), into your ColdFusion application.
ColdFusion features described in this book35
FeatureDescriptionChapters
COM and CORBA
objects
The cfobject tag lets you use COM (Component Object Model) or
DCOM (Distributed Component Object Model) and CORBA
34
(Common Object Request Broker) objects in your ColdFusion
applications.
E-mail messagesYou can add interactive e-mail features to your ColdFusion
applications using the
HTTP and FTPThe
cfhttp and cfftp tags provide simple methods of using HTTP
cfmail and cfpop tags.
35
36
(Hypertext Transfer Protocol) and FTP (File Transfer Protocol)
communications in your application.
File and directory
access
You can use the
cffile, cfdirectory, and cfcontent tags to read,
write, and manage files and directories on the server.
37
36Chapter 1: Introduction to ColdFusion MX
The CFML Programming Language
This part describes the elements of the CFML programming language. It tells
you how to use CFML tags, functions, variables and expressions, the CFScript
scripting language, and regular expressions.
This chapter provides an overview of the basic elements of CFML, including tags, functions,
constants, variables, expressions, and CFScript. The chapters in Part I of this book describe these
topics in detail.
This chapter introduces and describes the basic elements of CFML. These elements make CFML
a powerful tool for developing interactive web applications. Because CFML is a dynamic
application development tool, it has many of the features of a programming language, including
the following:
• Functions
• Expressions
• Variables and constants
• Flow-control constructs such as if-then and loops
CFML also has a “language within a language”, CFScript, which enables you to use a syntax
similar to JavaScript for many operations.
This chapter introduces these elements and other basic CFML entities such as data types,
comments, escape characters, and reserved words.
The remainder of Part I of this book provides more detailed information on many of the basic
CFML elements. The rest of this book helps you use these elements effectively in your
applications.
Character case
The ColdFusion server is case-insensitive. For example, the following all represent the cfset tag:
cfset, CFSET, CFSet, and even cfsEt. However, you should get in the habit of consistently using
the same case rules in your programs; for example:
• Develop consistent rules for case use, and stick to them. If you use lowercase characters for
some tag names, use them for all tag names.
• Always use the same case for a variable. For example, do not use both myvariable and
MyVariable to represent the same variable on a page.
If you follow these rules, you will prevent errors on application pages where you use both CFML
and case-sensitive languages, such as JavaScript.
Tags
ColdFusion tags tell the ColdFusion server that it must process information. The ColdFusion
server only processes tag contents; it returns text outside of ColdFusion to the web server
unchanged. ColdFusion MX provides a wide variety of built-in tags and lets you create custom
tags.
Tag syntax
ColdFusion tags have the same format as HTML tags. They are enclosed in angle brackets (< and
>) and can have zero or more named attributes. Many ColdFusion tags have bodies; that is, they
have beginning and end tags with text to be processed between them. For example:
<cfoutput>
Hello #YourName#! <br>
</cfoutput>
40Chapter 2: Elements of CFML
Other tags, such as cfset and cfftp, never have bodies; all the required information goes
between the beginning (<) character and the ending (>) character, as in the following example:
<cfset YourName="Bob">
Sometimes, although the tag can have a body, you do not need to put anything in it because the
attributes specify all the required information. You can omit the end tag and put a forward slash
character before the closing (>) character, as in the following example:
Note: The
tag encloses an assignment statement that assigns a value to a variable. The
function without assigning a value to a result variable.
Built-in tags
Over 80 built-in tags make up the heart of ColdFusion. These tags have many uses, including the
following:
cfset tag differs from other tags in that it has neither a body nor arguments. Instead, the
cfset tag can also call a
• Manipulating variables
• Creating interactive forms
• Accessing and manipulating databases
• Displaying data
• Controlling the flow of execution on the ColdFusion page
• Handling errors
• Processing ColdFusion pages
• Managing the CFML application framework
• Manipulating files and directories
• Using external tools and objects, including Verity collections, COM, Java, and CORBA
objects, and executable programs
• Using protocols, such as mail, http, ftp, and pop
Much of this document describes how to use these tags effectively. CFML Reference documents
each tag in detail.
Custom tags
ColdFusion lets you create custom tags. You can create two types of custom tags:
• CFML custom tags that are ColdFusion pages
• CFX tags that you write in a programing language such as Java or C++
Custom tags can encapsulate frequently used business logic or display code. These tags enable you
to place frequently used code in one place and call it from many places. Custom tags also let you
abstract complex logic into a single, simple interface. They provide an easy way to distribute your
code to others; you can even distribute encrypted versions of the tags to prevent access to the tag
logic.
Currently, over 1,000 custom tags are available on the Macromedia developer’s exchange
(www.coldfusion.com/Developer/Gallery/index.cfm). They perform tasks ranging from checking
if Cookies and JavaScript are enabled on the client's browser to moving items from one list box to
another. Many of these tags are free and include source code.
Tags41
CFML custom tags
When you write a custom tag in CFML, you can take advantage of all the features of the
ColdFusion language, including all built-in tags and even other custom tags. CFML custom tags
can include body sections and end tags. Because they are written in CFML, you do not need to
know a programming language such as Java. CFML custom tags provide more capabilities than
user-defined functions, but are less efficient.
For more information on CFML custom tags, see Chapter 9, “Creating and Using Custom
CFML Tags,” on page 173. For information about, and comparisons among, ways to reuse
ColdFusion code, including CFML custom tags, user-defined functions, and CFX tags, see
Chapter 8, “Reusing Code in ColdFusion Pages,” on page 163.
CFX Tags
CFX tags are ColdFusion custom tags that you write in a programming language such as Java or
C++. These tags can take full advantage of all the tools and resources provided by these languages,
including their access to runtime environments. CFX tags also generally execute faster than
CFML custom tags because they are compiled. CFX tags can be cross-platform, but are often
platform-specific, for example if they take advantage of COM objects or the Windows API.
For more information on CFX tags, see Chapter 12, “Building Custom CFXAPI Tags,”
on page 251.
Functions
Functions typically manipulate data and return a result. CFML includes over 250 built-in
functions. You can also use CFScript to create user-defined functions (UDFs), sometimes referred
to as custom functions.
Functions have the following general form:
functionName([argument1[, argument2]]...)
Some functions, such as the Now function take no arguments. Other functions require one or
more comma-separated arguments and can have additional optional arguments. All ColdFusion
functions return a value. For example,
Round(3.14159) returns the value 3.
Built-in functions
ColdFusion built-in functions perform a variety of tasks, including, but not limited to, the
following:
• Creating and manipulating complex data variables, such as arrays, lists, and structures
• Creating and manipulating queries
• Creating, analyzing, manipulating, and formatting strings and date and time values
• Evaluating the values of dynamic data
• Determining the type of a variable value
• Converting data between formats
• Performing mathematical operations
• Getting system information and resources
For alphabetical and categorized lists of ColdFusion functions, see Chapter 3, “ColdFusion
Functions,” in CFML Reference.
42Chapter 2: Elements of CFML
You use built-in functions throughout ColdFusion pages. Built-in functions are frequently used
in a
cfset or cfoutput tag to prepare data for display or further use. For example, the following
line displays today’s date in the format October 12, 2001:
Note that this code uses two nested functions. The Now function returns a ColdFusion date-time
value representing the current date and time. The
by the
Now function and converts it to the desired string representation.
DateFormat function takes the value returned
Functions are also valuable in CFScript scripts. ColdFusion does not support ColdFusion tags in
CFScript, so you must use functions to access ColdFusion functionality in scripts.
User-defined functions
You can write your own functions, user-defined functions (UDFs). You can use these functions in
ColdFusion expressions or in CFScript. You can call a user-defined function anywhere you can
use a built-in CFML function. You create UDFs using the
function statement. UDFs that you create using the cffunction tag can include ColdFusion
cffunction tag or the CFScript
tags and functions. UDFs that you create in CFScript can only include functions.
User-defined functions let you encapsulate logic and operations that you use frequently in a single
unit. This way, you can write the code once and use it multiple times. UDFs ensure consistency of
coding and enable you to structure your CFML more efficiently.
Typical user-defined functions include mathematical routines, such as a function to calculate the
logarithm of a number; string manipulation routines, such as a function to convert a numeric
monetary value to a string such as “two dollars and three cents”; and can even include encryption
and decryption routines.
Note: The Common Function Library Project at http://www.cflib.org includes a number of free
libraries of user-defined functions.
For more information on user-defined functions, see Chapter 10, “Writing and Calling User-
Defined Functions,” on page 191.
Expressions
ColdFusion expressions consist of operands and operators. Operands are comprised of constants and
variables, such as “Hello” or MyVariable. Operators, such as the string concatenation operator
(&) or the division operator (/) are the verbs that act on the operands. ColdFusion functions also
act as operators.
The simplest expression consists of a single operand with no operators. Complex expressions
consist of multiple operands and operators. For example, the following statements are all
ColdFusion expressions:
The following sections briefly describe constants and variables. For detailed information on using
variables, see Chapter 3, “Using ColdFusion Variables,” on page 53. For detailed information on
expressions and operators, see Chapter 4, “Using Expressions and Pound Signs,” on page 83.
Expressions43
Constants
The value of a constant does not change during program execution. Constants are simple scalar
values that you can use within expressions and functions, such as “Robert Trent Jones” and
123.45. Constants can be integers, real numbers, time and date values, Boolean values, or text
strings. ColdFusion does not allow you to give names to constants.
Variables
Var ia bl es are the most frequently used operands in ColdFusion expressions. Variable values can be
set and reset, and can be passed as attributes to CFML tags. Variables can be passed as parameters
to functions, and can replace most constants.
ColdFusion has a number of built-in variables that provide information about the server and are
returned by ColdFusion tags. For a list of the ColdFusion built-in variables, see Chapter 1,
“Reserved Words and Variables,” in CFML Reference.
The following two characteristics classify a variable:
• The scope of the variable, which indicates where the information is available and how long the
variable persists
• The data type of the variable’s value, which indicates the kind of information a variable
represents, such as number, string, or date
The following section lists and briefly describes the variable scopes. “Data types” on page 45 lists
data types (which also apply to constant values). For detailed information on ColdFusion
variables, including data types, scopes, and their use, see Chapter 3, “Using ColdFusion
Variables,” on page 53.
Variable scopes
The following table describes ColdFusion variable scopes:
Scope Description
Variables
(local)
FormThe variables passed from a form page to its action page as the result of submitting
URLThe parameters passed to the current page in the URL that is used to call it.
AttributesThe values passed by a calling page to a custom tag in the custom tag’s attributes.
CallerA reference, available in a custom tag, to the Variables scope of the page that calls
ThisTagVariables that are specific to a custom tag, including built-in variables that provide
RequestVariables that are available to all pages, including custom tags and nested custom
44Chapter 2: Elements of CFML
The default scope for variables of any type that are created with the
cfparam tags. A local variable is available only on the page on which it is created and
any included pages.
the form.
Used only in custom tag pages.
the tag. Used only in custom tag pages.
information about the tag. Used only in custom tag pages. A nested custom tag can
use the
cfassociate tag to return values to the calling tag’s ThisTag scope.
tags, that are processed in response to an HTTP request. Used to hold data that
must be available for the duration of one HTTP request.
cfset and
Scope Description
CGIEnvironment variables identifying the context in which a page was requested. The
CookieVariables maintained in a user’s browser as cookies.
ClientVariables that are associated with one client. Client variables let you maintain state
SessionVariables that are associated with one client and persist only as long as the client
ApplicationVariables that are associated with one, named, application on a server. The
ServerVariables that are associated with the current ColdFusion server. This scope lets
FlashVariables sent by a Macromedia Flash movie to ColdFusion and returned by
ArgumentsVariables passed in a call to a user-defined function or ColdFusion component
ThisVariables that are declared inside a ColdFusion component or in a
function localVariables that are declared in a user-defined function and exist only while the
variables available depend on the browser and server software.
as a user moves from page to page in an application and are available across
browser sessions.
maintains a session.
cfapplication tag name attribute specifies the application name.
you define variables that are available to all your ColdFusion pages, across multiple
applications.
ColdFusion to the movie.
method.
cffunction tag
that is not part of a ColdFusion component.
function executes.
Data types
ColdFusion is considered typeless because you do not explicitly specify variable data types.
However, ColdFusion data, the constants and the data that variables represent, do have data types,
which correspond to the ways the data is stored on the computer.
ColdFusion data belongs to the following type categories:
CategoryDescription and types
SimpleRepresents one value. You can use simple data types directly in ColdFusion
ComplexA container for data. Complex variables generally represent more than one value.
expressions. ColdFusion simple data types are:
• strings, such as "This is a test."
• integers, such as 356
• real numbers, such as -3.14159
• Boolean values, True or False
• date-time values, such as 3:00 PM July 12, 2001
ColdFusion built-in complex data types are:
• arrays
• structures
• queries
Data types45
CategoryDescription and types
BinaryRaw data, such as the contents of a GIF file or an executable program file
ObjectCOM, CORBA, Java, web services, and ColdFusion Component objects:
Complex objects that you create and access using the
specialized tags.
cfobject tag and other
For more information on ColdFusion data types, see Chapter 3, “Using ColdFusion Variables,”
on page 53.
ColdFusion components
ColdFusion components encapsulate multiple, related, functions. A ColdFusion component is
essentially a set of related user-defined functions and variables, with additional functionality to
provide and control access to the component contents. ColdFusion components can make their
data private, so that it is available to all functions (also called methods) in the component, but not
to any application that uses the component.
ColdFusion components have the following features:
• They are designed to provide related services in a single unit.
• They can provide web services and make them available over the internet.
• They can providing ColdFusion services that Flash clients can call directly.
• They have several features that are familiar to object-oriented programmers including data
hiding, inheritance, packages, and introspection.
For more information on ColdFusion components, see Chapter 11, “Building and Using
ColdFusion Components,” on page 219
CFScript
CFScript is a language within a language. CFScript is a scripting language that is similar to
JavaScript but is simpler to use. Also, unlike JavaScript CFScript only runs on the ColdFusion
server; it does not run on the client system. A CFScript script can use all ColdFusion functions
and all ColdFusion variables that are available in the script’s scope.
CFScript provides a compact and efficient way to write ColdFusion logic. Typical uses of
CFScript include:
• Simplifying and speeding variable setting
• Building compact flow control structures
• Encapsulating business logic in user-defined functions
The following sample script populates an array and locates the first array entry that starts with the
word “key”. It shows several of the elements of CFScript, including setting variables, loop
structures, script code blocks, and function calls. Also, the code uses a
results. While you can use CFScript for output, the
<cfscript>
strings = ArrayNew(1);
strings[1]="the";
strings[2]="key to our";
strings[4]="idea";
for( i=1 ; i LE 4 ; i = i+1 )
{
46Chapter 2: Elements of CFML
cfoutput tag is usually easier to use.
cfoutput tag to display its
if(Find("key",strings[i],1))
break; }
</cfscript>
<cfoutput>Entry #i# starts with "key"</cfoutput><br>
You use CFScript to create user-defined functions.
For more information on CFScript, see Chapter 6, “Extending ColdFusion Pages with CFML
Scripting,” on page 127. For more information on user-defined functions, see Chapter 10,
“Writing and Calling User-Defined Functions,” on page 191.
Flow control
ColdFusion provides several tags that let you control how a page gets executed. These tags
generally correspond to programming language flow control statements, such as if, then, and else.
The following tags provide ColdFusion flow control.
TagsPurpose
cfif, cfelseif, cfelseSelect sections of code based on whether expressions are True or False.
cfswitch, cfcase,
cfdefaultcase
cfloop, cfbreakLoop through code based on any of the following values: entries in a list,
cfabort, cfexitEnd processing of a ColdFusion page or custom tag.
This section provides a basic introduction to using flow-control tags. CFScript also provides a set
of flow-control statements. For information on using flow-control statements in CFScript, see
Chapter 6, “Extending ColdFusion Pages with CFML Scripting,” on page 127. For more details
on using flow-control tags, see the reference pages for these tags in CFML Reference.
Select among sections of code based on the value of an expression. Case
processing is not limited to True and False conditions.
keys in a structure or external object, entries in a query column, an index, or
the value of a conditional expression.
cfif, cfelseif, and cfelse
The
cfif, cfelseif, and cfelse tags provide if-then-else conditional processing, as follows:
1 The cfif tag tests a condition and executes its body if the condition is True.
2 If the preceding cfif (or cfelseif) test condition is False, the cfelseif tag tests another
condition and executes its body if that condition is True.
3 The cfelse tag can optionally follow a cfif tag and zero or more cfelseif tags. Its body
executes if all the preceding tags’ test conditions are False.
The following example shows the use of the
cfif, cfelseif, and cfelse tags. If the value of the
type variable is “Date,” the date displays; if the value is “Time,” the time displays; otherwise, both
the time and date display.
cfswitch, cfcase, and cfdefaultcase tags let you select among different code blocks
based on the value of an expression. ColdFusion processes these tags as follows:
1 The cfswitch tag evaluates an expression. The cfswitch tag body contains one or more
cfcase tags and optionally includes cfdefaultcase tag.
2 Each cfcase tag in the cfswitch tag body specifies a value or set of values. If a value matches
the value determined by the expression in the cfswitch tag, ColdFusion runs the code in the
body of the
cfcase tag and then exits the cfswitch tag. If two cfcase tags have the same
condition, ColdFusion generates an error.
3 If none of the cfcase tags match the value determined by the cfswitch tag, and the cfswitch
tag body includes a
cfdefaultcase tag, ColdFusion runs the code in the cfdefaultcase tag
body.
Note: Although the cfdefaultcase tag does not have to follow all cfcase tags, it is good programming
practice to put it at the end of the
cfswitch statement.
The cfswitch tag provides better performance than a cfif tag with multiple cfelseif tags, and
is easier to read. Switch processing is commonly used when different actions are required based on
a a string variable such as a month or request identifier.
#FirstName# #LastName# is in <b>Accounting</b><br><br>
</cfcase>
<cfcase value = "Administration">
#FirstName# #LastName# is in <b>Administration</b><br><br>
</cfcase>
<cfdefaultcase>#FirstName# #LastName# is not in Sales,
Accounting, or Administration.<br>
</cfdefaultcase>
</cfswitch>
</cfoutput>
cfloop and cfbreak
The
cfloop tag loops through the tag body zero or more times based on a condition specified by
the tag attributes. The cfbreak tag exits a cfloop tag.
cfloop
The
cfloop tag provides five types of loops:
Loop typeDescription
IndexLoops through the body of the tag and increments a counter variable by a
Conditional Checks a condition and runs the body of the tag if the condition is True.
QueryLoops through the body of the tag once for each row in a query.
48Chapter 2: Elements of CFML
specified amount after each loop until the counter reaches a specified value.
Loop typeDescription
ListLoops through the body of the tag once for each entry in a list.
CollectionLoops through the body of the tag once for each key in a ColdFusion structure or
item in a COM/DCOM object.
The following example shows a simple index loop:
<cfloop index = "LoopCount" from = 1 to = 5>
The loop index is <cfoutput>#LoopCount#</cfoutput>.<br>
</cfloop>
The following example shows a simple conditional loop. The code does the following:
1 Sets up a ten-element array with the word “kumquats” in the fourth entry.
2 Loops through the array until it encounters an array element containing “kumquats” or it
reaches the end of the array.
3 Prints out the value of the Boolean variable that indicates whether it found the word kumquats
and the array index at which it exited the loop.
<cfset myArray = ArrayNew(1)>
<!--- Use ArraySet to initialize the first ten elements to 123 --->
<cfset ArraySet(myArray, 1, 10, 123)>
<cfset myArray[4] = "kumquats">
<cfset foundit = False>
<cfset i = 0>
<cfloop condition = "(NOT foundit) AND (i LT ArrayLen(myArray))">
<cfset i = i + 1>
<cfif myArray[i] IS "kumquats">
<cfset foundit = True>
</cfif>
</cfloop>
<cfoutput>
i is #i#<br>
foundit is #foundit#<br>
</cfoutput>
Note: You can get an infinite conditional loop if you do not force an end condition. In this example, the
loop is infinite if you omit the <cfset i = i + 1> statement. To end an infinite loop, stop the
ColdFusion application server.
cfbreak
The
cfbreak tag exits the cfloop tag. You typically use it in a cfif tag to exit the loop if a
particular condition occurs. The following example shows the use of a
cfbreak tag in a query
loop:
<cfloop query="fruitOrder">
<cfif fruit IS "kumquat">
<cfoutput>You cannot order kumquats!<br></cfoutput>
<cfbreak>
</cfif>
<cfoutput>You have ordered #quantity# #fruit#.<br></cfoutput>
</cfloop>
Flow control49
cfabort and cfexit
The
cfabort tag stops processing of the current page at the location of the cfabort tag.
ColdFusion returns to the user or calling tag everything that was processed before the
tag. You can optionally specify an error message to display. You can use the
body of a
The
cfif tag to stop processing a page when a condition, typically an error, occurs.
cfexit tag controls the processing of a custom tag, and can only be used in ColdFusion
cfabort tag as the
custom tags. For more information see, Chapter 9, “Terminating tag execution,” on page 185 and CFML Reference.
Comments
ColdFusion comments have a similar format to HTML comments. However, they use three dash
characters instead of two; for example:
<!--- This is a ColdFusion Comment. Browsers do not receive it. --->
The ColdFusion server removes all ColdFusion comments from the page before returning it to
the web server. As a result, the page that a user browser receives does not include the comment,
and users cannot see it even if they view the page source.
You can embed CFML comments in begin tags (not just tag bodies), functions calls, and variable
text in pound signs. ColdFusion ignores the text in comments such as the following:
This technique can be useful if you want to temporarily comment out parts of expressions or
optional attributes or arguments.
Note: You cannot embed comments inside a tag name or function name, such as <cf_My<!--- New -
-->CustomTag>
IsDefined("My<!--- New --->Variable").
. You also cannot embed comments inside strings, as in the following example:
cfabort
Special characters
The double quotation marks ("), single quotation mark ('), and pound sign (#) characters have
special meaning to ColdFusion. To include any of them in a string, double the character; for
example, use ## to represent a single # character.
The need to escape the single- and double-quotation marks is context-sensitive. Inside a doublequoted string, you do not need to escape single-quote (apostrophe) characters. Inside a singlequoted string, you do not escape double-quote characters.
The following example illustrates escaping special characters, including the use of mixed single
and double quotes.
<cfset mystring = "We all said ""For He's a jolly good fellow.""">
<cfset mystring2 = 'Then we said "For She''s a jolly good fellow".'>
<cfoutput>
#mystring#<br>
#mystring2#<br>
Here is a pound sign: ##
</cfoutput>
50Chapter 2: Elements of CFML
The output looks like this:
We all said "For He's a jolly good fellow."
Then we said "For She's a jolly good fellow."
Here is a pound sign: #
Reserved words
As with any programming tool, you cannot use just any word or name for ColdFusion variables,
UDFs and custom tags. You must avoid using any name that can be confused with a ColdFusion
element. In some cases, if you use a word that ColdFusion uses—for example, a built-in structure
name—you can overwrite the ColdFusion data.
The following list indicates words you must not use for ColdFusion variables, user-defined
function names, or custom tag names. While some of these words can be used safely in some
situations, you can prevent errors by avoiding them entirely. For a complete list of reserved words,
see CFML Reference.
• Built-in function names, such as Now or Hash
• Scope names, such as Form or Session
• Any name starting with cf. However, when you call a CFML custom tag directly, you prefix the
custom tag page name with cf_.
• Operators, such as NE or IS
• The names of any built-in data structures, such as Error or File
• The names of any built-in variables, such as RecordCount or CGI variable names
• CFScript language element names such as for, default, or continue
You must also not create form field names ending in any of the following, except to specify a form
field validation rule using a hidden form field name. (For more information on form field
validation, see Chapter 26, “Validating form field data types,” on page 579.)
• _integer
• _float
• _range
• _date
• _time
• _eurodate
Remember that ColdFusion is not case-sensitive. For example, all of the following are reserved
words: IS, Is, iS, and is.
Reserved words51
52Chapter 2: Elements of CFML
CHAPTER 3
Using ColdFusion Variables
Macromedia ColdFusion variables are the most frequently used operands in ColdFusion
expressions. Variable values can be set and reset, and can be passed as attributes to CFML tags.
Variables can be passed as parameters to functions, and can replace most constants.
This chapter describes how to create and use ColdFusion variables. It includes the following
information:
• How variables can represent different types of data
You create most ColdFusion variables by assigning them values. (You must use the ArrayNew
function to create arrays.) Most commonly, you create variables by using the
also use the
also create variables. For example, the
ColdFusion automatically creates some variables that provide information about the results of
certain tags or operations. ColdFusion also automatically generates variables in certain scopes,
such as Client and Server. For information on these special variables, see Chapter 1, “Reserved
Words and Variables,” in CFML Reference and the documentation of the CFML tags that create
these variables.
ColdFusion generates an error when it tries to use a variable before it is created. This can happen,
for example, when processing data from an incompletely filled form. To prevent such errors, test
for the variable’s existence before you use it. For more information on testing for variable
existence, see “Ensuring variable existence” on page 78.
For more information on how to create variables, see “Creating and using variables in scopes”
on page 75.
Variable naming rules
ColdFusion variable names, including form field names and custom function and ColdFusion
component argument names, must conform to Java naming rules and the following guidelines:
cfparam tag, and assignment statements in CFScript. Tags that create data objects
cfquery tag creates a query object variable.
cfset tag. You can
• A variable name must begin with a letter, underscore, or Unicode currency symbol.
• The initial character can by followed by any number of letters, numbers, underscore characters,
and Unicode currency symbols.
• A variable name cannot contain spaces.
• A query result is a type of variable, so it cannot have the same name as another local variable in
the current ColdFusion application page.
• ColdFusion variables are not case-sensitive. However, consistent capitalization makes the code
easier to read.
• When creating a form with fields that are used in a query, match form field names with the
corresponding database field names.
• Periods separate the components of structure or object names. They also separate a variable
scope from the variable name. You cannot use periods in simple variable names, with the
exception of variables in the Cookie and Client scopes. For more information on using periods,
see “Using periods in variable references” on page 64.
The following rule applies to variable names, but does not apply to form field and argument
names:
• Prefix each variable’s name with its scope. Although some ColdFusion programmers do not use
the Variables prefix for local variable names, you should use prefixes for all other scopes. Using
scope prefixes makes variable names clearer and increases code efficiency. In many cases, you
must prefix the scope. For more information, see “About scopes” on page 72.
Note: In some cases, when you use an existing variable name, you must enclose it with pound signs
(#) to allow ColdFusion to distinguish it from string or HTML text, and to insert its value, as opposed
to its name. For more information, see Chapter 4, “Using pound signs,” on page 89.
54Chapter 3: Using ColdFusion Variables
Variable characteristics
You can classify a variable using the following characteristics:
• The data type of the variable value, which indicates the kind of information a variable
represents, such as number, string, or date
• The scope of the variable, which indicates where the information is available and how long the
variable persists
The following sections provide detailed information on Data types and scopes.
Data types
ColdFusion is often referred to as typeless because you do not assign types to variables and
ColdFusion does not associate a type with the variable name. However, the data that a variable
represents does have a type, and the data type affects how ColdFusion evaluates an expression or
function argument. ColdFusion can automatically convert many data types into others when it
evaluates expressions. For simple data, such as numbers and strings, the data type is unimportant
until the variable is used in an expression or as a function argument.
ColdFusion variable data belongs to one of the following type categories:
• SimpleOne value. Can use directly in ColdFusion expressions. Include numbers, strings,
Boolean values, and date-time values.
• ComplexA container for data. Generally represent more than one value. ColdFusion built-
in complex data types include arrays, structures, queries, and XML document objects.
You cannot use a complex variable, such as an array, directly in a ColdFusion expression, but
you can use simple data type elements of a complex variable in an expression.
For example, with a one-dimensional array of numbers called myArray, you cannot use the
expression myArray * 5. However, you could use an expression myArray[3] * 5 to multiply the
third element in the array by five.
• BinaryRaw data, such as the contents of a GIF file or an executable program file.
• ObjectsComplex constructs. Often encapsulate both data and functional operations. The
following table lists the types of objects that ColdFusion can use, and identifies the chapters
that describe how to use them:
Object typeSee
Component Object Model (COM) Chapter 34, “Integrating COM and CORBA Objects in CFML
Common Object Request Broker
Architecture (CORBA)
JavaChapter 33, “Integrating J2EE and Java Elements in CFML
ColdFusion componentChapter 11, “Building and Using ColdFusion Components,”
Web serviceChapter 32, “Using Web Services,” on page 707
Applications,” on page 761
Chapter 34, “Integrating COM and CORBA Objects in CFML
Applications,” on page 761
Applications,” on page 735
on page 219
Data types55
Data type notes
Although ColdFusion variables do not have types, it is often convenient to use “variable type” as a
shorthand for the type of data that the variable represents.
ColdFusion can validate the type of data contained in form fields and query parameters. For more
information, see Chapter 26, “Validating form field data types,” on page 579 and Chapter 20,
“Using cfqueryparam,” on page 435.
The
cfdump tag displays the entire contents of a variable, including ColdFusion complex data
structures. It is an excellent tool for debugging complex data and the code that handles it.
ColdFusion provides the following functions for identifying the data type of a variable:
• IsArray
• IsBinary
• IsBoolean
• IsObject
• IsQuery
• IsSimpleValue
• IsStruct
• IsXmlDoc
ColdFusion also includes the following functions for determining whether a string can be
represented as another simple data type:
• IsDate
• IsNumeric
ColdFusion does not use a null data type. However, if ColdFusion receives a null value from an
external source such as a database, a Java object, or some other mechanism, it maintains the null
value until you use it as a simple value. At that time, ColdFusion converts the null to an empty
string ("").
Numbers
ColdFusion supports integers and real numbers. You can intermix integers and real numbers in
expressions; for example, 1.2 + 3 evaluates to 4.2.
Integers
ColdFusion supports integers between -2,147,483,648 and 2,147,483,647 (32-bit signed
integers). You can assign a value outside this range to a variable, but ColdFusion initially stores
the number as a string. If you use it in an arithmetic expression, ColdFusion converts it into a
floating point value, preserving its value, but losing precision as the following example shows:
<cfset mybignum=12345678901234567890>
<cfset mybignumtimes10=(mybignum * 10)>
<cfoutput>mybignum is: #mybignum#</cfoutput><br>
<cfoutput>mybignumtimes10 is: #mybignumtimes10# </cfoutput><br>
This example generates the following output:
mybignum is: 12345678901234567890
mybignumtimes10 is: 1.23456789012E+020
56Chapter 3: Using ColdFusion Variables
Real numbers
Real numbers, numbers with a decimal part, are also known as floating point numbers.
ColdFusion real numbers can range from approximately -10
300
to approximately 10
number can have up to 12 significant digits. As with integers, you can assign a variable a value
with more digits, but the data is stored as a string. The string is converted to a real number, and
can lose precision, when you use it in an arithmetic expression.
You can represent real numbers in scientific notation. This format is xEy, where x is a positive or
negative real number in the range 1.0 (inclusive) to 10 (exclusive), and y is an integer. The value
of a number in scientific notation is x times 10
equals 400. Similarly, 2.5E-2 is 2.5 times 10
y
. For example, 4.0E2 is 4.0 times 102, which
-2
, which equals 0.025. Scientific notation is useful
for writing very large and very small numbers.
Strings
In ColdFusion, text values are stored in strings. You specify strings by enclosing them in either
single- or double-quotation marks. For example, the following two strings are equivalent:
"This is a string"
'This is a string'
You can write an empty string in the following ways:
• "" (a pair of double-quotation marks with nothing in between)
• '' (a pair of single-quotation marks with nothing in between)
Strings can be any length, limited by the amount of available memory on the ColdFusion server.
There is, however, a 64K limit on the size of text data that can be read from and written to a
ColdFusion database or HTML text area. The ColdFusion MX Administrator lets you increase
the limit for database string transfers, but doing so can reduce server performance. To change the
limit, select the Enable retrieval of long text option on the Advanced Settings page for the data
source.
300
. A real
Escaping quotation marks and pound signs
To include a single-quotation character in a string that is single-quoted, use two single-quotation
marks (known as escaping the single-quotation mark). The following example uses escaped singlequotation marks:
<cfset myString='This is a single-quotation mark: '' This is a double-quotation
mark: "'>
<cfoutput>#mystring#</cfoutput><br>
To include a double-quotation mark in a double-quoted string, use two double-quotation marks
(known as escaping the double-quotation mark). The following example uses escaped doublequotation marks:
<cfset myString="This is a single-quotation mark: ' This is a double-quotation
mark: """>
<cfoutput>#mystring#</cfoutput><br>
Because strings can be in either double-quotation marks or single-quotation marks, both of the
preceding examples display the same text:
This is a single-quotation mark: ' This is a double-quotation mark: "
Strings57
To insert a pound sign in a string, you must escape the pound sign, as follows:
"This is a pound sign ##"
Lists
ColdFusion includes functions that operate on lists, but it does not have a list data type. In
ColdFusion, a list is just a string that consists of multiple entries separated by delimiter characters.
The default delimiter for lists is the comma. If you use any other character to separate list
elements, you must specify the delimiter in the list function. You can also specify multiple
delimiter characters. For example, you can tell ColdFusion to interpret a comma or a semicolon as
a delimiter, as the following example shows:
<cfset MyList="1,2;3,4;5">
<cfoutput>
List length using ; and , as delimiters: #listlen(Mylist, ";,")#<br>
List length using only , as a delimiter: #listlen(Mylist)#<br>
</cfoutput>
This example displays the following output:
List length using ; and , as delimiters: 5
List length using only , as a delimiter: 3
Each delimiter must be a single character. For example, you cannot tell ColdFusion to require two
hyphens in a row as a delimiter.
If a list has two delimiters in a row, ColdFusion ignores the empty element. For example, if
MyList is "1,2,,3,,4,,,5" and the delimiter is the comma, the list has five elements and list
functions treat it the same as "1,2,3,4,5".
Boolean values
A Boolean value represents whether something is true or false. ColdFusion has two special
constants—True and False—to represent these values. For example, the Boolean expression 1 IS 1
evaluates to True. The expression
"Monkey" CONTAINS "Money" evaluates to False.
You can use Boolean constants directly in expressions, as in the following example:
<cfset UserHasBeenHere = True>
In Boolean expressions, True, nonzero numbers, and the string “Yes” are equivalent, and False, 0,
and the string “No” are equivalent.
Boolean evaluation is not case-sensitive. For example, True, TRUE, and true are equivalent.
Date-Time values
ColdFusion can perform operations on date and time values. Date-time values identify a date and
time in the range 100 AD to 9999 AD. Although you can specify just a date or a time,
ColdFusion uses one data type representation, called a date-time object, for date, time, and date
and time values.
ColdFusion provides many functions to create and manipulate date-time values and to return all
or part of the value in several different formats.
You can enter date and time values directly in a
<cfset myDate = "October 30, 2001">
58Chapter 3: Using ColdFusion Variables
cfset tag with a constant, as follows:
When you do this, ColdFusion stores the information as a string. If you use a date-time function,
ColdFusion stores the value as a date-time object, which is a separate simple data type. When
possible, use date-time functions such as
CreateDate and CreateTime to specify dates and times,
because these functions can prevent you from specifying the date or time in an invalid format and
they create a date-time object immediately.
Date and time formats
You can directly enter a date, time, or date and time, using standard U.S. date formats.
ColdFusion processes the two-digit-year values 0 to 29 as twenty-first century dates; it processes
the two-digit-year values 30 to 99 as twentieth century dates. Time values can include units down
to seconds. The following table lists valid date and time formats:
To specifyUse these formats
DateOctober 30, 2003
Time02:34:12
Date and TimeAny combination of valid date and time formats, such as these:
Oct 30, 2003
Oct. 30, 2003
10/30/03
2003-10-30
10-30-2003
2:34a
2:34am
02:34am
2am
October 30, 2003 02:34:12
Oct 30, 2003 2:34a
Oct. 30, 2001 2:34am
10/30/03 02:34am
2003-10-30 2am
10-30-2003 2am
Locale-specific dates and times
ColdFusion provides several functions that let you input and output dates and times (and
numbers and currency values) in formats that are specific to the current locale. A locale identifies a
language and locality, such as English (US) or French (Swiss). Use these functions to input or
output dates and times in formats other than the U.S. standard formats. (Use the
SetLocale
function to specify the locale.) The following example shows how to do this:
For more information on international functions, see Chapter 17, “Developing Globalized
Applications,” on page 371 and CFML Reference.
Strings59
How ColdFusion stores dates and times
ColdFusion stores and manipulates dates and times as date-time objects. Date-time objects store
data on a time line as real numbers. This storage method increases processing efficiency and
directly mimics the method used by many popular database systems. In date-time objects, one
day is equal to the difference between two successive integers. The time portion of the date-andtime value is stored in the fractional part of the real number. The value 0 represents 12:00 AM
12/30/1899.
Although you can use arithmetic operations to manipulate date-and-time values directly, this
method can result in code that is difficult to understand and maintain. Use the ColdFusion datetime manipulation functions instead. For information on these functions, see the CFML Reference.
Binary data type and Base64 encoding
Binary data is raw data, such as the contents of a GIF file or an executable program file. You do
not normally use binary data directly, but you can use the
cffile tag to read a binary file into a
variable, typically for conversion to Base64 encoding before transmitting the file using e-mail.
Base64 format encodes the data in the lowest six bits of each byte. It ensures that binary data and
non-ANSI character data can be transmitted using e-mail without corruption. The MIME
specification defines the Base64 encoding method.
ColdFusion does not have a Base64 data type; it processes Base64 encoded data as string data.
ColdFusion provides the following functions that convert among string data, binary data, and
Base64 encoded string data:
FunctionDescription
ToBase64Converts string and binary data to Base64 encoded data.
ToBinaryConverts Base64 encoded data to binary data.
ToStringConverts most simple data types to string data. It can convert numbers, date-time
objects, and boolean values. (It converts date-time objects to ODBC timestamp
strings.) It cannot convert binary data that includes bytes that are not printable
characters.
The
ToString function cannot convert Base64 encoded data directly to an unencoded string. Use
the following procedure to convert Base64 encoded data that was originally a string back to a
readable string:
1 Use the ToBinary function to convert the Base64 data into binary format.
2 Use the ToString function to convert the binary data to string data.
For example, the following two lines print the same results:
Do not use binary data or Base64 data directly in ColdFusion expressions.
60Chapter 3: Using ColdFusion Variables
Complex data types
Arrays, structures, and queries are ColdFusion built-in complex data types. Structures and queries
are sometimes referred to as objects, because they are containers for data, not individual data
values.
For details on using arrays and structures, see Chapter 5, “Using Arrays and Structures,”
on page 103.
Arrays
Arrays are a way of storing multiple values in a table-like format that can have one or more
dimensions. To create an array and specify its initial dimensions, use the ColdFusion
function. For example, the following line creates an empty two-dimensional array:
<cfset myarray=ArrayNew(2)>
You reference elements using numeric indexes, with one index for each dimension. For example,
the following line sets one element of a two-dimensional array to the current date and time:
<cfset myarray[1][2]=Now()>
The ArrayNew function can create arrays with up to three dimensions. However, there is no limit
on array size or maximum dimension. To create arrays with more than three dimensions, create
arrays of arrays.
After you create an array, you can use functions or direct references to manipulate its contents.
When you assign an existing array to a new variable, ColdFusion creates a new array and copies
the old array’s contents to the new array. The following example creates a copy of the original
array:
<cfset newArray=myArray>
For more information on using arrays, see Chapter 5, “Using Arrays and Structures,”
on page 103.
ArrayNew
Structures
ColdFusion structures consist of key-value pairs, where the keys are text strings and the values can
be any ColdFusion data type, including other structures. Structures let you build a collection of
related variables that are grouped under a single name. To create a structure, use the ColdFusion
StructNew function. For example, the following line creates a new, empty, structure called depts:
<cfset depts=StructNew()>
You can also create a structure by assigning a value in the structure. For example, the following
line creates a new structure called MyStruct with a key, MyValue, equal to 2:
<cfset MyStruct.MyValue=2>
Note: In previous ColdFusion versions, this line created a Variables scope variable named
"MyStruct.MyValue" with the value 2.
After you create a structure, you can use functions or direct references to manipulate its contents,
including adding key/value pairs.
Strings61
You can use either of the following methods to reference elements stored in a structure:
• StructureName.KeyName
• StructureName["KeyName"]
The following examples show these methods:
depts.John="Sales"
depts["John"]="Sales"
When you assign an existing structure to a new variable, ColdFusion does not create a new
structure. Instead, the new variable accesses the same data (location) in memory as the original
structure variable. In other words, both variables are references to the same object.
For example, the following line creates a new variable, myStructure2, that is a reference to the
same structure as the myStructure variable:
<cfset myStructure2=myStructure>
When you change the contents of myStructure2, you also change the contents of myStructure. To
copy the contents of a structure, use the ColdFusion
contents of structures and other complex data types.
Structure key names can be the names of complex data objects, including structures or arrays.
This lets you create arbitrarily complex structures.
For more information on using structures, see Chapter 5, “Using Arrays and Structures,”
on page 103.
Queries
A query object, sometimes referred to as a query, query result, or record set, is a complex
ColdFusion data type that represents data in a set of named columns, similar to the columns of a
database table. The following ColdFusion tags can create query objects:
Duplicate function, which copies the
• cfquery
• cfdirectory
• cfhttp
• cfldap
• cfpop
• cfprocresult
In these tags, the
function also creates query objects.
When you assign a query to a new variable, ColdFusion does not copy the query object. Instead,
both names point to the same record set data. For example, the following line creates a new
variable, myQuery2, that references the same record set as the myQuery variable:
<cfset myQuery2 = myQuery>
If you make changes to data in myQuery, myQuery2 also shows those changes.
You reference query columns by specifying the query name, a period, and the column name; for
example:
myQuery.Dept_ID
name attribute specifies the query object’s variable name. The QueryNew
62Chapter 3: Using ColdFusion Variables
When you reference query columns inside tags, such as cfoutput and cfloop, in which you
specify the query name in a tag attribute, you do not have to specify the query name.
You can access query columns as if they are one-dimensional arrays. For example, the following
line assigns the contents of the Employee column in the second row of the myQuery query to the
variable myVar:
<cfset myVar = myQuery.Employee[2]>
Note: You cannot use array notation to refer to a row (of all columns) of a query. For example,
myQuery[2] does not refer to the second row of the myQuery query object.
Working with structures and queries
Because structure variables and query variables are references to objects, the rules in the following
sections apply to both types of data.
Multiple references to an object
When multiple variables refer to a structure or query object, the object continues to exist as long
as at least one reference to the object exists. The following example shows how this works:
<cfset depts=0> tag executes, the depts variable does not refer to a structure; it is a
simple variable with the value 0. However, the variable newStructure still refers to the original
structure object.
Assigning objects to scopes
You can give a query or structure a different scope by assigning it to a new variable in the other
scope. For example, the following line creates a server variable, Server.SScopeQuery, using the
local myquery variable:
<cfset Server.SScopeQuery = myquery>
To clear the server scope query variable, reassign the query object, as follows:
<cfset Server.SScopeQuery = 0>
This deletes the reference to the object from the server scope, but does not remove any other
references that might exist.
Copying and duplicating objects
You can use the Duplicate function to make a true copy of a structure or query object. Changes
to the copy do not affect the original.
Strings63
Using a query column
When you are not inside a cfloop, cfoutput, or cfmail tag that has a query attribute, you can
treat a query column as an array. However, query column references do not always behave as you
might expect. This section explains the behavior of references to query columns using the results
of the following
<cfquery dataSource="CompanyInfo" name="myQuery">
SELECT FirstName, LastName
FROM Employee
</cfquery>
cfquery tag in its examples:
To reference elements in a query column, use the row number as an array index. For example,
both of the following lines display the word "ben":
ColdFusion behavior is less straightforward, however, when you use the query column references
myQuery.Firstname and myQuery["Firstname"] without using an array index. The two reference
formats produce different results.
If you refer to myQuery.Firstname, ColdFusion automatically converts it to the first row in the
column. For example, the following lines print the word "ben":
If you refer to Query["Firstname"], ColdFusion does not automatically convert it to the first
row of the column. For example, the following line results in an error message indicating that
ColdFusion cannot convert a complex type to a simple value:
<cfoutput> #myQuery['Firstname']# </cfoutput><br>
Similarly, the following lines print the name "marjorie", the value of the second row in the
column:
However, when you make an assignment that requires a simple value, ColdFusion automatically
converts the query column to the value of the first row. For example, the following lines display
the name "ben" twice:
ColdFusion uses the period (.) to separate elements of a complex variable such as a structure,
query, XML document object, or external object, as in MyStruct.KeyName. A period also
separates a variable scope identifier from the variable name, as in Variables.myVariable or
CGI.HTTP_COOKIE.
64Chapter 3: Using ColdFusion Variables
With the exception of Cookie and Client scope variables, which must always be simple variable
types, you cannot normally include periods in simple variable names. However, ColdFusion
makes some exceptions that accommodate legacy and third-party code that does not conform to
this requirement.
For more information, see “About scopes” on page 72, Chapter 5, “Using Arrays and Structures,”
on page 103, and Chapter 31, “Using XML and WDDX,” on page 669.
Understanding variables and periods
The following descriptions use a sample variable named MyVar.a.b to explain how ColdFusion
uses periods when getting and setting the variable value.
Getting a variable
ColdFusion can correctly get variable values even if a simple variable name includes a period. For
example, the following set of steps shows how ColdFusion gets MyVar.a.b, as in
myVar.a.b>
1 Looks for myVar in an internal table of names (the symbol table).
2 If myVar is the name of a complex object, including a scope, looks for an element named a in
or IsDefined(myVar.a.b):
<cfset Var2 =
the object.
If myVar is not the name of a complex object, checks whether myVar.a is the name of a
complex object and skips step 3.
3 If myVar is the name of a complex object, checks whether a is a complex object.
4 If a or myVar.a is the name of a complex object, checks whether b is the name of a simple
variable, and returns the value of b.
If myVar is a complex object but a is not a complex object, checks whether a.b is the name of a
simple variable and returns its value.
If myVar.a is not a complex object, checks whether myVar.a.b is the name of a simple variable
and returns its value.
This way, even if myVar.a.b is a simple variable name, ColdFusion correctly resolves the variable
name and can get its value.
You can also use array notation to get a simple variable with a name that includes periods. In this
form of array notation, you use the scope name (or the complex variable that contains the simple
variable) as the “array” name. You put the simple variable name, in single- or double-quotation
marks, inside the square brackets.
Using array notation is more efficient than using plain dot notation because ColdFusion does not
have to analyze and look up all the possible key combinations. For example, both of the following
lines write the value of myVar.a.b, but the second line is more efficient than the first:
<cfoutput>myVar.a.b is: #myVar.a.b#<br></cfoutput>
<cfoutput>myVar.a.b is: #Variables["myVar.a.b"]#<br></cfoutput>
Setting a variable
ColdFusion cannot be as flexible when it sets a variable value as when it gets a variable, because it
must determine the type of variable to create or set. Therefore, the rules for variable names that
you set are stricter. Also, the rules vary depending on whether the first part of the variable name is
the Cookie or Client scope identifier.
Using periods in variable references65
For example, assume you have the following code:
<cfset myVar.a.b = "This is a test">
If a variable myVar does not exist, it does the following:
1 Creates a structure named myVar.
2 Creates a structure named a in the structure myVar.
3 Creates a key named b in myVar.a.
4 Gives it the value "This is a test".
If either myVar or myVar.a exist and neither one is a structure, ColdFusion generates an error.
In other words, ColdFusion uses the same rules as for getting a variable to resolve the variable
name until it finds a name that does not exist yet. It then creates any structures that are needed to
create a key named b inside a structure, and assigns the value to the key.
However, if the name before the first period is either Cookie or Client, ColdFusion uses a
different rule. It treats all the text (including any periods) that follow the scope name as the name
of a simple variable, because Cookie and Client scope variables must be simple. If you have the
following code, you see that ColdFusion creates a single, simple Client scope variable named
myVar.a.b:
<cfset Client.myVar.a.b = "This is a test">
<cfdump var=#Client.myVar.a.b#>
Creating variables with periods
You should avoid creating the names of simple variables (including arrays) that include periods.
However, ColdFusion provides mechanisms for handling cases where you must do so, for
example, to maintain compatibility with names of variables in external data sources or to integrate
your application with existing code that uses periods in variable names. The following sections
describe how to create simple variable names that include periods.
Using brackets to create variables with periods
You can create a variable name that includes periods by using associative array structure notation,
as described in Chapter 5, “Structure notation,” on page 114. To do so, you must do the
following:
• Refer to the variable as part of a structure. You can always do this, because ColdFusion
considers all scopes to be structures. For more information on scopes, see “Ab out sc opes”
on page 72.
• Put the variable name that must include a period inside square brackets and single- or double-
My.Variable.With.Periods is: #My.Variable.With.Periods#<br>
Request.Another.Variable.With.Periods is:
#Request.Another.Variable.With.Periods#<br>
</cfoutput>
66Chapter 3: Using ColdFusion Variables
Creating Client and Cookie variables with periods
To create a Client or Cookie variable with a name that includes one or more periods, simply
assign the variable a value. For example, the following line creates a Cookie named
User.Preferences.CreditCard:
ColdFusion automatically converts between data types to satisfy the requirements of an
expression’s operations, including a function’s argument requirements. As a result, you generally
don’t need to be concerned about compatibility between data types and the conversions from one
data type to another. However, understanding how ColdFusion evaluates data values and converts
data between types can help you prevent errors and create code more effectively.
Operation-driven evaluation
Conventional programming languages enforce strict rules about mixing objects of different types
in expressions. For example, in a language such as C++ or Basic, the expression
produces an error because the multiplication operator requires two numerical operands and "8" is
a string. When you program in such languages, you must convert between data types to ensure
error-free program execution. For example, the previous expression might have to be written as
(ToNumber("8") * 10).
In ColdFusion, however, the expression
("8" * 10) evaluates to the number 80 without
generating an error. When ColdFusion processes the multiplication operator, it automatically
attempts to convert its operands to numbers. Since "8" can be successfully converted to the
number 8, the expression evaluates to 80.
ColdFusion processes expressions and functions in the following sequence:
1 For each operator in an expression, it determines the required operands. (For example, the
multiplication operator requires numeric operands and the CONTAINS operator requires
string operands.)
For functions, it determines the type required for each function argument. (For example, the
Min function requires two numbers as arguments and the Len function requires a string.)
2 It evaluates all operands or function arguments.
3 It converts all operands or arguments whose types differ from the required type. If a conversion
fails, it reports an error.
("8" * 10)
Conversion between types
Although the expression evaluation mechanism in ColdFusion is very powerful, it cannot
automatically convert all data. For example, the expression
"eight" * 10 produces an error
because ColdFusion cannot convert the string "eight" to the number 8. Therefore, you must
understand the rules for conversion between data types.
Data type conversion67
The following table explains how conversions are performed. The first column shows values to
convert. The remaining columns show the result of conversion to the listed data type.
ValueAs BooleanAs numberAs date-timeAs string
"Yes"True1Error"Yes"
"No"False0Error"No"
TrueTrue1Error"Yes"
FalseFalse0Error"No"
Number True if Number
is not 0; False
otherwise.
StringIf "Yes", True
If "No", False
If it can be
converted to 0,
False
If it can be
converted to
any other
number, True
DateErrorThe numeric value
NumberSee “Date-time values”
If it represents a
number (for
example, "1,000"
or "12.36E-12"), it
is converted to the
corresponding
number. If it
represents a datetime (see next
column), it is
converted to the
numeric value of
the corresponding
date-time object.
of the date-time
object.
earlier in this chapter.
If it is an ODBC date, time,
or timestamp (for example
"{ts '2001-06-14
11:30:13'}", or if it is
expressed in a standard
U.S. date or time format,
including the use of full or
abbreviated month names,
it is converted to the
corresponding date-time
value.
Days of the week or
unusual punctuation result
in an error.
Dashes, forward-slashes,
and spaces are generally
allowed.
DateAn ODBC timestamp.
String representation
of the number (for
example, “8”).
String
ColdFusion cannot convert complex types, such as arrays, queries, and COM objects, to other
types. However, it can convert simple data elements of complex types to other simple data types.
Type conversion considerations
The following sections detail specific rules and considerations for converting between types.
The cfoutput tag
The cfoutput tag always displays data as a string. As a result, when you display a variable using
the
cfoutput tag, ColdFusion applies the type conversion rules to any non-string data before
displaying it. For example, the
cfoutput tag displays a date-time value as an ODBC timestamp.
Case-insensitivity and Boolean conversion
Because ColdFusion expression evaluation is not case-sensitive, Yes, YES, and yes are equivalent;
False, FALSE, and false are equivalent; No, NO, and no are equivalent; and True, TRUE, and
true are equivalent.
68Chapter 3: Using ColdFusion Variables
Converting binary data
ColdFusion cannot automatically convert binary data to other data types. To convert binary data,
use the
ToBase64 and ToString functions. For more information, see “Binary data type and
Base64 encoding” on page 60.
Converting date and time data
To ensure that a date and time value is expressed as a real number, add zero to the variable. The
following example shows this:
<cfset mynow = now()>
Use cfoutput to display the result of the now function:<br>
<cfoutput>#mynow#</cfoutput><br>
Now add 0 to the result and display it again:<br>
<cfset mynow = mynow + 0>
<cfoutput>#mynow#</cfoutput>
At 1:06 PM on June 6, 2003, its output looked like this:
Use cfoutput to display the result of the now function:
{ts '2003-06-03 13:06:44'}
Now add 0 to the result and display it again:
37775.5463426
Converting numeric values
When ColdFusion evaluates an expression that includes both integers and real numbers, the result
is a real number. To convert a real number to an integer, use a ColdFusion function. The
Round, Fix, and Ceiling functions convert real numbers to integers, and differ in their treatment
Int,
of the fractional part of the number.
If you use a hidden form field with a name that has the suffix
_integer or _range to validate a
form input field, ColdFusion truncates real numbers entered into the field and passes the
resulting integer to the action page.
If you use a hidden form field with a name that has the suffix
_integer, _float, or _range to
validate a form input field, and the entered data contains a dollar amount (including a dollar sign)
or a numeric value with commas, ColdFusion considers the input to be valid, removes the dollar
sign or commas from the value, and passes the resulting integer or real number to the action page.
Evaluation and type conversion issues
The following sections explain several issues that you might encounter with type evaluation and
conversion.
Comparing variables to True or False
You might expect the following two cfif tag examples to produce the same results:
<cfif myVariable>
<cfoutput>myVariable equals #myVariable# and is True
</cfoutput>
</cfif>
<cfif myVariable IS True>
<cfoutput>myVariable equals #myVariable# and is True
</cfoutput>
</cfif>
Data type conversion69
However, if myVariable has a numeric value such as 12, only the first example produces a result.
In the second case, the value of myVariable is not converted to a Boolean data type, because the IS
operator does not require a specific data type and just tests the two values for identity. Therefore,
ColdFusion compares the value 12 with the constant True. The two are not equal, so nothing is
printed. If myVariable is 1, "Yes", or True, however, both examples print the same result, because
ColdFusion considers these to be identical to Boolean True.
If you use the following code, the output statement does display, because the value of the variable,
12, is not equal to the Boolean value False:
<cfif myVariable IS NOT False>
<cfoutput>myVariable equals #myVariable# and IS NOT False
</cfoutput>
</cfif>
As a result, you should use the test <cfif testvariable>, and not use the IS comparison
operator when testing whether a variable is True or False. This issue is a case of the more general
problem of ambiguous type expression evaluation, described in the following section.
Ambiguous type expressions and strings
When ColdFusion evaluates an expression that does not require strings, including all comparison
operations, such as
IS or GT, it checks whether it can convert each string value to a number or
date-time object. If so, ColdFusion converts it to the corresponding number or date-time value
(which is stored as a number). It then uses the number in the expression.
Short strings, such as 1a and 2P, can produce unexpected results. ColdFusion can interpret a
single "a" as AM and a single "P" as PM. This can cause ColdFusion to interpret strings as datetime values in cases where this was not intended.
Similarly, if the strings can be interpreted as numbers, you might get unexpected results.
For example, ColdFusion interprets the following expressions as shown:
ExpressionInterpretation
<cfif "1a" EQ "01:00">
<cfif "1P" GT "2A">
<cfset age="4a">
<cfset age=age + 7>
<cfif "0.0" is "0">
If 1:00am is 1:00am.
If 1:00pm is later than 2:00am.
Treat the variable age as 4:00 am, convert it to the date-time
value 0.16666666667, and add 7 to make it 7.16666666667.
If 0 is 0.
To prevent such ambiguities when you compare strings, use the ColdFusion string comparison
functions
Compare and CompareNoCase, instead of the comparison operators.
You can also use the IsDate function to determine whether a string can be interpreted as a datetime value, or to add characters to a string before comparison to avoid incorrect interpretation.
Date-time functions and queries when ODBC is not supported
Many CFML functions, including the Now, CreateDate, CreateTime, and CreateDateTime
functions, return date-time objects. ColdFusion creates Open Database Connectivity (ODBC)
timestamp values when it converts date-time objects to strings. As a result, you might get
unexpected results when using dates with a database driver that does not support ODBC escape
sequences, or when you use SQL in a query of queries.
70Chapter 3: Using ColdFusion Variables
If you use SQL to insert data into a database or in a WHERE clause to select data from a
database, and the database driver does not support ODBC-formatted dates, use the
DateFormat
function to convert the date-time value to a valid format for the driver. This rule also applies to
queries of queries.
For example, the following SQL statement uses the
DateFormat function in a query of queries to
select rows that have MyDate values in the future:
<cfquery name="MyQofQQ" dbtype="query">
SELECT *
FROM DateQuery
WHERE MyDate >= '#DateFormat(Now())#'
</cfquery>
The following query of queries fails with the error message “Error: {ts is not a valid date,” because
the ColdFusion
<cfquery name="MyQofQQ" dbtype="query">
SELECT *
FROM DateQuery
WHERE MyDate >= '#now()#'
</cfquery>
Using JavaCast with overloaded Java methods
Now function returns an ODBC timestamp:
You can overload Java methods so a class can have several identically named methods that differ
only in parameter data types. At runtime, the Java virtual machine attempts to resolve the specific
method to use, based on the types of the parameters passed in the call. Because ColdFusion does
not use explicit types, you cannot predict which version of the method the virtual machine will
use.
The ColdFusion
JavaCast function helps you ensure that the right method executes by
specifying the Java type of a variable, as in the following example:
The JavaCast function takes two parameters: a string representing the Java data type and the
variable whose type you are setting. You can specify the following Java data types: bool, int, long,
float, double, and String.
For more information on the
JavaCast function, see CFML Reference.
Using quotation marks
To ensure that ColdFusion properly interprets string data, surround strings in single- or doublequotation marks. For example, ColdFusion evaluates “10/2/2001” as a string that can be
converted into a date-time object. However, it evaluates 10/2/2001 as a mathematical expression,
5/2001, which evaluates to 0.00249875062469.
Examples of type conversion in expression evaluation
The following examples demonstrate ColdFusion expression evaluation.
Example 1
2 * True + "YES" - ('y' & "es")
Result value as string: "2"
Explanation: (2*True) is equal to 2; ("YES"- "yes") is equal to 0; 2 + 0 equals 2.
Data type conversion71
Example 2
True AND 2 * 3
Result value as string: "YES"
Explanation: 6 is converted to Boolean True because it is nonzero; True AND True is True.
Example 3
"Five is " & 5
Result value as string: "Five is 5"
Explanation: 5 is converted to the string "5".
Example 4
DateFormat("October 30, 2001" + 1)
Result value as string: "31-Oct-01"
Explanation: The addition operator forces the string "October 30, 2001" to be converted to a
date-time object and then to a number. The number is incremented by one. The DateFormat
function requires its argument to be a date-time object; thus, the result of the addition is
converted to a date-time object. One is added to the date-time object, moving it ahead by one day
to October 31, 2001.
About scopes
Variables differ in the source of the data, the places in your code where they are meaningful, and
how long their values persist. These considerations are generally referred to as a variable’s scope.
Commonly used scopes include the Variables scope, the default scope for variables that you
create, and the Request scope, which is available for the duration of an HTTP request.
Note: User-defined functions also belong to scopes. For more information, see Chapter 10,
“Specifying the scope of a function,” on page 206.
Scope types
The following table describes ColdFusion scopes:
Scope Description
Variables
(local)
FormContains variables passed from a Form page to its action page as the result of
72Chapter 3: Using ColdFusion Variables
The default scope for variables of any type that are created with the cfset and
cfparam tags. A local variable is available only on the page on which it is created
and any included pages (see also the Caller scope).
submitting the form. (If you use the HTML
For more information, see Chapter 26, “Retrieving and Formatting Data,”
on page 559.
form tag, you must use method="post".)
Scope Description
URLContains parameters passed to the current page in the URL that is used to call it.
The parameters are appended to the URL in the format ?variablename =
value[&variablename=value...]; for example www.MyCompany.com/
inputpage.cfm?productCode=A12CD1510&
quantity=3.
Note: If a URL includes multiple parameters with the same name, the resulting
variable in the ColdFusion URL scope consists of all parameter values separated by
commas. For example, a URL of the form http://localhost/urlparamtest.cfm?
param=1¶m=2¶m=3 results in a URL.param variable value of 1,2,3 on the
ColdFusion page.
AttributesUsed only in custom tag pages. Contains the values passed by the calling page in
the custom tag’s attributes. For more information, see Chapter 9, “Creating and
Using Custom CFML Tags,” on page 173.
CallerUsed only in custom tag pages. The custom tag’s Caller scope is a reference to the
calling page’s Variables scope. Any variables that you create or change in the
custom tag page using the Caller scope are visible in the calling page’s Variables
scope. For more information, see Chapter 9, “Creating and Using Custom CFML
Tags,” on page 173.
ThisTagUsed only in custom tag pages. The ThisTag scope is active for the current
invocation of the tag. If a custom tag contains a nested tag, any ThisTag scope
values you set before calling the nested tag are preserved when the nested tag
returns to the calling tag.
The ThisTag scope includes three built-in variables that identify the tag’s execution
mode, contain the tag’s generated contents, and indicate whether the tag has an
end tag.
A nested custom tag can use the
cfassociate tag to return values to the calling tag’s
ThisTag scope. For more information, see “Accessing tag instance data”
on page 182.
RequestUsed to hold data that must be available for the duration of one HTTP request. The
Request scope is available to all pages, including custom tags and nested custom
tags, that are processed in response to the request.
This scope is useful for nested (child/parent) tags. This scope can often be used in
place of the Application scope, to avoid the need for locking variables. Several
chapters discuss using the Request scope.
CGIContains environment variables identifying the context in which a page was
requested. The variables available depend on the browser and server software. For
a list of the commonly used CGI variables, see Chapter 1, “Reserved Words and Variables,” in CFML Reference.
CookieContains variables maintained in a user’s browser as cookies. Cookies are typically
stored in a file on the browser, so they are available across browser sessions and
applications. You can create memory-only Cookie variables, which are not available
after the user closes the browser. Cookie scope variable names can include periods.
ClientContains variables that are associated with one client. Client variables let you
maintain state as a user moves from page to page in an application, and are available
across browser sessions. By default, Client variables are stored in the system
registry, but you can store them in a cookie or a database. Client variables cannot be
complex data types and can include periods in their names. For more information,
see Chapter 15, “Using Persistent Data and Locking,” on page 315.
About scopes73
Scope Description
SessionContains variables that are associated with one client and persist only as long as the
client maintains a session. They are stored in the server’s memory and can be set to
time out after a period of inactivity. You cannot use application variables on server
clusters where more than one computer can process requests from a single session.
For more information, see Chapter 15, “Using Persistent Data and Locking,”
on page 315.
ApplicationContains variables that are associated with one, named application on a server. The
cfapplication tag name attribute specifies the application name. For more
information, see Chapter 15, “Using Persistent Data and Locking,” on page 315.
ServerContains variables that are associated with the current ColdFusion server. This
scope lets you define variables that are available to all your ColdFusion pages,
across multiple applications. For more information, see Chapter 15, “Using
Persistent Data and Locking,” on page 315.
FlashVariables sent by a Macromedia Flash movie to ColdFusion and returned by
ColdFusion to the movie. For more information, see Chapter 29, “Using the Flash
Remoting Service,” on page 641.
ArgumentsVariables passed in a call to a user-defined function or ColdFusion component
method. For more information, see “About the Arguments scope” on page 194.
ThisExists only in ColdFusion components or
cffunction tags that are part of a
containing object such as a ColdFusion Struct. Exists for the duration of the
component instance or containing object. Data in the This scope is accessible from
outside the component or container by using the instance or object name as a prefix.
For more information, see Chapter 11, “Building and Using ColdFusion
Components,” on page 219 and “Using the This scope outside CFCs (advanced
topic)” on page 78.
function localContains variables that are declared inside a user-defined function or ColdFusion
component method and exist only while a function executes. For more information,
see Chapter 10, “Writing and Calling User-Defined Functions,” on page 191.
Caution: To prevent data corruption, you lock code that uses Session, Application, or Server scope
variables. For more information, see Chapter 15, “Using Persistent Data and Locking,” on page 315.
74Chapter 3: Using ColdFusion Variables
Creating and using variables in scopes
The following table shows how you create and refer to variables in different scopes in your code.
For more information on the mechanisms for creating variables in most scopes, see “Creating
variables” on page 54.
Scope
prefix
(type)
Variables
(Local)
FormNoOn the action page of a form
URLNoOn the target page of the
AttributesYesOn the custom tag page.The calling page passing the values
CallerOn the custom
ThisTagYesOn the custom tag page.Specifying the prefix ThisTag when
RequestYesOn the creating page and in
CGINoOn any page. Values are
Prefix
required to
referenceWhere availableCreated by
NoOn the current page. Cannot
tag page, Yes.
On the calling
page, No
(Variables prefix
is optional).
be accessed by a form’s
action page (unless the form
page is also the action page).
Variables in this scope used
on a page that calls a custom
tag can be accessed in the
custom tag by using its Caller
scope; however, they are not
available to any nested
custom tags.
and in custom tags called by
the action page; cannot be
used on a form page that is
not also the action page.
URL.
On the custom tag page, by
using the Caller scope prefix.
On the page that calls the
custom tag, as local variables
(Variables scope).
any pages invoked during the
current HTTP request after
the variable is created,
including in custom tags and
nested custom tags.
specific to the latest browser
request.
Specifying the prefix Variables, or
using no prefix, when you create the
variable.
A
form or cfform tag. Contains the
values of form field tags (such as
input) in the form body when the
form is submitted. The variable
name is the name of the form field.
The system. Contains the
parameters passed in the URL
query string used to access the
page.
to a custom tag page in the custom
tag’s attributes.
On the custom tag page, by
specifying the prefix Caller when
you create the variable.
On the calling page, by specifying
the prefix Variables, or using no
prefix, when you create the variable.
you create the variable in the tag or
using the cfassociate tag in a
nested custom tag.
Specifying the prefix Request when
you create the variable.
The web server. Contains the server
environment variables that result
from the browser request.
About scopes75
Scope
prefix
(type)
Prefix
required to
referenceWhere availableCreated by
CffileYesFollowing an invocation of
cffile.
CookieNoFor one client in one or more
applications and pages, over
multiple browser sessions.
ClientNoFor one client in one
application, over multiple
browser sessions.
SessionYesFor one client in one
application and one browser
session. Surround all code
that uses application variables
in cflock blocks.
Application YesFor multiple clients in one
application over multiple
browser sessions. Surround
all code that uses application
variables in
cflock blocks.
ServerYesTo any page on the
ColdFusion server. Surround
all code that uses server
variables in
cflock blocks.
FlashYesA ColdFusion page or
ColdFusion component called
by a Flash client.
Arguments NoWithin the body of a user-
defined function or
ColdFusion component
method.
ThisYesWithin a ColdFusion
component or the body of a
user-defined function that was
created using the
cffunction tag and put in an
object, structure, or scope. In
the containing page, through
the component instance or
containing object.
(function
local, no
prefix)
ProhibitedWithin the body of a user-
defined function or
ColdFusion component
method, only while the
function executes.
A cffile tag.
A cfcookie tag. You can also set
memory-only cookies by specifying
the prefix Cookie when you create
the variable.
Specifying the prefix Client when
you create the variable.
Specifying the prefix Session when
you create the variable.
Specifying the prefix Application
when you create the variable.
Specifying the prefix Server when
you create the variable.
The ColdFusion Client access. You
assign a value to Flash.You can
assign values to the Flash.result and
Flash.pagesize variables.
The calling page passing an
argument in the function call.
Within the component or function
by specifying the prefix This when
you create the variable.
In the containing page, by
specifying the component instance
or object that contains the function
as a prefix when you create the
variable.
In the function or method definition,
a
var keyword in a cfset tag or a
CFScript
var statement.
76Chapter 3: Using ColdFusion Variables
Using scopes
The following sections provide details on how you can create and use variables in different scopes.
Evaluating unscoped variables
If you use a variable name without a scope prefix, ColdFusion checks the scopes in the following
order to find the variable:
Because ColdFusion must search for variables when you do not specify the scope, you can
improve performance by specifying the scope for all variables.
To access variables in all other scopes, you must prefix the variable name with the scope identifier.
Scopes and CFX tags
ColdFusion scopes do not apply to ColdFusion Extension (CFX) tags, custom tags that you write
in a programming language such as C++ or Java. The ColdFusion page that calls a CFX tag must
use tag attributes to pass data to the CFX tag. The CFX tag must use the Java Request and
Response interfaces or the C++ Request class to get and return data.
The Java
setVariable Response interface method and C++ CCFX::SetVariable method return
data to the Variables scope of the calling page. Therefore, they are equivalent to setting a Caller
scope variable in a custom ColdFusion tag.
Using scopes as structures
ColdFusion makes all named scopes available as structures. You cannot access the function-local
scope for user defined functions (UDFs) that you define using CFScript as a structure. (In
ColdFusion 4.5 and 5, the following scopes are not available as structures: Variables, Caller,
Client, and Server.)
You can reference the variables in named scopes as elements of a structure. To do so, specify the
scope name as the structure name and the variable name as the key. For example, if you have a
MyVar variable in the Request scope, you can refer to it in either of the following ways:
Request.MyVar
Request["MyVar"]
Similarly, you can use CFML structure functions to manipulate the contents of the scope. For
more information on using structures, see Chapter 5, “Using Arrays and Structures,”
on page 103.
About scopes77
Caution: Do not call StructClear(Session) to clear session variables. This deletes the SessionID,
CFID, and CFtoken built-in variables, effectively ending the session. If you want to use StructClear to
delete your application variables, put those variables in a structure in the Session scope, then clear
that structure. For example, put all your application variables in Session.MyVars and then call
StructClear(Session.MyVars) to clear the variables.
Using the This scope outside CFCs (advanced topic)
The This scope is specifically designed for use with ColdFusion Components (CFCs). For
information on CFCs and the This scope, see Chapter 11, “Building and Using ColdFusion
Components,” on page 219. However, you can also use the This scope without having a CFC if
you do the following:
• Create a UDF using the cffunction tag.
• Assign the UDF to a containing object such as a structure or persistent scope.
In this case, the This scope inside the function is a reference to the containing object, and you
can therefore access the same variables.
• Specify This as the prefix, inside the function.
• Specify the containing object name as the prefix, outside the function.
First, just call the function<br>
<cfset TestFunction()>
Right now, the This variable is NOT a scope reference, just a structure.
<br><br>
Now put function in a structure and dump the structure<br>
Note that there is no foo variable in the structure.
<cfset newStruct.TestFunction=TestFunction>
<cfdump var="#newStruct#">
<br>
Now change newStruct.foo and call the function <br>
<cfset newStruct.foo="New This.foo">
<cfset newStruct.TestFunction()>
Note that now we've changed the foo variable from outside the function,<br>
And the function itself is part of the This scope!
Ensuring variable existence
ColdFusion generates an error if you try to use a variable value that does not exist. Therefore,
before you use any variable whose value is assigned dynamically, you must ensure that a variable
value exists. For example, if your application has a form, it must use some combination of
requiring users to submit data in fields, providing default values for fields, and checking for the
existence of field variable values before they are used.
There are several ways to ensure that a variable exists before you use it, including:
• You can use the IsDefined function to test for the variable’s existence.
• You ca n use the cfparam tag to test for a variable and set it to a default value if it does not exist.
78Chapter 3: Using ColdFusion Variables
• You can use a cfforminput tag with a hidden attribute to tell ColdFusion to display a helpful
message to any user who does not enter data in a required field. For more information on this
technique, see Chapter 26, “Requiring users to enter values in form fields,” on page 566.
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 by
using the
For example, if you submit a form with an unsettled check box, the action page does not get a
variable for the check box. The following example from a form action page makes sure the
Contractor check box Form variable exists before using it:
<cfif IsDefined("Form.Contractor")>
You must always enclose the argument passed to the IsDefined function in double-quotation
marks. For more information on the
If you attempt to evaluate a variable that you did not define, ColdFusion cannot process the page
and displays an error message. To help diagnose such problems, turn on debugging in the
ColdFusion MX Administrator or use the debugger in your editor. The Administrator debugging
information shows which variables are being passed to your application pages.
Variable existence considerations
If a variable is part of a scope that is available as a structure, you might get a minor performance
increase by testing the variable’s existence using the
IsDefined function.
You can also determine which Form variables exist by inspecting the contents of the
Form.fieldnames built-in variable. This variable contains a list of all the fields submitted by the
form. Remember, however, that form text fields are always submitted to the action page, and
might contain an empty string if the user did not enter data.
The
bracket notation. For example,
element
to a simple variable and use the
IsDefined function always returns False if you specify an array or structure element using
IsDefined("myArray[3]") always returns False, even if the array
myArray[3] has a value. To check for the existence of an array element, copy the element
IsDefined function to test whether the simple variable exists.
Using the cfparam tag
You can ensure that a variable exists by using the
existence and optionally supplies a default value if the variable does not exist. The
cfparam tag, which tests for the variable’s
cfparam tag
has the following syntax:
<cfparam name="VariableName"
type="data_type"
default="DefaultValue">
Note: For information on using the type attribute to validate the parameter data type, see CFML
Reference.
There are two ways to use the cfparam tag to test for variable existence, depending on how you
want the validation test to proceed:
Ensuring variable existence79
• With only the name attribute to test that a required variable exists. If it does not exist, the
ColdFusion server stops processing the page and displays an error message.
• With 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
The following example shows how to use the
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 the
cfparam tag with the name attribute is one 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 debug.
For example, the following
cfparam tags indicate that this page expects two form variables named
StartRow and RowsToFetch:
<cfparam name="Form.StartRow">
<cfparam name="Form.RowsToFetch">
If the page with these tags is called without either one of the form variables, an error occurs and
the page stops processing. By default, ColdFusion displays an error message; you can also handle
the error as described in Chapter 14, “Handling Errors,” on page 285.
Example: setting default values
The following example uses the
cfparam tag to see if optional variables exist. If they do exist,
processing continues. If they do not exist, the ColdFusion server creates them and sets them to
the default values.
You can use the cfparam tag to set default values for URL and Form variables, instead of using
conditional logic. For example, you could include the following code on the action page to ensure
that a SelectedDepts variable exists:
It is often not sufficient that input data merely exists; it must also have the right format. For
example, a date field must have data in a date format. A salary field must have data in a numeric
or currency format. There are many ways to ensure the validity of data, including the following
methods:
• Use the cfparam tag with the type attribute to validate any variable.
• Use a form input tag with a hidden attribute to validate the contents of a form input field. For
information on this technique, see Chapter 26, “Validating form field data types,”
on page 579.
• Use cfform controls that have validation attributes. For more information, see Chapter 27,
“Building Dynamic Forms,” on page 583.
80Chapter 3: Using ColdFusion Variables
• Use the cfqueryparam tag in a SQL WHERE clause to validate query parameters. For
information on this technique, see Chapter 20, “Using cfqueryparam,” on page 435.
Note: Data validation using the cfparam, cfqueryparam, and form tags is done by the server.
Validation using cfform tags is done using JavaScript in the user’s browser, before any data is sent
to the server.
Using the cfparam tag to validate the data type
The
cfparam type attribute lets you validate the type of a parameter. You can specify that the
parameter type must be any of the following values:
Type valueMeaning
anyAny value
arrayAny array value
binaryAny binary value
booleanTrue, False, Yes, or No
dateAny value in a valid date, time, or date-time format
numericAny number
queryA query object
stringA text string or single character
structA structure
UUIDA Universally Unique Identifier (UUID) formatted as XXXXXXXX-XXXX-XXXX-
variableNameA valid variable name
XXXXXXXXXXXXXXX where X stands for a hexadecimal digit (0-9 or A-F).
For example, you can use the following code to validate the variable BirthDate:
<cfparam name="BirthDate" type="date">
If the variable is not in a valid date format, an error occurs and the page stops processing.
Validating data types81
Passing variables to custom tags and UDFs
The following sections describe rules for how data gets passed to custom tags and user-defined
functions that are written in CFML, and to CFX custom tags that are written in Java or C++.
Passing variables to CFML tags and UDFs
When you pass a variable to a CFML custom tag as an attribute, or to a user-defined function as
an argument, the following rules determine whether the custom tag or function receives its own
private copy of the variable or only gets a reference to the calling page’s variable:
• Simple variables and arrays are passed as copies of the data. If your argument is an expression
that contains multiple simple variables, the result of the expression evaluation is copied to the
function or tag.
• Structures, queries, and cfobject objects are passed as references to the object.
If the tag or function gets a copy of the calling page’s data, changes to the variable in the custom
tag or function do not change the value of the variable on the calling page. If the variable is passed
by reference, changes to the variable in the custom tag or function also change the value of the
variable in the calling page.
To pass a variable to a custom tag, you must enclose the variable name in pound signs. To pass a
variable to a function, do not enclose the variable name in pound signs. For example, the
following code calls a user-defined function using three Form variables:
<cfoutput>
TOTAL INTEREST: #TotalInterest(Form.Principal, Form.AnnualPercent,
Form.Months)#<br>
</cfoutput>
The following example calls a custom tag using two variables, MyString and MyArray:
You cannot pass arrays, structures, or
CFX tag by using the
query attribute when calling the tag. ColdFusion normally converts simple
cfobject objects to CFX tags. You can pass a query to a
data types to strings when passing them to CFX tags; however, the Java Request Interface
getIntAttribute method lets you get a passed integer value.
82Chapter 3: Using ColdFusion Variables
CHAPTER 4
Using Expressions and Pound Signs
This chapter discusses how to use expressions in CFML. It discusses the elements of ColdFusion
Expressions and how to create expressions. It also describes the correct use of pound signs to
indicate expressions in ColdFusion tags such as
it describes how to use variables in variable names and strings to create dynamic expressions, and
dynamic variables.
cfoutput, in strings, and in expressions. Finally,
83
Expressions
ColdFusion expressions consist of operands and operators. Operands are comprised of constants
and variables. Operators, such as the multiplication symbol, are the verbs that act on the
operands; functions are a form of operator.
The simplest expression consists of a single operand with no operators. Complex expressions have
multiple operators and operands. The following are all ColdFusion expressions:
Operators act on the operands. Some operators, such as functions with a single argument, take a
single operand. Many operators, including most arithmetic and logical operators, take two
operands. The following is the general form of a two-operand expression:
Expression Operator Expression
Note that the operator is surrounded by expressions. Each expression can be a simple operand
(variable or constant) or a subexpression consisting of more operators and expressions. Complex
expressions are built up using subexpressions. For example, in the expression (1 + 1)/2, 1 + 1 is a
subexpression consisting of an operator and two operands.
Operator types
ColdFusion has four types of operators:
• Arithmetic
• Boolean
• Decision (or comparison)
• String
Functions also can be viewed as operators because they act on operands.
Arithmetic operators
The following table describes the arithmetic operators:
Operator Description
+ - * /Basic arithmetic: Addition, subtraction, multiplication, and division. In division, the right
+ -Unary arithmetic: Set the sign of a number.
MODModulus: Return the remainder after a number is divided by a divisor. The result has the
84Chapter 4: Using Expressions and Pound Signs
operand cannot be zero.
same sign as the divisor. The right should be an integer; using a non-numeric value
causes an error, and if you specify a real number, ColdFusion ignores the fractional part
(for example, 11 MOD 4 is 3).
Operator Description
\Integer division: Divide an integer by another integer. Use the backslash character (\) to
^Exponentiation: Return the result of a number raised to a power (exponent). Use the
separate the integers. The right operand cannot be zero. For example, 9\4 is 2.
caret character (^) to separate the number from the power; for example, 2^3 is 8. Real
and negative numbers are allowed for both the base and the exponent. However, any
expression that equates to an imaginary number, such -1^.5 results in the string "-1.#IND.
ColdFusion does not support imaginary or complex numbers.
Boolean operators
Boolean, or logical, operators perform logical connective and negation operations. The operands
of Boolean operators are Boolean (True/False) values.The following table describes the Boolean
operators:
Operator Description
NOTReverse the value of an argument. For example, NOT True is False and vice versa.
ANDReturn True if both arguments are True; return False otherwise. For example, True AND
ORReturn True if any of the arguments is True; return False otherwise. For example, True
XORExclusive or: Return True if one of the values is True and the other is False. Return False
EQVEquivalence: Return True if both operands are True or both are False. The EQV operator
IMPImplication: The statement A IMP B is the equivalent of the logical statement “If A Then
True is True, but True AND False is False.
OR False is True, but False OR False is False.
if both arguments are True or both are False. For example, True XOR True is False, but
True XOR False is True.
is the opposite of the XOR operator. For example, True EQV True is True, but True EQV
False is False.
B.” A IMP B is False only if A is True and B is False. It is True in all other cases.
Decision operators
The ColdFusion decision, or comparison, operators produce a Boolean True/False result. The
following table describes the decision operators:
OperatorDescription
ISPerform a case-insensitive comparison of two values. Return
IS NOTOpposite of IS. Perform a case-insensitive comparison of two
CONTAINSReturn True if the value on the left contains the value on the
DOES NOT CONTAINOpposite of CONTAINS. Return True if the value on the left
GREATER THANReturn True if the value on the left is greater than the value on
True if the values are identical.
values. Return True if the values are not identical.
right.
does not contain the value on the right.
the right.
Expressions85
OperatorDescription
LESS THANOpposite of GREATER THAN. Return True if the value on the
GREATER THAN OR EQUAL TOReturn True if the value on the left is greater than or equal to
LESS THAN OR EQUAL TOReturn True if the value on the left is less than or equal to the
Alternative notation for decision operators
left is smaller than the value on the right.
the value on the right.
value on the right.
You can replace some decision operators with alternative notations to make your CFML more
compact, as shown in the following table:
OperatorAlternative name(s)
ISEQUAL, EQ
IS NOTNOT EQUAL, NEQ
GREATER THANGT
LESS THANLT
GREATER THAN OR EQUAL TOGTE, GE
LESS THAN OR EQUAL TOLTE, LE
Decision operator rules
The following rules apply to decision operators:
• When ColdFusion evaluates an expression that contains a decision operator other than
CONTAINS or DOES NOT CONTAIN, it first determines if the data can be converted to
numeric values. If they can be converted, it performs a numeric comparison on the data. If
they cannot be converted, it performs a string comparison. This can sometimes result in
unexpected results. For more information on this behavior, see Chapter 3, “Evaluation and
type conversion issues,” on page 69.
• When ColdFusion evaluates an expression with CONTAINS or DOES NOT CONTAIN it
does a string comparison. The expression A CONTAINS B evaluates to True if B is a substring
of A. Therefore an expression such as the following evaluates as True:
123.45 CONTAINS 3.4
• When a ColdFusion decision operator compares strings, it ignores the case. As a result, the
following expression is True:
"a" IS "A"
• When a ColdFusion decision operator compares strings, it evaluates the strings from left to
right, comparing the characters in each position according to their sorting order. The first
position where the characters differ determines the relative values of the strings. As a result, the
following expressions are True:
"ab" LT "aba"
"abde" LT "ac"
86Chapter 4: Using Expressions and Pound Signs
String operators
There is one string operator, which is the concatenation operator.
OperatorDescription
&Concatenates strings.
Operator precedence and evaluation ordering
The order of precedence controls the order in which operators in an expression are evaluated. The
order of precedence is as follows:
Unary +, Unary ^
*, /
\
MOD
+, &
EQ, NEQ, LT, LTE, GT, GTE, CONTAINS, DOES NOT CONTAIN
NOT
AND
OR
XOR
EQV
IMP
To enforce a non-standard order of evaluation, you must parenthesize expressions. For example:
• 6 - 3 * 2 is equal to 0
• (6 - 3) * 2 is equal to 6
You can nest parenthesized expressions. When in doubt about the order in which operators in an
expression will be evaluated, use parentheses to force the order of evaluation.
Using functions as operators
Functions are a form of operator. Because ColdFusion functions return values, you can use
function results as operands. Function arguments are expressions. For example, the following are
valid expressions:
• Rand()
• UCase("This is a text: ") & ToString(123 + 456)
Expressions87
Function syntax
The following table shows function syntax and usage guidelines:
UsageExample
No arguments
Basic format
Nested functions
Multiple arguments
String arguments
Arguments that are expressions
Function()
Function(Data)
Function1(Function2(Data))
Function(Data1, Data2, Data3)
Function('This is a demo')
Function("This is a demo")
Function1(X*Y, Function2("Text"))
All functions return values. In the following example, the
returned by the
You can use the values returned by functions directly to create more complex expressions, as in the
following example:
Abs(Myvar)/Round(3.14159)
For more information on how to insert functions in expressions, see “Using pound signs”
on page 89.
Optional function arguments
Some functions take optional arguments after their required arguments. If omitted, all optional
arguments default to a predefined value. For example:
• Replace("Eat and Eat", "Eat", "Drink") returns "Drink and Eat"
• Replace("Eat and Eat", "Eat", "Drink", "All") returns "Drink and Drink"
The difference in the results is because the
that specifies the scope of replacement. The default value is “One,” which explains why only the
first occurrence of “Eat” was replaced with “Drink” in the first example. In the second example, a
fourth argument causes the function to replace all occurrences of “Eat” with “Drink”.
Expression evaluation and functions
It is important to remember that ColdFusion evaluates function attributes as expressions before it
executes the function. As a result, you can use any ColdFusion expression as a function attribute.
For example, consider the following lines:
<cfset firstVariable = "we all need">
<cfset myStringVar = UCase(firstVariable & " more sleep!")>
When ColdFusion server executes the second line, it does the following:
1 Determines that there is an expression with a string concatenation.
2 Evaluates the firstVariable variable as the string "we all need".
3 Concatenates "we all need" with the string " more sleep!" to get "we all need more sleep!".
4 Passes the string "we all need more sleep!" to the UCase function.
Replace function takes an optional fourth argument
88Chapter 4: Using Expressions and Pound Signs
5 Executes the UCase function on the string argument "we all need more sleep!" to get "WE ALL
NEED MORE SLEEP!".
6 Assigns the string value "WE ALL NEED MORE SLEEP!" to the variable myStringVar.
ColdFusion completes steps 1-3 before invoking the function.
Using pound signs
Pound signs (#) have a special meaning in CFML. When the ColdFusion server encounters
pound signs in CFML text, such as the text in a
cfoutput tag body, it checks to see if the text
between the pound signs is either a variable or a function.
Is so, it replaces the text and surrounding pound signs with the variable value or the result of the
function. Otherwise, ColdFusion generates an error.
For example, to output the current value of a variable named
Form.MyFormVariable, you delimit
(surround) the variable name with pound signs:
<cfoutput>Value is #Form.MyFormVariable#</cfoutput>
In this example, the variable Form.MyFormVariable is replaced with the value assigned to it.
Follow these guidelines when using pound signs:
• Use pound signs to distinguish variables or functions from plain text.
• Surround only a single variable or function in pound signs; for example, #Variables.myVar# or
#Left(myString, position)#. (However, a function in pound signs can contain nested functions,
such as #Left(trim(myString), position)#.
• Do not put complex expressions, such as 1 + 2 in pound signs.
• Use pound signs only where necessary, because unneeded pound signs slow processing.
The following sections provide more details on how to use pound signs in CFML. For a
description of using pound signs to create variable names, see “Using pound signs to construct a
variable name in assignments” on page 93
Using pound signs in ColdFusion tag attribute values
You can put variables, functions, or expressions inside tag attributes by enclosing the variable or
expression with pound signs. For example, if the variable CookieValue has the value "MyCookie",
the following line sets the
<cfcookie name="TestCookie" value="The value is #CookieValue#">
cfcookie value attribute to "The value is MyCookie":
You can optionally omit quotation marks around variables used as attribute values as shown in the
following example:
<cfcookie name = TestCookie value = #CookieValue#>
However, surrounding all attribute values in quotation marks is more consistent with HTML
coding style.
If you use string expressions to construct an attribute value, as shown in the following example,
the strings inside the expression use single quotation marks (’) to differentiate the quotation
marks from the quotation marks that surround the attribute value.
<cfcookie name="TestCookie2" value="The #CookieValue & 'ate the cookie!'#">
Using pound signs89
Note: You do not need to use pound signs when you use the cfset tag to assign one variable’s value
to another value. For example, the following tag assigns the value of the oldVar variable to the new
variable, newVar: <cfset newVar = oldVar>.
Using pound signs in tag bodies
You can put variables or functions freely inside the bodies of the following tags by enclosing each
variable or expression with pound signs:
• cfoutput
• cfquery
• cfmail
For example:
<cfoutput>
Value is #Form.MyTextField#
</cfoutput>
<cfoutput>
The name is #FirstName# #LastName#.
</cfoutput>
<cfoutput>
The value of Cos(0) is #Cos(0)#
</cfoutput>
If you omit the pound signs, the text, rather than the value, appears in the output generated by
the
cfoutput statement.
Two expressions inside pound signs can be adjacent to one another, as in the following example:
<cfoutput>
"Mo" and "nk" is #Left("Moon", 2)##Mid("Monkey", 3, 2)#
</cfoutput>
This code displays the following text:
"Mo" and "nk" is Monk
ColdFusion does not interpret the double pound sign as an escaped # character.
Using pound signs in strings
You can put variables or functions freely inside strings by enclosing each variable or expression
with pound signs; for example:
<cfset TheString = "Value is #Form.MyTextField#">
<cfset TheString = "The name is #FirstName# #LastName#.">
<cfset TheString = "Cos(0) is #Cos(0)#">
ColdFusion automatically replaces the text with the value of the variable or the value returned by
the function. For example, the following pairs of cfset statements produce the same result:
As with the cfoutput statement, two expressions can be adjacent to each other in strings, as in
the following example:
<cfset TheString = "Monk is #Left("Moon", 2)##Mid("Monkey", 3, 2)#">
The double quotes around "Moon" and "Monkey" do not need to be escaped (as in ""Moon""
and ""Monkey""). This is because the text between the pound signs is treated as an expression; it
is evaluated before its value is inserted inside the string.
Nested pound signs
In a few cases, you can nest pound signs in an expression. The following example uses nested
pound signs:
<cfset Sentence = "The length of the full name is
#Len("#FirstName# #LastName#")#">
In this example, pound signs are nested so that the values of the variables FirstName and
LastName are inserted in the string whose length the
Len function calculates.
Nested pound signs imply a complex expression that can typically be written more clearly and
efficiently without the nesting. For example, you can rewrite the preceding code example without
the nested pound signs, as follows:
<cfset Sentence2 = "The length of the full name is #Len(FirstName & " "
& LastName)#">
The following achieves the same results and can further improve readability:
<cfset FullName = "#FirstName# #LastName#">
<cfset Sentence = "The length of the full name
is #Len(FullName)#">
A common mistake is to put pound signs around the arguments of functions, as in:
These statements result in errors. As a general rule, never put pound signs around function
arguments.
Using pound signs in expressions
Use pound signs in expressions only when necessary, because unneeded pound signs reduce clarity
and can increase processing time. The following example shows the preferred method for
referencing variables:
This section discusses the advanced topics of dynamic expressions, dynamic evaluation, and
dynamic variable naming. Many ColdFusion programmers never encounter or need to use
dynamic expressions. However, dynamic variable naming is important in situations where the
variable names are not known in advance, such as in shopping cart applications.
This section also discusses the use of the
expressions. This function dynamically evaluates its arguments, and you must often use the
function to prevent the evaluation. For more information on using the
the IIF function” on page 98
Note: This section uses several tools and techniques that are documented in later chapters. If you are
unfamiliar with using ColdFusion forms, structures, and arrays, you should learn about these tools
before reading this section.
.
About dynamic variables
Dynamic variables are variables that are named dynamically, typically by creating a variable name
from a static part and a variable part. For example, the following example dynamically constructs
the variable name from a variable prefix and a static suffix:
<cfset "#flavor#_availability" = "out of stock">
Using dynamic variables in this manner does not require dynamic evaluation.
About dynamic expressions and dynamic evaluation
In a dynamic expression, the actual expression, not just its variable values, is determined at
execution time. In other words, in a dynamic expression the structure of the expression, such as
the names of the variables, not just the values of the variables, gets built at runtime.
You create dynamic expressions using string expressions, which are expressions contained in strings,
(that is, surrounded with quotation marks). Dynamic evaluation is the process of evaluating a
string expression. The
Evaluate and IIf functions, and only these functions, perform dynamic
evaluation.
When ColdFusion performs dynamic evaluation it does the following:
1 Takes a string expression and treats it as a standard expression, as if the expression was not a
string.
2 Parses the expression to determine the elements of the expression and validate the expression
syntax.
3 Evaluates the expression, looking up any variables and replacing them with their values, calling
any functions, and performing any required operations.
This process enables ColdFusion to interpret dynamic expressions with variable parts. However, it
incurs a substantial processing overhead.
Dynamic expressions were important in early versions of ColdFusion, before it supported arrays
and structures, and they still can be useful in limited circumstances. However, the ability to use
structures and the ability to use associative array notation to access structure elements provide
more efficient and easier methods for dynamically managing data. For information on using
arrays and structures, see Chapter 5, “Using Arrays and Structures,” on page 103.
IIf function, which is most often used without dynamic
IIF function, see “Using
DE
92Chapter 4: Using Expressions and Pound Signs
Selecting how to create variable names
The following two examples describes cases when you need dynamic variable names:
• Form applications where the number and names of fields on the form vary dynamically. In this
case, the form posts only the names and values of its fields to the action page. The action page
does not know all the names of the fields, although it does know how the field names (that is,
the variable names) are constructed.
• If the following are true:
■ ColdFusion calls a custom tag multiple times.
■ The custom tag result must be returned to different variables each time.
■ The calling code can specify the variable in which to return the custom tag result.
In this case, the custom tag does not know the return variable name in advance, and gets it as
an attribute value.
In both cases, it might appear that dynamic expressions using the
Evaluate function are needed
to construct the variable names. However, you can achieve the same ends more efficiently by
using dynamic variable naming, as shown in “Example: a dynamic shopping cart” on page 99.
This does not mean that you must always avoid dynamic evaluation. However, given the
substantial performance costs of dynamic evaluation, you should first ensure that one of the
following techniques cannot serve your purpose:
• An array (using index variables)
• Associative array references containing expressions to access structure elements
• Dynamically generated variable names
Dynamic variable naming without dynamic evaluation
While ColdFusion does not always allow you to construct a variable name in-line from variable
pieces, it does let you to do so in the most common uses, as described in the following sections.
Using pound signs to construct a variable name in assignments
You can combine text and variable names to construct a variable name on the left side of a
cfset
assignment. For example, the following code sets the value of the variable Product12 to the string
"Widget":
When you use a dynamic variable name in quotes on the left side of an assignment, the name
must be either a simple variable name or a complex name that uses object.property notation (such
as MyStruct.#KeyName#). You cannot use an array as part of a dynamic variable name. For
example, the following code generates an error:
However, you can construct an array index value dynamically from variables without using quotes
on the left side of an assignment. For example, the preceding sample code works if you replace the
final line with the following line:
The ability to use associative array notation to reference structures provides a way for you to use
variables to dynamically create structure references. (For a description of associative array
notation, see Chapter 5, “Structure notation,” on page 114.) Associative array structure notation
allows you to use a ColdFusion expression inside the index brackets. For example, if you have a
productName structure with keys of the form product_1, product_2 and so on, you can use the
following code to display the value of productName.product_3:
For an example of using this format to manage a shopping cart, see “Example: a dynamic
shopping cart” on page 99.
Using dynamic evaluation
The following sections describe how to use dynamic evaluation and create dynamic expressions.
ColdFusion dynamic evaluation functions
The following table describes the functions that perform dynamic evaluation and are useful in
evaluating dynamic expressions:
FunctionPurpose
DEEscapes any double quotes in the argument and wraps the result in double
EvaluateTakes one or more string expressions and dynamically evaluates their contents
94Chapter 4: Using Expressions and Pound Signs
quotes. The
function from evaluating a string to be output.
For an example of using the
function” on page 98.
as expressions from left to right. (The results of an evaluation to the left can have
meaning in an expression to the right.) Returns the result of evaluating the
rightmost argument.
For more information on this function see “About the Evaluate function”
on page 95.
DE function is particularly useful with the IIF function, to prevent the
DE function with the IIF function, see “Using the IIF
FunctionPurpose
IIfEvaluates a boolean condition expression. Depending on whether this
SetVariableSets a variable identified by the first argument to the value specified by the
expression is True or False, dynamically evaluates one of two string expressions
and returns the result of the evaluation. The
incorporating a cfif tag in-line in HTML.
For an example of using this function, see “Using the IIF function” on page 98.
second argument. This function is no longer required in well-formed ColdFusion
pages; see “SetVariable function considerations” on page 97.
IIF function is convenient for
Function argument evaluation considerations
It is important to remember that ColdFusion always evaluates function arguments before the
argument values are passed to a function:
For example, consider the following
<cfoutput>#DE("1" & "2")#</cfoutput>
DE function:
You might expect this line to display """1"" & ""2""". Instead, it displays “12”, because
ColdFusion processes the line as follows:
1 Evaluates the expression "1" & "2" as the string “12”.
2 Passes the string "12" (without the quotes) to the DE function.
3 Calls the DE function, which adds literal quotation marks around the 12.
Similarly, if you use the expression DE(1 + 2), ColdFusion evaluates 1 + 2 as the integer 3 and
passes it to the function. The function converts it to a string and surrounds the string in literal
quotation marks: “3”.
About the Evaluate function
The
Evaluate function takes one or more string expressions, dynamically evaluates their contents
as expressions from left to right, and returns the result of evaluating the rightmost argument.
The following example shows the
Evaluate function and how it works with ColdFusion variable
The following table describes how ColdFusion processes this code:
CodeDescription
<cfset myVar2="myVar">
<cfset myVar="27/9">
<cfoutput>
#myVar2#<br>
#myVar#<br>
#Evaluate("myVar2")#<br>
#Evaluate("myVar")#<br>
#Evaluate(myVar2)#<br>
#Evaluate(myVar)#<br>
</cfoutput>
Sets the two variables to the following strings:
myVar
27/9
Displays the values assigned to the variables, myVar and 27/9
respectively.
Passes the string "myvar2" (without the quotes) to the Evaluate
function, which does the following:
1 Evaluates it as the variable myVar2.
2 Returns the value of the myVar2 variable, the string "myvar"
(without the quotes).
Passes the string "myvar" (without the quotes) to the Evaluate
function, which does the following:
1 Evaluates it as the variable myVar.
2 Returns the value of the myVar variable, the string "27/9"
(without the quotes).
Evaluates the variable myVar2 as the string "myVar" and passes
the string (without the quotes) to the Evaluate function. The rest
of the processing is the same as in the previous line.
Evaluates the variable myVar as the string "27/9" (without the
quotes), and passes it to the Evaluate function, which does the
following:
1 Evaluates the string as the expression 27/9
2 Performs the division.
3 Returns the resulting value, 3
As you can see, using dynamic expressions can result in substantial expression evaluation
overhead, and the code can be confusing. Therefore, you should avoid using dynamic expressions
wherever a simpler technique, such as using indexed arrays or structures can serve your purposes.
Avoiding the Evaluate function
Using the
Evaluate function increases processing overhead, and in most cases it is not necessary.
The following sections provide examples of cases where you might consider using the Evaluate
function.
Example 1
You might be inclined to use the Evaluate function in code such as the following:
<cfoutput>1 + 1 is #Evaluate(1 + 1)#</cfoutput>
Although this code works, it is not as efficient as the following code:
<cfset Result = 1 + 1>
<cfoutput>1 + 1 is #Result#</cfoutput>
96Chapter 4: Using Expressions and Pound Signs
Example 2
This example shows how you can use an associative array reference in place of an Evaluate
function. This technique is powerful because:
• Most ColdFusion scopes are accessible as structures.
• You can use ColdFusion expressions in the indexes of associative array structure references. (For
more information on using associative array references for structures, see Chapter 5, “Structure
This code comes from an example where a form has entries for an indeterminate number of items
in a shopping cart. For each item in the shopping cart there is a product name field. The field
name is of the form product_1, product_2, and so on, where the number corresponds to the
product’s entry in the shopping cart. In this example, ColdFusion does the following:
1 Replaces the variable i with its value, for example 1.
2 concatenates the variable value with "Form.product_", and passes the result (for
Form.product_1) to the
3 Parses the variable product_1 and generates an executable representation of the variable.
Because ColdFusion must invoke its parser, this step requires substantial processing, even for a
simple variable.
4 Evaluates the representation of the variable, for example as "Air popper".
5 Returns the value of the variable.
The following example has the same result as the preceding example and is more efficient:
1 Evaluates the expression in the associative array index brackets as the string "product_"
concatenated with the value of the variable i.
2 Determines the value of the variable i; 1.
3 Concatenates the string and the variable value to get product_1.
4 Uses the result as the key value in the Form structure to get Form[product_1]. This associative
array reference accesses the same value as the object.attribute format reference Form.product_1;
in this case, Air popper.
This code format does not use any dynamic evaluation, but it achieves the same effect, of
dynamically creating a structure reference by using a string and a variable.
Evaluate function to construct a variable name:
Evaluate function, which does the remaining steps.
SetVariable function considerations
You can avoid using the
SetVariable function by using a format such as the following to set a
dynamically named variable. For example, the following lines are equivalent:
<cfset SetVariable("myVar" & i, myVal)>
<cfset "myVar#i#" = myVal>
Dynamic expressions and dynamic variables97
In the second line, enclosing the myVar#i# variable name in quotation marks tells ColdFusion to
evaluate the name and process any text in pound signs as a variable or function. ColdFusion
replaces the #i# with the value of the variable i, so that if the value of i is 12, this code is
equivalent to the line
<cfset myVar12 = myVal>
For more information on this usage, see “Using pound signs to construct a variable name in
assignments” on page 93.
Using the IIF function
The
IIf function is a shorthand for the following code:
<cfif argument1>
<cfset result = Evaluate(argument1)>
<cfelse>
<cfset result = Evaluate(argument2)>
</cfif>
The function returns the value of the result variable. It is comparable to the use of the JavaScript
and Java ? : operator, and can result in more compact code. As a result, the
IIF function can be
convenient even if you are not using dynamic expressions.
The
IIF function requires the DE function to prevent ColdFusion from evaluating literal strings,
as the following example shows:
<cfoutput>
#IIf(IsDefined("LocalVar"), "LocalVar", DE("The variable is not
defined."))#
</cfoutput>
If you do not enclose the string "The variable is not defined." in a DE function, the IIF function
tries to evaluate the contents of the string as an expression and generates an error (in this case, an
invalid parser construct error).
The
IIF function is useful for incorporating ColdFusion logic in-line in HTML code, but it
entails a processing time penalty in cases where you do not otherwise need dynamic expression
evaluation.
The following example shows using
and gray. It also shows the use of the
IIF to alternate table row background color between white
DE function to prevent ColdFusion from evaluating the color
<cfset Color = "gray">
</cfif>
<tr bgcolor="#color#">
<td>
hello #i#
</td>
</tr>
</cfloop>
</table>
</cfoutput>
Example: a dynamic shopping cart
The following example dynamically creates and manipulates variable names without using
dynamic expression evaluation by using associative array notation.
You need to dynamically generate variable names in applications such as shopping carts, where
the required output is dynamically generated and variable. In a shopping cart, you do not know in
advance the number of cart entries or their contents. Also, because you are using a form, the
action page only receives Form variables with the names and values of the form fields.
The following example shows the shopping cart contents and lets you edit your order and submit
it. To simplify things, the example automatically generates the shopping cart contents using
CFScript instead of having the user fill the cart. A more complete example would populate a
shopping cart as the user selected items. Similarly, the example omits all business logic for
committing and making the order.
To create the form:
1 Create a file in your editor.
<html>
<head>
<title>Shopping Cart</title>
</head>
<cfscript>
CartItems=4;
Cart = ArrayNew(1);
for ( i=1; i LE cartItems; i=i+1)
{
Cart[i]=StructNew();
Cart[i].ID=i;
Cart[i].Name="Product " & i;
Cart[i].SKU=i*100+(2*i*10)+(3*i);
Cart[i].Qty=3*i-2;
}
</cfscript>
<body>
Your shopping cart has the following items.<br>
You can change your order quantities.<br>
If you don't want any item, clear the item's check box.<br>
When you are ready to order, click submit.<br>
<br>
<cfform name="ShoppingCart" action="ShoppingCartAction.cfm" method="post">
<table>
Create a shopping cart as an array of structures,
with each structure containing the cart item ID,
product name, SKU number, and quantity ordered
for one item in the cart. Populate the shopping cart
by looping CartItems times and setting the structure
variables to arbitrary values based on the loop
counter. A real application would set the Name,
SKU, and Quantity values on other pages.
Start the form and its embedded table. When the
user clicks the submit button, post the form data to
the ShoppingCartAction.cfm page.
The table formats the form neatly. The first table
row contains the column headers. Each following
row has the data for one cart item.
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.