Adobe Langref Cold Fusion MX 6.1 CFML Reference Cfmx61 Ref

User Manual: adobe ColdFusion - MX 6.1 - CFML Reference Free User Guide for Adobe ColdFusion Software, Manual

Open the PDF directly: View PDF PDF.
Page Count: 806

DownloadAdobe Langref Cold Fusion - MX 6.1 CFML Reference Cfmx61 Ref
Open PDF In BrowserView PDF
CFML Reference

Trademarks
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.
Copyright © 1999–2003 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced,
translated, or converted to any electronic or machine-readable form in whole or in part without prior written approval of
Macromedia, Inc.
Part Number ZCF61M700
Acknowledgments
Project Management: Randy Nielsen
Writing: Hal Lichtin, Randy Nielsen
Editing: Linda Adler, Noreen Maher

First Edition: May 2002
Second Edition: August 2003
Macromedia, Inc.
600 Townsend St.
San Francisco, CA 94103

CONTENTS

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
About Macromedia ColdFusion MX documentation . . . . . . . . . . . . . . . . . . . . . . 17
Documentation set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Viewing online documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

INTRODUCTION

CHAPTER 1: Reserved Words and Variables

. . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Reserved words in forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Reserved words in queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Scope-specific built-in variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Variable scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Caller scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Client variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Server variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Application and session variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Custom tag variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Request variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Form variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
ColdFusion tag-specific variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
ColdFusion query variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
CFCATCH variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
CFDIRECTORY variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
CFERROR variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
CFFILE ACTION=Upload variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CFFTP error variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CFFTP ReturnValue variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CFFTP query object columns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
CFHTTP variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
CFLDAP variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
CFPOP variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
CFQUERY and CFSTOREDPROC variables . . . . . . . . . . . . . . . . . . . . . . . . . 28
CFREGISTRY variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
CFSEARCH variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Standard CGI variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Request. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

3

CGI environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Testing for CGI variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CGI server variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CGI client variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CGI client certificate variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 2: ColdFusion Tags

29
29
30
31
31

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

Tags by function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Application framework tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Database manipulation tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Data output tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Debugging tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Exception handling tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Extensibility tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
File management tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Flow-control tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Forms tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Internet Protocol tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Page processing tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Variable manipulation tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Other tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Tag changes since ColdFusion 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
New tags, attributes, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Deprecated tags, attributes, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Obsolete tags, attributes, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
cfabort. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
cfapplet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
cfapplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
cfargument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
cfassociate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
cfauthenticate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
cfbreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
cfcache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
cfcase. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
cfcatch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
cfchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
cfchartdata. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
cfchartseries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
cfcol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
cfcollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
cfcomponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
cfcontent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
cfcookie. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
cfdefaultcase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
cfdirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
cfdump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
cfelse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
cfelseif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
cferror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

4

Contents

cfexecute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
cfexit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
cffile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
cffile action = "append" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
cffile action = "copy" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
cffile action = "delete". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
cffile action = "move" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
cffile action = "read" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
cffile action = "readBinary". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
cffile action = "rename" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
cffile action = "upload". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
cffile action = "write" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
cfflush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
cfform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
cfftp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
cfftp: Opening and closing FTP server connections. . . . . . . . . . . . . . . . . . . . . . . 138
cfftp: Connection: File and directory operations . . . . . . . . . . . . . . . . . . . . . . . . . 141
cfftp action = "listDir" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
cffunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
cfgraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
cfgraphdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
cfgrid. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
How data is returned from cfgrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Using the href attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
cfgridcolumn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
cfgridrow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
cfgridupdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
cfheader. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
cfhtmlhead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
cfhttp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
cfhttpparam. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
cfif. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
cfimpersonate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
cfimport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
cfinclude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
cfindex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
cfinput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
cfinsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
cfinvoke. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
cfinvokeargument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
cfldap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
cflocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
cflock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
cflog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
cflogin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
cfloginuser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
cflogout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
cfloop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
cfloop: index loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
cfloop: conditional loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Contents

5

cfloop: looping over a query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
cfloop: looping over a list or file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
cfloop: looping over a COM collection or structure . . . . . . . . . . . . . . . . . . . . 239
cfmail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
cfmailparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
cfmailpart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
cfmodule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
cfobject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
cfobject: COM object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
cfobject: component object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
cfobject: CORBA object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
cfobject: Java or EJB object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
cfobject: web service object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
cfobjectcache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
cfoutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
cfparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
cfpop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
cfprocessingdirective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
cfprocparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
cfprocresult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
cfproperty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
cfquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
cfqueryparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
cfregistry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
cfregistry action = "getAll" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
cfregistry action = "get" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
cfregistry action = "set". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
cfregistry action = "delete" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
cfreport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
cfrethrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
cfreturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
cfsavecontent. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
cfschedule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
cfscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
cfsearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
cfselect. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
cfservlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
cfservletparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
cfset. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
cfsetting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
cfsilent. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
cfslider. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
cfstoredproc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
cfswitch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
cftable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
cftextinput. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
cfthrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
cftrace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
cftransaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
cftree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345

6

Contents

cftreeitem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cftry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cfupdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cfwddx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cfxml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 3: ColdFusion Functions

349
353
355
358
361

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

Functions by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Array functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Authentication functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Date and time functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Decision functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Display and formatting functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Dynamic evaluation functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Extensibility functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Full-text search functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
International functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
List functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Other functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Query functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
String functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Structure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
System functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
XML functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Function changes since ColdFusion 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
New functions, parameters, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Deprecated functions, parameters, and values . . . . . . . . . . . . . . . . . . . . . . . . . 373
Obsolete functions, parameters, and values. . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
ACos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
ArrayAppend. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
ArrayAvg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
ArrayClear. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
ArrayDeleteAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
ArrayInsertAt. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
ArrayIsEmpty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
ArrayLen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
ArrayMax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
ArrayMin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
ArrayNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
ArrayPrepend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
ArrayResize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
ArraySet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
ArraySort. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
ArraySum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
ArraySwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
ArrayToList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394

Contents

7

Asc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
ASin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Atn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
AuthenticatedContext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
AuthenticatedUser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
BitAnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
BitMaskClear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
BitMaskRead. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
BitMaskSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
BitNot. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
BitOr. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
BitSHLN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
BitSHRN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
BitXor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Ceiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Chr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
CJustify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
CompareNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
CreateDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
CreateDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
CreateObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
CreateObject object types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
CreateObject: COM object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
CreateObject: component object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
CreateObject: CORBA object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
CreateObject: Java or EJB object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
CreateObject: web service object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
CreateODBCDate. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
CreateODBCDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
CreateODBCTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
CreateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
CreateTimeSpan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
CreateUUID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
DateAdd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
DateCompare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
DateConvert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
DateDiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
DateFormat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
DatePart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
Day . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
DayOfWeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
DayOfWeekAsString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
DayOfYear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
DaysInMonth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
DaysInYear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
DE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
DecimalFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
DecrementValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461

8

Contents

Decrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
DeleteClientVariable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
DirectoryExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
DollarFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Duplicate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
Encrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Evaluate. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
Exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
ExpandPath. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
FileExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
FindNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
FindOneOf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
FirstDayOfMonth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
Fix. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
FormatBaseN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
GetAuthUser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
GetBaseTagData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
GetBaseTagList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
GetBaseTemplatePath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
GetClientVariablesList. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
GetCurrentTemplatePath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
GetDirectoryFromPath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
GetEncoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
GetException . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
GetFileFromPath. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
GetFunctionList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
GetHttpRequestData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
GetHttpTimeString. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
GetK2ServerDocCount. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
GetK2ServerDocCountLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
GetLocale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
GetMetaData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
GetMetricData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
GetPageContext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
GetProfileSections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
GetProfileString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
GetTempDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
GetTempFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
GetTemplatePath. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
GetTickCount. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
GetTimeZoneInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
GetToken . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
Hash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
Hour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
HTMLCodeFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
HTMLEditFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
IIf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
IncrementValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
InputBaseN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521

Contents

9

Insert. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
IsArray. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
IsAuthenticated . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
IsAuthorized . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
IsBinary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
IsBoolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
IsCustomFunction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
IsDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
IsDebugMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
IsDefined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
IsK2ServerABroker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
IsK2ServerDocCountExceeded . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
IsK2ServerOnline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
IsLeapYear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
IsNumeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
IsNumericDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
IsObject. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
IsProtected. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
IsQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
IsSimpleValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
IsStruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
IsUserInRole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
IsWDDX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
IsXmlDoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
IsXmlElem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
IsXmlRoot. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
JavaCast. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
JSStringFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
LCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
Left . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
Len . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
ListAppend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
ListChangeDelims. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
ListContains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
ListContainsNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
ListDeleteAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
ListFind. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
ListFindNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
ListFirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
ListGetAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
ListInsertAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
ListLast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
ListLen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
ListPrepend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
ListQualify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
ListRest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
ListSetAt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
ListSort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
ListToArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589

10

Contents

ListValueCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
ListValueCountNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
LJustify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Log10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
LSCurrencyFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
LSDateFormat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
LSEuroCurrencyFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
LSIsCurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
LSIsDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
LSIsNumeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
LSNumberFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
LSParseCurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
LSParseDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
LSParseEuroCurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
LSParseNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
LSTimeFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
LTrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Max. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Mid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Min. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
Minute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Month. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
MonthAsString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Now . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
NumberFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
ParagraphFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
ParameterExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
ParseDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
PreserveSingleQuotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
Quarter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
QueryAddColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
QueryAddRow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
QueryNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
QuerySetCell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
QuotedValueList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
Rand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
Randomize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
RandRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
REFind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
REFindNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
ReleaseComObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
RemoveChars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
RepeatString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
ReplaceList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
ReplaceNoCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
REReplace. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
REReplaceNoCase. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666

Contents

11

Reverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
Right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
RJustify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
Round . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
RTrim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
Second . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
SetEncoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
SetLocale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
SetProfileString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
SetVariable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
Sgn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
Sin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
SpanExcluding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
SpanIncluding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
Sqr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
StripCR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
StructAppend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
StructClear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
StructCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
StructCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
StructDelete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
StructFind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
StructFindKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
StructFindValue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
StructGet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
StructInsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
StructIsEmpty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
StructKeyArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708
StructKeyExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
StructKeyList. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
StructNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
StructSort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
StructUpdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716
Tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
TimeFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
ToBase64. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
ToBinary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
ToString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
Trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
UCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728
URLDecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
URLEncodedFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
URLSessionFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
Val. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734
ValueList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
Week . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
Wrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
WriteOutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738
XmlChildPos. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
XmlElemNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740

12

Contents

XmlFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XmlNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XmlParse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XmlSearch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XmlTransform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
YesNoFormat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 4: ColdFusion C++ CFX Reference

741
742
744
745
746
747
748

. . . . . . . . . . . . . . . . . . . . . . . . . . 749

C++ class overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
Deprecated class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
CCFXException class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
Class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
CCFXException::GetError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
CCFXException::GetDiagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
CCFXQuery class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
Class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
CCFXQuery::AddRow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
CCFXQuery::GetColumns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
CCFXQuery::GetData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
CCFXQuery::GetName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
CCFXQuery::GetRowCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
CCFXQuery::SetData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
CCFXRequest class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
Class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
CCFXRequest::AddQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
CCFXRequest::AttributeExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
CCFXRequest::CreateStringSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
CCFXRequest::Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
CCFXRequest::GetAttribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
CCFXRequest::GetAttributeList. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
CCFXRequest::GetCustomData. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
CCFXRequest::GetQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
CCFXRequest::ReThrowException . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
CCFXRequest::SetCustomData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
CCFXRequest::SetVariable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764
CCFXRequest::ThrowException . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764
CCFXRequest::Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
CCFXRequest::WriteDebug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
CCFXStringSet class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
Class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
CCFXStringSet::AddString. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
CCFXStringSet::GetCount. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
CCFXStringSet::GetIndexForString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
CCFXStringSet::GetString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767

Contents

13

CHAPTER 5: ColdFusion Java CFX Reference

. . . . . . . . . . . . . . . . . . . . . . . . . 769

Overview class libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
CustomTag interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
processRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
Query interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
addRow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
getColumnIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
getColumns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
getData. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
getName. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
getRowCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
setData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
Request interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
attributeExists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
getAttribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
getAttributeList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
getIntAttribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
getQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
getSetting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
Response interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
addQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
setVariable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
writeDebug. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
Debugging classes reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
DebugRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
DebugResponse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
DebugQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
CHAPTER 6: WDDX JavaScript Objects

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787

JavaScript object overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
WddxSerializer object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
serialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
serializeVariable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
serializeValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
WddxRecordset object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
addColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
addRows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 794
getField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
getRowCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796

14

Contents

setField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
wddxSerialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
CHAPTER 7: ColdFusion ActionScript Functions . . . .

. . . . . . . . . . . . . . . . . . . . 799

CF.query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800
CF.http . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801

Contents

15

16

Contents

INTRODUCTION

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:
Book

Description

Installing and Using
ColdFusion MX

Describes system installation and basic configuration for Windows, Solaris,
Linux, and HP-UX.

Configuring and
Administering
ColdFusion MX

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.

Developing ColdFusion Describes how to develop your dynamic web applications, including
MX Applications
retrieving and updating your data, using structures, and forms.
Getting Started
Building ColdFusion
MX Applications

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.

CFML Reference

Provides descriptions, syntax, usage, and code examples for all ColdFusion
tags, functions, and variables.

CFML Quick Reference A brief guide that shows the syntax of ColdFusion tags, functions, and
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.

18

Introduction

CHAPTER 1
Reserved Words and Variables

This chapter provides information on ColdFusion reserved words and lists scope variables.
Contents
Reserved words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Scope-specific built-in variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
ColdFusion tag-specific variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
CGI environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

19

Reserved words
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.
ABSOLUTE

ACTION

ADD

ALL

ALLOCATE

ALTER

AND

ANY

ARE

AS

ASC

ASSERTION

AT

AUTHORIZATION AVG

BEGIN

BETWEEN

BIT

BIT_LENGTH

BOTH

BY

CASCADE

CASCADED

CASE

CAST

CATALOG

CHAR

CHARACTER

CHARACTER_
LENGTH

CHAR_LENGTH

CHECK

CLOSE

COALESCE

COLLATE

COLLATION

20

Chapter 1: Reserved Words and Variables

COLUMN

COMMIT

CONNECT

CONNECTION

CONSTRAINT

CONSTRAINTS

CONTINUE

CONVERT

CORRESPON
DING

COUNT

CREATE

CROSS

CURRENT

CURRENT_DATE

CURRENT_TIME

CURRENT_TIME
STAMP

CURRENT_USER

CURSOR

DATE

DAY

DEALLOCATE

DEC

DECIMAL

DECLARE

DEFAULT

DEFERRABLE

DEFERRED

DELETE

DESC

DESCRIBE

DESCRIPTOR

DIAGNOSTICS

DISCONNECT

DISTINCT

DOMAIN

DOUBLE

DROP

ELSE

END

END-EXEC

ESCAPE

EXCEPT

EXCEPTION

EXEC

EXECUTE

EXISTS

EXTERNAL

EXTRACT

FALSE

FETCH

FIRST

FLOAT

FOR

FOREIGN

FOUND

FROM

FULL

GET

GLOBAL

GO

GOTO

GRANT

GROUP

HAVING

HOUR

IDENTITY

IMMEDIATE

IN

INDICATOR

INITIALLY

INNER

INPUT

INSENSITIVE

INSERT

INT

INTEGER

INTERSECT

INTERVAL

INTO

IS

ISOLATION

JOIN

KEY

LANGUAGE

LAST

LEADING

LEFT

LEVEL

LIKE

LOCAL

LOWER

MATCH

MAX

MIN

MINUTE

MODULE

MONTH

NAMES

NATIONAL

NATURAL

NCHAR

NEXT

NO

NOT

NULL

NULLIF

NUMERIC

OCTET_LENGTH

OF

ON

ONLY

OPEN

OPTION

OR

ORDER

OUTER

OUTPUT

OVERLAPS

PAD

PARTIAL

POSITION

PRECISION

PREPARE

PRESERVE

PRIMARY

PRIOR

PRIVILEGES

PROCEDURE

PUBLIC

READ

REAL

REFERENCES

RELATIVE

RESTRICT

REVOKE

RIGHT

ROLLBACK

ROWS

SCHEMA

SCROLL

SECOND

SECTION

SELECT

SESSION

SESSION_USER

SET

SIZE

SMALLINT

SOME

SPACE

SQL

SQLCODE

SQLERROR

SQLSTATE

SUBSTRING

SUM

SYSTEM_USER

TABLE

TEMPORARY

THEN

Reserved words

21

TIME

TIMESTAMP

TIMEZONE_
HOUR

TIMEZONE_
MINUTE

TO

TRAILING

TRANSACTION

TRANSLATE

TRANSLATION

TRIM

TRUE

UNION

UNIQUE

UNKNOWN

UPDATE

UPPER

USAGE

USER

USING

VALUE

VALUES

VARCHAR

VARYING

VIEW

WHEN

WHENEVER

WHERE

WITH

WORK

WRITE

YEAR

ZONE

22

Chapter 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  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

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 cfapplication tag. Reference them as
follows:
Application.myvariable
Session.myvariable

Scope-specific built-in variables

23

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:


The calling page can access the variable with the cfoutput tag, as follows:
#Caller.variable_name#

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:



...

Each nested tag can access the variable with the cfoutput tag, as follows:
#Request.field_name1#

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

24

Chapter 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 name attribute:
queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList

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 cferror generates an error page, the following
type="request", "exception", or "monitor".

error variables are available if

Error.Diagnostics
Error.MailTo
Error.DateTime
Error.Browser
Error.GeneratedContent
Error.RemoteAddress

ColdFusion tag-specific variables

25

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 stoponerror attribute, these variables are populated:
CFFTP.Succeeded

26

Chapter 1: Reserved Words and Variables

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 action attribute. When you
specify any of the following actions, cfftp returns a value:
GetCurrentDir
GetCurrentURL
ExistsDir
ExistsFile
Exists

CFFTP query object columns
When you use the cfftp tag with the listdir action, cfftp returns a query object, where
queryname is the name attribute value, and row is the row number of each file or directory entry:
queryname.Name[row]
queryname.Path[row]
queryname.URL[row]
queryname.Length[row]
queryname.LastModified[row]
queryname.Attributes
queryname.IsDirectory
queryname.Mode

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 variables

27

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

28

Chapter 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 variables

29

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:

CGI variable exists

CGI variable does not exist


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 variable

Description

SERVER_SOFTWARE

Name and version of the information server software answering the
request (and running the gateway). Format: name/version.

SERVER_NAME

Server's hostname, DNS alias, or IP address as it appears in selfreferencing URLs.

GATEWAY_INTERFACE CGI specification revision with which this server complies. Format: CGI/
revision.

30

SERVER_PROTOCOL

Name and revision of the information protocol this request came in with.
Format: protocol/revision.

SERVER_PORT

Port number to which the request was sent.

REQUEST_METHOD

Method with which the request was made. For HTTP, this is Get, Head,
Post, and so on.

PATH_INFO

Extra 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_TRANSLATED

Translated version of PATH_INFO after any virtual-to-physical mapping.

SCRIPT_NAME

Virtual path to the script that is executing; used for self-referencing
URLs.

QUERY_STRING

Query information that follows the ? in the URL that referenced this
script.

REMOTE_HOST

Hostname making the request. If the server does not have this
information, it sets REMOTE_ADDR and does not set
REMOTE_HOST.

REMOTE_ADDR

IP address of the remote host making the request.

AUTH_TYPE

If the server supports user authentication, and the script is protected, the
protocol-specific authentication method used to validate the user.

REMOTE_USER
AUTH_USER

If the server supports user authentication, and the script is protected, the
username the user has authenticated as. (Also available as
AUTH_USER.)

Chapter 1: Reserved Words and Variables

CGI server variable

Description

REMOTE_IDENT

If 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_TYPE

For queries that have attached information, such as HTTP POST and
PUT, this is the content type of the data.

CONTENT_LENGTH

Length 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 variable

Description

HTTP_REFERER

The referring document that linked to or submitted form data.

HTTP_USER_AGENT

The browser that the client is currently using to send the request.
Format: software/version library/version.

HTTP_IF_MODIFIED_SINCE

The 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. It can be used to take
advantage of browser-side caching.

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_SUBJECT

Client-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_ISSUER

Information 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_ENCODED

The 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 variables

31

32

Chapter 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
descriptions.
Contents
Tag summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Tags by function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Tag changes since ColdFusion 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Tag descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

33

Tag summary
The following table briefly describes CFML tags:

34

CFML tag

Category

Description

cfabort

Flow-control tags

Stops the processing of a ColdFusion page at
the tag location

cfapplet

Forms tags

Embeds Java applets in a cfform tag

cfapplication

Application framework
tags

Defines an application name; activates client
variables; specifies client variable storage
mechanism

cfargument

Extensibility tags

Creates a parameter definition within a
component definition; defines a function
argument

cfassociate

Application framework
tags

Enables subtag data to be saved with a base tag

cfbreak

Flow-control tags

Breaks out of a CFML looping construct

cfcache

Page processing tags

Caches ColdFusion pages

cfcase

Flow-control tags

Used with the cfswitch and cfdefaultcase tags

cfcatch

Exception handling tags, Catches exceptions in ColdFusion pages
Flow-control tags

cfchart

Data output tags

Generates and displays a chart

cfchartdata

Data output tags

Defines chart data points

cfchartseries

Data output tags

Defines style in which chart data displays

cfcol

Data output tags

Defines table column header, properties

cfcollection

Extensibility tags

Administers Verity collections

cfcomponent

Extensibility tags

Creates and defines a component object

cfcontent

Data output tags,
Page processing tags

Defines content type and filename of a file to be
downloaded by current page

cfcookie

Variable manipulation
tags

Defines and sets cookie variables, including
expiration and security options

cfdefaultcase

Flow-control tags

Receives control if there is no matching cfcase
tag value

cfdirectory

File management tags

Performs typical directory-handling tasks from
within a ColdFusion application

cfdump

Debugging tags,
Variable manipulation
tags

Outputs variables for debugging

cfelse

Flow-control tags

Creates IF-THEN-ELSE constructs

cfelseif

Flow-control tags

Creates IF-THEN-ELSE constructs

Chapter 2: ColdFusion Tags

CFML tag

Category

Description

cferror

Exception handling tags, Displays custom HTML error pages when errors
Application framework
occur
tags

cfexecute

Flow-control tags,
Extensibility tags

Executes developer-specified process on server
computer

cfexit

Flow-control tags

Aborts processing of executing CFML tag

cffile

File management tags

Performs typical file-handling tasks from within
ColdFusion application

cfflush

Data output tags,
Page processing tags

Flushes currently available data to client

cfform

Forms tags

Builds input form; performs client-side input
validation

cfftp

Forms tags,
Extensibility tags,
Internet Protocol tags

Permits FTP file operations

cffunction

Extensibility tags

Defines function that you build in CFML

cfgrid

Forms tags

Displays tabular grid control, in cfform tag

cfgridcolumn

Forms tags

Used in cfform; defines columns in a cfgrid

cfgridrow

Forms tags

Defines a grid row; used with cfgrid

cfgridupdate

Forms tags

Directly updates ODBC data source from edited
grid data

cfheader

Data output tags,
Page processing tags

Generates HTTP headers

cfhtmlhead

Forms tags,
Page processing tags

Writes text and HTML to HEAD section of page

cfhttp

Forms tags,
Internet Protocol tags

Performs GET and POST to upload file or post
form, cookie, query, or CGI variable directly to
server

cfhttpparam

Forms tags,
Internet Protocol tags

Specifies parameters required for a cfhttp
POST operation; used with cfhttp

cfif

Flow-control tags

Creates IF-THEN-ELSE constructs

cfimport

Application framework
tags

Imports JSP tag libraries into a CFML page

cfinclude

Flow-control tags

Embeds references to ColdFusion pages

cfindex

Extensibility tags

Creates Verity search indexes

cfinput

Forms tags

Creates an input element (radio button, check
box, text entry box); used in cfform

cfinsert

Database manipulation
tags

Inserts records in a data source

cfinvoke

Extensibility tags

Invokes component methods from a ColdFusion
page or component

Tag summary

35

CFML tag

Category

Description

cfinvokeargument

Extensibility tags

Passes a parameter to a component method or a
web service

cfldap

Forms tags,
Internet Protocol tags

Provides access to LDAP directory servers

cflocation

Flow-control tags

Controls execution of a page

cflock

Application framework
tags

Ensures data integrity and synchronizes
execution of CFML code

cflog

Data output tags,
Other tags

Writes a message to a log file

cflogin

Extensibility tags

Defines a container for user login and
authentication code

cfloginuser

Extensibility tags

Identifies an authenticated user to ColdFusion

cflogout

Extensibility tags

Logs the current user out

cfloop

Flow-control tags

Repeats a set of instructions based on
conditions

cfmail

Forms tags,
Internet Protocol tags

Assembles and posts an e-mail message

cfmailparam

Forms tags,
Internet Protocol tags

Attaches a file or adds a header to an e-mail
message

cfmailpart

Forms tags,
Internet Protocol tags

Contains one part of a multi-part mail message.

cfmodule

Application framework
tags

Invokes a custom tag for use in a ColdFusion
page

cfobject

Extensibility tags

Creates COM, component, CORBA, Java and
web service objects

cfobjectcache

Database manipulation
tags

Flushes the query cache

cfoutput

Data output tags

Displays the output of a database query or other
operation

cfparam

Variable manipulation
tags

Defines a parameter and its default value

cfpop

Forms tags,
Internet Protocol tags

Gets and deletes messages from POP mail
server

cfprocessingdirect Data output tags
ive

36

Suppresses white space and other output

cfprocparam

Database manipulation
tags

Holds parameter information for stored
procedure

cfprocresult

Database manipulation
tags

Result set name that ColdFusion tags use to
access result set of a stored procedure

cfproperty

Extensibility tags

Defines components

Chapter 2: ColdFusion Tags

CFML tag

Category

Description

cfquery

Database manipulation
tags

Passes SQL statements to a database

cfqueryparam

Database manipulation
tags

Checks data type of a query parameter

cfregistry

Other tags,
Variable manipulation
tags

Reads, writes, and deletes keys and values in a
Windows system registry

cfreport

Exception handling tags Embeds a Crystal Reports report

cfrethrow

Exception handling tags Rethrows currently active exception

cfreturn

Extensibility tags

Returns results from a component method

cfsavecontent

Variable manipulation
tags

Saves generated content inside tag body in a
variable

cfschedule

Variable manipulation
tags

Schedules page execution; optionally, produces
static pages

cfscript

Application framework
tags

Encloses a set of cfscript statements

cfsearch

Extensibility tags

Executes searches against data indexed in Verity
collections, using cfindex

cfselect

Forms tags

Creates a drop-down list box form element; used
in cfform tag

cfset

Variable manipulation
tags

Defines a variable

cfsetting

Other tags,
Variable manipulation
tags

Defines and controls ColdFusion settings

cfsilent

Data output tags,
Page processing tags

Suppresses CFML output within tag scope

cfslider

Forms tags

Creates slider control; used in cfform

cfstoredproc

Database manipulation
tags

Holds database connection information;
identifies a stored procedure to execute

cfswitch

Flow-control tags

Evaluates passed expression; passes control to
matching cfcase tag

cftable

Data output tags

Builds a table in a ColdFusion page

cftextinput

Forms tags

Puts a one-line text entry box in a form

cfthrow

Exception handling tags, Throws a developer-specified exception
Flow-control tags

cftrace

Debugging tags

Displays and logs application debugging data

cftransaction

Database manipulation
tags

Groups cfquery operations into one transaction;
performs rollback processing

cftree

Forms tags

Creates tree control element; used in cfform

Tag summary

37

38

CFML tag

Category

Description

cftreeitem

Forms tags

Populates a tree control element in a form; used
with cftree

cftry

Exception handling tags, Catches exceptions in ColdFusion pages
Flow-control tags

cfupdate

Database manipulation
tags

Updates rows in a database data source

cfwddx

Extensibility tags

Serializes and de-serializes CFML data
structures to XML-based WDDX format

cfxml

Extensibility tags

Creates an XML document object

Chapter 2: ColdFusion Tags

Tags by function
The following tables list Tags by their function or purpose.
Application framework tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Database manipulation tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Data output tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Debugging tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Exception handling tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Extensibility tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
File management tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Flow-control tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Forms tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Internet Protocol tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Page processing tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Variable manipulation tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Other tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Application framework tags
cfapplication

cfimport

cfassociate

cflock

cferror

cfmodule

cfscript

Database manipulation tags
cfinsert

cfprocresult

cfstoredproc

cfobjectcache

cfquery

cftransaction

cfprocparam

cfqueryparam

cfupdate

cfchart

cfcontent

cfoutput

cfchartdata

cfflush

cfprocessingdirective

cfchartseries

cfheader

cfsilent

cfcol

cflog

cftable

Data output tags

Debugging tags
cfdump

cftrace

Tags by function

39

Exception handling tags
cfcatch

cfrethrow

cferror

cfthrow

cftry

Extensibility tags
cfchart

cffunction

cfobject

cfchartdata

cfindex

cfproperty

cfchartseries

cfinvoke

cfreport

cfcollection

cfinvokeargument

cfreturn

cfcomponent

cflogin

cfsearch

cfexecute

cfloginuser

cfwddx

cfftp

cflogout

cfxml

cffile

cfftp

File management tags
cfdirectory

Flow-control tags
cfabort

cfexecute

cfrethrow

cfbreak

cfexit

cfswitch

cfcase

cfif

cfthrow

cfdefaultcase

cfinclude

cftry

cfelse

cflocation

cfelseif

cfloop

Forms tags

40

cfapplet

cfhtmlhead

cfpop

cfform

cfinput

cfselect

cfgrid

cfldap

cfslider

cfgridcolumn

cfmail

cftextinput

cfgridrow

cfmailparam

cftree

cfgridupdate

cfmailpart

cftreeitem

Chapter 2: ColdFusion Tags

Internet Protocol tags
cfftp

cfldap

cfmailpart

cfhttp

cfmail

cfpop

cfhttpparam

cfmailparam

Page processing tags
cfcache

cfheader

cfsetting

cfcontent

cfhtmlhead

cfsilent

cfflush

cfinclude

Variable manipulation tags
cfcookie

cfregistry

cfset

cfdump

cfsavecontent

cfsetting

cfparam

cfschedule

Other tags
cflog

cfregistry

Tags by function

41

Tag changes since ColdFusion 5
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.
New tags, attributes, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Deprecated tags, attributes, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Obsolete tags, attributes, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
New tags, attributes, and values
This table lists tags, attributes, and attribute values that have been added in ColdFusion MX
releases:
Tag

Attribute or value

Added in this ColdFusion
release

cfapplication

loginStorage

ColdFusion MX 6.1

cfargument

All

ColdFusion MX

cfcache

timespan attribute

ColdFusion MX

cachedirectory attribute

ColdFusion MX

cfchart

All

ColdFusion MX

cfchartdata

All

ColdFusion MX

cfchartseries

All

ColdFusion MX

cfcollection

list value of action attribute

ColdFusion MX

name attribute

ColdFusion MX

cfcomponent

All

ColdFusion MX

cfexecute

variable attribute

ColdFusion MX 6.1

cffunction

All

ColdFusion MX

cfhttp

attribute

ColdFusion MX

charset attribute

ColdFusion MX

HEAD, PUT, DELETE, OPTIONS, and TRACE ColdFusion MX 6.1
methods of method attribute

cfhttpparam

multipart attribute

ColdFusion MX 6.1

getasbinary attribute

ColdFusion MX 6.1

proxyUser

ColdFusion MX 6.1

proxyPassword

ColdFusion MX 6.1

header and body values of type

ColdFusion MX 6.1

attribute

42

Chapter 2: ColdFusion Tags

encoded attribute

ColdFusion MX 6.1

mimeType attribute

ColdFusion MX 6.1

Tag

Attribute or value

Added in this ColdFusion
release

cfimport

All

ColdFusion MX

cfinvoke

All

ColdFusion MX

cfinvokeargument

All

ColdFusion MX

cflogin

All

ColdFusion MX

cfloginuser

All

ColdFusion MX

cflogout

All

ColdFusion MX

cfmail

spoolEnable attribute

ColdFusion MX

charset attribute

ColdFusion MX 6.1

failto attribute

ColdFusion MX 6.1

replyTo attribute

ColdFusion MX 6.1

userName attribute

ColdFusion MX 6.1

password attribute

ColdFusion MX 6.1

wrapText attribute

ColdFusion MX 6.1

cfmailparam

type attribute

ColdFusion MX 6.1

cfmailpart

All

ColdFusion MX 6.1

cfobject

All

ColdFusion MX

cfobjectcache

All

ColdFusion MX

cfprocessingdirective pageEncoding attribute

ColdFusion MX

cfproperty

All

ColdFusion MX

cfreturn

All

ColdFusion MX

cfsetting

requestTimeOut attribute

ColdFusion MX

cfthrow

object attribute

ColdFusion MX

cftrace

All

ColdFusion MX

cfxml

All

ColdFusion MX

Tag changes since ColdFusion 5

43

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.
Tag

Attribute or value

Deprecated as of this ColdFusion
release

cfcache

timeout attribute

ColdFusion MX

cffile

attributes attribute value archive

ColdFusion MX

attributes attribute value system

ColdFusion MX

attributes attribute value temporary

ColdFusion MX

cfgraph

All

ColdFusion MX

cfgraphdata

All

ColdFusion MX

cfgridupdate

connectString attribute

ColdFusion MX

dbName attribute

ColdFusion MX

dbServer attribute

ColdFusion MX

dbType attribute

ColdFusion MX

provider attribute

ColdFusion MX

providerDSN attribute

ColdFusion MX

cfindex

external attribute

ColdFusion MX

cfinsert

connectString attribute

ColdFusion MX

dbName attribute

ColdFusion MX

dbServer attribute

ColdFusion MX

dbType attribute

ColdFusion MX

provider attribute

ColdFusion MX

providerDSN attribute

ColdFusion MX

filterConfig attribute

ColdFusion MX

filterFile attribute

ColdFusion MX

date attribute value "No"

ColdFusion MX

thread attribute value "No"

ColdFusion MX

time attribute value "No"

ColdFusion MX

cfldap

cflog

44

Chapter 2: ColdFusion Tags

Tag

Attribute or value

Deprecated as of this ColdFusion
release

cfquery

connectString attribute

ColdFusion MX

dbName attribute

ColdFusion MX

dbServer attribute

ColdFusion MX

The following dbType attribute values:
• dynamic
• ODBC
• Oracle73
• Oracle80
• Sybase11
• OLEDB
• DB2

ColdFusion MX
(The value query is valid.)

provider attribute

ColdFusion MX

providerDSN attribute

ColdFusion MX

sql attribute

ColdFusion MX

cfregistry

All, on UNIX only

ColdFusion MX

cfsearch

external attribute

ColdFusion MX

cfservlet

All

ColdFusion MX

cfservletparam

All

ColdFusion MX

cfslider

img attribute

ColdFusion MX

imgStyle attribute

ColdFusion MX

grooveColor attribute

ColdFusion MX

connectString attribute

ColdFusion MX

dbName attribute

ColdFusion MX

dbServer attribute

ColdFusion MX

provider attribute

ColdFusion MX

providerDSN attribute

ColdFusion MX

connectString attribute

ColdFusion MX

dbName attribute

ColdFusion MX

dbServer attribute

ColdFusion MX

provider attribute

ColdFusion MX

providerDSN attribute

ColdFusion MX

cfstoredproc

cfupdate

Tag changes since ColdFusion 5

45

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.
Tag

Attribute or value

Obsolete as of this ColdFusion
release

cfauthenticate

All

ColdFusion MX

cfimpersonate

All

ColdFusion MX

cfindex

action attribute value optimize

ColdFusion MX

cfinternaladminsecurity

All

ColdFusion MX
This tag did not appear in CFML
Reference.

cfnewinternaladminsecurity

All

ColdFusion MX
This tag did not appear in CFML
Reference.

cfsetting

catchExceptionsByPattern

ColdFusion MX

attribute

46

Chapter 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.
Category

Flow-control tags
Syntax

See also
cfbreak, cfexecute, cfexit, cfif, cflocation, cfloop, cfswitch, cfthrow, cftry
Attributes
Attribute

Req/Opt

showError

Optional

Default Description
Error 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 showError attribute value, processing stops when the tag is reached
and ColdFusion returns the page contents up to the line that contains the cfabort tag.
When you use this tag with the showError attribute, but do not define an error page using
page processing stops when the cfabort tag is reached. The message in showError
displays to the client.
cferror,

When you use this tag with the showError attribute and an error page using cferror,
ColdFusion redirects output to the error page specified in the cferror tag.
Example

Example A: Let the instruction complete itself

The value of myVariable after incrementing through the loop #Counter# times is: #myVariable#

Example B: Use cfabort to halt the instruction

cfabort 47

The value of myVariable after incrementing through the loop #counter# times is: #myVariable# 48 Chapter 2: ColdFusion Tags cfapplet Description This tag references a registered custom Java applet. To register a Java applet, in the ColdFusion Administrator, click Extensions > Java Applets. Using this tag within a cfform tag is optional. If you use it within cfform, and the method attribute is defined in the Administrator, the return value is incorporated into the form. Category Forms tags Syntax See also cfform, cfobject, cfservlet History ColdFusion MX: • 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 Attribute Req/Opt Default Description appletSource Required Name of registered applet name Required Form variable name for applet height Optional Height of applet, in pixel width Optional Width of applet, in pixels vSpace Optional Space above and below applet, in pixels hSpace Optional Space on left and right of applet, in pixels cfapplet 49 Attribute Req/Opt Default Description align Optional Alignment: • Left • Right • Bottom • Top • TextTop • Middle • AbsMiddle • Baseline • AbsBottom notSupported Optional param_n See Text to display if a page that contains a Java applet-based Description cfform control is opened by a browser that does not support Java or has Java support disabled. For example: notSupported = "Browser must support Java to view ColdFusion Java Applets" Default: Browser must support Java to
view ColdFusion Java Applets!
Optional Registered parameter for applet. Specify only to override values for applet in ColdFusion Administrator. Usage 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

cfapplet lets you reference custom Java applets that have been registered using the ColdFusion Administrator.

To register a Java applet, open the ColdFusion Administrator and click "Applets" link under "extensions" section.

This example applet copies text that you type into a form. Type some text, and then click "copy" to see the copied text. 50 Chapter 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 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 Attribute Req/Opt Default Description name See Description loginStorage Optional cookie • cookie: store login information in the Cookie scope • session: store login information in the Session scope clientManagement Optional No • Yes: enables client variables • No Name of application. Up to 64 characters. For Application and Session variables: Required. For Client variables: Optional cfapplication 51 Attribute Req/Opt Default Description clientStorage Optional registry How 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. setClientCookies Optional Yes • 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. sessionManagement Optional No • Yes: enables session variables • No sessionTimeout Optional Specified in Variables page of ColdFusion Administrator Lifespan of session variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas. applicationTimeout Optional Specified in Variables page of ColdFusion Administrator Lifespan of application variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas. setDomainCookies Optional No • Yes: Sets CFID and CFTOKEN cookies for a domain (not a host). Required, for applications running on clusters. • No Usage 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 cflock on page 221. If ColdFusion is running on a cluster, you must specify clientStorage = "cookie" or a data source name; you cannot specify "registry". 52 Chapter 2: ColdFusion Tags 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

cfapplication Example

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. E-Turtleneck is proud to say that we have sold #application.number# turtlenecks to date. cfapplication 53 cfargument Description Creates a parameter definition within a component definition. Defines a function argument. Used within a cffunction tag. Category Extensibility tags Syntax See also cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfobject, cfproperty, cfreturn Attributes 54 Attribute Req/Opt Default Description name Required String; an argument name. type Optional any Chapter 2: ColdFusion Tags String; 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. Attribute Req/Opt Default Description required Optional Whether the parameter is required to execute the component method. • yes (the parameter is not required if you specify a default attribute.) • no default Optional displayname Optional hint Optional no If no argument is passed, specifies a default argument value. name attribute value Meaningful only for CFC method parameters. A value to be displayed when using introspection to show information about the CFC. Meaningful only for CFC method parameters. Text to be displayed when using introspection to show information about the CFC. The hint attribute value follows the displayname attribute value in the parameter description line. This attribute can be useful for describing the purpose of the parameter. Usage 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 SELECT Descript FROM Courses WHERE Number = '#Course_Number#' cfargument 55 cfassociate Description Allows subtag data to be saved with a base tag. Applies only to custom tags. Category Application framework tags Syntax See also cfapplication, cferror, cflock, cfmodule Attributes Attribute Req/Opt baseTag Required dataCollection Optional Default Description Base tag name AssocAttribs Structure 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 AssocAttribs. To segregate subtag attributes (in a base tag that can have multiple subtags), specify a structure name, in the 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 ... 56 Chapter 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. cfauthenticate 57 cfbreak Description Used within a cfloop tag. Breaks out of a loop. Category Flow-control tags Syntax See also cfabort, cfexecute, cfif, cflocation, cfloop, cfswitch, cfthrow, cftry Example SELECT * FROM Courses ORDER by Course_Number

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.

Please enter a Course Number, and hit the "submit" button:

Your Desired Course was found:

#Course_Number# #Descript#

Searching...
58 Chapter 2: ColdFusion Tags cfcache Description 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. Category Page processing tags Syntax See also cfflush, cfheader, cfhtmlhead, cfsetting, cfsilent History ColdFusion MX: • 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 "http"and "80", respectively.) 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.) cfcache 59 Attributes Attribute Req/Opt Default Description action Optional cache • 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". directory Optional cf_root/cache Absolute path of cache directory. timespan Optional Page is The interval until the page is flushed from the cache. flushed only • A decimal number of days. For example: when cfcache - ".25", for one-fourth day (6 hours) action = - "1", for one day "flush" is - "1.5", for one and one half days executed • A return value from the CreateTimeSpan function. For example: "#CreateTimeSpan(0, 6, 0, 0)#" expireURL Optional Flush all Used with action = "flush". A URL reference. cached pages ColdFusion matches it against the mappings in the specified cache directory. Can include wildcards. For example: "*/view.cfm?id=*". username Optional A username. Provide this if the page requires authentication at the web server level. password Optional A password. Provide this if the page requires authentication at the web server level. port Optional The current page port protocol Optional The current Protocol that is used to create URL from cache. page protocol • http:// • https:// Port number of the web server from which the URL is requested. In the internal call from cfcache to cfhttp, ColdFusion resolves each URL variable in the page; this ensures that links in the page remain functional. 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 timespan attribute, or by invoking cfcache 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. 60 Chapter 2: ColdFusion Tags 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 cfcache unless the application page enables debugging. When generating a cached file, cfcache uses cfsetting showDebugOutput = "No". 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 is a test of some simple output

The value of URL.x = # URL.x # cfcache 61 cfcase Description Used only inside the cfswitch tag body. Contains code to execute when the expression specified in the cfswitch tag has one or more specific values. Category Flow-control tags Syntax See also cfdefaultcase, cfswitch Attributes Attribute Req/Opt value Required delimiter Optional Default Description The value or values that the expression attribute of the cfswitch tag must match. To specify multiple matching values, separate the values with the delimiter character. The value or values must be simple constants or constant expressions, not variables. , (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 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 cfcase tag, as you do in some languages. One cfcase tag can match multiple expression values. To do this, separate the matching values with the delimiter character, which is the comma by default. For example the following line matches "red", "blue", or "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": Example 62 Chapter 2: ColdFusion Tags Your grade is #grade# cfcase 63 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 Exception processing code here 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 an UNKNOWN exception. ■ • • • • 64 Chapter 2: ColdFusion Tags Attributes Attribute Req/Opt Default Description type Any application: catches application exceptions database: catches database exceptions template: catches ColdFusion page exceptions security: catches security exceptions object: catches object exceptions missingInclude: catches missing include file exceptions expression: catches expression exceptions lock: catches lock exceptions custom_type: catches the specified custom exception type that is defined in a cfthrow tag • searchengine: catches Verity search engine exceptions • any: catches all exception types Optional • • • • • • • • • Usage 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 cfcatch tag in the cftry block with 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: If you have the following cfcatch tag, it will handle the exception: Otherwise, if you have the following cfcatch tag, it will handle the exception: Finally, if you have the following cfcatch tag, it will handle the exception: You can code cfcatch tags in any order to catch a custom exception type. If you specify type = "Application", the cfcatch tag catches only custom exceptions that have the Application type in the cfthrow tag that defines them. cfcatch 65 The cfinclude, cfmodule, and cferror tags throw an exception of type = "template". An exception that is thrown within a cfcatch block cannot be handled by the cftry block that immediately encloses the cfcatch tag. However, you can rethrow the currently active exception with the cfrethrow tag. The cfcatch variables provide the following exception information: 66 cfcatch variable Content cfcatch.type Type: Exception type, as specified in cfcatch. cfcatch.message 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 Applies to type ="database". The SQL statement sent to the data source. cfcatch.queryError Applies to type ="database". The error message as reported by the database driver. cfcatch.where Applies to type ="database". If the query uses the cfqueryparam tag, query parameter name-value pairs. cfcatch.ErrNumber Applies to type="expression". Internal expression error number. cfcatch.MissingFileName Applies to type="missingInclude". Name of file that could not be included. cfcatch.LockName Applies to type="lock". Name of affected lock (if the lock is unnamed, the value is "anonymous"). cfcatch.LockOperation Applies to type="lock". Operation that failed (Timeout, Create Mutex, or Unknown). cfcatch.ErrorCode Applies to type="custom". String error code. cfcatch.ExtendedInfo Applies to type="application" and "custom". Custom error message; information that the default exception handler does not display. Chapter 2: ColdFusion Tags Advanced Exception types You can specify the following advanced exception types in the type attribute: ColdFusion advanced exception type COM.Allaire.ColdFusion.CFEXECUTE.OutputError COM.Allaire.ColdFusion.CFEXECUTE.Timeout COM.Allaire.ColdFusion.FileException COM.Allaire.ColdFusion.HTTPAccepted COM.Allaire.ColdFusion.HTTPAuthFailure COM.Allaire.ColdFusion.HTTPBadGateway COM.Allaire.ColdFusion.HTTPBadRequest COM.Allaire.ColdFusion.HTTPCFHTTPRequestEntityTooLarge COM.Allaire.ColdFusion.HTTPCGIValueNotPassed COM.Allaire.ColdFusion.HTTPConflict COM.Allaire.ColdFusion.HTTPContentLengthRequired COM.Allaire.ColdFusion.HTTPContinue COM.Allaire.ColdFusion.HTTPCookieValueNotPassed COM.Allaire.ColdFusion.HTTPCreated COM.Allaire.ColdFusion.HTTPFailure COM.Allaire.ColdFusion.HTTPFileInvalidPath COM.Allaire.ColdFusion.HTTPFileNotFound COM.Allaire.ColdFusion.HTTPFileNotPassed COM.Allaire.ColdFusion.HTTPFileNotRenderable COM.Allaire.ColdFusion.HTTPForbidden COM.Allaire.ColdFusion.HTTPGatewayTimeout COM.Allaire.ColdFusion.HTTPGone COM.Allaire.ColdFusion.HTTPMethodNotAllowed COM.Allaire.ColdFusion.HTTPMovedPermanently COM.Allaire.ColdFusion.HTTPMovedTemporarily COM.Allaire.ColdFusion.HTTPMultipleChoices COM.Allaire.ColdFusion.HTTPNoContent COM.Allaire.ColdFusion.HTTPNonAuthoritativeInfo COM.Allaire.ColdFusion.HTTPNotAcceptable COM.Allaire.ColdFusion.HTTPNotFound COM.Allaire.ColdFusion.HTTPNotImplemented cfcatch 67 ColdFusion advanced exception type COM.Allaire.ColdFusion.HTTPNotModified COM.Allaire.ColdFusion.HTTPPartialContent COM.Allaire.ColdFusion.HTTPPaymentRequired COM.Allaire.ColdFusion.HTTPPreconditionFailed COM.Allaire.ColdFusion.HTTPProxyAuthenticationRequired COM.Allaire.ColdFusion.HTTPRequestURITooLarge COM.Allaire.ColdFusion.HTTPResetContent COM.Allaire.ColdFusion.HTTPSeeOther COM.Allaire.ColdFusion.HTTPServerError COM.Allaire.ColdFusion.HTTPServiceUnavailable COM.Allaire.ColdFusion.HTTPSwitchingProtocols COM.Allaire.ColdFusion.HTTPUnsupportedMediaType COM.Allaire.ColdFusion.HTTPUrlValueNotPassed COM.Allaire.ColdFusion.HTTPUseProxy COM.Allaire.ColdFusion.HTTPVersionNotSupported COM.Allaire.ColdFusion.POPAuthFailure COM.Allaire.ColdFusion.POPConnectionFailure COM.Allaire.ColdFusion.POPDeleteError COM.Allaire.ColdFusion.Request.Timeout COM.Allaire.ColdFusion.SERVLETJRunError COMCOM.Allaire.ColdFusion.HTTPConnectionTimeout Example

cftry Example

SELECT * FROM EMPLOYEEAS

You've Thrown a Database Error

#cfcatch.message#

Caught an exception, type = #CFCATCH.TYPE#

68 Chapter 2: ColdFusion Tags

The contents of the tag stack are:


#i# #sCurrent["ID"]# (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#) #sCurrent["TEMPLATE"]#
cfcatch 69 cfchart Description Generates and displays a chart. Category Data output tags, Extensibility tags Syntax 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. 70 Chapter 2: ColdFusion Tags Attributes Attribute Req/Opt Default Description format flash File format in which to save graph. • flash • jpg • png chartHeight 240 Chart height; integer number of pixels chartWidth 320 Chart width; integer number of pixels scaleFrom Determined by Y-axis minimum value; integer. data scaleTo Determined by Y-axis maximum value; integer data showXGridlines no • yes: display X-axis gridlines • no: hide X-axis gridlines showYGridlines yes • yes: display Y-axis gridlines • no: hide Y-axis gridlines gridlines 10, including Number of grid lines to display on value axis, top and bottom including axis; positive integer. seriesPlacement default 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 foregroundColor black Color 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. dataBackgroundColor white Color of area around chart data. 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. showBorder no • yes • no font arial Name of text font • 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. cfchart 71 Attribute 72 Req/Opt Default Description fontSize 11 Font size; integer fontBold no • yes • no fontItalic no • Yes • No labelFormat number Format for Y-axis labels. • number • currency • percent • date xAxisTitle text; X-axis title yAxisTitle text; Y-axis title xAxisType category • category The axis indicates the data category. Data is sorted according to the sortXAxis attribute. • scale The axis is numeric. All cfchartdata item attribute values must numeric. The X axis is automatically sorted numerically. yAxisType category Currently has no effect, as Y axis is always used for data values. Valid values are category and scale sortXAxis no • yes: display column labels in alphabetic order along X-axis • no Ignored if xAxisType attribute is scale. show3D no • yes: display chart with three-dimensional appearance • no xOffset 0.1 Applies 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 yOffset 0.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 rotated no • yes: rotate chart 90 degrees. For a horizontal bar chart, use this option. • no showLegend yes • yes: if chart contains more than one data series, display legend • no Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description tipStyle mouseOver Determines 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 tipbgcolor white Applies 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. showMarkers yes Applies to chartseries type attribute values line, curve and scatter. • yes: display markers at data points • no markerSize (Automatic) Size of data point marker. in pixels. Integer. pieSliceStyle sliced Applies to chartseries type attribute value pie. • solid: displays pie as if unsliced • sliced: displays pie as if sliced url URL 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 name Page variable name. String. Generates the 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. Usage The cfchart tag defines a container in which a graph displays: its height, width, background color, labels, and so on. The cfchartseries tag defines the style in which data displays: bar, line, pie, and so on. The cfchartdata tag defines a data point. cfchart 73 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 fontbold andfontitalic attributes have no effect The color attributes accept the following W3C HTML 4 named color value or hex values: Color name RGB 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. 74 Chapter 2: ColdFusion Tags cfchartdata Description Used with the cfchart and cfchartseries tags. This tag defines chart data points. Its data is submitted to the cfchartseries tag. Category Data output tags, Extensibility tags Syntax See also cfchart, cfchartseries History ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description item string; data point name value number or expression; data point value cfchartdata 75 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 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 Attribute Req/Opt type Required Sets the chart display style: • bar • line • pyramid • area • cone • curve • cylinder • step • scatter • pie query Optional Name of ColdFusion query from which to get data. itemColumn Required if Name of a column in the query specified in the query attribute; contains the item label for a data point to graph. query attribute is specified valueColumn Required if query attribute is specified 76 Chapter 2: ColdFusion Tags Default Description Name of a column in the query specified in the query attribute; contains data values to graph. Attribute Req/Opt Default Description seriesLabel Optional Text of data series label seriesColor Optional Color 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 "##xxxxxx", where x = 0-9 or A-F; use two pound signs or none. paintStyle Optional plain Sets 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 markerStyle Optional rectangle Applies to chartseries type attribute values line, curve and scatter, and show3D attribute value no. Sets the icon that marks a data point: • rectangle • triangle • diamond • circle • letter • mcross • snow • rcross colorlist Optional Applies if chartseries type attribute = "pie". Sets pie slice colors. Comma-delimited list of hex values or supported, named web colors; see name list in the cfchart Usage section. For a hex value, use the form "##xxxxxx", where x = 0-9 or A-F; use two pound signs or none. Usage 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. cfchartseries 77 cfcol Description Defines table column header, width, alignment, and text. Used within a cftable tag. Category Data output tags Syntax See also cfcontent, cfoutput, cftable History ColdFusion MX: Added the ability to construct dynamic cfcol statements. Attribute Req/Opt header Required Default Description Column header text. To use this attribute, you must also use the cftable colHeaders attribute. width Optional 20 Column width. If the length of data displayed exceeds this value, data is truncated to fit. To avoid this, use an HTML table tag. If the surrounding cftable tag includes the htmltable attribute, width specifies the percent of the table width and it does not truncate text; otherwise, width specifies the number of characters. align Optional Left Column alignment • Left • Right • Center text Required Double-quotation mark-delimited text; determines what to display. Rules: same as for cfoutput sections. You can embed hyperlinks, image references, and input controls. Usage 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 cftable tags. To display the cfcol header text, you must specify the cfcol header and the cftable colHeader attribute. If you specify either attribute without the other, the header does not display. No error is thrown. Example SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department 78 Chapter 2: ColdFusion Tags FROM Employees

cfcol Example

cfcol 79 cfcollection Description Creates, registers, and administers Verity search engine collections. A collection that is created with the cfcollection tag is internal. A collection created any other way is external. A collection that is registered with ColdFusion using the cfcollection tag or registered with the K2 Server by editing the k2server.ini file is registered. Other collections are unregistered. An internal collection can be created in these ways: • With the cfcollection tag • In the ColdFusion Administrator, which calls the cfcollection tag An external collection can be created using a native Verity indexing tool, such as Vspider or MKVDK. Category Extensibility tags Syntax See also cfexecute, cfindex, cfobject, cfreport, cfsearch, cfwddx History ColdFusion MX: • 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 • • • 80 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. Chapter 2: ColdFusion Tags Attributes Attribute Req/Opt Default Description action 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 action = create: 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 name attribute value, of the attributes of the collections that are registered by ColdFusion and K2 Server. Required; see Usage section collection See Usage section • A collection name. The name can include spaces. path See Usage section 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, "C:\MyCollections\" language See Usage section name See Usage section English Options are listed in Usage section. Requires the appropriate (European or Asian) Verity Locales language pack. Name for the query results returned by the list action. Usage 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): For this action attribute value: create map collection Required Required Required path Required Optional language Optional Optional name list optimize repair delete Required Required Required If more than instance of the cfcollection tag might access or modify a collection simultaneously, use the cflock tag to protect the collection from attempts at simultaneous operations. To register a collection with K2Server, you update the k2server.ini file. cfcollection 81 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: Column Contents 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 LANGUAGE The 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 list attribute. If the K2 Server is not running when the 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: select * from myCollections where myCollections.name = 'myCollectionName' To get a result set with values for all the collections that are registered with the ColdFusion and K2 servers, use code such as the following: #name#
To add content to a collection, use cfindex. To search a collection, use cfsearch. 82 Chapter 2: ColdFusion Tags With the European Verity Locales language pack installed, the language attribute of this tag supports the following options: bokmal french norweg danish german portug dutch italian portuguese english nynorsk spanish finnish norwegian swedish With the Asian Verity Locales language pack installed, the language attribute of this tag supports the following options: arabic hungarian russian czech japanese simplified_chinese greek korean traditional_chinese hebrew polish turkish The default location of Verity collections is as follows: • Windows: C:\CFusionMX\verity\collections • Unix system: /opt/coldfusionmx/verity/collections Example

Collection created.
Use CFINDEX to populate it.

Collection repaired.

cfcollection 83

Collection optimized.

Collection deleted.

Please enter a name for your collection

Collection on which to act
Use the default value or enter your own Collection name

84 Chapter 2: ColdFusion Tags cfcomponent Description Creates and defines a component object; encloses functionality that you build in CFML and enclose within cffunction tags. This tag contains one or more cffunction tags that define methods. Code within the body of this tag, other than 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 hint = "text string"> variable declarations ... ... See also cfargument, cffunction, cfinvoke, cfinvokeargument, cfobject, cfproperty, cfreturn, Chapter 11, “Building and Using ColdFusion Components,” in Developing ColdFusion MX Applications cfcomponent 85 Attributes Attribute Req/Opt extends Optional output Optional displayname Optional hint Default Description Name of parent component from which to inherit methods and properties. Component body displayable text is processed as standard CFML 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. name attribute value A string to be displayed when using introspection to show information about the CFC. The information appears on the heading, following the component name. Optional Text to be displayed when using introspection to show 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. Usage 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: This tag requires an end tag. Example SELECT FIRSTNAME, LASTNAME, EMAIL FROM tblEmployees SELECT * FROM tblDepartments 86 Chapter 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 starting with a drive letter and a colon, or a forward or backward slash See also cfcol, cfheader, cfhttp, cfoutput, cftable cfcontent 87 Attributes 88 Attribute Req/Opt type Optional deleteFile Optional file Optional reset Optional Default Description 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" No Applies 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. Name 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. Yes Chapter 2: ColdFusion Tags The 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. Usage To set the character encoding (character set) of generated output, use code such as the following: 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 meta tag in the page). You can use the 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 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. cfheader name="Content-Disposition" value="attachment; filename=filename.ext" 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 cfheader tag similar to the following: 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 SetEncoding charset parameter and other ColdFusion attributes and parameters. For a complete list of media types used on the Internet, see www.iana.org/assignments/media-types/. Example cfcontent 89

cfcontent Example 2

This example shows how reset

reset = "Yes ": 123 This example shows how reset

reset = "No ": 123 reset = "Yes ">456

attribute changes output for text.

reset = "No ">456

cfcookie Description Defines web browser cookie variables, including expiration and security options. Category Forms tags, Variable manipulation tags Syntax See also cfdump, cfparam, cfregistry, cfsavecontent, cfschedule, cfset History ColdFusion MX 6.1: • 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/Opt Default Description name Required Name 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. value Optional Value to assign to cookie variable. Must be a string or variable that can be stored as a string. expires Optional Expiration 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). secure Optional If 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 cfcookie 91 Attribute Req/Opt path domain Default Description Optional URL, 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 cfcookie tags. If you specify path, you must also specify domain. Required if 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, ".mgm.com". You cannot use an IP address as a domain. path attribute is specified. Optional otherwise Usage 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 . To get a cookie’s value, refer to the cookie name in the Cookie scope, as in . 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: #cookie.person.name# Example SELECT EMail, FromUser, Subject, Posted FROM Comments

cfcookie Example

92 Chapter 2: ColdFusion Tags

The last AOL visitor to view this site was #Cookie.LastAOLVisitor#, on #DateFormat(COOKIE.TimeVisited)#

Hide my tracks

No AOL Visitors have viewed the site lately. cfcookie 93 cfdefaultcase Description Used only inside the cfswitch tag body. Contains code to execute when the expression specified in the cfswitch tag does not match a of the value specified by a cfcase tag. Category Flow-control tags Syntax See also cfcase, cfswitch History ColdFusion MX: Changed placement requirements: this tag does not have to follow all cfcase tags in the cfswitch tag body. 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 cfdefaultcase tag body can include HTML and text, and CFML tags, functions, variables, and expressions. You can specify only one cfdefaultcase tag within a cfswitch tag. You can put the tag at any position within a cfswitch statement; it is not required to be the last item, but it is good programming practice to put it last. cfdefaultcase Example Your grade is #grade# 94 Chapter 2: ColdFusion Tags cfdirectory Description Manages interactions with directories. Category File management tags Syntax See also cffile History ColdFusion MX: • Changed behavior for action ■ ■ ■ = "list": On Windows, cfdirectory action = "list" no longer returns the directory entries "." (dot) or ".." (dot dot), which represent "the current directory" and "the parent directory." On Windows, cfdirectory action = "list" no longer returns the values of the Archive and System attributes. On UNIX and Linux, cfdirectory action = "list" does not return any information in the mode column. Attributes Attribute Req/Opt Default Description action Optional List • 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 directory Required Absolute pathname of directory against which to perform action. Required if Name for output record set. name action = "list" filter Optional if action = "list" File extension filter applied to returned names. For example: *.cfm. One filter can be applied. cfdirectory 95 Attribute Req/Opt mode Optional sort Optional; used if action = Default Description Used with action = "create". Permissions. Applies 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 ASC "list" newDirectory Required if Query 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 = "rename" Usage Note: For this tag execute, it must be enabled in the ColdFusion Administrator. For more information, see Configuring and Administering ColdFusion MX. 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. 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: size: #mydirectory.name# #mydirectory.size# #mydirectory.type# #mydirectory.dateLastModified# #mydirectory.attributes# #mydirectory.mode# 96 Chapter 2: ColdFusion Tags 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: Pattern Matches foo.* any file called foo with any extention i.e. foo.html, foo.cfm, foo.xml, ... *.html all files with the suffix .html, but not files with the suffix .htm. ?? all files with 2 character names. Example

cfdirectory Example

cfdirectory 97 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. Category Debugging tags, Variable manipulation tags Syntax See also cfcookie, cfparam, cfsavecontent, cfschedule, cfset, cfwddx History ColdFusion MX 6.1: Added the ability to dump COM objects; it displays the methods and Get and Put properties typeinfo information for the object. Attributes Attribute Req/Opt var Required expand Optional label Optional Default Description Variable to display. Enclose a variable name in pound signs. These kinds of variables yield meaningful cfdump displays: • array • CFC • COM object • Java object • simple • query • structure • UDF • wddx • xml Yes • Yes: In Internet Explorer and Mozilla, expands views • No: contracts expanded views A string; header for the dump output. Usage The expand/contract display capability is useful when working with large structures, such as XML document objects, structures, and arrays. To display a construct, use code such as the following, in which myDoc is a variable of type XmlDocument: The tag output is color-coded according to data type. 98 Chapter 2: ColdFusion Tags If a table cell is empty, this tag displays "[empty string]". Example This example shows how to use this tag to display a URL variable. URL variables contain parameters that are passed in a URL string in a page request. cfdump 99 cfelse Description Used as the last control block in a cfif tag block to handle any case not identified by the cfif tag or a cfelseif tag. Category Flow-control tags Syntax HTML and CFML tags HTML and CFML tags HTML and CFML tags See also cfif, cfelseif, cfabort, cfbreak, cfexecute, cfexit, cflocation, cfloop, cfswitch, cfthrow, cftry Usage If the values of the expressions in the containing cfif tag and all cfelseif tags are false, ColdFusion processes the code between this tag and the cfif end tag. This tag must be inside a cfif tag block. It does not require an end tag. For more information and an example, see cfif on page 187. 100 Chapter 2: ColdFusion Tags cfelseif Description Used as a control block in a cfif tag block to handle any case not identified by the cfif tag or a cfelseif tag. Category Flow-control tags Syntax HTML and CFML tags HTML and CFML tags HTML and CFML tags See also cfif, cfelse, cfabort, cfbreak, cfexecute, cfexit, cflocation, cfloop, cfswitch, cfthrow, cftry Usage If the value of the expression in this tag is true, and the values of the expressions in the containing cfif tag and preceding cfelseif tags are false, ColdFusion processes the code between this tag and a following cfelseif or cfelse tag, or the cfif end tag and then skips to the code following the cfif end tag. Otherwise, ColdFusion skips the code. This tag must be inside a cfif tag block. It does not require an end tag. For more information and an example, see cfif on page 187. cfelseif 101 cferror Description Displays a custom HTML page when an error occurs. This lets you maintain a consistent look and feel among an application’s functional and error pages. Category Exception handling tags, Extensibility tags, Application framework tags Syntax See also cfrethrow, cfthrow, cftry History ColdFusion MX: Deprecated the monitor option of the exception attribute. It might not work, and might cause an error, in later releases. Attributes 102 Attribute Req/Opt type Required Type of error that the custom error page handles. The type also determines how ColdFusion handles the error page. For more information, see Chapter 14, “Specifying a custom error page,” in Developing ColdFusion MX Applications. • exception: a exception of the type specified by the exception attribute. • validation: errors recognized by sever-side type validation. • request: any encountered error. template Required Relative path to the custom error page. (A ColdFusion page was formerly called a template.) mailTo Optional An E-mail address. This attribute is available on the error page as the variable error.mailto. ColdFusion does not automatically send anything to this address. exception Optional Chapter 2: ColdFusion Tags Default Description Any Type of exception that the tag handles: • application: application exceptions • database: database exceptions • template: ColdFusion page exceptions • security: security exceptions • object: object exceptions • missingInclude: missing include file exceptions • expression: expression exceptions • lock: lock exceptions • custom_type: developer-defined exceptions, defined in the cfthrow tag • any: all exception types For more information on exception types, see cftry on page 353 Usage Use this tag to provide custom error messages for pages in an application. You generally embed this tag in the Application.cfm file. For more information, see Chapter 14, “Handling Errors,” in Developing ColdFusion MX Applications. To ensure that error pages display successfully, avoid using the cfencode tag to encode pages that include the cferror tag. Page Types The following table describes the types of errors you can specify and code you can use on the pages that handle these error type. Page type Description Use Exception Dynamically invoked by the CFML language Can handle specific exception processor when it detects an unhandled exception types or display general condition. information for exceptions. Uses the full range of CFML tags. Error variables must be in cfoutput tags. Request Includes the error variables described in the Error Variables section. Cannot include CFML tags, but you can display values of the error variables by enclosing them in number signs (#), as in #error.MailTo#. Validation Handles hidden form-field style Handles data input validation errors that occur when submitting a form that uses hidden form-field validation errors only. validation. Cannot include CFML tags, but you can display values of the error variables by enclosing them in number signs (#), as in #Error.InvalidFields#. You must specify the validation error handler in the Application.cfm file. Use as a backup error handler to other error handling methods, including exception type. Error variables The exception-handling page specified in the cferror tag template attribute contains one or more error variables. ColdFusion substitutes the value of the error variable when an error displays. The following table lists error variables: Page type Error variable Description Validation only error.validationHeader Validation message header text. error.invalidFields Unordered list of validation errors. error.validationFooter Validation message footer text. cferror 103 Page type Error variable Description Request and Exception error.diagnostics Detailed error diagnostics from ColdFusion MX. error.mailTo E-mail address (same as value in cferror.MailTo). error.dateTime Date and time when error occurred. error.browser Browser that was running when error occurred. error.remoteAddress IP address of remote client. error.HTTPReferer Page from which client accessed link to page where error occurred. error.template Page executing when error occurred. error.generatedContent The content generated by the page up to the point where the error occurred. error.queryString URL query string of client's request. error.messge Error message associated with the exception. error.rootCause Java servlet exception reported by the JVM as the cause of the "root cause" of the exception. This variable is a Java object. error.tagContext Array of structures containing information for each tag in the tag stack. The tag stack consists of each tag that is currently open. error.type Exception type. Exception only In exception error handling pages, you can access the error variables that are also available to the cfcatch tag. See cfcatch for a description of these variables. To use these variables, prefix them with "cferror." Note: If type = "exception" you can substitute the prefix cferror for Error; for example, cferror.diagnostics, cferror.mailTo, or cferror.dateTime. Example

cferror Example

cferror lets you display custom HTML pages when errors occur. This lets you maintain a consistent look and feel within the application even when errors occur. No CFML can be displayed in the pages, except specialized error variables.

cftry/cfcatch is a more interactive way to handle CF errors within a CF page than cferror, but cferror is a good safeguard against general errors.

You can also use cferror within Application.cfm to specify error handling responsibilities for an entire application. We’re sorry -- An Error Occurred 104 Chapter 2: ColdFusion Tags

We’re sorry -- An Error Occurred

If you continue to have this problem, please contact #error.mailTo# with the following information:

  • Your Location: #error.remoteAddress#
  • Your Browser: #error.browser#
  • Date and Time the Error Occurred: #error.dateTime#
  • Page You Came From: #error.HTTPReferer#
  • Message Content:

    #error.diagnostics#

cferror 105 cfexecute Description Executes a ColdFusion developer-specified process on a server computer. Category Extensibility tags, Flow-control tags Syntax ... See also cfcollection, cfindex, cfobject, cfreport, cfsearch, cfwddx History ColdFusion MX 6.1: • Added the variable attribute. • Changed file path behavior for the outputFile attribute: if you do not specify an absolute file path in the outputFile attribute, the path is relative to the ColdFusion temporary directory. Attributes 106 Attribute Req/Opt name Required Default Description Absolute path of the application to execute. On Windows, you must specify an extension; for example, C:\myapp.exe. arguments Optional Command-line variables passed to application. If specified as string, it is processed as follows: • Windows: passed to process control subsystem for parsing. • UNIX: tokenized into an array of arguments. The default token separator is a space; you can delimit arguments that have embedded spaces with double quotation marks. If passed as array, it is processed as follows: • Windows: elements are concatenated into a string of tokens, separated by spaces. Passed to process control subsystem for parsing. • UNIX: elements are copied into an array of exec() arguments. outputFile Optional File to which to direct program output. If no outputfile or variable attribute is specified, output is displayed on the page from which it was called. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. Chapter 2: ColdFusion Tags Attribute Req/Opt variable Optional Default Description Variable in which to put program output. If no outputfile or variable attribute is specified, output is displayed on page from which it was called. timeout Optional 0 Length of time, in seconds, that ColdFusion waits for output from the spawned program. • 0: equivalent to non-blocking mode. • A very high value: equivalent to blocking mode If the value is 0: • ColdFusion starts a process and returns immediately. ColdFusion may return control to the calling page before any program output displays. To ensure that program output displays, set the value to 2 or higher. • If the outputFile attribute is not specified, any program output is discarded Usage Do not put other ColdFusion tags or functions between the start and end tags of cfexecute. You cannot nest cfexecute tags. Exceptions Throws the following exceptions: • If the application name is not found: Application File Not Found • If the effective user of the ColdFusion executing thread does not have permissions to execute the process: a security exception The time out values must be between zero and the longest time out value supported by the operating system. Example

cfexecute

This example executes the Windows NT version of the netstat network monitoring program, and places its output in a file. cfexecute 107 cfexit Description This tag aborts processing of the currently executing CFML custom tag, exits the page within the currently executing CFML custom tag, or re-executes a section of code within the currently executing CFML custom tag. Category Debugging tags, Flow-control tags Syntax See also cfabort, cfbreak, cfexecute, cfif, cflocation, cfloop, cfswitch, cfthrow, cftry Attributes Attribute Req/Opt Default Description method Optional exitTag • exittag: aborts processing of currently executing tag • exittemplate: exits page of currently executing tag • loop: reexecutes body of currently executing tag Usage If this tag is encountered outside the context of a custom tag, for example in the base page or an included page, it executes in the same way as cfabort. The cfexit tag can help simplify error checking and validation logic in custom tags. The cfexit tag function depends on its location and execution mode: Method value Location of cfexit call Behavior exitTag Base page Terminate processing Execution mode = Start Continue after end tag Execution mode = End Continue after end tag Base page Terminate processing Execution mode = Start Continue from first child in body Execution mode = End Continue after end tag Base page Error Execution mode = Start Error Execution mode = End Continue from first child in body exitTemplate loop Example

cfexit Example

cfexit can be used to abort the processing of the currently executing CFML custom tag. Execution resumes following the invocation of the custom tag in the page that called the tag.

Usage of cfexit

108 Chapter 2: ColdFusion Tags

cfexit is used primarily to perform a conditional stop of processing inside a custom tag. cfexit returns control to the page that called that custom tag, or in the case of a tag called by another tag, to the calling tag.

If cfexit is used outside a custom tag, it functions like a cfabort. For example, the text after this message is not processed:

This text is not executed because of the cfexit tag above it. cfexit 109 cffile Description Manages interactions with server files. The following sections describe the actions of the cffile tag: • • • • • • • • • on page 113 on page 115 "delete" on page 116 "move" on page 117 "read" on page 119 "readBinary" on page 121 "rename" on page 122 "upload" on page 124 "write" on page 127 cffile action = "append" cffile action = "copy" cffile action = cffile action = cffile action = cffile action = cffile action = cffile action = cffile action = Note: To execute, this tag must be enabled in the ColdFusion Administrator. For more information, see Configuring and Administering ColdFusion MX. If your ColdFusion applications run on a server used by multiple customers, consider the security of the files that could be uploaded or manipulated by cffile. For more information, see Configuring and Administering ColdFusion MX. Category File management tags Syntax The tag syntax depends on the action attribute value. See the following sections. See also cfdirectory History ColdFusion MX 6.1: • Changed file path requirements: if you do not specify an absolute file path, the path is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. • Changed behavior for action="read": if the file starts with a byte order mark (BOM) ColdFusion uses it to determine the character encoding. • Changed behavior for action="upload" nameConflict="MakeUnique" ColdFusion now makes filenames unique by appending a incrementing number, 1 for the first file, 2 for the second and so on, to the name. In ColdFusion MX filenames were made unique by appending an additional "1" for each file, as in 1, 11, 111, and so on. ColdFusion MX: • Changed use of slashes in paths: you can use forward (/) or backward (\) slashes in paths on both UNIX and Windows systems. • Changed file hierarchy requirements: ColdFusion does not require that you put files and directories that you manipulate with this tag below the root of the web server document directory. 110 Chapter 2: ColdFusion Tags • Changed directory path requirements for the destination attribute: a directory path that you specify in the destination attribute does not require a trailing slash. • Deprecated the system value of the attributes attribute. • Deprecated the temporary value of the attributes attribute. In ColdFusion MX, it is a synonym for normal. It might not work in later releases. • Changed the action attribute options read, write, append and move: they support a new attribute, charset. • The archive value of the attributes attribute is obsolete and has no effect. Example This is a view-only example.

Type in some text to include in your file:

A file exists (foobar.txt, in #GetTempDirectory()#). You may add to it, read from it, or delete it. < !--- if reading from a form, let that information display in textarea ---> cffile 111

---> 112 Chapter 2: ColdFusion Tags cffile action = "append" Description Appends text to a text file on the server. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt action Required Type of file manipulation that the tag performs. file Required Pathname of the file to which to append content of output attribute. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. mode Optional Applies only to UNIX and Linux. Permissions. Octal values of Unix 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 output Required String to append to the file. addNewLine Optional Default Yes Description • Yes: appends newline character to text written to file • No cffile 113 Attribute Req/Opt attributes Optional charset Optional Default Description Applies to Windows. A comma-delimited list of attributes to set on the file. If omitted, the file's attributes are maintained. Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten. • readOnly • hidden • normal JVM default file character set. The character encoding in which the file contents is encoded. The following list includes commonly used 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 more information character encodings, see: www.w3.org/International/O-charset.html. Example This example appends a text string to the file fieldwork.txt: 114 Chapter 2: ColdFusion Tags cffile action = "copy" Description Copies a file from one directory to another on the server. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt Default Description action Required Type of file manipulation that the tag performs. source Required Pathname of the file to copy. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. destination Required Pathname of a directory or file on web server where the file will be copied. If not an absolute path, it is relative to the source directory.. mode Optional Applies only to UNIX and Linux. Permissions. Octal values of Unix 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 attributes Optional Applies to Windows. A comma-delimited list of attributes to set on the file. If omitted, the file's attributes are maintained. Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten. • readOnly • hidden • normal Example This example copies the keymemo.doc file to the c:\files\backup\ directory: cffile 115 cffile action = "delete" Description Deletes a file on the server. Syntax See also cfdirectory Attributes Attribute Req/Opt Default Description action Required Type of file manipulation that the tag performs. file Required Pathname of the file to delete. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. Example The following example deletes the specified file: 116 Chapter 2: ColdFusion Tags cffile action = "move" Description Moves a file from one location to another on the server. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt Default Description action Required Type of file manipulation that the tag performs. source Required Pathname of the file to move. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. destination Required Pathname of the destination directory or file. If not an absolute path, it is relative to the source directory. mode Applies only to UNIX and Linux. Permissions. Octal values of UNIX 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 Optional cffile 117 Attribute Req/Opt attributes Optional charset Optional Default Description Applies to Windows. A comma-delimited list of attributes to set on the file. If omitted, the file's attributes are maintained. Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten. • readOnly • hidden • normal JVM default file character set. The character encoding in which the file contents is encoded. The following list includes commonly used 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 more information character encodings, see: www.w3.org/International/O-charset.html. Example The following example moves the keymemo.doc file from the c:\files\upload\ directory to the c:\files\memo\ directory in Windows: In this example, the destination directory is "memo." 118 Chapter 2: ColdFusion Tags cffile action = "read" Description Reads a text file on the server. The file is read into a dynamic, local variable that you can use in the page. For example: • Read a text file; insert the file’s contents into a database • Read a text file; use the find and replace function to modify the file’s contents Note: This action reads the file into a variable in the local Variables scope. It is not intended for use with large files, such as logs, because this can bring down the server. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt Default action Required Type of file manipulation that the tag performs. file Required Pathname of the file to read. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. variable Required Name of variable to contain contents of text file. charset Optional Character encoding identified by the file’s byte order mark, if any; otherwise, JVM default file character set. Description The character encoding in which the file contents is encoded. The following list includes commonly used values: • utf-8 • iso-8859-1 • windows-1252 • us-ascii • shift_jis • iso-2022-jp • euc-jp • euc-kr • big5 • euc-cn • utf-16 If the file starts with a byte order mark and you set this attribute to a conflicting character encoding, ColdFusion generates an error. For more information character encodings, see: www.w3.org/International/O-charset.html. cffile 119 Usage The following example creates a variable named Message for the contents of the file message.txt: The variable Message can be used in the page. For example, you could display the contents of the message.txt file in the final web page as follows: #Message# ColdFusion supports functions for manipulating the contents of text files. You can also use the variable that is created by a cffile action = "read" operation in the ArrayToList and ListToArray functions. Note: If you use this tag to read a file that is encoded using the Windows Cp1252 (windows-1252) encoding of the Latin-1 character set on a system whose default character encoding is Cp1252, and the files has characters encoded in the Hex 8x or 9x range, you must specify charset="windows-1252" attribute, even though this is the default encoding. Otherwise, some characters in the Hex8x and 9x ranges that do not map correctly and display incorrectly. 120 Chapter 2: ColdFusion Tags cffile action = "readBinary" Description Reads a binary file (such as an executable or image file) on the serve, into a binary object parameter that you can use in the page. To send it through a web protocol (such as HTTP or SMTP) or store it in a database, first convert it to Base64 using the ToBase64 function. Note: This action reads the file into a variable in the local Variables scope. It is not intended for use with large files, such as logs, because they can bring down the server. Syntax See also cfdirectory Attributes Attribute Req/Opt Default Description action Required Type of file manipulation that the tag performs. file Required Pathname of a binary fine to read. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. variable Required Name of variable to contain contents of binary file. Usage You convert the binary file to Base64 to transfer it to another site. Example The following example creates a variable named aBinaryObj to contain the ColdFusion MX executable: cffile 121 cffile action = "rename" Description Renames or moves a file on the server. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt Default Description action Required Type of file manipulation that the tag performs. source Required Pathname of file to rename. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. destination Required Destination file or directory. If not an absolute path, it is relative to the source directory. mode Optional Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other. For example: • 644: Assigns read/write permission to owner; read permission to group and other • 777: Assigns read/write/execute permission to all attributes Optional Applies to Windows. A comma-delimited list of attributes to set on the file. If omitted, the file's attributes are maintained. Each value must be specified explicitly. For example, if attributes = "readOnly", all other attributes are overwritten. • hidden • normal • readOnly Usage The rename action renames or move a file. The destination attribute must be a pathname, not just a new name for the file. If the destination is a directory, the file is moved and not renamed. Example The following example renames the file keymemo.doc to oldmemo.doc: 122 Chapter 2: ColdFusion Tags cffile 123 cffile action = "upload" Description Copies a file to a directory on the server. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt action Required Type of file manipulation that the tag performs. fileField Required Name of form field used to select the file. Do not use pound signs (#) to specify the field name. destination Required Pathname of directory in which to upload the file. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. nameConflict Optional accept Default Error Optional Description Action to take if filename is the same as that of a file in the directory. • Error: file is not saved. ColdFusion stops processing the page and returns an error. • Skip: file is not saved. This option permits custom behavior based on file properties. • Overwrite: replaces file. • MakeUnique: forms a unique filename for the upload; name is stored in the file object variable serverFile. Limits the MIME types to accept. Comma-delimited list. For example, to permit JPG and Microsoft Word file uploads: accept = "image/jpg, application/msword" The browser uses file extension to determine file type. 124 Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description mode Optional Applies only to UNIX and Linux. Permissions. 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 attributes Optional Applies to Windows. A comma-delimited list of attributes to set on the file. If omitted, the file's attributes are maintained. Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten. • readOnly • hidden • normal (if you use this option with other attributes, it is overridden by them) Usage After a file upload is completed, you can get status information using file upload parameters. The status parameters use the cffile prefix; for example, cffile.clientDirectory. Status parameters can be used anywhere other ColdFusion parameters can be used. Note: The file prefix is deprecated, in favor of the cffile prefix. Do not use the file prefix in new applications. Tip: If your page is uploading a file that was selected on a form or was otherwise sent to your page via a multipart/form-data HTTP message, you can determine the approximate size of the file by checking the value of the CGI.content_length variable. This variable includes the file length plus the length of any other request content. The following file upload status parameters are available after an upload. Parameter Description attemptedServerFile Initial name ColdFusion used when attempting to save a file clientDirectory Directory location of the file uploaded from the client’s system clientFile Name of the file uploaded from the client’s system clientFileExt Extension of the uploaded file on the client system (without a period) clientFileName Name of the uploaded file on the client system (without an extension) contentSubType MIME content subtype of the saved file contentType MIME content type of the saved file dateLastAccessed Date and time the uploaded file was last accessed fileExisted Whether the file already existed with the same path (Yes or No) fileSize Size of the uploaded file fileWasAppended Whether ColdFusion appended uploaded file to a file (Yes or No) fileWasOverwritten Whether ColdFusion overwrote a file (Yes or No) fileWasRenamed Whether uploaded file renamed to avoid a name conflict (Yes or No) cffile 125 Parameter Description fileWasSaved Whether ColdFusion saves a file (Yes or No) oldFileSize Size of a file that was overwritten in the file upload operation serverDirectory Directory of the file saved on the server serverFile Filename of the file saved on the server serverFileExt Extension of the uploaded file on the server (without a period) serverFileName Name of the uploaded file on the server (without an extension) timeCreated Time the uploaded file was created timeLastModified Date and time of the last modification to the uploaded file Tip: To refer to parameters, use the cffile prefix: for example, #cffile.fileExisted#. Note: File status parameters are read-only. They are set to the results of the most recent cffile operation. (If two cffile tags execute, the results of the second overwrite the first.) Example The following example creates a unique filename, if there is a name conflict when the file is uploaded on Windows: The following examples show the use of the mode attribute. The first example creates the file /tmp/foo with permissions defined as: owner=read/write, group=read, other=read. This example appends to a file and sets permissions to read/write (rw) for all. This example uploads a file and sets permissions to owner/group/other = read/write/execute. 126 Chapter 2: ColdFusion Tags cffile action = "write" Description Writes a text file on the server, based on dynamic content. You can create static HTML files from the content, or log actions in a text file. Syntax See also cfdirectory History See the History section of the main cffile tag page. Attributes Attribute Req/Opt action Required Type of file manipulation that the tag performs. file Required Pathname of the file to write. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function. output Required Content of the file to be created. mode Optional Applies only to UNIX and Linux. Permissions. Octal values of Unix 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 addNewLine Optional Default Yes Description • Yes: appends newline character to text written to file • No cffile 127 Attribute Req/Opt attributes Optional charset Optional Default Description Applies to Windows. A comma-delimited list of attributes to set on the file. If omitted, the file's attributes are maintained. Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten. • readOnly • hidden • normal JVM default file character set. The character encoding in which the file contents is encoded. The following list includes commonly used 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 more information character encodings, see: www.w3.org/International/O-charset.html. Example This example creates a file with information a user entered in an HTML insert form: If the user submitted a form with the following: UpdateTitle = "FieldWork" FullName = "World B. Frueh" Date = "10/30/01" Content = "We had a wonderful time in Cambridgeport." ColdFusion would create a file named FieldWork.txt in the c:\files\updates\ directory and the file would contain the following text: Created By: World B. Frueh Date: 10/30/01 We had a wonderful time in Cambridgeport. This example shows the use of the mode attribute for UNIX. It creates the file /tmp/foo with permissions rw-r--r-- (owner = read/write, group = read, other = read): This example appends to the file and sets permissions to read/write (rw) for all: 128 Chapter 2: ColdFusion Tags This example uploads a file and gives it the permissions owner/group/other = read/write/execute): cffile action = "upload" fileField = "fieldname" destination = "/tmp/program.exe" mode = 777> cffile 129 cfflush Description Flushes currently available data to the client. Category Data output tags, Page processing tags Syntax See also cfcache, cfheader, cfinclude, cfsetting, cfsilent Attributes Attribute Req/Opt interval Optional Default Description Integer. Flushes output each time this number of bytes becomes available. HTML headers, and data that is already available when the tag is executed, are omitted from the count. Usage The first occurrence of this tag on a page sends back the HTML headers and any other available HTML. Subsequent cfflush tags on the page send only the output that was generated after the previous flush. When you flush data, ensure that enough information is available, as some browsers might not respond if you flush only a small amount. Similarly, set the interval attribute for a few hundred bytes or more, but not thousands of bytes. Use the interval attribute only when a large amount of output will be sent to the client, such as in a cfloop or a cfoutput of a large query. Using this form globally (such as in the Application.cfm file) might cause unexpected errors when CFML tags that modify HTML headers are executed. Caution: Because the cfflush tag sends data to the browser when it executes, it has several limitations, including the following: Using any of the following tags or functions on a page anywhere after the cfflush tag can cause errors or unexpected results: cfcontent, cfcookie, cfform, cfheader, cfhtmlhead, cflocation, and SetLocale. (These tags and functions normally modify the HTML header, but cannot do so after a cfflush tag, because the cfflush sends the header.) Using the cfset tag to set a cookie anywhere on a page that has a cfflush tag does not set the cookie in the browser. Using the cfflush tag within the body of several tags, including cfsavecontent, cfquery, and custom tags, cause errors. If you save Client variables as cookies, any client variables that you set after a cfflush tag are not saved in the browser. Note: Normally, the cferror tag discards the current output buffer and replaces it with the contents of the error page. The cfflush tag discards the current buffer. As a result, the Error.GeneratedContent variable resulting from a cferror tag after a cfflush contains any contents of the output buffer that has not been flushed. This content is not sent to the client. The content of the error page displays to the client after the bytes that have been sent. Example The following example uses cfloop tags and the rand random number generating function to delay data display. It simulates a page that is slow to generate data.

Your Magic numbers

130 Chapter 2: ColdFusion Tags

It will take us a little while to calculate your ten magic numbers. It takes a lot of work to find numbers that truly fit your personality. So relax for a minute or so while we do the hard work for you.

We are sure you will agree it was worth the short wait!

Magic number number #Myindex# is:  #RandRange( 100000, 999999)#

cfflush 131 cfform Description Builds a form with CFML custom control tags; these provide more functionality than standard HTML form input elements. Category Forms tags Syntax ... See also cfapplet, cfgrid, cfinput, cfselect, cfslider, cftextinput, cftree, cftreeitem History ColdFusion MX: • Deprecated the enableCAB attribute. It might not work, and might cause an error, in later • releases. Changed the name and action attributes to optional. Attributes 132 Attribute Req/Opt Default Description name Optional CFForm_1 [, ...] A name for the form. action Optional Name of ColdFusion page to execute when the form is submitted for processing. scriptSrc Optional /cfide/scripts Lets the user control the URL of the script file; useful if /cfform.js you do not keep the file in the /cfide directory. Chapter 2: ColdFusion Tags Attribute Req/Opt preserveData Optional Default Description No When the cfform action attribute posts back to the same page as the form, this determines whether to override the control values with the submitted values. • false: values specified in the control tag attributes are used • true: corresponding submitted values are used Applies to these controls: • cfform controls cfinput, cfslider, cftextinput; overrides value attribute value • cfselect controls that are populated from queries. Overrides the selected attribute. See cfselect on page 312. • cftree controls: Overrides the cftreeitem expand attribute. If true, expands previously-selected elements. The cftree completePath attribute must be set to Yes. • cfgrid controls: has no effect. (This avoids confusion as to whether data has been resubmitted to the database by the control.) onSubmit Optional JavaScript function to execute after input validation. Use for preprocessing data before form is submitted. See Developing ColdFusion MX Applications. passThrough Optional Passes arbitrary attribute-value pairs to the HTML code that is generated for the tag. You can use either of the following formats: passthrough="title=""myTitle""" passthrough=’title="mytitle"’ codeBase Optional See Description URL of downloadable JRE plug-in (for Internet Explorer only). Default: /CFIDE/classes/cf-j2re-win.cab archive Optional See Description URL of downloadable Java classes for ColdFusion controls. Default: /CFIDE/classes/CFJava2.jar In addition to the listed attributes, you can use the following HTML attributes in the cfform tag. The tag does not use these attributes, but includes them in the form tag that it generates and returns to the browser: • • • • • • class enctype id onReset style target cfform 133 Usage This tag requires an end tag. Some custom control tags that you can use within this tag require the client to download a Java applet; they might execute slightly more slowly than using an HTML form element to get the same information. In addition to regular HTML form elements, you can use the following custom control tags within the cfform tag: • • • • • • • Creates and validates an input element (radio button, text box, check box) cfselect Creates a drop-down list box cfslider Creates a slider control (Java support required) cftextinput Creates a text input box (Java support required) cftree Creates a tree control (Java support required) cfgrid Creates a grid control to display tabular data (Java support required) cfapplet Embeds a registered Java applet (Java support required) All of these control tags require that the browser is JavaScript-enabled. cfinput If you use this tag after the cfflush tag on a page, an error is thrown. The method attribute is automatically set to post; if you specify a value, it is ignored. If you specify a value in quotation marks, you must escape them by doubling them; for example: passThrough = "readonly = ""Yes"" ". Any form field name, from the cfform tag or an HTML form, that ends in one of the following suffixes invokes server-side form validation: • • • • • • _integer Verifies that the user entered a number. _float Verifies that the user entered a number. _range Verifies that a numeric value entered is within specified boundaries. _date Verifies that the user entered a date; converts to ODBC date format. _time Verifies that the user correctly entered a time; converts to ODBC time format. _eurodate Verifies that the user entered a date in a standard European date format; converts to ODBC date format. Do not use these suffixes for your field names. For more information, see Chapter 26, “Retrieving and Formatting Data,” in Developing ColdFusion MX Applications. Incorporating HTML form tags The cfform tag lets you incorporate these standard HTML elements: • Standard form tag attributes and values. The attributes and values are included in the form tag that cfform outputs in the page. For example, you can use form tag attributes like target with cfform. Other pass-through attributes include CLASS, ENCTYPE, ID, ONLOAD, ONRESET, and STYLE. 134 Chapter 2: ColdFusion Tags • HTML tags that can ordinarily be put within the HTML form tag. For example, you can use the HTML input tag to create a submit button in a cfform, without the other features of cfinput: Example

cfform Example

Results of Radio Button Test

Your radio button answer was yes Your radio button answer was no

Results of Checkbox Test

Your checkbox answer was yes

Results of Checkbox Test

Your checkbox answer was no

Results of Credit Card Input

Your credit card number, #form.textSample#, was valid under the MOD 10 algorithm.

You gave this page a rating of #form.sampleSlider#


cfform 135

This example displays radio button input type for cfinput.

Yes No

This example displays checkbox input type for cfinput.

This shows client-side validation for cfinput text boxes.


(This item is optional)
Please enter a credit card number:

This example shows the use of the cfslider tag.

Rate your approval of this example from 1 to 10 by sliding control.

1 10

136 Chapter 2: ColdFusion Tags cfftp Description Lets users implement File Transfer Protocol (FTP) operations. Category File management tags, Internet Protocol tags Syntax The tag syntax depends on the action attribute value. See the following sections: • “cfftp: Opening and closing FTP server connections” on page 138 • “cfftp: Connection: File and directory operations” on page 141 • “cfftp action = "listDir"” on page 145 See also cfhttp, cfldap, cfmail, cfpop History ColdFusion MX: Deprecated the agentname attribute. It might not work, and might cause an error, in later releases. Usage Use this tag to move files between a ColdFusion server and an FTP server. This tag does not move files between a ColdFusion server and a client browser. You do this as follows: • To transfer files from a client to a ColdFusion server: cffile action = • To transfer files from a ColdFusion server to a client: the cfcontent tag "upload" Security settings ColdFusion MX security settings can prevent the cfftp tag from executing. If you run ColdFusion applications on a server that is used by multiple customers, consider the security of the files that the customer can move. For more information, see Configuring and Administering ColdFusion MX. cfftp 137 cfftp: Opening and closing FTP server connections Description To establish a connection with an FTP server, you use the open action with a connection attribute. Syntax See also cfhttp, cfldap, cfmail, cfpop Attributes Attribute Req/Opt Default Description action Required FTP operation to perform. • open: create an FTP connection • close: terminate an FTP connection username Required if User name to pass in the FTP operation. action = "open" password Password to log in the user. Required if action = "open" server Required if FTP server to which to connect; for example, action = "open" ftp.myserver.com timeout Optional 30 Value in seconds for the timeout of all operations, including individual data request operations. port Optional 21 Remote port to which to connect. connection Optional, but always used with open or Name of the FTP connection. If you specify the username, password, and server attributes, and if no connection exists for them, ColdFusion creates one. Calls to cfftp with the same connection name reuse the connection. close proxyServer Optional retryCount 138 Optional Chapter 2: ColdFusion Tags String. Name of proxy server (or servers) to use, if proxy access is specified. 1 Number of retries until failure is reported. Attribute Req/Opt Default Description stopOnError Optional No • Yes: halts processing, displays an appropriate error. • No: populates these variables: - cfftp.succeeded – Yes or No. - cfftp.errorCode – Error number. See the IETF Network Working Group RFC 959: File Transfer Protocol (FTP) www.ietf.org/rfc/rfc0959.txt. - cfftp.errorText – Message text For conditional operations, use cfftp.errorCode. Do not use cfftp.errorText for this purpose. passive No • Yes: enable passive mode • No Optional Usage When you establish a connection with cfftp action="open" and specify a name in the connection attribute, ColdFusion caches the connection so that you can reuse it to perform additional FTP operations. When use a cached connection for subsequent FTP operations, you do not have to specify the username, password, or server connection attributes. The FTP operations that use the same connection name automatically use the information stored in the cached connection. Using a cached connection helps save connection time and improves file transfer performance. You do not need to open a connection for single, simple, FTP operations, such as GetFile or PutFile. To keep a connection open throughout a session or longer, you can use a Session or Application variable as the connection name. However, if you do this, you must specify the full variable name in all FTP operations, and you must use the close action when you are finished. Keeping a connection open prevents others from using the FTP server; so close a connection as soon as possible. If you do not assign the connection name to Session or Application variable, the connection remains open for the current page only, and you do not have to close it manually. Changes to a cached connection, such as changing retryCount or timeout values, might require reestablishing the connection. Example

cfftp lets users implement File Transfer Protocol operations. By default, cfftp caches an open connection to an FTP server.

cfftp operations are usually of two types:

  • Establishing a connection
  • Performing file and directory operations

This example opens and verifies a connection, lists the files in a directory, and closes the connection.

Open a connection

Did it succeed? #cfftp.succeeded#

List the files in a directory: #name#

Close the connection:

Did it succeed? #cfftp.succeeded# 140 Chapter 2: ColdFusion Tags cfftp: Connection: File and directory operations Description Use this form of the cfftp tag to perform file and directory operations with cfftp. Syntax See also cfhttp, cfldap, cfmail, cfpop Attributes Attribute Req/Opt Default Description action Required if connection is not cached FTP operation to perform. • changedir • createDir • listDir • removeDir • getFile • putFile • rename • remove • getCurrentDir • getCurrentURL • existsDir • existsFile • exists username Required if connection is not cached User name to pass in the FTP operation. password Required if action Password to log in the user. = "open" name Required if action Query name of directory listing. = "listDir" server Required if FTP connection is not cached FTP server to which to connect; for example, ftp.myserver.com. cfftp: Connection: File and directory operations 141 Attribute Req/Opt Default Description ASCIIExtension Optional List txt;htm;html; Delimited list of file extensions that force ASCII transfer mode, if transferMode = "auto". cfm;cfml; shtm;shtml; css;asp;asa transferMode Optional Auto • ASCII FTP transfer mode • Binary FTP transfer mode • Auto FTP transfer mode failIfExists Optional Yes • Yes: if a local file with same name exists, getFile fails • No directory Required if action = "changedir", "createDir", "listDir", or "existsDir" Directory on which to perform an operation. localFile Required if action = "getFile" or "putFile" Name of the file on the local file system. remoteFile Required if action = "getFile", "putFile", or "existsFile" Name of the file on the FTP server file system. item Required if action = "exists" or "remove" Object of these actions: file or directory. existing Required if action Current name of the file or directory on the remote server. = "rename" new Required if action New name of file or directory on the remote server = "rename" proxyServer Optional passive Optional String. Name of the proxy server (s) to use, if proxy access is specified No • Yes: enable passive mode • No Usage If you use connection caching to an active FTP connection, you do not have to respecify the username, password, or server connection attributes: Changing a cached connection, such as changing retryCount or timeout values, might require reestablishing the connection. If action = "listDir", the attributes column returns directory or normal. Other platform-specific values, such as hidden and system, are no longer supported. If action = "listDir", a mode column is returned. The column contains an octal string representation of UNIX permissions; for example, "777." 142 Chapter 2: ColdFusion Tags The cfftp.returnValue variable provides the return value for these actions: • • • • • getCurrentDir getCurrentURL existsDir existsFile exists For more information, see Developing ColdFusion MX Applications. Caution: Object (file and directory) names are case-sensitive. Action (cfftp.ReturnValue variable) The results of an action determine the value of the cfftp.returnValue variable. cfftp action Value of cfftp.returnValue getCurrentDir String. Current directory. getCurrentURL String. Current URL. existsDir Yes or No. existsFile Yes or No. exists Yes or No. Example The following example opens a connection and gets a file listing showing file or directory name, path, URL, length, and modification date.

Open a connection

Did it succeed? #cfftp.succeeded#

FTP Directory Listing:

Close the connection:

Did it succeed? #cfftp.succeeded# 144 Chapter 2: ColdFusion Tags cfftp action = "listDir" Description To access the columns in a query object, use this tag with action = "listDir". Usage When you use this action, you must specify a value for the name attribute. This value holds the results of the listDir action in a query object. The query object consists of columns that you can reference, in the form queryname.columname[row], where queryname is the name of the query, specified in the name attribute; and columnname is a column returned in the query object. The value row is the row number of each file/directory entry returned by the listDir operation. A separate row is created for each entry: cfftp query object column Description Name Filename of the current element. Path File path (without drive designation) of the current element. URL Complete URL for the current element (file or directory). Length File size of the current element. LastModified Unformatted date/time value of the current element. Attributes String. Attributes of the current element: normal or Directory. IsDirectory Boolean. Whether object is a file or directory. Mode Applies only to UNIX and Linux. Permissions. Octal string. Note: Previously supported query column values that pertain to system-specific information are not supported; for example, hidden and system. cfftp: Connection: File and directory operations 145 cffunction Description Defines a function that you can call in CFML. Required to defined ColdFusion component methods. Category Extensibility tags Syntax See also cfargument, cfcomponent, cfinvoke, cfinvokeargument, cfobject, cfproperty, cfreturn Attributes 146 Attribute Req/Opt name Required returnType Required for a web service; Optional, otherwise. Chapter 2: ColdFusion Tags Default Description A string; a component method that is used within the cfcomponent tag. any String; a type name; data type of the function return value: • 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. Attribute Req/Opt Default Description roles Optional "" (empty) A comma-delimited list of ColdFusion security roles that can invoke the method. Only users who are logged in with the specified roles can execute the function. If this attribute is omitted, all users can invoke the method. access Optional public The client security context from which the method can be invoked: • private: available only to the component that declares the method and any components that extend the component in which it is defined • package: available only to the component that declares the method, components that extend the component, or any other components in the package • public: available to a locally executing page or component method • remote: available to a locally or remotely executing page or component method, or a remote client through a URL, Flash, or a web service. To publish the function as a web service, this option is required. output Optional Specifies under which conditions the function can Function generate HTML output. body is processed • yes: The entire function body is processed as if it were as standard within a cfoutput tag. Variables names surrounded by CFML number signs (#) are automatically replaced with their values. • no: The function is processed as if it were within a cfsilent tag • If you do not specify this attribute, the function body is processed as standard CFML. Any variables must be in cfoutput tags. displayname Optional Meaningful only for CFC method parameters. A value to be displayed in parentheses following the function name when using introspection to show information about the CFC. hint Meaningful only for CFC method parameters. Text to be displayed when using introspection to show information about the CFC. The hint attribute value follows the syntax line in the function description. Optional Usage The cffunction tag can define a function that you call in the same manner as a ColdFusion built in function. To define a ColdFusion component (CFC) method, you must use a cffunction tag. For information on using the cffunction tag. The following example shows cffunction tag attributes for a simple CFC method that returns a ColdFusion Query object. For information on using the cffunction tag for ColdFusion components, see Chapter 11, “Building and Using ColdFusion Components,” in Developing ColdFusion MX Applications. If you specify a roles attribute, the function executes only if a user is logged in and belongs to one of the specified roles. If you specify variableName for the returnType attribute, the function must return a string that is in ColdFusion variable name format; that is, the function must return a string that starts with a letter, underscore, or Unicode currency symbol, and consist of letters, numbers, and underscores (_), periods, and Unicode currency symbols, only. ColdFusion does not check whether the value corresponds to an existing ColdFusion variable. Example SELECT FIRSTNAME, LASTNAME, EMAIL FROM tblEmployees SELECT * FROM tblDepartments 148 Chapter 2: ColdFusion Tags cfgraph Description This tag is deprecated. Use the cfchart, cfchartdata, and cfchartseries tags instead. Displays data graphically. History ColdFusion MX: Deprecated this tag. It works differently than it did in ColdFusion 5, and it might not work in later releases. The incompatibilities between the ColdFusion MX implementation and earlier implementations of this tag are as follows: cfgraph tag attribute ColdFusion MX functionality Title Ignored Titlefont Ignored Barspacing Ignored Bordercolor Color used for border, gridlines, and text displays Colorlist • Pie chart: list of colors to use for each data point • Other chart types: ignored Valuelabelfont Sets value label text font. If the Valuelabelfont, Itemlabelfont, and Legendfont values differ, ColdFusion uses the last value that you specify in the tag. Arial is not supported; it is mapped to Dialog. Itemlabelfont Sets item label text font. If the Valuelabelfont, Itemlabelfont, and Legendfont values differ, ColdFusion uses the last value that you specify in the tag Arial is not supported; it is mapped to Dialog. Legendfont Sets legend text font. If the Valuelabelfont, Itemlabelfont, and Legendfont values differ, ColdFusion uses the last value that you specify in the tag Arial is not supported; it is mapped to Dialog. ShowLegend • above, below, left, right: these options cause the legend to display, but have no effect on its location. • none: prevents display of a legend Valuelabelsize Sets value label text size. If the Valuelabelsize and Itemlabelsize values differ, ColdFusion uses the last value that you specify in the tag Itemlabelsize Sets item label text size Itemlabelorientation Ignored. ColdFusion calculates best orientation based on label and graph size. Borderwidth • a non-zero number: default-width border, regardless of number value • 0: no border Depth • 0: displays graph with two-dimensional appearance • any other value: displays graph with threedimensional appearance Linewidth Ignored cfgraph 149 150 cfgraph tag attribute ColdFusion MX functionality Showvaluelabel • yes: displays values on mouse-click; • no: suppresses value displays • rollover: displays values on mouse-over. Valuelocation Ignored url URL of page to open if any item in the graph is clicked. The following variables may be used within the URL; they are substituted with real values before the URL is accessed: • "$value$": selected row/column value or an empty string • "$itemlabel$": selected item (column) value or an empty string • "$serieslabel$": selected series (row) value or an empty string • "javascript:...": executes client side scripts. Urlcolumn Ignored. This attribute generates a graph, but the url link is missing data that the linked page may expect. Thus, drilling-down in the graph may result in an error. Type="HorizontalBar" The (0,0) coordinate is located at the lower-left. ScaleFrom If the smallest value in the data is less than scaleFrom or the largest value in the data is greater than scaleTo, the respective data value is used as the minimum or maximum on the Y scale. Therefore, regardless of the scaleFrom or scaleTo value, all data values display. Chapter 2: ColdFusion Tags cfgraphdata Description This tag is deprecated. Use the cfchart, cfchartdata, and cfchartseries tags instead. Displays a data point in a graph. Used within the cfgraph tag. History ColdFusion MX: Deprecated this tag. It works differently than in ColdFusion 5 and might not work in later releases. cfgraphdata 151 cfgrid Description Used within the cfform tag. Puts a grid control (a table of data) in a ColdFusion form. To specify grid columns and row data, use the cfgridcolumn and cfgridrow tags, or use the query attribute, with or without cfgridcolumn tags. Category Forms tags Syntax See also cfgridcolumn, cfgridrow, cfgridupdate, cfapplet, cfform, cfinput, cfselect, cfslider, cftextinput, cftree, cftreeitem History ColdFusion MX: Changed the rowHeaderWidth attribute: ColdFusion does not use the rowHeaderWidth attribute. You can omit it. Attributes Attribute Req/Opt Default Description name Required height Optional 300 Height of grid control, in pixels. width Optional 300 Width of grid control, in pixels. autoWidth No Optional; see description • Yes: sets column widths so that all columns display within grid width. • No: sets columns to equal widths. User can resize columns. Horizontal scroll bars are not available, because if you specify a column width and set autoWidth = "Yes", ColdFusion sets to this width, if possible. vSpace Optional Vertical space above and below grid control, in pixels. hSpace Optional Horizontal space to left and right of grid control, in pixels. align Optional Alignment of the grid cell contents: • Top • Left • Bottom • Baseline • Texttop • Absbottom • Middle • Absmiddle • Right query Optional Name of query associated with grid control. insert Optional No • Yes: user can insert row data in grid. Takes effect only if selectmode="edit" • No delete Optional No • Yes: user can delete row data from grid. Takes effect only if selectmode="edit" • No Name of grid element. cfgrid 153 154 Attribute Req/Opt Default Description sort Optional No The sort button performs simple text sort on column. User can sort columns by clicking column head or by clicking sort buttons. Not valid with selectmode=browse. • Yes: sort buttons display on grid control • No font Optional Font of column data in the grid control. fontSize Optional Size of text in the grid control, in points. italic Optional No • Yes: displays grid control text in italic • No bold Optional No • Yes: displays grid control text in bold • No textColor Optional Black Color of text in grid control; hex or text. 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. For a list of the supported named colors, see cfchart on page 70. href Optional URL o r query column name that contains a URL to hyperlink each grid cell with. hrefKey Optional The query column to use for the value appended to the href URL of each cell, instead of the cell's value. target Optional Target of href URL. appendKey Optional Yes • Yes: When used with href, appends "GFGRIDKEY=" and the value of the cell to each cell's URL. • No highlightHref Optional Yes • Yes: highlights links associated with a cfgrid with an href attribute value • No onValidate Optional A JavaScript function to validate user input. The form object, input object, and input object value are passed to routine, which returns True if validation succeeds; False otherwise. onError Optional A JavaScript function to execute if validation fails. gridDataAlign Optional Left • Left: left-aligns data within column. • Right: right-aligns data within column. • Center: center-aligns data within column. gridLines Optional Yes • Yes: enables row and column rules in grid control • No Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description rowHeight Optional rowHeaders Optional Yes • Yes: displays a column of numeric row labels in grid control • No rowHeaderAlign Optional Left • Left: left-aligns data within row header • Right: right-aligns data within row header • Center: center-aligns data within row header rowHeaderFont Optional Row label font. rowHeaderFontSize Optional Row label text size in grid control, in points. rowHeaderItalic Optional No • Yes: displays row label text in italic • No rowHeaderBold Optional No • Yes: displays row label text in bold • No rowHeaderTextColor Optional Black Text color of grid control row headers. • Options: same as for textColor attribute colHeaders Optional; Yes see description • Yes: displays column headers in grid control • No colHeaderAlign Optional • Left • Right • Center colHeaderFont Optional Font of column header in grid control. colHeaderFontSize Optional Size of column header text in grid control, in points. colHeaderItalic Optional No • Yes: displays column headers in italics • No colHeaderBold Optional No • Yes: displays column headers in bold • No colHeaderTextColor Optional Color of grid control column headers. • Options: same as for textColor attribute bgColor Optional Background color of grid control. • Options: same as for textColor attribute selectColor Optional Background color for a selected item. • Options: same as for textColor attribute Minimum row height, in pixels, of grid control. Used with cfgridcolumn type = "Image"; defines space for graphics to display in row. Left cfgrid 155 Attribute Req/Opt Default Description selectMode Optional Browse Selection mode for items in grid control. • Edit: user can edit grid data. Selecting a cell opens the editor for the cell type. • Single: user selections are limited to selected cell. • Row: user selections automatically extend to the row that contains selected cell. • Column: user selections automatically extend to column that contains selected cell. • Browse: user can only browse grid data maxRows Optional notSupported Optional (See Text to display if page that contains Java Description) applet-based cfform control is opened by a browser that does not support Java or has Java support disabled. Default: " Browser must support Java to view ColdFusion Java Applets" pictureBar Optional No • Yes: images for Insert, Delete, Sort buttons • No insertButton Optional Insert Insert button. Takes effect only if selectmode="edit". deleteButton Optional Delete Text of Delete button text. Takes effect only if selectmode="edit". sortAscendingButton Optional A -> Z Sort button text sortDescendingButton Optional Z -> A Sort button text Maximum number of rows to display in grid. Usage You can populate a cfgrid with data from a cfquery. If you do not specify any cfgridcolumn entries, ColdFusion generates a default set of columns, which includes each column in the query. A default header for each column is created by replacing hyphen or underscore characters in the table column name with spaces. The first character, and any character after a space, are changed to uppercase; all other characters are lowercase. This tag requires the client to download a Java applet; therefore, this tag might be slightly slower than using an HTML form element or the cfinput tag to get the same information. For this tag to work properly. the browser must be JavaScript-enabled. This tag requires an end tag. How data is returned from cfgrid This tag returns data by setting form variables in the data submitted to the form's action page, as an HTML form control does. Because the data can vary, depending on the tag’s SelectMode attribute value, the form variables that are returned also vary depending on this value. In general, the data returned falls into one of these categories: • Simple data, returned from simple select operations • Complex data, returned from insert, update and delete operations 156 Chapter 2: ColdFusion Tags Simple selection data (SelectMode = Single, Column, or Row) The data that form variables return to the cfform's action page contains information about which cells the user selected. In general, ColdFusion makes this data available in the action page, as ColdFusion variables in the Form scope, with the naming convention form.#GridName#.#ColumnName# Each SelectMode returns these form variable(s): • SelectMode="single" form.#GridName#.#ColumnName# = "SelectedCellValue" • SelectMode="column" form.#GridName#.#ColumnName# = "ValueOfCellRow1, ValueOfCellRow2, ValueOfCellRowN" • SelectMode="row" form.#GridName#.#Column1Name# = "ValueOfCellInSelectedRow" form.#GridName#.#Column2Name# = "ValueOfCellInSelectedRow" form.#GridName#.#ColumnNName# = "ValueOfCellInSelectedRow" Complex update data (SelectMode = Edit) The grid returns a large amount of data, to inform the action page of inserts, updates or deletes that the user made to the grid. In most cases, you can use the cfgridupdate tag to automatically gather the data from the form variables; the tag collects data, writes SQL calls, and updates the data source. If you cannot use cfgridupdate (if, for example, you must distribute the returned data to more than one data source), you must write code to read form variables. In this mode, ColdFusion creates the following array variables in the Form scope for each cfgrid: form.#GridName#.#ColumnName# form.#GridName#.original.#ColumnName# form.#GridName#.RowStatus.Action Each table row that contains an update, insert, or deletion has a parallel entry in each of these arrays. To view all the information for all the changes, you can traverse the arrays, as in this example:
form.#GridName#.#ColName#:
The form variable is not an array!
Result Array Size is #size#.
Contents:
The array is empty.
cfgrid 157

Loop Index Action Old Value New Value
#LoopCount# #Val_Action# #Val_Orig# #Val_New#
form.#GridName#.#ColName#: NotSet!
Using the href attribute When specifying a URL with grid items using the href attribute, the selectMode attribute value determines whether the appended key value is limited to one grid item or extends to a grid column or row. When a user clicks a linked grid item, a cfgridkey variable is appended to the URL, in this form: http://myserver.com?cfgridkey = selection If the appendKey attribute is set to No, no grid values are appended to the URL. The value of selection is determined by the value of the selectMode attribute: • If selectMode • If selectMode selection is the value of the column clicked. selection is a delimited list of column values in the clicked row, beginning with the value of the first cell in the row. • If selectMode = "Column", selection is a delimited list of row values in the clicked column, beginning with the value of the first cell in the column. Clicking the submit button while editing a grid cell occasionally causes the cell changes to be lost. To ensure that changes are submitted properly, Macromedia recommends that after user updates data in a cell, they click another cell before submitting the form. = "Single", = "Row", Example 158 Chapter 2: ColdFusion Tags SELECT Course_ID, Dept_ID, CorNumber, CorName, CorLevel, CorDesc FROM CourseList ORDER by Dept_ID ASC, CorNumber ASC cfgrid Example

cfgrid Example

Try adding a course to the database, and then deleting it. cfgrid 159 ... 160 Chapter 2: ColdFusion Tags cfgridcolumn Description Used with the cfgrid tag in a cfform. Use this tag to specify column data in a cfgrid control. The font and alignment attributes used in cfgridcolumn override global font or alignment settings defined in cfgrid. Category Forms tags Syntax See also cfgrid, cfgridrow, cfgridupdate, cfapplet, cfform, cfinput, cfselect, cfslider, cftextinput, cftree History ColdFusion MX: Changed behavior if select = "no": a user cannot select and edit the cell data, regardless of the cfgrid selectmode attribute value. When clicked, the cell border (and, depending on the selectColor value, the cell background) changes color, but the cell data cannot be edited. Attributes Attribute Req/Opt name Required header Optional Default Description Name of grid column element. If grid uses a query, column name must specify name of a query column. Yes Column header text. Used only if cfgrid colHeaders = "Yes". cfgridcolumn 161 Attribute Req/Opt Default Description width Optional; see Description Column head Column width, in pixels. width font Optional As specified by cfgrid Font of data in column. fontSize Optional As specified by cfgrid Size of text in column. italic Optional As specified by cfgrid • Yes: displays grid control text in italics • No bold Optional As specified by cfgrid • Yes: displays grid control text in bold • No textColor Optional Color of grid element text in column, or an expression to manipulate color; hex or text. To enter hex value, use the form "##xxxxxx", where x = 0-9 or A-F; use two pound signs or none. You can enter an expression; for example: textColor= "(C2 LT 0 ? red : pink)" This means: If value in Column 2 is less than 0, display value in red; otherwise, display value in pink. See “Using expressions in textColor and bgColor attributes” on page 164. • Any color, in hex format • Black • Red • Blue • Magenta • Cyan • Orange • Darkgray • Pink • Gray • White • Lightgray • Yellow 162 bgColor Optional Color of background of grid column, or an expression to manipulate color. See “Using expressions in textColor and bgColor attributes” on page 164. • Options: same as for textColor attribute href Optional URL o r query column name that contains a URL to hyperlink each grid column with. hrefKey Optional The query column to use for the value appended to the href URL of each column, instead of the column’s value. target Optional Frame in which to open link specified in href. Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description select Optional display Optional type Optional headerFont Optional as specified by cfgrid Column header font headerFontSize Optional as specified by cfgrid Column header text size, in pixels headerItalic Optional as specified by cfgrid • Yes: displays column header in italics • No headerBold Optional as specified by cfgrid • Yes: displays header in bold • No • Yes: user can select the column in grid control. • No: user cannot edit column, regardless of cfgrid insert and delete values. If cfgrid selectMode = "Row" or "Browse", this value is ignored. Yes • Yes • No: hides column • image: grid displays image that corresponds to value in column (a built-in ColdFusion image name, or an image in cfide\classes directory or subdirectory referenced with relative URL). If image is larger than column cell, it is clipped to fit. Built-in image names are as follows: - cd - computer - document - element - folder - floppy - fixed - remote • numeric: user can sort grid data numerically • boolean: column displays as check box; if cell is editable, user can change checkmark • string_noCase: user can sort grid data as case-insensitive text headerTextColor Optional Color of grid control column header text. • Options: same as for textColor attribute dataAlign Optional as specified by cfgrid Column data alignment: • Left • Right • Center headerAlign Optional as specified by cfgrid Column header text alignment: • Left • Right • Center numberFormat Optional Format for displaying numeric data in grid. See “numberFormat mask characters” on page 165. cfgridcolumn 163 Attribute Req/Opt values Optional Default Description Formats cells in column as drop-down list boxes; specify items in drop-down list. Example: values = "arthur, scott, charles, 1-20, mabel" valuesDisplay Optional valuesDelimiter Optional Maps elements in values attribute to string to display in drop-down list. Delimited strings and/or numeric range(s). , [comma] Delimiter in values and valuesDisplay attributes. Using expressions in textColor and bgColor attributes The textColor and bgColor attributes accept the following kinds of values: • A color value literal • A hex value • An expression that selects a text color based on the evaluation of a Boolean expression The syntax for an expression is as follows: (CX operator string ? true_condition : false_condition) The symbol meanings are as follows: • the column that contains the value to test. For the current column, use CX; if n is the column to evaluate, use Cn; for example, C2 • operator: One of these operators: EQ (equal), GT (greater than), LT (less than) • string: Value to compare against. A literal, such as (C2 EQ Johnson ? blue : green); or numeric: (C2 LT 0 ? red : black) • true_condition: Value for textColor if condition evaluates to "true" • false_condition: Value for textColor if condition evaluates to "false" If the string in the expression can be interpreted as a number, the comparisons in the expression are interpreted as numeric. Otherwise, the comparison is a string comparison. CX: This code shows an expression that displays the grid element in blue if the grid element contains the string "Pam"; or black, otherwise: This example displays the text in red if the value in column 1 is greater than four; or black, otherwise: 164 Chapter 2: ColdFusion Tags numberFormat mask characters You can use the following numberFormat attribute mask characters, which correspond to those in the NumberFormat function, to format output in U.S. numeric and currency styles. For more information, see NumberFormat on page 631. (This tag does not support international number formatting.) Character Meaning _ (Underscore) Digit placeholder. 9 Digit placeholder. . (Period) Location of mandatory decimal point. 0 Located to left or right of mandatory decimal point; pads with zeros. () Puts parentheses around mask if number is less than 0. + Puts plus sign before positive numbers, minus sign before negative numbers. - Puts space before positive numbers, minus sign before negative numbers. , (Comma) Separates every third decimal-place with a comma. L,C Left-justify or center-justify number within width of mask column. First character of mask must be L or C. Default: right-justified. $ Puts dollar sign before formatted number. Must be the first character of mask. ^ (Caret) Separates left from right formatting. Example For a code example, see cfgrid on page 152. cfgridcolumn 165 cfgridrow Description Lets you define a cfgrid that does not use a query as source for row data. If a query attribute is specified in cfgrid, the cfgridrow tags are ignored. Category Forms tags Syntax See also cfgrid, cfgridcolumn, cfgridupdate, cfapplet, cfform, cfinput, cfselect, cfslider, cftextinput, cftree Attributes Attribute Req/Opt Default Description data Required Delimited list of column values. If a value contains a comma, it must be escaped with another comma. Usage The following code shows how to populate a grid from a list with the cfgridrow tag: Example For a code example, see cfgrid on page 152. The following example populates two grids from the results of a query, as follows: • One uses cfgridrow within the cfquery tag, using the query to generate rows • One uses cfgridrow outside the cfquery tag, using a cfloop tag to generate rows. 166 Chapter 2: ColdFusion Tags select Course_ID, Dept_ID, CorNumber, CorName, CorLevel, CorDesc FROM CourseList ORDER by Dept_ID ASC, CorNumber ASC cfgridrow example

cfgridrow Example

Try adding a course to the database, and then deleting it.

Example Two

cfgridrow 167

This grid shows how the same grid can be built using cfgridrow with cfloop (i.e., defining query external to cfgrid, rather than within cfgrid).

168 Chapter 2: ColdFusion Tags cfgridupdate Description Used within a cfgrid tag. Updates data sources directly from edited grid data. This tag provides a direct interface with your data source. This tag applies delete row actions first, then insert row actions, then update row actions. If it encounters an error, it stops processing rows. Category Forms tags Syntax See also cfgrid, cfgridcolumn, cfgridrow, cfapplet, cfform, cfinput, cfselect, cfslider, cftextinput, cftree History ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5. Attributes Attribute Req/Opt Default Description grid Required Name of cfgrid form element that is the source for the update action. dataSource Required Name of data source for the update action. tableName Required Name of table to update. For ORACLE drivers, entry must be upper-case. For Sybase driver, entry is case-sensitive; must be same case as used when table was created username Optional Overrides username value specified in ODBC setup. password Optional Overrides password value specified in ODBC setup. tableOwner Optional Table owner, if supported. cfgridupdate 169 Attribute Req/Opt tableQualifier Optional keyOnly Default Description Table qualifier, if supported. Purpose: • SQL Server and Oracle driver: name of database that contains table • Intersolv dBASE driver: directory of DBF files No Applies to the update action: • Yes: the WHERE criteria are limited to the key values • No: the WHERE criteria include key values and the original values of changed fields Example ... ... 170 Chapter 2: ColdFusion Tags cfheader Description Generates custom HTTP response headers to return to the client. Category Data output tags, Page processing tags Syntax or See also cfcache, cfflush, cfhtmlhead, cfinclude, cfsetting, cfsilent, cfcontent History ColdFusion MX 6.1: Changed behavior for the name attribute: cfheader name="Content-Disposition" uses the default file character encoding to encode this header's value, so the name of a file can include characters in the character encoding used in the file. Attributes Attribute Req/Opt Default name Required if statusCode not specified Header name value Optional HTTP header value charset Optional UTF-8 Description The character encoding in which to encode the header value. The following list includes commonly used 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 more information character encodings, see: www.w3.org/International/O-charset.html. cfheader 171 Attribute Req/Opt Default Description statusCode Required if name not specified Number. HTTP status code statusText Optional Explains status code Usage If you use this tag after the cfflush tag on a page, an error is thrown. Example

cfheader Example

cfheader generates custom HTTP response headers to return to the client.

This example forces browser client to purge its cache of requested file. 172 Chapter 2: ColdFusion Tags cfhtmlhead Description Writes text to the head section of a generated HTML page. It is useful for embedding JavaScript code, or putting other HTML tags, such as meta, link, title, or base in an HTML page header. Category Page processing tags Syntax See also cfcache, cfflush, cfheader, cfheader, cfinclude, cfsetting, cfsilent Attributes Attribute Req/Opt text Required Default Description Text to add to the area of an HTML page. Usage If you use this tag after the cfflush tag on a page, an error is thrown. Example ">

cfhtmlhead writes the text specified in the text attribute to the <HEAD>section of a generated HTML page. cfhtmlhead can be useful for embedding JavaScript code, or placing other HTML tags such as META, LINK, TITLE, or BASE in an HTML header.

View the source of this frame to see that the title of the page is generated by the cfhtmlhead tag. cfhtmlhead 173 cfhttp Description Generates an HTTP request and handles the response from the server. Category Forms tags, Internet Protocol tags Syntax cfhttpparam tags [optional for some methods] See also cfhttpparam, GetHttpRequestData, cfftp, cfldap, cfmail, cfpop, SetEncoding History ColdFusion MX 6.1: • • • • • • • • 174 Added support for the following methods: HEAD, PUT, DELETE, OPTIONS, TRACE. Added multipart, getAsBinary, proxyUser, and proxyPassword attributes. Changed httpparam behavior: All operations can have httpparam tags. Added cfhttp.errorDetail return variable. Modified response body content types considered to be text Changed behavior for multiple headers: multiple headers of the same type are returned in an array. Added support for HTTPS proxy tunneling. Fixed bugs in code and documentation. Chapter 2: ColdFusion Tags ColdFusion MX: • Added the charset and firstrowasheaders attributes. • Changed Secure Sockets Layer (SSL) support: ColdFusion uses the Sun JSSE library, which supports 128-bit encryption, to support SSL. Attributes The following attributes control the HTTP transaction and can be used for all HTTP methods: Attribute Req/Opt Default Description url Req Uses the http protocol Address of the resource on the server which will handle the request. The URL must include the hostname or IP address. If you do not specify the transaction protocol (http:// or https://), ColdFusion defaults to http. If you specify a port number in this attribute, it overrides any port attribute value. The cfhttppparam tag URL attribute appends query string attribute-value pairs to the URL. port Opt 80 for http Port number on the server to which to send the request. A port value in the url attribute overrides this value. 413 for https method Opt GET proxyServer Opt proxyPort Opt • GET Requests information from the server. Any data that the server requires to identify the requested information must be in the URL or in cfhttp type="URL" tags. • POST Sends information to the server for processing. Requires one or more cfhttpparam tags. Often used for submitting form-like data. • PUT Requests the server to store the message body at the specified URL. Use this method to send files to the server. • DELETE Requests the server to delete the specified URL. • HEAD Identical to the GET method, but the server does not send a message body in the response. Use this method for testing hypertext links for validity and accessibility, determining the type or modification time of a document, or determining the type of server. • TRACE Requests that the server echo the received HTTP headers back to the sender in the response body. Trace requests cannot have bodies. This method enables the ColdFusion application to see what is being received at the server, and use that data for testing or diagnostic information. • OPTIONS A request for information about the communication options available for the server or the specified URL. This method enables the ColdFusion application to determine the options and requirements associated with a URL, or the capabilities of a server, without requesting any additional activity by the server. Host name or IP address of a proxy server to which to send the request. 80 Port number to use on the proxy server. cfhttp 175 176 Attribute Req/Opt Default Description proxyUser Opt User name to provide to the proxy server. proxyPassword Opt Password to provide to the proxy server. username Opt A username. May be required by server. password Opt A password. May be required by server userAgent Opt Cold Fusion Text to put in the user agent request header. Used to identify the request client software. Can make the ColdFusion application appear to be a browser. charset Opt For request: UTF-8 For response: charset specified by response ContentType header, or UTF-8 if response does not specify charset. The character encoding of the request, including the URL query string and form or file data, and the response. The following list includes commonly used 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 more information character encodings, see: www.w3.org/International/O-charset.html. resolveURL Opt No • No does not resolve URLs in the response body. As a result, any relative URL links in the response body do not work. • Yes resolves URLs in the response body to absolute URLs, including the port number, so that links in a retrieved page remain functional. Applies to these HTML tags: - img src - a href - form action - applet code - script src - embed src - embed pluginspace - body background - frame src - bgsound src - object data - object classid - object codebase - object usemap Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description throwOnError Opt No • Yes if the server returns an error response code, throws an exception that can be caught using the cftry and cfcatch or ColdFusion error pages. • No does not throw an exception if an error response is returned. In this case, your application can use the cfhttp.StatusCode variable to determine if there was an error and its cause. redirect Opt Yes If the response header includes a Location field, determines whether to redirect execution to the URL specified in the field. • Yes redirects execution to the specified page. • No stops execution and returns the response information in the cfhttp variable, or throws an error if the throwOnError attribute is True. The cfhttp.responseHeader.Location variable contains the redirection path. ColdFusion follows a maximum of four redirects on a request. If there are more, ColdFusion functions as if redirect ="no". timeout Opt getAsBinary Opt Value, in seconds of the maximum time the request can take. If the timeout passes without a response, ColdFusion considers the request to have failed. If the client specifies a timeout in the URL search parameter (for example, ?RequestTime=120) ColdFusion uses the lesser of the URL timeout and the timeout attribute value; this ensures that the request times out before, or at the same time as, the page. If the URL does not specify a timeout, ColdFusion uses the lesser of the Administrator timeout and the timeout attribute value. If the timeout is not set in any of these, ColdFusion waits indefinitely for the cfhttp request to process. No • No If ColdFusion does not recognize the response body type as text, convert it to a ColdFusion object. • Auto If ColdFusion does not recognize the response body type as text, convert it to ColdFusion Binary type data. • Yes Always convert the response body content into ColdFusion Binary type data, even if ColdFusion recognizes the response body type as text. ColdFusion recognizes the response body as text if: • the header does not specify a content type • the content type starts with "text" • the content type starts with "message" • the content type is "application/octet-stream" If ColdFusion does not recognize the body as text and converts it to an object, but the body consists of text, the cfoutput tag can display it. The cfoutput tag cannot display Binary type data. (To convert binary data to text, use the ToString function.) cfhttp 177 The following attribute is used with the PUT method to determine how to send data specified with httpparam type="formField": Attribute Req/Opt Default Description multipart Optional Tells ColdFusion to send all data specified by cfhttpparam type="formField" tags as multipart form data, with a No (Sends as multipart only if request includes File type data.) Content-Type of multipart/form-data. By default, ColdFusion sends cfhttp requests that contain only formField data with a Content Type of application/x-www-form-urlencoded. (If the request also includes File type data, ColdFusion uses the multipart/form-data content type for all parts.) If Yes, ColdFusion also sends the request’s charset in each Content-Type description. All form field data must be encoded in this character encoding, and ColdFusion does not URLEncode the data. (The field name must be in ISO-88591-1 or ASCII.) Some http parsers, including the one used by previous versions of ColdFusion, ignore the multipart form field character encoding description. The following attributes tell ColdFusion to put the HTTP response body in a file. You can put the response body in a file for GET, POST, PUT, DELETE, OPTIONS, and TRACE methods, but it is generally not useful with DELETE or OPTIONS. 178 Attribute Req/Opt Default Description path Required if file is specified. Tells ColdFusion to save the HTTP response body in a file. Contains the absolute path to the directory in which to store the file. file Required See if path is Description specified and not a GET method Name of file in which to store the response body. For a GET operation, defaults to the file requested in the URL, if there is one. For example, if the URL in a GET method is http:www.myco.com/test.htm, the default file is test.htm. Do not specify the path to the directory in this attribute, use the path attribute. Chapter 2: ColdFusion Tags The following attributes tell ColdFusion to convert the HTTP response body into a ColdFusion query object. They can be used with the GET and POST methods only: Attribute Req/Opt Default Description name Opt Tells ColdFusion to create a query object with the given name from the returned HTTP response body. columns Opt First row of response contains column names. The column names for the query, separated by commas. Column names must start with a letter. The remaining characters can be letters, numbers, or underscores (_). If there are no column name headers in the response, specify this attribute to identify the column names. If you specify this attribute and the firstrowasHeader attribute is true (the default), the column names specified by this attribute replace the first line of the response. You can use this behavior to replace the column names retrieved by the request with your own names. If a duplicate column heading is encountered in either this attribute or in the column names from the response, ColdFusion appends an underscore to the name to make it unique. If the number of columns specified by this attribute does not equal the number of columns in the HTTP response body, ColdFusion generates an error. firstrowas headers Opt Yes Determines how ColdFusion processes the first row of the query record set. • Yes processes the first row as column heads. If you specify a columns attribute, ColdFusion ignores the first row of the file. • No processes the first row as data. If you do not specify a columns attribute, ColdFusion generates column names by appending numbers to the word "column"; for example, "column_1". delimiter Opt , [comma] A character that separates query columns. The response body must use this character to separate the query columns. textQualifier Opt " [double quotation mark] A character that, optionally, specifies the start and end of a text column. This character must surround any text fields in the response body that contain the delimiter character as part of the field value. To include this character in column text, escape it by using two characters in place of one. For example, if the qualifier is a double quotation mark, escape it as "". Usage The cfhttp tag is a general-purpose tool for creating HTTP requests and handling the returned results. It enables you to generate most standard HTTP request types. You use embedded cfhttpparam tags to specify request headers and body content. When ColdFusion receives a response to a cfhttp request, it can put the response body (if any) in a file or the cfhttp.FileContent string variable. If the body text is structured as a result set, ColdFusion can put the body text in query object. You can also access the values of all returned headers and specify how to handle error status and redirections, and specify a timeout to prevent requests from hanging. cfhttp 179 The HTTP protocol is the backbone of the World Wide Web and is used for every web transaction. Because the cfhttp tag can generate most types of requests, it provides significant flexibility. Possible uses include: • Interacting with dynamic web sites and services that are not available as web services. (Use the the cfinvoke tag to access SOAP web services.) • Getting the contents of an HTML page or other file such as an image on a web server for use in your CFML page or storage in a file. • Sending a secure request to a server by specifying the https protocol in the url attribute. • Using the POST method to send a multipart/form-data style post to any URL that can handle such data and return results, including CGI executables or even other ColdFusion pages. • Using the PUT method to upload files to a server that does not accept FTP requests. This tag can, and for PUT and POST requests must, have a body that contains cfhttpparam tags. If this tag has cfhttpparam tags, it must have a end tag. Variables returned by a cfhttp get operation The cfhttp tag returns the following variables: 180 Name Description cfhttp.charSet Response character character set (character encoding) specified by the response Content-Type header. cfhttp.errorDetail If the connection to the HTTP server fails, contains details about the failure. For instance: "Unknown host: my.co.com"; otherwise, the empty string cfhttp.fileContent Response body; for example, the contents of a html page retrieved by a GET operation. Empty if you save the response in a file. cfhttp.header Raw response header containing all header information in a single string. Contains the same information as the cfhttp.responseHeader variable. cfhttp.mimeType MIME type specified by the response Content-Type header; for example, text/html. cfhttp.responseHeader The response headers formatted into a structure. Each element key is the header name, such as Content-Type or Status_Code. If there is more than one instance of a header type, the type values are put in an array. One common technique is to dynamically access the cfhttp.responseHeader structure as a dynamic array; for example, #cfhttp.resonseHeader[fieldVariable]#. cfhttp.statusCode The HTTP status_code header value followed by the HTTP Explanation header value, for example "200 OK". cfhttp.text Boolean; True if the response body content type is text. ColdFusion recognizes the response body as text if: • the header does not specify a content type • the content type starts with "text" • the content type starts with "message" • the content type is "application/octet-stream" Chapter 2: ColdFusion Tags Building a query from a delimited text file The cfhttp tag can create a ColdFusion query object form the response body. To do so, the response body must consist of lines of text, with each line having fields that are delimited by a character that identifies the column breaks. The default delimiter is a comma (,). The response data can also use a text qualifier; the default is a double quotation mark ("). If you surround a string field in the text qualifier, the field can contain the delimiter character. To include the text qualifier in field text, escape it by using a double character. The following line shows a two-line request body that is converted into a query. It has three comma-delimited fields: Field1,Field2,Field3 "A comma, in text","A quote: ""Oh My!""",Plain text Run the following code to show how ColdFusion treats this data:
Column names can be specified in three ways: • By default, ColdFusion uses the first row of the response as the column names. • If you specify a comma-delimited columns attribute, ColdFusion uses the names specified in the attribute as the column names. Set firstRowAsHeaders="No" if the first row of the response contains data. Otherwise, ColdFusion ignores the first row. • If you do not specify a columns attribute and set firstrowasheaders="No", ColdFusion generates column names of the form Column_1, Column2, etc. The cfhttp tag checks to ensure that column names in the data returned by the tag start with a letter and contain only letters, numbers, and underscores (_). ColdFusion checks for invalid column names. Column names must start with a letter. The remaining characters can be letters, numbers, or underscores (_). If a column name is not valid, ColdFusion generates an error. Notes • For the ColdFusion MX Administrator timeout and the URL timeout to take effect, you must • • • • enable the timeout in the ColdFusion MX Administrator, Server Settings page. For more information, see Configuring and Administering ColdFusion MX. The cfhttp tag supports Basic Authentication for all operations. However, Basic Authentication does not work if your web server has Windows NT Challenge/Response (Microsoft IIS) enabled. The cfhttp tag uses SSL to negotiate secure transactions. If you put the HTTP response body in a file, ColdFusion does not put it in the CFHTTP.FileContent variable or generate a query object. If you do not put the response body in a file, ColdFusion puts it in the CFHTTP.FileContent variable; if you specify a name attribute ColdFusion generates a query object. The cfhttp tag does not support NTLM or Digest Authentication with proxy servers. If a proxy server requires authentication, it must allow Basic Authentication. Example #item.title.xmltext#
Author  #item.author.xmltext#
Applies to these products
#item.xmlChildren[i].xmlAttributes.Name#

182 Chapter 2: ColdFusion Tags cfhttpparam Description Allowed inside cfhttp tag bodies only. Required for cfhttp POST operations. Optional for all others. Specifies parameters to build an HTTP request. Category Forms tags, Internet Protocol tags Syntax See also cfhttp, GetHttpRequestData, cfftp, cfldap, cfmail, cfmailparam, cfpop History ColdFusion MX 6.1: • • • • Added the header and body types. Added the encoded, and mimeType attributes. Changed HTTP method behavior: all HTTP methods can have httpparam tags. Changed the name attribute requirements: it is not required for all types. cfhttpparam 183 Attributes Attribute Req/Opt Default type Required Information type: • Header: The parameter specifies an HTTP header. ColdFusion does not URL encode the header. • CGI: Specifies an HTTP header. ColdFusion URL encodes the header by default. • Body: Specifies the body of the HTTP request. ColdFusion does not URL encode the body contents. • XML: Identifies the request as having a content-type of text/xml. Specifies that the value attribute contains the body of the HTTP request. Used to send XML to the destination URL. ColdFusion does not URL encode the XML data. • File: Tells ColdFusion to send the contents of the specified file. ColdFusion does not URL encode the file contents • URL: Specifies a URL query string name-value pair to append to the cfhttp url attribute. ColdFusion URL encodes the query string. • FormField: Specifies a form field to send. ColdFusion URL encodes the Form field by default. • Cookie: Specifies a cookie to send as an HTTP header. ColdFusion URL encodes the cookie. name Required. Optional for Body and XML types Variable name for data that is passed. Ignored for Body and XML types. For File type, specifies the filename to send in the request. value Required Optional (and ignored) for File type Value of the data that is sent. Ignored for File type. The value must contain string data or data that ColdFusion can convert to a string for all type attributes except Body. Body types can have string or binary values. file Required only if type="File" Applies to File type; ignored for all other types. The absolute path to the file that is sent in the request body. encoded Optional Yes mimeType Optional Description Applies to FormField and CGI types; ignored for all other types. Specifies whether to URLEncode the form field or header. Applies to File type; invalid for all other types. Specifies the MIME media type of the file contents. The content type can include an identifier for the character encoding of the file; for example, text/html; charset=ISO-8859-1 indicates that the file is HTML text in the ISO Latin-1 character encoding. Usage Specifies header or body data to send in the HTTP request. The type attribute identifies the information that the parameter specifies. A cfhttp tag can have multiple cfhttpparam tags, subject to the following limitations: • An XML type attribute cannot be used with additional XML type attributes, or with body, file, or formField type attributes. 184 Chapter 2: ColdFusion Tags • A body type attribute cannot be used with additional body type attributes, or with XML, file, or formField type attributes. • The XML and body type attributes cannot be used with the cfhttp tag TRACE method. • The file type attribute is only meaningful with the cfhttp tag POST and PUT methods. • The formField type attribute is only meaningful with the cfhttp tag POST and GET methods. If you send an HTTP request to a ColdFusion page, all HTTP headers, not just those sent using the CGI type, are available as CGI scope variables, However, any custom variables (such as "myVar") do not appear in a dump of the CGI scope. When you send a file using the type="file" attribute, the file content is sent in the body of a multipart/form-data request. If you send the file to a ColdFusion page, the Form scope of the receiving page contains an entry with the name you specified in the cfhttpparam tag name attribute as the key. The value of this variable is the path to a temporary file containing the file that you sent. If you also send Form field data, the location of the filename in the form.fieldnames key list depends on the position of the cfhttpparam tag with the file relative to the cfhttp tags with the form data. URL-encoding preserves special characters (such as the ampersand) when they are passed to the server. For more information, see the function URLEncodedFormat on page 731. Example #cfhttp.fileContent#

Output the passed variables

Form variable: #form.form_test#
URL variable: #URL.url_test#
Cookie variable: #Cookie.cookie_test# cfhttpparam 185
CGI variable: #CGI.cgi_test#

Note that the CGI variable is URL encoded.
186 Chapter 2: ColdFusion Tags cfif Description Creates simple and compound conditional statements in CFML. Tests an expression, variable, function return value, or string. Used, optionally, with the cfelse and cfelseif tags. Category Flow-control tags Syntax HTML and CFML tags HTML and CFML tags HTML and CFML tags See also cfelse, cfelseif, cfabort, cfbreak, cfexecute, cfexit, cflocation, cfloop, cfswitch, cfthrow, cftry Usage If the value of the expression in the cfif tag is True, ColdFusion processes all the code that follows, up to any cfelseif or cfelse tag, and then skips to the cfif end tag. Otherwise, ColdFusion does not process the code that immediately follows the cfif tag, and continues processing at any cfelseif or cfelse tag, or with the code that follows the cfif end tag. When testing the return value of a function that returns a Boolean, you do not have to define the True condition explicitly. This example uses the IsArray function: If successful, IsArray evaluates to Yes, the string equivalent of the Boolean True. This is preferred over explicitly defining the True condition this way: This tag requires an end tag. Example In this example, variables are shown within pound signs. This is not required. SELECT Center_ID, Name, Address1, Address2, City, State, Country, PostalCode, Phone, Contact FROM Centers ORDER by City, State, Name

CFIF gives us the ability to perform conditional logic based on a condition or set of conditions.

For example, we can output the list of Centers from the snippets datasource by group and only display them IF City = San Diego.


The following centers are in San Diego: cfif 187
Name/Address:#Name#, #Address1#, #City#, #State#
Contact: #Contact#


If we would like more than one condition to be the case, we can ask for a list of the centers in San Diego OR Santa Ana. If the center does not follow this condition, we can use CFELSE to show only the names and cities of the other centers.

Notice how a nested CFIF is used to specify the location of the featured site (Santa Ana or San Diego).

Complete information is shown for centers in San Diego or Santa Ana. All other centers are listed in italics:

Featured Center in San Diego Santa Ana

Name/Address:#Name#, #Address1#, #City#, #State#
Contact: #Contact#

#Name#, #City#

Finally, we can use CFELSEIF to cycle through a number of conditions and produce varying output. Note that you can use CFCASE and CFSWITCH for a more elegant representation of this behavior.


#Name#, #City# (this one is in San Diego Santa Ana )
#Name#, #City# (this one is in San Francisco)
#Name#, #City# (this one is in Suisun)
#Name# Not in a city we track
188 Chapter 2: ColdFusion Tags cfimpersonate 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. cfimpersonate 189 cfimport Description You can use the cfimport tag to import either of the following: • All ColdFusion pages in a directory, as a tag custom tag library. • A Java Server Page (JSP) tag library. A JSP tag library is a packaged set of tag handlers that conform to the JSP 1.1 tag extension API. Category Application framework tags Syntax See also cfapplication History ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description taglib Required Tag library URI. The path must be relative to the web root (and start with /), the current page location, or a directory specified in the Administrator ColdFusion mappings page. • A directory in which custom ColdFusion tags are stored. In this case, all the cfm pages in this directory are treated as custom tags in a tag library. • A path to a JAR in a web-application; for example, "/WEB-INF/lib/sometags.jar" • A path to a tag library descriptor; for example, "/sometags.tld" Note: You must put JSP custom tag libraries in the /WEB-IN/lib directory. This limitation does not apply to ColdFusion pages. prefix Required Prefix by which to access the imported custom CFML tags JSP tags. If you import a CFML custom tag directory and specify an empty value, "", for this attribute, you can call the custom tags without using a prefix. You must specify and use a prefix for a JSP tag library. Usage The following example imports the tags from the directory myCustomTags: You can import multiple tag libraries using one prefix. If there are duplicate tags in a library, the first one takes precedence. 190 Chapter 2: ColdFusion Tags JSP tags have fixed attributes; however, if the tag supports runtime attribute expressions, most tag libraries support the use of the syntax #expressions#. To reference a JSP tag in a CFML page, use the syntax . Set the prefix value in the prefix attribute. To use JSP custom tags in a ColdFusion page, follow these steps: 1 Put a JSP tag library JAR file (for example, myjsptags.jar) into the ColdFusion server directory wwwroot/WEB-INF/lib. If the tag library has a separate TLD file, put it in the same directory as the JAR file. 2 At the top of a CFML page, insert code such as the following: To reference a JSP tag from a JAR file, use the following syntax: The cfimport tag must be on the page that uses the imported tags. For example, if you use a cfimport tag on a page that you include with the cfinclude call, you cannot use the imported tags on the page that has the cfinclude tag. Similarly, if you have a cfimport tag on your Application.cfm page, the imported tags are available on the Application.cfm page only, not on the other pages in the application. ColdFusion does not throw an error in these situations, but the imported tags do not run. You cannot use the cfimport tag to suppress output from a tag library. For more information, see the Java Server Page 1.1 specification. Example

cfimport example

This example uses the random JSP tag library that is available from the Jakarta Taglibs project, at http://jakarta.apache.org/taglibs/ Your password is #myPassword#
cfimport 191 cfinclude Description Embeds references to ColdFusion pages in CFML. You can embed cfinclude tags recursively. For another way to encapsulate CFML, see cfmodule on page 250. (A ColdFusion page was formerly sometimes called a ColdFusion template or a template.) Category Flow-control tags, Page processing tags Syntax See also cfcache, cfflush, cfheader, cfhtmlhead, cfsetting, cfsilent History ColdFusion MX: Changed error behavior: if you use this tag to include a CFML page whose length is zero bytes, you do not get an error. Attributes Attribute Req/Opt template Required Default Description A logical path to a ColdFusion page. Usage ColdFusion searches for included files in the following sequence: 1 In the directory of the current page 2 In directories mapped in the ColdFusion Administrator for the included file The included file must be a syntactically correct and complete CFML page. For example, to output data from within the included page, you must have a cfoutput tag, including the end tag, on the included page, not the referring page. Similarly, you cannot span a cfif tag across the referring page and the included page; it must be complete within the included page. Example

This example includes the main.htm page from the CFDOCS directory. The images do not display, because they are located in a separate directory. However, the page appears fully rendered within the contents of this page.

192 Chapter 2: ColdFusion Tags cfindex Description Populates a Verity search engine collection with an index of documents on a file system or of ColdFusion query result sets. A collection must exist before it can be populated. A collection can be indexed in the following ways: • In ColdFusion, with the cfindex tag • In the ColdFusion Administrator, which calls the cfindex tag • Using a native Verity indexing tool, such as Vspider or MKVDK For more information, see Chapter 24, “Building a Search Interface,” in Developing ColdFusion MX Applications. Category Extensibility tags Syntax See also cfcollection, cfexecute, cfobject, cfreport, cfsearch, cfwddx History ColdFusion MX: • The action attribute value optimize is obsolete. It does not work, and might cause an error, • • • • • in ColdFusion MX. Changed the external attribute behavior: it is not necessary to specify the external attribute. (ColdFusion automatically detects whether a collection is internal or external.) Changed Verity operations behavior: ColdFusion supports Verity operations on Acrobat PDF files. Changed thrown exceptions: this tag can throw the SEARCHENGINE exception. Changed acceptable collection naming: this tag accepts collection names that include spaces. Changed query result behavior: the cfindex tag can index the query results from a cfsearch tag. cfindex 193 Attributes Attribute Req/Opt collection Required Default Description • Name of a collection that is registered by ColdFusion; for example, "personnel" • Name and absolute path of a collection that is not registered by ColdFusion; for example: "e:\collections\personnel" action • update: updates a collection and adds key to the index. Do not use the cflock tag with this option. • delete: deletes data in the entities specified by the type attribute • purge: deletes all keys from a collection • refresh: purges all keys from a collection, then updates it. Depends on collection attribute value; see Usage section type Optional custom, if query attribute is specified. file, otherwise. title key Optional Depends on action • Title for collection • Query column name for type and a valid query name Permits searching collections by title or displaying a separate title from the key (empty string) attribute value; see Usage section body Required if • Absolute path and filename, if type = "file" • Absolute path, if type = "path" • A query column name (typically, the primary key column name), if type = "custom" • A query column name, if type = any other value This attribute is required for the actions listed, unless you intend for its value to be an empty string. • ASCII text to index • Query column name(s), if name is specified in query You can specify columns in a delimited list. For example: type = "custom"; see Usage section "emp_name, dept_name, location" custom1 Optional Custom field in which you can store data during an indexing operation. Specify a query column name for type, and a query name. custom2 Optional Usage is the same as for custom1. URLpath Optional If type="file" or "path", specifies the URL path. When the collection is searched with cfsearch, this pathname is prefixed to filenames and returned as the url attribute. extensions Optional 194 • file: using the key attribute value of the query result as input, applies action value to filenames or filepaths. • path: using the key attribute value of the query result as input, applies action to filenames or filepaths that pass the extensions filter • custom: If action = "update" or "delete": applies action to custom entities in query results. HTM, HTML, CFM, CFML, DBM, DBML Chapter 2: ColdFusion Tags Delimited list of file extensions that ColdFusion uses to index files, if type = "Path". "*." returns files with no extension. For example: the following code returns files with a listed extension or no extension: extensions = ".htm, .html, .cfm, .cfml, "*." Attribute Req/Opt query Required if Default Description Query against which collection is generated type = "custom"; see Usage section recurse Optional No • Yes: if type = "path", directories below the path specified in key are included in indexing operation • No language Optional English For options, see cfcollection on page 80. Requires the appropriate (European or Asian) Verity Locales language pack. Usage This tag populates Verity search engine collections with metadata from the following sources: • Documents stored on a file system • ColdFusion query result sets The following table shows the dependent relationships among this tag’s attribute values: For this action attribute value: Specifying this attribute is delete required, optional purge or unnecessary (blank): update or refresh collection Required Required Optional If type = "file", "path", or "custom": Optional. type Required title If type = "file", "path", or "custom": Optional. Otherwise: unnecessary. key Required If type = "file", "path", or "custom": Required. Otherwise: unnecessary. body If type = "custom": Required. Otherwise: unnecessary. custom1 If type = "file", "path", or "custom": Optional. Otherwise: unnecessary. custom2 If type = "file", "path", or "custom": Optional. Otherwise: unnecessary. URLPath If type = "file" or "path": Optional. Otherwise: unnecessary. extensions If type = "path": Optional. Otherwise: unnecessary. cfindex 195 For this action attribute value: Specifying this attribute is delete required, optional purge or unnecessary (blank): query recurse language update or refresh If type = "file", "path": If type = "file","path": Optional. Optional. If type = "custom": Required. If type = "custom": Required. If type = "path": Optional. Otherwise: unnecessary. If If type = "file", "path", If type = "file", "path", or or "custom": Optional. "custom": Optional. For all action values of this tag except update, use the cflock tag to protect the collection during tag execution. For information on the file types you can use with the Verity search engine, see Article 22492, ColdFusion Server (versions 4.5 and higher): Supported File Types for Verity, on the Macromedia ColdFusion Support Center, at www.macromedia.com/support/coldfusion/. Example select *from book where bookid='file' --#url#,#description#--
select * from book where bookid='path1' or bookid='path2' --#url#,#description#--
select * from book select * from book select * from book where bookid='file' --#description#--
select * from book where bookid='path1' --#url#,#description#--
select * from book where bookid='bookid1' cfindex 199 200 Chapter 2: ColdFusion Tags cfinput Description Used within the cfform tag, to place radio buttons, check boxes, or text boxes on a form. Provides input validation for the specified control type. Category Forms tags Syntax See also cfapplet, cfform, cfgrid, cfselect, cfslider, cftextinput, cftree History ColdFusion MX 6.1: Changed the requirements for the validate = "creditcard" option: it requires that the text entry have 13-16 digits. ColdFusion MX: Changed the cfform tag preserveData attribute behavior: if it is set to True, ColdFusion checks radio and check box values only if their value matches the posted value for the control. (In earlier releases, if the posted value did not match any of the cfinput check boxes or radio buttons for the control, the checked attribute was used. Attributes Attribute Req/Opt Default Description type Optional text name Required Name for form input element. value Optional Initial value for form input element. required Optional range Optional No • • • • text: creates a text entry box control radio: creates a radio button control checkbox: creates a check box control password: creates a password entry control • Yes • No Minimum and maximum value range, separated by a comma. If type = "text" or "password", this applies only to numeric data. cfinput 201 Attribute Req/Opt Default Description validate Optional Verifies a value’s format: • date: US date mm/dd/yyyy • eurodate: European date dd/mm/yyyy • time: time hh:mm:ss • float: floating point entry • integer: integer entry • telephone: telephone ###-###-####. Separator: hyphen or blank. Area code and exchange must begin with a digit 1 – 9. • zipcode: (U.S. formats only) 5-digit ##### or 9-digit #####-####. Separator: hyphen or blank. • creditcard: must be a 13 to 16 digit integer after stripping blanks and dashes; uses the mod10 algorithm. • social_security_number: ###-##-####. Separator: hyphen or blank. • regular_expression: matches input against regular expression specified by the pattern attribute. onValidate Optional Custom JavaScript function to validate user input. The form object, input object, and input object values are passed to the routine, which should return True if validation succeeds, and False otherwise. If used, the validate attribute is ignored. pattern Required if validate = "regular_ expression" JavaScript regular expression pattern to validate input. Omit leading and trailing slashes. For examples and syntax, see Chapter 27, “Building Dynamic Forms,” in Developing ColdFusion MX Applications. message Optional Message text to display if validation fails. onError Optional Custom JavaScript function to execute if validation fails. size Optional Size of input control. Ignored, if type = "radio" or "checkbox". maxLength Optional Maximum length of text entered, if type = "Text" or "password". checked Optional passThrough Optional Selects a control. No value is required. Applies if type = "radio" or "checkbox". Optional: you can enter the following values: • true (equivalent to checked) • false (equivalent to omitting the attribute) Passes one or more arbitrary attribute-value pairs to the HTML code that is generated for the tag. You can use either of the following formats to include the quotation marks around the attribute value: passthrough="ID=""myID""" passthrough=’ID="myID"’ The second format, which surrounds all the attribute-value pairs to be passed through in single quotation marks is clearer, particularly when you pass multiple HTML attributes. In addition to the listed attributes, you can use the following HTML attributes in the cfform tag without using the passThrough attribute. The tag does not use these attributes, but includes them in the HTML of the form tag that it generates and returns to the browser: 202 Chapter 2: ColdFusion Tags • • • • • • • • • class id onBlur onChange onClick onDblclick onFocus style tabIndex Usage If the cfform preserveData attribute is true and the form posts back to the same page, the posted value of the cfinput control is used, instead of its Value or Checked attribute. If cfinput check box or radio type values match the submitted value for the control, ColdFusion checks their values. If no value matches, nothing is checked. To add other HTML tag attributes and values to this tag, use the passThrough attribute. They are passed through ColdFusion to the browser when creating a form. The supported HTML attributes are: CLASS, ID, MAXLENGTH, MESSAGE, ONBLUR, ONCHANGE, ONCLICK, ONDBLCLICK, ONFOCUS, SIZE, STYLE, and TABINDEX. If you specify a value in quotation marks, you must escape them; for example, passThrough = "readonly = " "YES " " " For more information, see cfform on page 132. For information on using JavaScript regular expressions with this tag, see Chapter 27, “Building Dynamic Forms,” in Developing ColdFusion MX Applications. Example Phone Number Validation (enter a properly formatted phone number):
Required

Zip Code Validation (enter a properly formatted zip code):
Required

Range Validation (enter an integer from 1 to 5):

Date Validation (enter a properly formatted date):
204 Chapter 2: ColdFusion Tags cfinsert Description Inserts records in data sources from data in a ColdFusion form or form Scope. Category Database manipulation tags Syntax See also cfprocparam, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cftransaction, cfupdate History ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider, and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5. Attributes Attribute Req/Opt Default Description dataSource Required Data source; contains table. tableName Required Table in which to insert form fields. ORACLE drivers: must be uppercase. Sybase driver:case-sensitive. Must be the same case used when table was created tableOwner Optional For data sources that support table ownership (such as SQL Server, Oracle, and Sybase SQL Anywhere), use this field to specify the owner of the table. tableQualifier Optional For data sources that support table qualifiers, use this field to specify qualifier for table. The purpose of table qualifiers varies among drivers. For SQL Server and Oracle, qualifier refers to name of database that contains table. For Intersolv dBASE driver, qualifier refers to directory where DBF files are located. username Optional Overrides username specified in ODBC setup. password Optional Overrides password specified in ODBC setup. formFields Optional (all on form, except keys) Comma-delimited list of form fields to insert. If not specified, all fields in the form are included. If a form field is not matched by a column name in the database, ColdFusion throws an error. The database table key field must be present in the form. It may be hidden. cfinsert 205 Example

Your record was added to the database.

Your record was added to the database.

SELECT CommentID, EMail, FromUser, Subject, CommtType, MessText, Posted, Processed FROM Comments

cfinsert Example

First, show a list of the comments in the cfsnippets datasource.

From UserSubjectComment Type MessageDate Posted
#FromUser# #Subject# #CommtType# #Left(MessText, 125)# #Posted#

Next, we’ll offer the opportunity to enter a comment:

Email: 
From: 
Subject:
Message:
Date Posted: #DateFormat(Now())#


206

Chapter 2: ColdFusion Tags




type = "hidden"
= "posted" value = "#Now()#">
type = "Submit"
= "" value = "insert my comment">

cfinsert

207

cfinvoke
Description

Does either of the following:

• Invokes a component method from within a ColdFusion page or component.
• Invokes a web service.
This tag works as follows:

• Transiently instantiates a component or web service and invokes a method on it
• Invokes a method on an instantiated component or web service
This tag can pass parameters to a method in the following ways:

• With the cfinvokeargument tag
• As named attribute-value pairs, one attribute per parameter
• As a structure, in the argumentCollection attribute
Category

Extensibility tags
Syntax


OR


OR


OR



component = "#mystringname for instantiated component#"
method = "method name"
returnVariable = "variable name"
argumentCollection = "argument collection"
...
>
OR



webservice = "#my stringname for instantiated web service#"
timeout = "request timeout in seconds"
proxyServer = "WSDL proxy server url
proxyPort = "numeric port on proxy server"
proxyUser = "string user id for proxy server"
proxyPassword = "string user password for proxy server"
>
See also
cfargument, cfcomponent, cffunction, cfinvokeargument, cfobject, cfproperty,
cfreturn
History

ColdFusion MX 6.1: Added the following attributes: timeout, proxyServer, proxyPort,
proxyUser, and proxyPassword.
ColdFusion MX: Added this tag.

cfinvoke

209

Attributes
Attribute

Req/Opt

Default

Description

component

See Usage
section

String or component object; a reference to a
component, or component to instantiate.

method

See Usage
section

Name of a method. For a web service, the
name of an operation.

returnVariable

Optional

Name of a variable for the invocation result.

argumentCollection Optional

Name of a structure; associative array of
arguments to pass to the method.

username

Optional

Overrides username specified in
Administrator > Web Services.

password

Optional

Overrides password specified in
Administrator > Web Services.

webservice

Required

The URL of the WSDL file for the web
service.

timeout

Optional

The timeout for the web service request, in
seconds

proxyServer

Optional

http.proxyHost
system property, if
any.

The proxy server required to access the
webservice URL.

proxyPort

Optional

http.proxyPort
system property, if
any.

The port to use on The proxy server.

proxyUser

Optional

http.proxyUser
system property, if
any

The user ID to send to the proxy server.

proxyPassword

Optional

http.proxyPasswor The user’s password on the proxy server.
d system property,
if any

input_params ...

Input parameters. For each named input
parameter specify paramName=paramValue.

Note: If you do not specify any the proxy attributes, and a corresponding system property is set
(typically in the JVM startup arguments) ColdFusion uses the system property value.
Usage

The following table shows when you can use each attribute:

210

This attribute is
required, optional,
ignored, or invalid:

For this cfinvoke tag syntax:
Syntax 1

Syntax 2

Syntax 3

Syntax 4A

Syntax 4B

component

Required

Optional

Invalid

Required

Invalid

method

Required

Required

Required

Required

Required

returnVariable

Optional

Optional

Optional

Optional

Optional

argumentCollection

Optional

Optional

Optional

Optional

Optional

Chapter 2: ColdFusion Tags

This attribute is
required, optional,
ignored, or invalid:

For this cfinvoke tag syntax:
Syntax 1

Syntax 2

Syntax 3

Syntax 4A

Syntax 4B

username

Ignored

Ignored

Optional

Ignored

Optional

password

Ignored

Ignored

Optional

Ignored

Optional

webservice

Ignored

Ignored

Required

Ignored

Required

timeout

Invalid

Invalid

Optional

Invalid

Optional

proxyServer

Invalid

Invalid

Optional

Invalid

Optional

proxyPort

Invalid

Invalid

Optional

Invalid

Optional

proxyUser

Invalid

Invalid

Optional

Invalid

Optional

proxyPassword

Invalid

Invalid

Optional

Invalid

Optional

input_params ...

Optional

Optional

Optional

Optional

Optional

If the component attribute specifies a component name, the component with the corresponding
name is instantiated, the requested method is invoked, and then the component instance is
immediately destroyed. If the attribute contains a reference to an instantiated component object,
no instantiation or destruction of the component occurs.
On UNIX systems, ColdFusion searches first for a file with a name that matches the specified
component name, but is all lower case. If it does not find the file, it looks for a file name that
matches the component name exactly, with the identical character casing.
Method arguments can be passed in any of the following ways. If an argument is passed in more
than one way with the same name, this order of precedence applies:
1 Using the cfinvokeargument tag
2 Passing directly as attributes of the cfinvoke tag (they cannot have the same name as a

registered cfinvoke attribute: method, component, webservice, returnVariable)
3 Passing as struct keys, using the argumentCollection attribute
For example, the params struct contains three keys: a=1, b=1, c=1. The following call is evaluated
as if the arguments were passed to the method in the order a=3, b=2, c=1:



Note: The following cfinvoke tag attribute names are reserved; they cannot be used for argument
names: component, method, argumentCollection, and result.
Example1

This example uses Syntax 1.




cfinvoke

211


#res#
Example2

This example uses Syntax 1.




#res#
Example3

This example uses Syntax 2.


Example4

This example uses Syntax 3.



#foo#

For more information on the BabelFish web service example, see Chapter 32, “Using Web
Services,” in Developing ColdFusion MX Applications.
Example5

This example uses Syntax 4A.



#res#

#res#

212

Chapter 2: ColdFusion Tags

cfinvokeargument
Description

Passes the name and value of a parameter to a component method or a web service. This tag is
used within the cfinvoke tag.
Category

Extensibility tags
Syntax

See also
cfargument, cfcomponent, cffunction, cfinvoke, cfobject, cfproperty, cfreturn
History

ColdFusion MX: Added this tag.
Attributes
Attribute

Req/Opt

Default

Description

name

Required

Argument name

value

Required

Argument value

Usage

You can have multiple cfinvokeargument tags in a cfinvoke tag body.
You can use cfinvokeargument tag to dynamically determine the arguments to be passed. For
example, you can use conditional processing to determine the argument name, or you can use a
cfif tag to determine whether to execute the cfinvokeargument tag.
Example1




#res#
Example2




#varName#

214

Chapter 2: ColdFusion Tags

cfldap
Description

Provides an interface to a Lightweight Directory Access Protocol (LDAP) directory server, such as
the Netscape Directory Server.
Category

Forms tags, Internet Protocol tags
Syntax

See also
cfftp, cfhttp, cfmail, cfmailparam, cfpop, Chapter 23, “Managing LDAP Directories,”

in Developing ColdFusion MX Applications
History

ColdFusion MX:

• Changed the name attribute behavior: this tag validates the query name in the name attribute.
• Changed sorting behavior: this tag does not support client-side sorting of query results. (It
•
•

supports server-side sorting; use the sort and sortcontrol attributes.)
Changed how results are sorted: server-side sorting results might be sorted slightly differently
than in ColdFusion 5. If you attempt a sort against a server that does not support it,
ColdFusion MX throws an error.
Deprecated the filterfile attribute. It might not work, and might cause an error, in later
releases.

cfldap

215

Attributes
Attribute

Req/Opt

server

Required

port

Optional

389

Port

Required if

(anonymous)

User ID

username

Default

Description
Host name or IP address of LDAP server.

secure =
"CFSSL_BASIC"

password

Password that corresponds to user name.
If secure = "CFSSL_BASIC", V2 encrypts the
password before transmission.

Required if
secure =
"CFSSL_BASIC"

action

name

Optional

query

Required if

• query: returns LDAP entry information only.
Requires name, start, and attributes attributes.
• add: adds LDAP entries to LDAP server.
Requires attributes attribute.
• modify: modifies LDAP entries, except
distinguished name dn attribute, on LDAP server.
Requires dn. See modifyType attribute.
• modifyDN: modifies distinguished name attribute
for LDAP entries on LDAP server. Requires dn.
• delete: deletes LDAP entries on an LDAP
server. Requires dn.
Name of LDAP query. The tag validates the value.

action =
"Query"

timeout

Optional

60

maxRows

Optional

Maximum number of entries for LDAP queries.

start

Required if

Distinguished name of entry to be used to start a
search.

action =
"Query"

scope

attributes

Optional

Required if
action =
"Query",
"Add",
"ModifyDN", or
"Modify"

filter

Optional

oneLevel

Maximum length of time, in seconds, to wait for
LDAP processing.

Scope of search, from entry specified in start
attribute for action = "Query".
• oneLevel: entries one level below entry.
• base: only the entry.
• subtree: entry and all levels below it.
For queries: comma-delimited list of attributes to
return. For queries, to get all attributes, specify "*".
If action = "add" or "modify", you can specify a
list of update columns. Separate attributes with a
semicolon.
If action = "ModifyDN", ColdFusion passes
attributes to the LDAP server without syntax
checking.

"objectclass = *" Search criteria for action = "query".
List attributes in the form:
"(attribute operator value)" Example: "(sn =
Smith)"

216

Chapter 2: ColdFusion Tags

Attribute

Req/Opt

sort

Optional

sortControl Optional

dn

startRow

Default

Description
Attribute(s) by which to sort query results. Use a
comma delimiter.

asc

• nocase: case-insensitive sort
• asc: ascending (a to z) case-sensitive sort
• desc: descending (z to a) case-sensitive sort
You can enter a combination of sort types; for
example, sortControl = "nocase, asc".

Required if

Distinguished name, for update action. Example:

action =
"Add",
"Modify",
"ModifyDN", or
"delete"

"cn = Bob Jensen, o = Ace Industry, c = US"

Optional

1

Used with action = "query". First row of LDAP
query to insert into a ColdFusion query.

modifyType Optional

replace

How to process an attribute in a multi-value list.
• add: appends it to any attributes
• delete: deletes it from the set of attributes
• replace: replaces it with specified attributes
You cannot add an attribute that is already present
or that is empty.

rebind

Optional

No

• Yes: attempt to rebind referral callback and
reissue query by referred address using original
credentials.
• No: referred connections are anonymous

referral

Optional

Integer. Number of hops allowed in a referral. A
value of 0 disables referred addresses for LDAP;
no data is returned.

secure

Optional

Security to employ, and required information. One
option:
• CFSSL_BASIC
"CFSSL_BASIC" provides V2 SSL encryption
and server authentication.

cfldap

217

Attribute

Req/Opt

Default

Description

separator

Optional

, [comma]

Delimiter to separate attribute values of multi-value
attributes. Used by query, add, and modify actions,
and by cfldap to output multi-value attributes.
For example, if $ (dollar sign), the attributes
attribute could be "objectclass = top$person",
where the first value of objectclass is top, and the
second value is person. This avoids confusion if
values include commas.

delimiter

Optional

; [semicolon]

Separator between attribute name-value pairs. Use
this attribute if:
• the attributes attribute specifies more than one
item, or
• an attribute contains the default delimiter
(semicolon). For example:
mgrpmsgrejecttext;lang-en

Used by query, add, and modify actions, and by
cfldap to output multi-value attributes.
For example, if $ (dollar sign), you could specify
"cn = Double Tree Inn$street = 1111 Elm; Suite
100 where the semicolon is part of the street value.

Usage

If you use the query action, cfldap creates a query object, allowing access to information in the
query variables, as follows:
Variable name

Description

queryname.recordCount

Number of records returned by query

queryname.currentRow

Current row of query that cfoutput is processing

queryname.columnList

Column names in query

If you use the security="CFSSL_BASIC" option, ColdFusion determines whether to trust the
sever by comparing the server’s certificate with the information in the jre/lib/security/cacerts
keystore of the JRE used by ColdFusion MX. The ColdFusion MX default cacerts file contains
information about many certificate granting authorities. If you must update the file with
additional information, you can use the keytool utility in the ColdFusion jre/bin directory to
import certificates that are in X.509 format. For example, enter the following:
keytool -import -keystore cacerts -alias ldap -file ldap.crt -keypass bl19mq

Then restart ColdFusion MX. The keytool utility initial keypass password is "change it". For
more information on using the keytool utility, see the Sun JDK documentation
Characters that are illegal in ColdFusion can be used in LDAP attribute names. As a result, the
cfldap tag could create columns in the query result set whose names contain illegal characters
and are, therefore, inaccessible in CFML. In ColdFusion, illegal characters are automatically
mapped to the underscore character; therefore, column names in the query result set might not
exactly match the names of the LDAP attributes.
For usage examples, see Developing ColdFusion MX Applications.
Example

cfldap Example

218 Chapter 2: ColdFusion Tags

Provides an interface to LDAP directory servers. The example uses the University of Connecticut public LDAP server. For more public LDAP servers, see http://www.emailman.com.

Enter a name and search the public LDAP resource. An asterisk before or after the name acts as a wildcard.

#results.recordCount# matches found
Name Organization Title E-Mail Phone
#cn# #o# #title# #mail# #telephonenumber#

Enter a name to search in the database.

cfldap 219 cflocation Description Stops execution of the current page and opens a ColdFusion page or HTML file. Category Flow-control tags, Page processing tags Syntax See also cfabort, cfbreak, cfexecute, cfexit, cfif, cfloop, cfswitch, cfthrow, cftry Attributes Attribute Req/Opt Default Description url Required URL of HTML file or CFML page to open. addToken Optional clientManagement must be enabled (see cfapplication on page 51). • Yes: appends client variable information to URL • No Usage You might write a standard message or response in a file, and call it from several applications. You could use this tag to redirect the user’s browser to the standard file. This tag has no effect if you use it after the cfflush tag on a page. Example

cflocation Example

This tag redirects the browser to a web resource; normally, you would use this tag to go to a CF page or an HTML file on the same server. The addToken attribute lets you send client information to the target page.

If you remove the comments, this code redirects you to CFDOCS home page: 220 Chapter 2: ColdFusion Tags cflock Description Ensures the integrity of shared data. Instantiates the following kinds of locks: • • Exclusive allows single-thread access to the CFML constructs in its body. The tag body can be executed by one request at a time. No other requests can start executing code within the tag while a request has an exclusive lock. ColdFusion issues exclusive locks on a first-come, first-served basis. Read-only allows multiple requests to access CFML constructs within the tag body concurrently. Use a read-only lock only when shared data is read and not modified. If another request has an exclusive lock on shared data, the new request waits for the exclusive lock to be released. Category Application framework tags Syntax See also cfapplication, cfassociate, cfmodule, Chapter 15, “Using Persistent Data and Locking,” in Developing ColdFusion MX Applications Attributes Attribute Req/Opt Default Description timeout Required Maximum length of time, in seconds, to wait to obtain a lock. If lock is obtained, tag execution continues. Otherwise, behavior depends on throwOnTimeout attribute value. scope Optional Lock scope. Mutually exclusive with the name attribute. Lock name. Only one request in the specified scope can execute the code within this tag (or within any other cflock tag with the same lock scope scope) at a time. • Application • Server • Session name Optional Lock name. Mutually exclusive with the scope attribute. Only one request can execute the code within a cflock tag with a given name at a time. Cannot be an empty string. Permits synchronizing access to resources from different parts of an application. Lock names are global to a ColdFusion server. They are shared among applications and user sessions, but not clustered servers. cflock 221 Attribute Req/Opt Default Description throwOnTimeout Optional Yes type Exclusive • readOnly: lets more than one request read shared data. • exclusive: lets one request read or write shared data. Optional How timeout conditions are handled. • Yes: exception is generated for the timeout. • No: execution continues past this tag. Note: Limit the scope of code that updates shared data structures, files, and CFXs. Exclusive locks are required to ensure the integrity of updates, but read-only locks are faster. In a performance-sensitive application, substitute read-only locks for exclusive locks where possible; for example, when reading shared data. Usage ColdFusion MX is a multithreaded server; it can process multiple page requests at a time. Use the cflock tag for these purposes: • To ensure that modifications to shared data and objects made in concurrently executing requests occur sequentially. • Around file manipulation constructs, to ensure that file updates do not fail because files are open for writing by other applications or tags. • Around CFX invocations, to ensure that ColdFusion can safely invoke CFXs that are not implemented in a thread-safe manner. (This applies only to CFXs developed in C++ using the CFAPI.) To work safely with ColdFusion, a C++ CFX that maintains and manipulates shared (global) data structures must be made thread-safe; however, this requires advanced knowledge. You can use a CFML custom tag wrapper around a CFX to make its invocation thread-safe. When you display, set, or update variables in a shared scope, use the scope attribute to identify the scope as Server, Application or Session. Deadlocks A deadlock is a state in which no request can execute the locked section of a page. Once a deadlock occurs, neither user can break it, because all requests to the protected section of the page are blocked until the deadlock can be resolved by a lock timeout. The cflock tag uses kernel level synchronization objects that are released automatically upon timeout and/or the abnormal termination of the thread that owns them. Therefore, while processing a cflock tag, ColdFusion never deadlocks for an infinite period of time. However, very large timeouts can block request threads for long periods, and radically decrease throughput. To prevent this, always use the minimum timeout value. Another cause of blocked request threads is inconsistent nesting of cflock tags and inconsistent naming of locks. If you nest locks, everyone accessing the locked variables must consistently nest cflock tags in the same order. Otherwise, a deadlock can occur. 222 Chapter 2: ColdFusion Tags These examples show situations that cause deadlocks: Example deadlock with two users User 1 User 2 Locks the session scope. Locks the Application scope. Deadlock: Tries to lock the Application scope, but it is already locked by User 2. Deadlock: Tries to lock the Session scope, but it is already locked by User 1. The following deadlock could occur if you tried to nest an exclusive lock inside a read lock: Example deadlock with one user User 1 Locks the Session scope with a read lock. Attempts to lock the Session scope with an exclusive lock. Deadlock: Cannot lock the Session scope with an exclusive lock because the scope is already locked for reading. The following code shows this scenario: ............... ......... To avoid a deadlock, everyone who nests locks must do so in a well-specified order and name the locks consistently. If you must lock access to the Server, Application, and Session scopes, you must do so in this order: 1 Lock the Session scope. In the cflock tag, specify scope = "session". 2 Lock the Application scope. In the cflock tag, specify scope = "Application". 3 Lock the Server scope. In the cflock tag, specify scope = "server". 4 Unlock the Server scope. 5 Unlock the Application scope. 6 Unlock the Session scope. Note: If you do not have to lock a scope, you can skip any pair of these lock/unlock steps. For example, if you do not have to lock the Server scope, you can skip Steps 3 and 4. Similar rules apply for named locks. For more information, see the following: • Chapter 15, “Using Persistent Data and Locking,” in Developing ColdFusion MX Applications • Article #20370, ColdFusion Locking Best Practices, on the Macromedia website at www.macromedia.com/support/service/ Example cflock 223

cflock Example

Thanks for shopping E-Turtleneck. You chose size #form.size#, color #form.color#.

E-Turtleneck has now sold #application.number# turtlenecks! 224 Chapter 2: ColdFusion Tags E-Turtleneck has sold #application.number# turtlenecks to date.

Congratulations! You selected the most comfortable turtleneck in the world. Please select color and size.

Select a color.
Select a size.
Press Submit when you are finished making your selection.
cflock 225 cflog Description Writes a message to a log file. Category Data output tags Syntax See also cfcol, cfcontent, cfoutput, cftable History ColdFusion MX: Deprecated the thread, date, and time attributes. They might not work, and might cause an error, in later releases. (In earlier releases, these attributes determined whether the respective data items were output to the log. In ColdFusion MX, this data is always output.) Attributes 226 Attribute Req/Opt Default text Required Message text to log. log Optional If you omit the file attribute, writes messages to standard log file. Ignored, if you specify file attribute. • Application: writes to Application.log, normally used for application-specific messages. • Scheduler: writes to Scheduler.log, normally used to log the execution of scheduled tasks. file Optional Message file. Specify only the main part of the filename. For example, to log to the Testing.log file, specify "Testing". The file must be located in the default log directory. You cannot specify a directory path. If the file does not exist, it is created automatically, with the suffix .log. type Optional Information Type (severity) of the message: • Information • Warning • Error • Fatal Information application Optional Yes • Yes: log application name, if it is specified in a cfapplication tag. • No Chapter 2: ColdFusion Tags Description Usage This tag logs custom messages to standard or custom log files. You can specify a file for the log message or send messages to the default application or scheduler log. The log message can include ColdFusion expressions. Log files must have the suffix .log and must be located in the ColdFusion log directory. Log entries are written as comma-delimited lists with these fields: • • • • • • type coio date time application text Values are enclosed in double quotation marks. If you specify No for the application attribute, the corresponding entry in the list is empty. You can disable cflog tag execution. For more information, see the ColdFusion Administrator, Basic Security page. The following example logs the name of a user that logs on an application. The message is logged to the file myAppLog.log in the ColdFusion log directory. It includes the date, time, and thread ID, but not the application name. For example, if a user enters "Sang Thornfield" in a form’s username field, this entry is added to the myApplog.log file entry: "Information","153","02/28/01","14:53:40",,"User Sang Thornfield logged on." cflog 227 cflogin Description A container for user login and authentication code. ColdFusion runs the code in this tag if a user is not already logged in. You put code in the tag that authenticates the user and identifies the user with a set of roles. Used with cfloginuser tag. Category Extensibility tags Syntax ...> See also cfloginuser, cflogout, GetAuthUser, IsUserInRole, Chapter 16, “Securing Applications,” in Developing ColdFusion MX Applications History ColdFusion MX 6.1: Changed behavior: the cflogin variable exists when ColdFusion receives a request with NTLM or Digest (CFHTTP Negotiated header) authentication information. ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description idletimout Optional 1800 Time interval with no keyboard activity after which ColdFusion logs the user off. Seconds. applicationtoken Optional The current application name Unique application identifier. Limits the login validity to one application, as specified by the cfapplication tag. cookiedomain Optional Domain of the cookie that is used to mark a user as logged in. Use this attribute to enable a user login cookie to work with multiple clustered servers in the same domain. Usage The body of this tag executes only if there is no logged-in user. When using application-based security, you put code in the body of the cflogin tag to check the user-provided ID and password against a data source, LDAP directory, or other repository of login identification. The body must include a cfloginuser tag to establish the authenticated user's identity in ColdFusion. 228 Chapter 2: ColdFusion Tags The cflogin tag has a built-in cflogin structure that contains two variables, cflogin.name and cflogin.password, if the page is executing in response to any of the following: • Submission of a form that contains input fields with the names j_username and j_password. • A request that uses CFHTTP Basic authentication, and therefore includes an Authorization header with the username and password. • A request that uses NTLM or Digest authentication. In this case, the username and password are hashed using a one-way algorithm in the Authorization header; ColdFusion gets the username from the web server and sets the cflogin.password value to the empty string. You can use these values in the cflogin tag body to authenticate the user, and, in the cfloginuser tag, to log the user in. The structure is only available in the cflogin tag body. Example The following example shows a simple authentication. This code is typically in the application.cfm page. cflogin 229 cfloginuser Description Identifies an authenticated user to ColdFusion. Specifies the user ID and roles. Used within a cflogin tag. Category Extensibility tags Syntax See also cflogin, cflogout, GetAuthUser, IsUserInRole, cfapplication, Chapter 16, “Securing Applications,” in Developing ColdFusion MX Applications History ColdFusion MX 6.1: Changed behavior: if the Session scope is enabled, and the cfapplication tag loginStorage attribute is set to Session, the login remains in effect until the session expires or the user is logged out by the cflogin tag. ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description name Required A username. password Required A user password. roles Required A comma-delimited list of role identifiers. ColdFusion processes spaces in a list element as part of the element. Usage Used inside the cflogin tag to identify the authenticated user to ColdFusion. After you call this function, the GetAuthUser and IsUserInRoles return the user name and role information. Note: By default, the user information is stored as memory-only cookies. The cfapplication tag can specify that login information be stored in the Session scope. Example See cflogin on page 228. 230 Chapter 2: ColdFusion Tags cflogout Description Logs the current user out. Removes knowledge of the user ID, password, and roles from the server. If you do not use this tag, the user is automatically logged out when the session ends. Category Extensibility tags Syntax See also cflogin, cfloginuser, Chapter 16, “Securing Applications,” in Developing ColdFusion MX Applications History ColdFusion MX 6.1: Changed behavior: if the Session scope is enabled, a login remains in effect until the session expires or the user is logged out by the cflogin tag. ColdFusion MX: Added this tag. Example Authorized user: #getAuthUser()# Authorized user: #getAuthUser()# cflogout 231 cfloop Description Looping is a programming technique that repeats a set of instructions or displays output repeatedly until one or more conditions are met. This tag supports the following types of loops: • • • • • “cfloop: index loop” on page 233 “cfloop: conditional loop” on page 235 “cfloop: looping over a query” on page 236 “cfloop: looping over a list or file” on page 238 “cfloop: looping over a COM collection or structure” on page 239 Category Flow-control tags 232 Chapter 2: ColdFusion Tags cfloop: index loop Description An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop. Syntax ... HTML or CFML code ... See also cfabort, cfbreak, cfdirectory, cfexecute, cfexit, cfif, cflocation, cfrethrow, cfswitch, cfthrow, cftry Attributes Attribute Req/Opt Default Description index Required Index value. ColdFusion sets it to from value and increments or decrements by step value, until it equals to value. from Required Beginning value of index. to Required Ending value of index. step Optional 1 Step by which to increment or decrement the index value. Usage Using anything other than integer values in the from and to attributes of an index loop can product unexpected results. For example, if you increment through an index loop from 1 to 2, with a step of 0.1, ColdFusion outputs "1,1.1,1.2,...,1.9", but not "2". This is a programming language problem regarding the internal representation of floating point numbers. Note: The to value is evaluated once, when the cfloop tag is encountered. Any change to this value within the loop block, or within the expression that evaluates to this value, does not affect the number of times the loop is executed. Example In this example, the code loops five times, displaying the index value each time: The loop index is #LoopCount#.
The output of this loop is as follows: The The The The The loop loop loop loop loop index index index index index is is is is is 1. 2. 3. 4. 5. cfloop: index loop 233 In this example, the code loops four times, displaying the index value each time. The value of j is decreased by one for each iteration. This does not affect the value of to, because it is a copy of j that is made before entering the loop. The loop index is #LoopCount#.
The output of this loop is as follows: The The The The loop loop loop loop index index index index is is is is 1. 2. 3. 4. As before, the value of j is decremented by one for each iteration, but this does not affect the value of to, because its value is a copy of j that is made before the loop is entered. In this example, step has the default value, 1. The code decrements the index: The loop index is #LoopCount#.
The output of this loop is as follows: The The The The The 234 loop loop loop loop loop index index index index index is is is is is 5. 4. 3. 2. 1. Chapter 2: ColdFusion Tags cfloop: conditional loop Description A conditional loop iterates over a set of instructions as long as a condition is True. To use this type of loop correctly, the instructions must change the condition every time the loop iterates, until the condition is False. Conditional loops are known as WHILE loops, as in, "loop WHILE this condition is true." Syntax ... See also cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfswitch, cfthrow, cftry Attributes Attribute Req/Opt condition Required Default Description Condition that controls the loop. Example The following example increments CountVar from 1 to 5. The loop index is #CountVar#.
The output of this loop is as follows: The The The The The loop loop loop loop loop index index index index index is is is is is 1. 2. 3. 4. 5. cfloop: conditional loop 235 cfloop: looping over a query Description A loop over a query executes for each record in a query record set. The results are similar to those of the cfoutput tag. During each iteration, the columns of the current row are available for output. The cfloop tag loops over tags that cannot be used within a cfoutput tag. Syntax See also cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfoutput, cfswitch, cfthrow, cftry Attributes Attribute Req/Opt Default Description query Required Query that controls the loop. startRow Optional First row of query that is included in the loop. endRow Optional Last row of query that is included in the loop. Example This example shows a cfloop looping over a query the same way as a cfoutput tag that uses the query attribute: SELECT * FROM Messages #Message_ID#
The cfloop tag also iterates over a record set with dynamic start and stop points. This gets the next n sets of records from a query. This example loops from the 10th through the 20th record returned by MyQuery: #MyQuery.MyColName#
The loop stops when there are no more records, or when the current record index is greater than the value of the endRow attribute. The advantage of looping over a query is that you can use CFML tags that are not allowed in a tag. The following example combines the pages that are returned by a query of a list of page names into one document, using the cfinclude tag. cfoutput SELECT TemplateName FROM Templates cfloop: looping over a query 237 cfloop: looping over a list or file Description Looping over a list steps through elements contained in any of these entities: • A variable • A value that is returned from an expression • A file Syntax ... See also cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfswitch, cfthrow, cftry Attributes Attribute Req/Opt Default Description index Required In a list loop, the variable to receive next list element. list Required A list, variable, or filename; contains a list delimiters Optional Character(s) that separates items in list Example This loop displays four names: #ListElement#
You can put more than one character in the delimiters attribute, in any order. For example, this loop processes commas, colons, and slashes as list delimiters: #ListElement#
ColdFusion skips the second and subsequent consecutive delimiters between list elements. Thus, in the example, the two colons between "George" and "Ringo" are processed as one delimiter. To loop over each line of a file, use the tag this way: ... 238 Chapter 2: ColdFusion Tags cfloop: looping over a COM collection or structure Description The cfloop collection attribute loops over every object within a COM/DCOM collection object, or every element in a structure: • A COM/DCOM collection object is a set of similar items referenced as a group. For example, the group of open documents in an application is a collection. • A structure contains a related set of items, or it can be used as an associative array. Looping is particularly useful when using a structure as an associative array. In the loop, each item is referenced by the variable name in the item attribute. The loop executes until all items have been accessed. The collection attribute is used with the item attribute. In the example that follows, item is assigned a variable called file2, so that with each cycle in the cfloop, each item in the collection is referenced. In the cfoutput section, the name property of the file2 item is referenced for display. Example This example uses a COM object to output a list of files. In this example, FFunc is a collection of file2 objects. #file2.name#
...
Employee Dept.
#person# #StructFind(Departments, person)#
cfloop: looping over a list or file 239 cfmail Description Sends an e-mail message that optionally contains query output, using an SMTP server. Category Forms tags, Internet Protocol tags Syntax (Optional) Mail message body and/or cfhttpparam tags See also cfmailparam, cfmailpart, cfpop, cfftp, cfhttp, cfldap, Wrap History ColdFusion MX 6.1: • Added the following attributes: charset, failto, replyto, username, password and wraptext. • Added support for multiple mail servers in the server attribute. • Added several configuration options to the ColdFusion MX Administrator Mail Settings page. ColdFusion MX: Added the SpoolEnable attribute. 240 Chapter 2: ColdFusion Tags Attributes Attribute Req/Opt Default Description to Required Message recipient e-mail addresses. • Static address. For example, "support@macromedia.com" • Variable that contains an address. For example, "#Form.Email#". • Name of a query column that contains an address. For example, "#EMail#". An e-mail message is sent for each returned row. from Required E-mail message sender: • A static string; for example, "support@mex.com" • A variable; for example, "#GetUser.EMailAddress#" This attribute does not have to be a valid internet address; it can be any text string. cc Optional Address(es) to which to copy the message. bcc Optional Address(es) to which to copy the message, without listing them in the message header. subject Required Message subject. Can be dynamically generated. For example, to send messages that give customers status updates, "Status of Order Number #Order_ID#". replyto Optional Address(es) to which the recipient is directed to send replies. failto Optional Address to which mailing systems should send delivery failure notifications. Sets the mail envelope reverse-path value. username Optional A user name to send to SMTP servers that require authentication. Requires a password attribute. password Optional A password to send to SMTP servers that require authentication. Requires a username attribute. wraptext Optional Do not wrap text Specifies the maximum line length, in characters of the mail text. If a line has more than the specified number of characters, replaces the last white space character, such as a tab or space, preceding the specified position with a line break. If there are no white space characters, inserts a line break at the specified position. A common value for this attribute is 72. cfmail 241 242 Attribute Req/Opt Default Description charset Optional Character encoding selected in ColdFusion MX Administrator Mail page; default is UTF-8 Character encoding of the mail message, including the headers. The following list includes commonly used values: • utf-8 • iso-8859-1 • windows-1252 • us-ascii • shift_jis • iso-2022-jp • euc-jp • euc-kr • iso-2022-kr • big5 • hz-gb-2312 • euc-cn • utf-16 For more information on character encodings, see: www.w3.org/International/O-charset.html. type Optional text/plain MIME type of the message. Can be a valid MIME media type or one of the following: • text specifies text/plain type • plain specifies text/plain type • html specifies text/html type For a list of all registered MIME media types see www.iana.org/assignments/media-types/ MIMEAttach Optional Path of file to attach to message. Attached file is MIMEencoded. ColdFusion attempts to determine the MIME type of the file; use the cfmailparam tag to send an attachement and specify the MIME type. query Optional Name of cfquery from which to draw data for message(s). Use this attribute to send more than one message, or to send query results within a message. group Optional CurrentRow Query column to use when you group sets of records to send as a message. For example, to send a set of billing statements to a customer, group on "Customer_ID." Casesensitive. Eliminates adjacent duplicates when data is sorted by the specified field. groupCase Sensitive Optional No Boolean. Whether to consider case when using the group attribute. To group on case-sensitive records, set this attribute to Yes. startRow Optional 1 Row in a query to start from. maxRows Optional Maximum number of messages to send when looping over a query. server Optional SMTP server address, or (Enterprise edition only) a comma-delimited list of server addresses, to use for sending messages. At least one server must be specified here or in the ColdFusion MX Administrator. A value here overrides the Administrator. A value that includes a port specification overrides the port attribute. See the Usage section for details. Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description port Optional TCP/IP port on which SMTP server listens for requests (normally 25). A value here overrides the Administrator. mailerID Optional timeout Optional ColdFusion MX Application Server spoolEnable Optional Mailer ID to be passed in X-Mailer SMTP header, which identifies the mailer application. Number of seconds to wait before timing out connection to SMTP server. A value here overrides the Administrator. Specifies whether to spool mail or always send it Immediately. Overrides the ColdFusion MX Administrator Spool mail messages to disk for delivery setting. • Yes: Saves a copy of the message until the sending operation is complete. Pages that use this option might run slower than those that use the No option. • No: Queues the message for sending, without storing a copy until the operation is complete. If a delivery error occurs when this option is No, ColdFusion generates an Application exception and logs the error to the mail.log file. Usage Sends a mail message to the specified address. Mail messages can include attachements. The tag body can include CFML code to generate mail output. The cfmailparam and cfmailpart tags can only be used in the cfmail tag body. Mail messages can be single or multipart. If you send a multi-part mail message, all message content must be in cfmailpart tags; ColdFusion ignores multipart message text text that is not in cfmailpart tags. Note: The cfmail tag does not make copies of attachments when spooling mail to disk. If you use the cfmail tag to send a message with an attachment with spooling enabled and you use the cffile tag to delete the attachment file, ColdFusion might not send the mail because the mailing process might execute after the file was is deleted. (When this happens, the mail log includes a FileNotFound exception and the e-mail is not sent.) You can prevent this problem by setting SpoolEnable="No" in the attribute or disabling spooling in the ColdFusion MX Administrator. Disabling spooling causes the e-mail to be delivered immediately. Mail addressing Mail addresses can have any of the following forms: Format Example user@server rsmith@company.com DisplayName Rob Smith "DisplayName" "Rob Smith" user@server (DisplayName) rsmith@company.com (Rob Smith) cfmail 243 Specifying mail servers The server attribute can specify one or more mail servers. Note: If you specify multiple mail servers in ColdFusion MX Standard, the cfmail tag uses only the first server in the specification. ColdFusion logs a warning message to the mail log file and ignores the additional servers. For each server, you can optionally specify a username, password, and port. These values override the corresponding attributes, if any. The server attribute has the following format: [user:password@]server[:port],[user:password@]server[:port],.... For example, the following line specifies one server, mail.myco.com that uses the default port and no user or password, and a second server with a user, password, and specific port: server=mail.myco.com,mail_admin:adm2qzf@mail2.myco.com:24 When you specify multiple mail servers in ColdFusion Enterprise, ColdFusion tries the available servers in the order they are listed until it connects to a server. ColdFusion does not try to connect to a server that was unavailable in the last 60 seconds. Example

cfmail Example

244 Chapter 2: ColdFusion Tags

---> cfmail 245 cfmailparam Description Attaches a file or adds a header to an e-mail message. Can only be used in the cfmail tag. You can use more than one cfmailparam tag within a cfmail tag. Category Forms tags, Internet Protocol tags Syntax or ... See also cfmail, cfmailpart, cfftp, cfhttp, cfldap, cfpop History ColdFusion MX 6.1: Added the type attribute. Attributes Attribute Req/Opt Default Description file Required if you do not specify name attribute Attaches file to a message. Mutually exclusive with name attribute. The file is MIME encoded before sending. type Optional The MIME media type of the part. Can be a valid MIME media type or one of the following: • text specifies text/plain type • plain specifies text/plain type • html specifies text/html type Note: For a list of all registered MIME media types, see www.iana.org/assignments/media-types/ name Required if you do not specify file attribute Name of header. Case-insensitive. Mutually exclusive with file attribute. value Optional Value of the header. Example

cfmailparam Example

This view-only example uses cfmailparam to attach files and add header to a message.

246 Chapter 2: ColdFusion Tags = "Importance" value = "Hich"> new logo. Tell us what you think. = "c:\work\readme.txt" type="text/plain"> = "c:\work\logo.gif" type="image/gif"> cfmailparam 247 cfmailpart Description Specifies one part of a multipart e-mail message. Can only be used in the cfmail tag. You can use more than one cfmailpart tag within a cfmail tag. Category Forms tags, Internet Protocol tags Syntax (Optional cfmailparam entries) Mail part contents ... History ColdFusion MX 6.1: Added this tag. See also cfmail, cfmailparam, cfpop, cfftp, cfhttp, cfldap, cfcontent, Wrap, Chapter 35, “Sending and Receiving E-Mail,” in Developing ColdFusion MX Applications Attributes Attribute Req/Opt type Default Required Description The MIME media type of the part. Can be a can be valid MIME media type or one of the following: • text specifies text/plain type • plain specifies text/plain type • html specifies text/html type Note: For a list of all registered MIME media types see www.iana.org/assignments/media-types/ 248 Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description wraptext Optional Do not wrap text Specifies the maximum line length, in characters of the mail text. If a line has more than the specified number of characters, replaces the last white space character, such as a tab or space, preceding the specified position with a line break. If there are no white space characters, inserts a line break at the specified position. A common value for this attribute is 72. charset Optional Character encoding specified by The character encoding in which the part text is encoded. The following list includes commonly used values:: • utf-8 • iso-8859-1 • windows-1252 • us-ascii • shift_jis • iso-2022-jp • euc-jp • euc-kr • iso-2022-kr • big5 • hz-gb-2312 • euc-cn • utf-16 For more information on character encodings, see: www.w3.org/International/O-charset.html. charset attribute of cfmail tag Usage Use this tag to create mail messages with alternative versions of the message that duplicate the content in multiple formats. The most common use is to send a plain text version of the message that can be read by all mail readers followed by a version formatted in HTML for display by HTML-compatible mail readers. Specify the simplest version first, with more complex versions afterwards. For more information, see www.ietf.org/rfc/rfc2046.txt. Example

cfmailpart Example

You are reading this message as plain text, because your mail reader does not handle HTML text. >

HTML Mail Message

You are reading this message as HTML.

Your mail reader handles HTML text.

cfmailpart 249 cfmodule Description Invokes a custom tag for use in ColdFusion application pages. This tag processes custom tag name conflicts. For more information, see Chapter 9, “Creating and Using Custom CFML Tags,” in Developing ColdFusion MX Applications. Category Application framework tags Syntax See also Chapter 9, “Creating and Using Custom CFML Tags,” in Developing ColdFusion MX Applications cfapplication, cfassociate, cflock, History ColdFusion MX: Changed behavior when using this tag within a custom tag: if the attribute_name parameter is the same as a key element within the attributeCollection parameter, ColdFusion now uses the name value that is within the attributeCollection parameter. (Earlier releases did not process this consistently.) Attributes Attribute Req/Opt Default Description template Required unless name attribute is used Mutually exclusive with the name attribute. A path to the page that implements the tag. • Relative path: expanded from the current page • Absolute path: expanded using ColdFusion mapping A physical path is not valid. name Required unless template attribute is used Mutually exclusive with the template attribute. A custom tag name, in the form "Name.Name.Name..." Identifies subdirectory, under the ColdFusion tag root directory, that contains custom tag page. For example (Windows format): This identifies the page GetUserOptions.cfm in the directory CustomTags\macromedia\Forums40 under the ColdFusion root directory. 250 Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description attributeCollection Optional Structure. A collection of key-value pairs that represent attribute names and values. You can specify multiple key-value pairs. You can specify this attribute only once. attribute_name Optional Attribute for a custom tag. You can include multiple instances of this attribute to specify the parameters of a custom tag. Usage To name a ColdFusion page that contains the custom tag definition, including its path, use the template attribute. To refer to the custom tag in the ColdFusion installation directory, using dot notation to indicate its location, use the name attribute. On UNIX systems, ColdFusion searches first for a file with a name that matches the name attribute, but is all lower case. If it does not find the file, it looks for a file name that matches the attribute with identical character casing. You can use attributeCollection and attribute_name in the same call. Within the custom tag code, the attributes passed with attributeCollection are saved as independent attribute values, with no indication that they are grouped into a structure by the custom tag’s caller. Similarly, if the custom tag uses a cfassociate tag to save its attributes, the attributes passed with attributeCollection are saved as independent attribute values, with no indication that they are grouped into a structure by the custom tag’s caller. Example

cfmodule Example

This view-only example shows use of cfmodule to call a custom tag inline.

This example uses a sample custom tag that is saved in myTag.cfm in the snippets directory. You can also save ColdFusion custom tags in the Cfusion\CustomTags directory.


Here is one way in which to invoke the custom tag, using the TEMPLATE attribute.

#HTMLCodeFormat(" ")#

The result: #result# cfmodule 251


Here is another way to invoke the custom tag, using the NAME attribute.

#HTMLCodeFormat(" ")#

The result: #result#

Here is the short cut to invoking the same tag.

#HTMLCodeFormat("")#

The result: #result#

252 Chapter 2: ColdFusion Tags cfobject Description Creates a ColdFusion object, of a specified type. Note: You can enable and disable this tag in the ColdFusion Administrator page, under ColdFusion Basic Security, Tag Restrictions. Category Extensibility tags Syntax The tag syntax depends on the object type. Some types use the type attribute; others do not. See the following sections: • • • • • “cfobject: COM object” on page 254 “cfobject: component object” on page 256 “cfobject: CORBA object” on page 257 “cfobject: Java or EJB object” on page 259 “cfobject: web service object” on page 261 Note: On UNIX, this tag does not support COM objects. See also cfargument, cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfproperty, cfreturn History ColdFusion MX: • Changed instantiation behavior: this tag, and the CreateObject function, can now instantiate ColdFusion components (CFCs); you can use them within the cfscript tag. • For CORBA object: changed the Naming Service separator format for addresses from a dot to • a forward slash. For example, if "context=NameService", for a class, use either of the following formats for the class parameter: ■ "Macromedia/Eng/CF" ■ "Macromedia.current/Eng.current/CF" (In earlier releases, the format was "Macromedia.Eng.CF".) For CORBA object: changed the locale attribute; it specifies the Java config that contains the properties file. cfobject 253 cfobject: COM object Description Creates and manipulates a Component Object Model (COM) object. Invokes a registered automation server object type. For information on OLEView, and about COM and DCOM, see the Microsoft OLE Development website: www.microsoft.com. To use this tag, you must provide the object’s program ID or filename, the methods and properties available through the IDispatch interface, and the arguments and return types of the object's methods. For most COM objects, you can get this information with the OLEView utility. Note: On UNIX, this tag does not support COM objects. Syntax See also ReleaseComObject, cfcollection, cfexecute Attributes 254 Attribute Req/Opt type Optional Object type: • com • corba • java (The other object types do not take the type attribute.) action Required • create: instantiates a COM object (typically, a DLL) before invoking methods or properties. • connect: connects to a COM object (typically, an EXE) running on server. class Required Component ProgID for the object to invoke. When using Java stubs to connect to the COM object, the class must be the ProgID of the COM object. name Required String; name for the instantiated component Chapter 2: ColdFusion Tags Default Description Attribute Req/Opt context Optional • inproc • local • remote On Windows: If not specified, uses Registry setting. server Required if Server name, using Universal Naming Convention (UNC) or Domain Name Serve (DNS) convention, in one of these forms: • \\lanserver • lanserver • http://www.servername.com • www.servername.com • 127.0.0.1 context = "Remote" Default Description Example

cfobject (COM) Example

This object has #obj.Count# items.

The last name in the third item is #emp.lastname#.

Looping through all items in the collection:
Last name: #file2.lastname#
cfobject: COM object 255 cfobject: component object Description Creates an instance of a ColdFusion component (CFC) object. Syntax See also cfcollection, cfcomponent, cfexecute, cfindex, cfreport, cfsearch, cfwddx Attributes Attribute Req/Opt name Required Default Description component Required String; name for the instantiated component. The name must not have a period as the first or last character. Name of component to instantiate Usage When the cfobject tag creates an instance of the CFC, ColdFusion executes any constructor code in the CFC; that is, it runs code that is not in the method definitions. On UNIX systems, ColdFusion searches first for a file with a name that matches the specified component name, but is all lower case. If it does not find the file, it looks for a file name that matches the component name exactly, with the identical character casing. Example #res#
#res# 256 Chapter 2: ColdFusion Tags cfobject: CORBA object Description Calls methods on a registered CORBA object. Syntax See also cfcollection, cfexecute, cfindex, cfreport, cfsearch, cfwddx History See the History section of the main cfobject tag page. Attributes Attribute Req/Opt Default Description type Optional Object type: • com • corba • java (The other object types do not take the type attribute.) context Required • ior: ColdFusion uses Interoperable Object Reference (IOR) to access CORBA server. • nameservice: ColdFusion uses naming service to access server. This option is valid only with the InitialContext of a VisiBroker Orb. class Required • If context = "ior": absolute path of file that contains string version of the Interoperable Object Reference (IOR). ColdFusion must be able to read file; it should be local to ColdFusion server or accessible on network. • If context = "nameservice": forward slash-delimited naming context for naming service. For example: Allaire//Doc/empobject name Required String; name for the instantiated component. An application uses it to reference the CORBA object’s methods and attributes. locale Optional Sets arguments for a call to init_orb. Use of this attribute is specific to VisiBroker ORBs. It is available on C++, Version 3.2. The value must be in the form: locale = " -ORBagentAddr 199.99.129.33 -ORBagentPort 19000" Each type-value pair must start with a hyphen. Usage ColdFusion Enterprise version 4.0 and later supports CORBA through the Dynamic Invocation Interface (DII). To use cfobject with CORBA objects, you must provide the name of the file that contains a string-formatted version of the IOR, or the object’s naming context in the naming service; and the object’s attributes, method names, and method signatures. User-defined types (for example, structures) are not supported. cfobject: CORBA object 257 Example 258 Chapter 2: ColdFusion Tags cfobject: Java or EJB object Description Creates and manipulates a Java and Enterprise Java Bean (EJB) object. Syntax See also cfcollection, cfexecute, cfindex, cfreport, cfsearch, cfwddx Attributes Attribute Req/Opt Default Description type Optional Object type: • com • corba • java (The other object types do not take the type attribute.) action Required Create: Creates a Java or WebLogic Environment object. class Required Java class. name Required String; name for the instantiated component. Usage To call Java CFXs or Java objects, ColdFusion uses a Java Virtual Machine(JVM) that is embedded in the process. You can configure JVM loading, location and settings in the ColdFusion Administrator. Any Java class available in the class path that is specified in the ColdFusion Administrator can be loaded and used from ColdFusion, using the cfobject tag. To access Java methods and fields, do the following steps: 1 Call the cfobject tag, to load the class. See the example code. 2 Use the init method with appropriate arguments, to call a constructor. For example: Calling a public method on the object without first calling the init method results in an implicit call to the default constructor. Arguments and return values can be any Java type (simple, array, object). ColdFusion makes the conversions if strings are passed as arguments, but not if they are received as return values. Overloaded methods are supported if the number of arguments is different. Calling EJBs To create and call EJB objects, use the cfobject tag. In the second example below, the WebLogic JNDI is used to register and find EJBHome instances. cfobject: Java or EJB object 259 Example Share value = #value# 260 Chapter 2: ColdFusion Tags cfobject: web service object Description Creates a web service proxy object. Syntax See also cfcollection, cfexecute, cfindex, cfreport, cfsearch, cfwddx Attributes Attribute Req/Opt Default Description webservice Required URL to web service WSDL file. • Absolute URL of web service • Name (string) assigned in the Administrator to the web service name Local name for the web service. String. Required Usage Instantiates a proxy object for a web service. You can enter the absolute URL in this tag, or refer to a web service that is entered in the ColdFusion Administrator. To minimize potential code maintenance, enter the web service in the Administrator, then refer to that name in this tag. cfobject: web service object 261 cfobjectcache Description Flushes the query cache. Category Database manipulation tags Syntax See also cfobject History ColdFusion 5: Added this tag. Attributes 262 Attribute Req/Opt action Required Default Description Chapter 2: ColdFusion Tags clear: Clears queries from the cache in the Application scope cfoutput Description Displays output that can contain the results of processing ColdFusion variables and functions. Can loop over the results of a database query. Category Data output tags Syntax See also cfcol, cfcontent, cfdirectory, cftable Attributes Attribute Req/Opt Default Description query Optional Name of cfquery from which to draw data for output section. group Optional Query column to use to group sets of records. Eliminates adjacent duplicate rows when data is sorted. Use if you retrieved a record set ordered on one or more a query columns. For example, if a record set is ordered on "Customer_ID" in the cfquery tag, you can group the output on "Customer_ID." groupCase Optional Sensitive Yes Boolean. Whether to consider the case in grouping rows. startRow Optional 1 Row from which to start output. maxRows Optional displays all Maximum number of rows to display. rows Usage In the cfoutput tag body, ColdFusion treats text that is surrounded by pound signs (#) as a ColdFusion variable or function call. For example, the following code displays the text "Hello World!": cfoutput>#myVar# When you specify a query attribute, this tag loops over the query rows and produces output for each row within the range specified by the startRow and maxRows values, and groups or eliminates duplicate entries as specified by the grouping attribute values, if any. It also sets the query.currentRow variable to the current row being processed. If you nest cfoutput blocks that process a query, you specify the query and group attributes at the top-most level; you can specify a group attribute for each inner block except the innermost cfoutput block. cfoutput 263 This tag requires an end tag. Example SELECT Dept_ID, CorName, CorLevel FROM courseList ORDER by Dept_ID, CorLevel, CorName

cfoutput Example

cfoutput tells ColdFusion Server to begin processing, and then to hand back control of page rendering to the web server.

For example, to show today’s date, you could write #DateFormat("#Now()#"). If you enclosed that expression in cfoutput, the result would be #DateFormat(Now())#.

In addition, cfoutput may be used to show the results of a query operation, or only a partial result, as shown:

There are #getCourses.recordCount# total records in our query. Using the maxRows parameter, we are limiting our display to 4 rows.

#Dept_ID##CorName##CorLevel#

The next example uses the group attribute to eliminate duplicate lines from a list of course levels taugh in each department.

SELECT Dept_ID, CorLevel FROM courseList ORDER by Dept_ID, CorLevel

#Dept_ID# #CorLevel#

cfoutput can also show the results of such as getting the day of the week from extract the integer representing the Day the server function Now() and then apply the DayofWeekAsString function: a more complex expression, today’s date. We first of the Week from the result to
Today is #DayofWeekAsString(DayofWeek(Now()))#
Today is #DayofWeekAsString(DayofWeek(Now()))# 264 Chapter 2: ColdFusion Tags cfparam Description Tests for a parameter’s existence, tests its data type, and, if a default value is not assigned, optionally provides one. Category Variable manipulation tags Syntax See also cfcookie, cfregistry, cfsavecontent, cfschedule, cfset Attributes Attribute Req/Opt Default Description name Required Name of parameter to test (such as "Client.Email " or "Cookie.BackgroundColor "). If omitted, and if the parameter does not exist, an error is thrown. type Optional default Optional any The parameter data type: • any: any type of value • array: an array value • binary: a binary value • boolean: a Boolean value • date: a date-time value • guid: a Univerally Unique Identifier that follows the Microsoft/ DCE standard, as follows: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" where ‘X’ is a hexadecimal number. • numeric: a numeric value • query: a query object • string: a string value or single character • struct: a structure • UUID: a ColdFusion Universally Unique Identifier, formatted ‘XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXX’, where ‘X’ is a hexadecimal number. See CreateUUID on page 438. • variableName: a string formatted according to ColdFusion variable naming conventions. Value to set parameter to if it does not exist. Usage You can use this tag to make the following tests: • To test whether a required variable exists, use this tag with only the name attribute. If it does • not exist, ColdFusion MX stops processing the page and returns an error. To test whether a required variable exists, and that it is of the specified type, use this tag with the name and type attributes. If the variable does not exist or its value is not of the specified type, ColdFusion returns an error. cfparam 265 • To test whether an optional variable exists, use this tag with the name and default attributes. If the variable does not exist, it is created and set to the default attribute value. If the variable exists, processing continues; the value is not changed. If you specify variableName for the returnType attribute, the parameter value must be a string that is in ColdFusion variable name format; that is, starts with a letter, underscore (_), or Unicode currency symbol, and contains letters, numbers, underscores, periods, and Unicode currency symbols, only. ColdFusion does not check whether the parameter value corresponds to an existing ColdFusion variable. Tip: To improve performance, avoid using the cfparam tag in ColdFusion functions, including in CFC methods. Instead, place the cfparam tags in the body of the CFML pages. Example

cfparam Example

cfparam is used to set default values so thata developer does not have to check for the existence of a variable using a function like IsDefined.

The default value of our tempVar is "#StoreTempVar# "

The value of tempVar has changed: the new value is #tempVar#

Type in a new value for tempVar, and hit submit:
266 Chapter 2: ColdFusion Tags cfpop Description Retrieves or deletes e-mail messages from a POP mail server. Category Forms tags, Internet Protocol tags Syntax See also cfftp, cfhttp, cfldap, cfmail, cfmailparam, SetLocale History ColdFusion MX 6.1: • Added support for multipart mail mesages with Text and HTML parts. • Changed the attachment name separator: the TAB character is now the separator between attachment names in the attachments and attachmentfiles query fields if a message has multiple attachments. This behavior is identical to ColdFusion 5 and earlier versions. ColdFusion MX: Changed the attachment name separator: the comma separates names in the attachments and attachmentfiles query fields if a message has multiple attachments. Attributes Attribute Req/Opt Default Description server Required port Optional username Optional A user name password Optional Password that corresponds to username. POP server identifier: • A host name; for example, "biff.upperlip.com" • An IP address; for example, "192.1.2.225" 110 POP port cfpop 267 Attribute Req/Opt Default Description action Optional getHeaderOnly • getHeaderOnly: returns message header information only • getAll: returns message header information, message text, and attachments if attachmentPath is specified • delete: deletes messages on POP server name Required if action = "getAll" or Name for query object that contains the retrieved message information. "getHeaderOnly" message Number Message number or comma-delimited list of message numbers to get or delete. Invalid message numbers are ignored. Ignored if uid is specified. uid UID or a comma-delimited list of UIDs to get or delete. Invalid UIDs are ignored.. attachment Path Optional If action="getAll", specifies a directory in which to save any attachments. If the directory does not exist, ColdFusion creates it. If you omit this attribute, ColdFusion does not save any attachments. If you specify a relative path, the path root is the ColdFusion temporary directory, which is returned by the GetTempDirectory function.. timeout Optional 60 Maximum time, in seconds, to wait for mail processing. maxRows Optional retrieves all available rows Number of messages to return or delete, starting with the number in startRow. Ignored if messageNumber or uid is specified, startRow Optional 1 First row number to get or delete. Ignored if messageNumber or uid is specified, generate Unique Filenames Optional No • Yes: Generate unique filenames for files attached to an e-mail message, to avoid naming conflicts when files are saved • No Usage The cfpop tag retrieves one or more mail messages from a POP server and populates a ColdFusion query object with the resulting messages, one message per row. Alternatively, it deletes one or more messages from the POP server. To optimize performance, two retrieve options are available. Message header information is typically short, and therefore quick to transfer. Message text and attachments can be very long, and therefore take longer to process. 268 Chapter 2: ColdFusion Tags cfpop query variables The following table describes the variables that provide information about the query that is returned by cfpop: Variable names Description queryname.recordCount Number of records returned by query queryname.currentRow Current row that cfoutput is processing queryname.columnList List of column names in query queryname.UID Unique identifier for the e-mail message file Query message header and body columns The following table lists the message header and body columns that are returned if action = "getHeaderOnly" or "getAll": Column name getHeaderOnly returns getAll returns queryname.date yes yes queryname.from yes yes queryname.messagenumber yes yes queryname.replyto yes yes queryname.subject yes yes queryname.cc yes yes queryname.to yes yes queryname.body not available yes queryname.textBody not available yes queryname.HTMLBody not available yes queryname.header not available yes queryname.attachments not available yes queryname.attachmentfiles not available yes If the mail message includes a part with a Content-Type of text/plain, the queryname.textBody column contains the part’s message content. If the mail message includes a part with a ContentType of text/HTML, the queryname.HTMLBody column contains the part’s message content. If no Content-Type matches these types, the columns are empty. The queryname.Body column always contains the first message body found. The queryname.attachments column contains a tab-separated list of all the attachment names. The queryname.attachments column contains a tab-separated list of the locations of the attachment files. Use the cffile tag to delete these temporary files when you have processed them. cfpop 269 To create a ColdFusion date/time object from the date-time string that is extracted from a mail message in the queryname.date column, use the following table: Locale How to create a ColdFusion date/time object from queryname.date English (US) Use the ParseDateTime function. If you specify the pop-conversion attribute, the function adjusts the date/time object to UTC. Other Extract the date part of string; pass it to the LSParseDateTime function Note: To set the default display format of date, time, number, and currency values, use the SetLocale function. For more information on cfpop, see Chapter 35, “Sending and Receiving E-Mail,” in Developing ColdFusion MX Applications. Example

cfpop Example

cfpop lets you retrieve and manipulate mail in a POP3 mailbox. This view-only example shows how to create one feature of a mail client, to display the mail headers in a POP3 mailbox.

To execute this, un-comment this code and run with a mail-enabled CF Server.

Message Headers in Your Inbox

Number of Records: #GetHeaders.recordCount#

  • Row: #currentRow#: From: #From# -- Subject: #Subject#

Enter your mail server:

Enter your username:

Enter your password:

---> 270 Chapter 2: ColdFusion Tags cfprocessingdirective Description Provides the following insformation to ColdFusion on how to process the current page: • Specifies whether to remove excess whitespace character from ColdFusion generated content in • the tag body. Identifies the character encoding (character set) of the page contents. Category Data output tags Syntax or CFML tags See also cfcol, cfcontent, cfoutput, cfsetting, cfsilent, cftable, SetEncoding, Chapter 17, “Developing Globalized Applications,” in Developing ColdFusion MX Applications History ColdFusion MX: • Changed suppresswhitespace attribute value behavior: you can specify the • suppresswhitespace attribute value as a string variable. (ColdFusion 5 supported setting it only as a constant.) Added the pageEncoding attribute. cfprocessingdirective 271 Attributes Attribute Req/Opt Default suppressWhiteSpace Optional pageEncoding Optional Description Boolean; whether to suppress white space characters within the cfprocessingdirective block that are generated by CFML tags and often do not affect HTML appearance. Does not affect any white space in HTML code. Character encoding identified by the page byte order mark, if any; otherwise, system default encoding A string literal; cannot be a variable. Identifies the character encoding of the current CFML page. This attribute affects the entire page, not just the cfprocessing tag body. The value may be enclosed in single or double quotation marks, or none. The following list includes commonly used 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 more information on character encodings, see: www.w3.org/International/O-charset.html. Usage The cfprocssingdirective tag has limitations that depend on the attribute you use. For this reason, Macromedia recommends that you include either the pageencoding or suppresswhitespace attribute in a cfprocessingdirective tag, not both. To specify both values, use separate tags. If you use the pageEncoding attribute, the following rules apply: • You must put the tag within the first 4096 bytes of a page. It can be positioned after a or cfsilent tag. If you use the tag on a page that includes other pages by using the cfinclude or cfmodule tags, custom tag invocation, and so on, the tag has no effect on the included pages. You cannot embed the tag within conditional logic, because the pageEncoding attribute is evaluated when ColdFusion compiles a page (not when it executes the page). For example, the following code has no effect at execution time, because the cfprocessingdirective tag has already been evaluated: cfsetting • • • If you have multiple cfprocessingdirective tags in one page that specify the pageEncoding attribute, they must all specify the same value; if not, ColdFusion throws an error. • If you specify only the pageencoding attribute, do not use a separate end tag. • ColdFusion accepts character encoding names that are supported by the Java platform. If an invalid name is specified, ColdFusion throws an InvalidEncodingSpecification exception. 272 Chapter 2: ColdFusion Tags • If a page has a byte order mark (BOM), and a pageengoding attribute specifies an encoding that differs from the BOM, ColdFusion generates an error. The following rules apply to the suppressWhiteSpace attribute: • You can specify the suppresswhitespace attribute value as a constant or a variable. To use a variable: define the variable (for example, whitespaceSetting), assign it the value "Yes" or "No", and code a statement such as the following: code to whose output the setting is applied • The suppresswhitespace attribute only affects code that you put between the begin tag and the end tag. The following example shows the use of a nested cfprocessingdirective tag. The outer tag suppresses unnecessary whitespace during computation of a large table; the inner tag retains whitespace, to output a preformatted table. Example #table_data# The following example shows the use of the pageencoding attribute: cfprocessingdirective 273 cfprocparam Description Defines stored procedure parameters. This tag is nested within a cfstoredproc tag. Category Database manipulation tags Syntax See also cfinsert, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cftransaction, cfupdate History ColdFusion MX: • The maxrows attribute is obsolete. • Changed the dbvarname attribute behavior: it is now ignored for all drivers. ColdFusion MX • uses JDBC 2.2 and does not support named parameters. Changed the maxLength attribute behavior: it now applies to IN and INOUT parameter values. Attributes Attribute Req/Opt Default Description type Optional in variable Required if type = "OUT" or "INOUT" value Required if type = "IN" or "INOUT" 274 Chapter 2: ColdFusion Tags • in: The parameter is used to send data to the database system only. Passes the parameter by value. • out: The parameter is used to receive data from the database system only. Passes the parameter as a bound variable. • inout: The parameter is used to send and receive data. Passes the parameter as a bound variable. ColdFusion variable name; references the value that the output parameter has after the stored procedure is called. Value that ColdFusion passes to the stored procedure. Attribute Req/Opt Default Description CFSQLType Required SQL type to which the parameter (any type) is bound. ColdFusion supports the following values, where the last element of the name corresponds to the SQL data type. Different database systems might support different subsets of this list. See your DBMS documentation for information on supported parameter types. • CF_SQL_BIGINT • CF_SQL_BIT • CF_SQL_BLOB • CF_SQL_CHAR • CF_SQL_CLOB • CF_SQL_DATE • CF_SQL_DECIMAL • CF_SQL_DOUBLE • CF_SQL_FLOAT • CF_SQL_IDSTAMP • CF_SQL_INTEGER • CF_SQL_LONGVARCHAR • CF_SQL_MONEY • CF_SQL_MONEY4 • CF_SQL_NUMERIC • CF_SQL_REAL • CF_SQL_REFCURSOR • CF_SQL_SMALLINT • CF_SQL_TIME • CF_SQL_TIMESTAMP • CF_SQL_TINYINT • CF_SQL_VARCHAR maxLength Optional 0 Maximum length of a string or character IN or INOUT value attribute. A maxLength of 0 allows any length. The maxLength attribute is not required when specifying type=out. scale Optional 0 Number of decimal places in numeric parameter. A scale of 0 allows any number of decimal places. null Optional No Whether the parameter is passed in as a null value. Not used with OUT type parameters. • Yes: tag ignores the value attribute • No Usage Use this tag to identify stored procedure parameters and their data types. Code one cfprocparam tag for each parameter. The parameters that you code vary based on parameter type and DBMS. ColdFusion MX supports positional parameters only and you must code cfprocparam tags in the same order as the associated parameters in the stored procedure definition. Output variables are stored in the ColdFusion variable specified by the variable attribute. You cannot use the cfprocparam tag for Oracle 8 reference cursors. Instead, use the cfprocresult tag. cfprocparam 275 Example The following example shows how to invoke an Oracle 8 PL/SQL stored procedure. It makes use of Oracle 8 support of the Reference Cursor type. The following package, Foo_Data, houses a procedure refcurproc that declares output parameters as Reference Cursor: • Parameter pParam1 returns the rows in the EMP table • Parameter pParam2 returns the rows in the DEPT table The procedure declares one input parameter as an integer, and one output parameter as a twobyte char varying type. Before the cfstoredproc tag can call this procedure, it must be created, compiled, and bound in the RDBMS environment. CREATE OR REPLACE PACKAGE Foo_Data AS TYPE EmpTyp IS REF CURSOR RETURN Emp%ROWTYPE; TYPE DeptTyp IS REF CURSOR RETURN Dept%ROWTYPE; PROCEDURE refcurproc(pParam1 in out EmpTyp, pParam2 in out DeptTyp, pParam3 in integer, pParam4 out varchar2); END foo_data; CREATE OR REPLACE PACKAGE BODY Foo_Data AS PROCEDURE RefCurProc(pParam1 in out EmpTyp, pParam2 in out DeptTyp, pParam3 in integer, pParam4 out varchar2) IS BEGIN OPEN pParam1 FOR select * from emp; OPEN pParam2 FOR select * from dept; IF pParam3 = 1 THEN pParam4 : = 'hello'; ELSE pParam4 : = 'goodbye'; END IF; END RefCurProc; END Foo_Data; The following CFML example shows how to invoke the RefCurProc procedure using cfstoredproc, cfprocparam, and cfprocresult: type = "Out" CFSQLType = "CF_SQL_REFCURSOR" "param2"> type = "IN" CFSQLType = "CF_SQL_INTEGER" value = "1"> The first result set:
276 Chapter 2: ColdFusion Tags

The second result set:

The output parameter is:'#FOO#' cfprocparam 277 cfprocresult Description Associates a query object with a result set returned by a stored procedure. Other ColdFusion tags, such as cfoutput and cftable, use this query object to access the result set. This tag is nested within a cfstoredproc tag. Category Database manipulation tags Syntax See also cfinsert, cfprocparam, cfquery, cfqueryparam, cfstoredproc, cftransaction, cfupdate Attributes Attribute Req/Opt Default Description name Required resultSet Optional 1 Names one result set, if stored procedure returns more than one. maxRows Optional -1 (All) Maximum number of rows returned in result set. Name for the query result set. Usage To enable access to data returned by the stored procedure, specify one or more cfprocresult tags. If the stored procedure returns more than one result set, use the resultSet attribute to specify which of the stored procedure’s result sets to return. The resultSet attribute must be unique within the scope of the cfstoredproc tag. If you specify a result set twice, the second occurrence overwrites the first.CFML supports Oracle 8 Reference Cursor type, which passes a parameter by reference. Parameters that are passed this way can be allocated and deallocated from memory within the execution of one application. To use reference cursors in packages or stored procedures, use the cfprocresult tag. This causes the ColdFusion JDBC database driver to put Oracle reference cursors into a result set. (You cannot use this method with Oracle's ThinClient JDBC drivers.) Example 278 Chapter 2: ColdFusion Tags The output param value: ’#foo#’

The Results Information

#name#,#DATE_COL#


Record Count: #RS1.recordCount#

Columns: #RS1.columnList#


#col1#,#col2#,#col3#


Record Count: #RS3.recordCount#

Columns: #RS3.columnList#


The return code for the stored procedure is: ’#cfstoredproc.statusCode#’
... cfprocresult 279 cfproperty Description Defines properties of a ColdFusion component (CFC). Used to create complex data types for web services. The attributes of this tag are exposed as component metadata and are subject to inheritance rules. Category Extensibility tags Syntax cfargument, cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfobject, cfreturn History ColdFusion MX: Added this tag. Attributes 280 Attribute Req/Opt Default Description name Required A string; a property name. Must be a static value. type Optional any A string; identifies the property data type: 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. Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description required Optional no Whether the parameter is required yes no default Optional If no property value is set when the component is used for a web service, specifies a default value. If this attribute is present, the required attribute must be set to "no" or not specified. displayname Optional A value to be displayed when using introspection to show information about the CFC. The value appears in parentheses following the property name. hint Text to be displayed when using introspection to show information about the CFC. This attribute can be useful for describing the purpose of the parameter. Optional Usage You must position cfproperty tags at the beginning of a component, above executable code and function definitions. If a component is not used as a web service, The cfproperty only provides metadata information when the component is viewed using introspection, for example, by opening the .cfc file directly in the browser. It does not define variables or set values that you can then use in your compoenent. For web services that you create in ColdFusion, the cfproperty tag defines complex variables used by the web service. Exceptions The following code defines a component in the file address.cfc that contains properties that represent a street address: This component represnts a complex data type that can be used in a component that is exported as a web service, such as the following: cfproperty 281 cfquery Description Passes queries or SQL statements to a data source. Macromedia recommends that you use the cfqueryparam tag within every cfquery tag, to help secure your databases from unauthorized users. For more information, see: • Security Bulletin ASB99-04, "Multiple SQL Statements in Dynamic Queries," in the • Macromedia Security Zone, http://www.macromedia.com/devnet/security/security_zone/ asb99-04.html. Chapter 20, “Accessing and Retrieving Data,” in Developing ColdFusion MX Applications Category Database manipulation tags Syntax SQL statement(s) See also cfinsert, cfprocparam, cfprocresult, cfqueryparam, cfstoredproc, cftransaction, cfupdate, chapters 19-22 of Developing ColdFusion MX Applications History ColdFusion MX: • Changed Query of Queries behavior: it now supports a larger subset of standard SQL. For • • 282 more information, see Chapter 22, “Using Query of Queries,” in Developing ColdFusion MX Applications. Changed dot notation support: ColdFusion now supports dot notation within a record set name. ColdFusion interprets such a name as a structure. For more information, see Chapter 22, “Using Query of Queries,” in Developing ColdFusion MX Applications. Deprecated the connectString, dbName, dbServer, provider, providerDSN, and sql attributes, and all values of the dbtype attribute except query. They do not work, and might cause an error, in releases later than ColdFusion 5. Chapter 2: ColdFusion Tags Attributes Attribute Req/Opt name Required Name of query. Used in page to reference query record set. Must begin with a letter. Can include letters, numbers, and underscores. dataSource Required Name of data source from which query gets data. dbtype Optional username Optional Overrides username in data source setup. password Optional Overrides password in data source setup. maxRows Optional -1 (All) Maximum number of rows to return in record set. blockFactor Optional 1 Maximum rows to get at a time from server. Range: 1 - 100. Might not be supported by some database systems. timeout cachedAfter Default Description query query. Use this value to specify the results of a query as input. Maximum number of seconds that each action of a query is permitted to execute before returning an error. The cumulative time may exceed this value. For JDBC statements, ColdFusion sets this attribute. For other drivers, check driver documentation. Optional Date value (for example, April 16, 1999, 4-16-99). If date of original query is after this date, ColdFusion uses cached query data. To use cached data, current query must use same SQL statement, data source, query name, user name, password. A date/time object is in the range 100 AD–9999 AD. When specifying a date value as a string, you must enclose it in quotation marks. cachedWithin Optional Timespan, using the CreateTimeSpan function. If original query date falls within the time span, cached query data is used. CreateTimeSpan defines a period from the present, back. Takes effect only if query caching is enabled in the Administrator. To use cached data, the current query must use the same SQL statement, data source, query name, user name, and password. debug • Yes, or if omitted: If debugging is enabled, but the Administrator Database Activity option is not enabled, displays SQL submitted to datasource and number of records returned by query. • No: If the Administrator Database Activity option is enabled, suppresses display. Optional; value and equals sign may be omitted Usage Because the timeout parameter only the maximum time for each sub-operation of a query, the cumulative time may exceed its value. To set a timeout for a page that might get a very large result set, set the Administrator > Server Settings > Timeout Requests option to an appropriate value. This tag returns data and query information from a ColdFusion data source. The cumulative query execution time, in seconds, is returned in the variable cfquery.ExecutionTime. cfquery 283 This tag creates a query object, providing this information in query variables: Variable name Description query_name.currentRow Current row of query that cfoutput is processing query_name.columnList Comma-delimited list of the query columns query_name.RecordCount Number of records (rows) returned from the query cfquery.ExecutionTime Cumulative time required to process the query You can cache query results and execute stored procedures. For information about this and about displaying cfquery output, see Developing ColdFusion MX Applications. The Caching page of the ColdFusion MX Administrator specifies the maximum number of cached queries. Setting this value to 0 disables query caching. You cannot use ColdFusion reserved words as query names. You cannot use SQL reserved words as variable or column names in a Query of Queries, unless they are escaped. The escape character is the bracket []; for example: SELECT [count] FROM MYTABLE. For a list of reserved keywords in ColdFusion MX, see Chapter 22, “Using Query of Queries,” in Developing ColdFusion MX Applications. Database query results for date and time values can vary in sequence and formatting, unless you use functions to format the results. To ensure that customers using your ColdFusion application are not confused by the display, Macromedia recommends that you use the DateFormat and TimeFormat functions to format values from queries. For more information and examples, see TechNote 22183, "ColdFusion Server (5 and 4.5.x) with Oracle: Formatting Date and Time Query Results," at www.coldfusion.com/Support/KnowledgeBase/SearchForm.cfm. Example SELECT PARKNAME, REGION, STATE FROM Parks ORDER BY ParkName, State 284 Chapter 2: ColdFusion Tags
Park Name Region State
#GetParks.CurrentRow# #ParkName# #Region# #State#
See next #MaxRows# rows
cfquery 285 cfqueryparam Description Verifies the data type of a query parameter and, for DBMSs that support bind variables, enables ColdFusion to use bind variables in the SQL statement. Bind variable usage enhances performance when executing a cfquery statement multiple times. This tag is nested within a cfquery tag, embedded in a query SQL statement. If you specify optional parameters, this tag performs data validation. Macromedia recommends that you use the cfqueryparam tag within every cfquery tag, to help secure your databases from unauthorized users. For more information, see: • Security Bulletin ASB99-04, “Multiple SQL Statements in Dynamic Queries,” at • www.macromedia.com/devnet/security/security_zone/asb99-04.html. Chapter 20, “Accessing and Retrieving Data,” in Developing ColdFusion MX Applications Category Database manipulation tags Syntax AND/OR ...additional criteria of the WHERE clause... See also cfinsert, cfprocparam, cfprocresult, cfquery, cfstoredproc, cftransaction, cfupdate 286 Chapter 2: ColdFusion Tags Attributes Attribute Req/Opt value Required Default Description Value that ColdFusion passes to the right of the comparison operator in a where clause. If CFSQLType is a date or time option, ensure that the date value uses your DBMS-specific date format. Use the CreateODBCDateTime or DateFormat and TimeFormat functions to format the date value. CFSQLType Optional CF_SQL_ SQL type that parameter (any type) is bound to. CHAR • CF_SQL_BIGINT • CF_SQL_BIT • CF_SQL_CHAR • CF_SQL_BLOB • CF_SQL_CLOB • CF_SQL_DATE • CF_SQL_DECIMAL • CF_SQL_DOUBLE • CF_SQL_FLOAT • CF_SQL_IDSTAMP • CF_SQL_INTEGER • CF_SQL_LONGVARCHAR • CF_SQL_MONEY • CF_SQL_MONEY4 • CF_SQL_NUMERIC • CF_SQL_REAL • CF_SQL_REFCURSOR • CF_SQL_SMALLINT • CF_SQL_TIME • CF_SQL_TIMESTAMP • CF_SQL_TINYINT • CF_SQL_VARCHAR maxLength Optional Length of Maximum length of parameter. string in value attribute scale Optional 0 Number of decimal places in parameter. Applies to CF_SQL_NUMERIC and CF_SQL_DECIMAL. null Optional No Whether parameter is passed as a null value. • Yes: tag ignores the value attribute • No list Optional No • Yes: The value attribute value is a delimited list • No separator Required, if , (comma) Character that separates values in list, in value attribute. you specify a list in value attribute cfqueryparam 287 Usage Use cfqueryparam in any SQL statement (for example, SELECT, INSERT, UPDATE, and DELETE) that uses ColdFusion variables. For maximum validation of string data, specify the maxlength attribute. This tag does the following: • • • • Allows the use of SQL bind parameters, which improves performance. Ensures that variable data matches the specified SQL type. Allows long text fields to be updated from a SQL statement. Escapes string variables in single quotation marks. To benefit from the enhanced performance of bind variables, you must use cfqueryparam for all ColdFusion variables, and your DBMS must support bind variables. If a DBMS does not support bind parameters, ColdFusion validates and substitutes the validated parameter value back into the string. If validation fails, it returns an error message. The validation rules are as follows: • For these types, a data value can be converted to a numeric value: CF_SQL_SMALLINT, CF_SQL_INTEGER, CF_SQL_REAL, CF_SQL_FLOAT, CF_SQL_DOUBLE, CF_SQL_TINYINT, CF_SQL_MONEY, CF_SQL_MONEY4, CF_SQL_DECIMAL, CF_SQL_NUMERIC, and CF_SQL_BIGINT • For these types, a data value can be converted to a date supported by the target data source: CF_SQL_DATE, CF_SQL_TIME, CF_SQL_TIMESTAMP • For all other types, if the maxLength attribute is used, a data value cannot exceed the maximum length specified. ColdFusion debug output shows the bind variables as question marks; it then lists the values beneath the query, in order of usage. Example

cfqueryparam Example

SELECT * FROM courses WHERE Course_ID =

Course Number: #Course_ID#
Description: #descript#

This example throws an error because the value passed in the CFQUERYPARAM tag exceeds the MAXLENGTH attribute

288 Chapter 2: ColdFusion Tags SELECT * FROM employees WHERE LastName=

Course Number: #FirstName# #LastName# Description: #Department#

cfqueryparam 289 cfregistry Description This tag is deprecated for the UNIX platform. Reads, writes, and deletes keys and values in the system registry. Provides persistent storage of client variables. Note: For this tag execute, it must be enabled in the ColdFusion Administrator. For more information, see Configuring and Administering ColdFusion MX. Category Other tags, Variable manipulation tags Syntax The tag syntax depends on the action attribute value. See the following sections. • • • • on page 291 cfregistry action = "get" on page 292 cfregistry action = "set" on page 293 cfregistry action = "delete" on page 294 cfregistry action = "getAll" See also cfcookie, cfparam, cfsavecontent, cfschedule, cfset History ColdFusion MX: • Deprecated this tag on the UNIX platform. It might not work, and might cause an error, in • 290 later releases. Changed how persistent data is stored: ColdFusion now stores most persistent data outside the system registry, in XML files. Chapter 2: ColdFusion Tags cfregistry action = "getAll" Description Returns all registry keys and values defined in a branch. You can access the values as you would any record set. Syntax Attributes Attribute Req/Opt Default Description action Required getall branch Required Name of a registry branch. type Optional String • • • • name Required Name of record set to contain returned keys and values. sort Optional ASC Sorts query column data (case-insensitive). Sorts on Entry, Type, and Value columns as text. Specify a combination of columns from query output, in a comma-delimited list. For example: string: return string values dWord: return DWord values key: return keys any: return keys and values sort = "value desc, entry asc" • asc: ascending (a to z) sort order • desc: descending (z to a) sort order Usage This tag returns #entry#, #type#, and #value# in a record set that you can access through tags such as cfoutput. To fully qualify these variables, use the record set name, as specified in the name attribute. If #type# is a key, #value# is an empty string. If you specify type= "any", getAll also returns binary registry values. For binary values, the #type# variable contains UNSUPPORTED and #value# is blank. Example

cfregistry action = "getAll"

cfregistry 291 cfregistry action = "get" Description Accesses a registry value and stores it in a ColdFusion variable. Syntax Attributes Attribute Req/Opt Default action Required get branch Required Name of a registry branch. entry Required Registry value to access. variable Required Variable into which to put value. type Optional string Description • string: return string value • dWord: return DWord value • key: return key’s default value Usage If the value does not exist, cfregistry does not create an entry. Example

cfregistry action = "get"

Java ClassPath value is #RegValue# 292 Chapter 2: ColdFusion Tags cfregistry action = "set" Description Adds a registry key, adds a value, or updates a value. Syntax Attributes Attribute Req/Opt Default Description action Required set branch Required Name of a registry branch. entry Required Key or value to set. type Optional • string: set a string value (default). • dWord: set a DWord value. • key: create a key. value Optional Value data to set. If you omit this attribute, cfregistry creates default value, as follows: • string: creates an empty string: "" • dWord: creates a value of 0 (zero) Usage If it does not exist, cfregistry creates the key or value. Example

cfregistry action = "set"

cfregistry 293 cfregistry action = "delete" Description Deletes a registry key or value. Syntax Attributes Attribute Req/Opt Default Description action Required delete branch Required • For key deletion: name of registry key to delete. Do not specify the entry. • For value deletion: name of registry branch that contains value to delete. You must specify entry. entry Required for value deletion Value to delete Usage If you delete a key, cfregistry also deletes values and subkeys defined beneath it. Example

cfregistry action = "delete"

294 Chapter 2: ColdFusion Tags cfreport Description Runs a predefined Crystal Reports report. Applies only to Windows systems. Uses the CFCRYSTAL.exe file to generate reports. Sets parameters in the Crystal Reports engine according to its attribute values. Category Extensibility tags Syntax See also cfcollection, cfexecute, cfindex, cfobject, cfsearch, cfwddx History ColdFusion MX: Changed data source connection behavior: Crystal Reports now establishes an independent connection to the data source. The connection is not subject to any ColdFusion data source-specific restrictions. For example, the Crystal Reports server can access a data source, regardless of whether it is disabled in the ColdFusion Administrator. Attributes Attribute Req/Opt Default Description datasource Optional Name of registered or native data source. type Optional standard • standard (not valid for Crystal Reports 8.0) • netscape • microsoft timeout Optional Maximum time, in seconds, in which a connection must be made to a Crystal Report. report Required Report path. Store Crystal Reports files in the same directories as ColdFusion page files. orderBy Optional Orders results according to your specifications. username Optional Username required for entry into database from which report is created. Overrides default settings for data source in ColdFusion Administrator. cfreport 295 Attribute Req/Opt Default Description password Optional Password that corresponds to username required for database access. Overrides default settings for data source in ColdFusion Administrator. formula Optional One or more named formulas. Terminate each formula with a semicolon. Use the format: formula = "formulaname1 = 'formula1';formulaname2 = 'formula2';" If you use a semicolon in a formula, you must escape it by typing it twice (;;). For example: formula = "Name1 = 'Val_1a;;Val_1b';Name2 = 'Val2';" Usage This tag requires an end tag. Example

cfreport Tag

cfreport lets reports from the Crystal Reports Professional report writer display through a ColdFusion interface. To run, the tag requires the name of the report. cfreport can also pass information to the report file displayed, to change the output conditions.

This example would run a report called "monthlysales.rpt " and pass it an optional filter condition to show only the information for a subset of the report. {Departments.Department} = ‘International’

Substitute your report files and filters for this code. cfreport can put Crystal Reports into web pages. 296 Chapter 2: ColdFusion Tags cfrethrow Description Rethrows the currently active exception. Preserves the exception’s cfcatch.type and cfcatch.tagContext variable values. Category Exception handling tags, Extensibility tags Syntax See also cferror, cfthrow, cftry Usage Use this tag within a cfcatch block. This tag is useful in error handling code, if the error handler cannot handle an error that it catches. For example, if cfcatch type = "any" gets a DATABASE exception, and the code is designed to handle only CFX exceptions, the handler raises the exceptions again, with details intact, so that a higher-level handler can process the error information. If you used the cfthrow tag, the type and details of the original exception would be lost. Example

cfrethrow Example

SELECT * FROM Messages

Sorry, this request can't be completed

Catch variables


#c# = #cfcatch[c]#
cfrethrow 297 cfreturn Description Returns result values from a component method. Contains an expression returned as result of the function. Return value An expression; the result of the function from which this tag is called. Category Extensibility tags Syntax See also cfargument, cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfobject, cfproperty History ColdFusion MX: Added this tag. Attributes Attribute Req/Opt expr Required Default Description Function result; value of any type Usage This tag is equivalent to a return statement within a cfscript tag. It accepts one return variable argument. To return more than one value, populate a structure with name-value-pairs, and return the structure with this tag. To access the result value from this tag, you use the variable scope that is the value of the cfinvoke tag returnVariable attribute. You can code a maximum of one cfreturn tag within a function. For example code, see Chapter 11, “Building and Using ColdFusion Components,” in Developing ColdFusion MX Applications. Example SELECT FIRSTNAME, LASTNAME, EMAIL FROM tblEmployees SELECT * FROM tblDepartments 298 Chapter 2: ColdFusion Tags cfreturn 299 cfsavecontent Description Saves the generated content of the cfsavecontent tag, including the results of evaluating expressions and executing custom tags, in the specified variable. Category Variable manipulation tags Syntax the content See also cfcookie, cfparam, cfregistry, cfschedule, cfset Attributes Attribute Req/Opt Default Description variable Name ofthe variable in which to save the generated content of the tag. Required Usage This tag requires an end tag. You cannot use this tag to suppress output from a tag library. Example The following example uses a custom tag to generate a report and saves the report in the variable CONTENT. It replaces all instances of the word "report" with the phrase "MyCompany Quarterly Report" and outputs the result. #replace(content, "report", "MyCompany Quarterly Report", "all")# 300 Chapter 2: ColdFusion Tags cfschedule Description Provides a programmatic interface to the ColdFusion scheduling engine. Can run a CFML page at scheduled intervals, with the option to write the page output to a static HTML page. This feature enables you to schedule pages that publish data, such as reports, without waiting while a database transaction is performed to populate the page. Category Variable manipulation tags Syntax proxyUser = "username" proxyPassword = "password" resolveURL = "Yes" or "No" History ColdFusion MX 6.1: Changed the way intervals are calculated. The day length now reflects changes between standard and daylight saving times. The month length is now the calendar month length, not four weeks. The scheduler handles leap years correctly. See also cfcookie, cfparam, cfregistry, cfsavecontent, cfset cfschedule 301 Attributes Attribute Req/Opt Default action Required • delete: deletes the specified task • update: updates an existing task or creates a new task, if one with the name specified by the task attribute does not exist • run: executes the specified task task Required Name of the task. operation Required if action = Operation that the scheduler performs. Must be HTTPRequest. "update" file Name of the file in which to store the published output of the scheuled task. Required if publish = "Yes" path startDate Description Required if publish = "Yes" Path to the directory in which to put the published file. Required if action = Date on which to first run the scheuled task. "update" startTime Required if action = Time at which to run the scheduled of task starts. "update" url Required if action = URL of the page to execute. "update" port Optional 80 Port to use on the server that is specified by the url parameter. If resolveURL = "yes", retrieved document URLs that specify a port number are automatically resolved, to preserve links in the retrieved document. A port value in the url attribute overrides this value. 302 publish Optional No • Yes: save the result to a file • No endDate Optional Date when scheduled task ends. endTime Optional Time when scheduled task ends (seconds). interval Required if action = One hour Interval at which task is scheduled. "update" • number of seconds (minimum is 60) • once • daily • weekly • monthly requestTimeOut Optional Can be used to extend the default timeout period. username Optional Username, if URL is protected. password Optional Password, if URL is protected. proxyServer Optional Host name or IP address of a proxy server. proxyPort Optional proxyUser Opt Chapter 2: ColdFusion Tags 80 Port number to use on the proxy server. User name to provide to the proxy server. Attribute Req/Opt proxyPassword Opt resolveURL Optional Default Description Password to provide to the proxy server. No • Yes: resolve links in the output page to absolute references • No Usage This tag and the ColdFusion MX Administrator Scheduled task page schedule ColdFusion tasks. Tasks that you add or change using this tag are visible in the Aministrator. You can disable this tag in the Administrator Sandbox/Resource security page. This tag’s success or failure status is written to the \cfusion\log\schedule.log file. When you create a task, you specify the URL of the ColdFusion page to execute, the date, time and frequency of execution, and whether to publish the task output to a HTML file. If the output is published, you specify the ouptupt file path and file. If you schedule a job to run monthly on any date in the range 28-31, the scheduler does the following: • If you schedule a monthly job to run on the last day of a month, the scheduled job will run on the last day of each month. For example, if you schedule a monthly job to start on January 31, it will run on Januray 31, February 28 or 29, March 31, April 30, and so on. • If you schedule a monthly job to run on the 29th or 30th of the month, the job will run on the specified day of each month for 30 or 31-day months, and the last day of February. For example, if you schedule a monthly job to start on January 30, the job will run on January 30, February 28 or 29, March 30, April 30, and so on. If you schedule a job to run once, the starting time is in the past, and the task has not yet run, it runs immediately. If you schedule a recurring job with a start time in the past, ColdFusion schedules the job to run on the next closest interval in the future. The Scheduler configuration file, cf_root\lib\neo-cron.xml contains all scheduled events, as individual entries. Example

cfschedule Example

cfschedule 303 cfscript Description Encloses a code block that contains cfscript statements. Category Application framework tags, Other tags Syntax cfscript code here See also cfinvoke, cfmodule, CreateObject, Chapter 6, “Extending ColdFusion Pages with CFML Scripting,” in Developing ColdFusion MX Applications History ColdFusion MX: • Changed how to invoke component methods: this tag can now invoke component methods, • • using the createObject function Changed use of reserved words: you cannot use ColdFusion reserved words within this tag Added the try and catch statements. Usage Performs processing in CFScript. This tag uses ColdFusion functions, expressions, and operators. You can read and write ColdFusion variables within this tag. For a detailed description of the CFScript scripting language, including documentation of CFScript statements and the CFScript equivalents of CFML tags, see Chapter 6, “Extending ColdFusion Pages with CFML Scripting,” in Developing ColdFusion MX Applications. You can use this tag to enclose a series of assignment statements that would otherwise require cfset statements. Caution: If you code a cftry/cfcatch block within this tag using an exception’s Java class name, you must provide the fully-qualified class name. You cannot use some ColdFusion reserved words in this tag. You cannot put a user-defined function whose name begins with any of these strings within this tag: • • • • • • 304 cf cf_ _cf coldfusion coldfusion_ _coldfusion Chapter 2: ColdFusion Tags You cannot use the elseif construct within a cfscript tag. You can use code such as the following: else if ( condition ) { ... } Exception handling with the cfscript tag To handle exceptions with this tag, use try and catch statements, which are equivalent to the cftry and cfcatch tags. For each try statement, you must have a catch statement. In the catch block, the variable exceptionVariable contains the exception type. This variable is the equivalent of the cfcatch tag built-in variable cfcatch.Type. For more information, see Chapter 6, “Extending ColdFusion Pages with CFML Scripting,” in Developing ColdFusion MX Applications. Invoking ColdFusion components with the cfscript tag CFScript invokes component methods using the createObject function. The following example shows how to invoke a component object with the cfscript tag, using ordered arguments: quote = createObject( “component”, “nasdaq.quote” ) ; res = quote.getLastTradePrice( “macr” ) ; The following example shows how to use an attribute collection within the cfscript tag to pass parameters when invoking a component object. An attribute collection is a structure in which each key corresponds to a parameter name and each value is the parameter value passed for the corresponding key. stArgs = structNew(); stArgs.translationmode = "en_es"; stArgs.sourceData= "Hello world, friend"; ... #varName# In this example, the structure is created in a cfscript block, but you can use any ColdFusion method to create the structure. Consuming web services with the cfscript tag The following example shows how to consume a web service with the cfscript tag. You use the CreateObject function to connect to the web service. ws = CreateObject("webservice", "http://www.xmethods.net/sd/2001/BabelFishService.wsdl"); cfscript 305 xlatstring = ws.BabelFish("en_es", "Hello world, friend"); writeoutput(xlatstring); For more information, see Chapter 32, “Using Web Services,” in Developing ColdFusion MX Applications. Example

This simple example shows variable declaration and manipulation. y = x; z = 2 * y; StringVar = form.myString;

twice #x# is #z#.

Your string value was: #StringVar# 306 Chapter 2: ColdFusion Tags cfsearch Description Searches Verity collections using ColdFusion or K2Server, whichever search engine a collection is registered by. (ColdFusion can also search collections that have not been registered, with the cfcollection tag.) A collection must be created and indexed before this tag can return search results. A collection can be created in these ways: • With the cfcollection tag • In the ColdFusion Administrator, which calls the cfcollection tag • Externally, using a native Verity indexing tool, such as Vspider or MKVDK A collection can be registered with ColdFusion in the following ways: • With the cfcollection tag • In the ColdFusion Administrator, which calls the cfcollection tag A collection can be registered with K2Server by editing the k2server.ini file. A collection can be indexed in the following ways: • In ColdFusion, with the cfindex tag • In the ColdFusion Administrator, which calls the cfindex tag • Using a native Verity indexing tool, such as Vspider or MKVDK For more information, see Chapter 24, “Building a Search Interface,” in Developing ColdFusion MX Applications. Category Extensibility tags Syntax See also cfcollection, cfexecute, cfindex, cfobject, cfreport, cfwddx History ColdFusion MX: • Deprecated the external attribute. It might not work, and might cause an error, in later • releases. (ColdFusion stores this information about each collection; it automatically detects whether a collection is internal or external.) This tag supports absolute (also known as fully qualified) collection pathnames and mapped collection names. Changed query result behavior: the cfindex tag can index the query results from a cfsearch operation. cfsearch 307 • Changed Verity operations behavior: ColdFusion supports Verity operations on Acrobat PDF files. • Changed multiple collection behavior: this tag can search multiple collections. In a multiple • • • collection search, you cannot combine collections that are registered with K2Server and registered in another way. Changed acceptable collection naming: this tag accepts collection names that include spaces. Changed the following support: this tag supports Verity 2.6.1 and the LinguistX and ICU locales. Changed thrown exceptions: this tag can throw the SEARCHENGINE exception. Attributes Attribute Req/Opt name Default Description Required Name of the search query. collection Required type Optional criteria Optional One or more path(s) and/or registered collection name(s). For a registered collection, specify the collection name. For an unregistered collection, specify an absolute path. Registered names are listed in the ColdFusion Administrator, Verity Collections and Verity Server pages. To specify multiple collections, use a comma delimiter. For example: "CFUSER, e:\collections\personnel" If you specify multiple collections, you cannot include a combination of collections that are registered by K2Server and registered by Verity. simple • simple: STEM and MANY operators are implicitly used. See Chapter 25, “Using Verity Search Expressions,” in Developing ColdFusion MX Applications. • explicit: operators must be invoked explicitly Search criteria. Follows the syntax rules of the type attribute. If you pass a mixed-case entry in this attribute, the search is casesensitive. If you pass all uppercase or all lowercase, the search is case-insensitive. Follow Verity syntax and delimiter character rules; see Chapter 25, “Using Verity Search Expressions,” in Developing ColdFusion MX Applications. maxRows Optional All Maximum number of rows to return in query results. Use double or single quotation marks. startRow Optional 1 First row number to get. language Optional english For options, see cfcollection on page 80. Requires the ColdFusion International Search Pack. Usage To permit application users to search Verity collections for non-standard strings, words or characters (for example, "AB23.45.67" or "--->") that would otherwise cause an error, you can create a text file that lists these elements and defines their formats for Verity. Name the file style.lex and put copies of the file in these directories: • Windows: ■ ■ 308 cf_root\lib\common\style (typically, cf_root = c:\cfusionmx) cf_root\lib\common\style\custom Chapter 2: ColdFusion Tags cf_root\lib\common\style\file Unix: ■ cf_root/lib/common/style (typically, cf_root = /opt/coldfusionmx) ■ cf_root/lib/common/style/custom ■ cf_root/lib/common/style/file ■ • Note: To search for a character such as an angle bracket (< or >), you must use a criteria attribute value such as "<:" or "<:". The bracket characters are reserved in Verity, and using a backslash to escape the character (criteria="\<") does not work in this context. For more information, see Chapter 25, “Using Verity Search Expressions,” in Developing ColdFusion MX Applications. Macromedia does not recommend using the cflock tag with this tag; Verity provides the locking function. Using the cflock tag slows search performance. This tag returns a record set whose columns you can reference in a cfoutput tag. For example, the following code specifies a search for the exact terms "filming" or "filmed":

Search Result total = #name.RecordCount#
url=#name.url#
key=#name.key#
title=#name.title#
score=#name.score#
custom1=#name.custom1#
custom2=#name.custom2#
summary=#name.summary#
recordcount=#name.recordcount#
currentrow=#name.currentrow#
columnlist=#name.columnlist#
recordssearched=#name.recordssearched#

url=#url#
key=#key#
title=#title#
score=#score#
custom1=#custom1#
custom2=#custom2#
summary=#summary#
recordcount=#recordcount#
currentrow=#currentrow#
columnlist=#columnlist#
recordssearched=#recordssearched#

url=#book.url#
key=#book.key#
title=#book.titleE#
score=#book.score#
custom1=#book.custom1#
custom2=#book.custom2#
summary=#book.summary#
recordcount=#book.recordcount#
currentrow=#book.currentrow#
columnlist=#book.columnlist#
recordssearched=#book.recordssearched#

cfsearch 311 cfselect Description Constructs a drop-down list box form control. Used within a cfform tag. You can populate the list from a query, or by using the HTML option tag. Category Forms tags Syntax See also cfapplet, cfform, cfgrid, cfinput, cfgridcolumn, cfgridrow, cfgridupdate, cfslider, cftextinput, cftree, cftreeitem Attributes 312 Attribute Req/Opt Default Description name Required size Optional 1 Number of entries to display at one time. The default, 1, displays a drop-down list. Any other value displays a list box with size number of entries visible at one time. required Optional No • Yes: a list element must be selected when form is submitted. Note: This attribute has no effect if you omit the size attribute or set it to 1 because the browser always submits the displayed item. • No message Optional Message to display if required = "Yes" and no selection is made. onError Optional Custom JavaScript function to execute if validation fails multiple Optional query Optional Name of query to populate drop-down list. selected Optional A list of option values to preselect in the selection list. This attribute applies only if list items are generated from a query. The cfform preservedata attribute value can override this value. Name of the select form element No Chapter 2: ColdFusion Tags • Yes: allow selecting multiple elements in drop-down list • No Attribute Req/Opt value Optional display Optional Default Description Query column to use for the value of each list element. Used with query attribute. Value of Query column to use for the display label of each list element. value Used with query attribute. attribute passThrough Optional Passes one or more arbitrary attribute-value pairs to the HTML code that is generated for the tag. You can use either of the following formats to include the quotation marks around the attribute value: passthrough="ID=""myID""" passthrough=’ID="myID"’ The second format, which surrounds all the attribute-value pairs to be passed through in single quotation marks is clearer, particularly when you pass multiple HTML attributes. In addition to the listed attributes, you can use the following HTML attributes in the cfform tag without using the passThrough attribute. The tag does not use these attributes, but includes them in the HTML of the form tag that it generates and returns to the browser: • • • • • • • • • class id onBlur onChange onClick onDblclick onFocus style tabIndex Usage To ensure that a selected list box item persists across postbacks, use the cfform preserveData attribute with a list generated from a query. (This strategy works only with data that is populated from a query.) If the cfform preserveData attribute is true and the form posts back to the same page, and if the control is populated by a query, the posted selection(s) for the cfselect control are used instead of the Selected attribute. For controls that are populated with regular HTML option tags, the developer must dynamically add the Selected attribute to the appropriate option tag(s). For this tag to work properly. the browser must be JavaScript-enabled. To add other HTML tag attributes and values to this tag, use the passThrough attribute. They are passed through to the select tag that ColdFusion generates for the cfselect control when creating a form. The supported HTML attributes are: CLASS, ID, MAXLENGTH, MESSAGE, ONBLUR, ONCHANGE, ONCLICK, ONDBLCLICK, ONFOCUS, SIZE, STYLE, and TABINDEX. If you put a value in quotation marks, you must escape them; for example: passThrough = "readonly = " "yes " " " For more information, see the cfform tag entry. This tag requires an end tag. cfselect 313 Example SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees WHERE 0=0 AND LastName = '#employeeNames#'

cfselect Example

cfselect Presentation of Data

Click on an employee’s last name and hit "see information for this employee" to see expanded information.

cftree Presentation of Data

Click on the folders to "drill down" and reveal information.

CFGRID Presentation of Data

cfselect 315 cfservlet Description This tag is deprecated. Executes a Java servlet on a JRun engine. To access servlets that run on the same server as ColdFusion, use code such as the following, in which path specifies a servlet, JSP, or anything else: GetPageContext().include(path) GetPageContext().forward(path) For more information, see the JSP PageContext API or the Servlet RequestDispatcher API. History ColdFusion MX: Deprecated this tag. It might not work, and it might cause an error, in later releases. 316 Chapter 2: ColdFusion Tags cfservletparam Description This tag is deprecated. A child tag of the cfservlet tag. Passes data to a servlet. Each cfservletparam tag within the cfservlet block passes a separate item of data to the servlet. To access servlets that run on the same server as ColdFUsion, use code such as the following, in which path specifies a servlet, JSP, or anything else: GetPageContext().include(path) GetPageContext().forward(path) For more information, see the JSP PageContext API or the Servlet RequestDispatcher API. History ColdFusion MX: Deprecated this tag. It might not work, and it might cause an error, in later releases. cfservletparam 317 cfset Description Sets a value in ColdFusion. Used to create a variable, if it does not exist, and assign it a value. Also used to call functions. Category Variable manipulation tags Syntax See also cfcookie, cfparam, cfregistry, cfsavecontent, cfschedule Attributes Attribute Req/Opt Default Description var Optional A keyword. Does not take a value. Identifies the variable as being local to a function. The variable only exists for the time of the current invocation of the function. variable_name Required Variable Usage The following sections provide detailed descriptions of some of the uses for the cfset tag. Calling Functions When you use the cfset tag to call a function, you do not need to assign the function return value to a variable if the function does not return a value or you do not need to use the value returned by the function. For example, the following line is a valid ColdFusion cfset tag for deleting the MyVariable variable from the Application scope: Arrays The following example assigns a new array to the variable months: This example creates a variable Array_Length that resolves to the length of the array Scores: This example assigns, to index position two in the array months, the value February: Dynamic variable names In this example, the variable name is itself a variable: 318 Chapter 2: ColdFusion Tags Function local variables The var keyword specifies that the variable being defined is only available inside the body of a function that you define using the cffunction tag. The variable value that is set in one invocation of the function is not available in any other invocation of the function. The var keyword is the equivalent of the var statement in CFScript. The following rules apply to the var keyword: • Any cfset tag that uses the var keyword must be inside the body of a cffunction tag. If you use the var keyword in a cfset tag outside a cffunction tag body, ColdFusion displays an error message. • You must place all cfset tags that use the var keyword at the beginning of the cffunction tag body, before any other ColdFusion tags. The following example shows how to use the new keyword: #myFunct()# In this example, the variable myVar exists only when the function myFunct executes, and it is not available elsewhere on the ColdFusion page. COM objects In this example, a COM object is created. A cfset defines a value for each method or property in the COM object interface. The last cfset creates a variable to store the return value from the COM object's SendMail method. #success# Example SELECT * FROM Messages

cfset Example

cfset sets and reassigns values to local or global variables within a page.

For example, the variable NumRecords has been declared on this page to hold the number of records returned from query (#NumRecords#). cfset 319

In addition, cfset can be used to pass variables from other pages, such as this example, which takes the url parameter Test from this link: ( ">click here) to display a message:

#url.test#

The variable url.test has not been passed from another page.

cfset can also be used to collect environmental variables, such as the time, the IP address of the user, or another function or expression. user_ip = CGI.REMOTE_ADDR> complex_expr = (23 MOD 12) * 3> str_example = Reverse(Left(GetMessages.body, 35))>

  • The date: #the_date#
  • User IP Address: #user_ip#
  • Complex Expression ((23 MOD 12) * 3): #complex_expr#
  • String Manipulation (the first 35 characters of the body of the first message in our query)
    Reversed: #str_example#
    Normal: #Reverse(str_example)#
320 Chapter 2: ColdFusion Tags cfsetting Description Controls aspects of page processing, such as the output of HTML code in pages. Category Page processing tags, Variable manipulation tags Syntax See also cfcache, cfflush, cfheader, cfhtmlhead, cfinclude, cfsilent History ColdFusion MX 6.1: Changed behavior: if the tag has a body, ColdFusion executes its contents. ColdFusion MX: • Added the requestTimeOut attribute. • The catchExceptionsByPattern attribute is obsolete. It does not work, and causes an error, • in releases later than ColdFusion 5. Changed exception handling: the structured exception manager searches for the best-fit cfcatch handler. (In earlier releases, an exception was handled by the first cfcatch block that could handle an exception of its type.) Attributes Attribute Req/Opt Default Description enableCFoutputOnly Required showDebugOutput Optional requestTimeout Optional • Yes: blocks output of HTML that is outside cfoutput tags • No: displays HTML that is outside cfoutput tags. Yes • Yes: If debugging is enabled in the Administrator, displays debugging information • No: suppresses debugging information that would otherwise display at end of generated page. • Integer; number of seconds. Time limit, after which ColdFusion processes the page as an unresponsive thread. Overrides the timeout set in the ColdFusion Administrator. Usage The cfsetting requestTimeout attribute replaces the use of requestTmeOut within a URL. To enforce a page timeout, detect the URL variable and use code such as the following to change the page timeout: You can use this tag to manage whitespace in ColdFusion output pages. cfsetting 321 If you nest cfsetting tags: to make HTML output visible, you must match each enableCFoutputOnly = "Yes" statement with an enableCFoutputOnly = "No" statement. For example, after five enableCFoutputOnly = "Yes" statements, to enable HTML output, you must have five corresponding enableCFoutputOnly = "No" statements. If HTML output is enabled (no matter how many enableCFoutputOnly = "No" statements have been processed) the first enableCFoutputOnly = "Yes" statement blocks output. Note: If the debugging service is enabled and showDebugOutput =" Yes", the IsDebugMode function returns Yes; otherwise, No. ColdFusion MX 6.1 allows a end tag; however, this end tag does not effect processing. The cfsetting attributes affect code inside and outside the cfsetting tag body. ColdFusion MX ignored code between cfsetting start and end tags. Example

CFSETTING is used to control the output of HTML code in ColdFusion pages. This tag can be used to minimize the amount of generated whitespace. This text is shown

Text within cfoutput is

Text within cfoutput is 322 Chapter 2: ColdFusion Tags "Yes"> "No"> "Yes"> always shown "No"> always shown cfsilent Description Suppresses output produced by CFML within a tag’s scope. Category Data output tags, Page processing tags Syntax ... See also cfcache, cfflush, cfheader, cfhtmlhead, cfinclude, cfsetting Usage This tag requires an end tag. Example

cfsilent

Inside cfsilent block
b-a = #c#

Even information within cfoutput tags does not display within a cfsilent block.
b-a = #c#

cfsilent 323 cfslider Description Puts a slider control, for selecting a numeric value from a range, in a ColdFusion form. The slider moves over the slider groove. As the user moves the slider, the current value displays. Used within a cfform tag. Category Forms tags Syntax See also cfapplet, cfinput, cfform, cfselect, cftextinput, cftree, cftreeitem History ColdFusion MX: Deprecated the img, imgStyle, and grooveColor attributes. They might not work, and might cause an error, in later releases. Attributes 324 Attribute Req/Opt Default Description name Required Name of cfslider control. label Optional Label to display with control; for example, "Volume" This displays: "Volume %value%" To reference the value, use "%value%". If %% is omitted, slider value displays directly after label. Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description refreshLabel Optional Yes • Yes: when user moves slider, label is refreshed • No range Optional "0,100" Numeric slider range values. Separate values with a comma. scale Optional value Optional onValidate Optional Custom JavaScript function to validate user input; in this case, a change to the default slider value. Specify only the function name. message Optional Message text to appear if validation fails. onError Optional Custom JavaScript function to execute if validation fails. Specify only the function name. height Optional width Optional Slider control width, in pixels. vSpace Optional Vertical spacing above and below slider, in pixels. hSpace Optional Horizontal spacing to left and right of slider, in pixels. align Optional Alignment of slider • top • left • bottom • baseline • texttop • absbottom • middle • absmiddle • right tickMarkMajor Optional No • Yes: render major tickmarks in slider scale. • No: no major tickmarks. Major tick marks display at intervals specified by scale. tickMarkMinor Optional No • Yes: render minor tickmarks in slider scale. • No: no minor tickmarks Minor tickmarks display between major tickmarks. tickMarkImages Optional Unsigned integer. Defines slider scale, within range. For example, if range = "0,1000" and scale = "100", the display values are: 0, 100, 200, 300, ... Signed and unsigned integers in ColdFusion are in the range -2,147,483,648 to 2,147,483,647. Minimum Starting slider setting. Must be within the range values. in range 40 Slider control height, in pixels. Comma-delimited list of URLs specifying images in slider tickmark scale. If you do not specify enough values, the last value is repeated for remaining tickmarks. If you specify too many values, extra values are ignored. cfslider 325 Attribute Req/Opt Default Description tickMarkLabels Optional No • yes: numeric tickmarks based on the value of the range and scale attributes. • no: prevents label text from displaying • Comma-delimited list of strings for tickmark labels; for example, "ten, twenty, thirty, forty" If you do not specify enough values, the last value is repeated for remaining tickmarks. If you specify too many values, extra values are ignored. lookAndFeel Optional Windows • motif: renders slider using Motif style • windows: renders slider using Windows style • metal: renders slider using Java Swing style If platform does not support choice, the tag defaults to the platform’s default style. vertical Optional No bgColor Optional Background color of slider label. For a hex value, use the form: bgColor = "##xxxxxx", where x = 0-9 or A-F; use two pound signs or none. • Any color, in hex format • black • red • blue • magenta • cyan • orange • darkgray • pink • gray • white • lightgray • yellow textColor Optional Options: same as for bgcolor attribute font Optional Font name for label text. fontSize Optional Font size for label text, in points. italic Optional No • Yes: italics label text • No: normal text bold Optional No • Yes: bold label text • No: medium text notSupported Optional • Yes: renders slider in browser vertically. You must set width and height attributes; ColdFusion does not automatically swap width and height values. • No: renders slider horizontally. 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: " Browser must support Java to view ColdFusion Java Applets" Default message: Browser must support Java to
view ColdFusion Java Applets!
326 Chapter 2: ColdFusion Tags Usage This tag requires the client to download a Java applet. Using this tag may be slightly slower than using an HTML form element to display the same information. For this tag to work properly. the browser must be JavaScript-enabled. If the following conditions are true, a user’s selection from query data that populates this tag’s options continues to display after the user submits the form: • The cfform preserveData attribute is set to "Yes" • The cfform action attribute posts to the same page as the form itself (this is the default), or the action page has a form that contains controls with the same names as corresponding controls on the user entry form For more information, see the cfform tag entry. Example

cfslider Example

cfslider, used within a cfform, can provide functionality to Java-enabled browsers.

Try moving the slider back and forth to see the real-time value change. Then, submit the form to show how cfslider passes its value on to a new page.

You slid to a value of #mySlider#

Try again! 100

cfslider 327 cfstoredproc Description Executes a stored procedure in a server database. It specifies database connection information and identifies the stored procedure. Category Database manipulation tags Syntax See also cfinsert, cfqueryparam, cfprocparam, cfprocresult, cftransaction, cfquery, cfupdate History ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5. (ColdFusion MX uses Type 4 JDBC drivers.) Attributes Attribute Req/Opt Default Description procedure Required Name of stored procedure on database server. dataSource Required Name of data source that points to database that contains stored procedure. username Optional Overrides username in data source setup. password Optional Overrides password in data source setup. blockFactor Optional 1 Maximum number of rows to get at a time from server. Range is 1 to 100. debug Optional No • Yes: Lists debug information on each statement • No returnCode Optional No • Yes: Tag populates cfstoredproc.statusCode with status code returned by stored procedure. • No Usage Use this tag to call a database stored procedure. Within this tag, you code cfprocresult and cfprocparam tags as follows: • 328 cfprocresult cfprocresult If the stored procedure returns one or more result sets, code one tag per result set. Chapter 2: ColdFusion Tags • If the stored procedure uses input or output parameters, code one tag per parameter. Additionally, you must code cfprocparam tags in the same order as the parameters in the stored procedure definition. If you set returnCode = "Yes", this tag sets the variable cfstoredproc.statusCode, which holds the status code for a stored procedure. Status code values vary by DBMS. For the meaning of code values, see your DBMS documentation. cfprocparam cfprocparam This tag sets the variable cfstoredproc.ExecutionTime, which contains the execution time of the stored procedure, in milliseconds. Before implementing this tag, ensure that you understand stored procedures and their usage. The following examples use a Sybase stored procedure; for an example of an Oracle 8 stored procedure, see cfprocparam. Example cfstoredproc 329 cfswitch Description Evaluates a passed expression and passes control to the cfcase tag that matches the expression result. You can, optionally, code a cfdefaultcase tag, which receives control if there is no matching cfcase tag value. Category Flow-control tags Syntax one or more cfcase tags zero or one cfdefaultcase tags See also cfcase, cfdefaultcase also cfabort, cfloop, cfbreak, cfrethrow, cfexecute, cfexit, cfthrow, cfif, cftry, cflocation History ColdFusion MX: Changed cfdefaultcase tag placement requirements: you can put the cfdefaultcase tag at any position within a cfswitch statement; it is not required to be the last item. Attributes Attribute Req/Opt expression Required Default Description ColdFusion expression that yields a scalar value. ColdFusion converts integers, real numbers, Booleans, and dates to numeric values. For example, True, 1, and 1.0 are all equal. Usage This tag requires an end tag. All code within this tag must be within a cfcase or cfdefaultcase tag. Otherwise, ColdFusion throws an error. Use this tag followed by one or more cfcase tags. Optionally, include a cfdefaultcase tag. This tag selects the matching alternative from the cfcase and cfdefaultcase tags, jumps to the matching tag, and executes the code between the cfcase start and end tags. The cfswitch tag provides better performance than a series of cfif/cfelseif tags, and the code is easier to read. Example SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees

cfswitch Example

330 Chapter 2: ColdFusion Tags

Each time the case is fulfilled, the specific information is printed; if the case is not fulfilled, the default case is output

#FirstName# #LastName# is in sales

#FirstName# #LastName# is in accounting

#FirstName# #LastName# is in administration

#FirstName# #LastName# is not in Sales, Accounting, or Administration.

cfswitch 331 cftable Description Builds a table in a ColdFusion page. This tag renders data as preformatted text, or, with the HTMLTable attribute, in an HTML table. If you don't want to write HTML table tag code, or if your data can be presented as preformatted text, use this tag. Preformatted text (defined in HTML with the
 and 
tags) displays text in a fixedwidth font. It displays white space and line breaks exactly as they are written within the pre tags. For more information, see an HTML reference guide. To define table column and row characteristics, use the cfcol tag within this tag. Category Data output tags Syntax ... See also cfcol, cfoutput, cfcontent, cfprocessingdirective, cflog, cftable Attributes 332 Attribute Req/Opt Default Description query Required Name of cfquery from which to draw data. maxRows Optional Maximum number of rows to display in the table. colSpacing Optional 2 Number of spaces between columns headerLines Optional 2 Number of lines to use for table header (the default leaves one line between header and first row of table). HTMLTable Optional Renders data in an HTML 3.0 table. If you use this attribute (regardless of its value), ColdFusion renders data in an HTML table. border Optional Displays border around table. If you use this attribute (regardless of its value), ColdFusion displays a border around the table. Use this only if you use the HTMLTable attribute. Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description colHeaders Optional startRow Optional Displays column heads. If you use this attribute, you must also use the cfcol tag header attribute to define them. If you use this attribute (regardless of its value), ColdFusion displays column heads. 1 The query result row to put in the first table row. Usage This tag aligns table data, sets column widths, and defines column heads. At least one cfcol tag is required within this tag. You must put cfcol and cftable tags adjacent in a page. The only tag that you can nest within this tag is the cfcol tag. You cannot nest cftable tags. To display the cfcol header text, you must specify the cfcol header and the cftable colHeader attribute. If you specify either attribute without the other, the header does not display and no error is thrown. Example SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees

cftable Example

cftable 333 cftextinput Description Puts a single-line text entry box in a cfform tag and controls its display characteristics. Category Forms tags Syntax See also cfapplet, cfform, cfgrid, cfgridcolumn, cfgridrow, cfgridupdate, cfinput, cfselect, cfslider, cftree, cftreeitem History ColdFusion MX 6.1: Changed the validate = "creditcard" option requirements: the text entry must have 13-16 digits. Attributes 334 Attribute Req/Opt name Required Name for the cftextinput control. value Optional Initial value to display in text control. required Optional range Optional Chapter 2: ColdFusion Tags Default Description No • Yes: the user must enter or change text • No Minimum–maximum value range, delimited by a comma. Valid only for numeric data. Attribute Req/Opt validate Optional Default Description • • • • • • • • • • date: verifies format mm/dd/yy. eurodate: verifies date format dd/mm/yyyy. time: verifies time format hh:mm:ss. float: verifies floating point format. integer: verifies integer format. telephone: verifies telephone format ###-###-####. The separator can be a blank. Area code and exchange must begin with digit 1 - 9. zipcode: verifies, in U.S. formats only, 5- or 9-digit format #####-####. The separator can be a blank. creditcard: strips blanks and dashes; verifies number using mod10 algorithm. Number must have 13-16 digits. social_security_number: verifies format ###-##-####. The separator can be a blank. regular_expression: matches input against pattern attribute. onValidate Optional Custom JavaScript function to validate user input. The form object, input object, and input object value are passed to routine, which should return True if validation succeeds, False otherwise. The validate attribute is ignored. pattern Required if validate = "regular_ expression" JavaScript regular expression pattern to validate input. Omit leading and trailing slashes. message Optional Message text to display if validation fails. onError Optional Custom JavaScript function to execute if validation fails. size Optional Number of characters displayed before horizontal scroll bar displays. font Optional Font name for text. fontSize Optional Font size for text. italic Optional No • Yes: italics text • No: normal text bold Optional No • Yes: bold text • No: medium text height Optional 40 Height of the control, in pixels. width Optional 200 Width of the control, in pixels. vSpace Optional Vertical spacing of the control, in pixels. hSpace Optional Horizontal spacing of the control, in pixels. cftextinput 335 Attribute Req/Opt align Optional Alignment of text entry box with respect to adjacent HTML content: • top • left • bottom • baseline • texttop • absbottom • middle • absmiddle • right bgColor Optional Background color of control. For a hex value, use the form: textColor = "##xxxxxx", where x = 0-9 or A-F; use two pound signs or none. • any color, in hex format • black • red • blue • magenta • cyan • orange • darkgray • pink • gray • white • lightgray • yellow textColor Optional Text color for control. Options: same as for bgcolor attribute. maxLength Optional The maximum length of text entered. notSupported Optional Default Description 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 = " Browser must support Java to view ColdFusion Java Applets" If no message is specified, this message displays: Browser must support Java to
view ColdFusion Java Applets!
Usage This tag requires the client to download a Java applet. Downloading an applet takes time; therefore, using this tag might be slightly slower than using an HTML form element or the cfinput tag to get the same information. For this tag to work properly. the browser must be JavaScript-enabled. If the following conditions are true, a user’s selection from query data that populates this tag’s options continues to display after the user submits the form: • The cfform preserveData attribute is set to "Yes" 336 Chapter 2: ColdFusion Tags • The cfform action attribute posts to the same page as the form itself (this is the default), or the action page has a form that contains controls with the same names as corresponding controls on the user entry form For more information, see cfform. If the cfform preserveData attribute is "yes", and the form posts back to the same page, the posted value (not the value of the value attribute) of the cftextinput control is used. Example

cftextinput Example

cftextinput provides simple validation for text fields in cfform and control over font information displayed in cfform input boxes for text. For example, the field below must not be blank, and provides a client-side message upon erring.

You entered #form.myInput# into the text box

cftextinput 337 cfthrow Description Throws a developer-specified exception, which can be caught with a cfcatch tag that has any of the following type attribute options: • • • type = "custom_type" type = "Application" type = "Any" Category Exception handling tags, Flow-control tags Syntax 1 Syntax 2 See also cferror, cfrethrow, cftry, Chapter 14, “Handling Errors,” in Developing ColdFusion MX Applications History ColdFusion MX: Changed thrown exceptions: this tag can throw ColdFusion component method exceptions. Attributes 338 Attribute Req/Opt Default Description type Optional message Optional Message that describes exception event. detail Optional Description of the event. ColdFusion appends error position to description; server uses this parameter if an error is not caught by your code. errorCode Optional A custom error code that you supply. extendedInfo Optional A custom error code that you supply. object Requires the value of the cfobject tag name attribute. Throws a Java exception from a CFML tag. This attribute is mutually exclusive with all other attributes of this tag. Application • A custom type • Application Do not enter another predefined type; types are not generated by ColdFusion applications. If you specify Application, you need not specify a type for cfcatch. Optional Chapter 2: ColdFusion Tags Usage Use this tag within a cftry block, to throw an error. The cfcatch block can access accompanying information, as follows: • Message, with cfcatch.message • Detail, with cfcatch.detail • Error code, with cfcatch.errorcode To get more information, use cfcatch.tagContext. This array shows where control switches from one page to another in the tag stack (for example, cfinclude, cfmodule). To display the information displayed by tagContext: in the ColdFusion MX Administrator, Debugging page, select Enable CFML Stack Trace. Using the object parameter To use this tag with the object parameter, you must first use a cfobject tag that specifies a valid Java exception class. For example, the following cfobject tag defines an object, obj, of the exception class myException (which you must create in Java): If your exception class has constructors that take parameters, such as a message, you can use the special init method to invoke the constructor, as in the following line. If you do not need to specify any constructor attributes, you can omit this step. You can then use the, the cfthrow statement to throw the exception as follows: For more information on using Java objects in ColdFusion, see Chapter 33, “Integrating J2EE and Java Elements in CFML Applications,”in Developing ColdFusion MX Applications. Example1

cfthrow Example

You've Thrown an Error

#cfcatch.message#

The contents of the tag stack are:


#i# #sCurrent["ID"]# cfthrow 339 (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#) #sCurrent["TEMPLATE"]#
Example2 The following example shows how to throw an exception from a component method: SELECT LASTNAME, FIRSTNAME, EMAIL FROM tblEmployees WHERE LASTNAME LIKE '#arguments.lastName#' For an explanation of the example and more information, see Chapter 11, “Building and Using ColdFusion Components,” in Developing ColdFusion MX Applications. 340 Chapter 2: ColdFusion Tags cftrace Description Displays and logs debugging data about the state of an application at the time the cftrace tag executes. Tracks runtime logic flow, variable values, and execution time. Displays output at the end of the request or in the debugging section at the end of the request; or, in Dreamweaver MX and later, in the Server Debug tab of the Results window. ColdFusion logs cftrace output to the file logs\cftrace.log, in the ColdFusion installation directory. Note: To permit this tag to execute, you must enable debugging in the ColdFusion Administrator. Optionally, to report trace summaries, enable the Trace section. Category Debugging tags, Variable manipulation tags Syntax See also Chapter 18, “Debugging and Troubleshooting Applications,” in Developing ColdFusion MX Applications cfdump, cferror, cfrethrow, cftry, History ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description abort Optional • Yes: calls cfabort tag when the tag is executed • No category Optional inline Optional text Optional No User-defined string for identifying trace groups No • Yes: displays trace code in line on the page in the location of the cftrace tag, addition to the debugging information output. • No User-defined string, which can include simple variable, but not complex variables such as arrays. Outputs to cflog text attribute. cftrace 341 Attribute Req/Opt Default Description type Optional Corresponds to the cflog type attribute; displays an appropriate icon. • Information • Warning • Error • Fatal Information var Optional Information The name of a simple or complex variable to display. Useful for displaying a temporary value, or a value that does not display on any CFM page. Usage You cannot put application code within this tag. (This avoids problems that can occur if you disable debugging.) This tag is useful for debugging CFML code during application development. You can display cftrace tag output in the following ways: • As a section in the debugging output • In-line in an application page, and as a section in debugging output. If you specify in-line tracing, ColdFusion flushes all output up to the cftrace tag, and displays the trace output when it encounters the tag. This is an example of a log file entry: "Information","web-4","04/08/02","23:21:30", ,"[30 ms (1st trace)] [C:\cfusion\wwwroot\generic.cfm @ line: 9] [thisPage = /generic.cfm] " "Information","web-0","04/08/02","23:58:58", ,"[5187 ms (10)] [C:\cfusion\wwwroot\generic.cfm @ line: 14] - [category] [thisPage = /generic.cfm] [ABORTED] thisPage " For a complex variable, ColdFusion lists the variable name and the number of elements in the object; it does not log the contents of the variable. The following example traces a FORM variable that is evaluated by a cfif block: Example

Congratulations, you're a winner!

Sorry, you lost!

342 Chapter 2: ColdFusion Tags cftransaction Description Instructs the database management system to treat multiple database operations as a single transaction. Provides database commit and rollback processing. Category Database manipulation tags Syntax See also cfinsert, cfprocparam, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cfupdate Attributes Attribute Req/Opt Default Description action Optional • begin: the start of the block of code to execute. • commit: commits a pending transaction • rollback: rolls back a pending transaction isolation Optional begin ODBC lock type. • read_uncommitted • read_committed • repeatable_read • serializable Usage Within a transaction block, you can do the following: • Commit a database transaction by nesting the tag within the block • Roll back a transaction by nesting the tag within the block (In these examples, the slash is alternate syntax that is the equivalent of an end tag.) Within a transaction block, you can write queries to more than one database, but you must commit or rollback a transaction to one database before writing a query to another. Using CFML error handling, you control whether each transaction is committed, based on the success or failure of the database query. To control how the database engine performs locking during the transaction, use the isolation attribute. Example

CFTRANSACTION can be used to group multiple queries that use CFQUERY into one business event. Changes to data that is requested by the queries are not committed to the datasource until all actions within the transaction block have executed successfully.

This a view-only example. 344 Chapter 2: ColdFusion Tags cftree Description Inserts a tree control in a form. Validates user selections. Used within a cftree tag block. You can use a ColdFusion query to supply data to the tree. Category Forms tags Syntax See also cfapplet, cfform, cfgrid, cfgridcolumn, cfgridrow, cfgridupdate, cfinput, cfselect, cfslider, cftextinput, cftree, cftreeitem History ColdFusion MX: Changed behavior: ColdFusion renders a tree control regardless of whether there are any treeitems within it. Attributes Attribute Req/Opt Default Description name Required Name for tree control. required Optional No • Yes: user must select an item in tree control • No delimiter Optional \\ Character to separate elements in form variable path. cftree 345 Attribute 346 Req/Opt Default Description completePath Optional No; tree name is returned as root • Yes: passes the root part of treename.path form variable when cftree is submitted • No, or omitted: root level of form variable is not passed; path value starts with the first node For the preserveData attribute of cfform to work with the tree, you must set this attribute to Yes. If you specify a root name for a tree item with cftreeitem queryasroot, that value is returned. If you do not specify a root name, ColdFusion returns the query name as the root. appendKey Optional Yes • Yes: when used with href, passes CFTREEITEMKEY variable with the value of the selected tree item in URL to the application page specified in the cfform action attribute • No highlightHref Optional Yes • Yes: highlights links that are associated with a cftreeitem with a URL attribute value • No: disables highlight onValidate Optional JavaScript function to validate user input. The form object, input object, and input object value are passed to the specified routine, which should return True if validation succeeds; False, otherwise. message Optional Message to display if validation fails. onError Optional JavaScript function to execute if validation fails. lookAndFeel Optional windows • motif: renders slider in Motif style • windows: renders slider in Windows style • metal: renders slider in Java Swing style If platform does not support style option, tag defaults to platform default style. font Optional Font name for data in tree control. fontSize Optional Font size for text in tree control, in points. italic Optional No • Yes: displays tree control text in italics • No bold Optional No • Yes: displays tree control text in bold • No height Optional 320 Tree control height, in pixels. width Optional 200 Tree control width, in pixels. vSpace Optional Vertical margin above and below tree control, in pixels. hSpace Optional Horizontal spacing to left and right of tree control, in pixels. Chapter 2: ColdFusion Tags Attribute Req/Opt Default Description align Optional • • • • • • • • • border Optional Yes • Yes • No hScroll Optional Yes • Yes: permits horizontal scrolling • No vScroll Optional Yes • Yes: permits vertical scrolling • No notSupported Optional top left bottom baseline texttop absbottom middle absmiddle right Message to display if page that contains Java applet-based form control is opened by browser that does not support Java, or has Java support disabled. For example: notSupported = " Browser must support Java to view ColdFusion Java Applets" If no message is specified, this message displays: Browser must support Java to
view ColdFusion Java Applets!
Usage This tag requires the client to download a Java applet. Downloading an applet takes time; therefore, using this tag might be slightly slower than using an HTML form element or the cfinput tag to get the same information. For this tag to work properly. the browser must be JavaScript-enabled. If the following conditions are true, a user’s selection from query data that populates this tag’s options continues to display after the user submits the form: • The cfform preserveData attribute is set to "Yes" • The cfform action attribute posts to the same page as the form itself (this is the default), or the action page has a form that contains controls with the same names as corresponding controls on the user entry form For more information, see the cfform tag entry. Example cftree 347 SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees where lastname = ’#employeeNames#’

cftree Example

cfselect Presentation of Data

Click an employee’s last name and "see information for this employee", to see expanded information.

cftree Presentation of Data

Click on the folders to "drill down" and reveal information.

cftreeitem is used to create the "branches" of the tree.

... 348 Chapter 2: ColdFusion Tags cftreeitem Description Populates a form tree control, created with the cftree tag, with elements. To display icons, you can use the img values that ColdFusion provides, or reference your own icons. Category Forms tags Syntax See also cfapplet, cfform, cfgrid, cfgridcolumn, cfgridrow, cfgridupdate, cfinput, cfselect, cfslider, cftextinput, cftree Attributes Attribute Req/Opt Default Description value Required Value passed when cfform is submitted. When populating a tree with data from a cfquery, specify columns in a delimited list. Example: value = "dept_id,emp_id" display Optional value Tree item label. When populating a tree with data from a query, specify names in a delimited list. Example: display = "dept_name,emp_name" parent Optional img Optional Value for tree item parent. folder Image name, filename, or file URL for tree item icon. The following values are provided: • cd • computer • document • element • folder • floppy • fixed • remote You can specify a custom image. To do so, include path and file extension; for example: img = "../images/page1.gif" To specify more than one image in a tree, or an image at the second or subsequent level, use commas to separate names, corresponding to level; for example: img = "folder,document" img = ",document" (example of second level) cftreeitem 349 Attribute Req/Opt Default Description imgopen Optional Icon displayed with open tree item. You can specify icon filename with a relative path. You can use a ColdFusion image. href Optional URL to associate with tree item or query column for a tree that is populated from a query. If href is a query column, its value is the value populated by query. If href is not recognized as a query column, it is assumed that its text is an HTML href. When populating a tree with data from a query, HREFs can be specified in delimited list; for example: href = "http://dept_svr,http://emp_svr" target Optional Target attribute of href URL. When populating a tree with data from a query, specify target in delimited list: target = "FRAME_BODY,_blank" query Optional Query name to generate data for the treeitem. queryAsRoot Optional Defines query as the root level. This avoids having to create another parent cftreeitem. • Yes • No • String to use as the root name If you do not specify a root name, ColdFusion returns the query name as the root. expand Optional Yes • Yes: expands tree to show tree item children • No: keeps tree item collapsed Usage This tag requires the client to download a Java applet. Downloading an applet takes time; therefore, using this tag might be slightly slower than using an HTML form element or the cfinput tag to get the same information. For this tag to work properly. the browser must be JavaScript-enabled. Example SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees WHERE 0=0 AND LastName = '#employeeNames#' 350 Chapter 2: ColdFusion Tags

cfselect Presentation of Data

Click an employee’s last name and click "see information for this employee" to see expanded information.

cftree Presentation of Data

Click the folders to "drill down" and reveal information.

cftreeitem is used to create the branches of the cftree.

cfgrid Presentation of Data

352 Chapter 2: ColdFusion Tags cftry Description Used with one or more cfcatch tags. 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 Code that might throw an exception One or more cfcatch blocks See also cfcatch, cferror, cfrethrow, cfthrow, Chapter 14, “Handling Errors,” in Developing ColdFusion MX Applications History ColdFusion MX: Changed cfscript to include try and catch statements that are equivalent to the cftry and cfcatch tags. Usage Within a cftry block, put the code that might throw an exception, followed by one ore more cfcatch tags that catch and process exceptions. This tag requires an end tag. Example

cftry Example

SELECT * FROM EMPLOYEEAS

You've Thrown a Database Error

#cfcatch.message#

Caught an exception, type = #CFCATCH.TYPE#

The contents of the tag stack are:


#i# #sCurrent["ID"]# (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#) #sCurrent["TEMPLATE"]#
cftry 353
354 Chapter 2: ColdFusion Tags cfupdate Description Updates records in a data source from data in a ColdFusion form or form Scope. Category Database manipulation tags Syntax See also cfinsert, cfprocparam, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cftransaction History ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5. Attributes Attribute Req/Opt Default dataSource Required Name of the data source that contains the table. tableName Required Name of table to update. • For ORACLE drivers, must be uppercase. • For Sybase driver: case-sensitive; must be in same case as used when the table was created tableOwner Optional For data sources that support table ownership (for example, SQL Server, Oracle, Sybase SQL Anywhere), the table owner. tableQualifier Optional For data sources that support table qualifiers. The purpose of table qualifiers is as follows: • SQL Server and Oracle: name of database that contains table • Intersolv dBASE driver: directory of DBF files username Optional Overrides username value specified in ODBC setup. password Optional Overrides password value specified in ODBC setup. formFields Optional (all on form, except keys) Description Comma-delimited list of form fields to update. If a form field is not matched by a column name in the database, ColdFusion throws an error. The formFields lies must include the database table primary key field, which must be present in the form. It can be hidden. cfupdate 355 Example SELECT Course_Number, Course_ID, Descript FROM Courses WHERE Course_ID = #Trim(url.Course_ID)# ORDER by Course_Number CFUPDATE Example

CFUPDATE Example

You can alter the contents of this record, and then click "Update" to use CFUPDATE and alter the database

Course Number

Course Description

356 Chapter 2: ColdFusion Tags
cfupdate 357 cfwddx Description Serializes and deserializes CFML data structures to the XML-based WDDX format. The WDDX is an XML vocabulary for describing complex data structures in a standard, generic way. Implementing it lets you use the HTTP protocol to such information among application server platforms, application servers, and browsers. This tag generates JavaScript statements to instantiate JavaScript objects equivalent to the contents of a WDDX packet or CFML data structure. Interoperates with Unicode. Category Extensibility tags Syntax See also cfcollection, cfdump, cfexecute, cfindex, cfobject, cfreport, cfsearch History ColdFusion MX • Changed column name case behavior: ColdFusion preserves the case of column names in JavaScript. (Earlier releases converted query column names to lowercase.) • Changed encoding format support: this tag supports several encoding formats. The default encoding format is UTF-8. The tag interoperates with Unicode. Attributes Attribute Req/Opt action Required • • • • input Required A value to process output Required if Name of variable for output. If action = "WDDX2JS" or "CFML2JS", and this attribute is omitted, result is output in HTML stream. action = "wddx2cfml" topLevelVariable Required if action = "wddx2js" or "cfml2js" 358 Chapter 2: ColdFusion Tags Default Description cfml2wddx: serialize CFML to WDDX wddx2cfml: deserialize WDDX to CFML cfml2js: serialize CFML to JavaScript wddx2js: deserialize WDDX to JavaScript Name of top-level JavaScript object created by deserialization. The object is an instance of the WddxRecordset object. Attribute Req/Opt Default Description useTimeZoneInfo Optional Yes Whether to output time-zone information when serializing CFML to WDDX. • Yes: the hour-minute offset, represented in ISO8601 format, is output. • No: the local time is output. validate No Applies if action = "wddx2cfml" or "wddx2js". • yes: validates WDDX input with an XML parser using WDDX DTD. If parser processes input without error, packet is deserialized. Otherwise, an error is thrown. • no: no input validation Optional Usage ColdFusion preserves the case of column names cases in JavaScript. The wddx2js and cfml2js actions create a WddxRecordset javascript object when they encounter a RecordSet java object. The serialized JavaScript code requires a wddx.js file. This tag performs the following conversions: From To CFML WDDX CFML JavaScript WDDX CFML WDDX JavaScript For more information, and a list of the ColdFusion array and structure functions that you can use to manage XML document objects and functions, see Chapter 31, “Using XML and WDDX,” in Developing ColdFusion MX Applications. Example select Message_Id, Thread_id, Username from messages The recordset data is:...

#Message_ID# #Thread_ID# #Username#

Serializing CFML data...

Resulting WDDX packet is:

<cfoutput>#wddxText#</cfoutput> cfwddx 359 Deserializing WDDX packet...

The recordset data is:...

#Message_ID# #Thread_ID# #Username#

360 Chapter 2: ColdFusion Tags cfxml Description Creates a ColdFusion XML document object that contains the markup in the tag body. This tag can include XML and CFML tags. ColdFusion processes the CFML code in the tag body, then assigns the resulting text to an XML document object variable. Category Extensibility tags Syntax See also IsXmlDoc, IsXmlElem, IsXmlRoot, XmlChildPos, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description variable caseSensitive Name of an xml variable Optional no • yes: maintains the case of document elements and attributes • no Usage An XML document object is represented in ColdFusion as a structure. The following example creates a document object whose root element is MyDoc. The object includes text that displays the value of the ColdFusion variable testVar. The code creates four nested child elements, which are generated by an indexed cfloop tag. The cfdump tag displays the XML document object. Note: Do not include an processing directive in the cfxml tag body. This directive is not required for processing, and causes an error. To process XML text that includes this directive, use the XmlParse function. Example The value of testVar is True. The value of testVar is False. This is Child node #LoopCount#. cfxml 361 362 Chapter 2: ColdFusion Tags CHAPTER 3 ColdFusion Functions This chapter lists and categorizes ColdFusion Markup Language (CFML) functions. Contents Function list. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364 Functions by category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Function changes since ColdFusion 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 Function descriptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 363 Function list ColdFusion Markup Language (CFML) includes a set of functions that you use in ColdFusion pages to perform logical and arithmetic operations and manipulate data. The following table lists CFML functions: 364 Abs GetHttpTimeString Min ACos GetK2ServerDocCount Minute ArrayAppend GetK2ServerDocCountLimit Month ArrayAvg GetLocale MonthAsString ArrayClear GetMetaData Now ArrayDeleteAt GetMetricData NumberFormat ArrayInsertAt GetPageContext ParagraphFormat ArrayIsEmpty GetProfileSections ParameterExists ArrayLen GetProfileString ParseDateTime ArrayMax GetTempDirectory Pi ArrayMin GetTempFile PreserveSingleQuotes ArrayNew GetTemplatePath Quarter ArrayPrepend GetTickCount QueryAddColumn ArrayResize GetTimeZoneInfo QueryAddRow ArraySet GetToken QueryNew ArraySort Hash QuerySetCell ArraySum Hour QuotedValueList ArraySwap HTMLCodeFormat Rand ArrayToList HTMLEditFormat Randomize Asc IIf RandRange ASin IncrementValue REFind Atn InputBaseN REFindNoCase BitAnd Insert ReleaseComObject BitMaskClear Int RemoveChars BitMaskRead IsArray RepeatString BitMaskSet IsBinary Replace BitNot IsBoolean ReplaceList BitOr IsCustomFunction ReplaceNoCase BitSHLN IsDate REReplace BitSHRN IsDebugMode REReplaceNoCase Chapter 3: ColdFusion Functions BitXor IsDefined Reverse Ceiling IsK2ServerABroker Right Chr IsK2ServerDocCountExceeded RJustify CJustify IsK2ServerOnline Round Compare IsLeapYear RTrim CompareNoCase IsNumeric Second Cos IsNumericDate SetEncoding CreateDate IsObject SetLocale CreateDateTime IsQuery SetProfileString CreateObject IsSimpleValue SetVariable CreateODBCDate IsStruct Sgn CreateODBCDateTime IsUserInRole Sin CreateODBCTime IsWDDX SpanExcluding CreateTime IsXmlDoc SpanIncluding CreateTimeSpan IsXmlElem Sqr CreateUUID IsXmlRoot StripCR DateAdd JavaCast StructAppend DateCompare JSStringFormat StructClear DateConvert LCase StructCopy DateDiff Left StructCount DateFormat Len StructDelete DatePart ListAppend StructFind Day ListChangeDelims StructFindKey DayOfWeek ListContains StructFindValue DayOfWeekAsString ListContainsNoCase StructGet DayOfYear ListDeleteAt StructInsert DaysInMonth ListFind StructIsEmpty DaysInYear ListFindNoCase StructKeyArray DE ListFirst StructKeyExists DecimalFormat ListGetAt StructKeyList DecrementValue ListInsertAt StructNew Decrypt ListLast StructSort DeleteClientVariable ListLen StructUpdate DirectoryExists ListPrepend Tan Function list 365 366 DollarFormat ListQualify TimeFormat Duplicate ListRest ToBase64 Encrypt ListSetAt ToBinary Evaluate ListSort ToString Exp ListToArray Trim ExpandPath ListValueCount UCase FileExists ListValueCountNoCase URLDecode Find LJustify URLEncodedFormat FindNoCase Log URLSessionFormat FindOneOf Log10 Val FirstDayOfMonth LSCurrencyFormat ValueList Fix LSDateFormat Week FormatBaseN LSEuroCurrencyFormat Wrap GetAuthUser LSIsCurrency WriteOutput GetBaseTagData LSIsDate XmlChildPos GetBaseTagList LSIsNumeric XmlElemNew GetBaseTemplatePath LSNumberFormat XmlFormat GetClientVariablesList LSParseCurrency XmlNew GetCurrentTemplatePath LSParseDateTime XmlParse GetDirectoryFromPath LSParseEuroCurrency XmlSearch GetEncoding LSParseNumber XmlTransform GetException LSTimeFormat Year GetFileFromPath LTrim YesNoFormat GetFunctionList Max GetHttpRequestData Mid Chapter 3: ColdFusion Functions Functions by category The following tables list functions by their category or purpose. Array functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Authentication functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Date and time functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Decision functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Display and formatting functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 Dynamic evaluation functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Extensibility functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Full-text search functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 International functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 List functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 Mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Other functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Query functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 String functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Structure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 System functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 XML functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 Array functions ArrayAppend ArrayIsEmpty ArrayPrepend ArraySwap ArrayAvg ArrayLen ArrayResize ArrayToList ArrayClear ArrayMax ArraySet IsArray ArrayDeleteAt ArrayMin ArraySort ListToArray ArrayInsertAt ArrayNew ArraySum Authentication functions GetAuthUser IsUserInRole Conversion functions ArrayToList Hash URLEncodedFormat ToBase64 LCase Val XmlTransform Functions by category 367 ToBinary ListToArray XmlFormat ToString URLDecode XmlParse Date and time functions CreateDate DateFormat GetTimeZoneInfo MonthAsString CreateDateTime DatePart Hour Now CreateODBCDate Day IsDate ParseDateTime CreateODBCDateTime DayOfWeek IsLeapYear Quarter CreateODBCTime DayOfWeekAsString IsNumericDate Second CreateTime DayOfYear LSDateFormat TimeFormat CreateTimeSpan DaysInMonth LSIsDate Week DateAdd DaysInYear LSParseDateTime Year DateCompare FirstDayOfMonth LSTimeFormat DateConvert GetHttpTimeString Minute DateDiff GetTickCount Month Decision functions DirectoryExists IsDebugMode IsObject IsXmlRoot FileExists IsDefined IsQuery LSIsCurrency IIf IsK2ServerABroker IsSimpleValue LSIsDate IsArray IsK2ServerDocCountExceeded IsStruct LSIsNumeric IsBinary IsK2ServerOnline IsUserInRole StructIsEmpty IsBoolean IsLeapYear IsWDDX StructKeyExists IsCustomFunction IsNumeric IsXmlDoc YesNoFormat IsDate IsXmlElem IsNumericDate Display and formatting functions 368 CJustify HTMLEditFormat LSNumberFormat ParagraphFormat DateFormat LJustify LSParseCurrency RJustify DecimalFormat LSCurrencyFormat LSParseDateTime StripCR DollarFormat LSDateFormat LSParseEuroCurrency TimeFormat FormatBaseN LSEuroCurrencyFormat LSParseNumber YesNoFormat GetLocale LSIsCurrency LSTimeFormat StripCR HTMLCodeFormat LSIsDate NumberFormat Chapter 3: ColdFusion Functions Dynamic evaluation functions DE Evaluate IIf SetVariable Extensibility functions CreateObject XmlElemNew XmlParse ReleaseComObject XmlFormat XmlSearch XmlChildPos XmlNew XmlTransform Full-text search functions History ColdFusion MX 6.1: These functions are deprecated. They might not work, and might cause errors, in a future release. GetK2ServerDocCount IsK2ServerABroker IsK2ServerOnline GetK2ServerDocCountLimit IsK2ServerDocCoun tExceeded International functions DateConvert LSIsCurrency LSParseDateTime LSParseNumber GetEncoding LSCurrencyFormat LSIsNumeric LSTimeFormat GetHttpTimeString LSDateFormat LSNumberFormat SetEncoding GetLocale LSEuroCurrencyFormat LSParseCurrency SetLocale GetTimeZoneInfo LSIsDate LSParseEuroCurrency List functions ArraySort FindNoCase ListContainsNoCase ListQualify ArrayToList FindOneOf ListDeleteAt ListRest Asc FormatBaseN ListFind ListSetAt Chr GetClientVariablesList ListFindNoCase ListSort CJustify LCase ListFirst ListToArray Compare Left ListGetAt ListValueCount CompareNoCase Len ListInsertAt ListValueCountNoCase Decrypt ListAppend ListLast ReplaceList Encrypt ListChangeDelims ListLen Find ListContains ListPrepend Functions by category 369 Mathematical functions Abs BitNot FormatBaseN Randomize ACos BitOr IncrementValue RandRange ArrayAvg BitSHLN InputBaseN Round ArraySum BitSHRN Int Sgn ASin BitXor Log Sin Atn Ceiling Log10 Sqr BitAnd Cos Max Tan BitMaskClear DecrementValue Min BitMaskRead Exp Pi BitMaskSet Fix Rand Other functions CreateUUID GetBaseTagList QuotedValueList URLEncodedFormat Decrypt GetBaseTemplatePath StripCR URLSessionFormat DeleteClientVariable GetClientVariablesList ToBase64 ValueList Duplicate GetTickCount ToBinary WriteOutput Encrypt Hash ToString GetBaseTagData PreserveSingleQuotes URLDecode Query functions IsQuery QueryAddRow QuerySetCell QueryAddColumn QueryNew QuotedValueList ValueList String functions History ColdFusion MX: ColdFusion now supports the Java UCS-2 representation of Unicode character values 0–65535. (Earlier releases supported ASCII values.) String-processing functions process any of these characters (including ASCII 0 (NUL) characters), and continue counting subsequent characters of the string, if any. (In earlier releases, some string-processing functions processed the ASCII 0 (NUL) character, but did not process subsequent characters of the string.) 370 Asc JSStringFormat MonthAsString SpanExcluding Chr LCase ParagraphFormat SpanIncluding CJustify Left ParseDateTime StripCR Chapter 3: ColdFusion Functions Compare Len REFind ToBase64 CompareNoCase LJustify REFindNoCase ToBinary DayOfWeekAsString ListValueCount RemoveChars ToString Decrypt ListValueCountNoCase RepeatString Trim Encrypt LSIsCurrency Replace UCase FormatBaseN LSIsDate ReplaceList URLDecode Find LSIsNumeric ReplaceNoCase URLEncodedFormat FindNoCase LSParseCurrency REReplace Val FindOneOf LSParseDateTime REReplaceNoCase Wrap GetToken LSParseEuroCurrency Reverse XmlFormat Hash LSParseNumber Right Insert LTrim RJustify JavaCast Mid RTrim See also “Conversion functions” on page 367. Structure functions Duplicate StructCount StructGet StructKeyList IsStruct StructDelete StructInsert StructNew StructAppend StructFind StructIsEmpty StructSort StructClear StructFindKey StructKeyArray StructUpdate StructCopy StructFindValue StructKeyExists System functions DirectoryExists GetEncoding GetMetaData GetTemplatePath ExpandPath GetException GetMetricData GetPageContext FileExists GetFileFromPath GetProfileSections SetEncoding GetBaseTemplatePath GetFunctionList GetProfileString GetCurrentTemplatePath GetHttpRequestData GetTempDirectory GetDirectoryFromPath GetLocale SetLocale SetProfileString GetTempFile XML functions IsXmlDoc IsWDDX XmlFormat XmlSearch IsXmlElem XmlChildPos XmlNew XmlTransform IsXmlRoot XmlElemNew XmlParse Functions by category 371 Function changes since ColdFusion 5 The following tables list functions, parameters and values that have changed since ColdFusion 5.0 and indicate the specific release in which the change was made. Array functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Deprecated functions, parameters, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 Obsolete functions, parameters, and values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 New functions, parameters, and values 372 Function Parameter or value Added in this ColdFusion release CreateObject All ColdFusion MX DateAdd l key of datepart parameter ColdFusion MX 6.1 DatePart l key of datepart parameter ColdFusion MX 6.1 GetAuthUser All ColdFusion MX GetEncoding All ColdFusion MX GetMetaData All ColdFusion MX GetPageContext All ColdFusion MX GetProfileSections All ColdFusion MX IsObject All ColdFusion MX IsUserInRole All ColdFusion MX IsXmlDoc All ColdFusion MX IsXmlElem All ColdFusion MX IsXmlRoot All ColdFusion MX LSTimeFormat l key of mask parameter ColdFusion MX 6.1 ReleaseComObject All ColdFusion MX 6.1 SetEncoding All ColdFusion MX TimeFormat l key of mask parameter ColdFusion MX 6.1 URLDecode charset parameter ColdFusion MX URLEncodedFormat charset parameter ColdFusion MX URLSessionFormat All ColdFusion MX Wrap All ColdFusion MX 6.1 XmlChildPos All ColdFusion MX XmlElemNew All ColdFusion MX XmlNew All ColdFusion MX XmlParse All ColdFusion MX Chapter 3: ColdFusion Functions Function Parameter or value Added in this ColdFusion release XmlSearch All ColdFusion MX XmlTransform All ColdFusion MX Deprecated functions, parameters, and values The following functions, parameters, and 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. Function Parameter or value Deprecated as of this ColdFusion release getMetricData cachepops parameter ColdFusion MX getK2ServerDocCount All ColdFusion MX 6.1 getK2ServerDocCount All Limit ColdFusion MX 6.1 getTemplatePath All ColdFusion MX isK2ServerABroker All ColdFusion MX 6.1 isK2ServerDocCount Exceeded All ColdFusion MX 6.1 isK2ServerOnLine All ColdFusion MX 6.1 parameterExists All ColdFusion MX. Use the IsDefined function. setLocale locale = "Spanish ColdFusion MX. Use Spanish (Standard). (Mexican)" value Obsolete functions, parameters, and values The following functions, parameters, and values are obsolete. Do not use them in ColdFusion applications. They might not work, and might cause an error, in releases later than ColdFusion 5. Function Parameter or value Obsolete as of this ColdFusion release AuthenticatedContext All ColdFusion MX AuthenticatedUser All ColdFusion MX isAuthenticated All ColdFusion MX isAuthorized All ColdFusion MX isProtected All ColdFusion MX Function changes since ColdFusion 5 373 Abs Description Absolute-value function. The absolute value of a number is the number without its sign. Returns The absolute value of a number. Category Mathematical functions Function syntax Abs(number) See also Sgn Parameters Parameter Description number A number Example

Abs Example

The absolute value of the following numbers: 1,3,-4,-3.2,6 is #Abs(1)#,#Abs(3)#,#Abs(-4)#,#Abs(-3.2)#,#Abs(6)#

The absolute value of a number is the number without its sign. 374 Chapter 3: ColdFusion Functions ACos Description Arccosine function. The arccosine is the angle whose cosine is number. Returns The arccosine, in radians, of a number. Category Mathematical functions Function syntax ACos(number) See also Cos, Sin, ASin, Tan, Atn, Pi Parameters Parameter Description number Cosine of an angle. The value must be between -1.0 and 1.0, inclusive. Usage The range of the result is 0 to π. To convert degrees to radians, multiply degrees by π/180. To convert radians to degrees, multiply radians by 180/π. Example

ACos Example

ACos(#FORM.CosNum#) = #ACos(FORM.cosNum)# Radians
or
ACos(#FORM.CosNum#) = #ACos(FORM.cosNum) * 180/PI()#

Enter a number between -1 and 1

Enter a number to get its arccosine in Radians and Degrees.

ACos 375 ArrayAppend Description Appends an array element to an array. Returns True, on successful completion. Category Array functions Function syntax ArrayAppend(array, value) See also ArrayPrepend History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description array Name of an array value Value to add at end of array Example

ArrayAppend Example

SELECT FirstName, LastName FROM Employees #ArrayAppend(myArray, "#FirstName# #LastName#")# , Array was appended

The contents of the array are as follows:

#myList# 376 Chapter 3: ColdFusion Functions ArrayAvg Description Calculates the average of the values in an array. Returns Number. If the array parameter value is an empty array, returns zero. Category Array functions, Mathematical functions Function syntax ArrayAvg(array) See also ArraySum Parameters Parameter Description array Name of an array Usage The following example uses the ColdFusion built-in variable Form.fieldNames, which is available on the action page of a form. It contains a comma-delimited list of the names of the fields on the form. Example ArrayAvg Example

ArrayAvg Example

This example uses ArrayAvg to find the average of the numbers that you enter into an array.
To enter more than two numbers press the more button.

ArrayAvg 377
Number #LoopItem#

The average of the numbers that you entered is #ArrayAvg(myNumberArray)#. Try again. You must enter at least two numeric values. 378 Chapter 3: ColdFusion Functions ArrayClear Description Deletes the data in an array. Returns True, on successful completion. Category Array functions Function syntax ArrayClear(array) See also ArrayDeleteAt History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description array Name of an array Example

ArrayClear Example

Your array contents are: #ArrayToList(MyArray)#

Is the array empty?: #ArrayIsEmpty(MyArray)#

Now, clear the array:

Is the array empty?: #ArrayIsEmpty(MyArray)# ArrayClear 379 ArrayDeleteAt Description Deletes an element from an array. When an element is deleted, ColdFusion recalculates index positions. For example, in an array that contains the months of the year, deleting the element at position 5 removes the entry for May. After this, to delete the entry for June, you would delete the element at position 5 (not 6). Returns True, on successful completion. Category Array functions Function syntax ArrayDeleteAt(array, position) See also ArrayInsertAt History ColdFusion MX: • Changed behavior: this function can be used on XML objects. • Changed thrown exceptions: this function can throw the InvalidArrayIndexException error. Parameters Parameter Description array Name of an array position Array position Throws If this function attempts to delete an element at position 0, or specifies a value for position that is greater than the size of array, this function throws an InvalidArrayIndexException error. Example

ArrayDeleteAt Example

Is the second element gone?: #ArrayDeleteAt(DaysArray,2)#

The second element is now: #DaysArray[2]# 380 Chapter 3: ColdFusion Functions ArrayInsertAt Description Inserts a value into an array. Array elements whose indexes are greater than the new position are incremented by one. The array length increases by one. Returns True, on successful completion. Category Array functions Function syntax ArrayInsertAt(array, position, value) See also ArrayDeleteAt History ColdFusion MX: • Changed behavior: this function can be used on XML objects. • Changed thrown exceptions: this function can throw the InvalidArrayIndexException error. Parameters Parameter Description array Name of an array position Index position at which to insert value value Value to insert Throws If this function attempts to insert an element at position 0, or specifies a value for position that is greater than the size of array, this function throws an InvalidArrayIndexException error. Example

ArrayInsertAt Example

Add an element before position 3: #ArrayInsertAt(DaysArray,3,"Wednesday")#

Now output the array as a list: #ArrayToList(DaysArray)# ArrayInsertAt 381 ArrayIsEmpty Description Determines whether an array is empty of data elements. Returns True, if the array is empty; otherwise, False. Category Array functions Function syntax ArrayIsEmpty(array) See also ArrayLen History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description array Name of an array Example

ArrayIsEmpty Example

Your array contents are: #ArrayToList(MyArray)#

Is the array empty?: #ArrayIsEmpty(MyArray)#

Now, clear the array:

Is the array empty?: #ArrayIsEmpty(MyArray)# 382 Chapter 3: ColdFusion Functions ArrayLen Description Determines the number of elements in an array. Returns The number of elements in an array. Category Array functions Function syntax ArrayLen(array) See also ArrayIsEmpty History ColdFusion MX: Changed behavior: this function can be used on child XML objects. Parameters Parameter Description array Name of an array Example

ArrayLen Example

SELECT FirstName, LastName FROM Employees

The contents of the array are as follows:

#myList#

This array has #ArrayLen(MyArray)# elements. ArrayLen 383 ArrayMax Description Array maximum function. Returns The largest numeric value in an array. If the array parameter value is an empty array, returns zero. Category Array functions Function syntax ArrayMax(array) Parameters Parameter Description array Name of an array Example

ArrayMax Example

This example uses ArrayMax to find the largest number in an array.

The largest number that you entered is #ArrayMax(myNumberArray)#.



384 Chapter 3: ColdFusion Functions ArrayMin Description Array minimum function. Returns The smallest numeric value in an array. If the array parameter value is an empty array, returns zero. Category Array functions Function syntax ArrayMin(array) Parameters Parameter Description array Name of an array Example

ArrayMin Example

This example uses ArrayMin to find the smallest number in an array.

The smallest number that you entered is #ArrayMin(myNumberArray)#.



ArrayMin 385 ArrayNew Description Creates an array of 1–3 dimensions. Index array elements with square brackets: [ ]. ColdFusion arrays expand dynamically as data is added. Returns An array Category Array functions Function syntax ArrayNew(dimension) Parameters Parameter Description dimension Number of dimensions in new array. 1, 2, or 3 Example

ArrayNew Example

Is this an array? #IsArray(MyNewArray)#

It has #ArrayLen(MyNewArray)# elements.

Contents: #ArrayToList(MyNewArray)# 386 Chapter 3: ColdFusion Functions ArrayPrepend Description Inserts an array element at the beginning of an array. Returns True, on successful completion. Category Array functions Function syntax ArrayPrepend(array, value) See also ArrayAppend Parameters Parameter Description array Name of an array value Value to insert at beginning of array Example

ArrayPrepend Example

SELECT FirstName, LastName FROM Employees #ArrayPrepend(myArray, "#FirstName# #LastName#")# , Array was prepended

The contents of the array are as follows:

#myList# ArrayPrepend 387 ArrayResize Description Resets an array to a specified minimum number of elements. This can improve performance, if used to size an array to its expected maximum. For more than 500 elements, use ArrayResize immediately after using the ArrayNew tag. ColdFusion arrays expand dynamically as data is added. Returns True, on successful completion. Category Array functions Function syntax ArrayResize(array, minimum_size) Parameters Parameter Description array Name of an array minimum_size Minimum array size Example

ArrayResize Example

SELECT * FROM Courses The array is now #ArrayLen(MyArray)# elements, to match the query of #GetCourses.RecordCount# records. 388 Chapter 3: ColdFusion Functions ArraySet Description In a one-dimensional array, sets the elements in a specified index range to a value. Useful for initializing an array after a call to ArrayNew. Returns True, on successful completion. Category Array functions Function syntax ArraySet(array, start_pos, end_pos, value) See also ArrayNew History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description array Name of an array. start_pos Starting index position of range to set. end_pos Ending index position of range to set. If this value is greater than array length, ColdFusion adds elements to array. value Value to which to set each element in the range. Example

ArraySet Example

... ArraySet 389 ArraySort Description Sorts array elements numerically or alphanumerically. Returns True, if sort is successful; False, otherwise. Category Array functions, List functions Function syntax ArraySort(array, sort_type [, sort_order ]) History ColdFusion MX: • Changed thrown exceptions: this function can throw the ArraySortSimpleValueException error and ValueNotNumeric error. • Changed the order in which sorted elements are returned: in a textnocase, descending sort, this function might return elements in a different sort order than in earlier releases. If and sort_order = "desc", ColdFusion MX processes elements that differ only in case differently from earlier releases, as follows: ■ ColdFusion MX reverses the elements’ original order ■ Earlier releases of ColdFusion do not change the elements’ original order For example, in a textnocase, desc sort of d,a,a,b,A, the following occurs: ■ ColdFusion MX returns d,b,A,a,a ■ Earlier ColdFusion releases return d,b,a,a,A sort_type = "textnocase" Parameters 390 Parameter Description array Name of an array sort_type • numeric: sorts numbers • text: sorts text alphabetically, taking case into account (also known as case sensitive). All letters of one case precede the first letter of the other case: - aabzABZ, if sort_order = "asc" (ascending sort) - ZBAzbaa, if sort_order = "desc" (descending sort) • textnocase: sorts text alphabetically, without regard to case (also known as caseinsensitive). A letter in varying cases precedes the next letter: - aAaBbBzzZ, in an ascending sort; preserves original intra-letter order - ZzzBbBaAa, in a descending sort; reverses original intra-letter order sort_order • asc - ascending sort order. Default. - aabzABZ or aAaBbBzzZ, depending on value of sort_type, for letters - from smaller to larger, for numbers • desc - descending sort order. - ZBAzbaa or ZzzBbBaAa, depending on value of sort_type, for letters - from larger to smaller, for numbers Chapter 3: ColdFusion Functions Throws If an array element is other than a simple element, this function throws an ArraySortSimpleValueException error. If sort_type is numeric and an array element is not numeric, this function throws a ValueNotNumeric error. Example SELECT FirstName, LastName FROM Employees ... ArraySort 391 ArraySum Description Array sum function. Returns The sum of values in an array. If the array parameter value is an empty array, returns zero. Category Array functions, Mathematical functions Function syntax ArraySum(array) Parameters Parameter Description array Name of an array Example

ArraySum Example

This example uses ArraySum to add two numbers together.

The sum of the numbers is #ArraySum(myNumberArray)#.



392 Chapter 3: ColdFusion Functions ArraySwap Description Swaps array values of an array at specified positions. This function is more efficient than multiple cfset tags. Returns True, on successful completion. Category Array functions Function syntax ArraySwap(array, position1, position2) Parameters Parameter Description array Name of an array position1 Position of first element to swap position2 Position of second element to swap Example

ArraySwap Example

month[1] = "February"> month[2] = "January"> temp = ArraySwap(month, 1, 2)> temp = ArrayToList(month)>

Show the results: #temp# ArraySwap 393 ArrayToList Description Converts a one-dimensional array to a list. Returns Delimited list, as a string. Category Array functions, Conversion functions, List functions Function syntax ArrayToList(array [, delimiter ]) Parameters Parameter Description array Name of array delimiter Character or multi-character string to separate list elements. Default: comma. Example

ArrayToList Example

SELECT FirstName, LastName FROM Employees

The contents of the array are as follows:

#myList#

This array, alphabetized by first name (descending):

#myAlphaList#

This array has #ArrayLen(MyArray)# elements. 394 Chapter 3: ColdFusion Functions Asc Description Determines the value of a character. Returns The value of the first character of a string; if string is empty, returns zero. Category String functions Function syntax Asc(string) See also Chr History ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode characters, up to a value of 65536. (Earlier releases supported 1-255.) Parameters Parameter Description string A string Example

Asc Example

#Left(FORM.charVals,1)# = #Asc(FORM.charVals)#

Enter a character

Enter a character to see its ASCII value

Asc 395 ASin Description Determines the arcsine of a number. The arcsine is the angle whose sine is number. Returns The arcsine, in radians, of a number. Category Mathematical functions Function syntax ASin(number) See also Sin, Cos, ACos, Tan, Atn, Pi Parameters Parameter Description number Sine of an angle. The value must be between -1 and 1, inclusive. Usage The range of the result is -π/2 to π/2 radians. To convert degrees to radians, multiply degrees by π/180. To convert radians to degrees, multiply radians by 180/π. Example

ASin Example

ASin(#FORM.SinNum#) = #Evaluate(ASin(FORM.sinNum))# Radians
or
ASin(#FORM.SinNum#) = #Evaluate(ASin(FORM.sinNum) * 180/Pi())# Degrees

Enter the sine of the angle to calculate, in degrees and radians. The value must be between 1 and -1, inclusive.

Enter the sine of the angle to calculate, in degrees and radians. The value must be between 1 and -1, inclusive.

Enter the sine of the angle to calculate, in degrees and radians. The value must be between 1 and -1,inclusive.

Enter a number to get its arcsine in Radians and Degrees. 396 Chapter 3: ColdFusion Functions

ASin 397 Atn Description Arctangent function. The arctangent is the angle whose tangent is number. Returns The arctangent, in radians, of a number. Category Mathematical functions Function syntax Atn(number) See also Atn, Sin, ASin, Cos, ACos, Pi Parameters Parameter Description number Tangent of an angle Usage The range of the result is -π/2 to π/2 radians. To convert degrees to radians, multiply degrees by π/180. To convert radians to degrees, multiply radians by 180/π. Example

Atn Example

Atn(#FORM.AtnNum#) = #Atn(FORM.AtnNum)# radians = #Evaluate(Atn(FORM.AtnNum * 180/PI())# Degrees

Enter a number

Enter a number to get its arctangent in Radians and Degrees

398 Chapter 3: ColdFusion Functions AuthenticatedContext Description This function 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 function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases. AuthenticatedContext 399 AuthenticatedUser Description This function 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 function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases. 400 Chapter 3: ColdFusion Functions BitAnd Description Performs a bitwise logical AND operation. Returns The bitwise AND of two long integers. Category Mathematical functions Function syntax BitAnd(number1, number2) See also BitNot, BitOr, BitXor Parameters Parameter Description number1 32-bit signed integer number2 32-bit signed integer Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitAnd Example

Returns the bitwise AND of two long integers.

BitAnd(5,255): #BitAnd(5,255)#

BitAnd(5,0): #BitAnd(5,0)#

BitAnd(128,128): #BitAnd(128,128)# BitAnd 401 BitMaskClear Description Performs a bitwise mask clear operation. Returns A number, bitwise cleared, with length bits beginning at start. Category Mathematical functions Function syntax BitMaskClear(number, start, length) See also BitMaskRead, BitMaskSet Parameters Parameter Description number 32-bit signed integer start Integer, in the range 0-31, inclusive; start bit for mask length Integer, in the range 0-31, inclusive; length of mask Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitMaskClear Example

Returns number bitwise cleared with length bits beginning from start.

BitMaskClear(255, 4, 4): #BitMaskClear(255, 4, 4)#

BitMaskClear(255, 0, 4): #BitMaskClear(255, 0, 4)#

BitMaskClear(128, 0, 7): #BitMaskClear(128, 0, 7)# 402 Chapter 3: ColdFusion Functions BitMaskRead Description Performs a bitwise mask read operation. Returns An integer, created from length bits of number, beginning at start. Category Mathematical functions Function syntax BitMaskRead(number, start, length) See also BitMaskClear, BitMaskSet Parameters Parameter Description number 32-bit signed integer to mask start Integer, in the range 0-31, inclusive; start bit for read length Integer, in the range 0-31, inclusive; length of mask Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitMaskRead Example

Returns integer created from length bits of number, beginning with start.

BitMaskRead(255, 4, 4): #BitMaskRead(255, 4, 4)#

BitMaskRead(255, 0, 4): #BitMaskRead(255, 0, 4)#

BitMaskRead(128, 0, 7): #BitMaskRead(128, 0, 7)# BitMaskRead 403 BitMaskSet Description Performs a bitwise mask set operation. Returns A number, bitwise masked with length bits of mask beginning at start. Category Mathematical functions Function syntax BitMaskSet(number, mask, start, length) See also BitMaskClear, BitMaskRead Parameters Parameter Description number 32-bit signed integer mask 32-bit signed integer; mask start Integer, in the range 0-31, inclusive; start bit for mask length Integer, in the range 0-31, inclusive; length of mask Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitMaskSet Example

Returns number bitwise masked with length bits of mask beginning at start.

BitMaskSet(255, 255, 4, 4): #BitMaskSet(255, 255, 4, 4)#

BitMaskSet(255, 0, 4, 4): #BitMaskSet(255, 0, 4, 4)#

BitMaskSet(0, 15, 4, 4): #BitMaskSet(0, 15, 4, 4)# 404 Chapter 3: ColdFusion Functions BitNot Description Performs a bitwise logical NOT operation. Returns A number; the bitwise NOT of a long integer. Category Mathematical functions Function syntax BitNot(number) See also BitAnd, BitOr, BitXor Parameters Parameter Description number 32-bit signed integer Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitNot Example

Returns the bitwise NOT of a long integer.

BitNot(0): #BitNot(0)#

BitNot(255): #BitNot(255)# BitNot 405 BitOr Description Performs a bitwise logical OR operation. Returns A number; the bitwise OR of two long integers. Category Mathematical functions Function syntax BitOr(number1, number2) See also BitAnd, BitNot, BitXor Parameters Parameter Description number1 32-bit signed integer number2 32-bit signed integer Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitOr Example

Returns the bitwise OR of two long integers.

BitOr(5,255): #BitOr(5,255)#

BitOr(5,0): #BitOr(5,0)#

BitOr(7,8): #BitOr(7,8)# 406 Chapter 3: ColdFusion Functions BitSHLN Description Performs a bitwise shift-left, no-rotation operation. Returns A number, bitwise shifted without rotation to the left by count bits. Category Mathematical functions Function syntax BitSHLN(number, count) See also BitSHRN Parameters Parameter Description number 32-bit signed integer count Integer, in the range 0-31, inclusive; number of bits to shift the number Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitSHLN Example

Returns the number, bitwise shifted, without rotation, to the left by count bits.

BitSHLN(1,1): #BitSHLN(1,1)#

BitSHLN(1,30): #BitSHLN(1,30)#

BitSHLN(1,31): #BitSHLN(1,31)#

BitSHLN(2,31): #BitSHLN(2,31)# BitSHLN 407 BitSHRN Description Performs a bitwise shift-right, no-rotation operation. Returns A number, bitwise shifted, without rotation, to the right by count bits. Category Mathematical functions Function syntax BitSHRN(number, count) See also BitSHLN Parameters Parameter Description number 32-bit signed integer count Integer, in the range 0-31, inclusive. Number of bits to shift the number Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitSHRN Example

Returns a number, bitwise shifted, without rotation, to the right, by count bits.

BitSHRN(1,1): #BitSHRN(1,1)#

BitSHRN(255,7): #BitSHRN(255,7)#

BitSHRN(-2147483548,1): #BitSHRN(-2147483548,1)# 408 Chapter 3: ColdFusion Functions BitXor Description Performs a bitwise logical XOR operation. Returns Bitwise XOR of two long integers. Category Mathematical functions Function syntax BitXor(number1, number2) See also BitAnd, BitNot, BitOr Parameters Parameter Description number1 32-bit signed integer number2 32-bit signed integer Usage Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647. Example

BitXOr Example

Returns the bitwise XOR of two long integers.

BitXOr(5,255): #BitXOr(5,255)#

BitXOr(5,0): #BitXOr(5,0)#

BitXOr(128,128): #BitXOr(128,128)# BitXor 409 Ceiling Description Determines the closest integer that is greater than a specified number. Returns The closest integer that is greater than a given number. Category Mathematical functions Function syntax Ceiling(number) See also Int, Fix, Round Parameters Parameter Description number A real number Example

Ceiling Example

The ceiling

The ceiling

The ceiling

The ceiling 410 of of of of 3.4 is #ceiling(3.4)# 3 is #ceiling(3)# 3.8 is #ceiling(3.8)# -4.2 is #ceiling(-4.2)# Chapter 3: ColdFusion Functions Chr Converts a numeric value to a UCS-2 character. Returns A character with the specified UCS-2 character code. Category String functions Function syntax Chr(number) See also Asc History ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode characters, up to a value of 65535. (Earlier releases supported 1-255.) Parameters Parameter Description number A value (a number in the range 0 to 65535, inclusive) Usage The values 0 – 31 are standard, nonprintable codes. For example: • Chr(10) returns a linefeed character • Chr(13) returns a carriage return character • The two-character string Chr(13) & Chr(10) returns a Windows newline Note: For a complete list of the Unicode characters and their codes, see www.unicode.org/charts/. Example #form.charVals# = #Chr(form.charVals)#

Type an integer character code from 1 to 65535
to see its corresponding character.

Chr 411 CJustify Description Centers a string in a field length. Returns String, center-justified by adding spaces before or after the input parameter. If length is less than the length of the input parameter string, the string is returned unchanged. Category Display and formatting functions, String functions Function syntax Cjustify(string, length) See also LJustify, RJustify Parameters Parameter Description string A string or a variable that contains one. May be empty. If it is a variable that is defined as a number, the function processes it as a string. length A positive integer or a variable that contains one. Length of field. Can be coded as: • A number; for example, 6 • A string representation of a number; for example, "6" Any other value causes ColdFusion to throw an error. Example CJustify Example

CJustify

Enter a string; it will be center-justified within the sample field.

412 Chapter 3: ColdFusion Functions Compare Description Performs a case-sensitive comparison of two strings. Returns • -1, if string1 is less than string2 • 0, if string1 is equal to string2 • 1, if string1 is greater than string2 Category String functions Function syntax Compare(string1, string2) See also CompareNoCase, Find Parameters Parameter Description string1 A string or a variable that contains one string2 A string or a variable that contains one Usage Compares the values of corresponding characters in string1 and string2. Example

Compare Example

The compare function performs a case-sensitive comparison of two strings.

String 1 is less than String 2

The strings are not equal

String 1 is equal to String 2

The strings are equal!

String 1 is greater than String 2

The strings are not equal

This is the default case

Compare 413

String 1

String 2

414 Chapter 3: ColdFusion Functions CompareNoCase Description Performs a case-insensitive comparison of two strings. Returns An indicator of the difference: • A negative number, if string1 is less than string2 • 0, if string1 is equal to string2 • A positive number, if string1 is greater than string2 Category String functions Function syntax CompareNoCase(string1, string2) See also Compare, FindNoCase Parameters Parameter Description string1 A string or a variable that contains one string2 A string or a variable that contains one Example

CompareNoCase Example

This function performs a case-insensitive comparison of two strings.

String 1 is less than String 2

The strings are not equal

String 1 is equal to String 2

The strings are equal!

String 1 is greater than String 2

The strings are not equal

This is the default case

String 1

String 2
CompareNoCase 415

416 Chapter 3: ColdFusion Functions Cos Description Calculates the cosine of an angle that is entered in radians. Returns A number; the cosine of the angle. Category Mathematical functions Function syntax Cos(number) See also ACos, Sin, ASin, Tan, Atn, Pi Parameters Parameter Description number Angle, in radians, for which to calculate the cosine Usage The range of the result is -1 to 1. To convert degrees to radians, multiply degrees by π/180. To convert radians to degrees, multiply radians by 180/π. Note: Because the function uses floating point arithmetic, it returns a very small number (such as 6.12323399574E-017) for angles that should produce 0. To test for a 0 value, check whether the value is less than 0.0000000000001. Example

Cos Example

Cos(#FORM.cosNum#) = #cosValue#

You must enter a numeric angle in degrees.

Enter an angle in degrees to get its cosine:
Cos 417

   418 Chapter 3: ColdFusion Functions CreateDate Description Creates a date/time object. Returns A date/time value. Category Date and time functions Function syntax CreateDate(year, month, day) See also CreateDateTime, CreateODBCDate Parameters Parameter Description year Integer in the range 0-9999. Integers in the range 0-29 are converted to 20002029. Integers in the range 30-99 are converted to 1930-1999. You cannot specify dates before AD 100. month Integer in the range 1 (January) - 12 (December) day Integer in the range 1 - 31 Usage CreateDate is a subset of CreateDateTime. The time in the returned object is set to 00:00:00. Example

CreateDate Example

Your date value, generated with CreateDate:

  • Formatted with CreateDate: #CreateDate(form.year, form.month, form.day)#
  • Formatted with CreateDateTime: #CreateDateTime(form.year, form.month, form.day, 12,13,0)#
  • Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
  • Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#

The same value can be formatted with DateFormat:

  • Formatted with CreateDate and DateFormat: #DateFormat(CreateDate(form.year, form.month, form.day), "mmm-ddyyyy")#
  • Formatted with CreateDateTime and DateFormat: #DateFormat(CreateDateTime(form.year, form.month, form.day, 12,13,0))#
  • Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
  • Formatted with CreateODBCDateTime and DateFormat: CreateDate 419 #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#

Enter the year, month and day, as integers:

Year
Month
Day

420 Chapter 3: ColdFusion Functions CreateDateTime Description Creates a date-time object. Returns A date/time value. Category Date and time functions Function syntax CreateDateTime(year, month, day, hour, minute, second) See also CreateDate, CreateTime, CreateODBCDateTime, Now Parameters Parameter Description year Integer in the range 0-9999. Integers in the range 0-29 are converted to 20002029. Integers in the range 30-99 are converted to 1930-1999. You cannot specify dates before AD 100. month Integer in the range 1 (January)–12 (December) day Integer in the range 1–31 hour Integer in the range 0–23 minute Integer in the range 0–59 second Integer in the range 0–59 Example

CreateDateTime Example

Your date value, generated with CreateDateTime:
  • Formatted with CreateDate: #CreateDate(form.year, form.month, form.day)#
  • Formatted with CreateDateTime: #CreateDateTime(form.year, form.month, form.day, form.hour, form.minute, form.second)#
  • Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
  • Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#

The same value can be formatted with DateFormat:

  • Formatted with CreateDate and DateFormat: #DateFormat(CreateDate(form.year, form.month, form.day), "mmm-dd-yyyy")#
  • Formatted with CreateDateTime and DateFormat: #DateFormat(CreateDateTime(form.year, form.month, form.day, form.hour, form.minute, form.second))# CreateDateTime 421
  • Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
  • Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#

Please enter the year, month, and day, in integer format, for a date to view:

Year
Month
Day
Hour
Minute
Second

422 Chapter 3: ColdFusion Functions CreateObject Description Creates a ColdFusion object, of a specified type. Returns An object, of the specified type. Note: You can enable and disable this function in the ColdFusion Administrator, ColdFusion Basic Security, Tag Restrictions page. Category Extensibility functions History ColdFusion MX: • Changed instantiation behavior: this function, and the cfobject tag, can instantiate • • ColdFusion components and web services. Executing operations on a CFC object executes CFML code that implements the CFC's method in the CFC file. For more information, see Developing ColdFusion MX Applications. For CORBA object: changed the Naming Service separator format for addresses from a dot to a forward slash. For example, if "context=NameService", for a class, use either of the following formats for the class parameter: ■ "Macromedia/Eng/CF" ■ "Macromedia.current/Eng.current/CF" (In earlier releases, the format was "Macromedia.Eng.CF".) For CORBA object: changed the locale attribute; it specifies the Java config that contains the properties file. CreateObject object types For information about using this function, see these sections: • • • • • “CreateObject: COM object” on page 424 “CreateObject: component object” on page 425 “CreateObject: CORBA object” on page 426 “CreateObject: Java or EJB object” on page 428 “CreateObject: web service object” on page 429 Note: On UNIX, this function does not support COM objects. CreateObject 423 CreateObject: COM object Description The CreateObject function can create a Component Object Model (COM) object. To create a COM object, you must provide this information: • The object’s program ID or filename • The methods and properties available to the object through the IDispatch interface • The arguments and return types of the object's methods For most objects, you can get this information from the OLEView utility. Note: On UNIX, this function does not support COM objects. Returns A COM object. Function syntax CreateObject(type, class, context, serverName) See also ReleaseComObject, cfobject Parameters Parameter Description type Type of object to create. • com • corba • java • component • webservice class Component ProgID for the object to invoke context • InProc • Local • Remote serverName Server name, using UNC or DNS convention, in one of these forms: • \\lanserver • lanserver • http://www.servername.com • www.servername.com • 127.0.0.1 If context = "remote", this parameter is required. Usage The following example creates the Windows Collaborative Data Objects (CDO) for NTS NewMail object to send mail. You would use this code within a cfscript tag. Mailer = CreateObject("COM", "CDONTS.NewMail"); For more information, see Chapter 34, “Integrating COM and CORBA Objects in CFML Applications,” in Developing ColdFusion MX Applications. 424 Chapter 3: ColdFusion Functions CreateObject: component object Description The CreateObject function can create an instance of a ColdFusion component (CFC) object. Returns A component object. Function syntax CreateObject(type, component-name) Parameters Parameter Description type Type of object to create. • com • corba • java • component • webservice component-name The CFC name; corresponds to the name of the file that defines the component; for example, use engineComp to specify the component defined in the engineComp.cfc file Usage On UNIX systems, ColdFusion searches first for a file with a name that matches the specified component name, but is all lower case. If it does not find the file, it looks for a file name that matches the component name exactly, with the identical character casing. In the following example, the CFScript statements assign the tellTimeCFC variable to the tellTime component using the CreateObject function. The CreateObject function references the component in another directory. To invoke component methods, you use function syntax. For more information, see Chapter 11, “Building and Using ColdFusion Components,” in Developing ColdFusion MX Applications. Example Server's Local Time: tellTimeCFC=CreateObject("component","appResources.components. tellTime"); tellTimeCFC.getLocalTime();
Calculated UTC Time: tellTimeCFC.getUTCTime(); CreateObject 425 CreateObject: CORBA object Description The CreateObject function can call a method on a CORBA object. The object must be defined and registered for use. Returns A handle to a CORBA interface. Function syntax CreateObject(type, context, class, locale) History See the History section of the main CreateObject function page. Parameters Parameter Description type Type of object to create. • com • corba • java • component • webservice context • IOR: ColdFusion uses IOR to access CORBA server • NameService: ColdFusion uses naming service to access server. Valid only with the InitialContext of a VisiBroker ORB. class • If context = "ior": absolute path of file that contains string version of the Interoperable Object Reference (IOR). ColdFusion must be able to read file; it should be local to ColdFusion server or accessible on network • If context = "nameservice": forward slash-delimited naming context for naming service. For example: Allaire//Doc/empobject locale The name of the Java config that holds the properties file. For more information, see Configuring and Administering ColdFusion MX. Usage In the class attribute, if "context=NameService", use a dot separator for the first part of the string. Use either of the following formats: • "Macromedia/Eng/CF" • "Macromedia.current/Eng.current/CF" ColdFusion Enterprise supports CORBA through the Dynamic Invocation Interface (DII). To use this function with CORBA objects, you must provide the name of the file that contains a string version of the IOR, or the object’s naming context in the naming service. You must provide the object’s attributes, method names and method signatures. This function supports user-defined types (structures, arrays, and sequences). Example myobj = CreateObject("corba", "d:\temp\tester.ior", "ior", "visibroker") // uses IOR 426 Chapter 3: ColdFusion Functions myobj = CreateObject("corba", "Macromedia/Eng/CF", "nameservice", "visibroker") // uses nameservice myobj = CreateObject("corba", "d:\temp\tester.ior", "nameservice") // uses nameservice and default configuration CreateObject 427 CreateObject: Java or EJB object Description The CreateObject function can create a Java object, and, by extension, an EJB object. Returns A Java object. Function syntax CreateObject(type, class) Parameters Parameter Description type Type of object to create. • com • corba • java • component • webservice class A Java class name Usage Any Java class available in the class path that is specified in the ColdFusion Administrator can be loaded and used from ColdFusion with the CreateObject function. To access Java methods and fields: 1 Call the CreateObject function or the cfobject tag to load the class. 2 Use the init method, with appropriate arguments, to call an instance of the class. For example: Calling a public method on the object without first calling the "init" method invokes a static method. Arguments and return values can be any Java type (simple, array, object). If strings are passed as arguments, ColdFusion does the conversions; if strings are received as return values, ColdFusion does no conversion. Overloaded methods are supported if the number of arguments is different. Future enhancements will let you use cast functions that allow method signatures to be built more accurately. 428 Chapter 3: ColdFusion Functions CreateObject: web service object Description This function can create a web service object. Returns A web service object. Function syntax CreateObject(type, urltowsdl) Parameters Parameter Description type Type of object to create. • com • corba • java • component • webservice urltowsdl WSDL file URL; location of web service Usage You can use the CreateObject function to create a web service. Example newobject2 = CreateObject("webservice","wsdlurl") CreateObject 429 CreateODBCDate Description Creates an ODBC date object. Returns A date object, in normalized ODBC date format. Category Date and time functions Function syntax CreateODBCDate(date) See also CreateDate, CreateODBCDateTime Parameters Parameter Description date Date or date/time object in the range 100 AD–9999 AD. Usage This function does not parse or validate values. To ensure that dates are entered and processed correctly (for example, to ensure that a day/month/year entry is not confused with a month/day/ year entry, and so on), Macromedia recommends that you parse entered dates with the DateFormat function, using the mm-dd-yyyy mask, into three elements. Ensure that values are within appropriate ranges; for example, to validate a month value, use the attributes validate = "integer" and range = "1,12". Example

CreateODBCDate Example

Your date value, generated with CreateDateTime:

  • Formatted with CreateDate: #CreateDate(form.year, form.month, form.day)#
  • Formatted with CreateDateTime: #CreateDateTime(form.year, form.month, form.day, form.hour, form.minute, form.second)#
  • Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
  • Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#

The same value can be formatted with DateFormat:

  • Formatted with CreateDate and DateFormat: #DateFormat(CreateDate(form.year,form.month, form.day), "mmm-dd-yyyy")#
  • Formatted with CreateDateTime and DateFormat: #DateFormat(CreateDateTime(form.year, form.month, form.day, form.hour, form.minute, form.second))#
  • Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
  • Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")# 430 Chapter 3: ColdFusion Functions

Enter the year, month and day, as integers:

Year 
Month
Day

Hour 
Minute
Second

CreateODBCDate 431 CreateODBCDateTime Description Creates an ODBC date-time object. Returns A date/time object, in ODBC timestamp format. Category Date and time functions Function syntax CreateODBCDateTime(date) See also CreateDateTime, CreateODBCDate, CreateODBCTime, Now Parameters Parameter Description date Date/time object in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

CreateODBCDateTime Example

Your date value, generated using CreateDateTime:
  • Formatted with CreateDate: #CreateDate(form.year, form.month,form.day)#
  • Formatted with CreateDateTime: #CreateDateTime(form.year,form.month, form.day,form.hour,form.minute,form.second)#
  • Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
  • Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#

The same value can be formatted with DateFormat:

  • Formatted with CreateDate and DateFormat: #DateFormat(CreateDate(form.year,form.month,form.day), "mmm-dd-yyyy")#
  • Formatted with CreateDateTime and DateFormat: #DateFormat(CreateDateTime(form.year,form.month,form.day, form.hour,form.minute,form.second))#
  • Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
  • Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#
432 Chapter 3: ColdFusion Functions

Enter a year, month and day, as integers:

Year 

NAME="year" VALUE="1998" VALIDATE="integer"

Month
Day 
Hour 
Minute
Second

CreateODBCDateTime 433 CreateODBCTime Description Creates an ODBC time object. Returns A time object, in ODBC timestamp format. Category Date and time functions Function syntax CreateODBCTime(date) See also CreateODBCDateTime, CreateTime Parameters Parameter Description date Date/time object in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

CreateODBCTime Example

Your time value, created with CreateTime...
  • Formatted with CreateODBCTime: #CreateODBCTime(yourTime)#
  • Formatted with TimeFormat: #TimeFormat(yourTime)#
Hour 
Minute
second

434 Chapter 3: ColdFusion Functions CreateTime Description Creates a time variable. Returns A time variable. Category Date and time functions Function syntax CreateTime(hour, minute, second) See also CreateODBCTime, CreateDateTime Parameters Parameter Description hour Number in the range 0–23 minute Number in the range 0–59 second Number in the range 0–59 Usage CreateTime is a subset of CreateDateTime. A time variable is a special case of a date/time variable. The date part of a time variable is set to December 30, 1899. Example

CreateTime Example

Your time value, presented using CreateTime time function:
  • Formatted with timeFormat: #TimeFormat(yourTime)#
  • Formatted with timeFormat and hh:mm:ss: #TimeFormat(yourTime, 'hh:mm:ss')#
Hour
Minute 
Second 

CreateTime 435 CreateTimeSpan Description Creates a date/time object that defines a time period. You can add or subtract it from other date/ time objects and use it with the cachedWithin attribute of cfquery. Returns A date/time object. Category Date and time functions Function syntax CreateTimeSpan(days, hours, minutes, seconds) See also CreateDateTime, DateAdd, DateConvert Parameters Parameter Description days Integer in the range 0–32768; number of days in time period hours Number of hours in time period minutes Number of minutes in time period seconds Number of seconds in time period Usage Creates a special date/time object that should be used only to add and subtract from other date/ time objects or with the cfquery cachedWithin attribute. If you use the cachedWithin attribute of cfquery, and the original query date falls within the time span you define, cached query data is used. In this case, the CreateTimeSpan function is used to define a period of time from the present backwards. The cachedWithin attribute takes effect only if you enable query caching in the ColdFusion Administrator. For more information, see cfquery. Example

CreateTimeSpan Example

SELECT PARKNAME, REGION, STATE FROM Parks ORDER by ParkName, State 436 Chapter 3: ColdFusion Functions
Park Name Region State
#GetParks.CurrentRow# #ParkName# #Region# #State#
See next #MaxRows# rows
CreateTimeSpan 437 CreateUUID Description Creates a Universally Unique Identifier (UUID). A UUID is a 35-character string representation of a unique 128-bit integer. Returns A ColdFusion format UUID, in the format xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx, where x is a hexadecimal digit (0-9 or A-F). (The character groups are 8-4-4-4-16.) Category Other functions Function syntax CreateUUID() Usage The ColdFusion UUID generation algorithm uses the unique time-of-day value, the IEEE 802 Host ID, and a cryptographically strong random number generator to generate UUIDs that conform to the principles laid out in the draft IEEE RFC "UUIDs and GUIDs." The ColdFusion UUID format is as follows: xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx (8-4-4-16). This does not conform to the Microsoft/DCE standard, which is as follows: xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12) There are UUID test tools and a user-defined function called CreateGUID, which converts CFML UUIDs to UUID/Microsoft GUID format, available on the web at www.cflib.org. Use this function to generate a persistent identifier in a distributed environment. To a very high degree of certainty, this function returns a unique value; no other invocation on the same or any other system returns the same value. UUIDs are used by distributed computing frameworks, such as DCE/RPC, COM+, and CORBA. In ColdFusion, you can use UUIDs as primary table keys for applications in which data is stored in shared databases. In such cases, using numeric keys can cause primary-key constraint violations during table merges. Using UUIDs, you can eliminate these violations. Example

CreateUUID Example

This example uses CreateUUID to generate a UUID when you submit the form. You can submit the form more than once.


Your new UUID is: #CreateUUID()#

438 Chapter 3: ColdFusion Functions DateAdd Description Adds units of time to a date. Returns A date/time object. Category Date and time functions Function syntax DateAdd("datepart", number, "date") See also DateConvert, DatePart, CreateTimeSpan History ColdFusion MX 6.1: Added the datepart character L or l to represent milliseconds. Parameters Parameter Description datepart String: • yyyy: Year • q: Quarter • m: Month • y: Day of year • d: Day • w: Weekday • ww: Week • h: Hour • n: Minute • s: Second • l: Millisecond number Number of units of datepart to add to date (positive, to get dates in the future; negative, to get dates in the past) date Date/time object, in the range 100 AD–9999 AD. Usage The datepart specifiers y, d, and w add a number of days to a date. When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Example DateAdd 439 SELECT UserName, Subject, Posted FROMMessages

This example uses DateAdd to determine when a message in the database will expire. Currently, messages older than #value# years quarters months days of year weekdays weeks hours minutes seconds years are expired.

UserName Subject Posted
#UserName# #Subject# #Posted# EXPIRED
Select an expiration value: 440 Chapter 3: ColdFusion Functions DateCompare Description Performs a full date/time comparison of two dates. Returns • -1, if date1 is less than date2 • 0, if date1 is equal to date2 • 1, if date1 is greater than date2 Category Date and time functions Function syntax DateCompare("date1", "date2" [, "datePart"]) See also CreateDateTime, DatePart Parameters Parameter Description date1 Date/time object, in the range 100 AD–9999 AD. date2 Date/time object, in the range 100 AD–9999 AD. datePart Optional. String. Precision of the comparison. • s Precise to the second (default) • n Precise to the minute • h Precise to the hour • d Precise to the day • m Precise to the month • yyyy Precise to the year Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Example

DateCompare Example

The DateCompare function compares two date/time values.

#DateFormat(FORM.date1)# #TimeFormat(FORM.date1)# (Date 1) is earlier than #DateFormat(FORM.date2)# #TimeFormat(FORM.date2)# (Date 2)

The dates are not equal DateCompare 441

#DateFormat(FORM.date1)# #TimeFormat(FORM.date1)# (Date to #DateFormat(FORM.date2)# #TimeFormat(FORM.date2)# (Date The dates are equal!

#DateFormat(FORM.date1)# #TimeFormat(FORM.date1)# (Date than #DateFormat(FORM.date2)# #TimeFormat(FORM.date2)# (Date The dates are not equal

This is the default case

Enter two valid date values

1) is equal 2)

1) is later 2)


Date 1

Date 2

Specify precision to the:

442 Chapter 3: ColdFusion Functions DateConvert Description Converts local time to Coordinated Universal Time (UTC), or UTC to local time. The function uses the daylight savings settings in the executing computer to compute daylight savings time, if required. Returns UTC- or local-formatted time object. Category Date and time functions Function syntax DateConvert("conversion-type", "date") See also GetTimeZoneInfo, CreateDateTime, DatePart Parameters Parameter Description conversion-type • local2Utc: Converts local time to UTC time. • utc2Local: Converts UTC time to local time. date Date and time string or a variable that contains one. To create, use CreateDateTime. Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the CreateDate or Now function as the date parameter of this function; for example: #DateConvert(CreateDate(2001, 3, 3))# Example

DateConvert Example

The current date and time: #curDate#.

The current date and time converted to UTC time: #utcDate#.

Your date value, presented as a ColdFusion date/time string:#yourdate#.

Your date and time value, converted to Coordinated Universal Time (UTC): #yourUTC#.

DateConvert 443

Your UTC date and time, converted back to local date and time: #DateConvert("utc2local", yourUTC)#.

Type the date and time, and press Enter to see the conversion.

Enter year, month and day in integer format for date value to view:

Year
Month
Day
Hour
Minute
Second
444 Chapter 3: ColdFusion Functions DateDiff Description Determines the integer number of units by which date1 is less than date2. Returns A number of units, of type datepart. Category Date and time functions Function syntax DateDiff("datepart", "date1", "date2") See also DateAdd, DatePart, CreateTimeSpan History ColdFusion MX: • Changed how negative date differences are calculated: this function calculates negative date differences correctly; its output may be different from that in earlier releases. • Changed the w and ww attributes; they determine the number of full weeks between the two dates. Parameters Parameter Description datepart String specifying the units in which to count; for example yyyy requests a date difference in whole years. • yyyy: Years • q: Quarters • m: Months • y: Days of year (same as d) • d: Days • w: Weekdays (same as ww) • ww: Weeks • h: Hours • n: Minutes • s: Seconds date1 Date/time object, in the range 100 AD–9999 AD. date2 Date/time object, in the range 100 AD–9999 AD. Usage The DateDiff function determines the number of complete datepart units between the two dates; for example, if the datepart parameter is "m" and the dates differ by 55 days, the function returns 1. Enclose string constant dates in quotation marks. If the text contains only numbers (such 1932), and is not surrounded by quotation marks, ColdFusion interprets it as a date/time object, resulting in an incorrect value. DateDiff 445 Example

This example uses DateDiff to determine the difference in years quarters months days days weekdays weeks hours minutes seconds years dateparts between date1 and date2.

The difference is #Abs(DateDiff(type, form.date2, form.date1))# years quarters months days days weekdays weeks hours minutes seconds years .

The two dates are equal! Try changing one of the values ...

Please enter two valid date/time values, formatted like this: #DateFormat(Now())#

Date 1

446

Chapter 3: ColdFusion Functions


Date 2

What kind of unit to show difference?

. DateDiff 447 DateFormat Description Formats a date value using U.S. date formats. For international date support, use LSDateFormat. Returns A text string representing the date formatted according to the mask. If no mask is specified, returns the value in dd-mmm-yy format. Category Date and time functions Function syntax DateFormat("date" [, "mask" ]) See also Now, CreateDate, LSDateFormat, LSParseDateTime, LSTimeFormat, TimeFormat, ParseDateTime History ColdFusion MX: Added support for the following mask attribute options: short, medium, long, and full. Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. mask Characters that show how ColdFusion displays a date: • d: Day of the month as digits; no leading zero for single-digit days. • dd: Day of the month as digits; leading zero for single-digit days. • ddd: Day of the week as a three-letter abbreviation. • dddd: Day of the week as its full name. • m: Month as digits; no leading zero for single-digit months. • mm: Month as digits; leading zero for single-digit months. • mmm: Month as a three-letter abbreviation. • mmmm: Month as its full name. • y: Year as last two digits; no leading zero for years less than 10. • yy: Year as last two digits; leading zero for years less than 10. • yyyy: Year represented by four digits. • gg: Period/era string. Ignored. Reserved. The following masks tell how to format the full date and cannot be combined with other masks: • short: equivalent to m/d/y • medium: equivalent to mmm d, yyyy • long: equivalent to mmmm d, yyyy • full: equivalent to dddd, mmmm d, yyyy Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example: #DateFormat(CreateDate(2001, 3, 3))# 448 Chapter 3: ColdFusion Functions Date and time values in database query results can vary in sequence and formatting unless you use functions to format them. To ensure that application users correctly understand displayed dates and times, Macromedia recommends that you use this function and the LSDateFormat, TimeFormat, and LSTimeFormat functions to format resultset values. For more information and examples, see TechNote 22183, "ColdFusion Server (5 and 4.5.x) with Oracle: Formatting Date and Time Query Results," on our website at www.coldfusion.com/Support/KnowledgeBase/ SearchForm.cfm. Example

DateFormat Example

Today’s date is #todayDate#.

Using DateFormat, we can display that date in different ways:

  • #DateFormat(todayDate)#
  • #DateFormat(todayDate, "mmm-dd-yyyy")#
  • #DateFormat(todayDate, "mmmm d, yyyy")#
  • #DateFormat(todayDate, "mm/dd/yyyy")#
  • #DateFormat(todayDate, "d-mmm-yyyy")#
  • #DateFormat(todayDate, "ddd, mmmm dd, yyyy")#
  • #DateFormat(todayDate, "short")#
  • #DateFormat(todayDate, "medium")#
  • #DateFormat(todayDate, "long")#
  • #DateFormat(todayDate, "full")#
DateFormat 449 DatePart Description Extracts a part from a date value. Returns Part of a date, as an integer. Category Date and time functions Function syntax DatePart("datepart", "date") See also DateAdd, DateConvert History ColdFusion MX 6.1: Added the datepart character L or l to represent milliseconds. Parameters Parameter Description datepart String: • yyyy: Year • q: Quarter • m: Month • y: Day of year • d: Day • w: Weekday • ww: Week • h: Hour • n: Minute • s: Second • l: Millisecond date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Example

DatePart Example

Today’s date is #todayDate#.

Using datepart, we extract an integer representing the dateparts from that value

  • year: #DatePart("yyyy", todayDate)#
  • quarter: #DatePart("q", todayDate)#
  • month: #DatePart("m", todayDate)#
  • day of year: #DatePart("y", todayDate)# 450 Chapter 3: ColdFusion Functions
  • day: #DatePart("d", todayDate)#
  • weekday: #DatePart("w", todayDate)#
  • week: #DatePart("ww", todayDate)#
  • hour: #DatePart("h", todayDate)#
  • minute: #DatePart("n", todayDate)#
  • second: #DatePart("s", todayDate)#
DatePart 451 Day Description Determines the day of the month, in a date. Returns The ordinal for the day of the month, ranging from 1 to 31. Category Date and time functions Function syntax Day("date") See also DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example: #Day(CreateDate(2001, 3, 3))# Example

Day Example

More information about your date:

Date: #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(YourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year 452 Chapter 3: ColdFusion Functions DayOfWeek Description Determines the day of the week, in a date. Returns The ordinal for the day of the week, as an integer in the range 1 (Sunday) to 7 (Saturday). Category Date and time functions Function syntax DayOfWeek("date") See also Day, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example, #DayOfWeek(CreateDate(2001, 3, 3))# Example

DayOfWeek Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(YourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year DayOfWeek 453 DayOfWeekAsString Description Determines the day of the week, in a date, as a string function. Returns The day of the week, as a string that corresponds to day_of_week. Category Date and time functions, String functions Function syntax DayOfWeekAsString(day_of_week) See also Day, DayOfWeek, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth Parameters Parameter Description day_of_week Integer, in the range 1 (Sunday) - 7 (Saturday). Example

DayOfWeekAsString Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(YourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year 454 Chapter 3: ColdFusion Functions DayOfYear Description Determines the day of the year, in a date. Returns The ordinal value of day of the year, as an integer. Category Date and time functions Function syntax DayOfYear("date") See also Day, DayOfWeek, DayOfWeekAsString, DaysInMonth, DaysInYear, FirstDayOfMonth Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage This function accounts for leap years. When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example, #DayOfYear(CreateDate(2001, 3, 3))# Example

Day7OfYear Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(yourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(yourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year DayOfYear 455 DaysInMonth Description Determines the number of days in a month. Returns The number of days in the month in Date. Category Date and time functions Function syntax DaysInMonth("date") See also Day, DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInYear, FirstDayOfMonth Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the Now function or the CreateDate function as the date parameter of this function; for example: #DaysInMonth(CreateDate(2001, 3, 3))# Example

DaysInMonth Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(YourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year 456 Chapter 3: ColdFusion Functions DaysInYear Description Determines the number of days in a year. Returns The number of days in a year. Category Date and time functions Function syntax DaysInYear("date") See also Day, DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth, IsLeapYear Parameters Parameter Description date • Date/time object, in the range 100 AD–9999 AD. Usage DaysInYear accounts for leap years. When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object. Note: You can pass the CreateDate function or the Now function as the date parameter of this function; for example: #DaysInYear(CreateDate(2001, 3, 3))# Example

DaysInYear Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(yourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#). DaysInYear 457 DE Description Postpones evaluation of a string as an expression, when it is passed as a parameter to the IIf or Evaluate functions. Escapes any double quotation marks in the parameter and wraps the result in double quotation marks. This function is especially useful with the IIf function, to prevent the function from evaluating a string that is to be output. This applies to expressions that are not surrounded by pound signs. (If pound signs surround any part of an expression, a ColdFusion function evaluates that part first, regardless of whether the DE function is present.) Returns Parameter, surrounded by double quotation marks, with any inner double quotation marks escaped. Category Dynamic evaluation functions Function syntax DE(string) See also Evaluate, IIf Parameters Parameter Description string String to evaluate, after delay Usage Consider this example: IIf( 1 eq 2, DE('#Var1#'), DE('#Var2#')) ColdFusion evaluates whatever is surrounded by pounds in the expression before executing it. So, although this expression is never true (because Var1 does not exist), the expression fails with an 'Error Resolving Parameter' error, because ColdFusion evaluates #Var1#' and #Var2#' before executing either expression. This example returns 'Var2': IIf( 1 eq 2, DE('Var1'), DE('Var2')) The following example uses IIF to alternate table-row background colors, white and gray. It uses the DE function to prevent ColdFusion from evaluating the color strings.

458 Chapter 3: ColdFusion Functions
hello #i#
For more information and code examples, see Chapter 4, “Using Expressions and Pound Signs,” in Developing ColdFusion MX Applications. Example

DE Example

The Expression Result

The value of the expression #Evaluate(DE(FORM.MyExpression))# is #MyExpression#.

Sorry, there’s been an Error. Try a simple expression, such as "2+2".

#cfcatch.message# DE 459 DecimalFormat Description Converts a number to a decimal-formatted string. Returns A number as a string formatted with two decimal places and a thousands separator. Category Display and formatting functions Function syntax DecimalFormat(number) See also DollarFormat, NumberFormat Parameters Parameter Description number Number to format Example

DecimalFormat Function

Returns a number to two decimal places.

#counter# * Square Root of 2: #DecimalFormat(Evaluate(counter * sqr(2)))#
460 Chapter 3: ColdFusion Functions DecrementValue Description Decrements the integer part of a number. Returns Integer part of number, decremented by one. Category Mathematical functions Function syntax DecrementValue(number) See also IncrementValue Parameters Parameter Description number Number to decrement Example

DecrementValue Example

Returns the integer part of a number decremented by one.

DecrementValue(0): #DecrementValue(0)#

DecrementValue("1"): #DecrementValue("1")#

DecrementValue(123.35): #DecrementValue(123.35)# DecrementValue 461 Decrypt Description Decrypts a string that is encrypted with the Encrypt function. Returns String, unencrypted. Category Other functions, String functions Function syntax Decrypt(encrypted_string, seed) See also Duplicate, Encrypt Parameters Parameter Description encrypted_string String or a variable that contains one. String to decrypt seed String. The 32-bit key that was used to encrypt the string. Example

Decrypt Example

This function encrypts/decrypts a string. Enter a string and a key.

The string:

#string#

The key:

#key#

Encrypted:

#encrypted#

Decrypted:

#decrypted#

Input your key:

Enter string to encrypt:

462 Chapter 3: ColdFusion Functions DeleteClientVariable Description Deletes a client variable. (To test for the existence of a variable, use IsDefined.) Returns True, if the variable is successfully deleted; false, otherwise. Category Other functions Function syntax DeleteClientVariable("name") See also GetClientVariablesList History ColdFusion MX: Changed behavior: if the variable is not present, this function now returns False. (In earlier releases, it threw an error.) Parameters Parameter Description name Name of a client variable to delete, surrounded by double quotation marks Example

DeleteClientVariable Example

This view-only example deletes a client variable called "User_ID", if it exists in the list of client variables returned by GetClientVariablesList.

This example requires the existence of an Application.cfm file and client management to be in effect. DeleteClientVariable 463 DirectoryExists Description Determines whether a directory exists. Returns Yes, if the specified directory exists; No, otherwise. Category System functions Function syntax DirectoryExists(absolute_path) See also FileExists Parameters Parameter Description absolute_path An absolute path Example

DirectoryExists Example

Enter a directory to check for existence.


Your directory exists. Directory name: #yourDirectory#

Your directory does not exist.

464 Chapter 3: ColdFusion Functions DollarFormat Description Formats a string in U.S. format. (For other currencies, use LSCurrencyFormat or LSEuroCurrencyFormat.) Returns A number as a string, formatted with two decimal places, thousands separator, and dollar sign. If number is negative, the return value is enclosed in parentheses. If number is an empty string, returns zero. Category Display and formatting functions Function syntax DollarFormat(number) See also DecimalFormat, NumberFormat Parameters Parameter Description number Number to format Example DollarFormat Example

DollarFormat Example

bill#DollarFormat(full)##DollarFormat(quarter)#
#DollarFormat(half)# #DollarFormat(threefourth)#
18% tip#DollarFormat(Evaluate(full * (18/100)))#
#DollarFormat(Evaluate(quarter * (18/100)))#
#DollarFormat(Evaluate(half * (18/100)))#
#DollarFormat(Evaluate(threefourth * (18/100)))#
DollarFormat 465 Duplicate Description Returns a clone, also known as a deep copy, of a variable. There is no reference to the original variable. Returns A clone of a variable. Category Structure functions, System functions Function syntax Duplicate(variable_name) See also StructCopy, other Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description variable_name Name of a variable to duplicate Usage Use this function to duplicate complex structures, such as nested structures and queries. Note: With this function, you cannot duplicate a COM, CORBA, or JAVA object returned from the cfobject tag or the CreateObject function. If an array element or structure field is a COM, CORBA, or JAVA object, you cannot duplicate the array or structure. Example

Duplicate Example

The copy contains the modified value: #copy.nested.item#

The duplicate contains the original value: #clone.nested.item#

466 Chapter 3: ColdFusion Functions Encrypt Description Encrypts a string. Uses a symmetric key-based algorithm, in which the same key is used to encrypt and decrypt a string. The security of the encrypted string depends on maintaining the secrecy of the key. Uses an XOR-based algorithm that uses a pseudo-random 32-bit key, based on a seed passed by the user as a function parameter. Returns String; can be much longer than the original string. Category Other functions, String functions Function syntax Encrypt(string, seed) See also Decrypt Parameters Parameter Description string String to encrypt seed String. Seed used to generate 32-bit encryption key. Can be any combination of any number of characters. Example

Encrypt Example

This function allows for the encryption and decryption of a string. Try it by entering a string and a key to see the results.

The string:

#string#

The key:

#key#

Encrypted:

#encrypted#

Decrypted:

#decrypted#

Input your key:

Input your string to be encrypted:

Encrypt 467 Evaluate Description Evaluates one or more string expressions, dynamically, from left to right. (The results of an evaluation on the left can have meaning in an expression to the right.) Returns the result of evaluating the rightmost expression. Returns An object; the result of the evaluation(s). Category Dynamic evaluation functions Function syntax Evaluate(string_expression1 [, string_expression2 [, … ] ] ) See also DE, IIf Parameters Parameter Description string_expression1, string_expression2... Expressions to evaluate Usage String expressions can be complex. If a string expression contains a single or double quotation mark, it must be escaped. This function is useful for forming one variable from multiple variables. For example, to reference a column of the query qNames with a variable, var, using an index value to traverse rows, you could use the following code: For more information, see Chapter 4, “Using Expressions and Pound Signs,” in Developing ColdFusion MX Applications. Example

Evaluate Example

The Expression Result

The value of the expression #Evaluate(DE(FORM.MyExpression))# is #MyExpression#. ... 468 Chapter 3: ColdFusion Functions Exp Description Calculates the exponent whose base is e that represents number. The constant e equals 2.71828182845904, the base of the natural logarithm. This function is the inverse of Log, the natural logarithm of number. Returns The constant e, raised to the power of number. Category Mathematical functions Function syntax Exp(number) See also Log, Log10 Parameters Parameter Description number Exponent to apply to the base e Usage To calculate powers of other bases, use the exponentiation operator (^). Example

Exp Example

Your number, #FORM.number#
#FORM.number# raised to the E power: #exp(FORM.number)#
You must enter a positive real number to see its natural logarithm
The natural logarithm of #FORM.number#: #log(FORM.number)#

You must enter a positive real number to see its logarithm to base 10
The logarithm of #FORM.number# to base 10: #log10(FORM.number)#
Enter a number to see its value raised to the E power, its natural logarithm, and the logarithm of number to base 10. Exp 469 ExpandPath Description Creates an absolute, platform-appropriate path that is equivalent to the value of relative_path, appended to the base path. This function (despite its name) can accept an absolute or relative path in the relative_path attribute The base path is the currently executing page’s directory path. It is stored in pageContext.getServletContext(). Returns A string. If the relative path contains a trailing forward slash or backward slash, the return value contains the same trailing character. Category System functions Function syntax ExpandPath(relative_path) See also FileExists, GetCurrentTemplatePath, GetFileFromPath History ColdFusion MX: Changed behavior for the relative_path attribute: this function can now accept an absolute or relative path in the relative_path attribute. To resolve a path, this function uses virtual mappings that are defined in the ColdFusion Administrator. This function does not reliably use virtual mappings that are defined in IIS, Apache, or other Web servers. Parameters Parameter Description relative_path Relative or absolute directory reference or file name, within the current directory, (.\ and ..\) to convert to an absolute path. Can include forward backward slashes. Usage If the parameter or the returned path is invalid, the function throws an error. These examples show the valid constructions of relative_path: • • • • • • • • ExpandPath( ExpandPath( ExpandPath( ExpandPath( ExpandPath( ExpandPath( ExpandPath( ExpandPath( "*.*") "/") "\") "/mycfpage.cfm") "mycfpage.cfm") "myDir/mycfpage.cfm") "/myDir/mycfpage.cfm") "../../mycfpage.cfm") Example

ExpandPath Example - View Only

Please enter a file name

Enter the name of a file in this directory (try expandpath.cfm)

---> ExpandPath 471 FileExists Description Determines whether a file exists. Returns Yes, if the file specified in the parameter exists; No, otherwise. Category System functions, Decision functions Function syntax FileExists(absolute_path) See also DirectoryExists, ExpandPath, GetTemplatePath Parameters Parameter Description absolute_path An absolute path Example

FileExists Example

The current directory is: #GetDirectoryFromPath(thisPath)#

Your file exists in this directory. You entered the correct file name, #GetFileFromPath("#thisPath#/#yourfile#")# 472 Chapter 3: ColdFusion Functions Find Description Finds the first occurrence of a substring in a string, from a specified start position. The search is case-sensitive. Returns A number; the position of substring in string; or 0, if substring is not in string. Category String functions Function syntax Find(substring, string [, start ]) See also FindNoCase, Compare, FindOneOf, REFind, Replace Parameters Parameter Description substring A string or a variable that contains one. String for which to search. string A string or a variable that contains one. String in which to search. start Start position of search. Example #find("the",stringToSearch)#
#find("the",stringToSearch,35)#
#find("no such substring",stringToSearch)#

#findnocase("the",stringToSearch)#
#findnocase("the",stringToSearch,5)#
#findnocase("no such substring",stringToSearch)#

#findoneof("aeiou",stringToSearch)#
#findoneof("aeiou",stringToSearch,4)#
#findoneof("@%^*()",stringToSearch)#
Find 473 FindNoCase Description Finds the first occurrence of a substring in a string, from a specified start position. If substring is not in string, returns zero. The search is case-insensitive. Returns The position of substring in string; or 0, if substring is not in string. Category String functions Function syntax FindNoCase(substring, string [, start ]) See also Find, CompareNoCase, FindOneOf, REFind, Replace Parameters Parameter Description substring A string or a variable that contains one. String for which to search. string A string or a variable that contains one. String in which to search. start Start position of search. Example #find("the",stringToSearch)#
#find("the",stringToSearch,35)#
#find("no such substring",stringToSearch)#

#findnocase("the",stringToSearch)#
#findnocase("the",stringToSearch,5)#
#findnocase("no such substring",stringToSearch)#

#findoneof("aeiou",stringToSearch)#
#findoneof("aeiou",stringToSearch,4)#
#findoneof("@%^*()",stringToSearch)#
474 Chapter 3: ColdFusion Functions FindOneOf Description Finds the first occurrence of any one of a set of characters in a string, from a specified start position. The search is case-sensitive. Returns The position of the first member of set found in string; or 0, if no member of set is found in string. Category String functions Function syntax FindOneOf(set, string [, start ]) See also Find, Compare, REFind Parameters Parameter Description set A string or a variable that contains one. String that contains one or more characters to search for. string A string or a variable that contains one. String in which to search. start Start position of search. Example #find("the",stringToSearch)#
#find("the",stringToSearch,35)#
#find("no such substring",stringToSearch)#

#findnocase("the",stringToSearch)#
#findnocase("the",stringToSearch,5)#
#findnocase("no such substring",stringToSearch)#

#findoneof("aeiou",stringToSearch)#
#findoneof("aeiou",stringToSearch,4)#
#findoneof("@%^*()",stringToSearch)#
FindOneOf 475 FirstDayOfMonth Description Determines the ordinal (day number, in the year) of the first day of the month in which a given date falls. Returns A number corresponding to a day-number in a year. Category Date and time functions Function syntax FirstDayOfMonth(date) See also Day, DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

FirstDayOfMonth Example

The first day of #MonthAsString(Month(Now()))#, #Year(Now())# was day #FirstDayOfMonth(Now())# of the year. 476 Chapter 3: ColdFusion Functions Fix Description Converts a real number to an integer. Returns If number is greater than or equal to 0, the closest integer less than number. If number is less than 0, the closest integer greater than number. Category Mathematical functions Function syntax Fix(number) See also Ceiling, Int, Round Parameters Parameter Description number A number Example

Fix Example

Fix returns the closest integer less than the number if the number is greater than or equal to 0. Fix returns the closest integer greater than the number if number is less than 0.

The fix of 3.4 is #Fix(3.4)#

The fix of 3 is #Fix(3)#

The fix of 3.8 is #Fix(3.8)#

The fix of -4.2 is #Fix(-4.2)# Fix 477 FormatBaseN Description Converts number to a string, in the base specified by radix. Returns String that represents number, in the base radix. Category Display and formatting functions, Mathematical functions, String functions Function syntax FormatBaseN(number, radix) See also InputBaseN Parameters Parameter Description number Number to convert radix Base of the result Example

FormatBaseN Example

Converts a number to a string in the base specified by Radix.


FormatBaseN(10,2): #FormatBaseN(10,2)#
FormatBaseN(1024,16): #FormatBaseN(1024,16)#
FormatBaseN(125,10): #FormatBaseN(125,10)#
FormatBaseN(10.75,2): #FormatBaseN(10.75,2)#

InputBaseN Example

InputBaseN returns the number obtained by converting a string, using base specified by Radix (an integer from 2 to 36).
InputBaseN("1010",2): #InputBaseN("1010",2)#
InputBaseN("3ff",16): #InputBaseN("3ff",16)#
InputBaseN("125",10): #InputBaseN("125",10)#
InputBaseN(1010,2): #InputBaseN(1010,2)#
478 Chapter 3: ColdFusion Functions GetAuthUser Description Gets the name of an authenticated user. Returns The name of an authenticated user. Category Authentication functions Function syntax GetAuthUser() See also IsUserInRole, cflogin, cfloginuser, Chapter 16, “Securing Applications,” in Developing ColdFusion MX Applications History ColdFusion MX: Added this function. Usage This function works with cflogin authentication or web server authentication. It checks for a logged-in user as follows: 1 It checks for a login made with cfloginuser. 2 If no user was logged in with cfloginuser, it checks for a web server login (cgi.remote_user). Example

GetAuthUser Example

Authenticated User: GetAuthUser() GetAuthUser 479 GetBaseTagData Description Used within a custom tag. Finds calling (ancestor) tag by name and accesses its data. Returns An object that contains data (variables, scopes, and so on) from an ancestor tag. If there is no ancestor by the specified name, or if the ancestor does not expose data (for example, cfif ), an exception is thrown. Category Other functions Function syntax GetBaseTagData(tagname [, instancenumber ] ) See also GetBaseTagList Parameters Parameter Req/Opt Default Description tagname Required Ancestor tag name for which to return data instancenumber Optional 1 (closest Number of ancestor levels to jump before returning data ancestor) Example ... Running in the context of a custom tag named #inCustomTag#.

Located inside the template BODY 480 Chapter 3: ColdFusion Functions GetBaseTagList Description Gets ancestor tag names, starting with the parent tag. Returns A comma-delimited list of uppercase ancestor tag names, as a string. The first list element is the current tag. If the current tag is nested, the next element is the parent tag. If the function is called for a top-level tag, it returns an empty string. If an ancestor does not expose data (see GetBaseTagData), its name might not be returned. Category Other functions Function syntax GetBaseTagList() See also GetBaseTagData Usage This function does not display the following tags or end tags in the ancestor tag list: • • • cfif, cfelseif, cfelse cfswitch, cfcase, cfdefaultcase cftry, cfcatch This function displays the following tags only under the following conditions: • • • cfloop: if it uses a query attribute if at least one of its children is a complex expression cfprocessingdirective: if it has at least one other attribute besides pageencoding cfoutput: Example

Dump of GetBaseTagList output:


This is custom tag #ListGetAt(ancestorList,1)#
Running in the context of a cfloop tag.
GetBaseTagList 481 GetBaseTemplatePath Description Gets the absolute path of an application’s base page. Returns The absolute path of the application base page, as a string. Category Other functions, System functions Function syntax GetBaseTemplatePath() See also GetCurrentTemplatePath, FileExists, ExpandPath Example

GetBaseTemplatePath Example

The template path of the current page is: #GetBaseTemplatePath()# 482 Chapter 3: ColdFusion Functions GetClientVariablesList Description Finds the client variables to which a page has write access. Returns Comma-delimited list of non-read-only client variables, as a string. Category List functions, Other functions Function syntax GetClientVariablesList() See also DeleteClientVariable Usage The list of variables returned by this function is compatible with ColdFusion list functions. Example

GetClientVariablesList Example

This view-only example deletes a client variable called "User_ID", if it exists in the list of client variables returned by GetClientVariablesList().

This example requires the existence of an Application.cfm file and that client management be in effect. GetClientVariablesList 483 GetCurrentTemplatePath Description Gets the path of the page that calls this function. Returns The absolute path of the page that contains the call to this function, as a string. Category System functions Function syntax GetCurrentTemplatePath() See also GetBaseTemplatePath, FileExists, ExpandPath Usage If the function call is made from a page included with a cfinclude tag, this function returns the page path of an included page. Contrast this with the GetBaseTemplatePath function, which returns the path of the top-level page, even if it is called from an included page. Example

GetCurrentTemplatePath Example

The template path of the current page is: #GetCurrentTemplatePath()# 484 Chapter 3: ColdFusion Functions GetDirectoryFromPath Description Extracts a directory from an absolute path. Returns Absolute path, without the filename. The last character is a forward or backward slash, depending on the operating system. Category System functions Function syntax GetDirectoryFromPath(path) See also ExpandPath, GetFileFromPath Parameters Parameter Description path Absolute path (drive, directory, filename, and extension) Example

GetDirectoryFromPath Example

The current directory is: #GetDirectoryFromPath(thisPath)#

Your file exists in this directory. You entered the correct file name, #GetFileFromPath("#thisPath#/#yourfile#")#

Your file was not found in this directory:
Here is a list of the other files in this directory:

Please enter a file name

Enter the name of a file in this directory (try expandpath.cfm)

GetDirectoryFromPath 485
---> 486 Chapter 3: ColdFusion Functions GetEncoding Description Returns the encoding (character set) of the Form or URL scope. Returns String; the character encoding of the specified scope. Category International functions, System functions Function syntax GetEncoding(scope_name) See also SetEncoding, cfcontent, cfprocessingdirective, URLDecode, URLEncodedFormat History ColdFusion MX: Added this function. Parameters Parameter Description scope_name • Form • URL. Usage Use this function to determine the character encoding of the URL query string or the fields of a form that was submitted to the current page. The default encoding, if none has been explicitly set, is UTF-8. For more information, see: www.iana.org/assignments/character-sets. Example
SetEncoding("url", "big5"); WriteOutput("URL.XXX is " & URL.xxx & "
"); WriteOutput("URL.YYY is " & URL.yyy & "
"); theEncoding = GetEncoding("URL"); WriteOutput("The URL variables were decoded using '" & theEncoding & "' encoding."); WriteOutput("The encoding is " & theEncoding);
GetEncoding 487 GetException Description Used with the cftry and cfcatch tags. Retrieves a Java exception object from a Java object. Returns Any Java exception object raised by a previous method call on the Java object. Category System functions Syntax getException(object) Parameters Parameter Description object A Java object. Usage ColdFusion stores a Java exception object for each method call on a Java object. Subsequent method calls reset the exception object. To get the current exception object, you must call GetException on the Java object before other methods are invoked on it. Example Error
I got exception

The exception message is: #message#
488 Chapter 3: ColdFusion Functions GetFileFromPath Description Extracts a filename from an absolute path. Returns Filename, as a string. Category System functions Function syntax GetFileFromPath(path) See also ExpandPath, GetCurrentTemplatePath Parameters Parameter Description path Absolute path (drive, directory, filename, and extension) Example

GetFileFromPath Example

The current directory is: #GetDirectoryFromPath(thisPath)#

Your file exists in this directory. You entered the correct file name, #GetFileFromPath("#thisPath#/#yourfile#")#

Your file was not found in this directory:
Here is a list of the other files in this directory: ... GetFileFromPath 489 GetFunctionList Description Displays a list of the functions that are available in ColdFusion. Returns A structure of functions. Category System functions Function syntax GetFunctionList() Example #StructCount(fList)# functions

#key#
490 Chapter 3: ColdFusion Functions GetHttpRequestData Description Makes HTTP request headers and body available to CFML pages. Useful for capturing SOAP request data, which can be delivered in an HTTP header. Returns A ColdFusion structure. Category System functions Function syntax GetHttpRequestData() Parameters Parameter Description content Raw content from form submitted by client, in string or binary format. For content to be considered string data, the FORM request header "CONTENT_TYPE" must start with "text/" or be special case "application/x-www-form-urlencoded". Other types are stored as a binary object. headers Structure that contains HTTP request headers as value pairs. Includes custom headers, such as SOAP requests. method String that contains the CGI variable Request_Method. protocol String that contains the Server_Protocol CGI variable. Usage The structure returned by this function contains the following entries: Note: To determine whether data is binary, use IsBinary(x.content).To convert data to a string value, if it can be displayed as a string, use toString(x.content). The following example shows how this function can return HTTP header information. Example

HTTP Request item Value
#http_item# #StructFind(x.headers, http_item)#
request_method #x.method#
server_protocol #x.protocol#
GetHttpRequestData 491 http_content --- #x.content#
492 Chapter 3: ColdFusion Functions GetHttpTimeString Description Gets the current time, in the Universal Time code (UTC). Returns The time, as a string, according to the HTTP standard described in RFC 1123. Category Date and time functions, International functions Function syntax GetHttpTimeString(date_time_object) See also GetLocale, GetTimeZoneInfo, SetLocale Parameters Parameter Description date_time_object A ColdFusion date-time object string or Java Date object Usage The time in the returned string is UTC, consistent with the HTTP standard. Example #GetHttpTimeString("#Now()#")#
GetHttpTimeString 493 GetK2ServerDocCount Description This function is deprecated. Determines the number of documents that can be searched by the ColdFusion registered K2 Server. This function is used primarily by the ColdFusion Verity and K2Server Administrator pages, and requires significant processing time. Avoid using it in production applications. This function uses Verity K2Server Release K2.2.0. Returns The number of collection metadata items stored in Verity collections. Category Full-text search functions, Query functions Function syntax GetK2ServerDocCount() See also GetK2ServerDocCountLimit History ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases. ColdFusion MX: Added this function. Example GetK2ServerDocCount = $*#GetK2ServerDocCount()#*$ 494 Chapter 3: ColdFusion Functions GetK2ServerDocCountLimit Description This function is deprecated. Gets the maximum number of documents that the ColdFusion registered K2 Server is permitted to return from a search. This function is used primarily by the ColdFusion Verity and K2Server Administrator pages. This function uses Verity K2Server Release K2.2.0. Returns Number of collection metadata items that the K2 server permits, as an integer Category Full-text search functions, Query functions Function syntax GetK2ServerDocCountLimit() See also GetK2ServerDocCount History ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases. ColdFusion MX: Added this function. Usage If a search generates a larger number of documents than the limit, ColdFusion puts a warning message in the Administrator and in the log file. The restricted version of K2 Server version that is installed with ColdFusion has the following document search limits: • • • • • For ColdFusion MX Evaluation: 250,000 For ColdFusion MX Developer: 10,000 For ColdFusion MX Professional: 125,000 For ColdFusion MX Enterprise: 250,000 For ColdFusion MX with Macromedia Spectra: 750,000 K2Broker with ColdFusion MX has no limit. Example GetK2ServerDocCountLimit = $*#GetK2ServerDocCountLimit()#*$ GetK2ServerDocCountLimit 495 GetLocale Description Gets the current geographic/language locale value. To set the default display format of date, time, number, and currency values in a ColdFusion application session, you use the SetLocale function. Returns The current locale value, as a string. Category Display and formatting functions, International functions, System functions Function syntax GetLocale() See also SetLocale History ColdFusion MX: Changed behavior: this function determines whether a locale value is set. (The value is set with the SetLocale function.) • If the locale value is present, the function now returns it. • If the locale has not been explicitly set, ColdFusion now determines whether the default locale of the ColdFusion server computer operating system is among the locale values it supports. (The default locale is stored in the user environment variables user.language and user.region.) ■ If the default locale value is supported, the function returns this value ■ If the default locale value is not supported, the function returns English (US). (The code is "en_us"). (When ColdFusion is started, it stores the supported locale values in the variable Server.ColdFusion.SupportedLocales.) ColdFusion sets the locale in the JVM to this value; it persists until the server is restarted or it is reset with the SetLocale function. Usage This function does not access a web browser’s Accept-Language HTTP header setting. Example

GetLocale Example

The locale for this system is #GetLocale()# 496 Chapter 3: ColdFusion Functions GetMetaData Description Gets metadata (the methods, properties, and parameters of a component) associated with an object that is deployed on the ColdFusion server. This functionality, called introspection, lets applications dynamically determine how to use a component. Returns Key-value pairs, as a component descriptor data structure or as structured XML Category System functions Function syntax GetMetaData(object) or, if used within a ColdFusion component: GetMetaData(this) History ColdFusion MX: Added this function. Parameters Parameter Description object Reference to an object; use this attribute to call a function from a CFML page this Reference to an object; use this attribute to call a function from a component. Usage The this scope is available at runtime to the component body and to the invoked method’s function body. It is used to read and write variables that are present during the life of the component. Component metadata contains at least the following keys: • • • • name: the component name path: an absolute path to the component extends: ancestor component metadata functions: an array of metadata for each component function Other component attributes are returned as additional keys. Function metadata contains at least the following keys: • • name: the function name parameters: an array of argument metadata Other function attributes are returned as additional keys. Argument metadata contains at least the following key: • name: the argument name Other argument attributes are returned as additional keys. GetMetaData 497 Property metadata contains at least the following key: • the property name Other property attributes are returned as additional keys. 498 name: Chapter 3: ColdFusion Functions GetMetricData Description Gets server performance metrics. Returns ColdFusion structure that contains metric data, depending on the mode value. Category System functions Function syntax GetMetricData(mode) History ColdFusion MX: Deprecated the cachepops parameter. It might not work, and it might cause an error, in later releases. Parameters Parameter Option Description mode perf_monitor Returns internal data, in a structure. To receive data, you must enable PerfMonitor in ColdFusion Administrator before executing the function. On Windows, this data is otherwise displayed in the Windows PerfMonitor. simple_load Returns an integer value that is computed from the state of the server's internal queues. Indicates the overall server load. prev_req_time Returns the time, in milliseconds, that it took the server to process the previous request. avg_req_time Returns the average time, in milliseconds, that it takes the server to process a request. Changing the setting to 0 prevents the server from calculating the average and removes overhead associated with gathering data. Default: 120 seconds. Usage If mode = "perf_monitor", the function returns a structure with these data fields: Field Description InstanceName The name of the ColdFusion server. Default: cfserver PageHits Number of HTTP requests received since ColdFusion MX was started. ReqQueued Number of HTTP requests in the staging queue, waiting for processing. DBHits Number of database requests since the server was started. ReqRunning Number of HTTP requests currently running. In the ColdFusion Administrator, you can set the maximum number of requests that run concurrently. GetMetricData 499 Field Description ReqTimedOut Number of HTTP requests that timed out while in the staging queue or during processing. BytesIn Number of bytes in HTTP requests to ColdFusion MX BytesOut Number of bytes in HTTP responses from ColdFusion MX AvgQueueTime For the last two HTTP requests (current and previous), the average length of time the request waited in the staging queue. AvgReqTime For the last two HTTP requests (current and previous), the average length of time the server required to process the request AvgDBTime For the last two HTTP requests (current and previous), the average length of time the server took to process CFQueries in the request. cachepops This parameter is deprecated.ColdFusion automatically sets its value to -1. Example Current PerfMonitor data is:

InstanceName:#pmData.InstanceName#

PageHits:#pmData.PageHits#

ReqQueued: #pmData.ReqQueued#

DBHits: #pmData.DBHits#

ReqRunning: #pmData.ReqRunning#

ReqTimedOut: #pmData.ReqTimedOut#

BytesIn: #pmData.BytesIn#

BytesOut: #pmData.BytesOut#

AvgQueueTime: #pmData.AvgQueueTime#

AvgReqTime: #pmData.AvgReqTime#

AvgDBTime: #pmData.AvgDBTime#

500 Chapter 3: ColdFusion Functions GetPageContext Description Gets the current ColdFusion MX PageContext object that provides access to page attributes and configuration, request and response objects. Returns The current ColdFusion MX Java PageContext Java object. Category System functions Function syntax GetPageContext() History ColdFusion MX: Added this function. Usage The ColdFusion MX PageContext class is a wrapper class for the Java PageContext object that can resolve scopes and perform case-insensitive variable lookups. The PageContext object exposes fields and methods that can be useful in J2EE integration. It includes the include and forward methods that provide the equivalent of the corresponding standard JSP tags. You use these methods to call JSP pages and servlets. For example, you use the following code in CFScript to include the JSP page hello.jsp and pass it a name parameter: GetPageContext().include("hello.jsp?name=Bobby"); === For more information, see your Java Server Pages (JSP) documentation). Example name: #variables.name#
Language of the current locale is #pc.getRequest().getLocale().getDisplayLanguage()#>. GetPageContext 501 GetProfileSections Description Gets all the sections of an initialization file. An initialization file assigns values to configuration variables, also known as entries, that are set when the system boots, the operating system comes up, or an application starts. An initialization file has the suffix INI; for example, boot.ini, Win32.ini. Returns An initialization file, as a struct whose format is as follows: • Each initialization file section name is a key in the struct • Each list of entries in a section of an initialization file is a value in the struct If there is no value, returns an empty string. Category System functions Function syntax GetProfileSections(iniFile) See also GetProfileString, SetProfileString History ColdFusion MX: Added this function. Parameters Parameter Description iniFile 502 Absolute path (drive, directory, filename, extension) of initialization file; for example, C:\boot.ini Chapter 3: ColdFusion Functions GetProfileString Description Gets an initialization file entry. An initialization file assigns values to configuration variables, also known as entries, that are set when the system boots, the operating system comes up, or an application starts. An initialization file has the suffix INI; for example, boot.ini, Win32.ini. Returns An entry in an initialization file, as a string. If there is no value, returns an empty string. Category System functions Function syntax GetProfileString(iniPath, section, entry) See also GetProfileSections, GetProfileString, SetProfileString Parameters Parameter Description iniPath Absolute path (drive, directory, filename, extension) of initialization file; for example, C:\boot.ini section Section of initialization file from which to extract information entry Name of value to get Example

GetProfileString Example

Uses GetProfileString to get the value of timeout in an initialization file. Enter the full path of your initialization file, and submit the form.

Boot Loader

Timeout is set to: #timeout#.

GetProfileString 503
Full Path of Init File
504 Chapter 3: ColdFusion Functions GetTempDirectory Description Gets the path of the directory that ColdFusion uses for temporary files. The directory depends on the account under which ColdFusion is running and other factors. Before using this function in an application, test to determine the directory it returns under your account. Returns The absolute pathname of a directory, including a trailing slash, as a string. Category System functions Function syntax GetTempDirectory() See also GetTempFile History ColdFusion MX: Changed behavior: on Windows, this function now returns the temporary directory of the embedded Java application server. On other platforms, it returns the temporary directory of the operating system. Example

GetTempDirectory Example

The temporary directory for this ColdFusion server is #GetTempDirectory()#.

We have created a temporary file called: #GetTempFile(GetTempDirectory(),"testFile")# GetTempDirectory 505 GetTempFile Description Creates a temporary file in a directory whose name starts with (at most) the first three characters of prefix. Returns Name of a temporary file, as a string. Category System functions Function syntax GetTempFile(dir, prefix) See also GetTempDirectory Parameters Parameter Description dir Directory name prefix Prefix of a temporary file to create in the directory dir Example

GetTempFile Example

The temporary directory for this ColdFusion Server is #GetTempDirectory()#.

We have created a temporary file called: #GetTempFile(GetTempDirectory(),"testFile")# 506 Chapter 3: ColdFusion Functions GetTemplatePath Description This function is deprecated. Use the GetBaseTemplatePath function instead. Gets the absolute path of an application’s base page. History ColdFusion MX: Deprecated this function. It might not work, and it might cause an error, in later releases. GetTemplatePath 507 GetTickCount Description Returns the current value of an internal millisecond timer. Returns A string representation of the system time, in milliseconds. Category Date and time functions Function syntax GetTickCount() Usage This function is useful for timing CFML code segments or other page processing elements. The value of the counter has no meaning. To generate useful timing values, take the difference between the results of two GetTickCount calls. Example Loop time (#iterationCount# iterations) was: #loopTime# milliseconds 508 Chapter 3: ColdFusion Functions GetTimeZoneInfo Description Gets local time zone information for the computer on which it is called, relative to Universal Time Coordinated (UTC). UTC is the mean solar time of the meridian of Greenwich, England, used as the basis for calculating standard time throughout the world. ColdFusion stores date and time values as date-time objects: real numbers on a universal time line. It converts an object to a time zone when it formats an object; it converts a date/time value from a time zone to a real number when it parses a value. Returns Structure that contains these elements and keys: • utcTotalOffset: offset of local time, in seconds, from UTC A plus sign indicates a time zone west of UTC (such as a zone in North America) A minus sign indicates a time zone east of UTC (such as a zone in Germany) utcHourOffset: offset, in hours of local time, from UTC utcMinuteOffset: offset, in minutes, beyond the hours offset. For North America, this is 0. For countries that are not exactly on the hour offset, the number is between 0 and 60. For example, standard time in Adelaide, Australia is offset 9 hours and 30 minutes from UTC. isDSTOn: True, if Daylight Savings Time (DST) is on in the host; False, otherwise ■ ■ • • • Category Date and time functions, International functions Function syntax GetTimeZoneInfo() See also DateConvert, CreateDateTime, DatePart Example

GetTimeZoneInfo Example

The local date and time are #now()#.

Total offset in seconds is #info.utcTotalOffset#.

Offset in hours is #info.utcHourOffset#.

Offset in minutes minus the offset in hours is #info.utcMinuteOffset#.

Is Daylight Savings Time in effect? #info.isDSTOn#.

GetTimeZoneInfo 509 GetToken Description Determines whether a token of the list in the delimiters parameter is present in a string. Returns The token found at position index of the string, as a string. If index is greater than the number of tokens in the string, returns an empty string. Category String functions Function syntax GetToken(string, index [, delimiters ]) See also Left, Right, Mid, SpanExcluding, SpanIncluding Parameters Parameter Description string A string or a variable that contains one. String in which to search. index Positive integer or a variable that contains one. The position of a token. delimiters A string or a variable that contains one. A delimited list of delimiters. Elements may consist of multiple characters. Default list of delimiters: space character, tab character, newline character; or their codes: "chr(32)", "chr(9)", chr(10). Default list delimiter: comma character. Usage The following examples show how this function works. Example A: Consider the following code: GetToken("red,blue:;red,black,tan:;red,pink,brown:;red,three", 2, ":;") This function call requests element number 2 from the string, using the delimiter ":;". The output is as follows: red,black,tan Example B: Consider the following code: #mystring#

510 Chapter 3: ColdFusion Functions The output is as follows: four, ,five, nine,zero:; nine,ten:, eleven:;twelve:;thirteen, ,four The GetToken function recognizes explicit spaces, tabs, or newline characters as the parameter delimiters (To specify a space character, the code is chr(32); a tab character, chr(9); and a newline character, chr(10).) In the example string mystring, there is: • • • • A forced space between the substrings "four," and ",five" A literal space between "five," and "nine" A literal space between "ten:," and "eleven," A forced space between "thirteen," and ",four" In the following call against mystring, no spaces are specified in delimiters (it is omitted), so the function uses the space character as the string delimiter:
GetToken(mystring, 3) is : #GetToken(mystring, 3)#
The output of this code is as follows: GetToken(mystring, 3) is : nine,zero:; The function finds the third delimiter, and returns the substring just before it that is between the second and third delimiter. This substring is "nine,zero:;". Example C: Consider the following code: #mystring2#
The output is as follows: four, ,five,nine,zero:; nine,ten:,eleven:;twelve:;thirteen, ,four The following is a call against mystring2: GetToken(mystring2, 2) is : #GetToken(mystring2, 2)# The output is as follows: GetToken(mystring2, 2) is : ,five,nine,zero:; GetToken 511 The function finds the second delimiter, and returns the substring just before it that is between the first and second delimiter. This substring is ",five,nine,zero:;". Example

GetToken Example

Element #FORM.ReturnElement# in #FORM.yourString#, delimited by "#yourDelimiter#"
is:#GetToken(FORM.yourString, FORM.returnElement, yourDelimiter)# ... 512 Chapter 3: ColdFusion Functions Hash Description Converts a variable-length string to a 32-byte, hexadecimal string, using the MD5 algorithm. (It is not possible to convert the hash result back to the source string.) Returns 32-byte, hexadecimal string Category Conversion functions, Other functions, String functions Function syntax Hash(string) Parameters Parameter Description string A string or a variable that contains one. Usage The result is useful for comparison and validation. For example, a developer can store the hash of a password in a database without exposing the password. The developer can check the validity of the password with the following code: Example

Hash Example

SELECT PasswordHash FROM SecureData WHERE UserID = ... Hash 513 Hour Description Gets the current hour of the day. Returns Ordinal value of the hour, in the range 0 - 23. Category Date and time functions Function syntax Hour(date) See also DatePart, Minute, Second Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

Hour Example

The time is currently #TimeFormat(Now())#. We are in hour #Hour(Now())#, Minute #Minute(Now())# and Second #Second(Now())# of the day. 514 Chapter 3: ColdFusion Functions HTMLCodeFormat Description Replaces special characters in a string with their HTML-escaped equivalents and inserts
and 
tags at the beginning and end of the string. Returns HTML-escaped string string, enclosed in
 and 
tags. Returns are removed from string. Special characters (> < " &) are escaped. Category Display and formatting functions Function syntax HTMLCodeFormat(string [, version ]) See also HTMLEditFormat Parameters Parameter Description string A string or a variable that contains one. version HTML version to use: currently ignored. • -1: The latest implementation of HTML • 2.0: HTML 2.0 (Default) • 3.2: HTML 3.2 Usage This function typically increases the length of a string. This can cause unpredictable results when performing certain string functions (Left, Right, and Mid, for example) against the expanded string. The only difference between this function and HTMLEditFormat is that HTMLEditFormat does not surround the text in an HTML pre tag. Example

The text without processing

#testString#

Using HTMLCodeFormat

#HTMLCodeFormat(testString)#

Using HTMLEditFormat

#HTMLEditFormat(testString)#
HTMLCodeFormat 515 HTMLEditFormat Description Replaces special characters in a string with their HTML-escaped equivalents. Returns HTML-escaped string string. Returns are removed from string. Special characters (for example, < " &) are escaped. Category Display and formatting functions Function syntax HTMLEditFormat(string [, version ]) See also HTMLCodeFormat Parameters Parameter Description string A string or a variable that contains one. version HTML version to use. currently ignored. • -1: The latest implementation of HTML • 2.0: HTML 2.0 (Default) • 3.2: HTML 3.2 Usage This function typically increases the length of a string. This can cause unpredictable results when performing certain string functions (Left, Right, and Mid, for example) against the expanded string. The only difference between this function and HTMLCodeFormat is that HTMLCodeFormat surrounds the text in an HTML pre tag. Example

The text without processing

#testString#

Using HTMLCodeFormat

#HTMLCodeFormat(testString)#

Using HTMLEditFormat

#HTMLEditFormat(testString)#
516 Chapter 3: ColdFusion Functions IIf Description Evaluates a Boolean conditional dynamic expression. Depending on whether the expression is true or false, dynamically evaluates one of two string expressions and returns the result. This function is convenient for incorporating a cfif tag in-line in HTML. For general conditional processing, see cfif. For error handling, see cftry. For more information, see Developing ColdFusion MX Applications. Returns If result is True, returns the value of Evaluate(string_expression1); otherwise, returns the value of Evaluate(string_expression2). Category Decision functions, Dynamic evaluation functions Function syntax IIf(condition, string_expression1, string_expression2) See also DE, Evaluate Parameters Parameter Description condition An expression that can be evaluated as a Boolean. string_expression1 A string or a variable that contains one. Expression to evaluate and return if condition is True. string_expression2 A string or a variable that contains one. Expression to evaluate and return if condition is False. Usage The IIf function is a shortcut for the following construct: The expressions string_expression1 and string_expression2 must be string expressions, so that they are not evaluated immediately as the parameters of IIf. For example: IIf(y is 0, DE("Error"), x/y) If y = 0, this generates an error, because the third expression is the value of x/0 (invalid expression). ColdFusion evaluates string_expression1 and string_expression2. To return the string itself, use the function. DE IIf 517 Note: If you use pound signs (#) in string_expression1 or string_expression2, ColdFusion evaluates the part of the expression in pound signs first. If you misuse the pound signs, you can cause unexpected results from the IIf function. For example, if you use pound signs around the whole expression in string_expression1, and if there is an undefined variable in string_expression1, the function might fail, with the error 'Error Resolving Parameter,' If a variable is undefined, ColdFusion throws an error when it processes this function. The following example shows this problem: #IIf(IsDefined("Form.Deliver"), DE(Form.Deliver), DE("no"))# This returns "Error resolving parameter FORM.DELIVER". To avoid this problem, use the DE and Evaluate functions in code such as the following: #IIf(IsDefined("Form.Deliver"), Evaluate(DE("Form.Deliver")), DE("no"))# This returns "no"; ColdFusion does not throw an error. In the following example, LocalVar is undefined; however, if you omit pound signs around LocalVar, the code works properly: #IIf(IsDefined("LocalVar"), "LocalVar", DE("The variable is not defined."))# The output is: The variable is not defined. The pound signs around LocalVar in the following code cause it to fail with the error message 'Error Resolving Parameter', because ColdFusion never evaluates the original condition IsDefined("LocalVar"). Here is another example: #IIf(IsDefined("LocalVar"), DE("#LocalVar#"), DE("The variable is not defined."))# The error message would be as follows: Error resolving parameter LOCALVAR The DE function has no effect on the evaluation of LocalVar, because the pound signs cause it to be evaluated immediately. Example

IIf Function Example

IIf evaluates a condition, and does an Evaluate on string expression 1 or string expression 2 depending on the Boolean outcome (True: run expression 1; False: run expression 2).

The result of the expression IIf( Hour(Now()) GTE 12, DE("It is afternoon or evening"), DE("It is morning")) is:
#IIf( Hour(Now()) GTE 12, DE("It is afternoon or evening"), DE("It is morning"))# 518 Chapter 3: ColdFusion Functions IIf 519 IncrementValue Description Adds one to an integer. Returns The integer part of number, incremented by one. Category Mathematical functions Function syntax IncrementValue(number) See also DecrementValue Parameters Parameter Description number Number to increment Example

IncrementValue Example

Returns the integer part of a number incremented by one.

IncrementValue(0): #IncrementValue(0)#

IncrementValue("1"): #IncrementValue("1")#

IncrementValue(123.35): #IncrementValue(123.35)# 520 Chapter 3: ColdFusion Functions InputBaseN Description Converts string, using the base specified by radix, to an integer. Returns A number in the range 2-36, as a string. Category Mathematical functions Function syntax InputBaseN(string, radix) See also FormatBaseN Parameters Parameter Description string A string or a variable that contains one. String that represents a number, in the base specified by radix. radix Base of the number represented by string, in the range 2 — 36. Example

InputBaseN Example

FormatBaseN converts a number to a string in the base specified by Radix.


FormatBaseN(10,2): #FormatBaseN(10,2)#
FormatBaseN(1024,16): #FormatBaseN(1024,16)#
FormatBaseN(125,10): #FormatBaseN(125,10)#
FormatBaseN(10.75,2): #FormatBaseN(10.75,2)#

InputBaseN Example

InputBaseN returns the number obtained by converting a string, using the base specified by Radix,.
InputBaseN("1010",2): #InputBaseN("1010",2)#
InputBaseN("3ff",16): #InputBaseN("3ff",16)#
InputBaseN("125",10): #InputBaseN("125",10)#
InputBaseN(1010,2): #InputBaseN(1010,2)#
InputBaseN 521 Insert Description Inserts a substring in a string after a specified character position. If position = 0, prefixes the substring to the string. Returns A string. Category String functions Function syntax Insert(substring, string, position) See also RemoveChars, Len Parameters Parameter Description substring A string or a variable that contains one. String to insert. string A string or a variable that contains one. String into which to insert substring. position Integer or variable; position in string after which to insert substring. Example

Insert Example

This string only has #Len(MyString)# characters; therefore, you cannot insert the substring #FORM.mySubString# at position #FORM.insertPosition#.

You inserted the substring #FORM.MySubstring# into the string #FORM.MyString#, resulting in the following string:
#Insert(FORM.MySubString, FORM.myString, FORM.insertposition)# 522 Chapter 3: ColdFusion Functions Int Description Calculates the closest integer that is smaller than number. Returns An integer, as a string. Category Mathematical functions Function syntax Int(number) See also Ceiling, Fix, Round Parameters Parameter Description number Real number to round down to an integer Example

Int Example

Int returns the closest integer smaller than a number.

Int(11.7) : #Int(11.7)#

Int(-11.7) : #Int(-11.7)#

Int(0) : #Int(0)# Int 523 IsArray Description Determines whether a value is an array. Returns True, if value is an array, or a query column object. Category Array functions, Decision functions Function syntax IsArray(value [, number ]) See also Array functions History ColdFusion MX: • Changed behavior: if the value attribute contains a reference to a query result column, this • function now returns True. For example: isArray(MyQuery[’Column1’]) returns True. (In earlier releases, it returns False.) Changed behavior: this function can be used on XML objects. Parameters Parameter Description value Variable or array name number Dimension; function tests whether the array has exactly this dimension Usage This function evaluates a Java array object, such as vector object, as having one dimension. Example

IsArray Example

Is this an array? #IsArray(MyNewArray)#

It has #ArrayLen(MyNewArray)# elements.

Contents: #ArrayToList(MyNewArray)# 524 Chapter 3: ColdFusion Functions IsAuthenticated Description This function 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 function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases. IsAuthenticated 525 IsAuthorized Description This function 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 function is obsolete. It does not work in ColdFusion MX and later releases. 526 Chapter 3: ColdFusion Functions IsBinary Description Determines whether a value is stored as binary data. Returns True, if the value is binary; False, otherwise. Category Decision functions Function syntax IsBinary(value) See also ToBinary, ToBase64, IsNumeric, YesNoFormat Parameters Parameter Description value Number or string Example The following string is the concatenation of all characters (32 to 255) from the ASCII table.

#htmleditformat(charData)#

The binaryData variable is binary!
The another64 variable is NOT binary!
Base 64 representation of binary data is identical to the Base 64 representation of string data.

Conversion error.

IsBinary 527 IsBoolean Description Determines whether a value can be converted to Boolean Returns True, if the parameter can be converted to Boolean; False, otherwise. Category Decision functions Function syntax IsBoolean(value) See also IsNumeric, YesNoFormat Parameters Parameter Description value Number or string Example

IsBoolean Example

The expression #DE(FORM.theTestValue)# is Boolean

The expression #DE(FORM.theTestValue)# is not Boolean

Enter an expression, and discover whether it can be evaluated to a Boolean value.

528 Chapter 3: ColdFusion Functions IsCustomFunction Description Determines whether a name represents a custom function. Returns True, if name can be called as a custom function; False, otherwise. Category Decision functions Function syntax IsCustomFunction(name) Parameters Parameter Description name Name of a custom function. Must not be in quotes. If not a defined variable or function name, ColdFusion generates an error. Usage The IsCustomFunction function returns true for any function that can be called as a custom function, including functions defined using CFScript function declarations and cffunction tags, and functions that are ColdFusion component methods. For CFC methods, you must first instantiate the component. Note: To prevent undefined variable exceptions, always precede IsCustomFunction with an IsDefined test, as shown in the example. Example

IsCustomFunction Example

function realUDF() { return 1; } Foo is a UDF.
X is a UDF.
realUDF is a function.
myTestCFCobject.testFunc is a function. 530 Chapter 3: ColdFusion Functions IsDate Description Determines whether a string or Java object can be converted to a date/time value. Returns True, if string can be converted to a date/time value; otherwise, False. ColdFusion converts the Boolean return value to its string equivalent, "Yes" or "No." Category Date and time functions, Decision functions Function syntax IsDate(string) See also CreateDateTime, IsNumericDate, LSDateFormat, LSIsDate, ParseDateTime Parameters Parameter Description string A string or a variable that contains one. Usage This function checks against U.S. date formats only. For other date support, see LSDateFormat. A date/time object falls in the range 100 AD–9999 AD. Example

IsDate Example

The string #DE(FORM.theTestValue)# is a valid date

The string #DE(FORM.theTestValue)# is not a valid date

Enter a string, find whether it can be evaluated to a date value.

IsDate 531 IsDebugMode Description Determines whether debugging output is enabled. Returns True, if debugging mode is set in the ColdFusion Administrator; False if debugging mode is disabled. Category Decision functions Function syntax IsDebugMode() See also cfsetting Description If debugging output is enabled in ColdFusion Administrator and has not been overridden by setting the cfsetting tag showDebugOutput attribute to No, the IsDebugMode function returns Yes; otherwise, No. Example

IsDebugMode Example

Debugging is set in the ColdFusion Administrator

Debugging is disabled

532 Chapter 3: ColdFusion Functions IsDefined Description Evaluates a string value to determine whether the variable named in it exists. This function is an alternative to the ParameterExists function, which is deprecated. Returns True, if the variable is found, or, for a structure, if the specified key is defined; False, otherwise. Returns False for an array or structure element referenced using bracket notation. For example, IsDefined("myArray[3]") always returns False, even if the array element myArray[3] has a value. Category Decision functions Function syntax IsDefined("variable_name") See also Evaluate History ColdFusion MX: Changed behavior: this function can process only the following constructs: • a simple variable • a named variable with dot notation • a named structure with dot notation (for example: mystruct.key) Parameters Parameter Description variable_name String, enclosed in quotation marks. Name of variable to test for. Usage When working with scopes that ColdFusion exposes as structures, the StructKeyExists function can sometimes replace this function. The following lines are equivalent: if(isDefined("form.myVariable")) if(structKeyExists(form,"myVariable")) Example

The variable form.myString has been defined, so show its contents. This construction allows us to place a form and its resulting action code on the same page and use IsDefined to control the flow of execution.

The value of "form.myString" is #form.myString#

During the first time through this template, the variable "form.myString" has not yet been defined, so we do not try to evaluate it.

IsDefined 533
534 Chapter 3: ColdFusion Functions IsK2ServerABroker Description This function is deprecated. Determines whether the K2Server version is K2 Broker. For more information, see GetK2ServerDocCountLimit on page 495. This function is used primarily by the ColdFusion Verity and K2Server Administrator pages. This function uses Verity K2Server Release K2.2.0. Returns True, if K2Broker is in configured with ColdFusion; False, otherwise. Category Decision functions, Full-text search functions, Query functions Function syntax IsK2ServerABroker() See also GetK2ServerDocCountLimit, IsK2ServerDocCountExceeded, IsK2ServerOnline History ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases. ColdFusion MX: Added this function. Example IsK2ServerABroker = $*#IsK2ServerABroker()#*$ IsK2ServerABroker 535 IsK2ServerDocCountExceeded Description This function is deprecated. Determines whether the number of documents that can be searched by the ColdFusion registered K2 Server exceed the limit. Depends on the K2Server platform limit; see GetK2ServerDocCountLimit on page 495. This function is used primarily by the ColdFusion Verity and K2Server Administrator pages. This function uses Verity K2Server Release K2.2.0. Returns True, if the document count limit is exceeded; False, otherwise. Category Decision functions, Full-text search functions, Query functions Function syntax IsK2ServerDocCountExceeded() See also GetK2ServerDocCountLimit, IsK2ServerABroker History ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases. ColdFusion 5: Added this function. Example IsK2ServerDocCountExceeded = $*#IsK2ServerDocCountExceeded()#*$ 536 Chapter 3: ColdFusion Functions IsK2ServerOnline Description This function is deprecated. Determines whether the K2Server is running and available to perform a search. This function is used primarily by the ColdFusion Verity and K2Server Administrator pages. This function uses Verity K2Server Release K2.2.0. Returns True, if the K2Server is available to perform a search; False, otherwise. Category Decision functions, Full-text search functions, Query functions Function syntax IsK2ServerOnline() See also IsK2ServerABroker History ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases. ColdFusion MX: Added this function. Example IsK2ServerOnline = $*#IsK2ServerOnline()#*$ IsK2ServerOnline 537 IsLeapYear Description Determines whether a year is a leap year. Returns True, if year is a leap year; otherwise, False. Category Date and time functions, Decision functions Function syntax IsLeapYear(year) See also DaysInYear Parameters Parameter Description year Number representing a year Example

IsLeapYear Example

The year value #DE(FORM.theTestValue)# is a Leap Year

The year value #DE(FORM.theTestValue)# is not a Leap Year

Enter a year value, and find out whether it is a Leap Year.

538 Chapter 3: ColdFusion Functions IsNumeric Description Determines whether a string can be converted to a numeric value. Supports numbers in U.S. number format. For other number support, use LSIsNumeric. Returns True, if string can be converted to a number; otherwise, False. Category Decision functions Function syntax IsNumeric(string) See also IsBinary Parameters Parameter Description string A string or a variable that contains one. Example

IsNumeric Example

The string #DE(FORM.theTestValue)# can be converted to a number

The string #DE(FORM.theTestValue)# cannot be converted to a number

Enter a string, and find out whether it can be evaluated to a numeric value.

IsNumeric 539 IsNumericDate Description Evaluates whether a real number is a valid representation of a date (date/time object). Returns True, if the parameter represents a valid date/time object; otherwise, False. Category Date and time functions, Decision functions Function syntax IsNumericDate(number) See also IsDate, ParseDateTime Parameters Parameter Description number A real number Usage ColdFusion, by default, evaluates any input parameter and attempts to convert it to a real number before it passes the parameter to the IsNumericDate function. As a result, parameter values such as 12/12/03 and {ts '2003-01-14 10:04:13'} return True, because ColdFusion converts valid date string formats to date/time objects, which are real numbers. Example

IsNumericDate Example

The string #DE(form.theTestValue)# can be converted to a valid numeric date

The string #DE(form.theTestValue)# can not be converted to a valid numeric date

The string #DE(form.theTestValue)# is not a valid numeric date

Enter a value, and discover if it can be evaluated to a date value.

540 Chapter 3: ColdFusion Functions IsObject Description Determines whether a value is an object. Returns True, if the value represents a ColdFusion object. False if the value is any other type of data, such as an integer, string, date, or struct. Category Decision functions Function syntax IsObject(value) See also IsDate, IsNumeric, IsNumericDate, IsQuery, IsSimpleValue, IsStruct, IsWDDX, IsXmlDoc, IsXmlElem, IsXmlRoot History ColdFusion MX: Added this function. Parameters Parameter Description value A value, typically the name of a variable. Usage This function returns False for query and XML objects. Example ---> The value of myColor = #myColor#

IsObject 541 542 Chapter 3: ColdFusion Functions IsProtected Description This function 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 function is obsolete. It does not work in ColdFusion MX and later releases. IsProtected 543 IsQuery Description Determines whether value is a query. Returns True, if value is a query. Category Decision functions, Query functions Function syntax IsQuery(value) See also QueryAddRow Parameters Parameter Description value Query variable Example

IsQuery Example

Before the query is run, the value of GetEmployees is #GetEmployees#

GetEmployees is currently a simple value SELECT * FROM employees

After the query is run, GetEmployees contains a number of rows that look like this (display limited to three rows):

#Emp_ID# #FirstName# #LastName#
GetEmployees is no longer a simple value, but the name of a query 544 Chapter 3: ColdFusion Functions IsSimpleValue Description Determines the type of a value. Returns True, if value is a string, number, Boolean, or date/time value; False, otherwise. Category Decision functions Function syntax IsSimpleValue(value) Parameters Parameter Description value Variable or expression Example

IsSimpleValue Example

Before the query is run, the value of GetEmployees is #GetEmployees#

GetEmployees is currently a simple value SELECT * FROM employees

After the query is run, GetEmployees contains a number of rows that look like this (display limited to three rows):

#Emp_ID# #FirstName# #LastName#
GetEmployees is no longer a simple value, but the name of a query IsSimpleValue 545 IsStruct Description Determines whether a variable is a structure. Returns True, if variable is a ColdFusion structure or is a Java object that implements the java.lang.Map interface. Returns False if the object in variable is a user-defined function (UDF). Category Decision functions, Structure functions Function syntax IsStruct(variable) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description variable Variable name Example

This file is similar to addemployee.cfm, which is called by StructNew, StructClear, and StructDelete. It is an example of a custom tag used to add employees. Employee information is passed through the employee structure (the EMPINFO attribute). In UNIX, you must also add the Emp_ID. IsStruct 547 IsUserInRole Description Determines whether an authenticated user belongs to the specified Role. Returns True, if the authenticated user, belongs to the specified Role; False, otherwise. Category Authentication functions, Decision functions Function syntax IsUserInRole("role_name") See also GetAuthUser, cflogin, cfloginuser, Chapter 16, “Securing Applications,” in Developing ColdFusion MX Applications History ColdFusion MX: Added this function. Parameters Parameter Description role_name Name of a security role Usage Role names are case-sensitive. To check if a user is in multiple roles, specify them in a comma delimited list, such as "Admin,HR". Lists with multiple roles cannot contain spaces as separators; for example, do not use "Admin, HR". Example Authenticated user is an administrator Authenticated user is a user 548 Chapter 3: ColdFusion Functions IsWDDX Description Determines whether a value is a well-formed WDDX packet. Returns True, if the value is a well-formed WDDX packet; False, otherwise. Category Decision functions, XML functions Syntax IsWDDX(value) History ColdFusion MX: Changed behavior: if the value parameter is not a WDDX packet, ColdFusion returns False. (In earlier releases, ColdFusion threw an error.) Parameters Parameter Description value A WDDX packet Usage This function processes a WDDX packet with a validating XML parser, which uses the WDDX Document Type Definition (DTD). To prevent CFWDDX deserialization errors, you can use this function to validate WDDX packets from unknown sources. Example


<cfoutput>#packet# IsWDDX 549 IsWDDX() returns #IsWDDX(packet)#
550 Chapter 3: ColdFusion Functions IsXmlDoc Description Determines whether a function parameter is an Extended Markup language (XML) document object. Returns True, if the function argument is an XML document object; False, otherwise. Category Decision functions, XML functions Function syntax IsXmlDoc(value) See also IsXmlElem, IsXmlRoot, XmlChildPos, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description value name of an XML document object IsXmlDoc 551 IsXmlElem Description Determines whether a function parameter is an Extended Markup language (XML) document object element. Returns True, if the function argument is an XML document object element; False, otherwise. Category Decision functions, XML functions Function syntax IsXmlElem(value) See also IsXmlDoc, IsXmlRoot, XmlChildPos, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters 552 Parameter Description value name of an XML document object element Chapter 3: ColdFusion Functions IsXmlRoot Description Determines whether a function parameter is the root element of an Extended Markup language (XML) document object. Returns True, if the function argument is the root object of an XML document object; False, otherwise. Category Decision functions, XML functions Function syntax IsXmlRoot(value) See also IsXmlDoc, IsXmlElem, XmlChildPos, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description value name of an XML document object IsXmlRoot 553 JavaCast Description Converts the data type of a ColdFusion variable to pass as an argument to an overloaded method of a Java object. Use only for scalar and string arguments. Returns The variable, as type type. Category String functions Function syntax JavaCast(type, variable) See also CreateObject, cfobject Parameters Parameter Description type Data type to which to convert variable: • boolean • int • long • float • double • string variable A ColdFusion variable that holds a scalar or string type Usage Use after creating a Java object with the cfobject tag, before calling one of its methods. If the method takes more than one overloaded argument, you must call JavaCast for each one. Use JavaCast only when a method is overloaded (because its arguments can take more than one data type, not because the method can take a variable number of arguments). cannot be used to cast between complex objects, nor to cast to a super-class. Use this function’s result only on calls to Java objects. Because there is not a one-to-one correspondence between internally stored ColdFusion types and Java scalar types, some conversions cannot be performed. JavaCast Example The method fooMethod in the class fooClass takes one overloaded argument. The fooClass class is defined as follows: public class fooClass { public fooClass () { } public String fooMethod(String arg) { return "Argument was a String"; } public String fooMethod(int arg) { return "Argument was an Integer"; } 554 Chapter 3: ColdFusion Functions } Within ColdFusion, you use the following code: Perform an explicit cast to an int and call fooMethod:
#obj.fooMethod(myInt)#

Perform an explicit cast to a string and call fooMethod:
#obj.fooMethod(myString)# JavaCast 555 JSStringFormat Description Escapes special JavaScript characters, such as single quotation mark, double quotation mark, and newline. Returns A string that is safe to use with JavaScript. Category String functions Function syntax JSStringFormat(string) Parameters Parameter Description string A string or a variable that contains one. Usage Escapes special JavaScript characters, so you can put arbitrary strings safely into JavaScript. Example

JSStringFormat

This is the string we have created:
#stringValue#

556 Chapter 3: ColdFusion Functions LCase Description Converts the alphabetic characters in a string to lowercase. Returns A string, converted to lowercase. Category String functions Function syntax LCase(string) See also UCase Parameters Parameter Description string A string or a variable that contains one Example

LCase Example

Your text, #FORM.sampleText#, returned in lowercase is #LCase(FORM.sampleText)# .

Please enter some text.

Enter your text. Press "submit" to see it returned in lowercase:

LCase 557 Left Description Returns the leftmost count characters in a string. Returns String; the first count characters in the string parameter. Category String functions Function syntax Left(string, count) See also Right, Mid, Len Parameters Parameter Description string A string or a variable that contains one. count A positive integer or a variable that contains one. Number of characters to return. Example

Left Example

Your string #form.myText# only has #Len(form.myText)# characters. You cannot output the #form.removeChars# leftmost characters of this string because it is not long enough

Your original string: #form.myText#

Your changed string, showing only the #form.removeChars# leftmost characters: #Left(Form.myText, form.removeChars)#

Please enter a string

Type in some text

How many characters from the left do you want to show?

Left 559 Len Description Determines the length of a string or binary object. Returns Number; length of a string or a binary object. Category String functions Function syntax Len(string or binary object) See also ToBinary, Left, Right, Mid History ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535. (ColdFusion 5 and earlier releases supported ASCII values 1–255. When calculating a length, some string-processing functions processed the ASCII 0 (NUL) character, but did not process subsequent characters of the string.) Parameters Parameter Description string A string, the name of a string, or a binary object Example

Len Example

Your string, "#FORM.myText#", has #Len(FORM.myText)# characters.

Please enter a string of more than 0 characters.

Type in some text to see the length of your string.

560 Chapter 3: ColdFusion Functions ListAppend Description Concatenates a list or element to a list. Returns A copy of the list, with value appended. If delimiter = "", returns a copy of the list, unchanged. Category List functions Function syntax ListAppend(list, value [, delimiters ]) See also ListPrepend, ListInsertAt, ListGetAt, ListLast, ListSetAt Parameters Parameter Description list A list or a variable that contains one. value An element or a list of elements. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion uses only the first character. Usage ColdFusion inserts a delimiter character before value. To add an element to the beginning or end of a list, Macromedia recommends that you do so with code such as the following, rather than with the ListAppend or ListPrepend functions: The following table shows examples of ListAppend processing: Statement Output Comment ListAppend('elem1,elem2', '' ) elem1,elem2, Appended element is empty; delimiter is last character in list; list length is 2 ListAppend('', 'elem1,elem2' ) elem1,elem2 List length is 2 ListAppend ("one___two", "three", "___") "one___two_three" Inserted the first character of delimiters before "three." Example

ListAppend Example

ListAppend 561 SELECT PARKNAME,CITY,STATE FROM PARKS WHERE PARKNAME LIKE ‘AL%’

The original list: #temp# ... 562 Chapter 3: ColdFusion Functions ListChangeDelims Description Changes a list delimiter. Returns A copy of the list, with each delimiter character replaced by new_delimiter. Category List functions Function syntax ListChangeDelims(list, new_delimiter [, delimiters ]) See also ListFirst, ListQualify Parameters Parameter Description list A list or a variable that contains one. new_delimiter Delimiter string or a variable that contains one. Can be an empty string. ColdFusion processes the string as one delimiter. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Example

ListChangeDelims Example

ListChangeDelims lets you change the delimiters of a list. SELECT PARKNAME,CITY,STATE FROM Parks WHERE PARKNAME LIKE 'BA%'

The original list:

#temp#

After executing the statement ListChangeDelims(Temp, "|:P|", ","), the updated list:

#temp2# ListChangeDelims 563 ListContains Description Determines the index of the first list element that contains a specified substring. Returns Index of the first list element that contains substring. If not found, returns zero. Category List functions Function syntax ListContains(list, substring [, delimiters ]) See also ListContainsNoCase, ListFind Parameters Parameter Description list A list or a variable that contains one. substring A string or a variable that contains one. The search is case-sensitive. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

Here is a list: #aList#

ListContains checks for substring "wo" in the list elements:

   Substring "wo" is in element #ListContains(aList, "wo")# of list.

ListFind cannot check for a substring within an element; therefore, in the code, it does not find substring "wo" (it returns 0):

   Substring "wo" is in element #ListFind(aList, "wo")# of the list.

If you specify a string that exactly equals an entire list element, such as "two", both ListContains and ListFind find it, in the second element:

   ListContains: The string "two" is in element #ListContains(aList, "two")# of the list.    

ListFind: 564 Chapter 3: ColdFusion Functions The string "two" is in element #ListFind(aList, "two")# of the list. ListContains 565 ListContainsNoCase Description Determines the index of the first list element that contains a specified substring. Returns Index of the first list element that contains substring, regardless of case. If not found, returns zero. Category List functions Function syntax ListContainsNoCase(list, substring [, delimiters ]) See also ListContains, ListFindNoCase Parameters Parameter Description list A list or a variable that contains one. substring A string or a variable that contains one. The search is case-insensitive. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListContainsNoCase Example

SELECT PARKNAME,CITY,STATE FROM Parks WHERE PARKNAME LIKE '#form.letter#%' There are parks in your city!

Sorry, there were no parks found for your city. Try searching under a different letter. 566 Chapter 3: ColdFusion Functions ListDeleteAt Description Deletes an element from a list. Returns A copy of the list, without the specified element. Category List functions Function syntax ListDeleteAt(list, position [, delimiters ]) See also ListGetAt, ListSetAt, ListLen Parameters Parameter Description list A list or a variable that contains one. position A positive integer or a variable that contains one. Position at which to delete element. The first list position is 1. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage To use this and other functions with the default delimiter (comma), you can code as follows: To specify another delimiter, you code as follows: ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example SELECT PARKNAME,CITY,STATE FROM Parks WHERE PARKNAME LIKE 'CHI%'

The original list: #temp# ListDeleteAt 567

The changed list: #temp2#

This list element:
#deleted_element#
is no longer present at position three of the list.
568 Chapter 3: ColdFusion Functions ListFind Description Determines the index of the first list element in which a specified value occurs. Case-sensitive. Returns Index of the first list element that contains value, with matching case. If not found, returns zero. The search is case-sensitive. Category List functions Function syntax ListFind(list, value [, delimiters ]) See also ListContains, ListFindNoCase Parameters Parameter Description list A list or a variable that contains one value A string, a number, or a variable that contains one. Item for which to search. The search is case-sensitive. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

Try changing the case in Leary's last name:

Pick a search type:

SELECT FirstName, RTrim(LastName) AS LName, Phone, Department FROM Employees ListFind 569

An employee with that exact last name was not found

Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)# #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the #ListGetAt(ValueList(SearchEmpLastName.Department), temp)# Department, can be reached at #ListGetAt(ValueList(SearchEmpLastName.Phone), temp)#.

This was the first employee found under this case-sensitive last name search.

An employee with that exact last name was not found

Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)# #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the #ListGetAt(ValueList(SearchEmpLastName.Department), temp)# Department, can be reached at #ListGetAt(ValueList(SearchEmpLastName.Phone), temp)#.

This was the first employee found under this case-insensitive last name search. 570 Chapter 3: ColdFusion Functions ListFindNoCase Description Determines the index of the first list element in which a specified value occurs. Returns Index of the first list element that contains value. If not found, returns zero. The search is caseinsensitive. Category List functions Function syntax ListFindNoCase(list, value [, delimiters ]) See also ListContains, ListFind Parameters Parameter Description list A list or a variable that contains one. value Number or string for which to search. The search is case-insensitive. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

Try changing the case in Leary's last name:

Pick a search type:

SELECT FirstName, RTrim(LastName) AS LName, Phone, Department FROM Employees ListFindNoCase 571

An employee with that exact last name was not found

Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)# #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the #ListGetAt(ValueList(SearchEmpLastName.Department), temp)# Department, can be reached at #ListGetAt(ValueList(SearchEmpLastName.Phone), temp)#.

This was the first employee found under this case-sensitive last name search.

An employee with that exact last name was not found

Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)# #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the #ListGetAt(ValueList(SearchEmpLastName.Department), temp)# Department, can be reached at #ListGetAt(ValueList(SearchEmpLastName.Phone), temp)#.

This was the first employee found under this case-insensitive last name search. 572 Chapter 3: ColdFusion Functions ListFirst Description Gets the first element of a list. Returns The first element of a list. If the list is empty, returns an empty string. Category List functions Function syntax ListFirst(list [, delimiters ]) See also ListGetAt, ListLast, ListQualify Parameters Parameter Description list A list or a variable that contains a list. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListFirst Example

SELECT Username, Subject, Posted FROM Messages

Before editing the list, it is:  #ValueList(GetMessageUser.Username)#.

(Users who posted more than once are listed more than once.)

The first user in the list is: #ListFirst(temp)#

The rest of the list is: #ListRest(temp)#.

(Users who posted more than once are listed more than once.)

The last user in the list is: #ListLast(temp)# ListFirst 573 ListGetAt Description Gets a list element at a specified position. Returns Index of the list element at position position. Category List functions Function syntax ListGetAt(list, position [, delimiters ]) See also ListFirst, ListLast, ListQualify, ListSetAt Parameters Parameter Description list A list or a variable that contains one. position A positive integer or a variable that contains one. Position at which to get element. The first list position is 1. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage If you use list functions on strings that are delimited by a delimiter character and a space, a returned list element might contain a leading space; you use the trim function to remove such spaces from a returned element. For example, consider this list: To get a value from this list, use the trim function to remove the space before the returned value: With this usage, MyValue = "two hundred", not " two hundred", and spaces within a list element are preserved. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListGetAt Example

SELECT Username, Subject, Posted FROM Messages

This list of usernames who have posted messages numbers #ListLen(temp)# users.

    574 Chapter 3: ColdFusion Functions
  • Username #Counter#: #ListGetAt(temp, Counter)#
ListGetAt 575 ListInsertAt Description Inserts an element in a list. Returns A copy of the list, with value inserted at the specified position. Category List functions Function syntax ListInsertAt(list, position, value [, delimiters ]) See also ListDeleteAt, ListAppend, ListPrepend, ListSetAt Parameters Parameter Description list A list or a variable that contains one. position A positive integer or a variable that contains one. Position at which to insert element. The first list position is 1. value An element or a list of elements. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage When inserting an element, ColdFusion inserts a delimiter. If delimiters contains more than one delimiter, ColdFusion uses the first delimiter in the string; if delimiters is omitted, ColdFusion uses a comma. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example SELECT PARKNAME,CITY,STATE FROM PARKS WHERE PARKNAME LIKE ‘DE%’

The original list: #temp# 576 Chapter 3: ColdFusion Functions ListLast Description Gets the last element of a list. Returns The last element of the list. Category List functions Function syntax ListLast(list [, delimiters ]) See also ListGetAt, ListFirst Parameters Parameter Description list A list or a variable that contains a list. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter; you cannot specify a multicharacter delimiter. Usage If you use list functions on strings that separated by a delimiter character and a space, a returned list element might contain a leading space; use the trim function to remove leading and trailing spaces from a returned element. For example, consider this list: To get a value from this list, use the trim function to remove the space before the returned value: With this usage, the MyValue variable gets the value "three hundred", not " three hundred", and spaces within a list element are preserved. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListFirst, ListLast, and ListRest Example

SELECT Username, Subject, Posted FROM Messages

Before editing the list, it is:  #ValueList(GetMessageUser.Username)#.

(Users who posted more than once are listed more than once.)

The first user in the list is: #ListFirst(temp)#

The rest of the list is: #ListRest(temp)#. ListLast 577

(Users who posted more than once are listed more than once.)

The last user in the list is: #ListLast(temp)# 578 Chapter 3: ColdFusion Functions ListLen Description Determines the number of elements in a list. Integer; the number of elements in a list. Category List functions Function syntax ListLen(list [, delimiters ]) See also ListAppend, ListDeleteAt, ListInsertAt, ListPrepend Parameters Parameter Description list A list or a variable that contains one. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Here are some examples of ListLen processing: Statement Output Comment ListLen('a,b, c,,,d') 4 Third element is " c" ListLen('a,b, c,,,d',',') 4 Fourth element is "d'" ListLen('elem_1___elem_2___elem_3') 1 ListLen('elem*1***elem*2***elem*3') 1 ListLen('elem_1___elem_2___elem_3','_') 6 Example

ListLen Example

SELECT Username, Subject, Posted FROM Messages

This is a list of usernames who have posted messages #ListLen(temp)# users.

  • Username #Counter#: #ListGetAt(temp, Counter)#
ListLen 579 ListPrepend Description Inserts an element at the beginning of a list. Returns A copy of the list, with value inserted at the first position. Category List functions Function syntax ListPrepend(list, value [, delimiters ]) See also ListAppend, ListInsertAt, ListSetAt Parameters Parameter Description list A list or a variable that contains one. value An element or a list of elements. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion only uses the first character and ignores the others. Usage When prepending an element to a list, ColdFusion inserts a delimiter. If delimiters contains more than one delimiter character, ColdFusion uses the first delimiter in the string; if delimiters is omitted, ColdFusion uses a comma. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. If the delimiters parameter is the empty string (""), ColdFusion returns the contents of the value parameter. To add an element to the beginning or end of a list, Macromedia recommends that you do so with code such as the following, rather than with the ListAppend or ListPrepend functions: Example SELECT PARKNAME,CITY,STATE FROM PARKS WHERE PARKNAME LIKE ‘DE%’ 580 Chapter 3: ColdFusion Functions

The original list: #temp# ListPrepend 581 ListQualify Description Inserts a string at the beginning and end of list elements. Returns A copy of the list, with qualifier before and after the specified element(s). Category List functions Function syntax ListQualify(list, qualifier [, delimiters ] [, elements ]) History ColdFusion MX: Changed behavior: as the elements parameter value, you must specify "all" or "char"; otherwise, ColdFusion throws an exception. (In earlier releases, the function ignored an invalid value, and used "all"; this was inconsistent with other functions.) Parameters Parameter Description list A list or a variable that contains one. qualifier A string or a variable that contains one. Character or string to insert before and after the list elements specified in the elements attribute. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion uses the first character as the delimiter and ignores the remaining characters. elements • all: all elements • char: elements that are composed of alphabetic characters Usage The new list might not preserve all of the delimiters in the list. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example SELECT FirstName, LastName FROM Employees

ListQualify Example

This example uses ListQualify to put the full names of the employees in the query within quotation marks.

582 Chapter 3: ColdFusion Functions

The contents of the unqualified list are as follows:

#myList#

The contents of the qualified list are as follows:

#qualifiedList1#

The contents of the second qualified list are:

#qualifiedList2#

ListQualify 583 ListRest Description Gets a list, without its first element. Returns A copy of list, without the first element. If list has one element, returns an empty list. Category List functions Function syntax ListRest(list [, delimiters ]) See also ListFirst, ListGetAt, ListLast Parameters Parameter Description list A list or a variable that contains one. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage If the list begins with one or more empty entries, this function drops them, as well as the first element. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListFirst, ListLast, and ListRest Example

SELECT Username, Subject, Posted FROM Messages

Before editing the list, it is:  #ValueList(GetMessageUser.Username)#.

(Users who posted more than once are listed more than once.)

The first user in the list is: #ListFirst(temp)#

The rest of the list is: #ListRest(temp)#.

(Users who posted more than once are listed more than once.)

The last user in the list is: #ListLast(temp)# 584 Chapter 3: ColdFusion Functions ListSetAt Description Replaces the contents of a list element. Returns A copy of a list, with a new value assigned to the element at a specified position. Category List functions Function syntax ListSetAt(list, position, value [, delimiters ]) See also ListDeleteAt, ListGetAt, ListInsertAt History ColdFusion MX: Changed delimiter modification: ColdFusion MX does not modify delimiters in the list. (In earlier releases, in some cases, replaced delimiters with the first character in the delimiters parameter.) Parameters Parameter Description list A list or a variable that contains one. position A positive integer or a variable that contains one. Position at which to set a value. The first list position is 1. value An element or a list of elements. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Usage When assigning an element to a list, ColdFusion inserts a delimiter. If delimiters contains more than one delimiter, ColdFusion uses the first delimiter in the string, or, if delimiters was omitted, a comma. ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListSetAt Example

SELECT Username, Subject, Posted FROM Messages

This is a list of #ListLen(temp)# ListSetAt 585 subjects posted in messages.

  • (#Counter#) SUBJECT: #ListGetAt(temptoo, Counter)#

Note that element 2, "#changedElement#", has been altered to "I changed this subject" using ListSetAt. 586 Chapter 3: ColdFusion Functions ListSort Description Sorts list elements according to a sort type and sort order. Returns A copy of a list, sorted. Category List functions Function syntax ListSort(list, sort_type [, sort_order] [, delimiters ]) History ColdFusion MX: Changed the order in which sorted elements are returned: in a textnocase, descending sort, this function might return elements in a different sort order than in earlier releases. If sort_type = "textnocase" and sort_order = "desc", ColdFusion MX processes elements that differ only in case differently from earlier releases. ColdFusion MX outputs the elements in the reverse of the ascending order. Earlier releases do not change order of elements that differ only in case. Both operations are correct. The new operation ensures that an ascending and descending sort output elements in exactly reverse order. For example, in a textnocase, desc sort of d,a,a,b,A, the following occurs: • ColdFusion MX returns d,b,A,a,a • Earlier ColdFusion releases return d,b,a,a,A (In a textnocase, asc sort, all ColdFusion releases return a,a,A,b,d.) Parameters Parameter Description list A list or a variable that contains one. sort_type • numeric: sorts numbers • text: sorts text alphabetically, taking case into account (also known as case sensitive). All letters of one case precede the first letter of the other case: - aabzABZ, if sort_order = "asc" (ascending sort) - ZBAzbaa, if sort_order = "desc" (descending sort) • textnocase: sorts text alphabetically, without regard to case (also known as caseinsensitive). A letter in varying cases precedes the next letter: - aAaBbBzzZ, in an ascending sort; preserves original intra-letter order - ZzzBbBaAa, in a descending sort; reverses original intra-letter order ListSort 587 Parameter Description sort_order • asc - ascending sort order. Default. - aabzABZ or aAaBbBzzZ, depending on value of sort_type, for letters - from smaller to larger, for numbers • desc - descending sort order. - ZBAzbaa or ZzzBbBaAa, depending on value of sort_type, for letters - from larger to smaller, for numbers delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion uses the first character in the string as the delimiter, and ignores the rest. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. Example

ListSort Example

SELECT Username, Subject, Posted FROM Messages

Here is the unsorted list.

#myList#

Here is the list sorted alphabetically:

#sortedList#

Here is a numeric list that is to be sorted in descending order.

#sortedNums#

Here is a list that must be sorted numerically, since it contains negative and positive numbers, and decimal numbers.

#sortedNums2#

Here is a list to be sorted alphabetically without consideration of case. #sortedMix# 588 Chapter 3: ColdFusion Functions ListToArray Description Copies the elements of a list to an array. Returns An array Category Array functions, Conversion functions, List functions Function syntax ListToArray(list [, delimiters ]) See also ArrayToList Parameters Parameter Description list A list or a variable that contains one. You define a list variable with a cfset statement. delimiters A string or a variable that contains one. ColdFusion treats each character in the string as a delimiter. Default: comma. Usage ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements. ColdFusion treats each character in the delimiters attribute as a separate delimiter. Therefore, if the attribute is ",+" ColdFusion will break the list at either a comma plus sign. Example

ListToArray Example

SELECT Username, Subject, Posted FROM Messages

My list is a list with #ListLen(myList)# elements.

My array list is an array with #ArrayLen(myArrayList)# elements. ListToArray 589 ListValueCount Description Counts instances of a specified value in a list. The search is case-sensitive. Returns The number of instances of value in the list. Category List functions, String functions Function syntax ListValueCount(list, value [, delimiters ]) See also ListValueCountNoCase Parameters Parameter Description list A list or a variable that contains one. value String or number or a variable that contains one. Item for which to search. The search is case-sensitive. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Example SELECT Department FROM Employees

ListValueCount Example

This example uses ListValueCount to count employees in a department.

Select a department:

590 Chapter 3: ColdFusion Functions

There are no employees in #FORM.departmentName#

There is only one person in #FORM.departmentName#.

There are #numberInDepartment# people in #FORM.departmentName#. ListValueCount 591 ListValueCountNoCase Description Counts instances of a specified value in a list. The search is case-insensitive. Returns The number of instances of value in the list. Category List functions Function syntax ListValueCountNoCase(list, value [, delimiters ]) See also ListValueCount Parameters Parameter Description list A list or a variable that contains one. value String or number or a variable that contains one. Item for which to search. The search is case-insensitive. delimiters A string or a variable that contains one. Character(s) that separate list elements. Default: comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter. Example SELECT Department FROM Employees

ListValueCountNoCase Example

This example uses ListValueCountNoCase to count employees in a department.

Select a department:

592 Chapter 3: ColdFusion Functions

There are no employees in #FORM.departmentName#

There is only one person in #FORM.departmentName#.

There are #numberInDepartment# people in #FORM.departmentName#. ListValueCountNoCase 593 LJustify Description Left justifies characters in a string of a specified length. Returns A copy of a string, left-justified. Category Display and formatting functions, String functions Function syntax LJustify(string, length) See also CJustify, RJustify Parameters Parameter Description string A string or a variable that contains one length Length of field in which to justify string Example LJustify Example

LJustify Function

Enter a string, and it will be left justified within the sample field

594 Chapter 3: ColdFusion Functions Log Description Calculates the natural logarithm of a number. Natural logarithms are based on the constant e (2.71828182845904). Returns The natural logarithm of a number. Category Mathematical functions Function syntax Log(number) See also Exp, Log10 Parameters Parameter Description number Positive real number for which to calculate the natural logarithm Example

Log Example

Your number, #FORM.number#
#FORM.number# raised to the E power: #exp(FORM.number)#
Enter a positive real number to get its natural logarithm
The natural logarithm of #FORM.number#: #log(FORM.number)#

Enter a positive real number to get its logarithm to base 10
The logarithm of #FORM.number# to base 10: #log10(FORM.number)#
Enter a number to see its value raised to the E power, its natural logarithm, and the logarithm of number to base 10. Log 595 Log10 Description Calculates the logarithm of number, to base 10. Returns Number; the logarithm of number, to base 10. Category Mathematical functions Function syntax Log10(number) See also Exp, Log Parameters Parameter Description number Positive real number for which to calculate the logarithm Example

Log10 Example

Your number, #FORM.number#
#FORM.number# raised to the E power: #exp(FORM.number)#
You must enter a positive real number to see the natural logarithm of that number
The natural logarithm of #FORM.number#: #log(FORM.number)#

You must enter a positive real number to see the logarithm of that number to base 10
The logarithm of #FORM.number# to base 10: #log10(FORM.number)#
Enter a number to find its value raised to the E power, its natural logarithm, and the logarithm of number to base 10. 596 Chapter 3: ColdFusion Functions LSCurrencyFormat Description Formats a number in a locale-specific currency format. For countries that use the euro, the result depends on the JVM. Returns A formatted currency value. Category Display and formatting functions, International functions Function syntax LSCurrencyFormat(number [, type ]) See also LSEuroCurrencyFormat, LSIsCurrency, LSParseCurrency, LSParseEuroCurrency, SetLocale History ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. If a negative number is passed to it, it returns a negative number. If type = "local", it returns the value in the current locale’s standard format. If type = "international", it returns the value in the current locale’s international standard format. This function uses Java standard locale formatting rules on all platforms. Parameters Parameter Description number Currency value type • local: the currency format and currency symbol used in the locale. - With JDK 1.3, the default for Euro Zone countries is their local currency. - With JDK 1.4, the default for Euro Zone countries is the euro. • international: the international standard currency format and currency symbol of the locale. • none: the currency format used in the locale; no currency symbol Usage This function uses Java standard locale formatting rules on all platforms. Note: With a Sun 1.3.1-compliant JVM, use the LSEuroCurrencyFormat function to format euro currency values. Currency output The following table shows sample currency output. For locales that use Euro, the Local and International columns contains two entries. The first is entry is the result with a Sun the 1.4.1compliant JVM, the second entry is the result with a 1.3.1-compliant JVM. Locale Type = Local Type = International Type = None Chinese (China) ¥100,000.00 CNY100,000.00 100,000.00 Chinese (Hong Kong) HK$100,000.00 HKD100,000.00 100,000.00 LSCurrencyFormat 597 598 Locale Type = Local Type = International Type = None Chinese (Taiwan) NT$100,000.00 TWD100,000.00 100,000.00 Dutch (Belgian) 100.000,00 ¤ 100.000,00 BF BEF100.000,00 EUR100.000,00 100.000,00 Dutch (Standard) ¤ 100.000,00 fl 100.000,00 NLG100.000,00 EUR100.000,00 100.000,00 English (Australian) $100,000.00 AUD100,000.00 100,000.00 English (Canadian) $100,000.00 CAD100,000.00 100,000.00 English (New Zealand) $100,000.00 NZD100,000.00 100,000.00 English (UK) £100,000.00 GBP100,000.00 100,000.00 English (US) $100,000.00 USD100,000.00 100,000.00 French (Belgian) 100.000,00 ¤ 100.000,00 FB EUR100.000,00 BEF100.000,00 100.000,00 French (Canadian) 100 000,00 $ CAD100 000,00 100 000,00 French (Standard) 100 000,00 ¤ 100 000,00 F EUR100 000,00 FRF100 000,00 100 000,00 French (Swiss) SFr. 100'000.00 CHF100'000.00 100'000.00 German (Austrian) ¤ 100.000,00 öS 100.000,00 EUR100.000,00 ATS100.000,00 100.000,00 German (Standard) 100.000,00 ¤ 100.000,00 DM EUR100.000,00 DEM100.000,00 100.000,00 German (Swiss) SFr. 100'000.00 CHF100'000.00 100'000.00 Italian (Standard) ¤ 100.000,00 L. 10.000.000 EUR10.000.000 ITL10.000.000 10.000.000 Italian (Swiss) SFr. 100'000.00 CHF100'000.00 100'000.00 Japanese ¥100,000 JPY100,000 JPY100,000 Korean W100,000 KRW100,000 100,000 Norwegian (Bokmal) kr 100 000,00 NOK100 000,00 100 000,00 Norwegian (Nynorsk) kr 100 000,00 NOK100 000,00 100 000,00 Portuguese (Brazilian) R$100.000,00 BRC100.000,00 100.000,00 Portuguese (Standard) 100.000,00 ¤ R$100.000,00 EUR100.000,00 BRC100.000,00 100.000,00 Spanish (Mexican) $100,000.00 MXN100,000.00 100,000.00 Spanish (Modern) 100.000,00 ¤ 10.000.000 Pts EUR10.000.000 ESP10.000.000 10.000.000 Spanish (Standard) 100.000,00 ¤ 10.000.000 Pts ESP10.000.000 EUR10.000.000 10.000.000 Swedish 100.000,00 kr SEK100.000,00 100.000,00 Chapter 3: ColdFusion Functions Note: ColdFusion maps Spanish (Modern) to the Spanish (Standard) format. To set the default display format of date, time, number, and currency values, use the SetLocale function. Example

LSCurrencyFormat Example

LSCurrencyFormat returns a currency value using the locale convention. Default value is "local."

#locale#
Local: #LSCurrencyFormat(100000, "local")#
International: #LSCurrencyFormat(100000, "international")#
None: #LSCurrencyFormat(100000, "none")#


LSCurrencyFormat 599 LSDateFormat Description Formats the date part of a date/time value in a locale-specific format. Returns A formatted date/time value. If no mask is specified, the value is formatted according to the locale setting of the client computer. Category Date and time functions, Display and formatting functions, International functions Function syntax LSDateFormat(date [, mask ]) See also LSParseDateTime, LSTimeFormat, DateFormat, SetLocale History ColdFusion MX: • Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms. • Added support for the following mask attribute options: short, medium, long, and full. Parameters Parameter Description date A date/time object, in the range 100 AD–9999 AD. mask Characters that show how ColdFusion displays the date: • d: Day of month. Digits; no leading zero for single-digit days • dd: Day of month. Digits; leading zero for single-digit days • ddd: Day of week, abbreviation • dddd: Day of week. Full name • m: Month. Digits; no leading zero for single-digit months • mm: Month. Digits; leading zero for single-digit months • mmm: Month. abbreviation (if appropriate) • mmmm: Month. Full name • y: Year. Last two digits; no leading zero for years less than 10 • yy: Year. Last two digits; leading zero for years less than 10 • yyyy: Year. Four digits • gg: Period/era string. Not processed. Reserved for future use The following conform to Java locale-specific time encoding standards. Their exact formats depend on the locale: • short: dd, mm, and yy separated by / marks • medium: text format using mmm, d, and yyyy • long: text format using mmmm, d, and yyyy • full: text format using dddd, mmmm, d, and yyyy Default: medium For more information on formats, see LSParseDateTime on page 615. Usage This function uses Java standard locale formatting rules on all platforms. 600 Chapter 3: ColdFusion Functions When passing date/time value as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. To calculate a difference between time zones, use the GetTimeZoneInfo function. Example

LSDateFormat Example

LSDateFormat formats the date part of a date/time value using the locale convention.

#locale#
#LSDateFormat(Now(), "mmm-dd-yyyy")#
#LSDateFormat(Now(), "mmmm d, yyyy")#
#LSDateFormat(Now(), "mm/dd/yyyy")#
#LSDateFormat(Now(), "d-mmm-yyyy")#
#LSDateFormat(Now(), "ddd, mmmm dd, yyyy")#
#LSDateFormat(Now(), "d/m/yy")#
#LSDateFormat(Now())#


LSDateFormat 601 LSEuroCurrencyFormat Description Formats a number in a locale-specific currency format. Returns A formatted currency value. For countries in the Euro currency zone, the function uses the locale’s rule’s for formatting currency in euros. Category Display and formatting functions, International functions Function syntax LSEuroCurrencyFormat(currency-number [, type ]) See also LSParseEuroCurrency, LSCurrencyFormat, SetLocale History ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java locale formatting rules on all platforms, except that it uses the rule detailed in the Usage section for countries in the Euro currency zone. As a result, it format currencies for non Euro zone locales using the country’s currency, not euros. Parameters Parameter Description currency-number Currency value. type • local: the currency format used in the locale. (Default.) • international: the international standard currency format of the locale. For example, EUR10.00 • none: the currency format used in the locale; no currency symbol Usage This function uses euro currency formatting rules for all JVM versions, as follows: • If the country of the current locale belongs to the Euro Zone (whose members have converted to the euro) the formatted output for the local type includes the Euro currency sign (€); for the international type, the output includes the euro currency symbol (EUR). If the value is negative, the format includes a negative sign before the value or parentheses around the value, according to the formatting rules of the current locale. • If the country of the current locale is not in the Euro Zone, the currency sign or symbol of the current locale displays. If the value is negative, the format includes a negative sign before the value or parentheses around the value, according to the formatting rules of the current locale. For a list of the locale options that ColdFusion supports, and information on setting the default display format of date, time, number, and currency values, see SetLocale on page 676. 602 Chapter 3: ColdFusion Functions Currency output The following table shows examples of currency output: Locale Type = Local Type = International Type = None Chinese (China) ¥100,000.00 CNY100,000.00 100,000.00 Chinese (Hong Kong) HK$100,000.00 HKD100,000.00 100,000.00 Chinese (Taiwan) NT$100,000.00 TWD100,000.00 100,000.00 Dutch (Belgian) 100.000,00 ¤ EUR100.000,00 100.000,00 Dutch (Standard) ¤ 100.000,00 EUR100.000,00 100.000,00 English (Australian) $100,000.00 AUD100,000.00 100,000.00 English (Canadian) $100,000.00 CAD100,000.00 100,000.00 English (New Zealand) $100,000.00 NZD100,000.00 100,000.00 English (UK) £100,000.00 GBP100,000.00 100,000.00 English (US) $100,000.00 USD100,000.00 100,000.00 French (Belgian) 100.000,00 ¤ EUR100.000,00 100.000,00 French (Canadian) 100 000,00 $ CAD100 000,00 100 000,00 French (Standard) 100 000,00 ¤ EUR100 000,00 100 000,00 French (Swiss) SFr. 100'000.00 CHF100'000.00 100'000.00 German (Austrian) ¤ 100.000,00 EUR100.000,00 100.000,00 German (Standard) 100.000,00 ¤ EUR100.000,00 100.000,00 German (Swiss) SFr. 100'000.00 CHF100'000.00 100'000.00 Italian (Standard) ¤ 100.000,00 EUR10.000.000 10.000.000 Italian (Swiss) SFr. 100'000.00 CHF100'000.00 100'000.00 Japanese ¥100,000 JPY100,000 JPY100,000 Korean W100,000 KRW100,000 100,000 Norwegian (Bokmal) kr 100 000,00 NOK100 000,00 100 000,00 Norwegian (Nynorsk) kr 100 000,00 NOK100 000,00 100 000,00 Portuguese (Brazilian) R$100.000,00 BRC100.000,00 100.000,00 Portuguese (Standard) 100.000,00 ¤ EUR100.000,00 100.000,00 Spanish (Mexican) $100,000.00 MXN100,000.00 100,000.00 Spanish (Modern) 100.000,00 ¤ EUR10.000.000 10.000.000 Spanish (Standard) 100.000,00 ¤ ESP10.000.000 10.000.000 Swedish 100.000,00 kr SEK100.000,00 100.000,00 Note: ColdFusion uses the Spanish (Standard) formats for Spanish (Modern) and Spanish (Standard). LSEuroCurrencyFormat 603 The following example shows how the function formats negative values. The format includes a negative sign before the value, or parentheses around the value, according to the formatting rules of the current locale. Input value Output if locale = French (Standard) Output if locale = English (US) -1234.56 -1 234,56 ¤ ($1,234.56) Example

LSEuroCurrencyFormat Example

LSEuroCurrencyFormat returns a currency value using the locale convention. Default value is "local."

#locale#
Local: #LSEuroCurrencyFormat(100000, "local")#
International: #LSEuroCurrencyFormat(100000, "international")#
None: #LSEuroCurrencyFormat(100000, "none")#


604 Chapter 3: ColdFusion Functions LSIsCurrency Description Determines whether a string is a valid representation of a currency amount in the current locale. Returns True, if the parameter is formatted as a valid currency amount, including the appropriate currency indicator. Returns True for amounts in the local, international, or none currency formats. Category Display and formatting functions, Decision functions, International functions Function syntax LSIsCurrency(string) See also GetLocale, SetLocale, LSCurrencyFormat History ColdFusion MX: Changed formatting behavior: this function might return a different result than in earlier releases. This function uses Java standard locale formatting rules on all platforms; the results might vary depending upon the JVM; for example, Sun JVM 1.4.1 requires euro format the local currency if the current locale’s country belongs to the Euro Zone. Parameters Parameter Description string A currency string or a variable that contains one. Usage For examples of ColdFusion code and output that shows differences between earlier ColdFusion releases and ColdFusion MX in accepting input formats and displaying output, see LSCurrencyFormat on page 597. Note: If the locale belongs to a Euro zone country and the currency is a correctly formatted euro value for the locale, this function returns True for all JVMs, including Sun 1.3.1. As a result, with 1.3.1compliant JVMs, the LSIsCurrency function does not ensure that LSParseCurrency returns a value. If a currency uses the older country-specific format for Euro Zone locales, the LSIsCurrency function False for newer JVMs, such as Sun 1.4.1 and True for older JVMs, such as Sun 1.3.1. Note: To set the default display format of date, time, number, and currency values, use the SetLocale function. Example

LSIsCurrency Example

Is the value "#FORM.myValue#" a proper currency value for #GetLocale()#?

Answer: #LSIsCurrency(FORM.myValue)# LSIsCurrency 605

Select a locale for which you would like to check a currency value: 606 Chapter 3: ColdFusion Functions LSIsDate Description Determines whether a string is a valid representation of a date/time value in the current locale. Returns True, if the string can be formatted as a date/time value in the current locale; False, otherwise. Category Date and time functions, Display and formatting functions, International functions Function syntax LSIsDate(string) See also CreateDateTime, GetLocale, IsNumericDate, LSDateFormat, ParseDateTime, SetLocale History ColdFusion MX: • Changed formatting behavior: this function might return a different result than in earlier releases. This function uses Java standard locale formatting rules on all platforms. • Changed behavior: this function accepts a dash or hyphen character only in the • Dutch(Standard) and Portuguese (Standard) locales. If called this way (for example, LsIsDate("3-1-2002") in any other locale, this function returns False. (Earlier releases returned True.) Changed behavior: when using the SUN JRE 1.3.1 on an English(UK) locale, this function returns False for a date that has a one-digit month or day (for example, 1/1/01). To work around this, insert a zero in a one-digit month or day (for example, 01/01/01). Parameters Parameter Description string A string or a variable that contains one Usage A date/time object is in the range 100 AD–9999 AD. To set the default display format of date, time, number, and currency values, use the SetLocale function. Example

LSIsDate Example

Is the value "#FORM.myValue#" a proper date value for #GetLocale()#?

Answer: #LSIsDate(FORM.myValue)#

Select a locale for which you would like to check a date value: LSIsDate 607 608 Chapter 3: ColdFusion Functions LSIsNumeric Description Determines whether a string is a valid representation of a number in the current locale. Returns True, if the string represents a number the current locale; False, otherwise. Category Decision functions, International functions, String functions Function syntax LSIsNumeric(string) See also GetLocale, SetLocale History ColdFusion MX: Changed formatting behavior: this function might return a different result than in earlier releases. This function uses Java standard locale formatting rules on all platforms. Parameters Parameter Description string A string or a variable that contains one Usage To set the default display format of date, time, number, and currency values, use the SetLocale function. Example

LSIsNumeric Example

Is the value "#FORM.myValue#" a proper numeric value for #GetLocale()#?

Answer: #LSIsNumeric(FORM.myValue)#

Select a locale for which to check a numeric value: ... LSIsNumeric 609 LSNumberFormat Description Formats a number in a locale-specific format. Returns A formatted number. • • • • If no mask is specified, it returns the number formatted as an integer If no mask is specified, truncates the decimal part; for example, it truncates 34.57 to 35 If the specified mask cannot correctly mask a number, it returns the number unchanged If the parameter value is "" (an empty string), it returns 0. Category Display and formatting functions, International functions Function syntax LSNumberFormat(number [, mask ]) See also GetLocale, SetLocale History ColdFusion MX: • Changed behavior: if the specified mask format cannot correctly mask a number, this function returns the number unchanged. (In earlier releases, it truncated the number or threw an error.) (If no mask is specified, ColdFusion MX truncates the decimal part as ColdFusion 5 does. For example, it truncates 1234.567 to 1235.) Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms. • Parameters Parameter Description number Number to format mask LSNumberFormat mask characters apply, except: dollar sign, comma, and dot are mapped to their locale-specific equivalents. The following table lists the LSNumberFormat mask characters. 610 Character Meaning _ (Underscore.) Digit placeholder. 9 Digit placeholder. (Shows decimal places more clearly than _ .) . Location of a mandatory decimal point (or locale-appropriate symbol). 0 Located to the left or right of a mandatory decimal point. Pads with zeros. () If number is less than zero, puts parentheses around the mask. + Puts plus sign before positive number; minus sign before negative number. Chapter 3: ColdFusion Functions Character Meaning - Puts space before positive number; minus sign before negative number. , Separates every third decimal place with a comma (or locale-appropriate symbol). L,C Left-justifies or center-justifies number within width of mask column. First character of mask must be L or C. Default: right-justified. $ Puts a dollar sign (or locale-appropriate symbol) before formatted number. First character of mask must be the dollar sign ($). ^ Separates left and right formatting. Note: If you do not specify a sign for the mask, positive and negative numbers do not align in columns. To put a plus sign or space before positive numbers and a minus sign before negative numbers, use the plus or hyphen mask character, respectively. Usage This function uses Java standard locale formatting rules on all platforms. The position of symbols in format masks determines where the codes take effect. For example, if you put a dollar sign at the far left of a format mask, ColdFusion displays a dollar sign at the left edge of the formatted number. If you separate the dollar sign on the left edge of the format mask by at least one underscore, ColdFusion displays the dollar sign just to the left of the digits in the formatted number. These examples show how symbols determine formats: Number Mask Result 4.37 $____.__ "$ 4.37" 4.37 _$___.__ " $4.37" The positioning can also show where to put a minus sign for negative numbers: Number Mask Result -4.37 -____.__ "- 4.37" -4.37 _-___.__ " -4.37" The positions for a symbol are: far left, near left, near right, and far right. The left and right positions are determined by the side of the decimal point on which the code character is shown. For formats that do not have a fixed number of decimal places, you can use a caret (^) to separate the left fields from the right. An underscore determines whether the code is placed in the far or near position. Most code characters’ effect is determined by the field in which they are located. This example shows how to specify where to put parentheses to display negative numbers: Number Mask Result 3.21 C(__^__) "( 3.21 )" 3.21 C__(^__) " (3.21 )" LSNumberFormat 611 Number Mask Result 3.21 C(__^)__ "( 3.21) " 3.21 C__(^)__ " (3.21) " To set the default display format of date, time, number, and currency values, use the SetLocale function. When converting from string to double, to prevent rounding errors, this function adds a rounding factor of 1.5543122344752E-014 to the converted number. For example, without adding the rounding factor, converting the string value 1.275 to double with two digits of precision results in a value of 1.27499999999999999, which would be rounded up to 1.27. By adding the rounding factor, the conversion correctly results in a value of 1.28. If you round off a double, such as 1.99499999999999999999999999999, where the last decimal is 10E-14, the rounding factor can cause an incorrect result. Example

LSNumberFormat Example

LSNumberFormat returns a number value using the locale convention.

#locale#
#LSNumberFormat(-1234.5678, "_________")#
#LSNumberFormat(-1234.5678, "_________.___")#
#LSNumberFormat(1234.5678, "_________")#
#LSNumberFormat(1234.5678, "_________.___")#
#LSNumberFormat(1234.5678, "$_(_________.___)")#
#LSNumberFormat(-1234.5678, "$_(_________.___)")#
#LSNumberFormat(1234.5678, "+_________.___")#
#LSNumberFormat(1234.5678, "-_________.___")#
612 Chapter 3: ColdFusion Functions LSParseCurrency Description Converts a locale-specific currency string into a formatted number. Attempts conversion by comparing the string with each the three supported currency formats (none, local, international) and using the first that matches. Returns A formatted number (string representation of a number) that matches the value of the parameter. Category International functions, String functions Function syntax LSParseCurrency(string) See also LSParseEuroCurrency, LSCurrencyFormat, LSEuroCurrencyFormat, LSIsCurrency History ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms. Parameters Parameter Description string A locale-specific string a variable that contains one Usage This function uses the locale formatting rules of the JVM (specified in the ColdFusion Administrator Java and JVM page) on all platforms. These rules changed between Sun JVM 1.3.1 and JVM 1.4.1: • JVM 1.3.1 requires that the local and international versions of currencies of countries in the • Euro zone be formatted using the older, country-specific designations, such as 100.000,00 DM or DEM100.000,00 for the German (Standard) locale. Use the LSParseEuroCurrency function to parse euro currencies in these locales with JVM 1.3.1. JVM 1.4.1 requires that currencies for Euro zone countries be expressed as euros; for example 100.000,00 € or EUR100.000,00. Note: The LSIsCurrency function always returns True if the locale is in the Euro currency zone and the currency is expressed in euros, including when using JVM 1.3.1. As a result, with older JVMs, LSIsCurrency does not ensure that LSParseCurrency returns a value. To set the default display format of date, time, number, and currency values, use the SetLocale function. See LSCurrencyFormat for a list of the local-specific formats used to parse the currency. Example

LSParseCurrency Example

LSParseCurrency coverts a locale-specific currency string to a number. Attempts conversion through each of the three default currency formats. LSParseCurrency 613

#locale#
Local: #LSCurrencyFormat(123456.78, "local")#
Parsed local Currency: #LSParseCurrency(LSCurrencyFormat(123456,"local"))#
International: #LSCurrencyFormat(123456.78999, "international")#
Parsed International Currency: #LSParseCurrency(LSCurrencyFormat(123456.78999,"international"))#
None: #LSCurrencyFormat(123456.78999, "none")#
Parsed None formatted currency: #LSParseCurrency(LSCurrencyFormat(123456.78999,"none"))#


614 Chapter 3: ColdFusion Functions LSParseDateTime Description Converts a string that is a valid date/time representation in the current locale into a date/time object. Returns A date/time object. Category Date and time functions, Display and formatting functions, International functions, String functions Function syntax LSParseDateTime(date/time-string) See also LSDateFormat, ParseDateTime, SetLocale, GetLocale History ColdFusion MX: • Changed formatting behavior: this function might not parse string formats that worked with • earlier releases. This function uses Java standard locale formatting rules on all platforms. Changed how the date/time-string parameter value is processed: ColdFusion processes the date/time-string parameter value time zone information differently than in earlier releases, as described in the Usage section. Parameters Parameter Description date/time-string A string a variable that contains one, in a format that is readable in the current locale. Usage This function can parse any date, time, or date/time combination that conforms to Java standard locale formatting rules for the current locale. The following table lists some of the date/time values you can pass to this function in the English (US) locale. You can also pass only the date or the time parts of these formats: Format Example m/dd/yy h:mm:ss 1/30/02 7:02:33 m/dd/yy h:mm tt 1/30/02 7:02 AM m/dd/yyyy h:mm 1/30/2002 7:02 AM mmm dd, yyyy h:mm:ss tt Jan 30, 2002 7:02:12 AM mmmm dd, yyyy h:mm:ss tt zzz January 30, 2002 7:02:23 AM PST ddd, mmm dd, yyyy hh:mm:ss Wed, Jan 30, 2002 07:02:12 dddd, mmmm dd, yyyy h:mm:ss tt zzz Wednesday, January 30, 2002 7:02:12 AM PST LSParseDateTime 615 Valid dates are in the range 100 AD–9999 AD. Two digit years in the range 00-29 are interpreted as being 2000-2029. Two digit years in the range 30-99 are interpreted as being 1930-1999 This function corrects for differences between the current time zone and any time zone specified in the input parameter. • If a time zone specified in the date/time-string parameter is different from the time zone • setting of the computer, ColdFusion adjusts the time value to its equivalent in the computer time zone. If a time zone is not specified in the date/time-string parameter, ColdFusion does not adjust the time value. Note: This function does not accept POP dates, which include a time zone offset value. Example

LSParseDateTime Example - returns a locale-specific date/time object

#locale#

Locale-specific formats:
#LSDateFormat(Now(), "mmm-dd-yyyy")# #LSTimeFormat(Now())#
#LSDateFormat(Now(), "mmmm d, yyyy")# #LSTimeFormat(Now())#
#LSDateFormat(Now(), "mm/dd/yyyy")# #LSTimeFormat(Now())#
#LSDateFormat(Now(), "d-mmm-yyyy")# #LSTimeFormat(Now())#
#LSDateFormat(Now(), "ddd, mmmm dd, yyyy")# #LSTimeFormat(Now())#
#LSDateFormat(Now(), "d/m/yy")# #LSTimeFormat(Now())#
#LSDateFormat(Now())# #LSTimeFormat(Now())#

Standard Date/Time: #LSParseDateTime("#LSDateFormat(Now())# #LSTimeFormat(Now())#")#
616 Chapter 3: ColdFusion Functions LSParseEuroCurrency Description Formats a locale-specific currency string as a number. Attempts conversion through each of the default currency formats (none, local, international). Ensures correct handling of euro currency for Euro zone countries. Returns A formatted number that matches the value of the string. Category International functions, String functions Function syntax LSParseEuroCurrency(currency-string) See also LSParseCurrency, LSEuroCurrencyFormat, SetLocale History ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java locale formatting rules on all platforms, except that it uses the rule detailed in the Usage section for countries in the Euro currency zone. Parameters Parameter Description currency-string Locale-specific string or a variable that contains one. Usage This function determines whether the current locale’s country belongs to the Euro Zone, whose members have converted to the euro; if so, the currency-string parameter must be formatted in euros on all JVMs, including Sun JVM 1.3.1. If the country is not in the Euro zone, the string must follow the locale formatting rules of the JVM. For examples of valid currency formats in all supported locales, see LSEuroCurrencyFormat on page 602. For a list of the locale options that ColdFusion supports, and information on setting the default display format of date, time, number, and currency values, see SetLocale on page 676. Example

LSParseEuroCurrency Example

Loop through all available locales. Create string representations of the value 123,456 in the three supported currency formats, and parse the results back to numbers.

Current Locale: #locale#
Value in local currency: #localCurrency#
Parsed using LSParseEuroCurrency: #LSParseEuroCurrency(localCurrency)#
LSParseEuroCurrency 617 Value with International currency formatting: #IntlCurrency#
Parsed using LSParseEuroCurrency: #LSParseEuroCurrency(IntlCurrency)#
Value with no currency formatting: #currency#
Parsed using LSParseEuroCurrency: #LSParseEuroCurrency(Currency)#


618 Chapter 3: ColdFusion Functions LSParseNumber Description Converts a string that is a valid numeric representation in the current locale into a formatted number. Returns A formatted number that matches the value of the string. Category International functions, String functions Function syntax LSParseNumber(string) See also LSParseDateTime, SetLocale History ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms. Parameters Parameter Description string A string or a variable that contains one Usage This function uses Java standard locale formatting rules on all platforms. To set the default display format of date, time, number, and currency values, use the SetLocale function. Example

LSParseNumber Example

LSParseNumber converts a locale-specific string to a number. Returns the number matching the value of string.

#locale#
#LSNumberFormat(-1234.5678, "_________")#
#LSNumberFormat(-1234.5678, "_________.___")#
#LSNumberFormat(1234.5678, "_________")#
#LSNumberFormat(1234.5678, "_________.___")#
#LSNumberFormat(1234.5678, "$_(_________.___)")#
#LSNumberFormat(-1234.5678, "$_(_________.___)")#
#LSNumberFormat(1234.5678, "+_________.___")#
#LSNumberFormat(1234.5678, "-_________.___")#
The actual number: #LSParseNumber(LSNumberFormat(1234.5678, "_________"))#


LSParseNumber 619 620 Chapter 3: ColdFusion Functions LSTimeFormat Description Formats the time part of a date/time string into a string in a locale-specific format. Returns A string representing the time value. Category Date and time functions, Display and formatting functions, International functions Function syntax LSTimeFormat(time [, mask ]) See also LSParseDateTime, LSDateFormat, TimeFormat History ColdFusion MX 6.1: Added the mask character L or l to represent milliseconds. ColdFusion MX: • Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms. • Added support for the following mask attribute options: short, medium, long, and full. Parameters Parameter Description string • A date/time value • A string that is convertible to a time value A date/time object is in the range 100 AD–9999 AD. mask Masking characters that determine the format: • h: Hours; no leading zero for single-digit hours (12-hour clock) • hh: Hours; leading zero for single-digit hours. (12-hour clock) • H: Hours; no leading zero for single-digit hours (24-hour clock) • HH: Hours; leading zero for single-digit hours (24-hour clock) • m: Minutes; no leading zero for single-digit minutes • mm: Minutes; leading zero for single-digit minutes • s: Seconds; no leading zero for single-digit seconds • ss: Seconds; leading zero for single-digit seconds • l: Milliseconds • t: One-character time marker string, such as A or P. • tt: Multiple-character time marker string, such as AM or PM The following conform to Java locale-specific time encoding standards. Their exact formats depend on the locale: • short: includes hours, minutes; may include AM or PM • medium: includes hours, minutes; may include AM or PM • long: medium plus time zone • full: long, may also include an hour designator Default: short LSTimeFormat 621 Usage This function uses Java standard locale formatting rules on all platforms. When passing date/time value as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. To calculate a difference between time zones, use the GetTimeZoneInfo function. To set the default display format of date, time, number, and currency values, use the SetLocale function. If no seconds value is passed to this function, and the mask value is s, the default output seconds format is one zero; for example, lstimeformat(6:39, "h:m:s") returns 6:39:0. If the mask value is ss, it returns 6:39:00. Example

LSTimeFormat Example

LSTimeFormat returns a time value using the locale convention.

#locale#
#LSTimeFormat(Now())#
#LSTimeFormat(Now(), ‘hh:mm:ss’)#
#LSTimeFormat(Now(), ‘hh:mm:sst’)#
#LSTimeFormat(Now(), ‘hh:mm:sstt’)#
#LSTimeFormat(Now(), ‘HH:mm:ss’)#


622 Chapter 3: ColdFusion Functions LTrim Description Removes leading spaces from a string. Returns A copy of the string, without leading spaces. Category Display and formatting functions, String functions Function syntax LTrim(string) See also RTrim, ToBase64 Parameters Parameter Description string A string or a variable that contains one Example

LTrim Example

Your string:"#FORM.myText#"
Your string:"#LTrim(FORM.myText)#"
(left trimmed)

Type in some text, and it will be modified by LTrim to remove leading spaces from the left

LTrim 623 Max Description Determines the greater of two numbers. Returns The greater of two numbers. Category Mathematical functions Function syntax Max(number1, number2) See also Min Parameters Parameter Description number1, number2 Numbers Example

Max Example

The maximum of the two numbers is #Max(FORM.myNum1, FORM.myNum2)#

The minimum of the two numbers is #Min(FORM.myNum1, FORM.myNum2)#

Please enter two numbers

Enter two numbers, see the maximum and minimum of them

Number 1
Number 2
624 Chapter 3: ColdFusion Functions Mid Description Extracts a substring from a string. Returns A string; the set of characters from string, beginning at start, of length count. Category String functions Function syntax Mid(string, start, count) See also Left, Len, Right Parameters Parameter Description string A string or a variable that contains one. Must be single-quote or double-quote delimited. start A positive integer or a variable that contains one. Position at which to start count. Positions start with 1, not 0. count A positive integer or a variable that contains one. Number of characters to return. (0 is not valid, but it does not throw an error.) Example

Mid Example

Your string #FORM.myText# only has #Len(FORM.myText)# characters. You cannot output the #FORM.removeChars# middle characters of this string because it is not long enough

Your original string: #FORM.myText#

Your changed string, showing only the #FORM.removeChars# middle characters: #Mid(Form.myText, FORM.removeChars, Form.countChars)# Mid 625 Min Description Determines the lesser of two numbers. Returns The lesser of two numbers. Category Mathematical functions Function syntax Min(number1, number2) See also Max Parameters Parameter Description number1, number2 Numbers Example

Min Example

The maximum of the two numbers is #Max(FORM.myNum1, FORM.myNum2)#

The minimum of the two numbers is #Min(FORM.myNum1, FORM.myNum2)#

Please enter two numbers

Enter two numbers, and see the maximum and minimum of the two numbers

Number 1
Number 2
626 Chapter 3: ColdFusion Functions Minute Description Extracts the minute value from a date/time object. Returns The ordinal value of the minute, in the range 0–59. Category Date and time functions Function syntax Minute(date) See also DatePart, Hash, Second Parameters Parameter Description date • A date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

Minute Example

The time is currently #TimeFormat(Now())#. We are in hour #Hour(Now())#, Minute #Minute(Now())# and Second #Second(Now())# of the day. Minute 627 Month Description Extracts the month value from a date/time object. Returns The ordinal value of the month, in the range 1 (January) – 12 (December). Category Date and time functions Function syntax Month(date) See also DatePart, MonthAsString, Quarter Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Note: You can pass the CreateDate function or the Now function as the date parameter of this function; for example: #Month(CreateDate(2001, 3, 3))# Example

Month Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(yourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(yourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year 628 Chapter 3: ColdFusion Functions MonthAsString Description Determines the name of the month that corresponds to month_number. Returns A string; the name of a month. Category Date and time functions, String functions Function syntax MonthAsString(month_number) See also DatePart, Month, Quarter Parameters Parameter Description month_number An integer in the range 1 – 12. Example

MonthAsString Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayofWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(yourDate)# (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
This is a leap year This is not a leap year MonthAsString 629 Now Description Gets the current date and time of the computer running the ColdFusion server. The return value can be passed as a parameter to date functions such as DaysInYear or FirstDayOfMonth. Returns A date/time object; the current date and time of the computer running the ColdFusion server. Category Date and time functions Function syntax Now() See also CreateDateTime, DatePart Example

Now Example

Now returns the current date and time as a valid date/time object.

The current date/time value is #Now()#

You can also represent this as #DateFormat(Now())#, #TimeFormat(Now())# 630 Chapter 3: ColdFusion Functions NumberFormat Description Creates a custom-formatted number value. Supports the numeric formatting used in the U.S. For international number formatting, see LSNumberFormat. Returns A formatted number value: • If no mask is specified, returns the value as an integer with a thousands separator. • If the parameter value is "" (an empty string), returns 0. Category Display and formatting functions Function syntax NumberFormat(number [, mask ]) See also DecimalFormat, DollarFormat, IsNumeric, LSNumberFormat History ColdFusion MX: Changed behavior: if the mask format cannot correctly mask a number, this function returns the number unchanged. (It does not truncate the number nor throw an error.) (If no mask is selected, ColdFusion MX rounds the decimal part as ColdFusion 5 does. For example, it rounds 34.567 to 35.) Parameters Parameter Description number A number. mask A string or a variable that contains one. Set of characters that determine how ColdFusion displays the number The following table explains mask characters: Mask character Meaning _ (underscore) Optional. Digit placeholder. 9 Optional. Digit placeholder. (Shows decimal places more clearly than _.) . Location of a mandatory decimal point. 0 Located to the left or right of a mandatory decimal point. Pads with zeros. () If number is less than zero, puts parentheses around the mask. + Puts plus sign before positive number; minus sign before negative number. - Puts a space before positive number; minus sign before negative number. , Separates every third decimal place with a comma. L,C Left-justifies or center-justifies number within width of mask column. First character of mask must be L or C. Default: right-justified. NumberFormat 631 Mask character Meaning $ Puts a dollar sign before formatted number. First character of mask must be the dollar sign ($). ^ Separates left and right formatting. Note: If you do not specify a sign for the mask, positive and negative numbers do not align in columns. To put a plus sign or space before positive numbers and a minus sign before negative numbers, use the plus or minus sign, respectively. Usage This function uses Java standard locale formatting rules on all platforms. The position of symbols in format masks determines where the codes take effect. For example, if you put a dollar sign at the far left of a format mask, ColdFusion displays a dollar sign at the left edge of the formatted number. If you separate the dollar sign on the left edge of the format mask by at least one underscore, ColdFusion displays the dollar sign just to the left of the digits in the formatted number. These examples show how symbols determine formats: Number Mask Result 4.37 $____.__ "$ 4.37" 4.37 _$___.__ " $4.37" The positioning can also show where to place the minus sign for negative numbers: Number Mask Result -4.37 -____.__ "- 4.37" -4.37 _-___.__ " -4.37" The positions for a symbol are: far left, near left, near right, and far right. The left and right positions are determined by the side of the decimal point on which the code character is shown. For formats that do not have a fixed number of decimal places, you can use a caret (^) to separate the left fields from the right. An underscore determines whether the code is placed in the far or near position. Most code characters’ effect is determined by the field in which they are located. This example shows how to specify where to put parentheses to display negative numbers: 632 Number Mask Result 3.21 C(__^__) "( 3.21 )" 3.21 C__(^__) " (3.21 )" 3.21 C(__^)__ "( 3.21) " 3.21 C__(^)__ " (3.21) " Chapter 3: ColdFusion Functions When converting from string to double, to prevent rounding errors, this function adds a rounding factor of 1.5543122344752E-014 to the converted number. For example, without adding the rounding factor, converting the string value 1.275 to double with two digits of precision results in a value of 1.27499999999999999, which would be rounded up to 1.27. By adding the rounding factor, the conversion correctly results in a value of 1.28. If you round off a double such as 1.99499999999999999999999999999, where the last decimal is 10E-14, the rounding factor can cause an incorrect result. To set the default display format of date, time, number, and currency values, use the SetLocale function. Example

NumberFormat Example

#counter# * Square Root of 2: #NumberFormat(CounterRoot2,
‘_____.__’)#
#counter# * Square Root of 2: #NumberFormat(CounterRoot2)#
NumberFormat 633 ParagraphFormat Description Replaces characters in a string: • Single newline characters (CR/LF sequences) with spaces • Double newline characters with HTML paragraph tags (

) Returns A copy of the string, with characters converted. Category Display and formatting functions, String functions Function syntax ParagraphFormat(string) See also StripCR Parameters Parameter Description string A string or a variable that contains one Usage This function is useful for displaying data entered in textarea fields. Example

ParagraphFormat Example

Enter text into this textarea, and see it returned as HTML.

Your text area, formatted

#ParagraphFormat(FORM.myTextArea)#

634 Chapter 3: ColdFusion Functions ParameterExists Description This function is deprecated. Use the IsDefined function. Determines whether a parameter exists. ColdFusion does not evaluate the argument. History ColdFusion MX: Deprecated this function. It might not work, and might cause an error, in later releases. ParameterExists 635 ParseDateTime Description Parses a date/time string according to the English (U.S.) locale conventions. (To format a date/ time string for other locales, use the LSParseDateTime function.) Returns A date/time object Category Date and time functions, Display and formatting functions Function syntax ParseDateTime(date/time-string [, pop-conversion ] ) See also IsDate, IsNumericDate, SetLocale Parameters Parameter Description date/time string A string containing a date/time value formatted according to U.S. locale conventions. Can represent a date/time in the range 100 AD–9999 AD. Years 0-29 are interpreted as 2000-2029; years 30-99 are interpreted as 19901999. pop-conversion • pop: Specifies that the date/time string is in POP format, which includes the local time of the sender and a time-zone offset from UTC. ColdFusion applies the offset and returns a value with the UTC time. • standard: (the default) function does no conversion. Usage This function is similar to CreateDateTime, but it takes a string instead of enumerated date/time values. These functions are provided primarily to increase the readability of code in compound expressions. To calculate a difference between time zones, use the GetTimeZoneInfo function. To set the default display format of date, time, number, and currency values, use the SetLocale function. Note: This function does not accept POP dates. Example

ParseDateTime Example

The expression #DE(form.theTestValue)# is a valid date

The parsed date/time is: #ParseDateTime(form.theTestValue)#

The expression #DE(form.theTestValue)# is not a valid date

636 Chapter 3: ColdFusion Functions

Enter an expression, and discover if it can be evaluated to a date value.

ParseDateTime 637 Pi Description Gets the mathematical constant π, accurate to 15 digits. Returns The number 3.14159265358979. Category Mathematical functions Function syntax Pi() See also ASin, Cos, Sin, Tan Example

Pi Example

The Pi function Returns the number #NumberFormat(Pi(), "_._______________")#, the mathematical constant pi, accurate to 15 digits. 638 Chapter 3: ColdFusion Functions PreserveSingleQuotes Description Prevents ColdFusion from automatically escaping single quotation mark characters that are contained in a variable. ColdFusion does not evaluate the argument. Returns (None) Category Other functions Function syntax PreserveSingleQuotes(variable) History ColdFusion MX: Changed behavior: ColdFusion automatically escapes simple-variable, arrayvariable, and structure-variable references within a cfquery tag body or block. (Earlier releases did not automatically escape array-variable references.) Parameters Parameter Description variable Variable that contains a string in which to preserve single quotation marks. Usage This function is useful in SQL statements to defer evaluation of a variable reference until runtime. This prevents errors that result from the evaluation of a single-quote or apostrophe data character (for example, "Joe’s Diner") as a delimiter. Example A: Consider this code: PreserveSingleQuotes(#mystring#) is #PreserveSingleQuotes(mystring)# The output is as follows: PreserveSingleQuotes(#mystring#) is 'Newton's Law', 'Fermat's Theorem' Example B: Consider this code: ColdFusion escapes the single-quote characters in the list as follows: ""1"", ""2"", ""3"" The cfquery tag throws an error. You code this function correctly as follows: PreserveSingleQuotes 639 This function ensures that ColdFusion evaluates the code as follows: '1', '2', '3' Example

PreserveSingleQuotes Example

This is a useful function for creating lists of information to return from a query. In this example, we pick the list of Centers in Suisun, San Francisco, and San Diego, using the SQL grammar IN to modify a WHERE clause, rather than looping through the result set after the query is run. SELECT Name, Address1, Address2, City, Phone FROM Centers WHERE City IN (#PreserveSingleQuotes(List)#)

We found #GetCenters.RecordCount# records.

#Name#
#Address1#
#Address2# #City#
#Phone#
640 Chapter 3: ColdFusion Functions Quarter Description Calculates the quarter of the year in which a date falls. Returns An integer, 1–4. Category Date and time functions Function syntax Quarter(date) See also DatePart, Month Parameters Parameter Description date A date/time object in the range 100 AD–9999 AD. Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

Quarter Example

Today, #DateFormat(Now())#, is in Quarter #Quarter(Now())#. Quarter 641 QueryAddColumn Description Adds a column to a query and populates its rows with the contents of a one-dimensional array. Pads query columns, if necessary, to ensure that all columns have the same number of rows. Returns The number of the column that was added. Category Query functions Function syntax QueryAddColumn(query, column-name, array-name) See also QueryNew, QueryAddRow, QuerySetCell History ColdFusion MX: Changed behavior: if a user attempts to add a column whose name is invalid, ColdFusion throws an error. (In earlier releases, ColdFusion permitted the add operation, but the user could not reference the column after adding it.) Parameters Parameter Description query Name of a query that was created with QueryNew. column-name Name of the new column. array-name Name of an array whose elements are to populate the new column. Usage You can add columns to query objects such as queries retrieved with the cfquery tag or queries created with the QueryNew function. You cannot us the QueryAddColumn function on a cached query. Useful for generating a query object from the arrays of output parameters that Oracle stored procedures can generate. Example

QueryAddColumn Example

This example adds three columns to a query object and then populates the columns with the contents of three arrays.

After populating the query, the example shows, in tabular format, the contents of the columns.

642 Chapter 3: ColdFusion Functions
Fast Food Fine Cuisine Health Food
#FastFood# #FineCuisine# #HealthFood#

Note: Because there are fewer elements in the Fine Cuisine and Health Food arrays, QueryAddColumn added padding to the corresponding columns in the query.

QueryAddColumn 643 QueryAddRow Description Adds a specified number of empty rows to a query. Returns The number of rows in the query Category Query functions Function syntax QueryAddRow(query [, number ]) See also QueryAddColumn, QueryAddRow, QuerySetCell, QueryNew Parameters Parameter Description query Name of an executed query. number Number of rows to add to the query. Default: 1. Example

QueryAddRow Example

SELECT Course_ID, Descript FROM Courses

The Query "GetCourses" has #GetCourses.RecordCount# rows.

After the QueryAddRow action, the query has #GetCourses.RecordCount# records.

#Course_ID# #Course_Number# #Descript#
644 Chapter 3: ColdFusion Functions QueryNew Description Creates an empty query (query object). Returns An empty query with a set of named columns, or an empty query. Category Query functions Function syntax QueryNew(columnlist) See also QueryAddColumn, QueryAddRow, QuerySetCell Parameters Parameter Description columnlist A string or a variable that contains one. Delimited list of column names, or an empty string. Usage If you specify an empty string, you can add a column to the query and populate its rows with the contents of a one-dimensional array using QueryAddColumn. Example

QueryNew Example

We will construct a new query with two rows:

#name##address##phone#
To get any element in the query, we can output it individually

#MyQuery.name[2]#’s phone number: #MyQuery.phone[2]# QueryNew 645 QuerySetCell Description Sets a cell to a value. If no row number is specified, the cell on the last row is set. Returns True, if successful; False, otherwise. Category Query functions Function syntax QuerySetCell(query, column_name, value [, row_number ]) See also QueryAddColumn, QueryAddRow, QueryNew Parameters Parameter Description query Name of an executed query column_name Name of a column in the query value Value to set in the cell row_number Row number. Default: last row. Example SELECT Course_ID, Descript FROM Courses

The Query "GetCourses" has #GetCourses.RecordCount# rows.

After the QueryAddRow action, the query has #GetCourses.RecordCount# records.

#Course_ID# #Course_Number# #Descript#
646 Chapter 3: ColdFusion Functions QuotedValueList Description Gets the values of each record returned from an executed query. ColdFusion does not evaluate the arguments. Returns A delimited list of the values of each record returned from an executed query. Each value is enclosed in single quotation marks. Category Query functions Function syntax QuotedValueList(query.column [, delimiter ]) See also ValueList Parameters Parameter Description query.column Name of an executed query and column. Separate query name and column name with a period. delimiter A string or a variable that contains one. Character(s) that separate column data. Example

QuotedValueList Example

SELECT Dept_ID FROM Departments WHERE Dept_ID IN (#PreserveSingleQuotes(List)#) SELECT * FROM CourseList WHERE Dept_ID IN (#QuotedValueList(GetDepartments.Dept_ID)#)
#Course_ID##Dept_ID##CorNumber##CorName#
QuotedValueList 647 Rand Description Generates a random number. Returns A random decimal number, in the range 0 – 1. Category Mathematical functions Function syntax Rand() See also Randomize, RandRange Usage To ensure greater randomness, call the Randomize function before calling Rand. Example

Rand Example

Rand() returns a random number in the range 0 to 1.

Rand() returned: #Rand()#

Try again 648 Chapter 3: ColdFusion Functions Randomize Description Seeds the ColdFusion random number generator with an integer number. Seeding the generator helps ensure that the Rand function generates highly random numbers. Returns A non-random decimal number, in the range 0 – 1. Category Mathematical functions Function syntax Randomize(number) See also Rand, RandRange Parameters Parameter Description number A number Usage Call this function before calling Rand. Although this function returns a decimal number, it is not a random number. Example

Randomize Example

Call Randomize to seed the random number generator. This helps to ensure the randomness of numbers generated by Rand.

Seed value is #FORM.myRandomInt#
Next random number is #Rand()#

Please enter a number.

Enter a number to seed the randomizer:

Randomize 649 RandRange Description Generates a random integer between two specified numbers. Requests for random integers that are greater than 100,000,000 result in non-random numbers, to prevent overflow during internal computations. Returns A random integer Category Mathematical functions Function syntax RandRange(number1, number2) See also Rand, Randomize Parameters Parameter Description number1, number2 Integer numbers less than 100,000,000 Example

RandRange Example

RandRange returns an integer between two specified integers.

RandRange returned: #RandRange(FORM.myInt, FORM.myInt2)#

Enter a number to seed the randomizer:

650 Chapter 3: ColdFusion Functions REFind Description Uses a regular expression (RE) to search a string for a pattern. The search is case sensitive. For more information on regular expressions, including escape sequences, anchors, and modifiers, see Chapter 7, “Using Regular Expressions in Functions,” in Developing ColdFusion MX Applications. Returns Depends on the value of the returnsubexpressions parameter: • If returnsubexpressions = "False": The position in the string where the match begins ■ 0, if the regular expression is not matched in the string If returnsubexpressions = "True": a structure that contains two arrays, len and pos. The array elements are as follows: ■ If the regular expression is found in the string, the first element of the len and pos arrays contains the length and position, respectively, of the first match of the entire regular expression. If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group. ■ If the regular expression is not found in the string, the first element of the len and pos arrays contains 0. ■ • Category String functions Function syntax REFind(reg_expression, string [, start ] [, returnsubexpressions ] ) See also Find, FindNoCase, REFindNoCase, REReplace, REReplaceNoCase Parameters Parameter Description reg_expression Regular expression for which to search. Case-sensitive. string A string, or a variable that contains one, in which to search. REFind 651 Parameter Description start Optional. A positive integer, or a variable that contains one. Position in the string at which to start search. Default: 1. returnsubexpressions Optional. Boolean. Whether to return substrings of reg_expression, in arrays named len and pos: • True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match. If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group. If the regular expression is not found, the arrays each contain one element with the value 0. • False: the function returns the position in the string where the match begins. Default. Usage This function finds the first occurrence of a regular expression in a string. To find the second and subsequent instances of the expression or of subexpressions in it, you call this function more than once, each time with a different start position. To determine the next start position, use the returnsubexpressions parameter, and add the value returned in the first element of the length array to the value in the first element of the position array. Example

REFind Example

This example shows the use of the REFind function with and without the returnsubexpressions parameter set to True. If you do not use the returnsubexpressions parameter, REFind returns the position of the first occurrence of a regular expression in a string starting from the specified position. Returns 0 if no occurrences are found.

REFind("a+c+", "abcaaccdd"): #REFind("a+c+", "abcaaccdd")#

REFind("a+c*", "abcaaccdd"): #REFind("a+c*", "abcaaccdd")#

REFind("[[:upper:]]", "abcaacCDD"): #REFind("[[:upper:]]", "abcaacCDD")#

REFind("[\?&]rep = ", "report.cfm?rep = 1234&u = 5"): #REFind("[\?&]rep = ", "report.cfm?rep = 1234&u = 5")#


If you use the returnssubexpression parameter, REFind returns the position and length of the first occurrence of a regular expression in a string starting from the specified position. The position and length variables are stored in a structure. To access position and length information, use the keys pos and len, respectively.

The string in which the function is to search is: #teststring#.

The first call to REFind to search this string is: REFind("[A-Za-z]+",testString,1,"TRUE")

This function returns a structure that contains two arrays: pos and len.

To create this structure you can use a CFSET statement, for example:

<CFSET st = REFind("[[:alpha:]]",testString,1,"TRUE")> 652 Chapter 3: ColdFusion Functions

The number of elements in each array: #ArrayLen(st.pos)#.

The number of elements in the pos and len arrays is always one if you do not use parentheses in the regular expression.

The value of st.pos[1] is: #st.pos[1]#.

The value of st.len[1] is: #st.len[1]#.

Substring is [#Mid(testString,st.pos[1],st.len[1])#]


However, if you use parentheses in the regular expression, the first element contains the position and length of the first instance of the whole expression. The position and length of the first instance of each parenthesized subexpression within is included in additional array elements.

For example: <CFSET st1 = REFind("([[:alpha:]])[ ]+(\1)",testString,1,"TRUE")>

The number of elements in each array is #ArrayLen(st1.pos)# .

First whole expression match; position is #st1.pos[1]#; length is #st1.len[1]#; whole expression match is [#Mid(testString,st1.pos[1],st1.len[1])#]

Subsequent elements of the arrays provide the position and length of the first instance of each parenthesized subexpression therein.

Position is #st1.pos[i]#; Length is #st1.len[i]#; Substring is [#Mid(testString,st1.pos[i],st1.len[i])#]


REFind 653 REFindNoCase Description Uses a regular expression (RE) to search a string for a pattern, starting from a specified position. The search is case-insensitive. For more information on regular expressions, including escape sequences, anchors, and modifiers, see Chapter 7, “Using Regular Expressions in Functions,” in Developing ColdFusion MX Applications. Returns Depends on the value of the returnsubexpressions parameter: • If returnsubexpressions = "False": The position in the string where the match begins ■ 0, if the regular expression is not matched in the string If returnsubexpressions = "True": a structure that contains two arrays, len and pos. The array elements are as follows: ■ If the regular expression is found in the string, the first element of the len and pos arrays contains the length and position, respectively, of the first match of the entire regular expression. ■ If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group. ■ If the regular expression is not found in the string, the first element of the len and pos arrays contains 0. ■ • Category String functions Function syntax REFindNoCase(reg_expression, string [, start] [, returnsubexpressions] ) See also Find, FindNoCase, REFind, REReplace, REReplaceNoCase Parameters 654 Parameter Description reg_expression Regular expression for which to search. Case-insensitive. For more information, see Chapter 7, “Using Regular Expressions in Functions,” in Developing ColdFusion MX Applications. string A string or a variable that contains one. String in which to search. Chapter 3: ColdFusion Functions Parameter Description start Optional. A positive integer or a variable that contains one. Position at which to start search. Default: 1. returnsubexpressions Optional. Boolean. Whether to return substrings of reg_expression, in arrays named len and pos: • True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match. If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group. If the regular expression is not found, the arrays each contain one element with the value 0. • False: the function returns the position in the string where the match begins. Default. Usage This function finds the first occurrence of a regular expression in a string. To find the second and subsequent instances of the expression or of subexpressions in it, you call this function more than once, each time with a different start position. To determine the next start position, use the returnsubexpressions parameter, and add the value returned in the first element of the length array to the value in the first element of the position array. Example

REFindNoCase Example

This example demonstrates the use of the REFindNoCase function with and without the returnsubexpressions parameter set to True.

If you do not use the returnsubexpressions parameter, REFindNoCase returns the position of the first occurrence of a regular expression in a string starting from the specified position. Returns 0 if no occurrences are found.

REFindNoCase("a+c+", "abcaaccdd"): #REFindNoCase("a+c+", "abcaaccdd")#

REFindNoCase("a+c*", "abcaaccdd"): #REFindNoCase("a+c*", "abcaaccdd")#

REFindNoCase("[[:alpha:]]+", "abcaacCDD"): #REFindNoCase("[[:alpha:]]+", "abcaacCDD")#

REFindNoCase("[\?&]rep = ", "report.cfm?rep = 1234&u = 5"): #REFindNoCase("[\?&]rep = ", "report.cfm?rep = 1234&u = 5")#


If you do use the returnssubexpression parameter, REFindNoCase returns the position and length of the first occurrence of a regular expression in a string starting from the specified position. The position and length variables are stored in a structure. To access position and length information, use the keys pos and len, respectively.

The string in which the function is to search is: #teststring#.

The first call to REFindNoCase to search this string is: REFindNoCase("[[:alpha:]]+",testString,1,"True")

This function returns a structure that contains two arrays: pos and len.

To create this structure you can use a CFSET statement, for example:

<CFSET st = REFindNoCase("[[:alpha:]]+",testString,1,"True")> REFindNoCase 655

The number of elements in each array: #ArrayLen(st.pos)#.

The number of elements in the pos and len arrays will always be one, if you do not use parentheses to denote subexpressions in the regular expression.

The value of st.pos[1] is: #st.pos[1]#.

The value of st.len[1] is: #st.len[1]#.

Substring is [#Mid(testString,st.pos[1],st.len[1])#]


However, if you use parentheses to denote subexpressions in the regular expression, the first element contains the position and length of the first instance of the whole expression. The position and length of the first instance of each subexpression within will be included in additional array elements.

For example: <CFSET st1 = REFindNoCase("([[:alpha:]]+)[ ]+(\1)",testString,1,"True")>

The number of elements in each array is #ArrayLen(st1.pos)# .

First whole expression match; position is #st1.pos[1]#; length is #st1.len[1]#; whole expression match is [#Mid(testString,st1.pos[1],st1.len[1])#]

Subsequent elements of the arrays provide the position and length of the first instance of each parenthesized subexpression therein.

Position is #st1.pos[i]#; Length is #st1.len[i]#; Substring is [#Mid(testString,st1.pos[i],st1.len[i])#]


656 Chapter 3: ColdFusion Functions ReleaseComObject Description Releases a COM Object and frees up resources that it used. Returns Nothing. Category Extensibility functions Function syntax ReleaseComObject(objectName) See also CreateObject, cfobject History ColdFusion MX 6.1: Added this function. Parameters Parameter Description objectName Variable name of a COM object that was created using the CreateObject function or cfobject tag. Usage This function forcefully terminates and releases the specified COM object and all COM objects that it created. Use this function when the object is no longer in use, to quickly free up resources. If the COM object has a method, such as a quit method, that terminates the program, call this method before you call the ReleaseComObject function. This function can improve processing efficiency, but is not required for an application to work. If you do not use this function, the Java garbage collection mechanism eventually frees the resources. If you use this function on an object that is in use, the object is prematurely released and your application will get exceptions. Example

ReleaseComObject Example

obj = CreateObject("Com", "excel.application.9"); //code that uses the object goes here obj.quit(); ReleaseObject(obj); ReleaseComObject 657 RemoveChars Description Removes characters from a string. Returns A copy of the string, with count characters removed from the specified start position. If no characters are found, returns zero. Category String functions Function syntax RemoveChars(string, start, count) See also Insert, Len Parameters Parameter Description string A string or a variable that contains one. String in which to search. start A positive integer or a variable that contains one. Position at which to start search. count Number of characters to remove Example

RemoveChars Example

Returns a string with count characters removed from the start position. Returns 0 if no characters are found.

Your string is only #Len(FORM.myString)# characters long. Please enter a longer string, select fewer characters to remove or begin earlier in the string.

Your original string: #FORM.myString#

Your modified string:#RemoveChars(FORM.myString, FORM.numChars, FORM.start)# 658 Chapter 3: ColdFusion Functions RepeatString Description Creates a string that contains a specified number of repetitions of the specified string. Returns A string. Category String functions Function syntax RepeatString(string, count) See also CJustify, LJustify, RJustify Parameters Parameter Description string A string or a variable that contains one count Number of repeats Example

RepeatString Example

RepeatString returns a string created from string, repeated a specified number of times.

  • RepeatString("-", 10): #RepeatString("-", 10)#
  • RepeatString("<BR>", 3): #RepeatString("
    ", 3)#
  • RepeatString("", 5): #RepeatString("", 5)#
  • RepeatString("abc", 0): #RepeatString("abc", 0)#
  • RepeatString("Lorem Ipsum", 2): #RepeatString("Lorem Ipsum", 2)#
RepeatString 659 Replace Description Replaces occurrences of substring1 in a string with substring2, in a specified scope. The search is case-sensitive. Returns The string, after making replacements. Category String functions Function syntax Replace(string, substring1, substring2 [, scope ]) See also Find, REFind, ReplaceNoCase, ReplaceList, REReplace Parameters Parameter Description string A string or a variable that contains one. String in which to search substring1 A string or a variable that contains one. String for which to search substring2 String that replaces substring1 scope • one: replace the first occurrence (default) • all: replace all occurrences Usage To remove a string, specify the empty string ("") as substring2. You do not need to escape comma characters in strings. For example, the following code deletes the commas from the sentence: replace("The quick brown fox jumped over the lazy cow, dog, and cat.",",","","All") Example

Replace Example

The Replace function returns string with substring1 replaced by substring2 in the specified scope. This is a case-sensitive search.

Your original string, #FORM.MyString#

You wanted to replace the substring #FORM.MySubstring1# with the substring #FORM.MySubstring2#.

The result: #Replace(FORM.myString, FORM.MySubstring1, FORM.mySubString2)# 660 Chapter 3: ColdFusion Functions ReplaceList Description Replaces occurrences of the elements from a delimited list in a string with corresponding elements from another delimited list. The search is case-sensitive. Returns A copy of the string, after making replacements. Category List functions, String functions Function syntax ReplaceList(string, list1, list2) See also Find, REFind, Replace, REReplace Parameters Parameter Description string A string, or a variable that contains one, within which to replace substring list1 Comma-delimited list of substrings for which to search list2 Comma-delimited list of replacement substrings Usage The list of substrings to replace is processed sequentially. If a list1 element is contained in list2 elements, recursive replacement might occur. The second example shows this. Example

The ReplaceList function returns string with substringlist1 (e.g. "a,b") replaced by substringlist2 (e.g. "c,d") in the specified scope.

Your original string, #FORM.MyString#

You wanted to replace the substring #FORM.MySubstring1# with the substring #FORM.MySubstring2#.

The result: #Replacelist(FORM.myString, FORM.MySubstring1, FORM.mySubString2)#

String 1

Substring 1 (find this list of substrings)

Substring 2 (replace with this list of substrings)

Replacelist Example Two

ReplaceList 661 #replacelist(stringtoreplace,"dog,brown,fox,black", "cow,black,ferret,white")# 662 Chapter 3: ColdFusion Functions ReplaceNoCase Description Replaces occurrences of substring1 with substring2, in the specified scope. The search is caseinsensitive. Returns A copy of the string, after making replacements. Category String functions Function syntax ReplaceNoCase(string, substring1, substring2 [, scope ]) See also Find, REFind, Replace, ReplaceList, REReplace Parameters Parameter Description string A string (or variable that contains one) within which to replace substring substring1 String (or variable that contains one) to replace, if found. substring2 String (or variable that contains one) that replaces substring1 scope • one: Replace the first occurrence (default) • all: Replace all occurrences Example

ReplaceNoCase Example

The ReplaceNoCase function returns string with substring1 replaced by substring2 in the specified scope. The search/replace is case-insensitive.

Your original string, #FORM.MyString#

You wanted to replace the substring #FORM.MySubstring1# with the substring #FORM.MySubstring2#.

The result: #ReplaceNoCase(FORM.myString, FORM.MySubstring1, FORM.mySubString2)# ReplaceNoCase 663 REReplace Description Uses a regular expression (RE) to search a string for a string pattern and replace it with another. The search is case-sensitive. Returns If the scope attribute is set to one, returns a string with the first occurrence of the regular expression replaced by the value of substring. If the scope attribute is set to all, returns a string with all occurrences of the regular expression replaced by the value of substring. If the function finds no matches, it returns a copy of the string unchanged. Category String functions Function syntax REReplace(string, reg_expression, substring [, scope ]) See also REFind, Replace, ReplaceList, REReplaceNoCase History ColdFusion MX: Added supports for the following special codes in a replacement substring, to control case conversion: • • • • • \u - uppercase the next character \l - lowercase the next character \U - uppercase until \E \L - lowercase until \E \E - end \U or \L For more information on new features, see REFind. Parameters Parameter Description string A string or a variable that contains one. String within which to search. reg_expression Regular expression to replace. The search is case-sensitive. substring A string or a variable that contains one. Replaces reg_expression. scope • one: replace the first occurrence (default) • all: replace all occurrences Usage For details on using regular expressions, see Chapter 7, “Using Regular Expressions in Functions,” in Developing ColdFusion MX Applications. 664 Chapter 3: ColdFusion Functions Example

The REReplace function returns string with a regular expression replaced with substring in the specified scope. Case-sensitive search.

REReplace("CABARET","C|B","G","ALL"): #REReplace("CABARET","C|B","G","ALL")#

REReplace("CABARET","[A-Z]","G","ALL"): #REReplace("CABARET","[A-Z]","G","ALL")#

REReplace("I love jellies","jell(y|ies)","cookies"): #REReplace("I love jellies","jell(y|ies)","cookies")#

REReplace("I love jelly","jell(y|ies)","cookies"): #REReplace("I love jelly","jell(y|ies)","cookies")# REReplace 665 REReplaceNoCase Description Uses a regular expression to search a string for a string pattern and replace it with another. The search is case-insensitive. Returns • If scope • • = "one": returns a string with the first occurrence of the regular expression replaced by the value of substring. If scope = "all": returns a string with all occurrences of the regular expression replaced by the value of substring. If the function finds no matches: returns a copy of the string, unchanged. Category String functions Function syntax REReplaceNoCase(string, reg_expression, substring [, scope ]) See also REFind, REFindNoCase, Replace, ReplaceList History ColdFusion MX: Changed behavior: this function inserts the following special characters in regular expression replacement strings, to control case conversion: \u, \U, \l, \L, and \E. If any of these strings is present in a ColdFusion 5 application, you must insert a backslash before it (for example, change "\u" to "\\u"). Parameters Parameter Description string A string or a variable that contains one. reg_expression Regular expression to replace. For more information, see Chapter 7, “Using Regular Expressions in Functions,” in Developing ColdFusion MX Applications. substring A string or a variable that contains one. Replaces reg_expression. scope • one: Replace the first occurrence of the regular expression. Default. • all: Replace all occurrences of the regular expression. Usage For details on using regular expressions, see Chapter 7, “Using Regular Expressions in Functions,” in Developing ColdFusion MX Applications. Example

The REReplaceNoCase function returns string with a regular expression replaced with substring in the specified scope. This is a case-insensitive search.

REReplaceNoCase("cabaret","C|B","G","ALL"): #REReplaceNoCase("cabaret","C|B","G","ALL")#

REReplaceNoCase("cabaret","[A-Z]","G","ALL"): #REReplaceNoCase("cabaret","[A-Z]","G","ALL")#

REReplaceNoCase("I LOVE JELLIES","jell(y|ies)","cookies"): 666 Chapter 3: ColdFusion Functions #REReplaceNoCase("I LOVE JELLIES","jell(y|ies)","cookies")#

REReplaceNoCase("I LOVE JELLY","jell(y|ies)","cookies"): #REReplaceNoCase("I LOVE JELLY","jell(y|ies)","cookies")# REReplaceNoCase 667 Reverse Description Reverses the order of items, such as the characters in a string, the digits in a number, or the elements in an array. Returns A copy of string, with the characters in reverse order. Category String functions Function syntax Reverse(string) See also Left, Mid, Right Parameters Parameter Description string A string or a variable that contains one Usage You can call this function on a number with code such as the following: reverse(6*2) equals #reverse(6*2)# This code outputs the following: reverse(6*2) equals 21 Example

Reverse Example

Reverse returns your string with the positions of the characters reversed.

Reverse returned: #Reverse(FORM.myString)#

Please enter a string to be reversed.

Enter a string to be reversed:

668 Chapter 3: ColdFusion Functions Right Description Gets a specified number of characters from a string, beginning at the right. Returns • If the length of the string is greater than or equal to count, the rightmost count characters of • • the string If count is greater than the length of the string, the whole string If count is greater than 1, and the string is empty, an empty string Category String functions Function syntax Right(string, count) See also Mid, Left, Reverse Parameters Parameter Description string A string or a variable that contains one count A positive integer or a variable that contains one. Number of characters to return. Example

Right Example

Your string #FORM.myText# only has #Len(FORM.myText)# characters. You cannot output the #FORM.removeChars# rightmost characters of this string because it is not long enough

Your original string: #FORM.myText#

Your changed string, showing only the #FORM.removeChars# rightmost characters: #right(Form.myText, FORM.removeChars)#

Please enter a string Right 669 RJustify Description Right justifies characters of a string. Returns A copy of a string, right-justified in the specified field length. Category Display and formatting functions, String functions Function syntax RJustify(string, length) See also CJustify, LJustify Parameters Parameter Description string A string enclosed in quotation marks, or a variable that contains one. length A positive integer or a variable that contains one. Length of field in which to justify string. Example RJustify Example

RJustify Function

Enter a string. It will be right justified within the sample field

670 Chapter 3: ColdFusion Functions Round Description Rounds a number to the closest integer. Returns An integer. Category Mathematical functions Function syntax Round(number) See also Ceiling, Fix, Int Parameters Parameter Description number Number to round Example

Round Example

This function rounds a number to the closest integer.

  • Round(7.49) : #Round(7.49)#
  • Round(7.5) : #Round(7.5)#
  • Round(-10.775) : #Round(-10.775)#
  • Round(1.2345*100)/100 : #Round(1.2345*100)/100#
Round 671 RTrim Description Removes spaces from the end of a string. Returns A copy of string, after removing trailing spaces. Category String functions Function syntax RTrim(string) See also LTrim, Trim Parameters Parameter Description string A string or a variable that contains one Example

RTrim Example

Your string:"#FORM.myText#"
Your string:"#RTrim(FORM.myText)#"
(right trimmed)

Enter some text. It will be modified by Rtrim to remove spaces from the right.

672 Chapter 3: ColdFusion Functions Second Description Extracts the ordinal for the second from a date/time object. Returns An integer in the range 0–59. Category Date and time functions Function syntax Second(date) See also DatePart, Hash, Minute Parameters Parameter Description date A date/time object Usage When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Example

Second Example

The time is currently #TimeFormat(Now())#. We are in hour #Hour(Now())#, Minute #Minute(Now())# and Second #Second(Now())# of the day. Second 673 SetEncoding Description Sets the character encoding (character set) of Form and URL scope variable values; used when the character encoding of the input to a form, or the character encoding of a URL, is not in UTF-8 encoding. Returns None Category International functions, System functions Function syntax SetEncoding(scope_name,charset) See also GetEncoding, cfcontent, cfprocessingdirective, URLDecode, URLEncodedFormat History ColdFusion MX: Added this function. Parameters Parameter Description scope_name • url • form charset The character encoding in which text in the scope variables is encoded. The following list includes commonly used values: • utf-8 • iso-8859-1 • windows-1252 • us-ascii • shift_jis • iso-2022-jp • euc-jp • euc-kr • big5 • euc-cn • utf-16 Usage Use this function when the character encoding of the input to a form or the character encoding of a URL is not in UTF-8 encoding. For example, Traditional Chinese characters are often in Big5 encoding. Before using URL or Form variables, call this function (typically, in the Application.cfm page) to set the encoding and avoid interpreting the characters of the variables incorrectly. For more information on character encoding, see the following web pages: • www.w3.org/International/O-charset.html provides general information on character encoding and the web, and has several useful links. 674 Chapter 3: ColdFusion Functions • 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.4.1/docs/guide/intl/encoding.doc.html lists the character encoding that Java 1.4.1, and therefore the default ColdFusion configuration, can interpret. If you use a JVM that does not conform to the Sun Java 2 Platform, Standard Edition, v 1.4.1, the supported locales may differ. The list uses Java internal names, not the IANA character encoding names that you normally use in the SetEncoding charset parameter and other ColdFusion attributes and parameters. Java automatically converts standard IANA names to its internal names as needed. Example
SetEncoding("url", "big5"); WriteOutput("URL.XXX is " & URL.xxx & "
"); WriteOutput("URL.YYY is " & URL.yyy & "
"); theEncoding = GetEncoding("URL"); WriteOutput("The URL variables were decoded using '" & theEncoding & "' encoding.");
SetEncoding 675 SetLocale Description Sets the country/language locale for ColdFusion processing and the page returned to the client. The locale value determines the default format of date, time, number, and currency values, according to language and regional conventions. Returns The locale value prior to setting the new locale, as a string. Category International functions, System functions Function syntax SetLocale(new_locale) See also GetHttpTimeString, GetLocale History ColdFusion MX: • Changed formatting behavior: this function might return a different value than in earlier • • releases. This function uses Java standard locale determination and formatting rules on all platforms. Deprecated the Spanish (Mexican) locale option. It might not work, and it might cause an error, in later releases. Changed the Spanish (Modern) option: it now sets the locale to Spanish (Standard). Parameters Parameter Description new_locale The name of a locale; for example, "English (US)" Usage You can specify the following locale names: 676 Chinese (China) French (Belgian) Korean Chinese (Hong Kong) French (Canadian) Norwegian (Bokmal) Chinese (Taiwan) French (Standard) Norwegian (Nynorsk) Dutch (Belgian) French (Swiss) Portuguese (Brazilian) Dutch (Standard) German (Austrian) Portuguese (Standard) English (Australian) German (Standard) Spanish (Modern) English (Canadian) German (Swiss) Spanish (Standard) English (New Zealand) Italian (Standard) Swedish English (UK) Italian (Swiss) English (US) Japanese Chapter 3: ColdFusion Functions ColdFusion determines the locale value as follows: • By default, ColdFusion uses the JVM locale, and the default JVM locale is the operating system locale. You can set JVM locale value explicitly in ColdFusion MX in the ColdFusion Administrator Java and JVM Settings page JVM Arguments field; for example: Duser.language=de -Duser.region=DE. • A locale set using the SetLocale function persists for the current request or until it is reset by another SetLocale function in the request. • If a request has multiple SetLocale functions, the current locale setting affects how localesensitive ColdFusion tags and functions, such as the functions that start with LS format data. The last SetLocale function that ColdFusion processes before sending a response to the requestor (typically the client browser) determines the value of the response ContentLanguage HTTP header. The browser that requested the page displays the response according to the rules for the language specified by the Content-Language header. • ColdFusion ignores any SetLocale functions that follow a cfflush tag. Because this function returns the previous locale setting, you can save the original locale value. You can restore the original locale by calling SetLocale again with the saved variable. For example, the following line saves the original locale ins a Session variable: The variable server.ColdFusion.SupportedLocales is initialized at startup with a commadelimited list of the locales that ColdFusion and the operating system support. If you call SetLocale with a locale that is not in the list, the call generates an error. Note: ColdFusion uses the Spanish (Standard) formats for Spanish (Modern) and Spanish (Standard). Example

SetLocale Example

SetLocale sets the locale to the specified new locale for the current session.

A locale encapsulates the set of attributes that govern the display and formatting of date, time, number, and currency values.

The locale for this system is #GetLocale()#

the old locale was #SetLocale("English (UK)")#

The locale is now #GetLocale()# SetLocale 677 SetProfileString Description Sets the value of a profile entry in an initialization file. Returns An empty string, upon successful execution; otherwise, an error message. Category System functions Function syntax SetProfileString(iniPath, section, entry, value) See also GetProfileSections, GetProfileString, SetProfileString Parameters Parameter Description iniPath Absolute path of initialization file section Section of the initialization file in which the entry is to be set entry Name of the entry to set value Value to which to set the entry Example

SetProfileString Example

This example uses SetProfileString to set the timeout value in an initialization file. Enter the full path of your initialization file, specify the timeout value, and submit the form. "boot loader"> = FORM.MyTimeout> GetProfileString(IniPath, Section, "timeout")>

Setting the timeout value to #MyTimeout#

Value returned from SetProfileString: #code#


Timeout value should be greater than zero in order to provide time for user response.


678 Chapter 3: ColdFusion Functions

The timeout value in your initialization file is already #MyTimeout#.

Boot Loader

Timeout is set to: #timeout#.

Default directory is: #default#.


Full Path of Init File
Timeout
SetProfileString 679 SetVariable Description This function is no longer required in well-formed ColdFusion pages. Sets a variable in the name parameter to the value of the value parameter. Returns The new value of the variable. Category Dynamic evaluation functions Function syntax SetVariable(name, value) See also DE, Evaluate, IIf Parameters Parameter Description name Variable name value A string, the name of a string, or a number Usage Before this function is called, the client variable must exist, and the cfapplication tag ClientManagement attribute must be set to "Yes". You can use direct assignment statements in place of this function to set values of dynamically named variables. To do so, put the dynamically named variable in quotation marks and pound signs (#); for example: Also, the following lines are equivalent: SetVariable("myVar" & i, myVal) For more information, see Chapter 4, “Using Expressions and Pound Signs,” in Developing ColdFusion MX Applications. Example

SetVariable Example

680 Chapter 3: ColdFusion Functions

Your variable, #varName#

The value of #varName# is #varNameValue# SetVariable 681 Sgn Description Determines the sign of a number. Returns • 1, if number is positive. • 0, if number is 0. • -1, if number is negative. Category Mathematical functions Function syntax Sgn(number) See also Abs Parameters Parameter Description number A number Example

Sgn Example

Sgn determines the sign of a number. Returns 1 if number is positive; 0 if number is 0; -1 if number is negative.

Sgn(14): #Sgn(14)#

Sgn(21-21): #Sgn(21-21)#

Sgn(-0.007): #Sgn(-0.007)# 682 Chapter 3: ColdFusion Functions Sin Description Calculates the sine of an angle that is entered in radians. Returns A number; the sine of the angle. Category Mathematical functions Function syntax Sin(number) See also ASin, Cos, ACos, Tan, Atn, Pi Parameters Parameter Description number Angle, in radians for which to calculate the sine. Usage The range of the result is -1 to 1. To convert degrees to radians, multiply degrees by π/180. To convert radians to degrees, multiply radians by 180/π. Note: Because the function uses floating point arithmetic, it returns a very small number (such as 6.12323399574E-017) for angles that should produce 0. To test for a 0 value, check whether the value is less than 0.0000000000001. Example

Sin Example

Sin(#FORM.sinNum#) = #sinValue#

You must enter a numeric angle in degrees.

Enter an angle in degrees to get its sine:
Sin 683

   684 Chapter 3: ColdFusion Functions SpanExcluding Description Gets characters from a string, from the beginning to a character that is in a specified set of characters. The search is case-sensitive. Returns A string; characters from string, from the beginning to a character that is in set. Category String functions Function syntax SpanExcluding(string, set) See also GetToken, SpanIncluding Parameters Parameter Description string A string or a variable that contains one set A string or a variable that contains one. Must contain one or more characters Example

SpanExcluding Example

Your string was #FORM.myString#

Your set of characters was #FORM.mySet#

Your string up until one of the characters in the set is: #SpanExcluding(FORM.myString, FORM.mySet)#

Returns all characters from string from beginning to a character from the set of characters. The search is case-sensitive.

Enter a string:

And a set of characters:

SpanExcluding 685 SpanIncluding Description Gets characters from a string, from the beginning to a character that is not in a specified set of characters. The search is case-sensitive. Returns A string; characters from string, from the beginning to a character that is not in set. Category String functions Function syntax SpanIncluding(string, set) See also GetToken, SpanExcluding Parameters Parameter Description string A string or a variable that contains the search string. set A string or a variable that contains a set of characters. Must contain one or more characters Example

SpanIncluding Example

Your string was #FORM.myString#

Your set of characters was #FORM.mySet#

Your string, until the characters in the set have been found, is: #SpanIncluding(FORM.myString, FORM.mySet)#

Returns characters of a string, from beginning to a character that is not in set. The search is case-sensitive.

Enter a string:

And a set of characters:

686 Chapter 3: ColdFusion Functions Sqr Description Calculates the square root of a number. Returns Number; square root of number. Category Mathematical functions Function syntax Sqr(number) See also Abs Parameters Parameter Description number A positive integer or a variable that contains one. Number whose square root to get. Usage The value in number must be greater than or equal to 0. Example

Sqr Example

Returns the square root of a positive number.

Sqr(2): #Sqr(2)#

Sqr(Abs(-144)): #Sqr(Abs(-144))#

Sqr(25^2): #Sqr(25^2)# Sqr 687 StripCR Description Deletes return characters from a string. Returns A copy of string, after removing return characters. Category Display and formatting functions, Other functions, String functions Function syntax StripCR(string) See also ParagraphFormat Parameters Parameter Description string A string or a variable that contains one Usage Useful for preformatted (between

 and 
tags) HTML display of data entered in textarea fields. Example

StripCR Example

Function StripCR is useful for preformatted HTML display of data (PRE) entered in textarea fields.

#StripCR(Form.myTextArea)#
688 Chapter 3: ColdFusion Functions StructAppend Description Appends one structure to another. Returns True, upon successful completion; False, otherwise. Category Structure functions Function syntax StructAppend(struct1, struct2, overwriteFlag) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description struct1 Structure to append. struct2 Structure that contains the data to append to struct1 overwriteFlag • Yes: values in struct2 overwrite corresponding values in struct1. Default. • No Usage This function appends the fields and values of struct2 to struct1; struct2 is not modified. If struct1 already contains a field of struct2, overwriteFlag determines whether the value in struct2 overwrites it. A structure’s keys are unordered. Example StructAppend 689

The person struct before the Append call:
#myItem#

The person struct after the Append call:
#myItem#
690 Chapter 3: ColdFusion Functions StructClear Description Removes all data from a structure. Returns True, on successful execution; False, otherwise. Category Structure functions Function syntax StructClear(structure) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description structure Structure to clear Usage Do not call this function on a session variable. For more information, see TechNote 14143, "ColdFusion 4.5 and the StructClear(Session) function," at www.coldfusion.com/Support/ KnowledgeBase/SearchForm.cfm. (The article applies to ColdFusion 4.5, 5.x, and ColdFusion MX.) Example

Add New Employees

Please fill out the form. employee = StructNew(); StructInsert(employee, "firstname", Form.firstname); StructInsert(employee, "lastname", Form.lastname); StructInsert(employee, "email", Form.email); StructInsert(employee, "phone", Form.phone); StructInsert(employee, "department", Form.department); StructClear 691 StructClear(employee); 692 Chapter 3: ColdFusion Functions StructCopy Description Copies a structure. Copies top-level keys, values, and arrays in the structure by value; copies nested structures by reference. Returns A copy of a structure, with the same keys and values; if structure does not exist, throws an exception. Category Structure functions Function syntax StructCopy(structure) See also Structure functions Parameters Parameter Description structure Structure to copy Usage The following code shows how this function copies a structure that contains a string field, a number field, and a two-dimensional array at the top level: The following code shows how StructCopy copies a nested structure: To copy a structure entirely by value, use Duplicate on page 466. The following table shows how variables are assigned: Variable type Assigned by structure.any_simple_value Boolean Binary Base64 Value structure.array Value structure.nested_structure Reference StructCopy 693 Variable type Assigned by structure.object Reference structure.query Reference Example // This script creates a structure that StructCopy copies by value.
// Create elements. s = StructNew(); s.array = ArrayNew(2); // Assign simple values to original top-level structure fields. s.number = 99; s.string = "hello tommy"; // Assign values to original top-level array. s.array[1][1] = "one one"; s.array[1][2] = "one two";


Original Values
// Simple values
s.number = #s.number#
s.string = #s.string#
// Array value
s.array[1][1] = #s.array[1][1]#
s.array[1][2] = #s.array[1][2]#
// Copy this structure to a new structure.
// Change the values of the original structure.
s.number = 100; s.string = "hello tommy (modified)"; s.array[1][1] = "one one (modified)"; s.array[1][2] = "one two (modified)";

Modified Original Values
// Simple values
s.number = #s.number#
s.string = #s.string#
// Array value
s.array[1][1] = #s.array[1][1]#
s.array[1][2] = #s.array[1][2]#

Copied structure values should be the same as the original.
// Simple values
copied.number = #copied.number#
694 Chapter 3: ColdFusion Functions copied.string = #copied.string#
// Array value
copied.array[1][1] = #copied.array[1][1]#
copied.array[1][2] = #copied.array[1][2]#
// This script creates a structure that StructCopy copies by reference. // Create elements. s = StructNew(); s.nested = StructNew(); s.nested.array = ArrayNew(2); // Assign simple values to nested structure fields. s.nested.number = 99; s.nested.string = "hello tommy"; // Assign values to nested array. s.nested.array[1][1] = "one one"; s.nested.array[1][2] = "one two";
Original Values
// Simple values
s.nested.number = #s.nested.number#
s.nested.string = #s.nested.string#
// Array values
s.nested.array[1][1] = #s.nested.array[1][1]#
s.nested.array[1][2] = #s.nested.array[1][2]#
// Use copied = StructCopy(s)> Duplicate to clone this structure to a new structure.
duplicated = Duplicate(s)> // Change the values of the original structure. s.nested.number = 100; s.nested.string = "hello tommy (modified)"; s.nested.array[1][1] = "one one (modified)"; s.nested.array[1][2] = "one two (modified)";
Modified Original Values
// Simple values
s.nested.number = #s.nested.number#
s.nested.string = #s.nested.string#
// Array value
s.nested.array[1][1] = #s.nested.array[1][1]#
s.nested.array[1][2] = #s.nested.array[1][2]#

Copied structure values should reflect changes to original.
// Simple values
StructCopy 695 copied.nested.number = #copied.nested.number#
copied.nested.string = #copied.nested.string#
// Array values
copied.nested.array[1][1] = #copied.nested.array[1][1]#
copied.nested.array[1][2] = #copied.nested.array[1][2]#

Duplicated structure values should remain unchanged.
// Simple values
duplicated.nested.number = #duplicated.nested.number#
duplicated.nested.string = #duplicated.nested.string#
// Array value
duplicated.nested.array[1][1] = #duplicated.nested.array[1][1]#
duplicated.nested.array[1][2] = #duplicated.nested.array[1][2]#
696 Chapter 3: ColdFusion Functions StructCount Description Counts the keys in a structure. Returns A number; if structure does not exist, throws an exception. Category Structure functions Function syntax StructCount(structure) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description structure Structure to access Example

This file is similar to addemployee.cfm, which is called by StructNew, StructClear, and StructDelete. To test, copy StructCount function to appropriate place in addemployee.cfm. StructCount 697 StructDelete Description Removes an element from a structure. Returns Boolean value. The value depends on the indicatenotexisting parameter value. Category Structure functions Function syntax StructDelete(structure, key [, indicatenotexisting ]) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description structure Structure or a variable that contains one. Contains element to remove key Element to remove indicatenotexisting • True: return Yes if key exists; No if it does not. • False: return Yes regardless of whether key exists. Default. Example

StructDelete Function

Field to be deleted: #form.field#

employee = StructNew(); StructInsert(employee, "firstname", firstname); StructInsert(employee, "lastname", lastname); StructInsert(employee, "email", email); StructInsert(employee, "phone", phone); StructInsert(employee, "department", department); Before deletion, employee structure looks like this:
698 Chapter 3: ColdFusion Functions Did I delete the field "#form.field#"? The code indicates: #rc#
The structure now looks like this:



Select the field to be deleted: 

Delete this comment to make this page work ---> StructDelete 699 StructFind Description Determines the value associated with a key in a structure. Returns The value associated with a key in a structure; if structure does not exist, throws an exception. Category Structure functions Function syntax StructFind(structure, key) See also Structure functions Parameters Parameter Description structure Structure that contains the value to return key Key whose value to return Usage A structure’s keys are unordered. Example

This file is identical to addemployee.cfm, which is called by StructNew, StructClear, and StructDelete. It adds employees. Employee information is passed through the employee structure (EMPINFO attribute). In UNIX, you must also add the Emp_ID. 700 Chapter 3: ColdFusion Functions StructFindKey Description Searches recursively through a substructure of nested arrays, structures, and other elements, for structures whose values match the search key in the value parameter. Returns An array that contains structures with values that match value. Category Structure functions Function syntax StructFindKey(top, value, scope) See also Structure functions Parameters Parameter Description top ColdFusion object (structure or array) from which to start search. This attribute requires an object, not a name of an object. value String or a variable that contains one for which to search. scope • one: returns one matching key. Default. • all: returns all matching keys Usage Returns an array that includes one structure for each of the specified values it finds. The fields of each of these structures are: • • • Value: value held in the found key string that can be used to reach the found key Owner: parent object that contains the found key A structure’s keys are unordered. Path: Example StructFindKey 701 StructFindValue Description Searches recursively through a substructure of nested arrays, structures, and other elements for structures with values that match the search key in the value parameter. Returns An array that contains structures with values that match the search key value. If none are found, returns an array of size 0. Category Structure functions Function syntax StructFindValue( top, value [, scope]) See also Structure functions Parameters Parameter Description top ColdFusion object (a structure or an array) from which to start search. This attribute requires an object, not a name of an object. value String or a variable that contains one for which to search. The type must be a simple object. Arrays and structures are not supported. scope • one: function returns one matching key (default) • all: function returns all matching keys Usage The fields of each structure in the returned array are: • • • Key: name of the key in which the value was found Path: string which could be used to reach the found key Owner: parent object that contains the found key A structure’s keys are unordered. Example 702 Chapter 3: ColdFusion Functions StructGet Description Gets a structure(s) from a specified path. Returns An alias to the variable in the pathDesired parameter. If necessary, StructGet creates structures or arrays to make pathDesired a valid variable "path." Category Structure functions Function syntax StructGet(pathDesired) See also Structure functions History ColdFusion MX: • Changed behavior: this function can be used on XML objects. • Changed behavior: if there is no structure or array present in oathDesired, this function creates structures or arrays to make pathDesired a valid variable "path." Parameters Parameter Description pathDesired Pathname of variable that contains structure or array from which ColdFusion retrieves structure. Usage You can inadvertently create invalid structures using this function. For example, if array notation is used to expand an existing array, the specified new element is created, regardless of the type currently held in the array. Example Dog is not defined
Dog.Myscope is not defined
Dog.Myscope.Test is not defined
Dog.Myscope.Test.Foo is not defined
#dog.myscope.test.foo#
StructGet 703
#request.myscope[1].test.foo#
#request.myscope[1].test[2].foo#
704 Chapter 3: ColdFusion Functions StructInsert Description Inserts a key-value pair into a structure. Returns True, upon successful completion. If structure does not exist, or if key exists and allowoverwrite = "False", ColdFusion throws an exception. Category Structure functions Function syntax StructInsert(structure, key, value [, allowoverwrite ]) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description structure Structure to contain the new key-value pair. key Key that contains the inserted value. value Value to add. allowoverwrite Optional. Whether to allow overwriting a key. Default: False. Usage A structure’s keys are unordered. Example

Add New Employees

Please fill out the form. employee = StructNew(); StructInsert(employee, "firstname", FORM.firstname); StructInsert(employee, "lastname", FORM.lastname); StructInsert(employee, "email", FORM.email); StructInsert(employee, "phone", FORM.phone); StructInsert(employee, "department", FORM.department); StructInsert 705

First name is #StructFind(employee, "firstname")#

Last name is #StructFind(employee, "lastname")#

EMail is #StructFind(employee, "email")#

Phone is #StructFind(employee, "phone")#

Department is #StructFind(employee, "department")#


First Name: 

Last Name: 

EMail: 

Phone: 

Department: 

706 Chapter 3: ColdFusion Functions StructIsEmpty Description Determines whether a structure contains data. Returns True, if structure is empty; if structure does not exist, ColdFusion throws an exception. Category Decision functions, Structure functions Function syntax StructIsEmpty(structure) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description structure Structure to test Example

This file is identical to addemployee.cfm, which is called by StructNew, StructClear, and StructDelete. It adds employees. Employee information is passed through employee structure (EMPINFO attribute). In UNIX, you must also add the Emp_ID. Error. No employee data was passed. INSERT INTO Employees (FirstName, LastName, Email, Phone, Department) VALUES ( ‘#StructFind(attributes.EMPINFO, "firstname")#’ , ‘#StructFind(attributes.EMPINFO, "lastname")#’ , ‘#StructFind(attributes.EMPINFO, "email")#’ , ‘#StructFind(attributes.EMPINFO, "phone")#’ , ‘#StructFind(attributes.EMPINFO, "department")#’ )


Employee Add Complete StructIsEmpty 707 StructKeyArray Description Finds the keys in a ColdFusion structure. Returns An array of keys; if structure does not exist, ColdFusion throws an exception. Category Structure functions Function syntax StructKeyArray(structure) See also Structure functions Parameters Parameter Description structure Structure from which to extract a list of keys Usage A structure’s keys are unordered. Example

StructKeyArray Example

Extracting the Keys from the Employee Structure

This example uses the StructNew function to create a structure called "employee" that supplies employee info. Its fields are filled by the form. After you enter employee information in structure, the example uses StructKeyArray function to copy all of the keys from the structure into an array.


First Name:
Last Name:
EMail
Phone:
Company:
After you submit the FORM, scroll down to see the array.

Key#i# is #keysToStruct[i]#

Value#i# is #employee[keysToStruct[i]]#

StructKeyArray 709 StructKeyExists Description Determines whether a specific key is present in a structure. Returns True, if key is in structure; if structure does not exist, ColdFusion throws an exception. Category Decision functions, Structure functions Function syntax StructKeyExists(structure, "key") See also Structure functions Parameters Parameter Description structure Name of structure to test key Key to test Usage This function can sometimes be used in place of the IsDefined function, when working with the URL and Form scopes, which are structures. The following pieces of code are equivalent: cfif IsDefined("Form.JediMaster")> A structure’s keys are unordered. Example

This file is similar to addemployee.cfm, which is called by StructNew, StructClear, and StructDelete. To test, copy the <CFELSEif> statement to the appropriate place in addemployee.cfm. It is a custom tag to add employees. Employee information is passed through the employee structure (the EMPINFO attribute). In UNIX, you must also add the Emp_ID. Error. No employee data was passed. StructUpdate(attributes.EMPINFO, "department", "Unassigned"); 710 Chapter 3: ColdFusion Functions StructKeyList Description Extracts keys from a ColdFusion structure. Returns A list of keys; if structure does not exist, ColdFusion throws an exception. Category Structure functions Function syntax StructKeyList(structure [, delimiter]) See also Structure functions Parameters Parameter Description structure Structure from which to extract a list of keys. delimiter Optional. Character that separates keys in list. Default: comma. Usage A structure’s keys are unordered. Example StructKeyList Function

StructKeyList Function

Listing the Keys in the Employees Structure

This example uses StructNew function to create structure "employee" that supplies employee information. The fields are filled with the contents of the following form.

StructKeyList 711

After you enter employee information into structure, example uses StructKeyList function to list keys in structure.

This code does not show how to insert information into a database. See cfquery for more information about database insertion.


First Name:
Last Name:
EMail
Phone:
Company:
After you submit form, scroll down to see the list.

")>

Here are the keys to the structure:

  • #keysToStruct#

If fields are correct, we can process new employee information. If they are not correct, consider rewriting application.

712 Chapter 3: ColdFusion Functions StructNew Description Creates a structure. Returns A structure. Category Structure functions Function syntax StructNew() See also Structure functions Parameters None Example

Add New Employees

Please fill out the form. employee = StructNew(); StructInsert(employee, "firstname", FORM.firstname); StructInsert(employee, "lastname", FORM.lastname); StructInsert(employee, "email", FORM.email); StructInsert(employee, "phone", FORM.phone); StructInsert(employee, "department", FORM.department);

First name is #StructFind(employee, "firstname")#

Last name is #StructFind(employee, "lastname")#

EMail is #StructFind(employee, "email")#

Phone is #StructFind(employee, "phone")#

Department is #StructFind(employee, "department")# StructNew 713 StructSort Description Returns a sorted array of the top level keys in a structure. Sorts using alphabetic or numeric sorting, and can sort based on the values of any structure element. Returns An array of top-level key names (strings), sorted by the value of the specified subelement. Category Structure functions Function syntax StructSort(base, sortType, sortOrder, pathToSubElement) See also Structure functions Parameters Parameter Description base A ColdFusion struct with one field (an associative array). sortType • numeric • text: case sensitive (all lower-case letters precede the first upper-case letter). Default. • textnocase sortOrder • asc: ascending (a to z) sort order. Default. • desc: descending (z to a) sort order pathToSubElement String or a variable that contains one. Path to apply to each top-level key, to reach element value by which to sort. Default: nothing (top-level entries sorted by their own values). Usage The pathToSubElement string does not support array notation, and only supports substructures of structures. This function does not sort or change the structure. Example salaries = StructNew() ; employees = StructNew() ; departments = StructNew() ; for ( i=1; i lt 6; i=i+1 ) { salary = 120000 - i*10000 ; salaries["employee#i#"] = salary ; employee = StructNew() ; employee["salary"] = salary ; // employee.salary = salary ; employees["employee#i#"] = employee ; 714 Chapter 3: ColdFusion Functions departments["department#i#"] = StructNew() ; departments["department#i#"].boss = employee ; }

list of employees based on the salary (text search):
1) #ArrayToList( StructSort( salaries ) )#
2) #ArrayToList( StructSort( salaries, "text", "ASC" ) )#
3) #ArrayToList( StructSort( salaries, "textnocase", "ASC" ) )#
4) #ArrayToList( StructSort( salaries, "text", "DESC" ) )#

list of employees based on the salary (numeric search):
5) #ArrayToList( StructSort( salaries, "numeric", "ASC" ) )#
6) #ArrayToList( StructSort( salaries, "numeric", "DESC" ) )#

list of employees based on the salary (subfield search):
7) #ArrayToList( StructSort( employees, "numeric", "DESC", "salary" ) )#
8) #ArrayToList( StructSort( employees, "text", "ASC", "salary" ) )#

list of departments based on the salary (sub-sub-field search):
9) #ArrayToList( StructSort( departments, "text", "ASC", "boss.salary" ) )#

We have a problem - this was supposed to throw an exception!
ERROR: This error was expected!
#cfcatch.message# - #cfcatch.detail#
StructSort 715 StructUpdate Description Updates a key with a value. Returns True, on successful execution; if the structure does not exist, ColdFusion throws an error. Category Structure functions Function syntax StructUpdate(structure, key, value) See also Structure functions History ColdFusion MX: Changed behavior: this function can be used on XML objects. Parameters Parameter Description structure Structure to update key Key, the value of which to update value New value Example

This file is similar to addemployee.cfm, which is called by StructNew, StructClear, and StructDelete. To test this file, copy the <CFELSEIF> statement to the appropriate place in addemployee.cfm. It is an example of a custom tag used to add employees. Employee information is passed through the employee structure (the EMPINFO attribute). In UNIX, you must also add the Emp_ID. Error. No employee data was passed. StructUpdate(attributes.EMPINFO, "department", "Unassigned"); 716 Chapter 3: ColdFusion Functions Tan Description Calculates the tangent of an angle that is entered in radians. Returns A number; the tangent of an angle. Category Mathematical functions Function syntax Tan(number) See also Atn, Cos, ACos, Sin, ASin, Pi Parameters Parameter Description number Angle, in radians, for which to calculate the tangent. Usage To convert degrees to radians, multiply degrees by π/180. To convert radians to degrees, multiply radians by 180/π. Note: Because the function uses floating point arithmetic, it can return a very small number (such as 6.12323399574E-017) for angles that should produce 0 and can return a very large number (such as 1.63312393532E+016) for infinity or not a number. To test for a 0 value, check whether the value is less than 0.0000000000001. To test for an infinite value, check whether the value is more than 1E15. Example

Tan Example

Tan(#FORM.tanNum#) = #tanValue#

You must enter a numeric angle in degrees.

Enter an angle in degrees to get its tangent: Tan 717


   718 Chapter 3: ColdFusion Functions TimeFormat Description Formats a time value using US English time formatting conventions. Returns A custom-formatted time value. If no mask is specified, returns a time value using the hh:mm tt format. For international time formatting, see LSTimeFormat. Category Date and time functions, Display and formatting functions Function syntax TimeFormat(time [, mask ]) See also CreateTime, Now, ParseDateTime, LSTimeFormat, DateFormat History ColdFusion MX 6.1: Added the mask character L or l to represent milliseconds. ColdFusion MX: • Changed the way extra characters are processed: this function processes extra characters within • the mask value differently than in earlier releases, as follows: ■ ColdFusion 5 and earlier: the function returns the time format and an apostrophe-delimited list of the extra characters. For example, TimeFormat(Now(), "hh:mm:ss dog") returns 8:17:23 d'o'g. ■ ColdFusion MX: the function returns the time format and the extra characters. For example, for the call above, it returns 8:17:23 dog. If the extra characters are single-quoted (for example, hh:mm:ss 'dog'), ColdFusion 5 and ColdFusion MX return the time format and the extra characters: 8:17:23 dog. Added support for the following mask attribute options: short, medium, long, and full. TimeFormat 719 Parameters Parameter Description time A date/time value or string to convert mask Masking characters that determine the format: • h: Hours; no leading zero for single-digit hours (12-hour clock) • hh: Hours; leading zero for single-digit hours (12-hour clock) • H: Hours; no leading zero for single-digit hours (24-hour clock) • HH: Hours; leading zero for single-digit hours (24-hour clock) • m: Minutes; no leading zero for single-digit minutes • mm: Minutes; a leading zero for single-digit minutes • s: Seconds; no leading zero for single-digit seconds • ss: Seconds; leading zero for single-digit seconds • l: Milliseconds • t: One-character time marker string, such as A or P • tt: Multiple-character time marker string, such as AM or PM • short: equivalent to h:mm tt • medium: equivalent to h:mm:ss tt • long: medium followed by three-letter time zone; as in, 2:34:55 PM EST • full: same as long Usage When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object. Database query results for date and time values can vary in sequence and formatting unless you use functions to format the results. To ensure that dates and times display with appropriate formatting, and that users of your ColdFusion application are not confused by dates and times displayed, Macromedia recommends that you use the DateFormat and TimeFormat functions to format date and time values from queries. For more information and examples, see TechNote 22183, "ColdFusion Server (5 and 4.5.x) with Oracle: Formatting Date and Time Query Results," at www.coldfusion.com/Support/KnowledgeBase/SearchForm.cfm. Example

TimeFormat Example

Today’s date is #todayDate#.

Using Timeformat, we can display the value in different ways:

  • #TimeFormat(todayDate)#
  • #TimeFormat(todayDate, "hh:mm:ss")#
  • #TimeFormat(todayDate, "hh:mm:sst")#
  • #TimeFormat(todayDate, "hh:mm:sstt")#
  • #TimeFormat(todayDate, "HH:mm:ss")#
720 Chapter 3: ColdFusion Functions ToBase64 Description Calculates the Base64 representation of a string or binary object. The Base64 format uses printable characters, allowing binary data to be sent in forms and e-mail, and stored in a database or file. The Base64 representation of a string or binary object. Category Conversion functions, Other functions, String functions Function syntax ToBase64(string or binary_object[, encoding]) See also • • • for information about loading and reading binary data for information about serializing and deserializing binary data IsBinary and ToBinary for checking for binary data and converting a Base64 object to binary format cffile cfwddx History ColdFusion MX: Added the encoding attribute. Parameters Parameter Description string or binary_object A string, the name of a string, or a binary object. encoding For a string, defines how characters are represented in a byte array. The following list includes commonly used 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 more information on character encoding, see: www.w3.org/International/O-charset.html. Default: the encoding of the page on which the function is called. See cfcontent on page 87. For a binary object, this parameter is ignored. Usage Base64 provides 6-bit encoding of data. The encoding process represents 24-bit groups of input bits as output strings of 4 encoded ASCII characters. Binary objects and, in some cases, 8-bit characters, cannot be transported over many internet protocols, such as HTTP and SMTP. Using Base64 safely converts the data into a format that is safe over any internet protocol. ToBase64 721 Base64 lets you store binary objects in a database. Note: To reverse Base64 encoding of a string, you can convert it to a binary object, then convert the binary object to a string, using the toString function. Example

ToBase64 Example

The following string is the concatenation of all characters (32 to 255) from the ASCII table.
#charData#

Base64 representations are identical.

Conversion error.

722 Chapter 3: ColdFusion Functions ToBinary Description Calculates the binary representation of Base64-encoded data. Returns The binary representation of Base64-encoded data. Category Conversion functions, Other functions, String functions Function syntax ToBinary(string_in_Base64 or binary_value) See also • • • • for information about loading and reading binary data cfwddx for information about serializing and deserializing binary data IsBinary and ToBase64 for checking format and converting to Base64 Len for determining the length of a binary object cffile Parameters Parameter Description string_in_Base64 or binary_value A string or a variable that contains one: • In Base64 format to convert to binary • In binary format to test whether it is valid Usage Base64 provides 6-bit encoding of 8-bit ASCII characters. From Base64 data, you can recreate the binary object that it represents, such as a GIF, JPG, or executable file. Example

ToBinary Example

The following string is the concatenation of all characters (32 to 255) from the ASCII table.
#charData#

Base64 representation of binary data is identical to the Base64 representation of string data.

ToBinary 723

Conversion error.

724 Chapter 3: ColdFusion Functions ToString Description Converts a value to a string. Returns A string. Category Conversion functions, Other functions, String functions Function syntax ToString(any_value[, encoding]) See also ToBase64, ToBinary History ColdFusion MX: • Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535. (ColdFusion 5 and earlier releases supported ASCII values 1–255.) • Added the encoding attribute. Parameters Parameter Description any_value Value to convert to a string encoding The character encoding (character set) of the string. The following list includes commonly used 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 more information on character encoding, see: www.w3.org/International/O-charset.html. Default: the encoding of the page on which the function is called. See cfcontent on page 87. Usage This function can convert simple values and binary values that do not contain Byte zero. If this function cannot convert a value, it throws an exception. This function can convert an XML document object to a string representation. Note: You can use this function to reverse Base64 encoding of a string. Convert the Base64 encoded object to a binary object, then use this function to convert the binary object to a string. ToString 725 Example

ToString Example

The following string is the concatenation of characters (32 to 255) from the ASCII table.
#charData#

The following string is the Base64 representation of the string.
#data64#

The following is the string representation of the binary data.
#dataString#

726 Chapter 3: ColdFusion Functions Trim Description Removes leading and trailing spaces from a string. Returns A copy of string, after removing leading and trailing spaces. Category String functions Function syntax Trim(string) See also LTrim, RTrim Parameters Parameter Description string A string or a variable that contains one Example

Trim Example

Your string:"#FORM.myText#"
Your string:"#Trim(FORM.myText)#"
(trimmed on both sides)

Type in some text, and it will be modified by trim to remove leading spaces from the left and right

Trim 727 UCase Description Converts the alphabetic characters in a string to uppercase. Returns A copy of a string, converted to uppercase. Category String functions Function syntax UCase(string) See also LCase Parameters Parameter Description string A string or a variable that contains one Example

UCase Example

Your text, #FORM.sampleText#, returned in uppercase is #UCase(FORM.sampleText)#.

Please enter some text.

Enter your sample text, and press "submit" to see the text returned in uppercase:

728 Chapter 3: ColdFusion Functions URLDecode Description Decodes a URL-encoded string. Returns A copy of a string, decoded. Category Conversion functions, Other functions, String functions Function syntax URLDecode(urlEncodedString[, charset]) See also URLEncodedFormat History ColdFusion MX 6.1: Changed the default charset: the default charset is the character encoding of the URL scope. ColdFusion MX: • Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535. (Earlier releases supported ASCII values.) • Added the charset parameter. Parameters Parameter Description urlEncodedString URL-encoded string or a variable that contains one. charset The character encoding in which the URL is encoded. Optional. The following list includes commonly used 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 more information on character encoding, see: www.w3.org/International/O-charset.html. Default: the character encoding of the URL scope. See SetEncoding on page 674. Usage URL encoding formats some characters with a percent sign and the two-character hexadecimal representation of the character. For example, a character whose code is 129 is encoded as %81. A space is encoded with a plus sign. URLDecode 729 Query strings in HTTP are always URL-encoded. Example This example creates, encodes, and decodes a string that contains ASCII character codes. // Build string s = ""; for (c = 1; c lte 256; c = c + 1) { s = s & chr(c); } // Encode string and display result enc = URLEncodedFormat(s); WriteOutput("Encoded string is: '#enc#'.
"); // Decode and compare result with original dec = URLDecode(enc); if (dec neq s) { WriteOutput("Decoded is not the same as encoded."); } else { WriteOutput("All's quiet on the Western front."); }
730 Chapter 3: ColdFusion Functions URLEncodedFormat Description Generates a URL-encoded string. For example, it replaces spaces with %20, and nonalphanumeric characters with equivalent hexadecimal escape sequences. Passes arbitrary strings within a URL (ColdFusion automatically decodes URL parameters that are passed to a page). Returns A copy of a string, URL-encoded. Category Conversion functions, Other functions, String functions Function syntax URLEncodedFormat(string [, charset ]) See also URLDecode History ColdFusion MX 6.1: Changed the default encoding to be the response character encoding. ColdFusion MX: Added the charset parameter. Parameters Parameter Description string A string or a variable that contains one charset The character encoding in which the string is encoded. Optional. The following list includes commonly used 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 more information on character encoding, see: www.w3.org/International/O-charset.html. Default: the character encoding of the response. See cfcontent on page 87. Usage URL encoding formats some characters with a percent sign and the two-character hexadecimal representation of the character. For example, a character whose code is 129 is encoded as %81. A space is encoded with a plus sign. Query strings in HTTP are always URL-encoded. Example

URLEncodedFormat Example

URLEncodedFormat 731

The url variable url.myExample was passed from the previous link ... its value is:
"#url.myExample#"

This function returns a URL encoded string.

Click me 732 Chapter 3: ColdFusion Functions URLSessionFormat Description Depending on whether a client computer accepts cookies, this function does the following: • If the client does not accept cookies: automatically appends all required client identification information to a URL • If the client accepts cookies: does not append information This function automatically determines which identifiers are required, and sends only the required information. It provides a more secure and robust method for supporting client identification than manually encoding the information in each URL, because it sends only required information, when it is required, and it is easier to code. Returns A URL; if cookies are disabled for the browser, client and session data are appended. Category Other functions Function syntax URLSessionFormat(request_URL) Parameters Parameter Description request_URL URL of a ColdFusion page Usage In the following example, the cfform tag posts a request to another page and sends the client identification, if required. If cookie support is detected, the function returns the following: myactionpage.cfm If the detected cookie is not turned on, or cookie support cannot be reliably detected, the function return value is as follows: myactionpage.cfm?jsessionid=xxxx;cfid=xxxx&cftoken=xxxxxxxx Example URLSessionFormat 733 Val Description Converts numeric characters that occur at the beginning of a string to a number. Returns A number. If conversion fails, returns zero. Category Conversion functions, String functions Function syntax Val(string) See also IsNumeric Parameters Parameter Description string A string or a variable that contains one Usage This function works as follows: • • • • If TestValue If TestValue If TestValue If TestValue = "234A56?7'", Val(TestValue) returns 234 returns 234 = "BG234", Val(TestValue) returns the value 0, (not an error) = "0", Val(TestValue) returns the value 0, (not an error) = "234'5678'9?'", Val(TestValue) Example

Val Example

The string #DE(FORM.theTestValue)# can be converted to a number: #Val(FORM.theTestValue)#

The beginning of the string #DE(FORM.theTestValue)# cannot be converted to a number

Enter a string, and determine whether its beginning can be evaluated to a numeric value.

734 Chapter 3: ColdFusion Functions ValueList Description Inserts a delimiter between each value in an executed query. ColdFusion does not evaluate the arguments. Returns A delimited list of the values of each record returned from an executed query. Category Other functions, Query functions Function syntax ValueList(query.column [, delimiter ]) See also QuotedValueList Parameters Parameter Description query.column Name of an executed query and column. Separate query name and column name with a period. delimiter A delimiter character to separate column data items. Default: comma (,). Example

ValueList Example

SELECT Dept_ID FROM Departments WHERE Dept_ID IN (‘BIOL’) SELECT * FROM CourseList WHERE Dept_ID IN (‘#ValueList(GetDepartments.Dept_ID)#’)
#Course_ID##Dept_ID##CorNumber##CorName#
ValueList 735 Week Description From a date/time object, determines the week number within the year. Returns An integer in the range 1–53; the ordinal of the week, within the year. Category Date and time functions Function syntax Week(date) See also DatePart Parameters Parameter Description date A date/time object in the range 100 AD–9999 AD. Usage When passing date as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date. Example

Week Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayOfWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(YourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(yourDate)# (day #DayOfYear(yourDate)# of #DaysInYear(yourDate)#).
This is a leap year This is not a leap year 736 Chapter 3: ColdFusion Functions Wrap Description Wraps text so that each line has a specified maximum number of characters. Returns String containing the wrapped text. Category String functions Function syntax Wrap(string, limit[, strip]) See also cfmail History ColdFusion MX 6.1: Added this function Parameters Parameter Description string String or variable that contains one. The text to wrap. limit Positive integer maximum number of characters to allow on a line. strip Boolean specifying whether to remove all existing newline and carriage return characters in the input string with spaces before wrapping the text. Default: False. Usage Inserts line break at the location of the first white space character (such as a space, tab, or new line) before the specified limit on a line. If a line has no whitespace characters before the limit, inserts a line break at the limit. Uses the operating-system specific line break: newline for UNIX, carriage return and newline on Windows. If you specify the strip parameter, all existing line breaks are removed, so any paragraph formatting is lost. Use this function to limit the length of text lines, such as text to be included in a mail message. The cfmail and cfmailpart tag wraptext attributes use this function Example

Wrap Example

#Wrap(inputText, 59)# Wrap 737 WriteOutput Description Appends text to the page-output stream. This function writes to the page-output stream regardless of conditions established by the cfsetting tag. Category Other functions Function syntax WriteOutput(string) Parameters Parameter Description string A string or a variable that contains one Usage Within the cfquery and cfmail tags, this function does not output to the current page; it writes to the current SQL statement or mail text. Do not use WriteOutput within cfquery and cfmail. Although you can call this function anywhere within a page, it is most useful inside a cfscript block. Example ... employee = StructNew(); StructInsert(employee, "firstname", FORM.firstname); StructInsert(employee, "lastname", FORM.lastname); StructInsert(employee, "email", FORM.email); StructInsert(employee, "phone", FORM.phone); StructInsert(employee, "department", FORM.department); WriteOutput("About to add " & FORM.firstname & " " & FORM.lastname); 738 Chapter 3: ColdFusion Functions XmlChildPos Description Gets the position of a child element within an XML document object. Returns The position, in an XmlChildren array, of the Nth child that has the specified name. Category Extensibility functions, XML functions Function syntax XmlChildPos(elem, childName, N) See also cfxml, IsXmlDoc, XmlChildPos, XmlFormat, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description elem XML element within which to search childName XML child element for which to search N Index of XMLchild element for which to search Usage The returned index can be used in the ArrayInsertAt and ArrayDeleteAt functions. Example This example searches the XML document object mydoc.employee.XmlChildren for the mydoc.employee.name[2] element: XmlChildPos(mydoc.employee, "name", 2) XmlChildPos 739 XmlElemNew Description Creates an XML document object element. Returns An XML document object element. Category Extensibility functions, XML functions Function syntax XmlElemNew(xmlObj, childName) See also cfxml, IsXmlDoc, XmlChildPos, XmlFormat, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description xmlObj The name of an XML object. An XML document or an element. childName The name of the element to create. This element becomes a child element of xmlObj in the tree. Example The following example creates and displays a ColdFusion document object. For more information on this example, see Chapter 31, “Using XML and WDDX,” in Developing ColdFusion MX Applications. MyDoc = XmlNew(); MyDoc.xmlRoot = XmlElemNew(MyDoc,"MyRoot"); if (testVar IS TRUE) MyDoc.MyRoot.XmlText = "The value of testVar is True."; else MyDoc.MyRoot.XmlText = "The value of testVar is False."; for (i = 1; i LTE 4; i = i + 1) { MyDoc.MyRoot.XmlChildren[i] = XmlElemNew(MyDoc,"childNode"); MyDoc.MyRoot.XmlChildren[i].XmlText = "This is Child node " & i &"."; } 740 Chapter 3: ColdFusion Functions XmlFormat Description Escapes special XML characters in a string, so that the string is safe to use with XML. Returns A copy of string that is safe to use with XML. Category Extensibility functions, String functions, XML functions Function syntax XmlFormat(string) See also cfxml, IsXmlDoc, XmlChildPos, XmlChildPos, XmlNew, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description string A string or a variable that contains one Usage The characters that this function escapes include the following: • • • • • Greater than symbol (>) Less than symbol (<) Single quotation mark (') Double quotation mark (") Ampersand symbol (&) Example

XMLFormat

This example shows how XMLFormat is used to escape special XML characters and make the use of XML with ColdFusion easy.

<?xml version = "1.0"?> <cfoutput> <someXML> <someElement someAttribute = "#XMLFormat("'a quoted value'")#> #XMLFormat("Body of element to be passed here.")# </someElement> </someXML> </cfoutput> XmlFormat 741 XmlNew Description Creates an XML document object. Returns An empty XML document object. Category Extensibility functions, XML functions Function syntax XmlNew([caseSensitive]) See also cfxml, IsXmlDoc, XmlChildPos, XmlChildPos, XmlFormat, XmlParse, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description caseSensitive Determines how ColdFusion processes the case of XML document object component identifiers • yes: maintains case • no. ColdFusion ignores case. Default. Usage An XML document object is represented in ColdFusion as a structure. The caseSensitive attribute value determines whether identifiers whose characters are of varying case, but are otherwise the same, refer to different components. For example: • If caseSensitive = "no", the names mydoc.employee.name[1] and mydoc.employee.NAME[1] refer to the same element • If caseSensitive = "yes", these names refer to two distinct elements The following example creates and displays a ColdFusion document object. For more information on this example, see Chapter 31, “Using XML and WDDX,” in Developing ColdFusion MX Applications. Example MyDoc = XmlNew(); MyDoc.xmlRoot = XmlElemNew(MyDoc,"MyRoot"); if (testVar IS TRUE) MyDoc.MyRoot.XmlText = "The value of testVar is True."; else MyDoc.MyRoot.XmlText = "The value of testVar is False."; for (i = 1; i LTE 4; i = i + 1) { MyDoc.MyRoot.XmlChildren[i] = XmlElemNew(MyDoc,"childNode"); MyDoc.MyRoot.XmlChildren[i].XmlText = "This is Child node " & i &"."; 742 Chapter 3: ColdFusion Functions } XmlNew 743 XmlParse Description Converts an XML document that is represented as a string variable into an XML document object. Returns An XML document object. Category Conversion functions, Extensibility functions, XML functions Function syntax XmlParse(xmlString [, caseSensitive ] ) See also cfxml, IsXmlDoc, XmlChildPos, XmlChildPos, XmlFormat, XmlNew, XmlSearch, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description xmlString An XML document object string caseSensitive • yes: maintains the case of document elements and attributes • no. Default. Usage The caseSensitive attribute value determines whether identifiers whose characters are of varying case, but are otherwise the same, refer to different components. For example: • If caseSensitive = "no", the names mydoc.employee.name[1] and mydoc.employee.NAME[1] refer to the same element • If caseSensitive = "yes", these names refer to two distinct elements If the XML document is represented by a string variable, use the XmlParse tag directly on the variable. For example, if your application uses cfhttp action="get" to get the XML document, use the following code to create the XML document object: If the XML document is in a file, use the cffile tag to convert the file to a CFML variable, then use the XmlParse tag on the resulting variable. For example, if the XML document is in the file C:\temp\myxmldoc.xml, use the following code to convert the file to an XML document object: Note: If the file is not encoded with the ASCII or Latin-1 character encoding, use the cffile tag charset attribute to specify the file’s character encoding. For example, if the file is encoded in UTF, specify charset="UTF-8". 744 Chapter 3: ColdFusion Functions XmlSearch Description Uses an XPath language expression to search an XML document that is represented as a string variable. Returns An array of XML object nodes that match the search criteria. Category Extensibility functions, XML functions Function syntax XmlSearch(xmlDoc, xPathString) See also cfxml, IsXmlDoc, XmlChildPos, XmlChildPos, XmlFormat, XmlNew, XmlParse, XmlTransform History ColdFusion MX: Added this function. Parameters Parameter Description xmlDoc XML document object xPathString XPath expression Usage XPath is specified by the World-Wide Web Consortium. For detailed information on XPath, see the W3C website at www.w3.org/TR/xpath. Example The following example extracts the elements named last, which contain employee last names, from the employeesimple.xml file, and displays the names. myxmldoc = XmlParse(myxml); selectedElements = XmlSearch(myxmldoc, "/employee/name/last"); for (i = 1; i LTE ArrayLen(selectedElements); i = i + 1) writeoutput(selectedElements[i].XmlText & "
");
XmlSearch 745 XmlTransform Description Applies an Extensible Stylesheet Language Transformation (XSLT) to an XML document object that is represented as a string variable. An XSLT converts an XML document to another format or representation by applying an Extensible Stylesheet Language (XSL) stylesheet to it. For more information, see Chapter 31, “Using XML and WDDX,” in Developing ColdFusion MX Applications. Returns A string; an XML document after the XSLT is applied Category Conversion functions, Extensibility functions, XML functions Function syntax XmlTransform(xmlString | xmlObj, xslString) See also cfxml, IsXmlDoc, XmlChildPos, XmlChildPos, XmlFormat, XmlNew, XmlParse, XmlSearch History ColdFusion MX: Added this function. Parameters 746 Parameter Description xmlString | xmlObj A string that represents the XML document, or a parsed object representation of it. xslString XSLT transformation to apply. Chapter 3: ColdFusion Functions Year Description From a date/time object, gets the year value. Returns The year value of date. Category Date and time functions Function syntax Year(date) See also DatePart, IsLeapYear Parameters Parameter Description date A date/time object in the range 100 AD–9999 AD. Usage When passing a date as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date. Example

Year Example

More information about your date:

Your date, #DateFormat(yourDate)#.
It is #DayOfWeekAsString(DayOfWeek(yourDate))#, day #DayOfWeek(yourDate)# in the week.
This is day #Day(yourDate)# in the month of #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
We are in week #Week(yourDate)# of #Year(YourDate)# (day #DayOfYear(yourDate)# of #DaysInYear(yourDate)#).
This is a leap year This is not a leap year Year 747 YesNoFormat Description Evaluates a number or Boolean value. Returns Yes, for a non-zero value; No, otherwise. Category Decision functions, Display and formatting functions Function syntax YesNoFormat(value) See also IsBinary, IsNumeric Parameters Parameter Description value A number or Boolean value Example

YesNoFormat Example

The YesNoFormat function returns non-zero values as "Yes"; zero values as "No".

  • YesNoFormat(1):#YesNoFormat(1)#
  • YesNoFormat(0):#YesNoFormat(0)#
  • YesNoFormat("1123"):#YesNoFormat("1123")#
  • YesNoFormat("No"):#YesNoFormat("No")#
  • YesNoFormat(True):#YesNoFormat(True)#
748 Chapter 3: ColdFusion Functions CHAPTER 4 ColdFusion C++ CFX Reference This chapter describes the CFXAPI classes and members. Contents C++ class overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750 Deprecated class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750 CCFXException class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751 CCFXQuery class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753 CCFXRequest class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757 CCFXStringSet class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766 749 C++ class overview A list of CFXAPI classes and members follows. Class Member CCFXException class CCFXException::GetError CCFXException::GetDiagnostics CCFXQuery class CCFXQuery::AddRow CCFXQuery::GetColumns CCFXQuery::GetData CCFXQuery::GetName CCFXQuery::GetRowCount CCFXQuery::SetData CCFXRequest class CCFXRequest::AddQuery CCFXRequest::AttributeExists CCFXRequest::CreateStringSet CCFXRequest::Debug CCFXRequest::GetAttribute CCFXRequest::GetAttributeList CCFXRequest::GetCustomData CCFXRequest::GetQuery CCFXRequest::ReThrowException CCFXRequest::SetCustomData CCFXRequest::SetVariable CCFXRequest::ThrowException CCFXRequest::Write CCFXRequest::WriteDebug CCFXStringSet class CCFXStringSet::AddString CCFXStringSet::GetCount CCFXStringSet::GetIndexForString CCFXStringSet::GetString Deprecated class members The following CFXAPI classes and members are deprecated. They do not work, and might cause an error, in later releases. 750 Class Deprecated member CCFXQuery Class CCFXQuery::SetQueryString ColdFusion MX CCFXQuery::SetTotalTime ColdFusion MX CCFXRequest Class CCFXRequest::GetSetting Chapter 4: ColdFusion C++ CFX Reference Deprecated as of this ColdFusion release ColdFusion MX CCFXException class An abstract class that represents an exception thrown during processing of a ColdFusion Extension (CFX) procedure. Exceptions of this type can be thrown by CCFXRequest class, CCFXQuery class, and CCFXStringSet class. Your ColdFusion Extension code must be written to handle exceptions of this type. For more information, see CCFXRequest::ThrowException and CCFXRequest::ReThrowException. Class members virtual LPCSTR GetError() The CCFXException::GetError function returns a general error message. virtual LPCSTR GetDiagnostics() The CCFXException::GetDiagnostics function returns detailed error information. CCFXException::GetError Description Provides basic user output for exceptions that occur during processing. CCFXException::GetDiagnostics Description Provides detailed user output for exception that occur during processing. Example This code block shows how GetError and GetDiagnostics work with ThrowException and ReThrowException. CCFXException class 751 // Write output back to the user here... pRequest->Write( "Hello from CFX_FOO2!" ) ; pRequest->ThrowException("User Error", "You goof'd..."); // Output optional debug info if ( pRequest->Debug() ) { pRequest->WriteDebug( "Debug info..." ) ; } // Catch ColdFusion exceptions & re-raise them catch( CCFXException* e ) { // This is how you would pull the error information LPCTSTR strError = e->GetError(); LPCTSTR strDiagnostic = e->GetDiagnostics(); pRequest->ReThrowException( e ) ; } // Catch ALL other exceptions and throw them as // ColdFusion exceptions (DO NOT REMOVE! -// this prevents the server from crashing in // case of an unexpected exception) catch( ... ) { pRequest->ThrowException( "Error occurred in tag CFX_FOO2", "Unexpected error occurred while processing tag." ) ; } 752 Chapter 4: ColdFusion C++ CFX Reference CCFXQuery class An abstract class that represents a query used or created by a ColdFusion Extension (CFX). Queries contain one or more columns of data that extend over a varying number of rows. Class members virtual int AddRow() virtual CCFXStringSet* GetColumns CCFXQuery::AddRow adds a row to a query. CCFXQuery::GetColumns retrieves a list of a query's column names. virtual LPCSTR GetData( int iRow, int iColumn ) CCFXQuery::GetData retrieves a data element virtual LPCSTR GetName() CCFXQuery::GetName retrieves the name of a from a row and column of a query. query. virtual int GetRowCount() CCFXQuery::GetRowCount retrieves the number of rows in a query. virtual void SetData( int iRow, int iColumn, LPCSTR lpszData ) CCFXQuery::SetData sets a data element within a virtual void SetQueryString( LPCSTR lpszQuery ) This function is deprecated. It might not work, and might cause an error, in later releases. virtual void SetTotalTime( DWORD dwMilliseconds ) This function is deprecated. It might not work, and might cause an error, in later releases. row and column of a query. CCFXQuery::AddRow Syntax int CCFXQuery::AddRow(void) Description Add a row to the query. Call this function to append a row to a query. Returns Returns the index of the row that was appended to a query. Example The following example shows the addition of two rows to a three-column ('City', 'State', and 'Zip') query: // First row int iRow ; iRow = pQuery->AddRow() ; pQuery->SetData( iRow, iCity, "Minneapolis" ) ; pQuery->SetData( iRow, iState, "MN" ) ; pQuery->SetData( iRow, iZip, "55345" ) ; // Second row iRow = pQuery->AddRow() ; pQuery->SetData( iRow, iCity, "St. Paul" ) ; pQuery->SetData( iRow, iState, "MN" ) ; pQuery->SetData( iRow, iZip, "55105" ) ; CCFXQuery class 753 CCFXQuery::GetColumns Syntax CCFXStringSet* CCFXQuery::GetColumns(void) Description Retrieves a list of the column names contained in a query. Returns Returns an object of CCFXStringSet class that contains a list of the columns in the query. ColdFusion automatically frees the memory that is allocated for the returned string set, after the request is completed. Example The following example gets the list of columns, then iterates over the list, writing each column name back to the user: // Get the list of columns from the query CCFXStringSet* pColumns = pQuery->GetColumns() ; int nNumColumns = pColumns->GetCount() ; // Print the list of columns to the user pRequest->Write( "Columns in query: " ) ; for( int i=1; i<=nNumColumns; i++ ) { pRequest->Write( pColumns->GetString( i ) ) ; pRequest->Write( " " ) ; } CCFXQuery::GetData Syntax LPCSTR CCFXQuery::GetData(int iRow, int iColumn) Description Gets a data element from a row and column of a query. Row and column indexes begin with 1. You can determine the number of rows in a query by calling CCFXQuery::GetRowCount. You can determine the number of columns in a query by retrieving the list of columns using CCFXQuery::GetColumns, and then calling CCFXStringSet::GetCount on the returned string set. Returns Returns the value of the requested data element. Parameters 754 Parameter Description iRow Row to retrieve data from (1-based) iColumn Column to retrieve data from (1-based) Chapter 4: ColdFusion C++ CFX Reference Example The following example iterates over the elements of a query and writes the data in the query back to the user in a simple, space-delimited format: int iRow, iCol ; int nNumCols = pQuery->GetColumns()->GetCount() ; int nNumRows = pQuery->GetRowCount() ; for ( iRow=1; iRow<=nNumRows; iRow++ ) { for ( iCol=1; iCol<=nNumCols; iCol++ ) { pRequest->Write( pQuery->GetData( iRow, iCol ) ) ; pRequest->Write( " " ) ; } pRequest->Write( "
" ) ; } CCFXQuery::GetName Syntax LPCSTR CCFXQuery::GetName(void) Description Returns the name of a query. Example The following example retrieves the name of a query and writes it back to the user: CCFXQuery* pQuery = pRequest->GetQuery() ; pRequest->Write( "The query name is: " ) ; pRequest->Write( pQuery->GetName() ) ; CCFXQuery::GetRowCount Syntax int CCFXQuery::GetRowCount(void) Description Returns the number of rows contained in a query. Example The following example retrieves the number of rows in a query and writes it back to the user: CCFXQuery* pQuery = pRequest->GetQuery() ; char buffOutput[256] ; wsprintf( buffOutput, "The number of rows in the query is %ld.", pQuery->GetRowCount() ) ; pRequest->Write( buffOutput ) ; CCFXQuery class 755 CCFXQuery::SetData Syntax void CCFXQuery::SetData(int iRow, int iColumn, LPCSTR lpszData) Description Sets a data element within a row and column of a query. Row and column indexes begin with 1. Before calling SetData for a given row, call CCFXQuery::AddRow and use the return value as the row index for your call to SetData. Parameters Parameter Description iRow Row of data element to set (1-based) iColumn Column of data element to set (1-based) lpszData New value for data element Example The following example shows the addition of two rows to a three-column ('City', 'State', and 'Zip') query: // First row int iRow ; iRow = pQuery->AddRow() ; pQuery->SetData( iCity, iRow, "Minneapolis" ) ; pQuery->SetData( iState, iRow, "MN" ) ; pQuery->SetData( iZip, iRow, "55345" ) ; // Second row iRow = pQuery->AddRow() ; pQuery->SetData( iCity, iRow, "St. Paul" ) ; pQuery->SetData( iState, iRow, "MN" ) ; pQuery->SetData( iZip, iRow, "55105" ) ; 756 Chapter 4: ColdFusion C++ CFX Reference CCFXRequest class Abstract class that represents a request made to a ColdFusion Extension (CFX). An instance of this class is passed to the main function of your extension DLL. The class provides interfaces that can be used by the custom extension for the following actions: • • • • Reading and writing variables Returning output Creating and using queries Throwing exceptions Class members virtual BOOL AttributeExists ( LPCSTR lpszName ) CCFXRequest::AttributeExists checks virtual LPCSTR GetAttribute ( LPCSTR lpszName ) CCFXRequest::GetAttribute gets the virtual CCFXStringSet* GetAttributeList() CCFXRequest::GetAttributeList gets an whether the attribute was passed to the tag. value of the passed attribute. array of attribute names passed to the tag. virtual CCFXQuery* GetQuery() CCFXRequest::GetQuery gets the query that was passed to the tag. virtual LPCSTR GetSetting( LPCSTR lpszSettingName ) CCFXRequest::GetSetting This member is deprecated. It might not work, and might cause an error, in later releases. virtual void Write( LPCSTR lpszOutput ) CCFXRequest::Write writes text output back to the user. virtual void SetVariable( LPCSTR lpszName, LPCSTR lpszValue ) CCFXRequest::SetVariable sets a virtual CCFXQuery* AddQuery( LPCSTR lpszName, CCFXStringSet* pColumns ) CCFXRequest::AddQuery adds a query to virtual BOOL Debug() CCFXRequest::Debug checks whether the variable in the template that contains this tag. the template that contains this tag. tag contains the DEBUG attribute. virtual void WriteDebug( LPCSTR lpszOutput ) CCFXRequest::WriteDebug writes text output into the debug stream. virtual CCFXStringSet* CreateStringSet() CCFXRequest::CreateStringSet allocates and returns a CCFXStringSet instance. virtual void ThrowException( LPCSTR lpszError, LPCSTR lpszDiagnostics ) CCFXRequest::ThrowException throws an virtual void ReThrowException ( CCFXException* e ) CCFXRequest::ReThrowException re- exception and ends processing of this request. throws an exception that has been caught. CCFXRequest class 757 virtual void SetCustomData( LPVOID lpvData ) CCFXRequest::SetCustomData sets custom (tag specific) data to carry with a request. virtual LPVOID GetCustomData() CCFXRequest::GetCustomData gets custom (tag specific) data for a request. CCFXRequest::AddQuery Syntax CCFXQuery* CCFXRequest::AddQuery(LPCSTR lpszName, CCFXStringSet* pColumns) Description Adds a query to the calling template. The query can be accessed by CFML tags (for example, CFOUTPUT or CFTABLE) within the template. After calling AddQuery, the query is empty (it has 0 rows). To populate the query with data, call the CCFXQuery::AddRow and CCFXQuery::SetData functions. Returns Returns a pointer to the query that was added to the template (an object of class CCFXQuery). The memory allocated for the returned query is freed automatically by ColdFusion after the request is completed. Parameters Parameter Description lpszName Name of query to add to the template (must be unique) pColumns List of column names to be used in the query Example The following example adds a query named 'People' to the calling template. The query has two columns ('FirstName' and 'LastName') and two rows: // Create a string set and add the column names to it CCFXStringSet* pColumns = pRequest->CreateStringSet() ; int iFirstName = pColumns->AddString( "FirstName" ) ; int iLastName = pColumns->AddString( "LastName" ) ; // Create a query that contains these columns CCFXQuery* pQuery = pRequest->AddQuery( "People", pColumns ) ; // Add data to the query int iRow ; iRow = pQuery->AddRow() ; pQuery->SetData( iRow, iFirstName, "John" pQuery->SetData( iRow, iLastName, "Smith" iRow = pQuery->AddRow() ; pQuery->SetData( iRow, iFirstName, "Jane" pQuery->SetData( iRow, iLastName, "Doe" ) 758 Chapter 4: ColdFusion C++ CFX Reference ) ; ) ; ) ; ; CCFXRequest::AttributeExists Syntax BOOL CCFXRequest::AttributeExists(LPCSTR lpszName) Description Checks whether the attribute was passed to the tag. Returns True if the attribute is available; False, otherwise. Parameters Parameter Description lpszName Name of the attribute to check (case insensitive) Example The following example checks whether the user passed an attribute named DESTINATION to the tag, and throws an exception if the attribute was not passed: if ( pRequest->AttributeExists("DESTINATION")==FALSE ) { pRequest->ThrowException( "Missing DESTINATION parameter", "You must pass a DESTINATION parameter in " "order for this tag to work correctly." ) ; } CCFXRequest::CreateStringSet Syntax CCFXStringSet* CCFXRequest::CreateStringSet(void) Description Allocates and returns an instance. Always use this function to create string sets, as opposed to directly using the 'new' operator. Returns Returns an object of CCFXStringSet class. The memory allocated for the returned string set is freed automatically by ColdFusion after the request is completed Example The following example creates a string set and adds three strings to it: CCFXStringSet* pColors = pRequest->CreateStringSet() ; pColors->AddString( "Red" ) ; pColors->AddString( "Green" ) ; pColors->AddString( "Blue" ) ; CCFXRequest class 759 CCFXRequest::Debug Syntax BOOL CCFXRequest::Debug(void) Description Checks whether the tag contains the DEBUG attribute. Use this function to determine whether to write debug information for a request. For more information, see CCFXRequest::WriteDebug. Returns Returns True if the tag contains the DEBUG attribute; False, otherwise. Example The following example checks whether the DEBUG attribute is present, and if it is, it writes a brief debug message: if ( pRequest->Debug() ) { pRequest->WriteDebug( "Top secret debug info" ) ; } CCFXRequest::GetAttribute Syntax LPCSTR CCFXRequest::GetAttribute(LPCSTR lpszName) Description Retrieves the value of the passed attribute. Returns an empty string if the attribute does not exist. (To test whether an attribute was passed to the tag, use CCFXRequest::AttributeExists.) Returns Returns the value of the attribute passed to the tag. If no attribute of that name was passed to the tag, an empty string is returned. Parameters Parameter Description lpszName Name of the attribute to retrieve (case insensitive) Example The following example retrieves an attribute named DESTINATION and writes its value back to the user: LPCSTR lpszDestination = pRequest->GetAttribute("DESTINATION") ; pRequest->Write( "The destination is: " ) ; pRequest->Write( lpszDestination ) ; 760 Chapter 4: ColdFusion C++ CFX Reference CCFXRequest::GetAttributeList Syntax CCFXStringSet* CCFXRequest::GetAttributeList(void) Description Gets an array of attribute names passed to the tag. To get the value of one attribute, use CCFXRequest::GetAttribute. Returns Returns an object of class CCFXStringSet class that contains a list of attributes passed to the tag. The memory allocated for the returned string set is freed automatically by ColdFusion after the request is completed. Example The following example gets the list of attributes and iterates over the list, writing each attribute and its value back to the user. LPCSTR lpszName, lpszValue ; CCFXStringSet* pAttribs = pRequest->GetAttributeList() ; int nNumAttribs = pAttribs->GetCount() ; for( int i=1; i<=nNumAttribs; i++ ) { lpszName = pAttribs->GetString( i ) ; lpszValue = pRequest->GetAttribute( lpszName ) ; pRequest->Write( lpszName ) ; pRequest->Write( " = " ) ; pRequest->Write( lpszValue ) ; pRequest->Write( "
" ) ; } CCFXRequest::GetCustomData Syntax LPVOID CCFXRequest::GetCustomData(void) Description Gets the custom (tag specific) data for the request. This member is typically used from within subroutines of a tag implementation to extract tag data from a request. Returns Returns a pointer to the custom data, or NULL if no custom data has been set during this request using CCFXRequest::SetCustomData. Example The following example retrieves a pointer to a request specific data structure of hypothetical type MYTAGDATA: void DoSomeGruntWork( CCFXRequest* pRequest ) { MYTAGDATA* pTagData = (MYTAGDATA*)pRequest->GetCustomData() ; ... remainder of procedure ... } CCFXRequest class 761 CCFXRequest::GetQuery Syntax CCFXQuery* CCFXRequest::GetQuery(void) Description Retrieves a query that was passed to a tag. To pass a query to a custom tag, you use the QUERY attribute. This attribute should be set to the name of a query (created using the CFQUERY tag or another custom tag). The QUERY attribute is optional and should be used only by tags that process an existing data set. Returns Returns an object of the CCFXQuery class that represents the query passed to the tag. If no query was passed to the tag, NULL is returned. The memory allocated for the returned query is freed automatically by ColdFusion after the request is completed. Example The following example retrieves the query that was passed to the tag. If no query was passed, an exception is thrown: CCFXQuery* pQuery = pRequest->GetQuery() ; if ( pQuery == NULL ) { pRequest->ThrowException( "Missing QUERY parameter", "You must pass a QUERY parameter in " "order for this tag to work correctly." ) ; } CCFXRequest::ReThrowException Syntax void CCFXRequest::ReThrowException(CCFXException* e) Description Re-throws an exception that has been caught within an extension procedure. This function is used to avoid having C++ exceptions that are thrown by DLL extension code propagate back into ColdFusion. Catch ALL C++ exceptions that occur in extension code, and either re-throw them (if they are of the CCFXException class) or create and throw a new exception pointer using CCFXRequest::ThrowException. Parameters 762 Parameter Description e A CCFXException that has been caught Chapter 4: ColdFusion C++ CFX Reference Example The following code demonstrates how to handle exceptions in ColdFusion Extension DLL procedures: try { ...Code that could throw an exception... } catch( CCFXException* e ) { ...Do appropriate resource cleanup here... // Re-throw the exception pRequest->ReThrowException( e ) ; } catch( ... ) { // Something nasty happened pRequest->ThrowException( "Unexpected error occurred in CFX tag", "" ) ; } CCFXRequest::SetCustomData Syntax void CCFXRequest::SetCustomData(LPVOID lpvData) Description Sets custom (tag specific) data to carry with the request. Use this function to store request specific data to pass to procedures within your custom tag implementation. Parameters Parameter Description lpvData Pointer to custom data Example The following example creates a request-specific data structure of hypothetical type MYTAGDATA and stores a pointer to the structure in the request for future use: void ProcessTagRequest( CCFXRequest* pRequest ) try { MYTAGDATA tagData ; pRequest->SetCustomData( (LPVOID)&tagData ) ; ... remainder of procedure ... } CCFXRequest class 763 CCFXRequest::SetVariable Syntax void CCFXRequest::SetVariable(LPCSTR lpszName, LPCSTR lpszValue) Description Sets a variable in the calling template. If the variable name already exists in the template, its value is replaced. If it does not exist, a variable is created. The values of variables created using SetVariable can be accessed in the same manner as other template variables (for example, #MessageSent#). Parameters Parameter Description lpszName Name of variable lpszValue Value of variable Example The following example sets the value of a variable named 'MessageSent' based on the success of an operation performed by the custom tag: BOOL bMessageSent; ...attempt to send the message... if ( bMessageSent == TRUE ) { pRequest->SetVariable( "MessageSent", "Yes" ) ; } else { pRequest->SetVariable( "MessageSent", "No" ) ; } CCFXRequest::ThrowException Syntax void CCFXRequest::ThrowException(LPCSTR lpszError, LPCSTR lpszDiagnostics) Description Throws an exception and ends processing of a request. Call this function when you encounter an error that does not allow you to continue processing the request. This function is almost always combined with the CCFXRequest::ReThrowException to protect against resource leaks in extension code. Parameters 764 Parameter Description lpszError Short identifier for error lpszDiagnostics Error diagnostic information Chapter 4: ColdFusion C++ CFX Reference Example The following example throws an exception indicating that an unexpected error occurred while processing a request: char buffError[512] ; wsprintf( buffError, "Unexpected Windows NT error number %ld " "occurred while processing request.", GetLastError() ) ; pRequest->ThrowException( "Error occurred", buffError ) ; CCFXRequest::Write Syntax void CCFXRequest::Write(LPCSTR lpszOutput) Description Writes text output back to the user. Parameters Parameter Description lpszOutput Text to output Example The following example creates a buffer to hold an output string, fills the buffer with data, and writes the output back to the user: CHAR buffOutput[1024] ; wsprintf( buffOutput, "The destination is: %s", pRequest->GetAttribute("DESTINATION") ) ; pRequest->Write( buffOutput ) ; CCFXRequest::WriteDebug Syntax void CCFXRequest::WriteDebug(LPCSTR lpszOutput) Description Writes text output into the debug stream. The text is only displayed to the end-user if the tag contains the DEBUG attribute. (For more information, see CCFXRequest::Debug.) Parameters Parameter Description lpszOutput Text to output Example The following example checks whether the DEBUG attribute is present; if so, it writes a brief debug message: if ( pRequest->Debug() ) { pRequest->WriteDebug( "Top secret debug info" ) ; } CCFXRequest class 765 CCFXStringSet class Abstract class that represents a set of ordered strings. Strings can be added to a set and can be retrieved by a numeric index (index values for strings are 1-based). To create a string set, use CCFXRequest::CreateStringSet. Class members virtual int AddString( LPCSTR lpszString ) CCFXStringSet::AddString adds a string to the end of a list. virtual int GetCount() CCFXStringSet::GetCount gets the number of strings contained in a list. virtual LPCSTR GetString( int iIndex ) CCFXStringSet::GetString gets the string located at the passed index. virtual int GetIndexForString ( LPCSTR lpszString ) CCFXStringSet::GetIndexForString gets the index for the passed string. CCFXStringSet::AddString Syntax int CCFXStringSet::AddString(LPCSTR lpszString) Description Adds a string to the end of the list. Returns The index of the string that was added. Parameters Parameter Description lpszString String to add to the list Example The following example demonstrates adding three strings to a string set and saving the indexes of the items that are added: CCFXStringSet* pSet = pRequest->CreateStringSet() ; int iRed = pSet->AddString( "Red" ) ; int iGreen = pSet->AddString( "Green" ) ; int iBlue = pSet->AddString( "Blue" ) ; CCFXStringSet::GetCount Syntax int CCFXStringSet::GetCount(void) Description Gets the number of strings in a string set. The value can be used with CCFXStringSet::GetString to iterate over the strings in the set (recall that the index values for strings in the list begin at 1). 766 Chapter 4: ColdFusion C++ CFX Reference Returns Returns the number of strings contained in the string set. Example The following example demonstrates using GetCount with CCFXStringSet::GetString to iterate over a string set and write the contents of the list back to the user: int nNumItems = pStringSet->GetCount() ; for ( int i=1; i<=nNumItems; i++ ) { pRequest->Write( pStringSet->GetString( i ) ) ; pRequest->Write( "
" ) ; } CCFXStringSet::GetIndexForString Syntax int CCFXStringSet::GetIndexForString(LPCSTR lpszString) Description Searches for a passed string. The search is case-insensitive. Returns If the string is found, its index within the string set is returned. If it is not found, the constant CFX_STRING_NOT_FOUND is returned. Parameters Parameter Description lpszString String to search for Example The following example demonstrates a search for a string and throwing an exception if it is not found: CCFXStringSet* pAttribs = pRequest->GetAttributeList() ; int iDestination = pAttribs->GetIndexForString("DESTINATION") ; if ( iDestination == CFX_STRING_NOT_FOUND ) { pRequest->ThrowException( "DESTINATION attribute not found." "The DESTINATION attribute is required " "by this tag." ) ; } CCFXStringSet::GetString Syntax LPCSTR CCFXStringSet::GetString(int iIndex) Description Retrieves the string located at the passed index (index values are 1-based). CCFXStringSet class 767 Returns Returns the string located at the passed index. Parameters Parameter Description iIndex Index of string to retrieve Example The following example demonstrates GetString with CCFXStringSet::GetCount to iterate over a string set and write the contents of a list back to the user: int nNumItems = pStringSet->GetCount() ; for ( int i=1; i<=nNumItems; i++ ) { pRequest->Write( pStringSet->GetString( i ) ) ; pRequest->Write( "
" ) ; } 768 Chapter 4: ColdFusion C++ CFX Reference CHAPTER 5 ColdFusion Java CFX Reference This chapter describes the Java interfaces available for building ColdFusion custom CFXs in Java. Contents Overview class libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770 CustomTag interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770 Query interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772 Request interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777 Response interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782 Debugging classes reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785 769 Overview class libraries The following Java interfaces are available for building ColdFusion custom CFXs in Java. Interface Methods CustomTag interface processRequest Query interface addRow getColumnIndex getColumns getData getName getRowCount setData Request interface attributeExists debug getAttribute getAttributeList getIntAttribute getQuery getSetting Response interface addQuery setVariable write writeDebug CustomTag interface public abstract interface CustomTag Interface for implementing custom tags. Classes that implement this interface can be specified in the CLASS attribute of the Java CFX tag. For example, in a class MyCustomTag, which implements this interface, the following CFML code calls the MyCustomTag.processRequest method: Other attributes can be passed to the Java CFX tag. Their values are available using the Request object passed to the processRequest method. Methods Returns Syntax Description void processRequest(Request request, Response response) Processes a request originating from the CFX_mycustomtag tag processRequest Description Processes a request originating from the Java CFX tag. 770 Chapter 5: ColdFusion Java CFX Reference Category CustomTag interface Syntax public void processRequest(Request request, Response response) Throws Exception If an unexpected error occurs while processing the request. Parameters Parameter Description request Parameters (attributes, query, and so on.) for this request response Interface for generating response to request (output, variables, queries, and so on) CustomTag interface 771 Query interface public abstract interface Query Interface to a query used or created by a custom tag. A query contains tabular data organized by named columns and rows. Methods Returns Method Description int addRow() Adds a row to the query int getColumnIndex(String name) Gets the index of a column given its name String[] getColumns() Gets a list of the column names in a query String getData(int iRow, int iCol) Gets a data element from a row and column of a query String getName() Gets the name of a query int getRowCount() Gets the number of rows in a query void setData(int iRow, int iCol, String data) Sets a data element in a row and column of a query addRow Description Adds a row to a query. Call this method to append a row to a query. Returns the index of the row that was appended to the query. Category Query interface Syntax public int addRow() See also setData, getData Example The following example demonstrates the addition of two rows to a query that has three columns, City, State, and Zip: // Define column indexes int iCity = 1, iState = 2, iZip = 3 ; // First row int iRow = query.addRow() ; query.setData( iRow, iCity, "Minneapolis" ) ; query.setData( iRow, iState, "MN" ) ; query.setData( iRow, iZip, "55345" ) ; // Second row iRow = query.addRow() ; query.setData( iRow, iCity, "St. Paul" ) ; 772 Chapter 5: ColdFusion Java CFX Reference query.setData( iRow, iState, "MN" ) ; query.setData( iRow, iZip, "55105" ) ; getColumnIndex Description Returns the index of the column, or 0 if no such column exists. Category Query interface Syntax public int getColumnIndex(String name) See also getColumns, getData Parameters Parameter Description name Name of column to get index of (lookup is case-insensitive) Example The following example retrieves the index of the EMAIL column and uses it to output a list of the addresses contained in the column: // Get the index of the EMAIL column int iEMail = query.getColumnIndex( "EMAIL" ) ; // Iterate over the query and output list of addresses int nRows = query.getRowCount() ; for( int iRow = 1; iRow <= nRows; iRow++ ) { response.write( query.getData( iRow, iEMail ) + "
" ) ; } getColumns Description Returns an array of strings containing the names of the columns in the query. Category Query interface Syntax public String[] getColumns() Example The following example retrieves the array of columns, then iterates over the list, writing each column name back to the user: // Get the list of columns from the query String[] columns = query.getColumns() ; int nNumColumns = columns.length ; Query interface 773 // Print the list of columns to the user response.write( "Columns in query: " ) ; for( int i=0; i" ) ; } 774 Chapter 5: ColdFusion Java CFX Reference getName Description Returns the name of a query. Category Query interface Syntax public String getName() Example The following example retrieves the name of a query and writes it back to the user: Query query = request.getQuery() ; response.write( "The query name is: " + query.getName() ) ; getRowCount Description Retrieves the number of rows in a query. Returns the number of rows contained in a query. Category Query interface Syntax public int getRowCount() Example The following example retrieves the number of rows in a query and writes it back to the user: Query query = request.getQuery() ; int rows = query.getRowCount() ; response.write( "The number of rows in the query is " + Integer.toString(rows) ) ; setData Description Sets a data element in a row and column of a query. Row and column indexes begin with 1. Before calling setData for a given row, call addRow and use the return value as the row index for your call to setData. Category Query interface Syntax public void setData(int iRow, int iCol, String data) Throws IndexOutOfBoundsException If an invalid index is passed to the method. Query interface 775 See also getData, addRow Parameters Parameter Description iRow Row of data element to set (1-based) iCol Column of data element to set (1-based) data New value for data element Example The following example demonstrates the addition of two rows to a query that has three columns, City, State, and Zip: // Define column indexes int iCity = 1, iState = 2, iZip = 3 ; // First row int iRow = query.addRow() ; query.setData( iRow, iCity, "Minneapolis" ) ; query.setData( iRow, iState, "MN" ) ; query.setData( iRow, iZip, "55345" ) ; // Second row iRow = query.addRow() ; query.setData( iRow, iCity, "St. Paul" ) ; query.setData( iRow, iState, "MN" ) ; query.setData( iRow, iZip, "55105" ) ; 776 Chapter 5: ColdFusion Java CFX Reference Request interface public abstract interface Request Interface to a request made to a CustomTag. The interface includes methods for retrieving attributes passed to the tag (including queries) and reading global tag settings. Methods Returns Syntax Description boolean attributeExists(String name) Checks whether the attribute was passed to this tag. boolean debug() Checks whether the tag contains the debug attribute. String getAttribute(String name) Retrieves the value of the passed attribute. String[] getAttributeList() Retrieves a list of attributes passed to the tag. int getIntAttribute(String name) Retrieves the value of the passed attribute as an integer. int getIntAttribute(String name, int def) Retrieves the value of the passed attribute as an integer (returns default if the attribute does not exist or is not a valid number). Query getQuery() Retrieves the query that was passed to this tag. attributeExists Description Checks whether the attribute was passed to this tag. Returns True if the attribute is available; otherwise returns False. Category Request interface Syntax public boolean attributeExists(String name) See also getAttribute, getAttributeList Parameters Parameter Description name Name of the attribute to check (case-insensitive) Example The following example checks whether the user passed an attribute named DESTINATION to the tag; if not, it throws an exception: if ( ! request.attributeExists("DESTINATION") ) { throw new Exception( Request interface 777 "Missing DESTINATION parameter", "You must pass a DESTINATION parameter in " "order for this tag to work correctly." ) ; } ; debug Description Checks whether the tag contains the debug attribute. Use this method to determine whether to write debug information for this request. For more information, see writeDebug. Returns True if the tag contains the debug attribute; otherwise returns False. Category Request interface Syntax public boolean debug() See also writeDebug Example The following example checks whether the debug attribute is present, and if so, it writes a brief debug message: if ( request.debug() ) { response.writeDebug( "debug info" ) ; } getAttribute Description Retrieves the value of a passed attribute. Returns an empty string if the attribute does not exist (use attributeExists to test whether an attribute was passed to the tag). Use getAttribute(String,String) to return a default value rather than an empty string. Returns the value of the attribute passed to the tag. If no attribute of that name was passed to the tag, an empty string is returned. Category Request interface Syntax public String getAttribute(String name) See also attributeExists, getAttributeList, getIntAttribute, getAttribute Parameters 778 Parameter Description name The attribute to retrieve (case-insensitive) Chapter 5: ColdFusion Java CFX Reference Example The following example retrieves an attribute named DESTINATION and writes its value back to the user: String strDestination = request.getAttribute("DESTINATION") ; response.write( "The destination is: " + strDestination ) ; getAttributeList Description Retrieves a list of attributes passed to the tag. To retrieve the value of one attribute, use the getAttribute member function. Returns an array of strings containing the names of the attributes passed to the tag. Category Request interface Syntax public String[] getAttributeList() See also attributeExists, getAttributeList Example The following example retrieves the list of attributes, then iterates over the list, writing each attribute and its value back to the user: String[] attribs = request.getAttributeList() ; int nNumAttribs = attribs.length ; for( int i = 0; i < nNumAttribs; i++ ) { String strName = attribs[i] ; String strValue = request.getAttribute( strName ) ; response.write( strName + "=" + strValue + "
" ) ; } getIntAttribute Description Retrieves the value of the passed attribute as an integer. Returns -1 if the attribute does not exist. Use attributeExists to test whether an attribute was passed to the tag. Use getIntAttribute(String,int) to return a default value rather than throwing an exception or returning -1. Returns the value of the attribute passed to the tag. If no attribute of that name was passed to the tag, -1 is returned. Category Request interface Syntax public int getIntAttribute(String name) Request interface 779 Throws NumberFormatException If the attribute is not a valid number. See also attributeExists, getAttributeList, getIntAttribute Parameters Parameter Description name The attribute to retrieve (case-insensitive) Example The following example retrieves an attribute named PORT and writes its value back to the user: int nPort = request.getIntAttribute("PORT") ; if ( nPort != -1 ) response.write( "The port is: " + String.valueOf(nPort) ) ; getQuery Description Retrieves the query that was passed to this tag. To pass a query to a custom tag, you use the query attribute. It should be set to the name of a query (created using the cfquery tag). The query attribute is optional and should be used only by tags that process an existing dataset. Returns the Query that was passed to the tag. If no query was passed, returns null. Category Request interface Syntax public Query getQuery() Example The following example retrieves a query that was passed to a tag. If no query was passed, an exception is thrown: Query query = request.getQuery() ; if ( query == null ) { throw new Exception( "Missing QUERY parameter. " + "You must pass a QUERY parameter in " "order for this tag to work correctly." ) ; } getSetting Description Retrieves the value of a global custom tag setting. Custom tag settings are stored in the CustomTags section of the ColdFusion Registry key. 780 Chapter 5: ColdFusion Java CFX Reference Returns the value of the custom tag setting. If no setting of that name exists, an empty string is returned. Category Request interface Syntax public String getSetting(String name) Parameters Parameter Description name The name of the setting to retrieve (case-insensitive) Usage All custom tags implemented in Java share a registry key for storing settings. To avoid name conflicts, preface the names of settings with the name of your custom tag class. For example, the code below retrieves the value of a setting named VerifyAddress for a custom tag class named MyCustomTag: String strVerify = request.getSetting("MyCustomTag.VerifyAddress") ; if ( Boolean.valueOf(strVerify) ) { // Do address verification... } Request interface 781 Response interface public abstract interface Response Interface to response generated from a custom tag. This interface includes methods for writing output, generating queries, and setting variables in the calling page. Methods Returns Syntax Description Query addQuery(String name, String[] columns) Adds a query to the calling template. void setVariable(String name, String value) Sets a variable in the calling template. void write(String output) Outputs text back to the user. void writeDebug(String output) Writes text output into the debug stream. addQuery Description Adds a query to the calling template. The query can be accessed by CFML tags in the template. After calling addQuery, the query is empty (it has 0 rows). To populate the query with data, call the Query member functions addRow and setData. Returns the Query that was added to the template. Category Response interface Syntax public Query addQuery(String name, String[] columns) Throws IllegalArgumentException If the name parameter is not a valid CFML variable name. See also addRow, setData Parameters Parameter Description name The name of the query to add to the template columns The column names to use in the query Example The following example adds a query named People to the calling template. The query has two columns (FirstName and LastName) and two rows: // Create string array with column names (also track columns indexes) String[] columns = { "FirstName", "LastName" } ; int iFirstName = 1, iLastName = 2 ; // Create a query which contains these columns Query query = response.addQuery( "People", columns ) ; 782 Chapter 5: ColdFusion Java CFX Reference // Add data to the query int iRow = query.addRow() ; query.setData( iRow, iFirstName, "John" query.setData( iRow, iLastName, "Smith" iRow = query.addRow() ; query.setData( iRow, iFirstName, "Jane" query.setData( iRow, iLastName, "Doe" ) ) ; ) ; ) ; ; setVariable Description Sets a variable in the calling template. If the variable name specified exists in the template, its value is replaced. If it does not exist, a new variable is created. Category Response interface Syntax public void setVariable(String name, String value) Throws IllegalArgumentException If the name parameter is not a valid CFML variable name. Parameters Parameter Description name The name of the variable to set value The value to set the variable to Example For example, this code sets the value of a variable named MessageSent based on the success of an operation performed by the custom tag: boolean bMessageSent ; ...attempt to send the message... if ( bMessageSent == true ) { response.setVariable( "MessageSent", "Yes" ) ; } else { response.setVariable( "MessageSent", "No" ) ; } Response interface 783 write Description Outputs text back to the user. Category Response interface Syntax public void write(String output) Parameters Parameter Description output Text to output Example The following example outputs the value of the DESTINATION attribute: response.write( "DESTINATION = " + request.getAttribute("DESTINATION") ) ; writeDebug Description Writes text output into the debug stream. This text is displayed to the end-user only if the tag contains the debug attribute (check for this attribute using the Request.debug member function). Category Response interface Syntax public void writeDebug(String output) See also debug Parameters Parameter Description output The text to output Example The following example checks whether the debug attribute is present; if so, it writes a brief debug message: if ( request.debug() ) { response.writeDebug( "debug info" ) ; } 784 Chapter 5: ColdFusion Java CFX Reference Debugging classes reference The constructors and methods supported by the DebugRequest, DebugResponse, and DebugQuery classes are as follows. These classes also support the other methods of the Request, Response, and Query interfaces, respectively. DebugRequest // initialize a debug request with attributes public DebugRequest( Hashtable attributes ) ; // initialize a debug request with attributes and a query public DebugRequest( Hashtable attributes, Query query ) ; // initialize a debug request with attributes, a query, and settings public DebugRequest( Hashtable attributes, Query query, Hashtable settings ) ; DebugResponse // initialize a debug response public DebugResponse() ; // print the results of processing public void printResults() ; DebugQuery // initialize a query with name and columns public DebugQuery( String name, String[] columns ) throws IllegalArgumentException ; // initialize a query with name, columns, and data public DebugQuery( String name, String[] columns, String[][] data ) throws IllegalArgumentException ; Debugging classes reference 785 786 Chapter 5: ColdFusion Java CFX Reference CHAPTER 6 WDDX JavaScript Objects This chapter provides information about JavaScript objects and functions used to WDDX in a ColdFusion application. Contents JavaScript object overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788 WddxSerializer object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789 WddxRecordset object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793 787 JavaScript object overview These are the JavaScript objects and functions. Class Members WddxSerializer object serialize serializeVariable serializeValue write WddxRecordset object addColumn addRows getField getRowCount setField wddxSerialize WDDX JavaScript objects are defined in the wddx.js file; this file is installed in the webroot/ cfide/scripts directory. To use these objects, you must put a JavaScript tag before the code that refers to the objects; for example: 788 Chapter 6: WDDX JavaScript Objects WddxSerializer object The WddxSerializer object includes functions that serialize any JavaScript data structure. Functions The only function that developers typically call is serialize. Function syntax Description object.serialize(rootobj) Creates a WDDX packet for a passed WddxRecordset instance. object.serializeVariable(name, obj) Serializes a property of a structure. If an object is not a string, number, array, Boolean, or a date, WddxSerializer treats it as a structure. object.serializeValue(obj) Recursively serializes eligible data in a passed instance. object.write(str) Appends data to the serialized data stream. serialize Description Creates a WDDX packet for a passed WddxRecordset instance. Syntax object.serialize( rootobj ) Parameters Parameter Description object Instance name of the WddxSerializer object rootobj JavaScript data structure to serialize Return value Returns a serialized WDDX packet as a string if the function succeeds, or a null value if an error occurs. Usage Call this function to serialize the data in a WddxRecordset instance. Example This example shows a JavaScript function that you can call to serialize a WddxRecordset instance. It copies serialized data to a form field for display: function serializeData(data, formField) { wddxSerializer = new WddxSerializer(); wddxPacket = wddxSerializer.serialize(data); if (wddxPacket != null) { formField.value = wddxPacket; } else { WddxSerializer object 789 alert("Couldn't serialize data"); } } serializeVariable Description Serializes a property of a structure. If an object is not a string, number, array, Boolean, or date, WddxSerializer treats it as a structure. Syntax object.serializeVariable( name, obj ) Parameters Parameter Description object Instance name of a WddxSerializer object name Property to serialize obj Instance name of the value to serialize Return value Returns a Boolean True if serialization was successful, or False if an error occurs. Usage This is an internal function; you do not typically call it. Example This example is from the WddxSerializer serializeValue function: ... // Some generic object; treat it as a structure this.write(""); for (prop in obj) { bSuccess = this.serializeVariable(prop, obj[prop]); if (! bSuccess) { break; } } this.write(""); ... serializeValue Description Recursively serializes eligible data in a passed instance. Eligible data includes: • • • • • 790 String Number Boolean Date Array Chapter 6: WDDX JavaScript Objects • Recordset • Any JavaScript object This function serializes null values as empty strings. Syntax object.serializeValue( obj ) Parameters Parameter Description object Instance name of the WddxSerializer object obj Instance name of the WddxRecordset object to serialize Return value Returns a Boolean True if obj was serialized successfully; or False if an error occurs. Usage This is an internal function; you do not typically call it. Example This example is from the WddxSerializer serialize function: ... this.wddxPacket = ""; this.write("
"); bSuccess = this.serializeValue(rootObj); this.write(""); if (bSuccess) { return this.wddxPacket; } else { return null; } ... write Description Appends data to a serialized data stream. Syntax object.write( str ) Parameters Parameter Description object Instance name of the WddxSerializer object str String to be copied to the serialized data stream Return value Returns an updated serialized data stream as a String. WddxSerializer object 791 Usage This is an internal function; you do not typically call it. Example This example is from the WddxSerializer serializeValue function: ... else if (typeof(obj) == "number") { // Number value this.write("" + obj + ""); } else if (typeof(obj) == "boolean") { // Boolean value this.write(""); } ... 792 Chapter 6: WDDX JavaScript Objects WddxRecordset object Includes functions that you call as needed when constructing a WDDX record set. Functions : Function syntax Description object.addColumn(name) Adds a column to all rows in a WddxRecordset instance. object.addRows(n) Adds rows to all columns in a WddxRecordset instance. object.dump(escapeStrings) Displays WddxRecordset object data. object.getField(row, col) Returns the element in a row/column position. object.getRowCount() Indicates the number of rows in a WddxRecordset instance. object.setField(row, col, value) Sets the element in a row/column position. object.wddxSerialize(serializer) Serializes a record set. Returns HTML table of the WddxRecordset object data. Usage Convenient for debugging and testing record sets. The boolean parameter escapeStrings determines whether <>& characters in string values are escaped as <>& in HTML. Example SELECT Message_Id, Thread_id, Username, Posted FROM messages addColumn Description Adds a column to all rows in a WddxRecordset instance. Syntax object.addColumn( name ) WddxRecordset object 793 Parameters Parameter Description object Instance name of the WddxRecordset object name Name of the column to add Return value None. Usage Adds a column to every row of the WDDX record set. Initially the new column’s values are set to NULL. Example This example calls the addColumn function: // create a new record set rs = new WddxRecordset(); // add a new column rs.addColumn("NewColumn"); // extend the record set by 3 rows rs.addRows(3); // set an element in the first row // newValue is a previously defined variable rs.setField(0, "NewColumn", newValue); addRows Description Adds rows to all columns in a WddxRecordset instance. Syntax object.addRows( n ) Parameters Parameter Description object Instance name of the WddxRecordset object n Integer; number of rows to add Return value None. Usage This function adds the specified number of rows to every column of a WDDX record set. Initially, the row/column values are set to NULL. Example This example calls the addRows function: 794 Chapter 6: WDDX JavaScript Objects // create a new record set rs = new WddxRecordset(); // add a new column rs.addColumn("NewColumn"); // extend the record set by 3 rows rs.addRows(3); // set an element in the first row // newValue is a previously defined variable rs.setField(0, "NewColumn", newValue); getField Description Returns the element in the specified row/column position. Syntax object.getField( row, col ) Parameters Parameter Description object Instance name of the WddxRecordset object row Integer; zero-based row number of the value to return col Integer or string; column of the value to be returned. Return value Returns the value in the specified row/column position. Usage Call this function to access a value in a WDDX record set. Example This example calls the getField function (the variable r is a reference to a WddxRecordset instance): for (row = 0; row < nRows; ++row) { o += ""; for (i = 0; i < colNames.length; ++i) { o += "" + r.getField(row, colNames[i]) + ""; } o += ""; } WddxRecordset object 795 getRowCount Description Indicates the number of rows in a WddxRecordset instance. Syntax object.getRowCount( ) Parameters Parameter Description object Instance name of a WddxRecordset object Return value Integer. Returns the number of rows in the WddxRecordset instance. Usage Call this function before a looping construct to determine the number of rows in a record set. Example This example calls the getRowCount function: function dumpWddxRecordset(r) { // Get row count nRows = r.getRowCount(); ... for (row = 0; row < nRows; ++row) ... setField Description Sets the element in the specified row/column position. Syntax object.setField( row, col, value ) Parameters Parameter Description object Instance name of a WddxRecordset object row Integer; row that contains the element to set col Integer or string; the column containing the element to set value Value to set Return value None. Usage Call this function to set a value in a WddxRecordset instance. 796 Chapter 6: WDDX JavaScript Objects Example This example calls the setField function: // create a new recordset rs = new WddxRecordset(); // add a new column rs.addColumn("NewColumn"); // extend the record set by 3 rows rs.addRows(3); // set an element in the first row // newValue is a previously defined variable rs.setField(0, "NewColumn", newValue); wddxSerialize Description Serializes a record set. Syntax object.wddxSerialize( serializer ) Parameters Parameter Description object Instance name of the WddxRecordset object serializer WddxSerializer instance Return value Returns a Boolean True if serialization was successful; or False if an error occurs. Usage This is an internal function; you do not typically call it. Example This example is from the WddxSerializer serializeValue function: ... else if (typeof(obj) == "object") { if (obj == null) { // Null values become empty strings this.write(""); } else if (typeof(obj.wddxSerialize) == "function") { // Object knows how to serialize itself bSuccess = obj.wddxSerialize(this); } ... WddxRecordset object 797 798 Chapter 6: WDDX JavaScript Objects CHAPTER 7 ColdFusion ActionScript Functions This chapter explains the syntax and usage of the two server-side ActionScript functions, CF.query and CF.http. Contents CF.query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800 CF.http . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801 799 CF.query Description Performs queries against ColdFusion data sources. Return value Returns a RecordSet object.W Syntax CF.query ({ datasource:"data source name", sql:"SQL stmts", username:"username", password:"password", maxrows:number, timeout:milliseconds }) Arguments Arguments Req/Opt Description datasource Required Name of the data source from which the query retrieves data. sql Required SQL statement. username Optional Username. Overrides the username specified in the data source setup. password Optional Password. Overrides the password specified in the data source setup. maxrows Optional Maximum number of rows to return in the record set. timeout Optional Maximum number of seconds for the query to execute before returning an error indicating that the query has timed out. Can only be used in named arguments. Usage You can code the CF.query function using named or positional arguments. You can invoke all supported arguments using the named argument style, as follows: CF.query({datasource:"datasource", sql:"sql stmt", username:"username", password:"password", maxrows:"maxrows", timeout:"timeout"}); Note: The named argument style uses curly braces {} to surround the function arguments. Positional argument style, which is a shorthand coding style, does not support all arguments. Use the following syntax to code the CF.query function using positional arguments: CF.query(datasource, CF.query(datasource, CF.query(datasource, CF.query(datasource, sql); sql, maxrows); sql, username, password); sql, username, password, maxrows); Note: Do not use curly braces {} with positional arguments. You can manipulate the record set returned by the CF.query function using methods in the RecordSet ActionScript class. The following are some of the methods available in the RecordSet class: 800 Chapter 7: ColdFusion ActionScript Functions • • • • • • • • RecordSet.getColumnnames RecordSet.getLength RecordSet.getItemAt RecordSet.getItemID RecordSet.sortItemsBy RecordSet.getNumberAvailable RecordSet.filter RecordSet.sort For more information on using server-side ActionScript, see Chapter 30, “Using Server-Side ActionScript,” of Developing ColdFusion MX Applications. For more detailed information about the RecordSet ActionScript class, see Using Flash Remoting. Example // Define a function to do a basic query // Note use of positional arguments function basicQuery() { result = CF.query("myquery", "cust_data", "SELECT * from tblParks"); return result; } // Example function declaration using named arguments function basicQuery() { result = CF.query({datasource:"cust_data", sql:"SELECT * from tblParks"}); return result; } // Example of the CF.query function using maxrows argument function basicQueryWithMaxRows() { result = CF.query("cust_data", "SELECT * from tblParks", 25); return result; } // Example of the CF.query function with username and password function basicQueryWithUser() { result = CF.query("cust_data", "SELECT * from tblParks", "wsburroughs", "migraine1"); return result; } CF.http Description Executes HTTP POST and GET operations on files. (POST operations upload MIME file types to a server, or post cookie, formfield, URL, file, or CGI variables directly to a server.) Return value Returns an object containing properties that you reference to access data. CF.http 801 Syntax CF.http ({ method:"get or post", url:"URL", username:"username", password:"password", resolveurl:"yes or no", params:arrayvar, path:"path", file:"filename" }) Arguments 802 Arguments Req/Opt Description method Required One of two arguments: • get: downloads a text or binary file or creates a query from the contents of a text file. • post: sends information to the server page or CGI program for processing. Requires the params argument. url Required The absolute URL of the host name or IP address of the server on which the file resides. The URL must include the protocol (http or https) and host name. username Optional When required by a server, a username. password Optional When required by a server, a password. resolveurl Optional For Get and Post methods. • Yes or No. Default is No. For GET and POST operations, if Yes, the page reference that is returned into the Filecontent property has its internal URLs fully resolved, including port number, so that links remain intact. The following HTML tags, which can contain links, are resolved: - img src - a href - form action - applet code - script src - embed src - embed pluginspace - body background - frame src - bgsound src - object data - object classid - object codebase - object usemap params Optional HTTP parameters passed as an array of objects. Supports the following parameter types: • name • type • value CF.http params are passed as an array of objects. The params argument is required for POST operations. Chapter 7: ColdFusion ActionScript Functions Arguments Req/Opt Description path Optional The path to the directory in which to store files. When using the path argument, the file argument is required. file Optional Name of the file that is accessed. For GET operations, defaults to the name specified in the url argument. Enter path information in the path argument. This argument is required if using the path argument. Usage You can write the CF.http function using named arguments or positional arguments. You can invoke all supported arguments using the named argument style, as follows: CF.http({method:"method", url:"URL", username:"username", password:"password", resolveurl:"yes or no", params:arrayvar, path:"path", file:"filename"}); Note: The named argument style uses curly braces {} to surround the function arguments. Positional arguments let you use a shorthand coding style. However, not all arguments are supported for the positional argument style. Use the following syntax to code the CF.http function using positional arguments: CF.http(url); CF.http(method, url); CF.http(method, url, username, password); CF.http(method, url, params, username, password); Note: Do not use curly braces {} with positional arguments. The following parameters can only be passed as an array of objects in the params argument in the CF.http function: Parameter Description name The variable name for data that is passed type The transaction type: • URL • FormField • Cookie • CGI • File value Value of URL, FormField, Cookie, File, or CGI variables that are passed The CF.http function returns data as a set of object properties, as described in the following table: Property Description Text A Boolean value that indicates whether the specified URL location contains text data. Charset The charset used by the document specified in the URL. HTTP servers normally provide this information, or the charset is specified in the charset parameter of the Content-Type header field of the HTTP protocol. For example, the following HTTP header announces that the character encoding is EUC-JP: Content-Type: text/html; charset=EUC-JP CF.http 803 Property Description Header Raw response header. For example, macromedia.com returns the following header: HTTP/1.1 200 OK Date: Mon, 04 Mar 2002 17:27:44 GMT Server: Apache/1.3.22 (Unix) mod_perl/1.26 Set-Cookie: MM_cookie=207.22.48.162.4731015262864476; path=/; expires=Wed, 03-Mar-04 17:27:44 GMT; domain=.macromedia.com Connection: close Content-Type: text/html Filecontent File contents, for text and MIME files. Mimetype MIME type. Examples of MIME types include text/html, image/png, image/ gif,video/mpeg, text/css, and audio/basic. responseHeader Response header. If there is only one header key, its value can be accessed as simple type. If there are multiple header keys, the values are put in an array in a responseHeader structure. Statuscode HTTP error code and associated error string. Common HTTP status codes returned in the response header include: 400: Bad Request 401: Unauthorized 403: Forbidden 404: Not Found 405: Method Not Allowed You access these attributes using the get function: function basicGet() { url = "http://localhost:8100/"; // Invoke with just the url. This is an HTTP GET. result = CF.http(url); return result.get("Filecontent"); } Note: For more information on using server-side ActionScript, see Chapter 30, “Using Server-Side ActionScript,” of Developing ColdFusion MX Applications. Example The following examples show a number of the ways to use the CF.http function: function postWithNamedArgs() { // Set up the array of Post parameters. params = new Array(); params[1] = {name:"arg1", type:"FormField", value:"value1"}; params[2] = {name:"arg2", type:"URL", value:"value2"}; params[3] = {name:"arg3", type:"CGI", value:"value3"}; url = "http://localhost:8100/"; path = application.getContext("/").getRealPath("/"); file = "foo.txt"; 804 Chapter 7: ColdFusion ActionScript Functions result = CF.http({method:"post", url:url, username:"karl", password:"salsa", resolveurl:true, params:params, path:path, file:file}); if (result) return result.get("Statuscode"); return null; } // Example of a basic HTTP GET operation // Shows that HTTP GET is the default function basicGet() { url = "http://localhost:8100/"; // Invoke with just the url. This is an HTTP GET. result = CF.http(url); return result.get("Filecontent"); } // Example showing simple array created to pass params arguments function postWithParams() { // Set up the array of Post parameters. These are just like cfhttpparam tags. params = new Array(); params[1] = {name:"arg2", type:"URL", value:"value2"}; url = "http://localhost:8100/"; // Invoke with the method, url, and params result = CF.http("post", url, params); return result.get("Filecontent"); } // Example with username and params arguments function postWithParamsAndUser() { // Set up the array of Post parameters. These are just like cfhttpparam tags. params = new Array(); params[1] = {name:"arg2", type:"URL", value:"value2"}; url = "http://localhost:8100/"; // Invoke with the method, url, params, username, and password result = CF.http("post", url, params, "karl", "salsa"); return result.get("Filecontent"); } CF.http 805 806 Chapter 7: ColdFusion ActionScript Functions


Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.4
Linearized                      : No
Modify Date                     : 2005:09:06 12:59:54-07:00
Create Date                     : 2003:07:01 12:02:19Z
Page Count                      : 806
Creation Date                   : 2003:07:01 12:02:19Z
Mod Date                        : 2005:09:06 12:59:54-07:00
Producer                        : Acrobat Distiller 5.0.5 (Windows)
Author                          : ladler
Metadata Date                   : 2005:09:06 12:59:54-07:00
Creator                         : ladler
Title                           : langref.book
Page Mode                       : UseOutlines
EXIF Metadata provided by EXIF.tools

Navigation menu