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.
CFML Reference is your primary ColdFusion Markup Language (CFML) reference. Use this book
to learn about CFML tags and functions, ColdFusion expressions, and using JavaScript objects
for WDDX in Macromedia ColdFusion MX. It also provides detailed references for Java and C++
CFX interfaces.
About Macromedia ColdFusion MX documentation
The ColdFusion MX documentation is designed to provide support for the complete spectrum of
participants.
Documentation set
The ColdFusion documentation set includes the following titles:
BookDescription
Installing and Using
ColdFusion MX
Configuring and
Administering
ColdFusion MX
Developing ColdFusion
MX Applications
Getting Started
Building ColdFusion
MX Applications
CFML Reference Provides descriptions, syntax, usage, and code examples for all ColdFusion
CFML Quick Reference A brief guide that shows the syntax of ColdFusion tags, functions, and
Describes system installation and basic configuration for Windows, Solaris,
Linux, and HP-UX.
Part I describes how to manage the ColdFusion environment, including
connecting to your data sources and configuring security for your
applications. Part II describes Verity search tools and utilities that you can
use for configuring the Verity K2 Server search engine, as well as creating,
managing, and troubleshooting Verity collections.
Describes how to develop your dynamic web applications, including
retrieving and updating your data, using structures, and forms.
Contains an overview of ColdFusion features and application development
procedures. Includes a tutorial that guides you through the process of
developing an example ColdFusion application.
tags, functions, and variables.
variables.
17
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.
18Introduction
CHAPTER 1
Reserved Words and Variables
This chapter provides information on ColdFusion reserved words and lists scope variables.
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.
• Any name starting with cf. However, when you call a CFML custom tag directly, you prefix the
custom tag page name with cf_.
• Built-in function names, such as Now or Hash
• Scope names, such as Form or Session
• 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
Remember that ColdFusion is not case-sensitive. For example, all of the following are reserved
words: IS, Is, iS, and is.
Reserved words in forms
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.
• _integer
• _float
• _range
• _date
• _time
• _eurodate
Reserved words in queries
The following table lists SQL keywords that are reserved in ColdFusion queries of queries. This
list includes all reserved words in the SQL standard, and should be avoided in variables used in all
queries. Do not use these keywords as variable names in any queries.
Note: Many database management systems have additional reserved words that you cannot use as
variable names in queries to their databases. See your DBMS documentation for detailed list.
ABSOLUTEACTIONADDALLALLOCATE
ALTERANDANYAREAS
ASCASSERTIONATAUTHORIZATION AVG
BEGINBETWEENBITBIT_LENGTHBOTH
BYCASCADECASCADEDCASECAST
CATALOGCHARCHARACTERCHARACTER_
CHECKCLOSECOALESCECOLLATECOLLATION
20Chapter 1: Reserved Words and Variables
CHAR_LENGTH
LENGTH
COLUMNCOMMITCONNECTCONNECTIONCONSTRAINT
CONSTRAINTSCONTINUECONVERTCORRESPON
COUNT
DING
CREATECROSSCURRENTCURRENT_DATECURRENT_TIME
CURRENT_TIME
CURRENT_USER CURSORDATEDAY
STAMP
DEALLOCATEDECDECIMALDECLAREDEFAULT
DEFERRABLEDEFERREDDELETEDESCDESCRIBE
DESCRIPTORDIAGNOSTICSDISCONNECTDISTINCTDOMAIN
DOUBLEDROPELSEENDEND-EXEC
ESCAPEEXCEPTEXCEPTIONEXECEXECUTE
EXISTSEXTERNALEXTRACTFALSEFETCH
FIRSTFLOATFORFOREIGNFOUND
FROMFULLGETGLOBALGO
GOTOGRANTGROUPHAVINGHOUR
IDENTITYIMMEDIATEININDICATORINITIALLY
INNERINPUTINSENSITIVEINSERTINT
INTEGERINTERSECTINTERVALINTOIS
ISOLATIONJOINKEYLANGUAGELAST
LEADINGLEFTLEVELLIKELOCAL
LOWERMATCHMAXMINMINUTE
MODULEMONTHNAMESNATIONALNATURAL
NCHARNEXTNONOTNULL
NULLIFNUMERICOCTET_LENGTHOFON
ONLYOPENOPTIONORORDER
OUTEROUTPUTOVERLAPSPADPARTIAL
POSITIONPRECISIONPREPAREPRESERVEPRIMARY
PRIORPRIVILEGESPROCEDUREPUBLICREAD
REALREFERENCESRELATIVERESTRICTREVOKE
RIGHTROLLBACKROWSSCHEMASCROLL
SECONDSECTIONSELECTSESSIONSESSION_USER
SETSIZESMALLINTSOMESPACE
SQLSQLCODESQLERRORSQLSTATESUBSTRING
SUMSYSTEM_USERTABLETEMPORARYTHEN
Reserved words21
TIMETIMESTAMPTIMEZONE_
HOUR
TIMEZONE_
MINUTE
TO
TRAILINGTRANSACTIONTRANSLATETRANSLATIONTRIM
TRUEUNIONUNIQUEUNKNOWNUPDATE
UPPERUSAGEUSERUSINGVALUE
VALUESVARCHARVARYINGVIEWWHEN
WHENEVERWHEREWITHWORKWRITE
YEARZONE
22Chapter 1: Reserved Words and Variables
Scope-specific built-in variables
ColdFusion returns variables, such as those returned in a cfdirectory or cfftp operation. A
variable is usually referenced by scoping it according to its type: naming it according to the code
context in which it is available; for example, Session.varname, or Application.varname. For more
information on ColdFusion scopes, see Chapter 3, “Using ColdFusion Variables,” in Developing
ColdFusion MX Applications
You use the
cflock tag to limit the scope of CFML constructs that modify shared data structures,
files, and CFXs, to ensure that modifications occur sequentially. For more information, see
cflock on page 221, and Chapter 15, “Using Persistent Data and Locking,” in Developing
ColdFusion MX Applications.
Variable scope
ColdFusion supports the Variables scope. Unscoped variables created with the
cfset tag acquire
the Variables scope by default. For example, the variable created by the statement
linguist = Chomsky>
can be referenced as #Variables.linguist#
Caller scope
History
ColdFusion MX: The Caller scope is accessible as a structure. (In earlier releases, it was not.)
Client variables
The following client variables are read-only:
Client.CFID
Client.CFToken
Client.HitCount
Client.LastVisit
Client.TimeCreated
Client.URLToken
<CFSET
Server variables
Use the Server prefix to reference server variables, as follows:
Server.ColdFusion.ProductName
Server.ColdFusion.ProductVersion
Server.ColdFusion.ProductLevel
Server.ColdFusion.SerialNumber
Server.ColdFusion.SupportedLocales
Server.OS.Name
Server.OS.AdditionalInformation
Server.OS.Version
Server.OS.BuildNumber
Application and session variables
To enable application and session variables, use the
follows:
Application.myvariable
Session.myvariable
cfapplication tag. Reference them as
Scope-specific built-in variables23
To ensure that modifications to shared data occur in the intended sequence, use the cflock tag.
For more information, see
cflock on page 221.
The predefined application and session variables are as follows:
Application.ApplicationName
Session.CFID
Session.CFToken
Session.URLToken
Custom tag variables
A ColdFusion custom tag returns the following variables:
ThisTag.ExecutionMode
ThisTag.HasEndTag
ThisTag.GeneratedContent
ThisTag.AssocAttribs[index]
A custom tag can set a Caller variable to provide information to the caller. The Caller variable is
set as follows:
<cfset Caller.variable_name = "value">
The calling page can access the variable with the cfoutput tag, as follows:
<cfoutput>#Caller.variable_name#</cfoutput>
Request variable
Request variables store data about the processing of one page request. Request variables store data
in a structure that can be passed to nested tags, such as custom tags, and processed once.
To provide information to nested tags, set a Request variable, as follows:
<CFSET Request.field_name1 = "value">
<CFSET Request.field_name2 = "value">
<CFSET Request.field_name3 = "value">
...
Each nested tag can access the variable with the cfoutput tag, as follows:
<CFOUTPUT>#Request.field_name1#</CFOUTPUT>
Form variable
ColdFusion supports the Form variable FieldNames. FieldNames returns the names of the fields
on a form. You use it on the action page associated with a form, as follows:
Form.FieldNames
ColdFusion tag-specific variables
Some ColdFusion tags return data as variables. For example, the cffile tag returns file size
information in the FileSize variable, referenced as CFFILE.FileSize.
The following tags return data that can be referenced in variables:
cfcatch
cfdirectory
cferror
cffile
cfftp
24Chapter 1: Reserved Words and Variables
cfhttp
cfindex
cfldap
cfmail
cfpop
cfquery
cfregistry
cfsearch
cfstoredproc
ColdFusion query variables
A ColdFusion tag that returns a query object supports the following variables, where queryname is
the value of the
queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList
name attribute:
CFCATCH variables
Within a
cfcatch block, the active exception properties can be accessed as the following
variables:
CFCATCH.Type
CFCATCH.Message
CFCATCH.Detail
CFCATCH.ErrNumber
CFCATCH.NativeErrorCode
CFCATCH.SQLState
CFCATCH.LockName
CFCATCH.LockOperation
CFCATCH.MissingFileName
CFCATCH.TagContext
CFCATCH.ErrorCode
CFCATCH.ExtendedInfo
CFDIRECTORY variables
The
cfdirectory tag, with action=list, returns a query object as follows, where queryname is
the
name attribute value:
queryname.Name
queryname.Size
queryname.Type
queryname.DateLastModified
queryname.Attributes
queryname.Mode
CFERROR variables
When
type="request", "exception", or "monitor".
Error.Diagnostics
Error.MailTo
Error.DateTime
Error.Browser
Error.GeneratedContent
Error.RemoteAddress
cferror generates an error page, the following error variables are available if
ColdFusion tag-specific variables25
Error.HTTPReferer
Error.Template
Error.QueryString
The following error variables are available if type="validation".
Error.ValidationHeader
Error.InvalidFields
Error.ValidationFooter
Any cfcatch variable that applies to exception type can be accessed within the Error scope, as
follows:
Error.Type
Error.Message
Error.Detail
Error.ErrNumber
Error.NativeErrorCode
Error.SQLState
Error.LockName
Error.LockOperation
Error.MissingFileName
Error.TagContext
Error.ErrorCode
Error.ExtendedInfo
Note: You can substitute the prefix CFERROR for Error, if type = "Exception" or "Monitor"; for
example, CFERROR.Diagnostics, CFERROR.Mailto or CFERROR.DateTime.
CFFILE ACTION=Upload variables
File variables are read-only. Use the CFFILE prefix to reference file variables; for example,
CFFILE.ClientDirectory. The File prefix is deprecated in favor of the CFFILE prefix.
CFFILE.AttemptedServerFile
CFFILE.ClientDirectory
CFFILE.ClientFile
CFFILE.ClientFileExt
CFFILE.ClientFileName
CFFILE.ContentSubType
CFFILE.ContentType
CFFILE.DateLastAccessed
CFFILE.FileExisted
CFFILE.FileSize
CFFILE.FileWasAppended
CFFILE.FileWasOverwritten
CFFILE.FileWasRenamed
CFFILE.FileWasSaved
CFFILE.OldFileSize
CFFILE.ServerDirectory
CFFILE.ServerFile
CFFILE.ServerFileExt
CFFILE.ServerFileName
CFFILE.TimeCreated
CFFILE.TimeLastModified
CFFTP error variables
When you use the
CFFTP.Succeeded
26Chapter 1: Reserved Words and Variables
cfftp stoponerror attribute, these variables are populated:
CFFTP.ErrorCode
CFFTP.ErrorText
CFFTP ReturnValue variable
Some
cfftp file and directory operations provide a return value, in the variable
CFFTP.ReturnValue. Its value is determined by the results of the
specify any of the following actions,
GetCurrentDir
GetCurrentURL
ExistsDir
ExistsFile
Exists
cfftp returns a value:
CFFTP query object columns
action attribute. When you
When you use the
queryname is the
queryname.Name[row]
queryname.Path[row]
queryname.URL[row]
queryname.Length[row]
queryname.LastModified[row]
queryname.Attributes
queryname.IsDirectory
queryname.Mode
cfftp tag with the listdir action, cfftp returns a query object, where
name attribute value, and row is the row number of each file or directory entry:
CFHTTP variables
A
cfhttp get operation can return text and binary files. Files are downloaded and the contents
stored in a variable or file, depending on the MIME type, as follows:
CFHTTP.FileContent
CFHTTP.MimeType
CFHTTP.Header
CFHTTP.ResponseHeader[http_hd_key]
CFHTTP.StatusCode
CFLDAP variables
The
cfldap action=query tag returns information about the LDAP query, as follows:
queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList
CFPOP variables
The
cfpop tag returns the following result columns, depending on the action attribute value and
the use of other attributes, such as attachmentpath, where queryname is the name attribute value:
queryname.Date
queryname.From
queryname.Body
queryname.Header
queryname.MessageNumber
queryname.ReplyTo
queryname.Subject
ColdFusion tag-specific variables27
queryname.CC
queryname.To
queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList
queryname.Attachments
queryname.AttachmentFiles
CFQUERY and CFSTOREDPROC variables
The
cfquery tag returns information about the query in this variable:
CFQUERY.ExecutionTime
The cfquery tag uses the query name to scope the following data about the query:
queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList
The cfstoredproc tag returns the following variables:
CFSTOREDPROC.ExecutionTime
CFSTOREDPROC.StatusCode
CFREGISTRY variables
The
cfregistry tag returns a query record set that you can reference after executing the GetAll
action, as follows, where queryname is the
name attribute value:
queryname.Entry
queryname.Type
queryname.Value
CFSEARCH variables
A
cfsearch operation returns the following variables, where searchname is the name attribute
value:
searchname.URL
searchname.Key
searchname.Title
searchname.Score
searchname.Custom1 and Custom2
searchname.Summary
searchname.RecordCount
searchname.CurrentRow
searchname.RecordsSearched
searchname.ColumnList
28Chapter 1: Reserved Words and Variables
Standard CGI variables
This section lists the CGI 1.1 variables that some web servers create when a CGI script is called.
The CGI variables that are available for your use vary with the web server and configuration.
Some of the following variables may not be available.
Request
CGI.AUTH_TYPE
CGI.CONTENT_LENGTH
CGI.CONTENT_TYPE
CGI.PATH_INFO
CGI.PATH_TRANSLATED
CGI.QUERY_STRING
CGI.REMOTE_ADDR
CGI.REMOTE_HOST
CGI.REMOTE_USER
CGI.REQUEST_METHOD
CGI.SCRIPT_NAME
Server
CGI.GATEWAY_INTERFACE
CGI.SERVER_NAME
CGI.SERVER_PORT
CGI.SERVER_PROTOCOL
CGI.SERVER_SOFTWARE
Client
CGI.CERT_ISSUER
CGI.CERT_SUBJECT
CGI.CLIENT_CERT_ENCODED
CGI.HTTP_ACCEPT
CGI.HTTP_IF_MODIFIED_SINCE
CGI.HTTP_USER_AGENT
The CERT_ISSUER, CERT_SUBJECT, CLIENT_CERT_ENCODED variables are available only when you
use client certificates.
CGI environment variables
When a browser makes a request to a server, the web server and the browser create environment
variables. In ColdFusion, these variables are referred to as CGI environment variables. They take
the CGI prefix regardless of whether the server uses a server API or CGI to communicate with the
ColdFusion server.
Environment variables contain data about the transaction between the browser and the server,
such as the IP Address, browser type, and authenticated username. You can reference CGI
environment variables for a given page request anywhere in the page. CGI variables are read-only.
Note: The environment variables available to applications depend on the browser and server
software.
CGI environment variables29
Testing for CGI variables
Because some browsers do not support some CGI variables, ColdFusion always returns True
when it tests for the existence of a CGI variable, regardless of whether the browser supports the
variable. To determine if the CGI variable is available, test for an empty string, as shown in the
following example:
<cfif CGI.varname IS NOT "">
CGI variable exists
<cfelse>
CGI variable does not exist
</cfif>
CGI server variables
The following table describes common CGI environment variables that the server creates (some
of these are not available with some servers):
CGI server variableDescription
SERVER_SOFTWAREName and version of the information server software answering the
request (and running the gateway). Format: name/version.
SERVER_NAMEServer's hostname, DNS alias, or IP address as it appears in self-
referencing URLs.
GATEWAY_INTERFACE CGI specification revision with which this server complies. Format: CGI/
revision.
SERVER_PROTOCOLName and revision of the information protocol this request came in with.
Format: protocol/revision.
SERVER_PORTPort number to which the request was sent.
REQUEST_METHODMethod with which the request was made. For HTTP, this is Get, Head,
Post, and so on.
PATH_INFOExtra path information, as given by the client. Scripts can be accessed
by their virtual pathname, followed by extra information at the end of this
path. The extra information is sent as PATH_INFO.
PATH_TRANSLATEDTranslated version of PATH_INFO after any virtual-to-physical mapping.
SCRIPT_NAMEVirtual path to the script that is executing; used for self-referencing
URLs.
QUERY_STRINGQuery information that follows the ? in the URL that referenced this
script.
REMOTE_HOSTHostname making the request. If the server does not have this
information, it sets REMOTE_ADDR and does not set
REMOTE_HOST.
REMOTE_ADDRIP address of the remote host making the request.
AUTH_TYPEIf the server supports user authentication, and the script is protected, the
protocol-specific authentication method used to validate the user.
REMOTE_USER
AUTH_USER
30Chapter 1: Reserved Words and Variables
If the server supports user authentication, and the script is protected, the
username the user has authenticated as. (Also available as
AUTH_USER.)
CGI server variableDescription
REMOTE_IDENTIf the HTTP server supports RFC 931 identification, this variable is set to
the remote username retrieved from the server. Use this variable for
logging only.
CONTENT_TYPEFor queries that have attached information, such as HTTP POST and
PUT, this is the content type of the data.
CONTENT_LENGTHLength of the content as given by the client.
CGI client variables
The following table describes common CGI environment variables the browser creates and passes
in the request header:
CGI client variableDescription
HTTP_REFERERThe referring document that linked to or submitted form data.
HTTP_USER_AGENTThe browser that the client is currently using to send the request.
Format: software/version library/version.
HTTP_IF_MODIFIED_SINCEThe last time the page was modified. The browser determines
whether to set this variable, usually in response to the server having
sent the LAST_MODIFIED HTTP header.
advantage of browser-side caching.
It can be used to take
CGI client certificate variables
ColdFusion makes available the following client certificate data. These variables are available
when running Microsoft IIS 4.0 or Netscape Enterprise under SSL if your web server is
configured to accept client certificates.
CGI client certificate variable Description
CERT_SUBJECTClient-specific information provided by the web server. This data
typically includes the client's name, e-mail address, etc. For
example:
O = "VeriSign, Inc.", OU = VeriSign Trust Network, OU =
"www.verisign.com/repository/RPA Incorp. by
Ref.,LIAB.LTD(c)98", OU = Persona Not Validated, OU =
Digital ID Class 1 - Microsoft, CN = Matthew Lund, E =
mlund@macromedia.com
CERT_ISSUERInformation about the authority that provided the client certificate.
For example:
O = "VeriSign, Inc.", OU = VeriSign Trust Network, OU =
"www.verisign.com/repository/RPA Incorp. By
Ref.,LIAB.LTD(c)98", CN = VeriSign Class 1 CA Individual
Subscriber-Persona Not Validated
CLIENT_CERT_ENCODEDThe entire client certificate binary, base-64 encoded. This data is
typically of interest to developers, so they can integrate with other
software that uses client certificates.
CGI environment variables31
32Chapter 1: Reserved Words and Variables
CHAPTER 2
ColdFusion Tags
ColdFusion Markup Language (CFML) includes a set of tags that you use in ColdFusion pages to
interact with data sources, manipulate data, and display output. CFML tag syntax is similar to
HTML element syntax.
This chapter contains categorized and alphabetical lists of the tags followed by the detailed tag
The following tables list Tags, attributes, and values that have changed since ColdFusion 5.0 and
indicate the specific release in which the change was made.
This table lists tags, attributes, and attribute values that have been added in ColdFusion MX
releases:
Added in this ColdFusion
TagAttribute or value
cfapplicationloginStorageColdFusion MX 6.1
cfargumentAllColdFusion MX
release
cfcache
cfchartAllColdFusion MX
cfchartdataAllColdFusion MX
cfchartseriesAllColdFusion MX
cfcollection
cfcomponentAllColdFusion MX
cfexecute
cffunctionAllColdFusion MX
cfhttp attributeColdFusion MX
timespan attributeColdFusion MX
cachedirectory attributeColdFusion MX
list value of action attributeColdFusion MX
name attributeColdFusion MX
variable attributeColdFusion MX 6.1
charset attributeColdFusion MX
HEAD, PUT, DELETE, OPTIONS, and TRACE
methods of
multipart attributeColdFusion MX 6.1
getasbinary attributeColdFusion MX 6.1
method attribute
ColdFusion MX 6.1
cfhttpparam
42Chapter 2: ColdFusion Tags
proxyUserColdFusion MX 6.1
proxyPasswordColdFusion MX 6.1
header and body values of type
attribute
encoded attributeColdFusion MX 6.1
mimeType attributeColdFusion MX 6.1
ColdFusion MX 6.1
Added in this ColdFusion
TagAttribute or value
release
cfimportAllColdFusion MX
cfinvokeAllColdFusion MX
cfinvokeargumentAllColdFusion MX
cfloginAllColdFusion MX
cfloginuserAllColdFusion MX
cflogoutAllColdFusion MX
cfmail
cfmailparam
spoolEnable attributeColdFusion MX
charset attributeColdFusion MX 6.1
failto attributeColdFusion MX 6.1
replyTo attributeColdFusion MX 6.1
userName attributeColdFusion MX 6.1
password attributeColdFusion MX 6.1
wrapText attributeColdFusion MX 6.1
type attributeColdFusion MX 6.1
cfmailpartAllColdFusion MX 6.1
cfobjectAllColdFusion MX
cfobjectcacheAllColdFusion MX
cfprocessingdirective
pageEncoding attributeColdFusion MX
cfpropertyAllColdFusion MX
cfreturnAllColdFusion MX
cfsetting
requestTimeOut attributeColdFusion MX
cfthrow
cftraceAllColdFusion MX
cfxmlAllColdFusion MX
object attributeColdFusion MX
Tag changes since ColdFusion 543
Deprecated tags, attributes, and values
The following tags, attributes, and attribute values are deprecated. Do not use them in
ColdFusion applications. They might not work, and might cause an error, in releases later than
ColdFusion MX.
Deprecated as of this ColdFusion
TagAttribute or value
release
cfcache
cffile
cfgraph
cfgraphdata
cfgridupdate
cfindex
cfinsert
timeout
attributes
attributes attribute value system ColdFusion MX
attributes attribute value temporary ColdFusion MX
attributeColdFusion MX
attribute value archive ColdFusion MX
AllColdFusion MX
AllColdFusion MX
connectString
dbName attributeColdFusion MX
dbServer attributeColdFusion MX
dbType attribute ColdFusion MX
provider attribute ColdFusion MX
providerDSN attribute ColdFusion MX
external
connectString
dbName attributeColdFusion MX
attribute ColdFusion MX
attributeColdFusion MX
attributeColdFusion MX
cfldap
cflog
dbServer attributeColdFusion MX
dbType attribute ColdFusion MX
provider attribute ColdFusion MX
providerDSN attribute ColdFusion MX
filterConfig
filterFile attributeColdFusion MX
date
attribute value "No"ColdFusion MX
thread attribute value "No"ColdFusion MX
time attribute value "No"ColdFusion MX
attributeColdFusion MX
44Chapter 2: ColdFusion Tags
TagAttribute or value
Deprecated as of this ColdFusion
release
cfquery
cfregistry
cfsearch
cfservlet
cfservletparam
cfslider
connectString
dbName attributeColdFusion MX
dbServer attributeColdFusion MX
The following
•
dynamic
• ODBC
attributeColdFusion MX
dbType attribute values:
ColdFusion MX
(The value
query is valid.)
• Oracle73
• Oracle80
• Sybase11
• OLEDB
• DB2
provider attribute ColdFusion MX
providerDSN attribute ColdFusion MX
sql attributeColdFusion MX
All, on UNIX only ColdFusion MX
external
attributeColdFusion MX
AllColdFusion MX
AllColdFusion MX
img
attributeColdFusion MX
cfstoredproc
cfupdate
imgStyle attributeColdFusion MX
grooveColor attributeColdFusion MX
connectString
dbName attributeColdFusion MX
dbServer attributeColdFusion MX
provider attribute ColdFusion MX
providerDSN attribute ColdFusion MX
connectString
dbName attributeColdFusion MX
dbServer attributeColdFusion MX
provider attribute ColdFusion MX
providerDSN attribute ColdFusion MX
attributeColdFusion MX
attributeColdFusion MX
Tag changes since ColdFusion 545
Obsolete tags, attributes, and values
The following tags, attributes, and attribute values are obsolete. Do not use them in ColdFusion
applications. They do not work, and might cause an error, in releases later than ColdFusion 5.
Obsolete as of this ColdFusion
TagAttribute or value
release
cfauthenticate
cfimpersonate
cfindex
cfinternaladminsecurity
cfnewinternaladminsecurity
cfsetting
AllColdFusion MX
AllColdFusion MX
action
attribute value optimizeColdFusion MX
AllColdFusion MX
This tag did not appear in CFML Reference.
AllColdFusion MX
This tag did not appear in CFML Reference.
catchExceptionsByPattern
ColdFusion MX
attribute
46Chapter 2: ColdFusion Tags
cfabort
Description
Stops the processing of a ColdFusion page at the tag location. ColdFusion returns everything that
was processed before the tag. The tag is often used with conditional logic to stop processing a
page when a condition occurs.
showErrorOptionalError to display, in a standard ColdFusion error page, when tag
executes.
Usage
When you use the cfabort and cferror tags together, the cfabort tag halts processing
immediately; the
cferror tag redirects output to a specified page.
If this tag does not contain a
and ColdFusion returns the page contents up to the line that contains the
When you use this tag with the
cferror, page processing stops when the cfabort tag is reached. The message in showError
showError attribute value, processing stops when the tag is reached
cfabort tag.
showError attribute, but do not define an error page using
displays to the client.
When you use this tag with the
ColdFusion redirects output to the error page specified in the
Example
<!--- this example shows the use of cfabort to stop processing.
In the second example, where cfabort is used, the result never displays --->
<h3>Example A: Let the instruction complete itself</h3>
<!--- first, set a variable --->
<cfset myVariable = 3>
<!--- now, perform a loop that increments this value --->
<cfloop from = "1" to = "4" index = "Counter">
<cfset myVariable = myVariable + 1>
</cfloop>
<cfoutput>
<p>The value of myVariable after incrementing through the loop #Counter# times
is:
#myVariable#
</cfoutput>
showError attribute and an error page using cferror,
cferror tag.
<h3>Example B: Use cfabort to halt the instruction</h3>
cfabort47
<!--- reset the variable and show the use of cfabort --->
<cfset myVariable = 3>
<!--- now, perform a loop that increments this value --->
<cfloop from = "1" to = "4" index = "Counter">
<!--- on the second time through the loop, cfabort --->
<cfif Counter is 2>
<cfabort>
<!--- processing is stopped, and subsequent operations are not carried out
• Removed the requirement that you use this tag within a cfform tag.
• Changed the behavior when this tag is used within a cfform tag; if the method attribute is
defined in the Administrator, the return value of the applet’s method is incorporated into the
form.
Attributes
AttributeReq/Opt DefaultDescription
appletSource RequiredName of registered applet
nameRequiredForm variable name for applet
heightOptionalHeight of applet, in pixel
widthOptionalWidth of applet, in pixels
vSpaceOptionalSpace above and below applet, in pixels
hSpaceOptionalSpace on left and right of applet, in pixels
cfapplet49
AttributeReq/Opt DefaultDescription
alignOptionalAlignment:
• Left
• Right
• Bottom
• Top
• TextTop
• Middle
• AbsMiddle
• Baseline
• AbsBottom
notSupported OptionalSee
Description
param_nOptionalRegistered parameter for applet. Specify only to override
Usage
Text to display if a page that contains a Java applet-based
cfform control is opened by a browser that does not support
Java or has Java support disabled. For example:
notSupported = "<b>Browser must support Java to view
ColdFusion Java Applets</b>"
Default:
<b>Browser must support Java to<br> view ColdFusion Java
Applets!</b>
values for applet in ColdFusion Administrator.
You can specify the applet method attribute only in the Administrator, Java Applets view. For
other attributes, you can accept the default values in the Administrator view, or specify values in
this tag and override the defaults.
If Java applet components are stored in a JAR file, enter the filename in the ColdFusion
Administrator, Java Applets window, Archive text box.
Example
<p>cfapplet lets you reference custom Java applets that have been
registered using the ColdFusion Administrator.
<p>To register a Java applet, open the ColdFusion Administrator and
click "Applets" link under "extensions" section.
<p>This example applet copies text that you type into a form. Type
some text, and then click "copy" to see the copied text.
<cfform action = "index.cfm">
<cfapplet appletsource = "copytext" name = "copytext">
</cfform>
50Chapter 2: ColdFusion Tags
cfapplication
Description
Defines the scope of a ColdFusion application; enables and disables storage of Client variables;
specifies the Client variable storage mechanism; enables Session variables; and sets Application
variable timeouts.
Category
Application framework tags
Syntax
<cfapplication
name = "application_name"
loginStorage = "cookie" or "session"
clientManagement = "Yes" or "No"
clientStorage = "datasource_name" or "Registry" or "Cookie"
setClientCookies = "Yes" or "No"
sessionManagement = "Yes" or "No"
sessionTimeout = #CreateTimeSpan(days, hours, minutes, seconds)#
applicationTimeout = #CreateTimeSpan(days, hours, minutes, seconds)#
setDomainCookies = "Yes" or "No">
See also
cfassociate, cferror, cflock, cfmodule
History
ColdFusion MX 6.1: Added loginStorage attribute
ColdFusion MX:
• Changed how persistent scopes are available: Server, Session, and Application scope variables
are stored in memory as structures. In earlier releases, only Session and Application scope
variables were stored this way. You cannot access the UDF function scope as a structure.
• Changed the algorithm for setting the CFTOKEN variable value: if the registry key
UUIDToken is a non-zero value, ColdFusion uses a number constructed from the UUID plus
a random number. Otherwise, ColdFusion sets the CFTOKEN variable default value using a
positive random integer. (In earlier releases, ColdFusion always used a number constructed
from the UUID plus a random number.)
Attributes
AttributeReq/OptDefaultDescription
nameSee
Description
loginStorageOptionalcookie• cookie: store login information in the Cookie
Name of application. Up to 64 characters.
For Application and Session variables:
Required.
For Client variables: Optional
scope
• session: store login information in the
Session scope
clientStorageOptionalregistryHow client variables are stored:
• datasource_name: in ODBC or native data
source. You must create storage repository
in the Administrator.
• registry: in the system registry.
• cookie: on client computer in a cookie.
Scalable. If client disables cookies in the
browser, client variables do not work.
setClientCookiesOptionalYes• Yes: enables client cookies
• No: ColdFusion does not automatically send
CFID and CFTOKEN cookies to client
browser; you must manually code CFID and
CFTOKEN on the URL for every page that
uses Session or Client variables.
setDomainCookiesOptionalNo• Yes: Sets CFID and CFTOKEN cookies for a
Usage
Lifespan of session variables.
CreateTimeSpan function and values in days,
hours, minutes, and seconds, separated by
commas.
Lifespan of application variables.
CreateTimeSpan function and values in days,
hours, minutes, and seconds, separated by
commas.
domain (not a host). Required, for
applications running on clusters.
• No
This tag is typically used in the Application.cfm file, to set defaults for a ColdFusion application.
This tag enables application variables, unless they are disabled in the ColdFusion Administrator.
The Administrator setting also overrides the
sessionManagement attribute. For more
information, see Configuring and Administering ColdFusion MX.
Server, application, and session variables
When you display, set, or update variables in the server, application, and session scopes, use the
cflock tag with the scope attribute set to the following value:
• For server variables, specify "server"
• For application variables, specify "application"
• For session variables, specify "session"
For information about locking scopes, see
If ColdFusion is running on a cluster, you must specify
source name; you cannot specify "registry".
52Chapter 2: ColdFusion Tags
cflock on page 221.
clientStorage = "cookie" or a data
If you use this tag to activate the Application and Client scopes, ColdFusion saves the application
name as a key, whose maximum length is 64 characters. If an application name is longer than this,
the client store fails during database processing.
Note: The CFTOKEN variable is 8 bytes in length. Its range is 10000000 —99999999.If you
specify ClientStorage=cookie, any Client scope variables set following a cfflush tag are not
saved in the Client browser.
Example
<!--- This example shows how to use cflock to guarantee consistent data
updates to variables in Application, Server, and Session scopes. --->
<h3>cfapplication Example</h3>
<p>cfapplication defines scoping for a ColdFusion application and
enables or disables the storing of application and/or sessionvariables.
This tag is placed in a special file calledApplication.cfm that is run
before any other CF page in a directory where the Application.cfm file
appears.
<cfapplication name = "ETurtle"
sessionTimeout = #CreateTimeSpan(0, 0, 0, 60)#
sessionManagement = "Yes">
<!--- Initialize session and application variables used by E-Turtleneck.
Use session scope for session variables. --->
<cflock scope = "Session" timeout = "30" type = "Exclusive">
<cfif NOT IsDefined("session.size")>
<cfset session.size = "">
</cfif>
<cfif NOT IsDefined("session.color")>
<cfset session.color = "">
</cfif>
</cflock>
<!--- Use the application scope for the application variable. This variable
keeps track of total number of turtlenecks sold. --->
<cflock scope = "Application" timeout = "30" type = "Exclusive">
type Optional anyString; a type name; data type of the argument.
• any
• array
• binary
• boolean
• date
• guid – The argument must be a UUID or GUID of the form
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where each x is a
character representing a hexadecimal number (0-9A-F).
• numeric
• query
• string
• struct
• uuid – The argument must be a ColdFusion UUID of the
form xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx where each x is a
character representing a hexadecimal number (0-9A-F).
• variableName: a string formatted according to ColdFusion
variable naming conventions.
• a component name – If the type attribute value is not one of
the preceding items, ColdFusion treats it as the name of a
ColdFusion component. When The function executes, it
generates an error if the argument that is passed in is not a
CFC with the specified name.
54Chapter 2: ColdFusion Tags
AttributeReq/Opt DefaultDescription
requiredOptionalnoWhether the parameter is required to execute the component
method.
• yes (the parameter is not required if you specify a
attribute.)
• no
defaultOptionalIf no argument is passed, specifies a default argument value.
default
displayname Optionalname
attribute
value
hintOptionalMeaningful only for CFC method parameters. Text to be
Usage
Meaningful only for CFC method parameters. A value to be
displayed when using introspection to show information about
the CFC.
displayed when using introspection to show information about
the CFC. The
attribute value in the parameter description line. This attribute
can be useful for describing the purpose of the parameter.
hint attribute value follows the displayname
This tag must be in a cffunction tag, before any other tags in the cffunction tag body.
Arguments that are passed when a method is invoked can be accessed from the method body in
the following ways:
• With shorthand syntax: #myargument#
(This example accesses the argument myargument.)
• Using the arguments scope as an array: #arguments[1]#
(This example accesses the first defined argument in the cffunction)
• Using the arguments scope as a struct: #arguments.myargument#
(This example accesses the argument myargument in the array)
Example
<!--- This example defines a function that takes a course number parameter
and returns the course description. --->
<cffunction name="getDescript">
<!--- Identify argument --->
<cfargument name="Course_Number" type="numeric" required="true">
<!--- Use the argument to get a course description from the database --->
<cfquery name="Description" datasource="cfsnippets">
SELECT Descript
FROM Courses
WHERE Number = '#Course_Number#'
</cfquery>
<!--- Specify the variable that the function returns --->
<cfreturn Description.Descript>
</cffunction>
cfargument55
cfassociate
Description
Allows subtag data to be saved with a base tag. Applies only to custom tags.
dataCollectionOptionalAssocAttribsStructure in which base tag stores subtag data
Usage
Call this tag within a subtag, to save subtag data in the base tag.
When ColdFusion passes subtag attributes back to the base tag, it saves them in a structure whose
default name is
multiple subtags), specify a structure name, in the
AssocAttribs. To segregate subtag attributes (in a base tag that can have
dataCollection attribute. The structure is
appended to an array whose name is thistag.collectionName.
Within the custom tag code, the attributes passed to the tag by using the
attributeCollection
attribute are saved as independent values, with no indication that they are grouped into a
structure by the custom tag’s caller. Therefore, in the called tag, if you assign a value to a specific
attribute, it replaces the value passed in the
attributeCollection attribute that you used when
calling the subtag.
Example
<!--- Find the context --->
<cfif thisTag.executionMode is "start">
<!--- Associate attributes --->
<cfassociate baseTag = "CF_TAGBASE">
<!--- Define defaults for attributes --->
<cfparam name = "attributes.happy" default = "Yes">
<cfparam name = "attributes.sad" default = "No">
...
56Chapter 2: ColdFusion Tags
cfauthenticate
Description
This tag is obsolete. Use the newer security tools; see “Authentication functions” on page 367 and
Chapter 16, “Securing Applications,” in Developing ColdFusion MX Applications.
History
ColdFusion MX: this tag is obsolete. It does not work in ColdFusion MX and later releases.
<!--- This shows the use of cfbreak to exit a loop when a condition is met --->
<!--- select courses; use cfloop to find a condition; then break the loop --->
<!--- check that number is numeric --->
<cfif IsDefined("form.number")>
ORDER by Course_Number
</cfquery>
<p> This example uses CFLOOP to cycle through a query to find a value.
(In our example, a list of values corresponding to courses in the Snippets
datasource). When the conditions of the query are met, CFBREAK stops the loop.
<p> Please enter a Course Number, and hit the "submit" button:
<form action="index.cfm" method="POST">
Stores a copy of a page on the server and/or client computer, to improve page rendering
performance. To do this, the tag creates temporary files that contain the static HTML returned
from a ColdFusion page.
Use this tag if it is not necessary to get dynamic content each time a user accesses a page.
You can use this tag for simple URLs and for URLs that contain URL parameters.
• Deprecated the timeout and cachedirectory attributes. They might not work, and might
cause an error, in later releases.
• Added the timespan attribute.
• Changed how pages are cached: the default action attribute value, cache, caches a page on
the server and the client. (In earlier releases, this option cached a page only on the server.)
• Changed the source of the protocol and port values: the default protocol and port values
are now taken from the current page URL. (In earlier releases, they were
respectively.)
"http"and "80",
• Changed how session state is handled when caching a page: this tag can cache pages that
depend on session state, including pages that are secured with a ColdFusion login. (In earlier
releases, the session state was cleared when caching the page, causing authentication to be lost.)
• Changed how files are cached: this tag uses a hash() of the URL for the filename to cache a file.
(In earlier releases, ColdFusion used the cfcache.map file.)
cfcache59
Attributes
AttributeReq/OptDefaultDescription
actionOptionalcache• cache: server-side and client-side caching.
• flush: refresh cached page(s).
• clientcache: browser-side caching only. To cache a
personalized page, use this option.
• servercache: server-side caching only. Not
recommended.
• optimal: same as "cache".
directoryOptionalcf_root/cache Absolute path of cache directory.
timespanOptionalPage is
flushed only
when
cfcache
action =
"flush"
executed
expireURLOptionalFlush all
cached pages
usernameOptionalA username. Provide this if the page requires
passwordOptionalA password. Provide this if the page requires
portOptionalThe current
page port
protocolOptionalThe current
page protocol
is
The interval until the page is flushed from the cache.
• A decimal number of days. For example:
- ".25", for one-fourth day (6 hours)
- "1", for one day
- "1.5", for one and one half days
• A return value from the CreateTimeSpan function.
For example:
"#CreateTimeSpan(0, 6, 0, 0)#"
Used with action = "flush". A URL reference.
ColdFusion matches it against the mappings in the
specified cache directory. Can include wildcards. For
example:
authentication at the web server level.
authentication at the web server level.
Port number of the web server from which the URL is
requested. In the internal call from
ColdFusion resolves each URL variable in the page;
this ensures that links in the page remain functional.
Protocol that is used to create URL from cache.
• http://
• https://
"*/view.cfm?id=*".
cfcache to cfhttp,
Usage
Use this tag in pages whose content is not updated frequently. Taking this action can greatly
improve the performance of your application.
The output of a cached page is stored in a file on the client browser and/or the ColdFusion server.
Instead of regenerating and redownloading the output of the page, each time it is requested,
ColdFusion uses the cached output. ColdFusion regenerates and downloads the page only when
the cache is flushed, as specified by the
action=flush
.
To enable a simple form of caching, put a cfcache tag, specifying the timespan attribute, at the
top of a page. Each time the specified time span passes, ColdFusion flushes (deletes) the copy of
the page from the cache and caches a new copy for users to access.
60Chapter 2: ColdFusion Tags
timespan attribute, or by invoking cfcache
You can specify client-side caching or a combination of client-side and server-side caching (the
default), using the action attribute. The advantage of client-side caching is that it requires no
ColdFusion resources; the browser stores pages in its own cache, improving performance. The
advantage of combination caching is that it optimizes server performance; if the browser does not
have a cache of the page, the server can get data from its own cache. (Macromedia recommends
that you do not use server-side only caching. Macromedia recommends that you use combination
caching.)
If a page contains personalized content, use the
action = "clientcache" option to avoid the
possibility of caching a personalized copy of a page for other users.
Debug settings have no effect on
generating a cached file,
cfcache uses cfsetting showDebugOutput = "No".
cfcache unless the application page enables debugging. When
The cfcache tag evaluates each unique URL, including URL parameters, as a distinct page, for
caching purposes. For example, the output of http://server/view.cfm?id=1 and the output of
http://server/view.cfm?id=2 are cached separately.
The
cfcache tag uses the cfhttp tag to get the contents of a page to cache. If there is an HTTP
error accessing the page, the contents are not cached. If a ColdFusion error occurs, the error is
cached.
Example
<!--- This example produces as many cached files as there are
URL parameter permutations. --->
<cfcache
timespan="#createTimeSpan(0,0,10,0)#">
<body>
<h3>This is a test of some simple output</h3>
<cfparam name = "URL.x" default = "no URL parm passed" >
<cfoutput>The value of URL.x = # URL.x #</cfoutput>
cfcache61
cfcase
Description
Used only inside the cfswitch tag body. Contains code to execute when the expression specified
in the
Category
Flow-control tags
Syntax
<cfcase
See also
cfdefaultcase, cfswitch
Attributes
cfswitch tag has one or more specific values.
value = "value or delimited set of values"
delimiters = "delimiter characters"
>
AttributeReq/OptDefaultDescription
valueRequiredThe value or values that the
cfswitch tag must match. To specify multiple matching
values, separate the values with the
character. The value or values must be simple
constants or constant expressions, not variables.
delimiterOptional, (comma)Specifies the delimiter character or characters that
separate multiple values to match. If you specify
multiple delimiter characters, you can use any of them
to separate the values to be matched.
Usage
expression attribute of the
delimiter
The contents of the cfcase tag body executes only if the expression attribute of the cfswitch
tag evaluates to a value specified by the
value attribute. The contents of the cfcase tag body can
include HTML and text, and CFML tags, functions, variables, and expressions. You do not have
to explicitly break out of the
One
cfcase tag can match multiple expression values. To do this, separate the matching values
cfcase tag, as you do in some languages.
with the delimiter character, which is the comma by default. For example the following line
matches "red", "blue", or "green":
<cfcase value="red,blue,green">
You can use the delimiter attribute to specify one or more delimiters to use in place of the
comma. For example, the following line matches "cargo, live", "cargo, liquid", and "cargo, solid":
<!--- The following example displays a grade based on a 1-10 score.
Several of the cfcase tags match more than one score.
For simplicity, the example sets the score to 7 --->
<cfset score="7">
<cfswitch expression="#score#">
<cfcase value="10">
<cfset grade="A">
62Chapter 2: ColdFusion Tags
</cfcase>
<cfcase value="9;8" delimiters=";">
<cfset grade="B">
</cfcase>
<cfcase value="7;6" delimiters=";">
<cfset grade="C">
</cfcase>
<cfcase value="5;4;" delimiters=";">
<cfset grade="D">
</cfcase>
<cfdefaultcase>
<cfset grade="F">
</cfdefaultcase>
</cfswitch>
<cfoutput>
Your grade is #grade#
</cfoutput>
cfcase63
cfcatch
Description
Used inside a cftry tag. Together, they catch and process exceptions in ColdFusion pages.
Exceptions are events that disrupt the normal flow of instructions in a ColdFusion page, such as
failed database operations, missing include files, and developer-specified events.
Category
Exception handling tags
Syntax
<cfcatch type = "exceptiontype">
Exception processing code here
</cfcatch>
See also
cftry, cferror, cfrethrow, cfthrow,
Chapter 14, “Handling Errors,” in Developing
ColdFusion MX Applications
History
ColdFusion MX:
• Changed SQLSTATE value behavior: the SQLSTATE return value in a cfcatch tag depends
on the database driver type:
■ Type 1 (JDBC-ODBC bridge): the value is the same as in ColdFusion 5
■ Type 4 (100% Java, no native methods): the value might be different
If your application depends on SQLSTATE values for flow control, the application might
produce unexpected behavior with ColdFusion MX.
• Changed the behavior of this tag when type="any": it is not necessary, when you include a
cfcatch tag with type="any", to do so in the last cfcatch tag in the block, to ensure that all
other tests are executed before it. ColdFusion finds the best-match
cfcatch block.
• Changed the behavior of the cfscript tag: it includes try and catch statements that are
equivalent to the
cftry and cfcatch tags.
• Changed object modification: you cannot modify the object returned by cfcatch.
• Changed thrown exceptions: the cfcollection, cfindex, and cfsearch tags can throw the
SEARCHENGINE exception. In earlier releases, an error in processing these tags threw only
You must code at least one cfcatch tag within a cftry block. Put cfcatch tags at the end of a
cftry block. ColdFusion MX tests cfcatch tags in the order in which they appear. This tag
requires an end tag.
If
type="any", ColdFusion MX catches exceptions from any CFML tag, data source, or external
object. To get the exception type use code such as the following:
#cfcatch.type#
Applications can use the cfthrow tag to throw developer-defined exceptions. Catch these
exceptions with any of these
type options:
• "custom_type"
• "Application"
• "Any"
The custom_type type is a developer-defined type specified in a cfthrow tag. If you define a
custom type as a series of strings concatenated by periods (for example,
"
MyApp.BusinessRuleException.InvalidAccount"), ColdFusion MX can catch the custom
type by its character pattern. ColdFusion MX searches for a
a matching exception type, starting with the most specific (the entire string), and ending with the
least specific.
For example, you could define a type as follows:
<cfthrow type = "MyApp.BusinessRuleException.InvalidAccount">
If you have the following cfcatch tag, it will handle the exception:
<cfcatch type = "MyApp.BusinessRuleException.InvalidAccount">
Otherwise, if you have the following cfcatch tag, it will handle the exception:
<cfcatch type = "MyApp.BusinessRuleException">
Finally, if you have the following cfcatch tag, it will handle the exception:
cfcatch tag in the cftry block with
<cfcatch type = "MyApp">
You can code cfcatch tags in any order to catch a custom exception type.
If you specify
the
Application type in the cfthrow tag that defines them.
type = "Application", the cfcatch tag catches only custom exceptions that have
cfcatch65
The cfinclude, cfmodule, and cferror tags throw an exception of type = "template".
An exception that is thrown within a
immediately encloses the
with the
The
cfrethrow tag.
cfcatch variables provide the following exception information:
cfcatch tag. However, you can rethrow the currently active exception
cfcatch block cannot be handled by the cftry block that
cfcatch variableContent
cfcatch.type
cfcatch.message
Type: Exception type, as specified in cfcatch.
Message: Exception's diagnostic message, if provided;
otherwise, an empty string; in the cfcatch.message variable
cfcatch.detail
Detailed message from the CFML interpreter or specified in
a
cfthrow tag. When the exception is generated by
ColdFusion (and not
cfthrow), the message can contain
HTML formatting and can help determine which tag threw
the exception.
cfcatch.tagcontext
An array of tag context structures, each representing one
level of the active tag context at the time of the exception.
cfcatch.NativeErrorCode
Applies to type= "database". Native error code associated
with exception. Database drivers typically provide error
codes to diagnose failing database operations. Default: -1.
cfcatch.SQLState
Applies to type="database". SQLState associated with
exception. Database drivers typically provide error codes to
help diagnose failing database operations. Default: -1.
cfcatch.Sql
cfcatch.queryError
cfcatch.where
cfcatch.ErrNumber
cfcatch.MissingFileName
cfcatch.LockName
cfcatch.LockOperation
cfcatch.ErrorCode
cfcatch.ExtendedInfo
Applies to type ="database". The SQL statement sent to
the data source.
Applies to type="database". The error message as
reported by the database driver.
Applies to type="database". If the query uses the
cfqueryparam tag, query parameter name-value pairs.
Applies to type="expression". Internal expression error
number.
Applies to type="missingInclude". Name of file that could
not be included.
Applies to type="lock". Name of affected lock (if the lock is
unnamed, the value is
"anonymous").
Applies to type="lock". Operation that failed (Timeout,
Create Mutex, or Unknown).
Applies to type="custom". String error code.
Applies to type="application" and "custom". Custom error
message; information that the default exception handler
does not display.
66Chapter 2: ColdFusion Tags
Advanced Exception types
You can specify the following advanced exception types in the type attribute:
<!--- cftry example, using TagContext to display the tag stack. --->
<h3>cftry Example</h3>
<!--- open a cftry block --->
<cftry>
<!--- note misspelled tablename "employees" as "employeeas" --->
<cfquery name = "TestQuery" dataSource = "cfsnippets">
SELECT *
FROM EMPLOYEEAS
</cfquery>
<!--- <p>... other processing goes here --->
<!--- specify the type of error for which we search --->
<cfcatch type = "Database">
<!--- the message to display --->
<h3>You've Thrown a Database <b>Error</b></h3>
<cfoutput>
<!--- and the diagnostic message from the ColdFusion server --->
<p>#cfcatch.message#</p>
<p>Caught an exception, type = #CFCATCH.TYPE# </p>
68Chapter 2: ColdFusion Tags
</cfoutput>
</cfcatch>
</cftry>
<p>The contents of the tag stack are:</p>
<cfloop index = i from = 1
to = #ArrayLen(CFCATCH.TAGCONTEXT)#>
<cfset sCurrent = #CFCATCH.TAGCONTEXT[i]#>
<br>#i# #sCurrent["ID"]#
(#sCurrent["LINE"]#,#sCurrent["COLUMN"]#)
#sCurrent["TEMPLATE"]#
</cfloop>
cfcatch69
cfchart
Description
Generates and displays a chart.
Category
Data output tags, Extensibility tags
Syntax
<cfchart
format = "flash, jpg, png"
chartHeight = "integer number of pixels"
chartWidth = "integer number of pixels"
scaleFrom = "integer minimum value"
scaleTo = "integer maximum value"
showXGridlines = "yes" or "no"
showYGridlines = "yes" or "no"
gridlines = "integer number of lines"
seriesPlacement = "default, cluster, stacked, percent"
foregroundColor = "Hex value or Web color"
dataBackgroundColor = "Hex value or Web color"
showBorder = "yes" or "no"
font = "font name"
fontSize = "integer font size"
fontBold = "yes" or "no"
fontItalic = "yes" or "no"
labelFormat = "number, currency, percent, date"
xAxisTitle = "title text"
yAxisTitle = "title text"
xAxisType = "scale or category"
yAxisType = "scale or category"
sortXAxis = "yes/no"
show3D = "yes" or "no"
xOffset = "number between -1 and 1"
yOffset = "number between -1 and 1"
rotated = "yes/no"
showLegend = "yes/no"
tipStyle = "MouseDown, MouseOver, none"
tipBGColor = "hex value or web color"
showMarkers = "yes" or "no"
markerSize = "integer number of pixels"
pieSliceStyle = "solid, sliced"
url = "onClick destination page"
name = "String"
</cfchart>
See also
cfchartdata, cfchartseries
History
ColdFusion MX 6.1:
• Added the xAxisType and yAxisType attributes.
• Changed interpolation behavior: the tag now interpolates data points on line charts with
multiple series.
ColdFusion MX: Added this tag.
70Chapter 2: ColdFusion Tags
Attributes
AttributeReq/OptDefaultDescription
formatflashFile format in which to save graph.
• flash
• jpg
• png
chartHeight240Chart height; integer number of pixels
chartWidth320Chart width; integer number of pixels
scaleFromDetermined by
Y-axis minimum value; integer.
data
scaleToDetermined by
Y-axis maximum value; integer
data
showXGridlinesno• yes: display X-axis gridlines
• no: hide X-axis gridlines
showYGridlinesyes• yes: display Y-axis gridlines
• no: hide Y-axis gridlines
gridlines10, including
top and bottom
Number of grid lines to display on value axis,
including axis; positive integer.
seriesPlacementdefault Applies to charts that have more than one
data series. Relative positions of series.
• default: ColdFusion determines relative
positions, based on graph types
• cluster
• stacked
• percent
foregroundColorblackColor of text, gridlines, and labels.
Hex value or supported named color; see
name list in the Usage section.
For a hex value, use the form
"##xxxxxx",
where x = 0-9 or A-F; use two pound signs or
none.
dataBackgroundColorwhiteColor of area around chart data.
showBorderno• yes
fontarial Name of text font
Hex value or supported named color; see
name list in the Usage section.
For a hex value, use the form
"##xxxxxx",
where x = 0-9 or A-F; use two pound signs or
none.
• no
• arial
• times
• courier
• arialunicodeMS. This option is required, if
you are using a double-byte character set
on UNIX, or using a double-byte character
set on Windows with a file type of Flash.
cfchart71
AttributeReq/OptDefaultDescription
fontSize11Font size; integer
fontBoldno• yes
• no
fontItalicno• Yes
• No
labelFormatnumberFormat for Y-axis labels.
• number
• currency
• percent
• date
xAxisTitletext; X-axis title
yAxisTitletext; Y-axis title
xAxisTypecategory• category The axis indicates the data
category. Data is sorted according to the
sortXAxis attribute.
• scale The axis is numeric. All
item attribute values must numeric. The X
cfchartdata
axis is automatically sorted numerically.
yAxisTypecategoryCurrently has no effect, as Y axis is always
used for data values. Valid values are
category and scale
sortXAxisno• yes: display column labels in alphabetic
order along X-axis
• no
Ignored if
xAxisType attribute is scale.
show3Dno• yes: display chart with three-dimensional
appearance
• no
xOffset0.1Applies if
show3D="yes". Number of units by
which to display the chart as angled,
horizontally.
• A number in the range -1 – 1, where "-1"
specifies 90 degrees left and "1" specifies
90 degrees right
yOffset0.1 Applies if
show3D="yes". Number of units by
which to display the chart as angled,
vertically.
• A number in the range -1 – 1, where "-1"
specifies 90 degrees down, and "1"
specifies 90 degrees up
rotatedno• yes: rotate chart 90 degrees. For a
horizontal bar chart, use this option.
• no
showLegendyes• yes: if chart contains more than one data
series, display legend
• no
72Chapter 2: ColdFusion Tags
AttributeReq/OptDefaultDescription
tipStylemouseOverDetermines the action that opens a popup
window to display information about the
current chart element.
• mouseDown: displays if the user positions
the cursor at the element and clicks the
mouse down. Applies only to Flash format
graph file. (For other formats, this option
functions the same as
mouseOver.)
• mouseOver: displays if the user positions
the cursor at the element
• none: suppresses display
tipbgcolorwhiteApplies only to Flash format graph file.
Hex value or supported named color; see
name list in the Usage section.
For a hex value, use the form
"##xxxxxx",
where x = 0-9 or A-F; use two pound signs or
none.
showMarkersyes Applies to
line, curve and scatter.
chartseries type attribute values
• yes: display markers at data points
• no
markerSize(Automatic)Size of data point marker. in pixels. Integer.
pieSliceStyleslicedApplies to
pie.
chartseries type attribute value
• solid: displays pie as if unsliced
• sliced: displays pie as if sliced
urlURL to open if the user clicks item in a data
series; the onClick destination page.
You can specify variables within the URL
string; ColdFusion passes current values of
the variables.
•
$VALUE$: value of selected row. If none,
value is empty string.
•
$ITEMLABEL$: label of selected item. If none,
value is empty string.
•
$SERIESLABEL$: label of selected series. If
none, value is empty string.
For example:
“somepage.cfm?item=$ITEMLABEL$&series=$
SERIESLABEL$&value=$VALUE$”
• "javascript:...": executes a client-side script
namePage variable name. String. Generates the
Usage
The cfchart tag defines a container in which a graph displays: its height, width, background
color, labels, and so on. The
pie, and so on. The
cfchartdata tag defines a data point.
the graph as binary data and assigns it to the
specified variable. Suppresses chart display.
You can use the
name value in the cffile tag
to write the chart to a file.
cfchartseries tag defines the style in which data displays: bar, line,
cfchart73
Data is passed to the cfchartseries tag in the following ways:
• As a query
• As data points, using the cfchartdata tag
For the
font attribute value "ArialUnicodeMS", the following rules apply:
• On Windows: to permit Flash charts (type = "flash") to render double-byte character set,
you must select this value
• On UNIX: for all type values, to render a double-byte character set, you must select this value.
• If this value is selected, the fontboldandfontitalic attributes have no effect
The color attributes accept the following W3C HTML 4 named color value or hex values:
Color nameRGB value
Black #000000
Green##008000
Silver##C0C0C0
Lime##00FF00
Gray##808080
Olive ##808000
White##FFFFFF
Yellow##FFFF00
Maroon##800000
Navy##000080
Red##FF0000
Blue##0000FF
Purple##800080
Teal##008080
Fuchsia##FF00FF
Aqua##00FFFF
For all other color values, you must enter the hex value.
For more color names that are supported by popular browsers, see www.w3.org/TR/css3-color
Flash does not conform fully to UNIX X11 naming conventions.
You can specify whether charts are cached in memory, the number of charts to cache, and the
number of chart requests that ColdFusion can process concurrently. To set these options: in the
ColdFusion Administrator, select Server Settings > Charting.
74Chapter 2: ColdFusion Tags
cfchartdata
Description
Used with the cfchart and cfchartseriestags. This tag defines chart data points. Its data is
submitted to the
Category
Data output tags, Extensibility tags
Syntax
<cfchartdata
item = "text"
value = "number">
See also
cfchart, cfchartseries
History
ColdFusion MX: Added this tag.
Attributes
AttributeReq/OptDefaultDescription
itemstring; data point name
cfchartseries tag.
valuenumber or expression; data point value
cfchartdata75
cfchartseries
Description
Used with the cfchart tag. This tag defines the style in which chart data displays: bar, line, pie,
and so on.
Category
Data output tags, Extensibility tags
Syntax
<cfchartseries
type="type"
query="queryName"
itemColumn="queryColumn"
valueColumn="queryColumn"
seriesLabel="Label Text"
seriesColor="Hex value or Web color"
paintStyle="plain, raise, shade, light"
markerStyle="style"
colorlist = "list">
</cfchartseries>
See also
cfchart, cfchartdata
History
ColdFusion MX 6.1: Changed interpolation behavior: the tag now interpolates data points on
line charts with multiple series.
ColdFusion MX: Added this tag.
Attributes
AttributeReq/OptDefaultDescription
typeRequiredSets the chart display style:
• bar
• line
• pyramid
• area
• cone
• curve
• cylinder
• step
• scatter
• pie
queryOptionalName of ColdFusion query from which to get data.
itemColumnRequired if
query
attribute is
specified
valueColumnRequired if
query
attribute is
specified
Name of a column in the query specified in the
attribute; contains the item label for a data point to
graph.
Name of a column in the query specified in the
attribute; contains data values to graph.
query
query
76Chapter 2: ColdFusion Tags
AttributeReq/OptDefaultDescription
seriesLabelOptionalText of data series label
seriesColorOptionalColor of the main element (such as the bars) of a chart.
For a pie chart, the color of the first slice.
Hex value or supported named color; see name list in
the
cfchart Usage section.
For a hex value, use the form
or A-F; use two pound signs or none.
paintStyleOptionalplainSets the paint display style of the data series.
• plain: solid color
• raise: the appearance of a button
• shade: gradient fill, darker at the edges
• light: a lighter shade of color; gradient fill
"##xxxxxx", where x = 0-9
markerStyleOptionalrectangleApplies to
and
Sets the icon that marks a data point:
• rectangle
• triangle
• diamond
• circle
• letter
• mcross
• snow
• rcross
colorlistOptionalApplies if
slice colors.
Comma-delimited list of hex values or supported,
named web colors; see name list in the
section.
For a hex value, use the form
or A-F; use two pound signs or none.
Usage
chartseries type attribute values line, curve
scatter, and show3Dattribute valueno.
chartseries type attribute = "pie". Sets pie
cfchart Usage
"##xxxxxx", where x = 0-9
If a chart has multiple line series, ColdFusion interpolates missing data points in the common X
axis range. For example, if one series has data points at 0, 10, and 20 on the X axis and a second
series has data points at 0, 20, and 30, ColdFusion calculates and displays a data point for X=10
on the second series line, but it does not calculate an X=30 value for the first series.
For a pie chart, ColdFusion sets pie slice colors as follows:
• If the seriesColor attribute is omitted, ColdFusion automatically colors the slices
• If the seriesColor attribute is specified, ColdFusion automatically colors the slices after the
first one, starting with the specified color for the first slice
• If the colorList attribute is specified, ColdFusion colors the slices after the first one,
according to the list
ColdFusion Generates an error if you use more than 16
chartseries tags in one cfchart tag.
cfchartseries77
cfcol
Description
Defines table column header, width, alignment, and text. Used within a cftable tag.
Category
Data output tags
Syntax
<cfcol
header = "column_header_text"
width = "number_indicating_width_of_column"
align = "Left" or "Right" or "Center"
text = "column_text">
See also
cfcontent, cfoutput, cftable
History
ColdFusion MX: Added the ability to construct dynamic cfcol statements.
AttributeReq/OptDefaultDescription
headerRequiredColumn header text. To use this attribute, you must also use the
cftable colHeaders attribute.
widthOptional20Column width. If the length of data displayed exceeds this value,
data is truncated to fit. To avoid this, use an HTML
If the surrounding
width specifies the percent of the table width and it does not
truncate text; otherwise,
characters.
alignOptionalLeftColumn alignment
• Left
• Right
• Center
textRequiredDouble-quotation mark-delimited text; determines what to
display. Rules: same as for
hyperlinks, image references, and input controls.
Usage
cftable tag includes the htmltable attribute,
width specifies the number of
cfoutput sections. You can embed
table tag.
At least one cfcol tag is required within the cftable tag. You must put cfcol and cftable tags
adjacent in a page. The only tag that you can nest within the cftable tag is the cfcol tag. You
cannot nest
To di s pl a y th e
colHeader attribute. If you specify either attribute without the other, the header does not display.
cftable tags.
cfcol header text, you must specify the cfcol header and the cftable
No error is thrown.
Example
<!--- This example shows the use of cfcol and cftable to align
information returned from a query --->
<!--- query selects information from cfsnippets data source --->
<cfquery name = "GetEmployees" dataSource = "cfsnippets">
SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
78Chapter 2: ColdFusion Tags
FROM Employees
</cfquery>
<html>
<body>
<h3>cfcol Example</h3>
<!--- Uses the HTMLTable attribute to display cftable as an HTML
table, rather than PRE formatted information --->
<cftable
query = "GetEmployees"
startRow = "1" colSpacing = "3"
HTMLTable colheaders>
<!--- each cfcol tag sets the width of a column in the table,
the header information and the text/CFML for the cell --->
• Changed the requirements for the action attribute: it is now required.
• Added the action attribute list value. It is the default.
• Changed the requirements for the action attribute value map: it is not necessary to specify the
action attribute value map. (ColdFusion detects collections and creates maps collections as
required.)
• Changed acceptable collection naming: this tag accepts collection names that include spaces.
• Changed Verity operations behavior: ColdFusion supports Verity operations on Acrobat PDF
files.
• Changed thrown exceptions: this tag can throw the SEARCHENGINE exception.
80Chapter 2: ColdFusion Tags
Attributes
Attribute Req/OptDefaultDescription
actionRequired; see
Usage section
collection See Usage
section
pathSee Usage
section
languageSee Usage
section
list• create: registers the collection with ColdFusion.
- If the collection is present: creates a map to it
- If the collection is not present: creates it
• repair: fixes data corruption in a collection.
• delete: unregisters a collection.
- If the collection was registered with
deletes its directories
- If the collection was registered and mapped: does not
delete collection directories
• map: creates a map to the collection. It is not necessary
to specify this value. (ColdFusion maps collections
automatically.)
• optimize: optimizes the structure and contents of the
collection for searching; recovers space.
• list: returns a query result set, named from the
attribute value, of the attributes of the collections that are
registered by ColdFusion and K2 Server.
• A collection name. The name can include spaces.
Absolute path to a Verity collection.
To map an existing collection, specify a fully-qualified path
to the collection (not including the collection name). For
example,
EnglishOptions are listed in Usage section. Requires the
appropriate (European or Asian) Verity Locales language
pack.
"C:\MyCollections\"
action = create:
name
nameSee Usage
section
Usage
Name for the query results returned by the
list action.
With this tag you can create, register a Verity collection and administer a collection that was
created by ColdFusion or by a Verity application.
The following table shows the dependence relationships among this tag’s attribute values:
Specifying this attribute
is required, optional or
unnecessary (blank):
collection
path
language
name
If more than instance of the
simultaneously, use the
For this action attribute value:
listcreatemapoptimizerepairdelete
RequiredRequired Required RequiredRequired
RequiredOptional
OptionalOptional
Required
cfcollection tag might access or modify a collection
cflock tag to protect the collection from attempts at simultaneous
operations.
To register a collection with K2Server, you update the k2server.ini file.
cfcollection81
Before you attempt to delete or purge a collection that is also opened by the K2Server, you must
stop the K2Server. If you do not, some files may be open, and ColdFusion might not complete
the action.
The
list action returns the following information in a result set that contains one row per
collection:
ColumnContents
EXTERNAL• Yes: the collection is external
• No: the collection is not external
• Not Found: the collection is registered but is not available in the defined path
LANGUAGEThe locale setting of the collection.
This information is not available for K2Server collections.
MAPPED• Yes: the collection is mapped
• No: the collection is not mapped
This information is not available for K2Server collections.
NAME• For a ColdFusion registered collection: its name
• For a K2Server registered collection: its alias, defined in the k2server.ini file.
(ColdFusion saves registered K2Server collection information; it is available
regardless of whether the K2Server is running)
ONLINE• Yes: the collection can be searched
• No: the collection cannot be searched
If EXTERNAL = "Not Found", this value is "No".
PATH Absolute path to the collection. If the collection is mapped or is registered by a
K2Server, the path includes the collection name.
REGISTERED• CF: collection is registered by ColdFusion
• K2: collection is registered by K2Server
The ColdFusion MX Administrator Verity > Collections page displays the information that is
returned when you use the
If the K2 Server is not running when the
list attribute.
list action is executed, the result set returned contains
K2Server information that was current when the server became unavailable.
To determine whether a collection exists, use code such as the following, to execute a query of
queries:
<!------------------------------------------------------------------------Check for server platform and use it’s default Verity Collection directory.
You may need to change the path if you did not install ColdFusion MX in the
default directory.
<option value="Create">Create this collection
<option value="Optimize">Optimize this collection
<option value="Repair">Repair this collection
<option value="Delete">Delete this collection
</select>
<p><strong>Collection on which to act</strong><br>
Use the default value or enter your own Collection name<br>
<input type="Text" name="CollectionName" value="snippets"></p>
<input type="Submit" name="" value="alter or create my collection">
</form>
84Chapter 2: ColdFusion Tags
cfcomponent
Description
Creates and defines a component object; encloses functionality that you build in CFML and
enclose within
methods. Code within the body of this tag, other than
cffunction tags. This tag contains one or more cffunction tags that define
cffunction tags, is executed when the
component is instantiated.
A component file has the extension CFC and is stored in any directory of an application.
A component method is invoked in the following ways:
• Within the cfinvoke tag in a ColdFusion page
• Within a URL that calls a CFC file and passes a method name as a URL parameter
• Within the cfscript tag
• As a web service
• From Flash code
Category
Extensibility tags
Syntax
<cfcomponent
extends ="anotherComponent"
output = "yes" or "no"
displayname = "text string">
hint = "text string">
Chapter 11, “Building and Using ColdFusion Components,” in Developing
ColdFusion MX Applications
cfcomponent85
Attributes
AttributeReq/OptDefaultDescription
extendsOptionalName of parent component from which to inherit methods
and properties.
outputOptionalComponent
body
displayable
text is
processed
as standard
CFML
displayname Optionalname
attribute
value
hintOptionalText to be displayed when using introspection to show
Usage
Specifies whether constructor code in the component can
generate HTML output; does not affect output in the body
of
cffunction tags in the component.
• yes: Constructor code is processed as if it were within a
cfoutput tag. Variable names surrounded by number
signs (#) are automatically replaced with their values.
• no: Constructor code is processed as if it were within a
cfsilent tag.
• If you do not specify this attribute, constructor code is
processed as standard CFML. Any variables must be in
cfoutput tags.
A string to be displayed when using introspection to show
information about the CFC. The information appears on the
heading, following the component name.
information about the CFC. The hint attribute value
appears below the component name heading. This attribute
can be useful for describing the purpose of the parameter.
If you specify the extends attribute, the data and methods of the parent component are available
to any as if they were parts of the current component. If the managerCFC component extends the
employeeCFC component, and the employeeCFC component has a getEmployeeName method,
you can call this method using the managerCFC, as follows:
SELECT FIRSTNAME, LASTNAME, EMAIL
FROM tblEmployees
</cfquery>
<cfreturn empQuery>
</cffunction>
<cffunction name="getDept">
<cfquery
name="deptQuery" datasource="ExampleApps" >
SELECT *
FROM tblDepartments
</cfquery>
<cfreturn deptQuery>
</cffunction>
</cfcomponent>
86Chapter 2: ColdFusion Tags
cfcontent
Description
Does either or both of the following:
• Sets the MIME content encoding header for the current page
• Sends the contents of a file from the server as the page output
Note: This tag executes only if it is enabled in the ColdFusion Administrator. For more information,
see Configuring and Administering ColdFusion MX.
Category
Data output tags
Syntax
<cfcontent
type = "file_type"
deleteFile = "Yes" or "No"
file = "filename"
reset = "Yes" or "No">starting with a drive letter and a colon, or a forward
or backward slash
See also
cfcol, cfheader, cfhttp, cfoutput, cftable
cfcontent87
Attributes
AttributeReq/OptDefaultDescription
typeOptional The MIME content type of the page, optionally followed by a
semicolon and the character encoding. By default, ColdFusion
sends pages as text/html content type in the UTF-8 character
encoding.
The content type determines how the browser or client
interprets the page contents.
The following are some of the content type values you can use
include:
• text/html
• text/plain
• application/x-shockwave-flash
• application/msword
• image/jpeg
The following list includes commonly used character encoding
values:
• utf-8
• iso-8859-1
• windows-1252
• us-ascii
• shift_jis
• iso-2022-jp
• euc-jp
• euc-kr
• big5
• euc-cn
• utf-16
For example:
type = "text/html"
type = "text/html; charset=ISO-8859-1"
deleteFileOptionalNoApplies only if you specify a file with the
file attribute.
• Yes: deletes the file on the server after sending its contents to
the client.
• No: leaves the file on the server.
fileOptionalName of file whose contents will be the page output. When
using ColdFusion in a distributed configuration, the
file
attribute must refer to a path on the system on which the web
server runs. When you use this attribute, any other output on
the current CFML page is ignored; only the contents of the file
is sent to the client.
resetOptionalYesThe
reset and file attributes are mutually exclusive. If you
specify a file, this attribute has no effect.
• Yes: discards output that precedes call to
cfcontent
• No: preserves output that precedes call to cfcontent. In this
case all output is sent with the specified type.
88Chapter 2: ColdFusion Tags
Usage
To set the character encoding (character set) of generated output, use code such as the following:
<cfcontent type="text/html; charset=ISO-8859-1">
When ColdFusion processes an HTTP request, it determines the character encoding of the data
returned in the HTTP response. By default, ColdFusion returns character data using the Unicode
UTF-8 format (regardless of the value of an HTML
cfcontent tag to override the default character encoding of the response. For example, to specify
the character encoding of the page output as Japanese EUC, use the
<cfcontent type="text/html; charset=EUC-JP">
meta tag in the page). You can use the
type attribute, as follows:
If you call the cfcontent tag from a custom tag, and you do not want the tag to discard the
current page when it is called from another application or custom tag, set
reset = "no".
If a file delete operation is unsuccessful, ColdFusion throws an error.
If you use this tag after the
cfflush tag on a page, ColdFusion throws an error. The following tag
can force most browsers to display a dialog that asks users whether they want to save the contents
of the file specified by the
cfcontent tag as a with the filename specified by the filename value.
For many file types, such as Excel documents, that Internet Explorer can display directly in the
browser, the browser displays the file without asking users whether to save it if you use a
For more information on character encodings, see the following web pages:
• www.w3.org/International/O-charset.html provides general information on character
encodings and the web, and has several useful links.
• www.iana.org/assignments/character-sets is a complete list of character sets names used on the
Internet, maintained by the Internet Assigned Numbers Authority.
• java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html lists the character encodings that
Java, and therefore ColdFusion, can interpret. This list uses Java internal names, not the IANA
character encoding names that you use in the
ColdFusion attributes and parameters.
For a complete list of media types used on the Internet, see
www.iana.org/assignments/media-types/.
SetEncoding charset parameter and other
Example
<!--- This example shows the use of cfcontent to return the contents of the CF
Documentation page dynamically to the browser.
You might need to change the path and/or drive letter depending on how
ColdFusion is installed on your system.
Notice that the graphics do not display and the hyperlinks do not work,
because the html page uses relative filename references.
The root of the reference is the ColdFusion page, not the location of the
html page.
• Changed the expires attribute: it now accepts a date time object.
• Cookie names can include all ASCII characters except commas, semicolons, or whitespace
characters.
Attributes
Attribute Req/OptDefaultDescription
nameRequiredName of cookie variable. ColdFusion converts cookie names to
all-uppercase. Cookie names set using this tag can include any
printable ASCII characters except commas, semicolons or white
space characters.
valueOptionalValue to assign to cookie variable. Must be a string or variable that
can be stored as a string.
expiresOptionalExpiration of cookie variable.
• The default: the cookie expires when the user closes the
browser, that is, the cookie is "session only".
• A date or date/time object (for example, 10/09/97)
• A number of days (for example, 10, or 100)
• now: deletes cookie from client cookie.txt file (but does not
delete the corresponding variable the Cookie scope of the
active page).
• never: The cookie expires in 30 years from the time it was
created (effectively never in web years).
secureOptionalIf browser does not support Secure Sockets Layer (SSL)
security, the cookie is not sent. To use the cookie, the page must
be accessed using the https protocol.
• Yes: variable must be transmitted securely
• No
cfcookie91
Attribute Req/OptDefaultDescription
pathOptionalURL, within a domain, to which the cookie applies; typically a
directory. Only pages in this path can use the cookie. By default,
all pages on the server that set the cookie can access the cookie.
path = "/services/login"
To specify multiple URLs, use multiple
If you specify path, you must also specify
cfcookie tags.
domain.
domainRequired if
path
attribute is
specified.
Optional
otherwise
Usage
Domain in which cookie is valid and to which cookie content can
be sent from the user’s system. By default, the cookie is only
available to the server that set it. Use this attribute to make the
cookie available to other servers.
Must start with a period. If the value is a subdomain, the valid
domain is all domain names that end with this string. This attribute
sets the available subdomains on the site upon which the cookie
can be used.
For a
domain value that ends in a country code, the specification
must contain at least three periods; for example,
".mongo.state.us". For top-level domains, two periods are
required; for example,
You cannot use an IP address as a domain.
".mgm.com".
If this tag specifies that a cookie is to be saved beyond the current browser session, the client
browser writes or updates the cookie in its local cookies file. Until the browser is closed, the
cookie resides in browser memory. If the
expires attribute is not specified, the cookie is not
written to the browser cookies file.
If you use this tag after the
cfflush tag on a page, ColdFusion does not send the cookie to the
browser; however, the value you set is available to ColdFusion in the Cookie scope during the
browser session.
Note: You can also create a cookie that expires when the current browser session expires by using
the cfset tag or a CFScript assignment statement to set a variable in the Cookie scope, as in <cfset Cookie.mycookie="sugar">. To get a cookie’s value, refer to the cookie name in the Cookie
scope, as in <cfif Cookie.mycookie="oatmeal">.
You can use dots in cookie names, as the following examples show:
To access cookies, including cookies that you set and all cookies that are sent by the client, use the
Cookie scope. For example, to display the value of the person.name cookie set in the preceding
code, use the following line:
<cfoutput>#cookie.person.name#</cfoutput>
Example
<!--- This example shows how to set/delete a cfcookie variable --->
<!--- Select users who have entered comments into sample database --->
<cfquery name = "GetAolUser" dataSource = "cfsnippets">
SELECT EMail, FromUser, Subject, Posted
FROM Comments
</cfquery>
<html>
<body>
<h3>cfcookie Example</h3>
92Chapter 2: ColdFusion Tags
<!--- if the URL variable delcookie exists, set cookie expiration date to NOW
--->
<cfif IsDefined("url.delcookie") is True>
<cfcookie name = "TimeVisited"
value = "#Now()#"
expires = "NOW">
<cfelse>
<!--- Otherwise, loop through list of visitors; stop when you match
the string aol.com in a visitor’s e-mail address --->
<cfloop query = "GetAolUser">
<cfif FindNoCase("aol.com", Email, 1) is not 0>
<cfcookie name = "LastAOLVisitor"
value = "#Email#"
expires = "NOW" >
</cfif>
</cfloop>
<!--- If the timeVisited cookie is not set, set a value --->
<cfif IsDefined("Cookie.TimeVisited") is False>
<cfcookie name = "TimeVisited"
value = "#Now()#"
expires = "10">
</cfif>
</cfif>
<!--- show the most recent cookie set --->
<cfif IsDefined("Cookie.LastAOLVisitor") is "True">
<p>The last AOL visitor to view this site was
<cfoutput>#Cookie.LastAOLVisitor#</cfoutput>, on
<cfoutput>#DateFormat(COOKIE.TimeVisited)#</cfoutput>
<!--- use this link to reset the cookies --->
<p><a href = "cfcookie.cfm?delcookie = yes">Hide my tracks</A>
<cfelse>
<p>No AOL Visitors have viewed the site lately.
</cfif>
cfcookie93
cfdefaultcase
Description
Used only inside the cfswitch tag body. Contains code to execute when the expression specified
in the
Category
Flow-control tags
Syntax
<cfdefaultcase>
See also
cfcase, cfswitch
History
ColdFusion MX: Changed placement requirements: this tag does not have to follow all cfcase
tags in the
Usage
The contents of the cfdefaultcase tag body is executes if the expression attribute of the
cfswitch tag does not match any of the values specified by the cfcase tags in the cfswitch tag
body. The contents of the
tags, functions, variables, and expressions.
cfswitch tag does not match a of the value specified by a cfcase tag.
cfswitch tag body.
cfdefaultcase tag body can include HTML and text, and CFML
You can specify only one
cfdefaultcase tag at any position within a cfswitch statement; it is not required to be the last
cfdefaultcase tag within a cfswitch tag. You can put the
item, but it is good programming practice to put it last.
Example
<!--- The following example displays a grade based on a 1-10 score.
Several of the cfcase tags match more than one score.
For simplicity, the example sets the score to 7 --->
<cfset score="7">
<cfswitch expression="#score#">
<cfcase value="10">
<cfset grade="A">
</cfcase>
<cfcase value="9;8" delimiters=";">
<cfset grade="B">
</cfcase>
<cfcase value="7;6" delimiters=";">
<cfset grade="C">
</cfcase>
<cfcase value="5;4;" delimiters=";">
<cfset grade="D">
</cfcase>
<cfdefaultcase>
<cfset grade="F">
</cfdefaultcase>
</cfswitch>
<cfoutput>
Your grade is #grade#
</cfoutput>
94Chapter 2: ColdFusion Tags
cfdirectory
Description
Manages interactions with directories.
Category
File management tags
Syntax
<cfdirectory
action = "directory action"
directory = "directory name"
name = "query name"
filter = "list filter"
mode = "permission"
sort = "sort specification"
newDirectory = "new directory name">
See also
cffile
History
ColdFusion MX:
• Changed behavior for action = "list":
■ On Windows, cfdirectoryaction = "list" no longer returns the directory entries "."
(dot) or
■ On Windows, cfdirectoryaction = "list" no longer returns the values of the Archive
and System attributes.
■ On UNIX and Linux, cfdirectoryaction = "list" does not return any information in
the
".." (dot dot), which represent "the current directory" and "the parent directory."
mode column.
Attributes
AttributeReq/OptDefaultDescription
actionOptionalList• list: returns a query record set of the files in the
specified directory. The directory entries "." (dot) and
".." (dot dot), which represent the current directory and
the parent directory, are not returned.
• create
• delete
• rename
directoryRequiredAbsolute pathname of directory against which to
perform action.
nameRequired if
action =
"list"
filterOptional if
action =
"list"
Name for output record set.
File extension filter applied to returned names. For
example: *.cfm. One filter can be applied.
cfdirectory95
AttributeReq/OptDefaultDescription
modeOptionalUsed with
only to UNIX and Linux. Octal values of chmod
command. Assigned to owner, group, and other,
respectively. For example:
• 644: Assigns read/write permission to owner; read
permission to group and other
• 777: Assigns read/write/execute permission to all
sortOptional; used
if
action =
"list"
newDirectory Required if
action =
"rename"
Usage
Note: For this tag execute, it must be enabled in the ColdFusion Administrator. For more information,
see Configuring and Administering ColdFusion MX.
ASCQuery column(s) by which to sort directory listing.
Delimited list of columns from query output.
To qualify a column, use:
• ac: ascending (a to z) sort order
• desc: descending (z to a) sort order
For example:
sort = "dirname ASC, file2 DESC, size,
datelastmodified"
New name for directory
action = "create". Permissions. Applies
If you put ColdFusion applications on a server that is used by multiple customers, you must
consider the security of files and directories that could be uploaded or otherwise manipulated
with this tag by unauthorized users. For more information about securing ColdFusion tags, see
Configuring and Administering ColdFusion MX.
If
action = "list", cfdirectory returns these result columns, which you can reference in a
cfoutput tag:
• name: directory entry name. The entries "." and ".." are not returned.
• size: directory entry size
• type: file type: File, for a file; Dir, for a directory
• dateLastModified: the date that an entry was last modified
• attributes: file attributes, if applicable
• mode: Empty column; retained for backward compatibility with ColdFusion 5 applications on
UNIX.
You can use the following result columns in standard CFML expressions, preceding the result
column name with the query name:
Note: If the cfdirectory tag does not appear to work, for example, if a list operation returns an
empty result set, make sure that you have correct permissions to access the directory. For example, if
you run ColdFusion as a service on Windows, it operates by default as System, and cannot access
directories on a remote system or mapped drive; to resolve this issue, do not run ColdFusion using
the local system account.
The filter attribute specifies a pattern of one or more characters. All names that match that
pattern are included in the list. On Windows systems, pattern matching ignores text case, on
UNIX and Linux, pattern matches are case-sensitive.
The following 2 characters have special meaning in the pattern and are called metacharacters:
• *matches any zero or more characters
• ?matches any single character
The following table shows examples of patterns and file names that they match:
PatternMatches
foo.*any file called foo with any extention i.e. foo.html, foo.cfm, foo.xml, ...
*.htmlall files with the suffix .html, but not files with the suffix .htm.
??all files with 2 character names.
Example
<h3>cfdirectory Example</h3>
<!--- use cfdirectory to give the contents of the directory that contains
sort="name ASC, size DESC">
<!---- Output the contents of the cfdirectory as a cftable ----->
<cftable
query="myDirectory"
htmltable
colheaders>
<cfcol
header="NAME:"
text="#Name#">
<cfcol
header="SIZE:"
text="#Size#">
</cftable>
cfdirectory97
cfdump
Description
Outputs the elements, variables and values of most kinds of ColdFusion objects. Useful for
debugging. You can display the contents of simple and complex variables, objects, components,
user-defined functions, and other elements.