MACROMEDIA COLFUSION MX 7-CFML Reference

Cfml reference
Hide thumbs Also See for COLFUSION MX 7-CFML:
Table of Contents

Advertisement

Quick Links

COLDFUSION
MX 7
®
CFML Reference

Advertisement

Table of Contents
loading

Summary of Contents for MACROMEDIA COLFUSION MX 7-CFML

  • Page 1 COLDFUSION MX 7 ® CFML Reference...
  • Page 2 Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.
  • Page 3: Table Of Contents

    CONTENTS ........... 5 INTRODUCTION CHAPTER 1: Reserved Words and Variables .
  • Page 4 CHAPTER 5: Application.CFC Reference ......945 Application variables ..........945 Method summary .
  • Page 5: Introduction

    CFML Reference is your primary ColdFusion Markup Language (CFML) reference. Use this manual to learn about CFML tags and functions, ColdFusion expressions, and using JavaScript objects for WDDX in Macromedia ColdFusion MX 7. It also provides detailed references for Java and C++ CFX interfaces.
  • Page 6 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. Introduction:...
  • Page 7: Chapter 1: Reserved Words And Variables

    CHAPTER 1 Reserved Words and Variables This chapter provides information on Macromedia ColdFusion reserved words, and lists scope variables. Contents Reserved words ............. 7 Scope-specific built-in variables .
  • Page 8 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 •...
  • Page 9: Scope-Specific Built-In Variables

    FROM FULL GLOBAL GOTO GRANT GROUP HAVING HOUR IDENTITY IMMEDIATE INDICATOR INITIALLY INNER INPUT INSENSITIVE INSERT INTEGER INTERSECT INTERVAL INTO ISOLATION JOIN LANGUAGE LAST LEADING LEFT LEVEL LIKE LOCAL LOWER MATCH MINUTE MODULE MONTH NAMES NATIONAL NATURAL NCHAR NEXT NULL NULLIF NUMERIC OCTET_LENGTH...
  • Page 10 You use the tag to limit the scope of CFML constructs that modify shared data structures, cflock files, and CFXs, to ensure that modifications occur sequentially. For more information, see on page 270, and Chapter 15, “Using Persistent Data and Locking” in ColdFusion MX cflock Developer’s Guide.
  • Page 11: Custom Tag Variables

    The predefined application and session variables are as follows: Application.ApplicationName Session.CFID Session.CFToken Session.URLToken Custom tag variables A ColdFusion custom tag returns the following variables: ThisTag.ExecutionMode ThisTag.HasEndTag ThisTag.GeneratedContent ThisTag.AssocAttribs[index] A custom tag can set a Caller variable to provide information to the caller. The Caller variable is set as follows: <cfset Caller.variable_name = "value">...
  • Page 12 cffile cfftp cfhttp cfindex cfldap 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 attribute: name queryname.CurrentRow queryname.RecordCount queryname.ColumnList CFCATCH variables Within a block, the active exception properties can be accessed as the following cfcatch variables:...
  • Page 13 CFCATCH.Line CFCATCH.KnownLine CFDIRECTORY variables , returns a query object as follows, where queryname is tag, with cfdirectory action=list attribute value: name queryname.Name queryname.Size queryname.Type queryname.DateLastModified queryname.Attributes queryname.Mode CFERROR variables When generates an error page, the following error variables are available if cferror type="request"...
  • Page 14 CFFILE ACTION=Upload variables File variables are read-only. Use the prefix to reference file variables; for example, CFFILE . The prefix is deprecated in favor of the prefix. CFFILE.ClientDirectory File CFFILE 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...
  • Page 15 queryname.LastModified[row] queryname.Attributes queryname.IsDirectory queryname.Mode CFHTTP variables operation can return text and binary files. Files are downloaded and the contents cfhttp get stored in a variable or file, depending on the MIME type, as follows: CFHTTP.FileContent CFHTTP.MimeType CFHTTP.Header [http_hd_key] CFHTTP.ResponseHeader CFHTTP.StatusCode CFLDAP variables tag returns information about the LDAP query, as follows: cfldap action=query...
  • Page 16: Standard Cgi Variables

    tag returns the following variables: cfstoredproc CFSTOREDPROC.ExecutionTime CFSTOREDPROC.StatusCode CFREGISTRY variables tag returns a query record set that you can reference after executing the cfregistry GetAll action, as follows, where queryname is the attribute value: name queryname.Entry queryname.Type queryname.Value CFSEARCH variables operation returns the following variables, where searchname is the attribute cfsearch...
  • Page 17: Cgi Environment Variables

    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 variables are available only when you CERT_ISSUER CERT_SUBJECT CLIENT_CERT_ENCODED use client certificates. CGI environment variables When a browser makes a request to a server, the web server and the browser create environment variables.
  • Page 18 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 self- referencing URLs.
  • Page 19 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 =...
  • Page 20 Chapter 1: Reserved Words and Variables...
  • Page 21: Chapter 2: Coldfusion Tags

    CHAPTER 2 ColdFusion Tags ColdFusion Markup Language (CFML) includes a set of tags that you use in Macromedia ColdFusion MX 7 pages to interact with data sources, manipulate data, and display output. CFML tag syntax is similar to HTML element syntax.
  • Page 22 CFML tag Category Description Forms tags Provides a calendar from which to select a date cfcalendar Flow-control tags Used with the tags cfcase cfswitch cfdefaultcase Exception handling tags, Catches exceptions in ColdFusion pages cfcatch Flow-control tags Data output tags Generates and displays a chart cfchart Data output tags Defines chart data points...
  • Page 23 CFML tag Category Description Data output tags, Flushes currently available data to client cfflush Page processing tags Forms tags Builds input form; performs client-side input cfform validation Forms tags Groups form control into a containing object cfformgroup Forms tags Adds text and dividing rules to Flash forms cfformitem Forms tags,...
  • Page 24 CFML tag Category Description Application framework Ensures data integrity and synchronizes cflock tags execution of CFML code Data output tags, Writes a message to a log file cflog Other tags Security tags Defines a container for user login and cflogin authentication code Security tags Identifies an authenticated user to ColdFusion...
  • Page 25 CFML tag Category Description Other tags, Reads, writes, and deletes keys and values in a cfregistry Variable manipulation Windows system registry tags Exception handling tags Embeds a ColdFusion Report Builder or Crystal cfreport Reports report Exception handling tags Passes an input parameter to a ColdFusion cfreportparam Report Builder report Exception handling tags...
  • Page 26: Tags By Function

    CFML tag Category Description Forms tags Creates tree control element; used in cftree cfform Forms tags Populates a tree control element in a form; used cftreeitem with cftree Exception handling tags, Catches exceptions in ColdFusion pages cftry Flow-control tags Database manipulation Updates rows in a database data source cfupdate tags...
  • Page 27: Database Manipulation Tags

    Database manipulation tags cfinsert cfprocresult cfstoredproc cfobjectcache cfquery cftransaction cfprocparam cfqueryparam cfupdate Data output tags cfchart cfdocumentitem cfoutput cfchartdata cfdocumentsection cfprocessingdirective cfchartseries cfflush cfreport cfcol cfheader cfreportparam cfcontent cflog cfsilent cfdocument cfoutput cftable Debugging tags cfdump cftimer cftrace Exception handling tags cfcatch cfrethrow cftry...
  • Page 28: Flow-Control Tags

    Flow-control tags cfabort cfexecute cfrethrow cfbreak cfexit cfswitch cfcase cfif cfthrow cfdefaultcase cfinclude cftry cfelse cflocation cfelseif cfloop Forms tags cfapplet cfgrid cfselect cfcalendar cfgridcolumn cfslider cfform cfgridrow cftextarea cfformgroup cfgridupdate cftree cfformitem cfinput cftreeitem Internet Protocol tags cfftp cfldap cfmailpart cfhttp cfmail...
  • Page 29: Tag Changes Since Coldfusion 5

    Other tags cflog cfregistry 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 ..........29 Deprecated tags, attributes, and values .
  • Page 30 Attribute or value Added in this ColdFusion release ColdFusion MX 7 cfcomponent style namespace serviceportname , and porttypename wsdlfile attributes bindingname Extended functionality for the hint attributes when displayname publishing document-literal style web services ColdFusion MX attribute ColdFusion MX 7 cfcontent variable attribute for...
  • Page 31 Attribute or value Added in this ColdFusion release attribute ColdFusion MX 7 cfhttp result , and ColdFusion MX 6.1 HEAD DELETE OPTIONS values of attribute TRACE method multipart getasbinary proxyUser attributes proxyPassword ColdFusion MX charset firstrowasheaders attributes values of ColdFusion MX 6.1 cfhttpparam header body...
  • Page 32 Attribute or value Added in this ColdFusion release attribute for web ColdFusion MX 7 cfinvoke servicePort services ColdFusion MX attribute ColdFusion MX 7 cfinvokeargument omit ColdFusion MX returnAsBinary attribute ColdFusion MX 7 cfldap ColdFusion MX cflogin ColdFusion MX cfloginuser ColdFusion MX cflogout attribute ColdFusion MX...
  • Page 33 Attribute or value Added in this ColdFusion release ColdFusion MX 7 cfsearch category categoryTree status suggestions contextPassages contextBytes contextHighlightBegin contextHighlightEnd attributes previousCriteria , and natural internet values of internet_basic type attribute attribute can take a list ColdFusion MX 7 cfselect selected enabled group...
  • Page 34 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. Attribute or value Deprecated as of this ColdFusion release cfcache attributes ColdFusion MX...
  • Page 35 Attribute or value Deprecated as of this ColdFusion release ColdFusion MX cfservlet ColdFusion MX cfservletparam cfslider ColdFusion MX imgStyle grooveColor refreshLabel tickmarkimages tickmarklabels tickmarkmajor attributes tickmarkminor ColdFusion MX cfstoredproc connectString dbName dbServer dbtype provider providerDSN attributes ColdFusion MX 7 cftextinput cfupdate ColdFusion MX connectString...
  • Page 36 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...
  • Page 37 <p>The value of myVariable after incrementing through the loop #Counter# times #myVariable# </cfoutput> <h3>Example B: Use cfabort to halt the instructions with showmessage attribute and cferror</h3> <!--- Reset the variable and show the use of cfabort. ---> <cfset myVariable = 3> <!--- now, perform a loop that increments this value --->...
  • Page 38 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 tag is optional. If you use it within , and the cfform cfform method...
  • Page 39 Attribute Req/Opt Default Description align Optional Alignment: • Left • Right • Bottom • Top • TextTop • Middle • AbsMiddle • Baseline • AbsBottom notSupported Optional 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.
  • Page 40 cfapplication Description Defines the scope of a ColdFusion application; enables and disables storage of Client variables; specifies the Client variable storage mechanism; enables Session variables; and sets Application variable timeouts. Category Application framework tags Syntax <cfapplication name = "application_name" loginStorage = "cookie" or "session" clientManagement = "yes"...
  • Page 41 Attributes Attribute Req/Opt Default Description name Name of application. Up to 64 characters. Description For Application and Session variables: Required. For Client variables: Optional loginStorage Optional cookie • cookie: store login information in the Cookie scope. • session: store login information in the Session scope.
  • Page 42 Attribute Req/Opt Default Description setDomainCookies Optional • yes: uses domain cookies for CFID and CFTOKEN cookies and for all Client variables when using cookies for client variable storage. Required for applications running on clusters. • no: uses host-specific cookies for CFID, CFTOKEN, and all client variable cookies.
  • Page 43 The ColdFusion MX cross-site scripting protection operation is done when ColdFusion MX processes the application settings at the beginning of a request. Thus, it can process the URL, and Cookie, CGI, and Form variables in a user’s request. By default, it replaces occurrences of the following tag names with the text InvalidTag: object, embed, script, applet, and meta.
  • Page 44 <!--- Use the application scope for the application variable to prevent race condition. This variable keeps track of total number of turtlenecks sold. -- -> <cflock scope = "Application" timeout = "30" type = "Exclusive"> <cfset application.number = application.number + session.numPurchased> </cflock>...
  • Page 45 cfargument Description Creates a parameter definition within a component definition. Defines a function argument. Used within a tag. cffunction Category Extensibility tags Syntax <cfargument name="string" type="data type" required="yes" or "no" default="default value" displayname="descriptive name" hint="extended description"> See also cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfobject, cfproperty, cfreturn Attributes Attribute...
  • Page 46 Attribute Req/Opt Default Description required Optional Note: All arguments are required when invoked as a web service, irrespective of how they are defined. Specifies whether the parameter is required to execute the component method. The parameter is not required if you specify a attribute.
  • Page 47 cfassociate Description Allows subtag data to be saved with a base tag. Applies only to custom tags. Category Application framework tags Syntax <cfassociate baseTag = "base_tag_name" dataCollection = "collection_name"> See also ; “High-level data exchange” in Chapter 11, cfapplication, cferror, cflock, cfmodule “Creating and Using Custom CFML Tags,”...
  • Page 48 cfauthenticate Description This tag is obsolete. Use the newer security tools; see “Conversion functions” on page 453 Chapter 16, “Securing Applications” in ColdFusion MX Developer’s Guide. History ColdFusion MX: this tag is obsolete. It does not work in ColdFusion MX and later releases. Chapter 2: ColdFusion Tags...
  • Page 49 cfbreak Description Used within a tag. Breaks out of a loop or switch block. cfloop cfswitch Category Flow-control tags Syntax <cfbreak> See also ; “cfloop and cfabort cfexecute cfif cflocation cfloop cfswitch cfthrow cftry cfbreak” in Chapter 2, “Elements of CFML,” in ColdFusion MX Developer’s Guide Example <!--- This shows the use of cfbreak to exit a loop when a condition is met.--->...
  • Page 50 <cfelse> <br> Searching... </cfif> </cfloop> </cfif> Chapter 2: ColdFusion Tags...
  • Page 51 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.
  • Page 52 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.
  • Page 53 (Macromedia recommends that you do not use server-side only caching. Macromedia recommends that you use combination caching.)
  • Page 54 Description Puts an interactive Macromedia Flash format calendar in an HTML or Flash form. Not supported in XML format forms. The calendar lets a user select a date for submission as a form variable. Category Forms tags Syntax <cfcalendar name = "name of calendar"...
  • Page 55 Attribute Req/Opt Default Description startRange Optional The start of a range of dates that are disabled. Users cannot select dates from this date through the date specified by the attribute. endRange endRange Optional The end of a range of dates that are disabled. Users cannot select dates from the date specified by the attribute through this date.
  • Page 56 Attribute Req/Opt Default Description visible Optional Flash only: Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank. tooltip Optional Flash only: Text to display when the mouse pointer hovers over the control. onChange Optional ActionScript that runs when the user selects a date.
  • Page 57 <cfparam name="Form.enddate" default="#dateformat(now()-1, 'mm/dd/yyyy')#"> <cfparam name="Form.selectdate" default="#dateformat(now(), 'mm/dd/yyyy')#"> <!--- If the form has been submitted, display the selected date. ---> <cfif isDefined("Form.submitit")> <cfoutput><b>You selected #Form.selectedDate#</b><br><br></cfoutput> </cfif> <b>Please select a date on the calendar and click Save.</b><br> <br> <cfform name="form1" format="Flash" skin="haloBlue" width="375" height="350" > <cfcalendar name="selectedDate"...
  • Page 58 cfcase Description Used only inside the tag body. Contains code to execute when the expression specified cfswitch in the tag has one or more specific values. cfswitch Category Flow-control tags Syntax <cfcase value = "value or delimited set of values" delimiters = "delimiter characters">...
  • Page 59 <cfset score="7"> <cfswitch expression="#score#"> <cfcase value="10"> <cfset grade="A"> </cfcase> <cfcase value="9;8" delimiters=";"> <cfset grade="B"> </cfcase> <cfcase value="7;6" delimiters=";"> <cfset grade="C"> </cfcase> <cfcase value="5;4;" delimiters=";"> <cfset grade="D"> </cfcase> <cfdefaultcase> <cfset grade="F"> </cfdefaultcase> </cfswitch> <cfoutput> Your grade is #grade# </cfoutput> cfcase...
  • Page 60 cfcatch Description Used inside a tag. Together, they catch and process exceptions in ColdFusion pages. cftry 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...
  • Page 61 Attributes Attribute Req/Opt Default Description type Optional • 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 •...
  • Page 62 You can code tags in any order to catch a custom exception type. cfcatch If you specify , the tag catches only custom exceptions that have type = "Application" cfcatch type in the tag that defines them. Application cfthrow , and tags throw an exception of cfinclude cfmodule...
  • Page 63 Advanced Exception types You can specify the following advanced exception types in the attribute: type 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...
  • Page 64 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 <!--- cfcatch example, using TagContext to display the tag stack. ---> <h3>cftry Example</h3> <!--- Open a cftry block. ---> <cftry>...
  • Page 65 <p>Caught an exception, type = #CFCATCH.TYPE# </p> <p>The contents of the tag stack are:</p> <cfdump var="#cfcatch.tagcontext#"> </cfoutput> </cfcatch> </cftry> cfcatch...
  • Page 66 cfchart Description Generates and displays a chart. Category Data output tags, Extensibility tags; “Controlling chart appearance” in Chapter 31, “Creating Charts and Graphs,” in ColdFusion MX Developer’s Guide Syntax Syntax 1 <!--- This syntax uses an XML file or string to specify the chart style. ---> <cfchart style = "XML string or filename">...
  • Page 67 See also cfchartdata cfchartseries History ColdFusion MX 7: • Added attributes. style title • Added support for eight-digit hexadecimal values to specify RGB color and transparency. • Removed the attribute. rotated • Renamed the column chart type to be horizontalbar chart type. ColdFusion MX 6.1: •...
  • Page 68 Attribute Req/Opt Default Description fontBold Optional Whether to make the text bold: • yes • no fontItalic Optional Whether to make the text italicized: • yes • no fontSize Optional Font size; integer. foregroundColor Optional black Color of text, grid lines, and labels. Hexadecimal value or supported named color;...
  • Page 69 Attribute Req/Opt Default Description seriesPlacement Optional default Relative positions of series in charts that have more than one data series. • default: ColdFusion determines relative positions, based on graph types • cluster • stacked • percent show3D Optional Whether to display the chart with three- dimensional appearance: •...
  • Page 70 Attribute Req/Opt Default Description tipStyle Optional mouseOver Determines the action that opens a pop-up window to display information about the current chart element. • mouseDown: display if the user positions the cursor at the element and clicks the mouse. Applies only to Flash format graph files.
  • Page 71 Attribute Req/Opt Default Description yAxisType Optional category Currently has no effect, as the y-axis is always used for data values. yOffset Optional Number of units by which to display the chart as angled, vertically. Applies if show3D="yes" The number can be between -1 and 1, where "-1"...
  • Page 72 Color name RGB value Teal ##008080 White ##FFFFFF Yellow ##FFFF00 For all other color values, you must enter the hexadecimal value. You can enter a six-digit value, which specifies the RGB value, or an eight-digit value, which specifies the RGB value and the transparency.
  • Page 73 <h1>Employee Salary Analysis</h1> <!--- Bar graph, from Query of Queries ---> <cfchart format="flash" xaxistitle="Department" yaxistitle="Salary Average"> <cfchartseries type="bar" query="DataTable" itemcolumn="Dept_Name" valuecolumn="avgSal"> <cfchartdata item="Facilities" value="35000"> </cfchartseries> </cfchart> cfchart...
  • Page 74 cfchartdata Description Used with the tags. This tag defines chart data points. Its data is cfchart cfchartseries submitted to the tag. cfchartseries Category Data output tags, Extensibility tags Syntax <cfchartdata item = "text" value = "number"> See also ; Chapter 31, “Creating Charts and Graphs,” in ColdFusion MX cfchart cfchartseries Developer’s Guide...
  • Page 75 </cfquery> <!--- Reformat the generated numbers to show only thousands. ---> <cfloop index = "i" from = "1" to = "#DataTable.RecordCount#"> <cfset DataTable.sumSal[i] = Round(DataTable.sumSal[i]/1000)*1000> <cfset DataTable.avgSal[i] = Round(DataTable.avgSal[i]/1000)*1000> </cfloop> <h1>Employee Salary Analysis</h1> <!--- Bar graph, from Query of Queries. ---> <cfchart format="flash"...
  • Page 76 cfchartseries Description Used with the tag. This tag defines the chart style in which the data displays: bar, line, cfchart pie, and so on. Category Data output tags, Extensibility tags Syntax <cfchartseries colorlist = "list"> itemColumn="queryColumn" markerStyle="style" paintStyle="plain, raise, shade, light" query="queryName"...
  • Page 77 Attributes Attribute Req/Opt Default Description colorlist Optional Sets colors for each data point. Applies if the attribute is cfchartseries type pyramid area , or horizontalbar cone cylinder step Comma-delimited list of hexadecimal values or supported, named web colors; see the name list and information about six- and eight-digit hexadecimal values in the Usage section.
  • Page 78 Attribute Req/Opt Default Description type Required Sets the chart display style: • bar • line • pyramid • area • horizontalbar • cone • curve • cylinder • step • scatter • pie valueColumn Required if Name of a column in the query specified in the query attribute;...
  • Page 79 <!--- Use a query of queries to generate a new query with ---> <!--- statistical data for each department. ---> <!--- AVG and SUM calculate statistics. ---> <!--- GROUP BY generates results for each department. ---> <cfquery dbtype = "query" name = "DataTable"> SELECT Dept_Name, AVG(Salary) AS avgSal,...
  • Page 80 cfcol Description Defines table column header, width, alignment, and text. Used within a tag. cftable Category Data output tags Syntax <cfcol header = "column_header_text" width = "number_indicating_width_of_column" align = "left" or "right" or "center" text = "column_text"> See also ; “Performing file operations with cfftp” in Chapter 40, cfcontent cfoutput cftable...
  • Page 81 Example <!--- This example shows the use of cfcol and cftable to align information returned from a query. ---> <!--- query selects information from cfdocexamples data source. ---> <cfquery name = "GetEmployees" dataSource = "cfdocexamples"> SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees </cfquery>...
  • Page 82 cfcollection Description Creates and administers Verity search engine collections. Category Extensibility tags Syntax <cfcollection action = "action" collection = "collection_name" path = "path_to_verity_collection" language = "language" name = "queryname" categories = "yes" or "no"> See also cfexecute, cfindex, cfobject, cfreport, cfsearch, cfwddx History ColdFusion MX 7:...
  • Page 83 Attributes Attribute Req/Opt Default Description action Required; see list • categorylist: retrieves categories from the collection and Usage indicates how many documents are in each one. Returns a structure of structures in which the category representing each substructure is associated with a number of documents.
  • Page 84 The following table shows the dependence relationships among this tag’s attribute values: This attribute For this action attribute value: is required, list create optimize repair delete categorylist optional, or unnecessary (blank): Required Required Required Required Required Required collection Required Required path language Optional Optional...
  • Page 85 Column Contents LASTMODIFIED The date and time that the collection was last changed. MAPPED Obsolete NAME The name of the collection. ONLINE Obsolete PATH Absolute path to the collection. REGISTERED Obsolete SIZE The size of the collection, expressed in kilobytes. The ColdFusion MX Administrator Verity >...
  • Page 86 Eastern European/Middle Eastern Language Pack Arabic Greek Polish Turkish Bulgarian Hebrew Russian Czech Hungarian Russian2 The default location of Verity collections is as follows: • Server configuration: Windows: C:\CFusionMX7\verity\collections UNIX system: /opt/coldfusionmx7/verity/collections • J2EE configuration: webapp_root/WEB-INF/cfusion/verity/collections Example <!------------------------------------------------------------------------- (coll_actn.cfm) Check for server platform and use its default Verity Collection directory. If you did not install ColdFusion MX in the default directory, or if you use the J2EE configuration, or if your webroot is not C:\CFusionMX7\wwwroot, you might need to change the path in this example.
  • Page 87 </cfcase> </cfswitch> <cfelse> <h3>Please enter a name for your collection</h3> </cfif> </cfif> <!-------------------------------------------------------------------- (coll_form.cfm) Form to specify the collection name and action coll_form.cfm ---------------------------------------------------------------------> <form action="coll_actn.cfm" method="POST" > <select name="CollectionAction"> <option value="Create">Create this collection <option value="Optimize">Optimize this collection <option value="Repair">Repair this collection <option value="Delete">Delete this collection </select>...
  • Page 88 cfcomponent Description Creates and defines a component object; encloses functionality that you build in CFML and enclose within tags. This tag contains one or more tags that define cffunction cffunction methods. Code within the body of this tag, other than tags, is executed when the cffunction component is instantiated.
  • Page 89 History ColdFusion MX 7: • Added support for publishing document-literal style web services. • Added the , and style namespace serviceportname porttypename wsdlfile attributes. bindingname • Extended functionality for the attributes when publishing document- hint displayname literal style web services. ColdFusion MX: Added this tag.
  • Page 90 Attribute Req/Opt Default Description porttypename Optional Specifies the attribute of the element in name porttype the WSDL. If you don’t specify this attribute, ColdFusion MX derives the value from the CFC class name. This attribute applies only when style="document" bindingname Optional Specifies the attribute of the...
  • Page 91 Example <cfcomponent> <cffunction name="getEmp"> <cfquery name="empQuery" datasource="cfdocexamples" > SELECT FIRSTNAME, LASTNAME, EMAIL FROM tblEmployees </cfquery> <cfreturn empQuery> </cffunction> <cffunction name="getDept"> <cfquery name="deptQuery" datasource="cfdocexamples" > SELECT * FROM tblDepartments </cfquery> <cfreturn deptQuery> </cffunction> </cfcomponent> cfcomponent...
  • Page 92 cfcontent Description Does either or both of the following: • Sets the MIME content encoding header for the current page; if the encoding information includes a character encoding, sets the character encoding of generated output. • Sends the contents of a file, or of a variable that contains binary data, as the page output. To restrict this tag, use the Sandbox Security feature of the ColdFusion MX Administrator.
  • Page 93 Attributes Attribute Req/Opt Default Description type Optional 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.
  • Page 94 Attribute Req/Opt Default Description variable Optional Name of a ColdFusion MX binary variable whose contents can be displayed by the browser, such as the contents of a chart generated by the tag or a PDF or Excel file retrieved by cfchart tag.
  • Page 95 For file types that might contain executable code, such as Microsoft Excel documents, most browsers always ask before opening the document. For these file types, the inline content disposition specification requests the browser to display the file directly if the user selects to open the file.
  • Page 96 <!--- CFCONTENT EXAMPLE 4 This example triggers a download of a Word document then deletes the original from the "temp" directory. The user will be prompted with an option to save the file or open it in the browser. ---> <cfheader name="Content-Disposition"...
  • Page 97 cfcookie Description Defines web browser cookie variables, including expiration and security options. Category Forms tags, Variable manipulation tags Syntax <cfcookie name = "cookie_name" value = "text" expires = "period" secure = "yes" or "no" path = "url" domain = ".domain"> See also cfdump, cfparam, cfregistry, cfsavecontent, cfschedule, cfset...
  • Page 98 Attribute Req/Opt Default Description 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. •...
  • Page 99 Example <!--- This example shows how to set/delete a cfcookie variable. ---> <!--- Select users who have entered comments into a sample database. ---> <cfquery name = "GetAolUser" dataSource = "cfdocexamples"> SELECT EMail, FromUser, Subject, Posted FROM Comments </cfquery> <html> <body>...
  • Page 100 cfdefaultcase Description Used only inside the tag body. Contains code to execute when the expression specified cfswitch in the tag does not match a of the value specified by a tag. cfswitch cfcase Category Flow-control tags Syntax <cfdefaultcase> See also ;...
  • Page 101 </cfdefaultcase> </cfswitch> <cfoutput> Your grade is #grade# </cfoutput> cfdefaultcase...
  • Page 102 cfdirectory Description Manages interactions with directories. Category File management tags Syntax <cfdirectory action = "directory action" directory = "directory name" name = "query name" filter = "list filter" mode = "permission" sort = "sort specification" newDirectory = "new directory name" recurse = "yes"...
  • Page 103 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. •...
  • Page 104 Usage 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.
  • Page 105 The following table shows examples of patterns and file names that they match: Pattern Matches foo.* Any file called foo with any extension; for example, foo.html, foo.cfm, and foo.xml. *.html All files with the suffix .html, but not files with the suffix .htm. All files with two-character names.
  • Page 106 </cfif> <cfelse> <!--- If FALSE, post message or do some other function. ---> <cfoutput><p>The directory did NOT exist.</p></cfoutput> </cfif> <!---EXAMPLE 3: List directories The following example creates both an array of directory names and a query that contains entries for the directories only. ---> <cfdirectory directory="C:/temp"...
  • Page 107 cfdocument Description Creates PDF or FlashPaper output from a text block containing CFML and HTML. Category Data output tags Syntax <cfdocument format = "PDF" or "FlashPaper" filename = "filename" overwrite = "yes" or "no" name = "output variable name" pagetype = "page type" pageheight = "page height in inches"...
  • Page 108 Attribute Req/Opt Default Description overwrite Optional Specifies whether ColdFusion MX overwrites an existing file. Used in conjunction with the filename attribute name Optional Specifies the name of an existing variable into which the tag stores the PDF or FlashPaper output. pagetype Optional Specifies the page size into which ColdFusion...
  • Page 109 Attribute Req/Opt Default Description encryption Optional None only) Specifies whether the output is format="PDF" encrypted: • 128-bit • 40-bit • none ownerpassword Optional only) Specifies an owner password. format="PDF" userpassword Optional only) Specifies a user password. format="PDF" permissions Optional only) Specifies one or more of the format="PDF"...
  • Page 110 tag does not support the Internet Explorer-specific HTML generated by cfdocument Microsoft Word. The PDF or FlashPaper document returned by the tag overwrites any previous cfdocument HTML in the input stream and ignores any HTML after the tag. </cfdocument> You cannot embed a tag in a tag.
  • Page 111 cfdocumentitem Description Specifies action items for a PDF or FlashPaper document created by the tag. Actions cfdocument include the following: • Page break • Header • Footer Category Data output tags Syntax <cfdocument ...> Syntax 1 <cfdocumentitem type = "pagebreak"/> Syntax 2 <cfdocumentitem type = "header"...
  • Page 112 You can use the cfdocument scope variable, cfdocument.currentpagenumber, to display the current page number in a header or footer. You can also use cfdocument.totalpagecount to display the total number of pages. For example: <cfdocumentItem type= "footer> #cfdocument.currentpagenumber# of #cfdocument.totalpagecount# </cfdocumentitem> You can use tags with or without the tag, as follows:...
  • Page 113 cfdocumentsection Description Divides a PDF or FlashPaper document into sections. By using this tag in conjunction with a tag, each section can have unique headers, footers, and page numbers. cfdocumentitem Category Data output tags Syntax <cfdocument ...> <cfdocumentsection margintop = "number" marginbottom = "number"...
  • Page 114 Usage Use the tag to divide a report into sections. Within each cfdocumentsection tag, you can use one or more tags to specify unique cfdocumentsection cfdocumentitem headers and footers for each section. When using , ColdFusion MX ignores HTML and CFML not enclosed cfdocumentsection within tags.
  • Page 115 </cfdocumentsection> </cfoutput> </cfdocument> cfdocumentsection...
  • Page 116 cfdump Description Use the tag to get the elements, variables, and values of most kinds of ColdFusion objects. cfdump 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...
  • Page 117 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: <cfif IsXmlDoc(mydoc) is "yes"> <cfdump var="#mydoc#">...
  • Page 118 cfelse Description Used as the last control block in a tag block to handle any case not identified by the cfif cfif tag or a tag. cfelseif Category Flow-control tags Syntax <cfif expression> HTML and CFML tags <cfelseif expression> HTML and CFML tags <cfelse>...
  • Page 119 cfelseif Description Used as a control block in a tag block to handle any case not identified by the tag or a cfif cfif tag. cfelseif Category Flow-control tags Syntax <cfif expression> HTML and CFML tags <cfelseif expression> HTML and CFML tags <cfelse>...
  • Page 120 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 <cferror type = "a type" template = "template_path"...
  • Page 121 Attribute Req/Opt Default Description mailTo Optional An e-mail address. This attribute is available on the error page as the variable . ColdFusion does not error.mailto automatically send anything to this address. exception Optional Type of exception that the tag handles: •...
  • Page 122 Page type Description Request Includes the error variables described in the Error Use as a backup error handler to Variables section. other error handling methods, including exception type. Cannot include CFML tags, but you can display values of the error variables by enclosing them in number signs (#), as in #error.MailTo# Validation...
  • Page 123 Page type Error variable Description Exception only error.message Error message associated with the exception. error.rootCause The root cause of the exception. This structure contains the information that is returned by a tag. For example, for a database exception, cfcatch the SQL statement that caused the error is in the error.RootCause.Sql variable.
  • Page 124 cfexecute Description Executes a ColdFusion developer-specified process on a server computer. Category Extensibility tags, Flow-control tags Syntax <cfexecute name = "application name" arguments = "command line arguments" outputFile = "output filename" variable = "variable name" timeout = "timeout interval"> </cfexecute> See also cfcollection, cfindex, cfobject, cfreport, cfsearch, cfwddx...
  • Page 125 Attribute Req/Opt Default Description outputFile Optional File to which to direct program output. If no outputfile attribute is specified, output is displayed on the page variable 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...
  • Page 126 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 <cfexit method = "method">...
  • Page 127 Example <h3>cfexit Example</h3> <p>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. <h3>Usage of cfexit</h3> <p>cfexit is used primarily to perform a conditional stop of processing inside a custom tag.
  • Page 128 cffile Description Manages interactions with server files. The following sections describe the actions of the tag: cffile • on page 131 cffile action = "append" • on page 133 cffile action = "copy" • on page 135 cffile action = "delete" •...
  • Page 129 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.
  • Page 130 <!--- First, check whether canned file exists. ---> <cfif FileExists("#GetTempDirectory()#foobar.txt") is "Yes"> <cfset fileExists="yes"> </cfif> <!--- Now, make the form that runs the example. ---> <form action="index.cfm" method="POST"> <h4>Type in some text to include in your file:</h4> <p> <cfif fileExists is "yes"> <p>A file exists (foobar.txt, in <cfoutput>#GetTempDirectory()#</cfoutput>).
  • Page 131 cffile action = "append" Description Appends text to a text file on the server. Syntax <cffile action = "append" file = "full_path_name" output = "string" addNewLine = "yes" or "no" attributes = "file_attributes_list" mode = "mode" charset = "charset_option" > See also cfdirectory History...
  • Page 132 Attribute Req/Opt Default Description 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 , all other attributes are attributes = "readOnly"...
  • Page 133 cffile action = "copy" Description Copies a file from one directory to another on the server. Syntax <cffile action = "copy" source = "full_path_name" destination = "full_path_name" mode = "mode" attributes = "file_attributes_list"> See also cfdirectory History See the History section of the main tag page.
  • Page 134 Example This example copies the keymemo.doc file to the c:\files\backup\ directory: <cffile action = "copy" source = "c:\files\upload\keymemo.doc" destination = "c:\files\backup\"> Chapter 2: ColdFusion Tags...
  • Page 135 cffile action = "delete" Description Deletes a file on the server. Syntax <cffile action = "delete" file = "full_path_name"> 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...
  • Page 136 cffile action = "move" Description Moves a file from one location to another on the server. Syntax <cffile action = "move" source = "full_path_name" destination = "full_path_name" mode = "mode" attributes = "file_attributes_list" charset = "charset_option"> See also cfdirectory History See the History section of the main tag page.
  • Page 137 Attribute Req/Opt Default Description 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 , all other attributes are attributes = "readOnly"...
  • Page 138 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 •...
  • Page 139 Attribute Req/Opt Default Description variable Required Name of variable to contain contents of text file. charset Optional Character The character encoding in which the file contents is encoding encoded. The following list includes commonly used values: identified • utf-8 by the file’s •...
  • Page 140 cffile action = "readBinary" Description Reads a binary file (such as an executable or image file) on the server, 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 function.
  • Page 141 cffile action = "rename" Description Renames or moves a file on the server. Syntax <cffile action = "rename" source = "full_path_name" destination = "path_name" mode = "mode" attributes = "file_attributes_list"> See also cfdirectory History See the History section of the main tag page.
  • Page 142 Example Windows Example: <!--- Source Document is read-only but when renamed it becomes normal (not hidden or read-only). ---> <cffile action = "rename" source = "c:\files\memo\readonlymemo.doc" destination = "c:\files\memo\normalmemo.doc" attributes="normal"> Unix Example: <cffile action = "rename" source = "#myWR#/memo/sample.txt" destination = "#myWR#/memo/other_sample.txt"...
  • Page 143 cffile action = "upload" Description Copies a file to a directory on the server. Syntax <cffile action = "upload" fileField = "formfield" destination = "full_path_name" nameConflict = "behavior" accept = "mime_type/file_type" mode = "permission" attributes = "file_attribute_or_list"> result = "result_name" See also cfdirectory History...
  • Page 144 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. •...
  • Page 145 Parameter Description 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...
  • Page 146 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 <cffile action = "write" file = "full_path_name" output = "content"...
  • Page 147 Attribute Req/Opt Default Description 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 , all other attributes are attributes = "readOnly"...
  • Page 148 This example shows the use of the attribute for UNIX. It creates the file /tmp/foo with mode permissions rw-r--r-- (owner = read/write, group = read, other = read): <cffile action = "write" file = "/tmp/foo" mode = 644> This example appends to the file and sets permissions to read/write (rw) for all: <cffile action = "append"...
  • Page 149 cfflush Description Flushes currently available data to the client. Category Data output tags, Page processing tags Syntax <cfflush interval = "integer number of bytes"> See also cfcache, cfheader, cfinclude, cfsetting, cfsilent Attributes Attribute Req/Opt Default Description interval Optional Integer. Flushes output each time this number of bytes becomes available.
  • Page 150 Example The following example uses tags and the random number generating function to cfloop rand delay data display. It simulates a page that is slow to generate data. <h1>Your Magic numbers</h1> <p>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.
  • Page 151 cfform Description Builds a form with CFML custom control tags; these provide more functionality than standard HTML form input elements. You can include the resulting form on the client page as HTML or Flash content, and generate the form using XML and XSLT. Category Forms tags Syntax...
  • Page 152 • Deprecated the attribute. The tag now supports all HTML tag attributes passthrough form directly. • Added the attribute and support for the GET method. method • Added support for Flash and XML output, including the format height width preloader , and attributes.
  • Page 153 XSL skin and displays the result. For more information, see the attribute. skin skin Flash, Flash: Flash: Use a Macromedia halo color to stylize the haloGreen output. The skin determines the color used for highlighted and selected elements. XML: • haloSilver default.xsl •...
  • Page 154 In Flash format, must be a style specification in CSS format. For detailed information on specifying Flash styles, see Chapter 29, “Creating Forms in Macromedia Flash” in ColdFusion MX Developer’s Guide. preserveData HTML When the cfform action attribute posts back to the...
  • Page 155 Attribute Applies Req/ Default Description scriptSrc HTML, Specifies the URL, relative to the web root, of the Flash Description directory that contains the cfform.js file with the client-side JavaScript used by this tag and its child tags. For XML format forms, this directory is also the default directory for XSLT skins.
  • Page 156 Attribute Applies Req/ Default Description wMode Flash Window Specifies how the Flash form appears relative to other displayable content that occupies the same space on an HTML page. • window: the Flash form is the topmost layer on the page and obscures anything that would share the space, such as drop-down dynamic HTML lists.
  • Page 157 In HTML format, all tags, and in Flash format the tags, require JavaScript cftree cfgrid support on the browser. The tag and applet format , and cfapplet cfgrid cfslider cftree tags require the client to download a Java applet. If you specify Flash format in the tag, ColdFusion ignores any HTML in the form body.
  • Page 158 <Incorporating HTML form tags and attributes In HTML format, the tag lets you incorporate the following standard HTML elements. cfform They are not available in Flash format: • Standard HTML tag attributes and values. The attributes and values are included in the form tag that outputs in the page.
  • Page 159 Please enter a credit card number: <cfinput type = "Text" name = "TextSample" message = "Please enter a Credit Card Number" validate = "creditcard" required = "No"> <h4>This example shows the use of the cfslider tag.</h4> Rate your approval of this example from 1 to 10 by sliding control.<br> 1 <cfslider name = "sampleSlider"...
  • Page 160 Description Creates a container control for multiple form controls. Used in the tag body of cfform Macromedia Flash and XML forms. Ignored in HTML forms. Category Forms tags Syntax <cfformgroup type = "group type" label = "label" style = "style specification"...
  • Page 161 Note: Attributes that are not marked as supported in XML are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML Attribute Req/Opt; Default Description Formats type Required; XML: Can be any XForms group type defined in the XSLT.
  • Page 162 Attribute Req/Opt; Default Description Formats type • hdividedbox: aligns children horizontally. Each child is (continued) in a box with a border, and there are dividers between the boxes that users can move to change the relative sizes of the children. Use a tag with this attribute to arrange groups of form controls horizontally.
  • Page 163 Optional; Flash: A Flash style specification in CSS format. For detailed information on specifying Flash styles, see Flash and XML Chapter 29, “Creating Forms in Macromedia Flash” in ColdFusion MX Developer’s Guide. XML: An inline CSS style specification. selectedIndex Optional;...
  • Page 164 For more information on using this tag in XML vertical dualselectlist forms, see Chapter 29, “Creating Forms in Macromedia Flash” in ColdFusion MX Developer’s Guide. Example For a simple example of an XML form that uses a single...
  • Page 165 <b>Try entering information on both tabs</b><br> Submit the form and see what ColdFusion gets in the Forms scope.</b><br> <a href="http://www.macromedia.com/" target="_blank"> <font color="#0000FF"><u> This link displays the Macromedia home page in a new browser window </u></font></a><br> &nbsp;<br> </cfformitem> <!--- Use a tabnavigator with two tabs for user input. --->...
  • Page 166 <cfformgroup type="page" label="Preferences"> <cfformitem type="text" height="30"> <b>Tell us your preferences</b> </cfformitem> <!--- Put the pet selectors to the left of the fruit selectors. ---> <cfformgroup type="hbox"> <!--- Group the pet selector box contents, aligned vertically. ---> <cfformgroup type="vbox"> <cfformitem type="text" height="20"> Pets: </cfformitem>...
  • Page 167 cfformitem Description Inserts a horizontal line, a vertical line, a spacer, or text in a Flash form. Used in the cfform tag body for Flash and XML forms. Ignored in HTML forms. cfformgroup Category Forms tags Syntax <cfformitem type = "hrule, vrule, or spacer" style = "style specification"...
  • Page 168 Ignored if the attribute is type html text For detailed information on specifying Flash styles, see Chapter 29, “Creating Forms in Macromedia Flash” in ColdFusion MX Developer’s Guide. Not used with the spacer type. XML: ColdFusion passes the attribute to the XML.
  • Page 169 <cfformitem type="hrule" /> For more information on using this tag in Flash forms, see Chapter 29, “Creating Forms in Macromedia Flash” in ColdFusion MX Developer’s Guide. Example The following example shows a simple Flash form using horizontal rules and text: <h3>cfformitem Example</h3>...
  • Page 170 cfftp Description Lets users implement File Transfer Protocol (FTP) operations. Category File management tags, Internet Protocol tags Syntax The tag syntax depends on the attribute value. See the following sections: action • “cfftp: Opening and closing FTP server connections” on page 171 •...
  • Page 171 cfftp: Opening and closing FTP server connections Description To establish a connection with an FTP server, you use the action with a open connection attribute. Syntax <cfftp action = "action" username = "name" password = "password" server = "server" timeout = "timeout in seconds" port = "port"...
  • Page 172 Attribute Req/Opt Default Description retryCount Optional Number of retries until failure is reported. stopOnError Optional • 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.
  • Page 173 username = "anonymous" connection = "My_query" password = "youremail@email.com" server = "ftp.tucows.com" stopOnError = "Yes"> <p>Did it succeed? <cfoutput>#cfftp.succeeded#</cfoutput> <p>List the files in a directory: <cfftp action = "LISTDIR" stopOnError = "Yes" name = "ListFiles" directory = "/" connection = "my_query"> <cfoutput query = "ListFiles">...
  • Page 174 cfftp: Connection: File and directory operations Description Use this form of the tag to perform file and directory operations with cfftp cfftp Syntax <cfftp action = "action" username = "name" password = "password" name = "query_name" server = "server" ASCIIExtensionList = "extensions" transferMode = "mode"...
  • Page 175 Attribute Req/Opt Default Description name Required if Query name of directory listing. action = "listDir" server Required if FTP FTP server to which to connect; for example, connection is not ftp.myserver.com cached ASCIIExtension Optional txt;htm;html; Delimited list of file extensions that force ASCII List cfm;cfml;...
  • Page 176 Usage If you use connection caching to an active FTP connection, you do not have to respecify the , or connection attributes. username password server Changing a cached connection, such as changing values, might require retryCount timeout reestablishing the connection. , the column returns .
  • Page 177 Example The following example opens a connection and gets a file listing showing file or directory name, path, URL, length, and modification date: <p>Open a connection <cfftp connection = "myConnection" username = "myUserName" password = "myUserName@allaire.com" server = "ftp.allaire.com" action = "open" stopOnError = "Yes">...
  • Page 178 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 attribute. This value holds the name results of the action in a query object.
  • Page 179 cffunction Description Defines a function that you can call in CFML. Required to define ColdFusion component methods. History ColdFusion MX 7: Added the value to the attribute. returntype ColdFusion MX: Added this tag. Category Extensibility tags Syntax <cffunction name = "methodName" returnType = "dataType"...
  • Page 180 Attributes Attribute Req/Opt Default Description name Required A string; a component method that is used within the tag. cfcomponent returnType Required for a String; a type name; data type of the function return web service; value: Optional, • any otherwise. •...
  • Page 181 Attribute Req/Opt Default Description 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. •...
  • Page 182 For information on using the tag for ColdFusion components, see Chapter 10, cffunction “Building and Using ColdFusion Components” in ColdFusion MX Developer’s Guide. If you specify a attribute, the function executes only if a user is logged in and belongs to roles one of the specified roles.
  • Page 183 cfgraph Description This tag is deprecated. Use the , and tags instead. cfchart cfchartdata cfchartseries 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...
  • Page 184 cfgraph tag attribute ColdFusion MX functionality Depth • 0: displays graph with two-dimensional appearance. • any other value: displays graph with threedimensional appearance. Linewidth Ignored. Showvaluelabel • yes: displays values on mouse-click. • no: suppresses value displays. • rollover: displays values on mouse-over. Valuelocation Ignored.
  • Page 185 cfgraphdata Description This tag is deprecated. Use the , and tags instead. cfchart cfchartdata cfchartseries Displays a data point in a graph. Used within the tag. cfgraph History ColdFusion MX: Deprecated this tag. It works differently than in ColdFusion 5 and might not work in later releases.
  • Page 186 cfgrid Description Used within the tag. Puts a grid control (a table of data) in a ColdFusion form. To specify cfform grid columns and row data, use the tags, or use the cfgridcolumn cfgridrow query attribute, with or without tags. cfgridcolumn Category Forms tags...
  • Page 187 onValidate = "javascript_function" onError = "text" gridDataAlign = "position" rowHeaders = "yes" or "no" rowHeaderAlign = "position" rowHeaderFont = "font_name" rowHeaderFontSize = "size" rowHeaderItalic = "yes" or "no" rowHeaderBold = "yes" or "no" rowHeaderTextColor = "web color" colHeaderAlign = "position" selectColor = "web color"...
  • Page 188 Attributes Note: In XML format, ColdFusion MX passes all attributes to the XML. The supplied XSLT skins do not handle or display XML format grids, but do display applet and Flash format grids. Attribute Req/Opt; Default Description Formats name Required; Name of the grid control.
  • Page 189 Attribute Req/Opt; Default Description Formats textColor Optional; Black Color of text. Can be a hexadecimal value or a named color. For a hexadecimal value, use the form " ", where x = 0-9 or A-F; use two ##xxxxxx number signs or none. For a list of the supported named colors, see cfchart selectColor...
  • Page 190 Attribute Req/Opt; Default Description Formats visible Optional; Flash format only: Boolean value specifying whether to show the control. Space that would Flash be occupied by an invisible control is blank. tooltip Optional; Flash format only: text to display when the mouse pointer hovers over the control.
  • Page 191 Attribute Req/Opt; Default Description Formats href Optional; URL or name of a query column that contains URLs to hyperlink each grid cell with. applet target Optional; The target frame or window in which to display URL; for example, "_blank". applet href appendKey Optional;...
  • Page 192 Attribute Req/Opt; Default Description Formats colHeaderAlign Optional; Left • Left: left-aligns the column header text. applet • Right: right-aligns the column header text. • Center: centers the column header text. notSupported Optional; (See Text to display if the browser does not support Description) Java or has Java support disabled.
  • Page 193 Note: 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.
  • Page 194 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. To make it work with a on a submitted , set the GridName variable to cfgrid...
  • Page 195 Using the href attribute When specifying a URL with grid items using the attribute, the attribute value href selectMode 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 variable is appended to the cfgridkey URL, in this form:...
  • Page 196 cfgridcolumn Description Used with the tag in a . Formats a columns and optionally populates the column cfgrid cfform from a query. The font and alignment attributes used in override global font or cfgridcolumn alignment settings defined in cfgrid Category Forms tags Syntax <cfgridcolumn...
  • Page 197 ColdFusion MX: Changed behavior if : a user cannot select and edit the cell data, select="no" regardless of the attribute value. When clicked, the cell border (and, cfgrid selectmode depending on the value, the cell background) changes color, but the cell data selectColor cannot be edited.
  • Page 198 Attribute Req/Opt; Default Description Formats type Optional; You can specify the following values in all formats: • image: grid displays the image specified by the URL in the column. If you use a relative URL, the image must be in the CFIDE\classes directory or a subdirectory.
  • Page 199 Attribute Req/Opt; Default Description Formats fontSize Optional; As specified Size of text in column. cfgrid italic Optional; As specified • yes: displays grid control text in italics. cfgrid • no bold Optional; As specified • yes: displays grid control text in bold. cfgrid •...
  • Page 200 Attribute Req/Opt; Default Description Formats mask optional; A mask pattern that controls the character pattern Flash that the form displays or allows users to input and sends to ColdFusion. For columns with the currency attribute, the type specifies the currency symbol. ColdFusion MX mask automatically inserts the character before the numeric value.
  • Page 201 Attribute Req/Opt; Default Description Formats numberFormat Optional; Format for displaying numeric data in the grid. See “numberFormat mask characters” on page 201. Applet values Optional; Formats cells in column as drop-down list boxes; specify items in drop-down list. For example: Applet values = "arthur, scott, charles, 1-20, mabel"...
  • Page 202 date/time formats in mask attribute By default, Flash displays date/time values in grid columns using a format that shows values such as Oct 29 2004 11:03:21. Use the attribute to display the date or time in a different format, mask as described in the following table: Pattern letter Description Year.
  • Page 203 Pattern letter Description Hour in am/pm (1-12). Minute in hour. Examples: N = 3 NN = 03 Second in minute. Other text You can add other text into the pattern string to further format the string. You can use punctuation, numbers, and all lowercase letters. You should avoid uppercase letters because they may be interpreted as pattern letters.
  • Page 204 <cfgridcolumn name = "CorNumber" header = "Course ##" Select="No" width="65"> <cfgridcolumn name = "CorName" header = "Name" width="125"> <cfgridcolumn name = "CorLevel" header = "Level" width="85"> <cfgridcolumn name = "CorDesc" header = "Description" width="125"> </cfgrid> <br> <cfinput type="submit" name="gridEntered"> </cfform> </body>...
  • Page 205 cfgridrow Description Lets you define a control that does not use a query as source for row data. If a query cfgrid attribute is specified in the tag, the tags are ignored. cfgrid cfgridrow Category Forms tags Syntax <cfgridrow data = "col1, col2, ..."> See also cfgrid, cfgridcolumn, cfgridupdate, cfform, cfinput, cfselect, cfslider, cftextarea,...
  • Page 206 cfgridupdate Description Used within a tag. Updates data sources directly from edited grid data. This tag provides cfgrid a direct interface with your data source. This tag applies row actions first, then row actions, then row actions. If it delete insert update encounters an error, it stops processing rows.
  • Page 207 Attribute Req/Opt Default Description tableQualifier Optional Table qualifier, if supported. Purpose: • SQL Server and Oracle driver: name of database that contains the table. • Intersolv dBASE driver: directory of DBF files. keyOnly Applies to the action: update • yes: the WHERE criteria are limited to the key values. •...
  • Page 208 cfheader Description Generates custom HTTP response headers to return to the client. Category Data output tags, Page processing tags Syntax <cfheader name = "header_name" value = "header_value" charset="charset"> <cfheader statusCode = "status_code" statusText = "status_text"> See also cfcache, cfflush, cfhtmlhead, cfinclude, cfsetting, cfsilent, cfcontent History ColdFusion MX 6.1: Changed behavior for the...
  • Page 209 Attribute Req/Opt Default Description statusCode Required if Number. HTTP status code. name specified statusText Optional Explains the status code. Usage If you use this tag after the tag on a page, an error is thrown. cfflush Example <h3>cfheader Example</h3> <p>cfheader generates custom HTTP response headers to return to the client. <p>This example forces browser client to purge its cache of requested file.
  • Page 210 If you use this tag after the tag on a page, an error is thrown. cfflush Example <!--- This example displays the information provided by the Macromedia Designer & Developer Center XML feed, http://www.macromedia.com/devnet/resources/macromedia_resources.rdf See http://www.macromedia.com/desdev/articles/xml_resource_feed.html for more information on this feed. --->...
  • Page 211 <strong>Description</strong> #item.description.xmlText#<br> <strong>Applies to these products</strong><br> <cfloop index="i" from="1" to="#arrayLen(item.subject)#" step="1"> #item.subject[i].xmltext#<br> </cfloop> <br> </cfoutput> </cfloop> cfhtmlhead...
  • Page 212 cfhttp Description Generates an HTTP request and handles the response from the server. Category Internet Protocol tags Syntax <cfhttp url = "server_URL" port = "port_number" method = "method_name" proxyServer = "hostname" proxyPort = "port_number" proxyUser = "username" proxyPassword = "password" username = "username"...
  • Page 213 • 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. ColdFusion MX: •...
  • Page 214 Attribute Req/Opt Default Description method • GET: requests information from the server. Any data that the server requires to identify the requested information must be in the URL or in tags. cfhttp type="URL" • POST: sends information to the server for processing. Requires one or more tags.
  • Page 215 Attribute Req/Opt Default Description charset The character encoding of the request, including the URL request: query string and form or file data, and the response. The UTF-8 following list includes commonly used values: • utf-8 response: • iso-8859-1 charset • windows-1252 specified •...
  • Page 216 Attribute Req/Opt Default Description redirect If the response header includes a Location field AND ColdFusion receives a 300-series (redirection) status code, specifies whether to redirect execution to the URL specified in the field: • yes: redirects execution to the specified page. •...
  • Page 217 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 tags as multipart form data, with a (Sends as type="formField"...
  • Page 218 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 Tells ColdFusion to create a query object with the given name from the returned HTTP response body.
  • Page 219 When ColdFusion receives a response to a request, it can put the response body (if any) in cfhttp a file or the string variable. If the body text is structured as a result set, cfhttp.FileContent 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.
  • Page 220 If the connection to the HTTP server fails, contains details about the failure. For instance: "Unknown host: my.co.com"; otherwise, the empty string. Macromedia recommends that you check this variable for an error condition before checking other variables. cfhttp.fileContent Response body; for example, the contents of a html page retrieved by a GET operation.
  • Page 221 ColdFusion generates a query object. • tag does not support NTLM or Digest Authentication. cfhttp Example <!--- This example displays the information provided by the Macromedia Designer & Developer Center XML feed, http://www.macromedia.com/desdev/resources/macromedia_resources.xml See http://www.macromedia.com/desdev/articles/xml_resource_feed.html for more information on this feed. --->...
  • Page 222 <!--- Parse the XML and output a list of resources. ---> <cfset xmlDoc = XmlParse(CFHTTP.FileContent)> <!--- Get the array of resource elements, the xmlChildren of the xmlroot. ---> <cfset resources=xmlDoc.xmlroot.xmlChildren> <cfset numresources=ArrayLen(resources)> <cfloop index="i" from="1" to="#numresources#"> <cfset item=resources[i]> <cfoutput> <strong><a href=#item.url.xmltext#>#item.title.xmltext#</strong></ a><br>...
  • Page 223 cfhttpparam Description Allowed inside tag bodies only. Required for POST operations. Optional for all cfhttp cfhttp others. Specifies parameters to build an HTTP request. Category Internet Protocol tags Syntax <cfhttpparam type = "transaction type" name = "data name" value = "data value" file = "filename"...
  • Page 224 Attributes Attribute Req/Opt Default Description type Required Information type: • header: 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 automatically set a content-type header or URL encode the body contents.
  • Page 225 Usage Specifies header or body data to send in the HTTP request. The attribute identifies the type information that the parameter specifies. A tag can have multiple tags, cfhttp cfhttpparam subject to the following limitations: • attribute cannot be used with additional attributes, or with XML type XML type...
  • Page 226 <cfhttpparam name="cgi_test" type="CGI" value="This is a CGI variable"> <cfhttpparam name="cookie_test" type="Cookie" value="This is a cookie"> </cfhttp> <!--- Output the results returned by the posted-to page. ---> <cfoutput> #cfhttp.fileContent# </cfoutput> <!--- This is the cfhttpparamexample.cfm page that receives and processes the Post request.
  • Page 227 cfif Description Creates simple and compound conditional statements in CFML. Tests an expression, variable, function return value, or string. Used, optionally, with the tags. cfelse cfelseif Category Flow-control tags Syntax <cfif expression> HTML and CFML tags <cfelseif expression> HTML and CFML tags <cfelse>...
  • Page 228 <hr> <!---- Use CFIF to test a condition when outputting a query. -----> <p>The following centers are in San Diego: <cfoutput query="getCenters"> <cfif Trim(City) is "San Diego"> <br><b>Name/Address:</b>#Name#, #Address1#, #City#, #State# <br><b>Contact:</b> #Contact# <br> </cfif> </cfoutput> <hr> <p>If we would like more than one condition to be the case, we can ask for a list of the centers in San Diego <b>OR</b>...
  • Page 229 cfimpersonate Description This tag is obsolete. Use the newer security tools; see “Conversion functions” on page 453 Chapter 16, “Securing Applications” in ColdFusion MX Developer’s Guide. History ColdFusion MX: This tag is obsolete. It does not work in ColdFusion MX and later releases. cfimpersonate...
  • Page 230 cfimport Description You can use the tag to import either of the following: cfimport • 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.
  • Page 231 Usage The following example imports the tags from the directory myCustomTags: <cfimport prefix="mytags" taglib="myCustomTags"> You can import multiple tag libraries using one prefix. If there are duplicate tags in a library, the first one takes precedence. 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...
  • Page 232 cfinclude Description Embeds references to ColdFusion pages in CFML. You can embed tags recursively. cfinclude For another way to encapsulate CFML, see on page 305. (A ColdFusion page was cfmodule formerly sometimes called a ColdFusion template or a template.) Category Flow-control tags, Page processing tags...
  • Page 233 You can specify a variable for the attribute, as the following example shows: template <cfset templatetouse="../header/header.cfm"> <cfinclude template="#templatetouse#"> Example <!--- This example shows the use of cfinclude to paste CFML or HTML code into another page dynamically. ---> <h4>This example includes the dochome.htm page from the CFDOCS directory. The images do not display, because they are located in a separate directory.
  • Page 234 cfindex Description Populates a Verity collection with metadata and creates indexes for searching it. Verity is a search engine that you can integrate in a ColdFusion application to search physical files of various types or a database query. Indexing database columns that result from a query lets users search the query data much faster than they could if you used multiple SQL queries to return the same data.
  • Page 235 ColdFusion MX: • attribute value is obsolete. It does not work, and might cause an error, action optimize in ColdFusion MX. • Changed the attribute behavior: it is not necessary to specify the external external attribute. (ColdFusion automatically detects whether a collection is internal or external.) •...
  • Page 236 Attribute Req/Opt Default Description body Required if • ASCII text to index. type = • Query column names, if name is specified in query. custom You can specify columns in a delimited list; for example: "emp_name, dept_name, location" This attribute is ignored if , and is type file...
  • Page 237 Usage The attributes settings that the tag requires depend on whether you set the cfindex query attribute. If you set the query attribute to a valid query name, it specifies that is to index cfindex the data in the query rather than indexing documents on a disk. If you do not set the query attribute, assumes it is indexing a file ( ), a set of files in a directory path...
  • Page 238 Status attribute attribute provides the following information and diagnostics about the result of a status operation: cfindex Type Description BADKEYS Struct A structure of keys with diagnostic messages about the indexing of these keys. If there are no bad keys, this key does not exist. DELETED Number The number of keys deleted.
  • Page 239 language="English" categoryTree="vw_files/newspaper/sports" category="Giants"> <!--- Search for any references to criteria. ---> <cfsearch name = "mySearch" collection = "CodeColl" categoryTree="vw_files/newspaper/sports" category="Giants" criteria = "Williams" contextpassages = "1" maxrows = "100"> <cfoutput> key=#mySearch.key#<br /> title=#mySearch.title#<br /> context=#mySearch.context#<br /> url=#mySearch.url#<br /> </cfoutput> <!---EXAMPLE #3: Index a QUERY (type = "custom") using custom1. ------------> <!--- Retrieve data from the table.
  • Page 240 title=#mySearch.title#<br /> context=#mySearch.context#<br /> url=#mySearch.url#<br /> </cfoutput> <!--- EXAMPLE #4 Index a FILE within a QUERY (type= "file"). ---------------> <!--- Retrieve row with a column that contains a filename (Contract_File). ---> <cfquery name="getEmps" datasource="cfdocexamples"> SELECT * FROM EMPLOYEE WHERE EMP_ID = 1 </cfquery>...
  • Page 241 <h2>Indexing Complete</h2> <cfsearch name = "getEmps" collection = "CodeColl" criteria = "cfsetting" contextpassages = "1" maxrows = "100"> <cfoutput> key=#getEmps.key#<br /> title=#getEmps.title#<br /> context=#getEmps.context#<br /> url=#getEmps.url#<br /> </cfoutput> <!--- EXAMPLE #6 Deletes keys in the CodeColl collection for html files ---> <!--- in the specified directory (but not in subdirectories).
  • Page 242 cfinput Description Used within the tag, to place input controls that support input validation on a form. cfform Category Forms tags Syntax <cfinput name = "name" type = "input type" label = "text" style = "style specification" required = "yes" or "no" mask = "masking pattern"...
  • Page 243 History ColdFusion MX 7: • Added support for button, file, hidden, image, reset, and submit controls. • Added support for generating Flash and XML controls (specified in the tag). cfform • Added type (Flash forms only) and the supporting datefield daynames monthnames attributes.
  • Page 244 In Flash format, must be a style specification in CSS format. For detailed information on specifying Flash styles, see Chapter 29, “Creating Forms in Macromedia Flash” in ColdFusion MX Developer’s Guide. In XML format, ColdFusion passes the style attribute to the XML.
  • Page 245 Attribute Req/Opt; Default Description Formats range Optional; Minimum and maximum allowed numeric values. ColdFusion uses this attribute only if you specify range in the attribute. validate If you specify a single number or a single number followed by a comma, it is treated as a minimum, with no maximum.
  • Page 246 Attribute Req/Opt; Default Description Formats disabled Optional; Disables user input, making the control read-only. To disabled disable input, specify disabled without an attribute or (or any ColdFusion positive Boolean disabled="Yes" value, such as True). To enable input, omit the attribute or specify (or any ColdFusion negative disabled="No"...
  • Page 247 Attribute Req/Opt; Default Description Formats enabled Optional; Boolean value specifying whether the control is Flash enabled. A disabled control appears in light gray. The inverse of the attribute. disabled visible Optional; Boolean value specifying whether to show the control. Flash Space that would be occupied by an invisible control is blank.
  • Page 248 • onBlur In HTML format the form page on the browser includes JavaScript functions that perform validation when the field loses the focus. In Flash format, the attribute is equivalent to onSubmit. OnBlur validation uses the same algorithms as onSubmit validation. OnBlur validation was added in ColdFusion MX 7.
  • Page 249 Type Description email A valid e-mail address of the form name@server.domain. ColdFusion validates the format only; it does not check that entry is a valid active e-mail address. A valid URL pattern; supports http, https, ftp file, mailto, and news URLs. guid A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx- xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number.
  • Page 250 The following pattern enforces entry of a part number of the format EB-1234-c1-098765, where the user starts the entry by typing the first numeric character, such as 3. ColdFusion fills in the preceding EA prefix and all - characters. The user must enters four numbers, followed by two alphanumeric characters, followed by six numbers.
  • Page 251 Phone Number Validation (enter a properly formatted phone number): <br> <cfinput type = "Text" name = "MyPhone" message = "Enter telephone number, formatted xxx-xxx-xxxx (e.g. 617-761- 2000)" validate = "telephone" required = "yes"> <font size = -1 color = red>Required</font> <!--- Zip code validation.
  • Page 252 cfinsert Description Inserts records in data sources from data in a ColdFusion form or form Scope. Category Database manipulation tags Syntax <cfinsert dataSource = "ds_name" tableName = "tbl_name" tableOwner = "owner" tableQualifier = "tbl_qualifier" username = "username" password = "password" formFields = "formfield1, formfield2, ...">...
  • Page 253 Attribute Req/Opt Default Description password Optional Overrides password specified in ODBC setup. formFields Optional (all on Comma-delimited list of form fields to insert. If not specified, form, all fields in the form are included. except If a form field is not matched by a column name in the keys) database, ColdFusion throws an error.
  • Page 254 <td valign = top>#CommtType#</td> <td valign = top><font size = "-2">#Left(MessText, 125)#</font></td> <td valign = top>#Posted#</td> </tr> </cfoutput> </table> <p>Next, we’ll offer the opportunity to enter a comment: <!--- make a form for input ---> <form action = "cfinsert.cfm" method = "post"> <pre>...
  • Page 255 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. •...
  • Page 256 proxyServer = "WSDL proxy server URL proxyPort = "port on proxy server" proxyUser = "user id for proxy server" proxyPassword = "password for proxy server" servicePort = "WSDL port name" inputParam1 = "value1" inputParam2 = "value2" returnVariable = "var_name" ...> Syntax 4A <!--- This syntax invokes a component.
  • Page 257 History ColdFusion MX 7: Added the attribute. servicePort ColdFusion MX 6.1: Added the following attributes: timeout proxyServer proxyPort , and proxyUser proxyPassword ColdFusion MX: Added this tag. Attributes Attribute Req/Opt Default Description component String or component object; a reference to a Usage.
  • Page 258 Attribute Req/Opt Default Description servicePort Optional First port found in The port name for the web service. This the WSDL value is case-sensitive and corresponds to element’s attribute under the port name element. service Specify this attribute if the web service contains multiple ports.
  • Page 259 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: Using the cfinvokeargument Passing directly as attributes of the tag (they cannot have the same name as a cfinvoke registered attribute:...
  • Page 260 Example4 This example uses Syntax 3. <!--- Using cfinvoke to consume a web service using a ColdFusion component.---> <cfinvoke webservice="http://www.xmethods.net/sd/2001/TemperatureService.wsdl" method="getTemp" returnvariable="aTemp"> <cfinvokeargument name="zipcode" value="55987"/> </cfinvoke> <cfoutput>The temperature at zip code 55987 is #aTemp#</cfoutput> For more information on web services, see Chapter 36, “Using Web Services” in ColdFusion MX Developer’s Guide.
  • Page 261 cfinvokeargument Description Passes the name and value of a parameter to a component method or a web service. This tag is used within the tag. cfinvoke Category Extensibility tags Syntax <cfinvokeargument name="argument name" value="argument value" omit = "yes" or "no"> See also cfargument, cfcomponent, cffunction, cfinvoke, cfobject, cfproperty, cfreturn...
  • Page 262 Example1 <cfinvoke component="nasdaq.quote" method="getLastTradePrice" returnVariable="res"> <cfinvokeargument name="symbol" value="mot"> <cfinvokeargument name="symbol" value="macr"> </cfinvoke> <cfoutput>#res#</cfoutput> Example2 <cfinvoke webservice ="http://www.xmethods.net/sd/2001/BabelFishService.wsdl" method ="BabelFish" returnVariable = "varName" > <cfinvokeargument name="translationmode" value="en_es"> <cfinvokeargument name="sourcedata" value="Hello world, friend"> </cfinvoke> <cfoutput>#varName#</cfoutput> Chapter 2: ColdFusion Tags...
  • Page 263 cfldap Description Provides an interface to a Lightweight Directory Access Protocol (LDAP) directory server, such as the Netscape Directory Server. Category Internet Protocol tags Syntax <cfldap server = "server_name" port = "port_number" username = "name" password = "password" action = "action" name = "name"...
  • Page 264 • Deprecated the attribute. It might not work, and might cause an error, in later filterfile releases. Attributes Attribute Req/Opt Default Description server Required Host name or IP address of LDAP server. port Optional Port. username Required if (anonymous) User ID. secure = "CFSSL_BASIC"...
  • Page 265 Attribute Req/Opt Default Description attributes Required if For queries: comma-delimited list of attributes to return. For queries, to get all attributes, action = specify "Query" "Add" "*" , or "ModifyDN" , you can specify a action = "add" or "modify" "Modify"...
  • Page 266 Attribute Req/Opt Default Description secure Optional Security to employ, and required information. One option: • CFSSL_BASIC "CFSSL_BASIC" provides V2 SSL encryption and server authentication. separator Optional , [comma] Delimiter to separate attribute values of multi- value attributes. Used by , and query modify actions, and by...
  • Page 267 Then restart ColdFusion MX. The keytool utility initial password is "change it". For keypass 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 tag could create columns in the query result set whose names contain illegal characters cfldap and are, therefore, inaccessible in CFML.
  • Page 268 </tr> </cfoutput> </table> </center> </cfif> </cfif> <form action="#cgi.script_name#" method="POST"> <p>Enter a name to search in the database. <p> <input type="Text" name="name"> <input type="Submit" value="Search" name=""> </form> Chapter 2: ColdFusion Tags...
  • Page 269 cflocation Description Stops execution of the current page and opens a ColdFusion page or HTML file. Category Flow-control tags, Page processing tags Syntax <cflocation url = "url" addToken = "yes" or "no"> See also cfabort, cfbreak, cfexecute, cfexit, cfif, cfloop, cfswitch, cfthrow, cftry Attributes Attribute...
  • Page 270 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.
  • Page 271 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 attribute throwOnTimeout value. If you set , the timeout is determined by timout="0"...
  • Page 272 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 attribute to identify scope...
  • Page 273 • Chapter 15, “Using Persistent Data and Locking” in ColdFusion MX Developer’s Guide • Article #20370, ColdFusion Locking Best Practices on the Macromedia website at www.macromedia.com/support/service/ Example <!--- This example shows how cflock can guarantee consistency of data updates to variables in the Application, Server, and Session scopes. --->...
  • Page 274 <!--- Use an application lock for the application-wide variable that keeps track of the number of turtlenecks sold. For a more efficient, but more complex, way of handling Application scope locking, see "ColdFusion MX Developer’s Guide"---> <cflock scope = "Application" timeout = "30" type = "Exclusive"> <cfif NOT IsDefined("application.number")>...
  • Page 275 <option>turquoise <option>black <option>forest green </select> </td> </tr> <tr> <td>Select a size.</td> <td><select type = "Text" name = "size" > <option>XXsmall <option>Xsmall <option>small <option>medium <option>large <option>Xlarge </select> </td> </tr> <tr> <td>Press Submit when you are finished making your selection.</td> <td><input type = "Submit" name = "submit" value = "Submit"> </td> </tr>...
  • Page 276 cflog Description Writes a message to a log file. Category Data output tags Syntax <cflog text = "text" log = "log type" file = "filename" type = "message type" application = "yes" or "no"> See also cfcol, cfcontent, cfoutput, cftable History ColdFusion MX: Deprecated the , and...
  • Page 277 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.
  • Page 278 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 tag.
  • Page 279 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 tag to check the user-provided ID and cflogin password against a data source, LDAP directory, or other repository of login identification. The body must include a tag to establish the authenticated user's identity in cfloginuser...
  • Page 280 <cfif qSecurity.recordcount gt 0> <cfloginuser name = "#cflogin.name#" password = "#cflogin.password#" roles = "#trim(qSecurity.Roles)#" > </cfif> Chapter 2: ColdFusion Tags...
  • Page 281 cfloginuser Description Identifies an authenticated user to ColdFusion. Specifies the user ID and roles. Used within a tag. cflogin Category Security tags Syntax <cfloginuser name = "name" password = "password-string" roles = "roles"> See also Chapter 16, cflogin, cflogout, GetAuthUser, IsUserInRole, cfapplication, “Securing Applications”...
  • Page 282 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 Security tags Syntax <cflogout>...
  • Page 283 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 284 • “cfloop: conditional loop”...
  • Page 284 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 <cfloop index = "parameter_name" from = "beginning_value" to = "ending_value" step = "increment">...
  • Page 285 The loop index is 3. The loop index is 4. The loop index is 5. In this example, the code loops four times, displaying the value each time. The value of index decreased by one for each iteration. This does not affect the value of , because it is a copy of that is made before entering the loop.
  • Page 286 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."...
  • Page 287 cfloop: looping over a date or time range Description Loops over the date or time range specified by the attributes. By default, the step is 1 from day, but you can change the step by creating a timespan. The tag loops over tags that cfloop cannot be used within a tag.
  • Page 288 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 tag. During each iteration, the columns of the current row are available for cfoutput output.
  • Page 289 The following example combines the pages that are returned by a query of a list of page names into one document, using the tag: cfinclude <cfquery name = "GetTemplate" dataSource = "Library" maxRows = "5"> SELECT TemplateName FROM Templates </cfquery> <cfloop query = "GetTemplate">...
  • Page 290 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 <cfloop index = "index_name" list = "list_items"...
  • Page 291 To loop over each line of a file, use the tag this way: <cfloop list="#theFile#" index="curLine" delimiters="#chr(10)##chr(13)#"> </cfloop> cfloop: looping over a list or file...
  • Page 292 cfloop: looping over a COM collection or structure Description attribute loops over every object within a COM/DCOM collection cfloop 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.
  • Page 293 <tr> <td>#person#</td> <td>#StructFind(Departments, person)#</td> </tr> </cfloop> </table> </cfoutput> cfloop: looping over a COM collection or structure...
  • Page 294 CHAPTER 2 ColdFusion Tags cfmail Description Sends an e-mail message that optionally contains query output, using an SMTP server. Category Internet Protocol tags Syntax <cfmail to = "recipient" from = "sender" cc = "copy_to" bcc = "blind_copy_to" subject = "msg_subject" replyto = "reply_to_addr"...
  • Page 295 Description 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, " ". An e-mail message is sent for each #EMail# returned row.
  • Page 296 Attribute Req/Opt Default Description charset Optional Character Character encoding of the mail message, including the encoding headers. The following list includes commonly used values: selected in • utf-8 ColdFusion • iso-8859-1 • windows-1252 Administrator • us-ascii Mail page; • shift_jis default is •...
  • Page 297 Attribute Req/Opt Default Description 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.
  • Page 298 Note: The 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 cfmail cffile to delete the attachment file, ColdFusion might not send the mail because the mailing process might execute after the file was is deleted.
  • Page 299 This message was sent by an automatic mailer built with cfmail: = = = = = = = = = = = = = = = = = = = = = = = = = = = #form.body# </cfmail> <h3>Thank you</h3>...
  • Page 300 cfmailparam Description Attaches a file or adds a header to an e-mail message. Category Internet Protocol tags Syntax <cfmail to = "recipient" subject = "msg_subject" from = "sender" ...more attributes... > <cfmailparam file = "file-name" type ="media type" contentID = "content ID" disposition = "disposition type">...
  • Page 301 Attribute Req/Opt Default Description type Optional The MIME media type of the file. Not used with the name attribute. Can be a valid MIME media type or one of the following: • text: specifies text/plain type. • plain: specifies text/plain type. •...
  • Page 302 </cfmail> <p>This view-only example displays an image in the body of an HTML message.</p> <cfmail type="HTML" to = "#form.mailto#" from = "#form.mailFrom#" subject = "Sample inline image"> <cfmailparam file="C:\Inetpub\wwwroot\web.gif" disposition="inline" contentID="image1"> <P>There should be an image here</p> <img src="cid:image1"> <p> After the picture</p> </cfmail>...
  • Page 303 cfmailpart Description Specifies one part of a multipart e-mail message. Can only be used in the tag. You can use cfmail more than one tag within a tag. cfmailpart cfmail Category Internet Protocol tags Syntax <cfmail ... > (Optional cfmailparam entries) <cfmailpart type="mime type"...
  • Page 304 Attribute Req/Opt Default Description wraptext Optional Do not Specifies the maximum line length, in characters of the mail text. wrap 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.
  • Page 305 Name.Name.Name... attribute is used Identifies subdirectory, under the ColdFusion tag root directory, that contains custom tag page. For example (Windows format): <cfmodule name = "macromedia.Forums40. GetUserOptions"> This identifies the page GetUserOptions.cfm in the directory CustomTags\macromedia\Forums40 under the ColdFusion root directory.
  • Page 306 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.
  • Page 307 using the TEMPLATE attribute.</P> <cfoutput>#HTMLCodeFormat(" <CFMODULE Template=""myTag.cfm"" attributeCollection=##attrCollection1## Y=4>")# </cfoutput> <P>The result: <cfoutput>#result#</cfoutput> <!--- Call the tag with CFMODULE with Name.---> <!--- <CFMODULE Name="myTag" X="3" attributeCollection=#attrCollection1# Y="4"> ---> <!--- Show the code. ---> <HR size="2" color="#0000A0"> <P>Here is another way to invoke the custom tag, using the NAME attribute.</P>...
  • Page 308 cfNTauthenticate Description Authenticates a user name and password against the Windows NT domain on which the ColdFusion server is running, and optionally retrieves the user’s groups. Category Security tags Syntax <cfNTauthenticate username="username" password="password" domain="nt_domain" result="result variable" listGroups = "yes" or "no" throwOnError = "yes"...
  • Page 309 Note: ColdFusion must run as a user that has the privilege to authenticate other users in the specified domain. The structure specified in the attribute contains the following information: result Field Value auth Whether the user is authenticated: • Yes •...
  • Page 310 Save the following page as loginform.cfm: <!--- A simple login form that posts back to the page whose request initiated the login. ---> <H2>Please Log In</H2> <cfform action="#CGI.script_name#"> <!--- j_username and j_password are special names that populate cflogin tag variables. ---> User Name: <cfinput type="text"...
  • Page 311 Please Try again</H2> </cfif> </cfoutput> <cfinclude template="loginform.cfm"> <cfabort> </cfif> </cfif> </cflogin> cfNTauthenticate...
  • Page 312 For example, if " ", for a class, use either of the context=NameService following formats for the parameter: class " " Macromedia/Eng/CF " " Macromedia.current/Eng.current/CF (In earlier releases, the format was " ".) Macromedia.Eng.CF • For CORBA object: changed the attribute;...
  • Page 313 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.
  • Page 314 Attribute Req/Opt Default Description 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 context = forms: "Remote"...
  • Page 315 cfobject: component object Description Creates an instance of a ColdFusion component (CFC) object. Syntax <cfobject name = "variable name" component = "component name"> See also ; “Using cfcollection cfcomponent cfexecute cfindex cfreport cfsearch cfwddx ColdFusion components” in Chapter 10, “Building and Using ColdFusion Components,” in ColdFusion MX Developer’s Guide Attributes Attribute...
  • Page 316 cfobject: CORBA object Description Calls methods on a registered CORBA object. Syntax <cfobject type = "corba" context = "context" class = "file or naming service" name = "text" locale = "type-value arguments"> See also ; “CORBA” in Chapter 17, cfcollection cfexecute cfindex cfreport...
  • Page 317 Usage ColdFusion Enterprise version 4.0 and later supports CORBA through the Dynamic Invocation Interface (DII). To use with CORBA objects, you must provide the name of the file cfobject that contains a string-formatted version of the IOR, or the object’s naming context in the naming service;...
  • Page 318 cfobject: Java or EJB object Description Creates and manipulates a Java and Enterprise Java Bean (EJB) object. Syntax <cfobject type = "Java" action = "Create" class = "Java class" name = "object name"> See also ; “Using Java objects” in cfcollection cfexecute cfindex...
  • Page 319 Calling EJBs To create and call EJB objects, use the tag. In the second example below, the WebLogic cfobject JNDI is used to register and find EJBHome instances. Example <!--- Example of a Java Object, this cfobject call loads the class MyClass but does not create an instance object.
  • Page 320 cfobject: web service object Description Creates a web service proxy object. Syntax <cfobject webservice= "http://..?wsdl" or "name set in Administrator" name = "myobjectname"> See also ; “Consuming web services” cfcollection cfexecute cfindex cfreport cfsearch cfwddx in Chapter 36, “Using Web Services,” in ColdFusion MX Developer’s Guide Attributes Attribute Req/Opt...
  • Page 321 cfobjectcache Description Flushes the query cache. Category Database manipulation tags Syntax <cfobjectcache action = "clear"> See also cfobject History ColdFusion 5: Added this tag. Attributes Attribute Req/Opt Default Description action Required clear: clears queries from the cache in the Application scope. cfobjectcache...
  • Page 322 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 <cfoutput query = "query_name" group = "query_column" groupCaseSensitive = "yes" or "no" startRow = "start_row"...
  • Page 323 When you specify a attribute, this tag loops over the query rows and produces output for query each row within the range specified by the values, and groups or startRow maxRows 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.
  • Page 324 <br>Today is <cfoutput>#DayofWeekAsString(DayofWeek(Now()))#</cfoutput> <p> EXAMPLE: This last example shows nested cfoutput tags:<p> <cfquery datasource="cfdocexamples" name="empSalary"> SELECT Emp_ID, firstname, lastname, e.dept_id, salary, d.dept_name FROM employee e, departmt d WHERE e.dept_id = d.dept_id ORDER BY d.dept_name </cfquery> <!--- Outer cfoutput. ---> <cfoutput query="empSalary" group="dept_id"> <h2>#dept_name#</h2>...
  • Page 325 cfparam Description Tests for the existence of a parameter (that is, a variable), validates its data, and, if a default value is not assigned, optionally provides one. Category Variable manipulation tags Syntax <cfparam name = "param_name" type = "data_type" default = "value" max = "value"...
  • Page 326 Attributes Attribute Req/Opt Default Description name Required Name of the parameter (variable) to test (such as "Client.Email " or "Cookie.BackgroundColor "). If omitted, and if the parameter does not exist, an error is thrown. type Optional The valid format for the data; one of the following. For detailed information on validation algorithms, see “Validating form data using hidden fields”...
  • Page 327 Attribute Req/Opt Default Description Optional The minimum valid value; used only for validation. range pattern Optional A JavaScript regular expression that the parameter must match; used only for validation. regex regular_expression Usage You can use this tag to make the following tests: •...
  • Page 328 <cfif tempVar is not #StoreTempVar# and tempVar is not ""> <h3>The value of tempVar has changed: the new value is <cfoutput>#tempVar#</cfoutput></h3> </cfif> <p> <form action = "cfparam.cfm" method = "post"> Type in a new value for tempVar, and hit submit:<br> <input type = "Text"...
  • Page 329 cfpop Description Retrieves or deletes e-mail messages from a POP mail server. Category Internet Protocol tags Syntax <cfpop server = "servername" port = "port_number" username = "username" password = "password" action = "action" name = "queryname" messageNumber = "number" uid = "number" attachmentPath = "path"...
  • Page 330 Attribute Req/Opt Default Description password Optional Password that corresponds to username action Optional getHeaderOnly • getHeaderOnly: returns message header information only • getAll: returns message header information, message text, and attachments if is specified attachmentPath • delete: deletes messages on POP server name Required if Name for query object that contains the...
  • Page 331 Attribute Req/Opt Default Description generate Optional • Yes: generate unique filenames for files Unique attached to an e-mail message, to avoid Filenames naming conflicts when files are saved. • No debug Optional • Yes: sends debugging output to standard output. By default, if the console window is unavailable on server configurations, ColdFusion sends output to cf_root/ runtime/logs/coldfusion-out.log.
  • Page 332 Query message header and body columns The following table lists the message header and body columns that are returned if action " or " getHeaderOnly" getAll" Column name getHeaderOnly returns getAll returns queryname.date queryname.from queryname.messagenumber queryname.messageid queryname.replyto queryname.subject queryname.cc queryname.to queryname.body queryname.textBody queryname.HTMLBody...
  • Page 333 , see Chapter 39, “Sending and Receiving E-Mail” in ColdFusion For more information on cfpop MX Developer’s Guide. Example <!--- This view-only example shows the use of cfpop. ---> <h3>cfpop Example</h3> <p>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.
  • Page 334 cfprocessingdirective Description Provides the following information to ColdFusion about 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,...
  • Page 335 For more information on character encodings, see www.w3.org/International/O-charset.html. Usage tag has limitations that depend on the attribute you use. For this cfprocssingdirective reason, Macromedia recommends that you include either the pageencoding attribute in a tag, not both. To specify both suppresswhitespace cfprocessingdirective values, use separate tags.
  • Page 336 • You cannot embed the tag within conditional logic, because the attribute is pageEncoding 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 tag has cfprocessingdirective already been evaluated: <cfif dynEncoding is not "dynamic encoding is not possible">...
  • Page 337 cfprocparam Description Defines stored procedure parameters. This tag is nested within a tag. cfstoredproc Category Database manipulation tags Syntax <cfprocparam type = "in" or "out" or "inout" variable = "variable name" value = "parameter value" CFSQLType = "parameter datatype" maxLength = "length" scale = "decimal places"...
  • Page 338 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.
  • Page 339 Output variables are stored in the ColdFusion variable specified by the attribute. variable You cannot use the tag for Oracle 8 and 9 reference cursors. Instead, use the cfprocparam tag. cfprocresult 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.
  • Page 340 variable = "param2"> <cfprocparam type = "IN" CFSQLType = "CF_SQL_INTEGER" value = "1"> <cfprocparam type = "OUT" CFSQLType = "CF_SQL_VARCHAR" variable = "FOO"> <cfprocresult name = "rs1"> <cfprocresult name = "rs2" resultSet = "2"> </cfstoredproc> <b>The first result set:</b><br> <hr> <cftable query = "rs1"...
  • Page 341 cfprocresult Description Associates a query object with a result set returned by a stored procedure. Other ColdFusion tags, such as , use this query object to access the result set. This tag is nested cfoutput cftable within a tag. cfstoredproc Category Database manipulation tags Syntax...
  • Page 342 dataSource = "MY_SYBASE_TEST" username = "sa" password = "" dbServer = "scup" dbName = "pubs2" returnCode = "Yes" debug = "Yes"> <!--- cfprocresult tags ---> <cfprocresult name = RS1> <cfprocresult name = RS3 resultSet = 3> <!--- cfprocparam tags ---> <cfprocparam type = "IN"...
  • Page 343 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 <cfproperty name="name" type="type"...
  • Page 344 Attributes 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).
  • Page 345 For web services that you create in ColdFusion, the tag defines complex variables cfproperty used by the web service. Example The following code defines a component in the file address.cfc that contains properties that represent a street address: <cfcomponent> <cfproperty name="Number" type="numeric"> <cfproperty name="Street"...
  • Page 346 For more information, see Security Bulletin ASB99-04, "Multiple SQL Statements in Dynamic Queries," in the Macromedia Security Zone, www.macromedia.com/devnet/security/security_zone/asb99-04.html, and Chapter 20, “Accessing and Retrieving Data” in ColdFusion MX Developer’s Guide. Category...
  • Page 347 ColdFusion MX: • Changed Query of Queries behavior: it now supports a larger subset of standard SQL. • Changed dot notation support: ColdFusion now supports dot notation within a record set name. ColdFusion interprets such a name as a structure. •...
  • Page 348 Attribute Req/Opt Default Description cachedWithin Optional Timespan, using the function. If original CreateTimeSpan query date falls within the time span, cached query data is used. defines a period from the present, CreateTimeSpan back. Takes effect only if query caching is enabled in the Administrator.
  • Page 349 Variable name Description result_name.columnList Comma-delimited list of the query columns. Cumulative time required to process the query. result_name.ExecutionTime You can cache query results and execute stored procedures. For information about this and about displaying output, see ColdFusion MX Developer’s Guide. cfquery Because the attribute only affects the maximum time for each suboperation of a query,...
  • Page 350 <b><i>Region</i></b> </td> <td bgcolor="f0f0f0"> <b><i>State</i></b> </td> </tr> <!--- Output the query and define the startrow and maxrows parameters. Use the query variable CurrentCount to keep track of the row you are displaying. ------> <cfoutput query="GetParks" startrow="#StartRow#" maxrows="#MaxRows#"> <tr> <td valign="top" bgcolor="ffffed"> <b>#GetParks.CurrentRow#</b>...
  • Page 351 This tag is nested within a tag, embedded in a query SQL statement. If you specify cfquery optional parameters, this tag performs data validation. Macromedia recommends that you use the tag within every tag, to help cfqueryparam cfquery secure your databases from unauthorized users. For more information, see Security Bulletin ASB99-04, “Multiple SQL Statements in Dynamic Queries,”...
  • Page 352 Attributes Attribute Req/Opt Default Description value Required Value that ColdFusion passes to the right of the comparison operator in a clause. where is a date or time option, ensure that the date CFSQLType value uses your DBMS-specific date format. Use the CreateODBCDateTime DateFormat TimeFormat...
  • Page 353 Usage Use the tag in any SQL statement (for example, SELECT, INSERT, UPDATE, cfqueryparam and DELETE) that uses ColdFusion variables. You cannot use the attributes with cfquery cachedAfter cachedWithin cfqueryparam. For maximum validation of string data, specify the attribute. maxlength This tag does the following: •...
  • Page 354 ColdFusion JDBC Informix Oracle MSSQL CF_SQL_CHAR CHAR Char char, char, char, nchar, nchar nchar unique identifier CF_SQL_CLOB CLOB Clob clob clob,nclob CF_SQL_DATE DATE Date date, datetime, year to CF_SQL_DECIMAL DECIMAL Decimal decimal, number decimal, money money, small money CF_SQL_DISTINCT DISTINCT CF_SQL_DOUBLE DOUBLE Double...
  • Page 355 ColdFusion JDBC Informix Oracle MSSQL CF_SQL_TIMESTAMP TIMESTAMP Timestamp datetime date datetime, year to smalldate fraction(5) time , datetime year to second CF_SQL_TINYINT TINYINT tinyint CF_SQL_VARBINARY VARBINARY Rowid varbinary CF_SQL_VARCHAR VARCHAR Varchar varchar, varchar2, varchar, nvarchar, nvarchar2 nvarchar, lvarchar sysname Example <!--- This example shows cfqueryparam with VALID input in Course_ID.
  • Page 356 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 to execute, it must be enabled in the ColdFusion MX Administrator. For more information, see Configuring and Administering ColdFusion MX.
  • Page 357 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 <cfregistry action = "getAll" branch = "branch" type = "data type" name = "query name" sort = "criteria">...
  • Page 358 <p><h1>cfregistry action = "getAll"</h1> <cftable query = "RegQuery" colHeaders HTMLTable border = "Yes"> <cfcol header = "<b>Entry</b>" width = "35" text = "#RegQuery.Entry#"> <cfcol header = "<b>Type</b>" width = "10" text = "#RegQuery.type#"> <cfcol header = "<b>Value</b>" width = "35" text = "#RegQuery.Value#"> </cftable>...
  • Page 359 cfregistry action = "get" Description Accesses a registry value and stores it in a ColdFusion variable. Syntax <cfregistry action = "get" branch = "branch" entry = "key or value" variable = "variable" type = "data type"> See also Chapter 15, “Using Persistent Data and Locking,” in ColdFusion MX Developer’s Guide Attributes Attribute Req/Opt...
  • Page 360 cfregistry action = "set" Description Adds a registry key, adds a value, or updates a value. Syntax <cfregistry action = "set" branch = "branch" entry = "key or value" type = "value type" value = "data"> See also Chapter 15, “Using Persistent Data and Locking,” in ColdFusion MX Developer’s Guide Attributes Attribute Req/Opt Default Description...
  • Page 361 cfregistry action = "delete" Description Deletes a registry key or value. Syntax <cfregistry action = "delete" branch = "branch" entry = "keyorvalue"> See also Chapter 15, “Using Persistent Data and Locking,” in ColdFusion MX Developer’s Guide Attributes Attribute Req/Opt Default Description action Required...
  • Page 362 cfreport Description Used to do either of the following: • Execute a report definition created with the ColdFusion Report Builder, displaying it in PDF, FlashPaper, or Excel format. You can optionally save this report to a file. • Run a predefined Crystal Reports report. Applies only to Windows systems. Uses the CFCRYSTAL.exe file to generate reports.
  • Page 363 History ColdFusion MX 7: Added support for the ColdFusion Report Builder. 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 MX Administrator.
  • Page 364 Attribute Applies Req/ Default Description permissions Report only) Specifies one or more of the format="PDF" Builder following permissions: • AllowPrinting • AllowModifyContents • AllowCopy • AllowModifyAnnotations • AllowFillIn • AllowScreenReaders • AllowAssembly • AllowDegradedPrinting Separate multiple permissions with a comma. datasource Crystal Name of registered or native data source.
  • Page 365 ColdFusion MX 7 Reporting. Images and charts are not supported and numeric data containing formatting (commas, percents, currency, and so on) appear as plain text in Excel. The Excel output format supports simple reports only and Macromedia recommends that you give careful design and layout consideration to reports designed for Excel output.
  • Page 366 cfreportparam Description Passes input parameters to a ColdFusion Report Builder report definition. Allowed inside tag bodies only. cfreport Category Data output tags Syntax <cfreportparam name = "data name" value = "data value"> See also ; Chapter 32, “Creating Reports for Printing,” in ColdFusion MX Developer’s Guide; cfreport Report Builder online Help History...
  • Page 367 <cfreport format="PDF" template="FourthReport.cfr" query="#coursedept#" overwrite="yes"> <cfreportparam NAME="ReportTime" VALUE="#DateFormat(Now())#, #TimeFormat(Now())#"> </cfreport> cfreportparam...
  • Page 368 cfrethrow Description Rethrows the currently active exception. Preserves the exception’s cfcatch type variable values. cfcatch.tagContext Category Exception handling tags, Extensibility tags Syntax <cfrethrow> See also ; “Handling runtime exceptions with ColdFusion tags” in Chapter 14, cferror cfthrow cftry “Handling Errors,” in ColdFusion MX Developer’s Guide Usage Use this tag within a block.
  • Page 369 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 <cfreturn expr> See also cfargument cfcomponent cffunction...
  • Page 370 </cffunction> <cffunction name="getDept"> <cfquery name="deptQuery" datasource="ExampleApps" > SELECT * FROM tblDepartments </cfquery> <cfreturn deptQuery> </cffunction> </cfcomponent> Chapter 2: ColdFusion Tags...
  • Page 371 cfsavecontent Description Saves the generated content of the tag, including the results of evaluating cfsavecontent expressions and executing custom tags, in the specified variable. Category Variable manipulation tags Syntax <cfsavecontent variable = "variable name"> the content </cfsavecontent> See also “Caching parts of ColdFusion pages” in Chapter 13, “Designing and Optimizing a ColdFusion Application,”...
  • Page 372 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.
  • Page 373 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. Attributes Attribute Req/Opt...
  • Page 374 Attribute Req/Opt Default Description password Optional Password, if URL is protected. proxyServer Optional Host name or IP address of a proxy server. proxyPort Optional Port number to use on the proxy server. proxyUser User name to provide to the proxy server. proxyPassword Opt Password to provide to the proxy server.
  • Page 375 operation = "HTTPRequest" url = "http://127.0.0.1/playpen/history.cfm" startDate = "8/7/03" startTime = "12:25 PM" interval = "3600" resolveURL = "Yes" publish = "Yes" file = "sample.html" path = "c:\inetpub\wwwroot\playpen" requestTimeOut = "600"> ---> cfschedule...
  • Page 376 cfscript Description Encloses a code block that contains statements. cfscript Category Application framework tags, Other tags Syntax <cfscript> cfscript code here </cfscript> See also ; Chapter 6, “Extending ColdFusion Pages with CFML cfinvoke cfmodule CreateObject Scripting” in ColdFusion MX Developer’s Guide History ColdFusion MX: •...
  • Page 377 You cannot use the construct within a tag. You can use code such as the elseif cfscript following: else if ( condition ) Exception handling with the cfscript tag To handle exceptions with this tag, use statements, which are equivalent to the catch tags.
  • Page 378 Consuming web services with the cfscript tag The following example shows how to consume a web service with the tag. You use the cfscript function to connect to the web service. CreateObject <cfscript> ws = CreateObject("webservice", "http://www.xmethods.net/sd/2001/BabelFishService.wsdl"); xlatstring = ws.BabelFish("en_es", "Hello world, friend"); writeoutput(xlatstring);...
  • Page 379 CHAPTER 2 ColdFusion Tags cfsearch Description Searches one or more Verity collections. 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 • In the ColdFusion MX Administrator •...
  • Page 380 See also cfcollection cfexecute cfindex cfobject cfreport cfwddx History ColdFusion MX 7: • Added category categoryTree status suggestions contextPassages contextBytes , and attributes. contextHighlightBegin contextHighlightEnd previousCriteria • Added , and author category categoryTree context rank size recordsSearched result columns. type •...
  • Page 381 Attribute Req/Opt Default Description category Optional A list of categories, separated by commas, to which the search is limited. If specified, and the collection does not have categories enabled, ColdFusion throws an exception. categoryTree Optional The location in a hierarchical category tree at which to start the search.
  • Page 382 Attribute Req/Opt Default Description suggestions Optional never Specifies whether Verity returns spelling suggestions for possibly misspelled words. Use one of the following options: • Always: Verity always returns spelling suggestions. • Never: Verity never returns spelling suggestions. • positive integer: Verity returns spelling suggestions if the number of documents retrieved by the search is less than or equal to the number specified.
  • Page 383 A value less than 300 helps to ensure optimal performance. Macromedia does not recommend using the tag with this tag; Verity provides the locking cflock function. Using the tag slows search performance.
  • Page 384 Status structure keys Variable Description The number of documents that contain the search criteria. found The number of documents searched. Corresponds to the searched recordsSearched column in the search results. The number of milliseconds the search took, as reported by the Verity K2 time search service.
  • Page 385 title=#name.title#<br> score=#name.score#<br> custom1=#name.custom1#<br> custom2=#name.custom2#<br> summary=#name.summary#<br> recordcount=#name.recordcount#<br> currentrow=#name.currentrow#<br> columnlist=#name.columnlist#<br> recordssearched=#name.recordssearched#<br> </cfoutput> <cfdump var = #name#> <br> <!--- #2 (TYPE=EXPLICIT) -----------------------------> <cfsearch name = "snippets" collection = "snippets" criteria = '<wildcard>`film{ing,ed}`' type="explicit" startrow=1 maxrows = "100"> <cfoutput query="snippets"> url=#url#<br> key=#key#<br> title=#title#<br> score=#score#<br> custom1=#custom1#<br>...
  • Page 386 currentrow=#book.currentrow#<br> columnlist=#book.columnlist#<br> recordssearched=#book.recordssearched#<br> </cfoutput> <cfdump var = #book#> Chapter 2: ColdFusion Tags...
  • Page 387 cfselect Description Constructs a drop-down list box form control. Used within a tag. You can populate the cfform list from a query, or by using the HTML tag. option Category Forms tags Syntax <cfselect name = "name" label = "label" style = "style specification"...
  • Page 388 XML. In Flash format, must be a style specification in CSS format, with the same syntax and contents as used in Macromedia Flex for the corresponding Flash element. size Optional; Number of entries to display at one time. The default, 1, displays a drop-down list.
  • Page 389 Attribute Req/Opt; Default Description Format display Optional; Value of Query column to use for the display label of each list element. Used with the attribute. value query attribute group Optional; Query column to use to group the items in the drop-down HTML and list into a two-level hierarchical list.
  • Page 390 Attribute Req/Opt; Default Description Format height Optional; The height of the control, in pixels. Flash width Optional; The width of the control, in pixels. Flash Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX.
  • Page 391 Show the selected names. ---> <cfif IsDefined("form.employeeid")> <!--- The form was submitted. ---> <h4>You Selected the following employees</h3> <cfif form.employeeid IS ""> <!--- Select All option was selected. Show all employees. ---> <cfoutput query="GetAllEmployees"> #name#<br> Email: #email#<br><br> </cfoutput> <cfelse> <!--- Use a query of queries to get the data for the selected users. Form.employeeid is a comma-delimited list of selected employee IDs.
  • Page 392 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.
  • Page 393 cfservletparam Description This tag is deprecated. A child tag of the tag. Passes data to a servlet. Each tag within the cfservlet cfservletparam block passes a separate item of data to the servlet. cfservlet 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)
  • Page 394 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 <cfset var variable_name = expression > See also ;...
  • Page 395 Dynamic variable names In this example, the variable name is itself a variable: <cfset myvariable = "current_value"> <cfset "#myvariable#" = 5> Function local variables keyword specifies that the variable being defined is only available inside the body of a function that you define using the tag.
  • Page 396 Example <!--- This example shows how to use cfset. ---> <cfquery name = "GetMessages" dataSource = "cfdocexamples"> SELECT * FROM Messages </cfquery> <h3>cfset Example</h3> <p>cfset sets and reassigns values to local or global variables within a page. <cfset NumRecords = GetMessages.recordCount> <p>For example, the variable NumRecords has been declared on this page to hold the number of records returned from query (<cfoutput>#NumRecords#</cfoutput>).
  • Page 397 cfsetting Description Controls aspects of page processing, such as the output of HTML code in pages. Category Page processing tags, Variable manipulation tags Syntax <cfsetting enableCFoutputOnly = "yes" or "no" showDebugOutput = "yes" or "no" requestTimeOut = "value in seconds" > See also cfcache cfflush...
  • Page 398 Usage attribute replaces the use of within a URL. cfsetting requestTimeout requestTimeOut To enforce a page timeout, detect the URL variable and use code such as the following to change the page timeout: <cfsetting RequestTimeout = "#URL.RequestTimeout#"> You can use this tag to manage whitespace in ColdFusion output pages. If you nest tags: to make HTML output visible, you must match each cfsetting...
  • Page 399 cfsilent Description Suppresses output produced by CFML within a tag’s scope. Category Data output tags, Page processing tags Syntax <cfsilent> </cfsilent> See also ; Chapter 9, “Writing and cfcache cfflush cfheader cfhtmlhead cfinclude cfsetting Calling User-Defined Functions,” in ColdFusion MX Developer’s Guide Usage This tag requires an end tag.
  • Page 400 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 tag. Not supported with Flash forms. cfform Category Forms tags...
  • Page 401 Attributes Attribute Req/Opt Default Description name Required Name of control. cfslider label Optional Label to display with control; for example, This "Volume" displays: "Volume %value%" To reference the value, use . If is omitted, "%value%" slider value displays directly after label. range Optional "0,100"...
  • Page 402 Attribute Req/Opt Default Description vertical Optional • Yes: renders slider in browser vertically. You must set attributes; ColdFusion does not width height automatically swap width and height values. • No: renders slider horizontally. bgColor Optional Background color of slider label. For a hexadecimal value, use the form: bgColor = , where x = 0-9 or A-F;...
  • Page 403 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: • attribute is set to " ". cfform preserveData • attribute posts to the same page as the form itself (this is the default), or cfform action the action page has a form that contains controls with the same names as corresponding controls on the user entry form.
  • Page 404 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 <cfstoredproc procedure = "procedure name" dataSource = "ds_name" username = "username" password = "password" blockFactor = "blocksize" debug = "yes"...
  • Page 405 Attribute Req/Opt Default Description returnCode Optional • Yes: populates with status cfstoredproc.statusCode code returned by the stored procedure. • No result Optional Specifies a name for the structure in which returns the statusCode and cfstoredproc ExecutionTime variables. If set, this value replaces as the prefix to use when accessing those cfstoredproc variables.
  • Page 406 <cfprocparam type = "IN" CFSQLType = CF_SQL_INTEGER value = "1" dbVarName = @param1> <cfprocparam type = "OUT" CFSQLType = CF_SQL_DATE variable = FOO dbVarName = @param2> </cfstoredproc> ---> <!--- <cfoutput>The output param value: ’#foo#’<br></cfoutput> <h3>The Results Information</h3> <cfoutput query = RS1>#name#,#DATE_COL#<br></cfoutput><p> <cfoutput>...
  • Page 407 cfswitch Description Evaluates a passed expression and passes control to the tag that matches the expression cfcase result. You can, optionally, code a tag, which receives control if there is no cfdefaultcase matching tag value. cfcase Category Flow-control tags Syntax <cfswitch expression = "expression">...
  • Page 408 Example <!--- This example shows the use of cfswitch and cfcase to exercise a case statement in CFML. ---> <cfquery name = "GetEmployees" dataSource = "cfdocexamples"> SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department FROM Employees </cfquery> <h3>cfswitch Example</h3> <!--- By outputting the query and using cfswitch, we classify the output without using a cfloop construct.
  • Page 409 cftable Description Builds a table in a ColdFusion page. This tag renders data as preformatted text, or, with the attribute, in an HTML table. If you don't want to write HTML table tag code, or if HTMLTable your data can be presented as preformatted text, use this tag. Preformatted text (defined in HTML with the <pre>...
  • Page 410 Attribute Req/Opt Default Description colHeaders Optional Displays column heads. If you use this attribute, you must also use the attribute to define them. cfcol header If you use this attribute (regardless of its value), ColdFusion displays column heads. startRow Optional The query result row to put in the first table row.
  • Page 411 </cftable> </body> </html> cftable...
  • Page 412 cftextarea Description Puts a multiline text entry box in a tag and controls its display characteristics. cfform Category Forms tags Syntax <cftextarea name = "name" label = "text" required = "yes" or "no" style = "style specification" validate = "data type" validateAt= one or more of "onBlur", "onServer", "onSubmit"...
  • Page 413 XML. style In Flash format forms, must be a style specification in CSS format, with the same syntax and contents as used in Macromedia Flex for the corresponding Flash element. required Optional; • yes: the field must contain text.
  • Page 414 Attribute Req/Opt; Default Description Format pattern Required if JavaScript regular expression pattern to validate input. Omit leading and trailing slashes. ColdFusion uses this validate = attribute only if you specify regex in the attribute. "regular_ validate For examples and syntax, see Chapter 27, “Building expression"...
  • Page 415 Attribute Req/Opt; Default Description Format enabled Optional; Boolean value specifying whether the control is enabled. A disabled control appears in light gray. The inverse of the Flash attribute. disabled visible Optional; Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is Flash blank.
  • Page 416 bind="Hello {userName.text}! Enter your comments here." /> Example This example has two controls. When you submit the form, ColdFusion copies the cftextarea text from the first control into the second. The onBlur maxlength validation prevents you from entering more than 100 characters. The > character that closes the opening tag, the cftextarea text in the tag body, and the...
  • Page 417 cftextinput Description Puts a single-line text entry box in a tag and controls its display characteristics. cfform This tag is deprecated, and is not supported in XML format forms. In its place, you should use a tag and use a cascading style sheet (CSS) to specify the text style cfinput cftextarea characteristics.
  • Page 418 cfthrow Description Throws a developer-specified exception, which can be caught with a tag that has any of cfcatch the following attribute options: type • type = "custom_type" • type = "Application" • type = "Any" Category Exception handling tags, Flow-control tags Syntax 1 <cfthrow type = "exception_type "...
  • Page 419 Attribute Req/Opt Default Description extendedInfo Optional A custom error code that you supply. object Optional Requires the value of the attribute. cfobject name Throws a Java exception from a CFML tag. This attribute is mutually exclusive with all other attributes of this tag.
  • Page 420 <!--- Perform the error catch. ---> <cfcatch type = "application"> <!--- Display your message. ---> <h3>You've Thrown an <b>Error</b></h3> <cfoutput> <!--- And the diagnostic feedback from the application server. ---> <p>#cfcatch.message#</p> <p>The contents of the tag stack are:</p> <cfloop index = i from = 1 to = #ArrayLen(cfcatch.tagContext)#>...
  • Page 421 cftimer Description Displays execution time for a specified section of CFML code. ColdFusion MX displays the timing information along with any output produced by the timed code. Note: To permit this tag to execute, you must enable the Timer Information option under Debugging Settings in the ColdFusion MX Administrator.
  • Page 422 Example1 <!--- type="inline"> ---> <cftimer label="Query and Loop Time Inline" type="inline"> <cfquery name="empquery" datasource="cfdocexamples"> select * from Employees </cfquery> <cfloop query="empquery"> <cfoutput>#lastname#, #firstname#</cfoutput><br> </cfloop> </cftimer> <hr><br> <!--- type="outline" ---> <cftimer label="Query and CFOUTPUT Time with Outline" type="outline"> <cfquery name="coursequery" datasource="cfdocexamples"> select * from CourseList </cfquery>...
  • Page 423 from Departments </cfquery> <p>Scroll down to CFTimer Times heading to see timing information</p> <table border="1" width="100%"> <cfoutput query="deptquery"> <tr> <td>#Dept_ID#</td> <td>#Dept_Name#</td> </tr> </cfoutput> </table> </cftimer> cftimer...
  • Page 424 cftrace Description Displays and logs debugging data about the state of an application at the time the cftrace 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.
  • Page 425 Attribute Req/Opt Default Description type Optional Information Corresponds to the attribute; displays an cflog type appropriate icon: • Information • Warning • Error • Fatal Information Optional 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.
  • Page 426 • repeatable_read: same as read_committed, except that rows in the recordset are exclusively locked until the transaction completes. Due to high overhead, Macromedia does not recommend this isolation level for normal database access. • serializable: places an exclusive lock on every data table in use for the duration of the transaction.
  • Page 427 Usage If you do not specify a value for the attribute, automatic transaction processing proceeds action as follows: • If the operations within the transaction block complete without an error, the cfquery transaction is committed. • If a tag generates an error within a block, all operations in cfquery...
  • Page 428 cftree Description Inserts a tree control in a form. Validates user selections. Used within a tag block. You can cfform use a ColdFusion query to supply data to the tree. Category Forms tags Syntax <cftree name = "name" format="applet", "flash", xml, or "object" required = "yes"...
  • Page 429 History ColdFusion MX 7: • Added the attribute and support for generating Flash and XML and object output. format • Added , and attributes (Flash format only). enabled onChange style tooltip visible ColdFusion MX: Changed behavior: ColdFusion renders a tree control regardless of whether there are any within it.
  • Page 430 Attribute Req/Opt Default Description Format appendKey Optional; • Yes: if you use attributes, ColdFusion cftreeitem href appends a CFTREEITEMKEY query string variable with the value of the selected tree item to the action cfform URL. • No: does not append the tree item value to the URL. highlightHref Optional;...
  • Page 431 • No object style Optional; Must be a style specification in CSS format, with the same syntax and contents as used in Macromedia Flex for the Flash corresponding Flash element. enabled Optional; Flash format only: Boolean value specifying whether the control is enabled.
  • Page 432 Note: All attributes are passed to the XML generated in XML format, but no ColdFusion MX skin interprets XML. cftree Usage This tag must be in a tag block. cfform The applet format tree requires the client to download a Java applet. Also, if the client does not have an up-to-date Java plugin installed, the system might also have to download an updated Java plugin to display an applet format tree.
  • Page 433 The structure variable name is specified by the attribute. The top level of the cftree name structure has two types of entries: • Attribute settings • A children array Attribute settings The structure has top-level entries with the values of the following attributes: cftree align...
  • Page 434 from CourseList c, Departments d where d.Dept_ID = c.Dept_ID order by d.dept_Name, c.corName, c.corLevel </cfquery> <cfform name="studentForm" format="flash" width="400" height="450"> <cftree name="courseTree" width="350" height="400"> <cftreeitem query="getCourses" value="dept_name,Course_id" display="dept_name,CorLabel" queryasroot="NO" expand="yes,no"> </cftree> </cfform> The following example creates a tree that shows the basic information about all employees in an organization, organized by department.
  • Page 435 <!--- Create an item for each employee in the department. Do not expand children. Each employee name links to this page, and sends the employee ID in the query string.---> <cftreeitem value = "#LastName#, #FirstName#" parent = "#Department#" expand="false" img="cd" href="#cgi.script_name#?user_id=#emp_id#">...
  • Page 436 cftreeitem Description Populates a form tree control, created with the tag, with one or more elements. cftree Category Forms tags Syntax <cftreeitem value = "text" display = "text" parent = "parent_name" img = "filename" imgopen = "filename" href = "URL" target = "URL_target"...
  • Page 437 Attribute Req/Opt; Default Description Format Optional; folder Image name, filename, or file URL for tree item icon. Applet, The following values are provided: object • cd • computer • document • element • folder • floppy • fixed • remote You can also specify a custom image.
  • Page 438 Attribute Req/Opt; Default Description Format queryAsRoot Optional; Applies only if you specify a attribute. Defines the query query as the root level for all items generated by this tag. This attribute enables you to avoid creating a parent cftreeitem • Yes: generates a parent (root) item for all other items generated by the tag, with the query name as its value;...
  • Page 439 <html> <body> <h3>cftreeitem Example</h3> <!--- The following runs if the user clicked on a link in the tree. A complete application would use the ID for additional processing. ---> <cfif isdefined("URL.user_ID")> <cfoutput> <!--- URL.cftreeitemkey is the selected tree item's value attribute. ---> You Requested information on #URL.cftreeitemKey#;...
  • Page 440 cftry Description Used with one or more tags. Together, they catch and process exceptions in ColdFusion cfcatch 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...
  • Page 441 <cfset sCurrent = #CFCATCH.TAGCONTEXT[i]#> <br>#i# #sCurrent["ID"]# (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#) #sCurrent["TEMPLATE"]# </cfloop> </cfoutput> </cfcatch> </cftry> cftry...
  • Page 442 cfupdate Description Updates records in a data source from data in a ColdFusion form or form Scope. Category Database manipulation tags Syntax <cfupdate dataSource = "ds_name" tableName = "table_name" tableOwner = "name" tableQualifier = "qualifier" username = "username" password = "password" formFields = "field_names">...
  • Page 443 Attribute Req/Opt Default Description password Optional Overrides the value specified in ODBC setup. password formFields Optional (all on Comma-delimited list of form fields to update. form, If a form field is not matched by a column name in the except database, ColdFusion throws an error.
  • Page 444 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.
  • Page 445 Attribute Req/Opt Default Description topLevelVariable Required if Name of top-level JavaScript object created by deserialization. The object is an instance of the action = WddxRecordset object. "wddx2js" "cfml2js" useTimeZoneInfo Optional Whether to output time-zone information when serializing CFML to WDDX. •...
  • Page 446 #Message_ID# #Thread_ID# #Username#<br> </cfoutput><p> <!--- Serialize data to WDDX format. ---> Serializing CFML data...<p> <cfwddx action = "cfml2wddx" input = #q# output = "wddxText"> <!--- Display WDDX XML packet. ---> Resulting WDDX packet is: <xmp><cfoutput>#wddxText#</cfoutput></xmp> <!--- Deserialize to a variable named wddxResult. ---> Deserializing WDDX packet...<p>...
  • Page 447 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, and then assigns the resulting text to an XML document object variable, which is always stored in Unicode.
  • Page 448 To change the declaration to specify another encoding, use the function. To specify the Replace encoding of the text that is returned to a browser or other application, use the tag. cfcontent The following example illustrates this process: <cfprocessingdirective suppresswhitespace="Yes"> <cfcontent type="text/xml;...
  • Page 449: Chapter 3: Coldfusion Functions

    Tag descriptions ............461 Function list ColdFusion Markup Language (CFML) includes a set of functions that you use in Macromedia ColdFusion MX 7 pages to perform logical and arithmetic operations and manipulate data.
  • Page 450 ArrayPrepend GetSOAPResponseHeader QueryAddRow ArrayResize GetTempDirectory QueryNew ArraySet GetTempFile QuerySetCell ArraySort GetTickCount QuotedValueList ArraySum GetTimeZoneInfo Rand ArraySwap GetToken Randomize ArrayToList Hash RandRange Hour REFind ASin HTMLCodeFormat REFindNoCase HTMLEditFormat ReleaseComObject BinaryDecode RemoveChars BinaryEncode IncrementValue RepeatString BitAnd InputBaseN Replace BitMaskClear Insert ReplaceList BitMaskRead ReplaceNoCase BitMaskSet IsArray...
  • Page 451 CreateTimeSpan IsXmlElem StructCopy CreateUUID IsXmlNode StructCount DateAdd IsXmlRoot StructDelete DateCompare JavaCast StructFind DateConvert JSStringFormat StructFindKey DateDiff LCase StructFindValue DateFormat Left StructGet DatePart StructInsert ListAppend StructIsEmpty DayOfWeek ListChangeDelims StructKeyArray DayOfWeekAsString ListContains StructKeyExists DayOfYear ListContainsNoCase StructKeyList DaysInMonth ListDeleteAt StructNew DaysInYear ListFind StructSort ListFindNoCase StructUpdate DecimalFormat...
  • Page 452: Functions By Category

    GetBaseTagList LSIsNumeric XmlParse GetBaseTemplatePath LSNumberFormat XmlSearch GetClientVariablesList LSParseCurrency XmlTransform GetCurrentTemplatePath LSParseDateTime XmlValidate GetDirectoryFromPath LSParseEuroCurrency Year GetEncoding LSParseNumber YesNoFormat GetException LSTimeFormat GetFileFromPath LTrim Functions by category The following tables list functions by their category or purpose. Array functions ............452 Conversion functions .
  • Page 453: Conversion Functions

    ArrayDeleteAt ArrayMin ArraySort ListToArray ArrayInsertAt ArrayNew ArraySum Conversion functions ArrayToList Hash ToScript XmlFormat BinaryDecode LCase ToString XmlParse BinaryEncode ListToArray URLDecode XmlTransform CharsetDecode ToBase64 URLEncodedFormat CharsetEncode ToBinary Date and time functions CreateDate DateFormat GetTimeZoneInfo MonthAsString CreateDateTime DatePart Hour CreateODBCDate IsDate ParseDateTime CreateODBCDateTime DayOfWeek IsLeapYear...
  • Page 454: Display And Formatting Functions

    Display and formatting functions CJustify HTMLCodeFormat LSIsDate NumberFormat DateFormat HTMLEditFormat LSNumberFormat ParagraphFormat DecimalFormat LJustify LSParseCurrency RJustify DollarFormat LSCurrencyFormat LSParseDateTime StripCR FormatBaseN LSDateFormat LSParseEuroCurrency TimeFormat GetLocale LSEuroCurrencyFormat LSParseNumber YesNoFormat GetLocaleDisplayName LSIsCurrency LSTimeFormat Dynamic evaluation functions Evaluate SetVariable Extensibility functions CreateObject ReleaseComObject ToScript GetGatewayHelper SendGatewayMessage...
  • Page 455: Mathematical Functions

    Compare Left ListGetAt ListValueCount CompareNoCase ListInsertAt ListValueCountNoCase Decrypt ListAppend ListLast ReplaceList Encrypt ListChangeDelims ListLen Find ListContains ListPrepend Mathematical functions BitNot FormatBaseN Randomize ACos BitOr IncrementValue RandRange ArrayAvg BitSHLN InputBaseN Round ArraySum BitSHRN ASin BitXor Ceiling Log10 BitAnd BitMaskClear DecrementValue BitMaskRead BitMaskSet Rand Other functions...
  • Page 456: Structure Functions

    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.) GetToken LSParseDateTime Reverse...
  • Page 457: Function Changes Since Coldfusion 5

    GetContextRoot GetMetaData SetLocale GetCurrentTemplatePath GetMetricData SetProfileString GetDirectoryFromPath GetPageContext WriteOutput GetEncoding GetProfileSections GetException GetProfileString XML functions AddSOAPRequestHeader IsSOAPRequest IsXmlRoot XmlGetNodeType AddSOAPResponseHeader IsXML IsWDDX XmlNew GetSOAPRequest IsXmlAttribute ToString XmlParse GetSOAPRequestHeader IsXmlDoc XmlChildPos XmlSearch GetSOAPResponse IsXmlElem XmlElemNew XmlTransform GetSOAPResponseHeader IsXmlNode XmlFormat XmlValidate 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.
  • Page 458 Function Parameter or value Added in this ColdFusion release GetAuthUser ColdFusion MX GetContextRoot ColdFusion MX 7 GetEncoding ColdFusion MX GetLocaleDisplayName ColdFusion MX 7 GetMetaData ColdFusion MX GetPageContext ColdFusion MX GetProfileSections ColdFusion MX GetSOAPRequest ColdFusion MX 7 GetSOAPRequestHeader ColdFusion MX 7 GetSOAPResponse ColdFusion MX 7 GetSOAPResponseHeader...
  • Page 459 Function Parameter or value Added in this ColdFusion release ToScript ColdFusion MX 7 URLDecode parameter ColdFusion MX charset URLEncodedFormat parameter ColdFusion MX charset URLSessionFormat ColdFusion MX Wrap ColdFusion MX 6.1 XmlChildPos ColdFusion MX XmlElemNew ColdFusion MX XmlElemNew parameter ColdFusion MX 7 namespace XmlGetNodeType ColdFusion MX 7...
  • Page 460 Obsolete functions, parameters, and values The following functions, parameters, and values are obsolete. Do not use them in ColdFusion applications. They do not work in releases later than ColdFusion 5. Function Parameter or value Obsolete as of this ColdFusion release AuthenticatedContext ColdFusion MX AuthenticatedUser...
  • Page 461 CHAPTER 3 ColdFusion Functions 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 Parameters Parameter Description number A number Example <h3>Abs Example</h3>...
  • Page 462 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, 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 .
  • Page 463 AddSOAPRequestHeader Description Adds a SOAP header to a web service request before making the request. Returns Nothing. Category XML functions History ColdFusion MX 7: Added this function. Function syntax AddSOAPRequestHeader(webservice, namespace, name, value [, mustunderstand]) See also AddSOAPResponseHeader GetSOAPRequest GetSOAPRequestHeader GetSOAPResponse ;...
  • Page 464 <!--- Note that you might need to modify the URL in the CreateObject function to match your server and the location of the headerservice.cfc file if it is different than shown here. Likewise for the cfinvoke tag at the end. ---> <h3>AddSOAPRequestHeader Example</h3>...
  • Page 465 AddSOAPResponseHeader Description Adds a SOAP response header to a web service response. Call only from within a CFC web service function that is processing a request as a SOAP web service. Returns Nothing Category XML functions History ColdFusion MX 7: Added this function. Function syntax AddSOAPResponseHeader(namespace, name, value [, mustunderstand]) See also...
  • Page 466 Save the following code as headerservice.cfc in a folder called soapheaders under your web root. Test its operation, and specifically the operation of the function, by AddSOAPResponseHeader executing the examples that invoke this web service. For example, see the example for AddSOAPRequestHeader <h3>AddSOAPResponseHeader Example</h3>...
  • Page 467 ArrayAppend Description Appends an array element to an array. Returns True, on successful completion. Category Array functions Function syntax ArrayAppend(array, value) See also ; “Adding elements to an array” in Chapter 5, “Using Arrays and Structures,” in ArrayPrepend ColdFusion MX Developer’s Guide History ColdFusion MX: Changed behavior: this function can be used on XML objects.
  • Page 468 ArrayAvg Description Calculates the average of the values in an array. Returns Number. If the parameter value is an empty array, returns zero. array Category Array functions, Mathematical functions Function syntax ArrayAvg(array) See also ; “Basic array techniques” in Chapter 5, “Using Arrays and Structures,” in ColdFusion ArraySum MX Developer’s Guide Parameters...
  • Page 469 <form action = "arrayavg.cfm"> <!--- The following code initially creates two fields. It adds fields if the user presses MORE. FormElem is initialized to two at the beginning of this code to show that the form has two fields. -----> <input type = "submit"...
  • Page 470 ArrayClear Description Deletes the data in an array. Returns True, on successful completion. Category Array functions Function syntax ArrayClear(array) See also ; “Functions for XML object management” in Chapter 35, “Using XML and ArrayDeleteAt WDDX,” in ColdFusion MX Developer’s Guide History ColdFusion MX: Changed behavior: this function can be used on XML objects.
  • Page 471 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.
  • Page 472 <cfoutput> #DaysArray[1][1]#&nbsp;&nbsp;#DaysArray[1][2]#<br> #DaysArray[2][1]#&nbsp;&nbsp;#DaysArray[2][2]#<br> #DaysArray[3][1]#&nbsp;&nbsp;#DaysArray[3][2]#<br> </cfoutput> <cfoutput> We delete this element of the array:<br> #ArrayDeleteAt(DaysArray,2)#<br> </cfoutput> <!--- the formerly third element, "Wednesday" is second element ---> <p>This is what the array looks like after delete:<br> <cfoutput> #DaysArray[1][1]#&nbsp;&nbsp;#DaysArray[1][2]#<br> #DaysArray[2][1]#&nbsp;&nbsp;#DaysArray[2][2]#<br> </cfoutput> Chapter 3: ColdFusion Functions...
  • Page 473 ArrayInsertAt Description Inserts a value into an array. Array elements whose indexes are equal to or 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 “Functions for XML object management”...
  • Page 474 <cfset DaysArray[1] = "Monday"> <cfset DaysArray[2] = "Tuesday"> <cfset DaysArray[3] = "Thursday"> <!--- add an element before position 3 ---> <p>Add an element before position 3: <cfoutput>#ArrayInsertAt(DaysArray,3,"Wednesday")#</cfoutput> <p>Now output the array as a list: <cfoutput>#ArrayToList(DaysArray)#</cfoutput> <!--- The array now has four elements. Element 3, "Thursday", has become element four --->...
  • Page 475 ArrayIsEmpty Description Determines whether an array is empty of data elements. Returns True, if the array is empty; False, otherwise. Category Array functions Function syntax ArrayIsEmpty(array) See also , “Functions for XML object management” in Chapter 35, “Using XML and WDDX,” ArrayLen in ColdFusion MX Developer’s Guide History...
  • Page 476 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 ; “Functions for XML object management” in Chapter 35, “Using XML and ArrayIsEmpty WDDX,” in ColdFusion MX Developer’s Guide History ColdFusion MX: Changed behavior: this function can be used on child XML objects.
  • Page 477 ArrayMax Description Array maximum function. Returns The largest numeric value in an array. If the parameter value is an empty array, returns array zero. Category Array functions Function syntax ArrayMax(array) Parameters Parameter Description array Name of an array Example <h3>ArrayMax Example</h3> <p>This example uses ArrayMax to find the largest number in an array.<br>...
  • Page 478 ArrayMin Description Array minimum function. Returns The smallest numeric value in an array. If the parameter value is an empty array, returns array zero. Category Array functions Function syntax ArrayMin(array) Parameters Parameter Description array Name of an array Example <h3>ArrayMin Example</h3> <p>This example uses ArrayMin to find the smallest number in an array.<br></p>...
  • Page 479 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 <h3>ArrayNew Example</h3>...
  • Page 480 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 ; “Adding elements to an array” in Chapter 5, “Using Arrays and Structures,” in ArrayAppend ColdFusion MX Developer’s Guide Parameters...
  • Page 481 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 tag. ArrayNew ColdFusion arrays expand dynamically as data is added. Returns True, on successful completion.
  • Page 482 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 ;...
  • Page 483 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.
  • Page 484 Parameter Description 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 (ascending sort) sort_order = "asc" - ZBAzbaa, if (descending sort) sort_order = "desc"...
  • Page 485 ArraySum Description Array sum function. Returns The sum of values in an array. If the parameter value is an empty array, returns zero. array Category Array functions, Mathematical functions Function syntax ArraySum(array) Parameters Parameter Description array Name of an array Example <h3>ArraySum Example</h3>...
  • Page 486 ArraySwap Description Swaps array values of an array at specified positions. This function is more efficient than multiple tags. cfset Returns True, on successful completion. Category Array functions Function syntax ArraySwap(array, position1, position2) See also “Functions for XML object management” in Chapter 35, “Using XML and WDDX,” in ColdFusion MX Developer’s Guide Parameters Parameter...
  • Page 487 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 multicharacter string to separate list elements. The default value is comma.
  • Page 488 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 History ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode characters, up to a value of 65536.
  • Page 489 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, Parameters Parameter Description number Sine of an angle.
  • Page 490 <cfelse> <!--- if it is empty, output an error message ---> <h4>Enter the sine of the angle to calculate, in degrees and radians. The value must be between 1 and -1,inclusive.</h4> </cfif> </cfif> <form action = "./evaltest.cfm" method="post"> <p>Enter a number to get its arcsine in Radians and Degrees. <br><input type = "Text"...
  • Page 491 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, Parameters Parameter Description number Tangent of an angle Usage The range of the result is - /2 to /2 radians.
  • Page 492 AuthenticatedContext Description This function is obsolete. Use the newer security tools; see “Conversion functions” on page 453 and Chapter 16, “Securing Applications” in ColdFusion MX Developer’s Guide. History ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases.
  • Page 493 AuthenticatedUser Description This function is obsolete. Use the newer security tools; see “Conversion functions” on page 453 and Chapter 16, “Securing Applications” in ColdFusion MX Developer’s Guide. History ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases.
  • Page 494 Binary data is often encoded as a string for transmission over many Internet protocols, such as HTTP and SMTP, or for storage in a database. Macromedia recommends that you use the function, not the...
  • Page 495 Example The following example reads a GIF file as binary data, converts it to a binary-encoded string, converts the binary-encoded data back to binary data and writes the result to a file. It displays the encoded string and the image in the output file. <h3>Binary Encoding Conversion Example</h3>...
  • Page 496 Internet protocol or store in a database as character data. To convert the data back to a binary format, use the function. BinaryDecode Macromedia recommends that you use the function, and not the BinaryEncode function, to convert binary data to Base64 data in all new applications.
  • Page 497 • for checking variables for binary format IsBinary • for determining the length of a binary object Example The following example reads a GIF file as binary data, converts it to a binary-encoded string, converts the binary-encoded data back to binary data, and writes the result to a file. It displays the encoded string and the image in the output file.
  • Page 498 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 –...
  • Page 499 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;...
  • Page 500 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;...
  • Page 501 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;...
  • Page 502 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 <h3>BitNot Example</h3>...
  • Page 503 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 –...
  • Page 504 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 –...
  • Page 505 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 –...
  • Page 506 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 <h3>BitXOr Example</h3>...
  • Page 507 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 <h3>Ceiling Example</h3>...
  • Page 508 CharsetDecode Description Converts a string to a binary representation. Returns A binary object that represents the string. Category Conversion functions, String functions Function syntax CharsetDecode(string, encoding) See also ; “Determining the page encoding of server BinaryDecode BinaryEncode CharsetEncode output” in Chapter 17, “Developing Globalized Applications,” in ColdFusion MX Developer’s Guide History ColdFusion MX 7: Added this function.
  • Page 509 Example The following example uses the function to convert a string from a form to a CharsetDecode binary object, and uses the function to convert it back to the original value. You CharsetEncode can change the character encoding that ColdFusion uses for the conversion. Notice that if you select the Asian language encodings, characters that are not in the specified character set do get successfully converted.
  • Page 510 <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL"> The following four characters are not in all character encodings: ½àç÷ </textArea><br> <br> <input type = "Submit" value = "convert my data"> </form> Chapter 3: ColdFusion Functions...
  • Page 511 For a complete list of character encoding names supported by Sun Java runtimes, http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html http:// java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html. Usage Macromedia recommends that you use this function, and not the function, to convert ToString binary data to strings in all new applications. CharsetEncode...
  • Page 512 Example The following example uses the function to convert a string from a form to a CharsetDecode binary object, and uses the function to convert it back to the original value. You CharsetEncode can change the character encoding that ColdFusion uses for the conversion. Notice that if you select the Asian language encodings, characters that are not in the specified character set do get successfully converted.
  • Page 513 <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL"> The following four characters are not in all character encodings: ½àç÷ </textArea><br> <br> <input type = "Submit" value = "convert my data"> </form> CharsetEncode...
  • Page 514 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 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...
  • Page 515 maxlength="5" > <p><input type="Submit" name=""> <input type="RESET"> </cfform>...
  • Page 516 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...
  • Page 517 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...
  • Page 518 <h3>This is the default case</h3> </CFDEFAULTCASE> </cfswitch> </cfif> <form action = "compare.cfm" method="post"> <p>String 1 <br><input type = "Text" name = "string1"> <p>String 2 <br><input type = "Text" name = "string2"> <p><input type = "Submit" value = "Compare these Strings" name = ""> <input type = "RESET">...
  • Page 519 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...
  • Page 520 </CFSWITCH> </CFIF> <FORM ACTION="comparenocase.cfm" METHOD="POST"> <P>String 1 <BR><INPUT TYPE="Text" NAME="string1"> <P>String 2 <BR><INPUT TYPE="Text" NAME="string2"> <P><INPUT TYPE="Submit" VALUE="Compare these Strings" NAME=""> <INPUT TYPE="RESET"> </FORM> Chapter 3: ColdFusion Functions...
  • Page 521 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, Parameters Parameter Description number Angle, in radians, for which to calculate the cosine Usage The range of the result is -1 to 1.
  • Page 522 </cfif> </cfif> <form action = "#CGI.script_name#" method="post"> Enter an angle in degrees to get its cosine: <br><input type = "Text" name = "cosNum" size = "15"> <br><br> <input type = "Submit" name = "">&nbsp;&nbsp; <input type = "RESET" </form> Chapter 3: ColdFusion Functions...
  • Page 523 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 ; “Date-time functions and queries when ODBC is not CreateDateTime, CreateODBCDate supported” in Chapter 3, “Using ColdFusion Variables” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 524 <li>Formatted with CreateDate and DateFormat: #DateFormat(CreateDate(form.year, form.month, form.day), "mmm-dd- yyyy")# <li>Formatted with CreateDateTime and DateFormat: #DateFormat(CreateDateTime(form.year, form.month, form.day, 12,13,0))# <li>Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")# <li>Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")# </ul> </cfoutput> </CFIF> <CFFORM ACTION="createdate.cfm" METHOD="POST"> <p>Enter the year, month and day, as integers: <PRE>...
  • Page 525 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 ; “Date-time functions and queries when CreateDate CreateTime CreateODBCDateTime ODBC is not supported” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion MX Developer’s Guide Parameters Parameter...
  • Page 526 <p>The same value can be formatted with DateFormat: <ul> <li>Formatted with CreateDate and DateFormat: #DateFormat(CreateDate(form.year, form.month, form.day), "mmm-dd-yyyy")# <li>Formatted with CreateDateTime and DateFormat: #DateFormat(CreateDateTime(form.year, form.month, form.day, form.hour, form.minute, form.second))# <li>Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")# <li>Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")# </ul>...
  • Page 527 For example, if " ", for a class, use either of the context=NameService following formats for the parameter: class " " Macromedia/Eng/CF " " Macromedia.current/Eng.current/CF (In earlier releases, the format was " ".) Macromedia.Eng.CF • For CORBA object: changed the parameter;...
  • Page 528 CreateObject: COM object Description function can create a Component Object Model (COM) object. CreateObject 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 •...
  • Page 529 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 tag. cfscript Mailer = CreateObject("COM", "CDONTS.NewMail"); CreateObject...
  • Page 530 CreateObject: component object Description function can create an instance of a ColdFusion component (CFC) object. CreateObject Returns A component object. Function syntax CreateObject(type, component-name) See also Chapter 10, “Building and Using ColdFusion Components” in ColdFusion MX Developer’s Guide Parameters Parameter Description type Type of object to create.
  • Page 531 Configuring and Administering ColdFusion MX. Usage In the parameter, if " ", use a dot separator for the first part of the class context=NameService string. Use either of the following formats: • " " Macromedia/Eng/CF • " " Macromedia.current/Eng.current/CF CreateObject...
  • Page 532 This function supports user-defined types (structures, arrays, and sequences). Example myobj = CreateObject("corba", "d:\temp\tester.ior", "ior", "visibroker") // uses IOR myobj = CreateObject("corba", "Macromedia/Eng/CF", "nameservice", "visibroker") // uses nameservice myobj = CreateObject("corba", "d:\temp\tester.ior", "nameservice") // uses nameservice and default configuration...
  • Page 533 CreateObject: Java or EJB object Description function can create a Java object, and, by extension, an EJB object. CreateObject Returns A Java object. Function syntax CreateObject(type, class) Parameters Parameter Description type Type of object to create. • com • corba •...
  • Page 534 CreateObject: web service object Description This function can create a web service object. Returns A web service object. Function syntax CreateObject(type, urltowsdl [, portname ]) Parameters Parameter Description type Type of object to create. • com • corba • java •...
  • Page 535 (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 function, using the mm-dd-yyyy mask, into three elements. Ensure that values are DateFormat within appropriate ranges;...
  • Page 536 #DateFormat(CreateDateTime(form.year, form.month, form.day, form.hour, form.minute, form.second))# <li>Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")# <li>Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")# </ul> </cfoutput> </cfif> <cfform action="createodbcdate.cfm" method="POST"> <p>Enter the year, month and day, as integers: <pre> Year <cfinput type="text" name="year" value="1998" validate="integer" required="yes">...
  • Page 537 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 ; “Evaluation and type conversion CreateDateTime CreateODBCDate CreateODBCTime issues” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 538 <li>Formatted with CreateODBCDate and DateFormat: #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")# <li>Formatted with CreateODBCDateTime and DateFormat: #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")# </ul> </cfoutput> </cfif> <CFFORM ACTION="createodbcdatetime.cfm" METHOD="POST"> <p>Enter a year, month and day, as integers: <pre> Year <CFINPUT TYPE="Text" NAME="year" VALUE="1998" VALIDATE="integer" REQUIRED="Yes"> Month<cfinput TYPE="Text" NAME="month" VALUE="6"...
  • Page 539 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 , “Evaluation and type conversion issues” in Chapter 3, CreateODBCDateTime CreateTime “Using ColdFusion Variables,” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 540 CreateTime Description Creates a time variable. Returns A time variable. Category Date and time functions Function syntax CreateTime(hour, minute, second) See also ; “Evaluation and type conversion issues” in Chapter 3, CreateODBCTime CreateDateTime “Using ColdFusion Variables,” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 541 MESSAGE="You must enter a value for seconds (0-59)" VALIDATE="integer" REQUIRED="Yes"> </PRE> <p><input type="submit" name=""> <input type="reset"> </cfform> CreateTime...
  • Page 542 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 attribute of cachedWithin cfquery Returns A date-time object. Category Date and time functions Function syntax CreateTimeSpan(days, hours, minutes, seconds) See also...
  • Page 543 cachedWithin = "#CreateTimeSpan(0, 6, 0, 0)#"> SELECT PARKNAME, REGION, STATE FROM Parks ORDER by ParkName, State </cfquery> </cfoutput> <!--- build HTML table to display query ---> <table cellpadding = 1 cellspacing = 1> <TR> <TD colspan = 2 bgcolor = f0f0f0> <b><I>Park Name</i></b>...
  • Page 544 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 , where xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx is a hexadecimal digit (0-9 or A-F). (The character groups are 8-4-4-16.) Category Other functions Function syntax...
  • Page 545 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...
  • Page 546 <!--- if numbers passed, then use those ---> <cfif IsDefined("form.value")> <cfset value = form.value> </cfif> <cfif IsDefined("form.type")> <cfset type = form.type> </cfif> <cfquery name="GetMessages" datasource="cfdocexamples"> SELECT UserName, Subject, Posted FROM Messages </cfquery> <p>This example uses DateAdd to determine when a message in the database will expire.
  • Page 547 <option value="yyyy">years <option value="m" selected>months <option value="d">days <option value="ww">weeks <option value="h">hours <option value="n">minutes <option value="s">seconds </select> <input type="Submit" value="Submit"> </cfform> DateAdd...
  • Page 548 DateCompare Description Performs a full date/time comparison of two dates. Returns • -1, if date1 is earlier than date2 • 0, if date1 is equal to date2 • 1, if date1 is later than date2 Category Date and time functions Function syntax DateCompare("date1", "date2"...
  • Page 549 #TimeFormat(FORM.date2)#</cfoutput> (Date 2)</h3> <I>The dates are not equal</I> </cfcase> <cfcase value = "0"> <h3><cfoutput>#DateFormat(FORM.date1)# #TimeFormat(FORM.date1)#</cfoutput> (Date 1) is equal to <cfoutput>#DateFormat(FORM.date2)# #TimeFormat(FORM.date2)#</cfoutput> (Date 2)</h3> <I>The dates are equal!</I> </cfcase> <cfcase value = "1"> <h3><cfoutput>#DateFormat(FORM.date1)# #TimeFormat(FORM.date1)#</cfoutput> (Date 1) is later than <cfoutput>#DateFormat(FORM.date2)# #TimeFormat(FORM.date2)#</cfoutput>...
  • Page 550 </option> </select> <p><input type = "Submit" value = "Compare these dates" name = ""> <input type = "reset"> </form> Chapter 3: ColdFusion Functions...
  • Page 551 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")
  • Page 552 <cfset yourUTC = DateConvert("local2utc", yourDate)> <p><cfoutput>Your date and time value, converted to Coordinated Universal Time (UTC): #yourUTC#.</cfoutput></p> <p><cfoutput>Your UTC date and time, converted back to local date and time: #DateConvert("utc2local", yourUTC)#. </cfoutput></p> <cfelse> Type the date and time, and press Enter to see the conversion. </cfif>...
  • Page 553 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: •...
  • Page 554 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. Example <cfif IsDefined("form.value")> <cfset value = form.value> </cfif>...
  • Page 555 <p>Please enter two valid date/time values, formatted like this: <cfoutput>#DateFormat(Now())#</cfoutput> </cfif> </cfif> <form action="index.cfm" method="post"> <pre> Date 1 <input type="Text" name="date1" value="<CFOUTPUT>#DateFormat(Now())#</ CFOUTPUT>"> Date 2 <input type="Text" name="date2" value="<CFOUTPUT>#DateFormat(Now())#</ CFOUTPUT>"> What kind of unit to show difference? <select name="type"> <option value="yyyy" selected>years <option value="q">quarters <option value="m">months <option value="y">days of year...
  • Page 556 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"...
  • Page 557 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 , and functions to format resultset values.
  • Page 558 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...
  • Page 559 <ul> <li>year: #DatePart("yyyy", todayDate)# <li>quarter: #DatePart("q", todayDate)# <li>month: #DatePart("m", todayDate)# <li>day of year: #DatePart("y", todayDate)# <li>day: #DatePart("d", todayDate)# <li>weekday: #DatePart("w", todayDate)# <li>week: #DatePart("ww", todayDate)# <li>hour: #DatePart("h", todayDate)# <li>minute: #DatePart("n", todayDate)# <li>second: #DatePart("s", todayDate)# </ul> </cfoutput> DatePart...
  • Page 560 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...
  • Page 561 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 DayOfWeekAsString DayOfYear DaysInMonth...
  • Page 562 DayOfWeekAsString Description Determines the day of the week, in a date, as a string function. Returns The day of the week, as a string in the current locale, that corresponds to day_of_week. Category Date and time functions, String functions Function syntax DayOfWeekAsString(day_of_week) See also DayOfWeek...
  • Page 563 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 DayOfWeek DayOfWeekAsString DaysInMonth DaysInYear FirstDayOfMonth Parameters Parameter Description date Date/time object, in the range 100 AD–9999 AD.
  • Page 564 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 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.
  • Page 565 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 DayOfWeek DayOfWeekAsString DayOfYear DaysInMonth DaysInYear FirstDayOfMonth IsLeapYear Parameters Parameter Description date • Date/time object, in the range 100 AD–9999 AD. Usage accounts for leap years.
  • Page 566 Description Escapes any double-quotation marks in the parameter and wraps the result in double-quotation marks. Returns Parameter, surrounded by double-quotation marks, with any inner double-quotation marks escaped. Category Dynamic evaluation functions Function syntax DE(string) See also , Chapter 4, “Using Expressions and Number Signs” in ColdFusion MX Developer’s Evaluate Guide Parameters...
  • Page 567 The following example shows how you can use the function and number signs together, and shows how the function works with an function: <cfoutput> <cfset var1=Blue> <cfset var2=Green> <cfset myresult=IIf( 1 eq 2, DE(#Var1#), DE(#Var2#))> The expression is #myresult# </cfoutput> ColdFusion processes this code as follows: ColdFusion sets the variables to be the strings Blue and Green.
  • Page 568 <!--- the message to display ---> <h3>Sorry, there’s been an <B>Error</B>. Try a simple expression, such as "2+2".</h3> <cfoutput> <!--- Display the diagnostic message from ColdFusion. ---> <p>#cfcatch.message# </cfoutput> </cfcatch> </cftry> </cfif> <h3>Enter any valid ColdFusion expression</h3> <cfform> <cfinput name="myExpression" type="Text" size="40"> <cfinput type="submit"...
  • Page 569 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 <h3>DecimalFormat Function</h3>...
  • Page 570 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 <h3>DecrementValue Example</h3> <p>Returns the integer part of a number decremented by one. <p>DecrementValue(0): <cfoutput>#DecrementValue(0)#</cfoutput>...
  • Page 571 Decrypt Description Decrypts a string that is encrypted using a standard encryption technique, including strings encrypted by the function. Encrypt Returns An unencrypted string. Category Security functions, String functions Function syntax Decrypt(encrypted_string, key[, algorithm[, encoding]]) See also Duplicate Encrypt ColdFusion MX 7: Added the parameters.
  • Page 572 Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third- party security providers.
  • Page 573 </select><br> <br> <b>Select the algorithm</b><br> <select size="1" name="myAlgorithm" > <option selected>CFMX_COMPAT</option> <option>AES</option> <option>DES</option> <option>DESEDE</option> </select><br> <br> <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br> <input type = "Text" name = "myKey" value = "MyKey"><br> <br> <b>Enter string to encrypt</b><br> <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">This string will be encrypted (you can replace it with more typing).
  • Page 574 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...
  • Page 575 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 <h3>DirectoryExists Example</h3> <h3>Enter a directory to check for existence.</h2> <form action = "directoryexists.cfm"...
  • Page 576 DollarFormat Description Formats a string in U.S. format. (For other currencies, use LSCurrencyFormat 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.
  • Page 577 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 , other Structure functions;...
  • Page 578 Encrypt Description Encrypts a string using a specific algorithm and encoding method. Returns String; can be much longer than the original string. Category Security functions, String functions Function syntax Encrypt(string, key[, algorithm[, encoding]])) See also Decrypt History ColdFusion MX 7: Added the parameters.
  • Page 579 Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.
  • Page 580 <!--- The input form. ---> <form action="#CGI.SCRIPT_NAME#" method="post"> <b>Select the encoding</b><br> <select size="1" name="myEncoding" > <option selected>UU</option> <option>Base64</option> <option>Hex</option> </select><br> <br> <b>Select the algorithm</b><br> <select size="1" name="myAlgorithm" > <option selected>CFMX_COMPAT</option> <option>AES</option> <option>DES</option> <option>DESEDE</option> </select><br> <br> <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br> <input type = "Text"...
  • Page 581 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...
  • Page 582 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 , the natural logarithm of number. Returns The constant e, raised to the power of number. Category Mathematical functions Function syntax...
  • Page 583 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 parameter relative_path The base path is the currently executing page’s directory path. It is stored in pageContext.getServletContext().
  • Page 584 Example <h3>ExpandPath Example - View Only</h3> <!--- <cfset thisPath=ExpandPath("*.*")> <cfset thisDirectory=GetDirectoryFromPath(thisPath)> <cfoutput> The current directory is: #GetDirectoryFromPath(thisPath)# <cfif IsDefined("form.yourFile")> <cfif form.yourFile is not ""> <cfset yourFile = form.yourFile> <cfif FileExists(ExpandPath(yourfile))> <p>Your file exists in this directory. You entered the correct file name, #GetFileFromPath("#thisPath#/#yourfile#")# <CFELSE>...
  • Page 585 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 Usage To access a file on a remote system, the account (for Windows) or user (for UNIX and Linux) that is running ColdFusion must have permission to access the file, directory, and remote system.
  • Page 586 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...
  • Page 587 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...
  • Page 588 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...
  • Page 589 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 DayOfWeek...
  • Page 590 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...
  • Page 591 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...
  • Page 592 Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third- party security providers.
  • Page 593 Example The following example encrypts and decrypts a text string. It lets you specify the encryption algorithm and encoding technique. It also has a field for a key seed to use with the CFMX_COMPAT algorithm. For all other algorithms, it uses the function GenerateSecretKey to generate a secret key.
  • Page 594 <option>DESEDE</option> </select><br> <br> <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br> <input type = "Text" name = "myKey" value = "foobar"><br> <br> <b>Enter string to encrypt</b><br> <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">This string will be encrypted (you can replace it with more typing). </textArea><br>...
  • Page 595 GetAuthUser Description Gets the name of an authenticated user. Returns The name of an authenticated user. Category Security functions Function syntax GetAuthUser() See also ; Chapter 16, “Securing Applications” in ColdFusion MX IsUserInRole, cflogin cfloginuser Developer’s Guide History ColdFusion MX: Added this function. Usage This function works with authentication or web server authentication.
  • Page 596 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, ), an cfif exception is thrown.
  • Page 597 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.
  • Page 598 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 <h3>GetBaseTemplatePath Example</h3> <p>The template path of the current page is: <cfoutput>#GetBaseTemplatePath()#</cfoutput>...
  • Page 599 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 <!--- This example is view-only.
  • Page 600 GetContextRoot Description Returns path to the J2EE server context root for the current request. Returns The path from the web root to the context root for the current page. The path starts with a forward slash character (/) but does not end with a forward slash character (/). For applications in the default (root) context, returns the empty string.
  • Page 601 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 tag, this function returns the...
  • Page 602 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...
  • Page 603 </cfoutput> <form action="getdirectoryfrompath.cfm" METHOD="post"> <H3>Enter the name of a file in this directory <I><FONT SIZE="-1"> (try expandpath.cfm)</FONT></I></H3> <input type="Text" NAME="yourFile"> <input type="Submit" NAME=""> </form> ---> GetDirectoryFromPath...
  • Page 604 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...
  • Page 605 WriteOutput("The encoding is " & theEncoding); </cfscript> </cfif> GetEncoding...
  • Page 606 GetException Description Used with the tags. Retrieves a Java exception object from a Java object. cftry cfcatch 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.
  • Page 607 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 <h3>GetFileFromPath Example</h3> <cfset thisPath = ExpandPath("*.*")> <cfset thisDirectory = GetDirectoryFromPath(thisPath)>...
  • Page 608 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 <!----- This example shows the use of GetFunctionList. ----> <cfset fList = GetFunctionList()> <cfoutput>#StructCount(fList)# functions<br><br> </cfoutput>...
  • Page 609 GetGatewayHelper Description Gets a Java GatewayHelper object that provides methods and properties for use with a ColdFusion event gateway. Returns A Java GatewayHelper object. Category Extensibility functions Function syntax GetGatewayHelper(gatewayID) See also SendGatewayMessage History ColdFusion MX 7: Added the function. Parameters Parameter Description...
  • Page 610 Example If an event gateway’s helper class includes an method that takes a single String addBuddy parameter, you could use the following code to get the GatewayHelper object and add a buddy to the buddies list: <h3>GetGatewayHelper Example</h3> <cfscript> myHelper = getGatewayHelper(myGatewayID); status = myHelper.addBuddy(“jsmith”);...
  • Page 611 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() Returns The function returns a structure containing the following entries: Parameter Description content...
  • Page 612 <tr> <td>server_protocol</td> <td>#x.protocol#</td></tr> </table> <b>http_content --- #x.content#</b> </cfoutput> Chapter 3: ColdFusion Functions...
  • Page 613 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 and its underlying RFC, 822. This format is commonly used in Internet protocols, including HTTP. Category Date and time functions,...
  • Page 614 GetK2ServerDocCount Description This function is deprecated. 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.
  • Page 615 GetK2ServerDocCountLimit Description This function is deprecated. 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.
  • Page 616 GetLocale Description Gets the current ColdFusion MX 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 function. SetLocale Returns The current locale value, as an English string. If a locale has a Java name and a name that ColdFusion MX used prior to the ColdFusion MX 7 release (for example, en_US and English (US)), ColdFusion MX returns the ColdFusion name (for example, English (US)).
  • Page 617 For more information, see “Locales” in Chapter 17, “Developing Globalized Applications,” in ColdFusion MX Developer’s Guide. Example <h3>Example: Using SetLocale and GetLocale</h3> <cfoutput> <!--- For each new request, the locale gets reset to the JVM locale ---> Initial locale's ColdFusion name: #GetLocale()#<br> <br>...
  • Page 618 GetLocaleDisplayName Description Gets a locale value and displays the name in a manner that is appropriate to a specific locale. By default, gets the current locale in the current locale’s language. Returns The localized display name of the locale, in the language of the specified locale. Category Display and formatting functions,...
  • Page 619 <br> <!--- Set the locale to the submitted value. SetLocale returns the old ColdFusion locale name. ---> <cfset oldlocale=SetLocale("#form.mylocale#")> <!--- Get the current locale's ColdFusion name. It should have changed. ---> <cfset newlocale=GetLocale()> New locale's ColdFusion name: #newlocale#<br> New locale's display name in current locale: #GetLocaleDisplayName()#<br> New locale's display name in old locale: #GetLocaleDisplayName(newlocale, oldlocale)#<br>...
  • Page 620 GetMetaData Description Gets metadata (such as the methods, properties, and parameters of a component) associated with an object that is deployed on the ColdFusion server. Returns Structured metadata information: for ColdFusion components (CFCs) and user defined functions (UDFs), a structure; for query objects, an array of structures. Category System functions Function syntax...
  • Page 621 The following table lists the data returned by the function for supported object types: Object Field Description Component A structure containing the following fields: displayname Value of the attribute, if any. cfcomponent displayname extends Metadata for the component’s ancestor component. Components that do not explicitly extend another component extend the WEB-INF.cftags.component.
  • Page 622 Object Field Description Parameter or Property A structure containing the following fields: default Value of the attribute, if cfargument cfproperty default any. displayname Value of the cfargument cfproperty displayname attribute, if any. hint Value of the attribute, if cfargument cfproperty hint any.
  • Page 623 <cfquery name="getemployees" datasource="cfdocexamples"> SELECT FROM Employees </cfquery> <cfset employeemeta=getMetaData(getemployees)> <h4>The Employees table has the following columns</h4> <cfloop index="i" from="1" to="#arrayLen(employeemeta)#"> <cfoutput> #employeemeta[i].name# #employeemeta[i].TypeName# #employeemeta[i].isCaseSensitive#<br> </cfoutput> </cfloop> GetMetaData...
  • Page 624 GetMetricData Description Gets server performance metrics. Returns ColdFusion structure that contains metric data, depending on the value. mode Category System functions Function syntax GetMetricData(mode) History ColdFusion MX: Deprecated the parameter. It might not work, and it might cause an cachepops error, in later releases.
  • Page 625 Field Description ReqRunning Number of HTTP requests currently running. In the ColdFusion Administrator, you can set the maximum number of requests that run concurrently. 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...
  • Page 626 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.
  • Page 627 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;...
  • Page 628 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.
  • Page 629 <tr> <td><input type = "Submit" name = "Submit" value = "Submit"></td> <td></td> </tr></table> </form> GetProfileString...
  • Page 630 GetSOAPRequest Description Returns an XML object that contains the entire SOAP request. Usually called from within a web service CFC. Returns An XML object that contains the entire SOAP request. Category XML functions History ColdFusion MX 7: Added this function. Function syntax GetSOAPRequest() See also...
  • Page 631 different than shown here. Note, too, that getSOAPRequest is called from the client here, whereas often it would be called from within the web service CFC. ---> <cfscript> ws = CreateObject("webservice", "http://localhost/soapheaders/headerservice.cfc?WSDL"); ws.echo_me("hello world"); req = getSOAPRequest(ws); </cfscript> <cfdump var="#req#"> GetSOAPRequest...
  • Page 632 GetSOAPRequestHeader Description Obtains a SOAP request header. Call only from within a CFC web service function that is processing a request as a SOAP web service. Returns A SOAP request header. Category XML functions History ColdFusion MX 7: Added this function. Function syntax GetSOAPRequestHeader(namespace, name [, asXML]) See also...
  • Page 633 <h3>GetSOAPRequestHeader Example</h3> <cfcomponent displayName="tester" hint="Test for SOAP headers"> <cffunction name="echo_me" access="remote" output="false" returntype="string" displayname="Echo Test" hint="Header test"> <cfargument name="in_here" required="true" type="string"> <cfset isSOAP = isSOAPRequest()> <cfif isSOAP> <!--- Get the first header as a string and as XML ---> <cfset username = getSOAPRequestHeader("http://mynamespace/", "username")> <cfset return = "The service saw username: "...
  • Page 634 GetSOAPResponse Description Returns an XML object that contains the entire SOAP response after invoking a web service. Returns An XML object that contains the entire SOAP response. Category XML functions History ColdFusion MX 7: Added this function. Function syntax GetSOAPResponse(webservice) See also AddSOAPRequestHeader AddSOAPResponseHeader...
  • Page 635 GetSOAPResponseHeader Description Returns a SOAP response header. Call this function from within code that is invoking a web service after making a web service request. Returns A SOAP response header. Category XML functions History ColdFusion MX 7: Added this function. Function syntax GetSOAPResponseHeader(webservice, namespace, name [, asXML]) See also...
  • Page 636 Execute the following example to see how the function operates: GetSOAPResponseHeader <!--- Note that you might need to modify the URL in the CreateObject function to match your server and the location of the headerservice.cfc file if it is different than shown here. Likewise for the cfinvoke tag at the end ---> <h3>GetSOAPResponseHeader Example</h3>...
  • Page 637 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.
  • Page 638 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...
  • Page 639 GetTemplatePath Description This function is deprecated. Use the function instead. GetBaseTemplatePath 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...
  • Page 640 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, System 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.
  • Page 641 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.
  • Page 642 GetToken Description Determines whether a token of the list in the parameter is present in a string. delimiters 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...
  • Page 643 <cfoutput> #mystring#<br><br> </cfoutput> The output is as follows: four, ,five, nine,zero:; nine,ten:, eleven:;twelve:;thirteen, ,four function recognizes explicit spaces, tabs, or newline characters as the parameter GetToken delimiters (To specify a space character, the code is ; a tab character, ; and a chr(32) chr(9) newline character,...
  • Page 644 The following is a call against mystring2 <cfoutput> GetToken(mystring2, 2) is : #GetToken(mystring2, 2)# </cfoutput> The output is as follows: GetToken(mystring2, 2) is : ,five,nine,zero:; The function finds the second delimiter, and returns the substring just before it that is between the first and second delimiter.
  • Page 645 Hash Description Converts a variable-length string to a fixed-length string that can act as a “fingerprint” or unique identifier for the original string. It is not possible to convert the hash result back to the source string. Returns A string. Category Conversion functions,...
  • Page 646 Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third- party security providers.
  • Page 647 <!--- Form for entering ID and password. ---> <form action="#CGI.SCRIPT_NAME#" method="post"> <b>User ID: </b> <input type = "text" name="UserID" ><br> <b>Password: </b> <input type = "text" name="password" ><br><br> <input type = "Submit" value = "Encrypt my String"> </form> Hash...
  • Page 648 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.
  • Page 649 HTMLCodeFormat Description Replaces special characters in a string with their HTML-escaped equivalents and inserts <pre> tags at the beginning and end of the string. </pre> Returns HTML-escaped string string, enclosed in tags. Return characters are removed; <pre> </pre> line feed characters are preserved. Characters with special meanings in HTML are converted to HTML character entities such as &gt;.
  • Page 650 Example <!--- This example shows the effects of HTMLCodeFormat and HTMLEditFormat. View it in your browser, then View it using your browser's the View Source command. ---> <cfset testString="This is a test & this is another <This text is in angle brackets> Previous line was blank!!!">...
  • Page 651 HTMLEditFormat Description Replaces special characters in a string with their HTML-escaped equivalents. Returns HTML-escaped string string. Return characters are removed; line feed characters are preserved. Characters with special meanings in HTML are converted to HTML character entities such as &gt;. Category Display and formatting functions Function syntax...
  • Page 652 The only difference between this function and is that HTMLCodeFormat HTMLCodeFormat surrounds the text in an HTML tag. Example <!--- This example shows the effects of HTMLCodeFormat and HTMLEditFormat. View it in your browser, then View it using your browser's the View Source command. ---> <cfset testString="This is a test &...
  • Page 653 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 tag in-line in HTML. cfif For general conditional processing, see .
  • Page 654 Note: If you use number signs (#) in string_expression1 or string_expression2, ColdFusion evaluates the part of the expression in number signs first. If you misuse the number signs, you can cause unexpected results from the function. For example, if you use number 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.
  • Page 655 <cfoutput> #IIf( Hour(Now()) GTE 12, DE("It is afternoon or evening"), DE("It is morning"))# </cfoutput> </b>...
  • Page 656 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 <h3>IncrementValue Example</h3> <p>Returns the integer part of a number incremented by one. <p>IncrementValue(0): <cfoutput>#IncrementValue(0)#</cfoutput>...
  • Page 657 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.
  • Page 658 Insert Description Inserts a substring in a string after a specified character position. If , prefixes the position = 0 substring to the string. Returns A string. Category String functions Function syntax Insert(substring, string, position) See also RemoveChars Parameters Parameter Description substring A string or a variable that contains one.
  • Page 659 Description Calculates the closest integer that is smaller than number. For example, it returns 3 for Int(3.3) and for ; it returns -4 for and for Int(3.7) Int(-3.3) Int(-3.7 Returns An integer, as a string. Category Mathematical functions Function syntax Int(number) See also Ceiling...
  • Page 660 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 661 IsAuthenticated Description This function is obsolete. Use the newer security tools; see “Conversion functions” on page 453 and Chapter 16, “Securing Applications” in ColdFusion MX Developer’s Guide. History ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases.
  • Page 662 IsAuthorized Description This function is obsolete. Use the newer security tools; see “Conversion functions” on page 453 and Chapter 16, “Securing Applications” in ColdFusion MX Developer’s Guide History ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later releases.
  • Page 663 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 <!--- Create a string of all ASCII characters (32-255) and concatenate them together.
  • Page 664 <cfelse> <h3>Conversion error.</h3> </cfif> Chapter 3: ColdFusion Functions...
  • Page 665 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 IsValid YesNoFormat Parameters Parameter Description value Number or string Example <h3>IsBoolean Example</h3>...
  • Page 666 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 quotation marks. If not a defined variable or function name, ColdFusion generates an error.
  • Page 667 <!--- Example using a CFC, defined in TestCFC.cfc---> <cfobject component="TestCFC" name="myTestCFCobject"> <CFIF IsDefined("myTestCFCobject.testFunc") AND IsCustomFunction(myTestCFCobject.testFunc)> myTestCFCobject.testFunc is a function. </CFIF> IsCustomFunction...
  • Page 668 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; False, otherwise. ColdFusion converts the Boolean return value to its string equivalent, "Yes" or "No." Category Date and time functions,...
  • Page 669 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 attribute to No, the function returns...
  • Page 670 IsDefined Description Evaluates a string value to determine whether the variable named in it exists. This function is an alternative to the function, which is deprecated. ParameterExists Returns True, if the variable is found, or, for a structure, if the specified key is defined; False, otherwise. The return value is False for an array or structure element referenced using bracket notation.
  • Page 671 <p>During the first time through this template, the variable "form.myString" has not yet been defined, so we do not try to evaluate it. </cfif> <form action="#CGI.Script_Name" method="POST"> <input type="Text" name="MyString" value="My sample value"> <input type="Submit" name=""> </form> IsDefined...
  • Page 672 IsK2ServerABroker Description This function is deprecated. 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.
  • Page 673 IsK2ServerDocCountExceeded Description This function is deprecated. 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.
  • Page 674 IsK2ServerOnline Description This function is deprecated because the K2Server is always running when ColdFusion is running. 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...
  • Page 675 IsLeapYear Description Determines whether a year is a leap year. Returns True, if year is a leap year; False, otherwise. Category Date and time functions, Decision functions Function syntax IsLeapYear(year) See also DaysInYear Parameters Parameter Description year Number representing a year Example <h3>IsLeapYear Example</h3>...
  • Page 676 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; False, otherwise. Category Decision functions Function syntax IsNumeric(string) See also...
  • Page 677 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; False, otherwise. Category Date and time functions, Decision functions Function syntax IsNumericDate(number) See also IsDate ParseDateTime Parameters...
  • Page 678 <p> <input type="Text" name="TheTestValue" value="<CFOUTPUT>#Now()#</CFOUTPUT>"> <input type="Submit" value="Is it a Date?" name=""> </form> Chapter 3: ColdFusion Functions...
  • Page 679 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...
  • Page 680 returnVariable="myColor"> </cfinvoke> <cfif IsDefined("myColor")> <!--- Output the returned variable ---> The value of myColor = <cfoutput>#myColor#</cfoutput><p> </cfif> </cfif> Chapter 3: ColdFusion Functions...
  • Page 681 IsProtected Description This function is obsolete. Use the newer security tools; see “Conversion functions” on page 453 and Chapter 16, “Securing Applications,” in ColdFusion MX Developer’s Guide History ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later releases.
  • Page 682 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 <!--- Shows an example of IsQuery and IsSimpleValue ---> <h3>IsQuery Example</h3>...
  • Page 683 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) See also IsValid Parameters Parameter Description value Variable or expression Example <!--- Shows an example of IsQuery and IsSimpleValue ---> <h3>IsSimpleValue Example</h3>...
  • Page 684 IsSOAPRequest Description Determines whether a CFC is being called as a web service. Returns True if CFC is being called as a web service; False, otherwise. Category XML functions History ColdFusion MX 7: Added this function. Function syntax IsSOAPRequest() See also AddSOAPRequestHeader AddSOAPResponseHeader GetSOAPRequest...
  • Page 685 <cfset return = "The service saw username: " & username> <cfset xmlusername = getSOAPRequestHeader("http://mynamespace/", "username", "TRUE")> <cfset return = return & "<br> as XML: " & xmlusername> <!--- Get the second header as a string and as XML ---> <cfset password = getSOAPRequestHeader("http://mynamespace/", "password")> <cfset return = return &...
  • Page 686 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. The return value is False if the object in variable is a user-defined function (UDF). Category Decision functions,...
  • Page 687 </cfoutput> </cfquery> </cfif> <cfoutput><hr>Employee Add Complete</cfoutput> </cfcase> </cfswitch> ---> IsStruct...
  • Page 688 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 Security functions, Decision functions Function syntax IsUserInRole("role_name") See also ; Chapter 16, “Securing Applications,” in ColdFusion MX GetAuthUser cflogin cfloginuser...
  • Page 689 IsValid Description Tests whether a value meets a validation or data type rule. Returns True, if the value conforms to the rule; False, otherwise. Category Decision functions Function syntax IsValid(type, value) isValid("range", value, min, max) isValid("regex" or "regular_expression", value, pattern) See also ;...
  • Page 690 Parameters Parameter Description type The valid format for the data; one of the following. For detailed information on validation algorithms, see “Validating form data using hidden fields” in Chapter 28, “Validating Data,” in ColdFusion MX Developer’s Guide. • any: any simple value. Returns false for complex values, such as query objects;; equivalent to the function.
  • Page 691 Example The following example checks whether a user has submitted a numeric ID and a valid email address and phone number. If any of the submitted values does not meet the validation test, it displays an error message. <cfif isDefined("form.saveSubmit")> <cfif isValid("integer", form.UserID) and isValid("email", form.emailAddr) and isValid("telephone", form.phoneNo)>...
  • Page 692 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) See also “Using WDDX” in Chapter 35, “Using XML and WDDX,” in ColdFusion MX Developer’s Guide History ColdFusion MX: Changed behavior: if the parameter is not a WDDX packet, ColdFusion...
  • Page 693 </struct> </data> </wddxPacket>" > <hr> <xmp> <cfoutput>#packet# </xmp> IsWDDX() returns #IsWDDX(packet)#<br> </cfoutput> IsWDDX...
  • Page 694 IsXML Description Determines whether a string is well-formed XML text. Returns True, if the function parameter is a string that contains well-formed XML text; False, otherwise. Category Decision functions, XML functions Function syntax IsXML(value) See also IsXmlAttribute IsXmlDoc IsXmlElem IsXmlNode IsXmlRoot XmlParse XmlValidate...
  • Page 695 <item id="43"> <quantity>1</quantity> <unitprice>15.95</unitprice> </items> </order>' > <!--- Test the strings to see if they are well formed XML ---> <cfoutput> xmlString1 contains the following text:<br><br> #HTMLCodeFormat(xmlstring1)# Is it well formed XML text? #IsXML(xmlString1)#<br><br> <hr> xmlString2 contains the following text:<br><br> #HTMLCodeFormat(xmlstring2)# Is it well formed XML text? #IsXML(xmlString2)# </cfoutput>...
  • Page 696 IsXmlAttribute Description Determines whether the function parameter is an XML Document Object Model (DOM) attribute node. Returns True, if the function argument is an XML attribute node; False, otherwise. Category Decision functions, XML functions Function syntax IsXmlAttribute(value) See also IsXML IsXmlDoc IsXmlElem IsXmlNode...
  • Page 697 <!--- Create an XML document object ---> <cfxml variable="xmlobject"> <order id="4323251"> <customer firstname="Philip" lastname="Cramer" accountNum="21"/> <items> <item id="43"> <quantity>1</quantity> <unitprice>15.95</unitprice> </item> </items> </order> </cfxml> <!--- Get an array with all lastname quantity DOM attribute nodes (In this example there is only one entry) ---> <cfset lastnames = XmlSearch(xmlobject, '//@lastname')>...
  • Page 698 IsXmlDoc Description Determines whether the function parameter is a ColdFusion 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 ; Chapter 35, IsXML IsXmlAttribute IsXmlElem IsXmlNode...
  • Page 699 IsXmlElem Description Determines whether the function parameter is an 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 IsXML IsXmlAttribute IsXmlDoc IsXmlNode IsXmlRoot XmlGetNodeType...
  • Page 700 IsXmlNode Description Determines whether the function parameter is an XML document object node. Returns True, if the function argument is an XML document object node, including an element; False, otherwise. Category Decision functions, XML functions Function syntax IsXmlNode(value) See also IsXML IsXmlAttribute IsXmlDoc...
  • Page 701 <quantity>1</quantity> <unitprice>15.95</unitprice> </item> </items> </order> </cfxml> <!--- use XmlSearch to get an attribute node. ---> <cfset lastnames = XmlSearch(xmlobject, '//@lastname')> <!--- Test the objects to see if they are XML nodes---> <cfoutput> <h3>Are the following XML nodes?</h3> xmlobject: #IsXmlNode(xmlobject)#<br> <!--- The items element ---> xmlobject.order.items: #IsXmlNode(xmlobject.order.items)#<br>...
  • Page 702 IsXmlRoot Description Determines whether the function parameter is the root element of an 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 IsXML...
  • Page 703 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...
  • Page 704 Because there is not a one-to-one correspondence between internally stored ColdFusion types and Java scalar types, some conversions cannot be performed. 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) {...
  • Page 705 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.
  • Page 706 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 <h3>LCase Example</h3>...
  • Page 707 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, Parameters Parameter Description string A string or a variable that contains one. count A positive integer or a variable that contains one.
  • Page 708 <select name="RemoveChars"> <option value="1">1 <option value="3" selected>3 <option value="5">5 <option value="7">7 <option value="9">9</select> <input type="Submit" name="Submit" value="Remove characters"></p> </form> Chapter 3: ColdFusion Functions...
  • Page 709 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, History ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535.
  • Page 710 ListAppend Description Concatenates a list or element to a list. Returns A copy of the list with value appended. If , returns a copy of the list, unchanged. delimiter = "" Category List functions Function syntax ListAppend(list, value [, delimiters ]) See also ;...
  • Page 711 <cfoutput> <p>The original list: #temp# </cfoutput> <!--- now, append a park name to the list ---> <cfset temp2 = ListAppend(Temp, "ANOTHER PARK")> ListAppend...
  • Page 712 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion ListFirst ListQualify MX Developer’s Guide...
  • Page 713 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 ;...
  • Page 714 as "two", both ListContains and ListFind find it, in the second element: <p>&nbsp;&nbsp;&nbsp;<strong>ListContains</strong>: <cfoutput> The string "two" is in <b>element #ListContains(aList, "two")#</b> of the list. </cfoutput> &nbsp;&nbsp;&nbsp;<p><strong>ListFind</strong>: <cfoutput> The string "two" is in <b>element #ListFind(aList, "two")#</b> of the list. </cfoutput> Chapter 3: ColdFusion Functions...
  • Page 715 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 ;...
  • Page 716 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ListGetAt ListSetAt ListLen ColdFusion MX Developer’s Guide...
  • Page 717 </cfoutput> <!--- Delete the third element from the list ---> <CFSET temp2 = ListDeleteAt(Temp, "3")> <cfoutput> <p>The changed list: #temp2# <p><I>This list element:<br>#deleted_element#<br> is no longer present at position three of the list.</I> </cfoutput> ListDeleteAt...
  • Page 718 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 ])
  • Page 719 <cfquery name="SearchEmpLastName" datasource="cfdocexamples"> SELECT FirstName, RTrim(LastName) AS LName, Phone, Department FROM Employees </cfquery> <cfset myList = ValueList(SearchEmpLastName.LName)> <!--- Is this case-sensitive or case-insensitive searching ---> <cfif form.type is "ListFind"> <cfset temp = ListFind(myList, form.myString)> <cfif temp is 0> <h3>An employee with that exact last name was not found</h3> <cfelse>...
  • Page 720 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 case- insensitive. Category List functions Function syntax ListFindNoCase(list, value [, delimiters ]) See also ;...
  • Page 721 SELECT FirstName, RTrim(LastName) AS LName, Phone, Department FROM Employees </cfquery> <cfset myList = ValueList(SearchEmpLastName.LName)> <!--- Is this case-sensitive or case-insensitive searching ---> <cfif form.type is "ListFind"> <cfset temp = ListFind(myList, form.myString)> <cfif temp is 0> <h3>An employee with that exact last name was not found</h3> <cfelse>...
  • Page 722 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ListGetAt ListLast ListQualify...
  • Page 723 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 ; “Lists” in Chapter 3, “Using ColdFusion ListFirst ListLast ListQualify ListSetAt Variables,”...
  • Page 724 </cfquery> <cfset temp = ValueList(GetMessageUser.Username)> <!--- loop through the list and show it with ListGetAt ---> <h3>This list of usernames who have posted messages numbers <cfoutput>#ListLen(temp)#</cfoutput> users.</h3> <ul> <cfloop From = "1" To = "#ListLen(temp)#" index = "Counter"> <cfoutput><li>Username #Counter#: #ListGetAt(temp, Counter)# </cfoutput> </cfloop>...
  • Page 725 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 ; “Lists” in Chapter 3, “Using ListDeleteAt ListAppend ListPrepend...
  • Page 726 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion MX ListGetAt ListFirst Developer’s Guide Parameters Parameter...
  • Page 727 <p>Before editing the list, it is:&nbsp; <cfoutput>#ValueList(GetMessageUser.Username)#</cfoutput>. <p>(Users who posted more than once are listed more than once.) <!--- Show the first user in the list ---> <p>The first user in the list is: <cfoutput>#ListFirst(temp)#</cfoutput> <p>The rest of the list is:&nbsp;<cfoutput>#ListRest(temp)#</cfoutput>. <p>(Users who posted more than once are listed more than once.) <p>The last user in the list is: <cfoutput>#ListLast(temp)#</cfoutput>...
  • Page 728 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 ; “Lists” in Chapter 3, “Using ListAppend ListDeleteAt ListInsertAt ListPrepend ColdFusion Variables,” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 729 <cfoutput>#ListLen(temp)#</cfoutput> users.</h3> <ul> <cfloop From = "1" TO = "#ListLen(temp)#" INDEX = "Counter"> <cfoutput><li>Username #Counter#: #ListGetAt(temp, Counter)#</cfoutput> </cfloop> </ul> ListLen...
  • Page 730 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ListAppend ListInsertAt ListSetAt...
  • Page 731 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 ]) See also “Lists”...
  • Page 732 <cfset myArray = ArrayNew(1)> <!--- loop through query; append these names successively to the last element ---> <cfloop query = "GetEmployeeNames"> <cfset temp = ArrayAppend(myArray, "#FirstName# #LastName#")> </cfloop> <!--- sort that array descending alphabetically ---> <cfset myAlphaArray = ArraySort(myArray, "textnocase")> <!--- show the resulting array as a list --->...
  • Page 733 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ListFirst ListGetAt ListLast...
  • Page 734 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 ;...
  • Page 735 </cfquery> <cfset temp = ValueList(GetMessageUser.Subject)> <!--- loop through the list and show it with ListGetAt ---> <h3>This is a list of <cfoutput>#ListLen(temp)#</cfoutput> subjects posted in messages.</h3> <cfset ChangedElement = ListGetAt(temp, 2)> <cfset TempToo = ListSetAt(temp, 2, "I changed this subject", ",")> <ul>...
  • Page 736 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 ]) See also “Lists” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion MX Developer’s Guide History ColdFusion MX: Changed the order in which sorted elements are returned: in a textnocase...
  • Page 737 Parameter Description sort_order • asc - ascending sort order. Default. - aabzABZ or aAaBbBzzZ, depending on value of , for letters sort_type - from smaller to larger, for numbers • desc - descending sort order. - ZBAzbaa or ZzzBbBaAa, depending on value of , for letters sort_type - from larger to smaller, for numbers...
  • Page 738 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 ; Chapter 5, “Using Arrays and Structures,” in ColdFusion MX Developer’s Guide ArrayToList Parameters Parameter...
  • Page 739 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion MX ListValueCountNoCase Developer’s Guide Parameters...
  • Page 740 Sales </OPTION> </select> <input type = "Submit" name = "Submit" value = "Search Employee List"> </form> <!--- wait to have a string for searching defined ---> <cfif IsDefined("FORM.Submit") and IsDefined("FORM.departmentName")> <cfset myList = ValueList(SearchByDepartment.Department)> <cfset numberInDepartment = ListValueCount(myList, FORM.departmentName)> <cfif numberInDepartment is 0> <h3>There are no employees in <cfoutput>#FORM.departmentName#</cfoutput></ h3>...
  • Page 741 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 ; “Lists” in Chapter 3, “Using ColdFusion Variables,” in ColdFusion MX ListValueCount Developer’s Guide Parameters...
  • Page 742 <option value = "Sales"> Sales </OPTION> </select> </select> <input type = "Submit" name = "Submit" value = "Search Employee List"> </form> <!--- wait to have a string for searching defined ---> <cfif IsDefined("FORM.Submit") and IsDefined("FORM.departmentName")> <cfset myList = ValueList(SearchByDepartment.Department)> <cfset numberInDepartment = ListValueCountNoCase(myList, FORM.departmentName)>...
  • Page 743 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...
  • Page 744 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 Log10 Parameters Parameter Description number Positive real number for which to calculate the natural logarithm Example <h3>Log Example</h3>...
  • Page 745 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 Parameters Parameter Description number Positive real number for which to calculate the logarithm Example <h3>Log10 Example</h3>...
  • Page 746 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...
  • Page 747 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.1- compliant JVM, the second entry is the result with a 1.3.1-compliant JVM. Locale Type = Local Type = International...
  • Page 748 Locale Type = Local Type = International Type = None Portuguese (Standard) 100.000,00 ¤ EUR100.000,00 100.000,00 R$100.000,00 BRC100.000,00 Spanish (Mexican) $100,000.00 MXN100,000.00 100,000.00 Spanish (Modern) 100.000,00 ¤ EUR10.000.000 10.000.000 10.000.000 Pts ESP10.000.000 Spanish (Standard) 100.000,00 ¤ ESP10.000.000 10.000.000 10.000.000 Pts EUR10.000.000 Swedish 100.000,00 kr...
  • Page 749 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,...
  • Page 750 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 •...
  • Page 751 <hr noshade> </cfoutput> </cfloop> LSDateFormat...
  • Page 752 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...
  • Page 753 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)
  • Page 754 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 ¤...
  • Page 755 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. The return value is True for amounts in the local, international, or none currency formats.
  • Page 756 <p>Is the value "<cfoutput>#FORM.myValue#</cfoutput>" a proper currency value for <cfoutput>#GetLocale()#</cfoutput>? <p>Answer: <cfoutput>#LSIsCurrency(FORM.myValue)#</cfoutput> </cfif> <p><form action = "LSIsCurrency.cfm"> <p>Select a locale for which you would like to check a currency value: <!--- check the current locale for server ---> <cfset serverLocale = GetLocale()> Chapter 3: ColdFusion Functions...
  • Page 757 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,...
  • Page 758 <p>Is the value "<cfoutput>#FORM.myValue#</cFOUTPUT>" a proper date value for <cfoutput>#GetLocale()#</cfoutput>? <p>Answer: <cfoutput>#LSIsDate(FORM.myValue)#</cfoutput> </cfif> <p><form action = "LSIsDate.cfm"> <p>Select a locale for which you would like to check a date value: <!--- check the current locale for server ---> <cfset serverLocale = GetLocale()> Chapter 3: ColdFusion Functions...
  • Page 759 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 ;...
  • Page 760 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 •...
  • Page 761 Character Meaning 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 space before positive number; minus sign before negative number. Separates every third decimal place with a comma (or locale-appropriate symbol).
  • Page 762 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...
  • Page 763 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,...
  • Page 764 For a list of the locale-specific formats used to parse the currency, see LSCurrencyFormat Example <h3>LSParseCurrency Example</h3> <p>LSParseCurrency coverts a locale-specific currency string to a number. Attempts conversion through each of the three default currency formats. <!--- loop through a list of locales; show currency values for 123,456 units - -->...
  • Page 765 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 ;...
  • Page 766 Format Example 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 Valid dates are in the range 100 AD–9999 AD.
  • Page 767 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,...
  • Page 768 <cfoutput><p>Current Locale: <b><i>#locale#</i></b><br> <cfset localCurrency = LSEuroCurrencyFormat(123456, "local")> Value in local currency: #localCurrency#<br> Parsed using LSParseEuroCurrency: #LSParseEuroCurrency(localCurrency)#<br> <cfset IntlCurrency = LSEuroCurrencyFormat(123456, "international")> Value with International currency formatting: #IntlCurrency#<br> Parsed using LSParseEuroCurrency: #LSParseEuroCurrency(IntlCurrency)#<br> <cfset Currency = LSEuroCurrencyFormat(123456, "none")> Value with no currency formatting: #currency#<br> Parsed using LSParseEuroCurrency: #LSParseEuroCurrency(Currency)#<br>...
  • Page 769 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 ;...
  • Page 770 #LSNumberFormat(1234.5678, "+_________.___")#<br> #LSNumberFormat(1234.5678, "-_________.___")#<br> The actual number: #LSParseNumber(LSNumberFormat(1234.5678, "_________"))#<br> <hr noshade> </cfoutput> </cfloop> Chapter 3: ColdFusion Functions...
  • Page 771 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 ;...
  • Page 772 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) •...
  • Page 773 <cfoutput><p><B><I>#locale#</I></B><br> #LSTimeFormat(Now())#<br> #LSTimeFormat(Now(), ‘hh:mm:ss’)#<br> #LSTimeFormat(Now(), ‘hh:mm:sst’)#<br> #LSTimeFormat(Now(), ‘hh:mm:sstt’)#<br> #LSTimeFormat(Now(), ‘HH:mm:ss’)#<br> <hr noshade> </cfoutput> </cfloop> LSTimeFormat...
  • Page 774 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 <h3>LTrim Example</h3>...
  • Page 775 Description Determines the greater of two numbers. Returns The greater of two numbers. Category Mathematical functions Function syntax Max(number1, number2) See also Parameters Parameter Description number1, number2 Numbers Example <h3>Max Example</h3> <cfif IsDefined("FORM.myNum1")> <cfif IsNumeric(FORM.myNum1) and IsNumeric(FORM.myNum2)> <p>The maximum of the two numbers is <cfoutput>#Max(FORM.myNum1, FORM.myNum2)#</cfoutput>...
  • Page 776 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 Right Parameters Parameter Description string A string or a variable that contains one. Must be single-quotation mark or double- quotation mark delimited.
  • Page 777 </cfif> </cfif> <form action="<cfoutput>#CGI.ScriptName#</cfoutput>" method="POST"> <p>Type in some text<br /> <input type="Text" name="myText"></p> <p>Enter a starting position (from the beginning of the entered text)<br /> <input name="startPos" type="text" size="1"></p> <p>How many characters do you want to show? <select name="RemoveChars"> <option value="1">1 <option value="3"...
  • Page 778 Description Determines the lesser of two numbers. Returns The lesser of two numbers. Category Mathematical functions Function syntax Min(number1, number2) See also Parameters Parameter Description number1, number2 Numbers Example <h3>Min Example</h3> <cfif IsDefined("FORM.myNum1")> <cfif IsNumeric(FORM.myNum1) and IsNumeric(FORM.myNum2)> <p>The maximum of the two numbers is <cfoutput>#Max(FORM.myNum1, FORM.myNum2)#</cfoutput>...
  • Page 779 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.
  • Page 780 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.
  • Page 781 MonthAsString Description Determines the name of the month that corresponds to month_number. Returns A string; the name of the specified month, in the current locale. Category Date and time functions, String functions Function syntax MonthAsString(month_number) See also DatePart Month Quarter Parameters Parameter Description...
  • Page 782 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 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...
  • Page 783 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. •...
  • Page 784 Mask character Meaning Separates every third decimal place with a comma. Left-justifies or center-justifies number within width of mask column. First character of mask must be L or C. The default value is right-justified. Puts a dollar sign before formatted number. First character of mask must be the dollar sign ($).
  • Page 785 Number Mask Result 3.21 C(__^)__ "( 3.21) " 3.21 C__(^)__ " (3.21) " 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.
  • Page 786 ParagraphFormat Description Replaces characters in a string: • Single newline characters (CR/LF sequences) with spaces • Double newline characters with HTML paragraph tags (<p>) Returns A copy of the string, with characters converted. Category Display and formatting functions, String functions Function syntax ParagraphFormat(string) See also...
  • Page 787 ParameterExists Description This function is deprecated. Use the function. IsDefined 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...
  • Page 788 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 function.) LSParseDateTime 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...
  • Page 789 <h3>The expression <cfoutput>#DE(form.theTestValue)#</cfoutput> is not a valid date</h3> </cfif> </cfif> <form action="#CGI.ScriptName#" method="POST"> <p>Enter an expression, and discover if it can be evaluated to a date value. <input type="Text" name="TheTestValue" value="<CFOUTPUT>#DateFormat(Now())# #TimeFormat(Now())#</CFOUTPUT>"> <input type="Submit" value="Parse the Date" name=""> </form> ParseDateTime...
  • Page 790 Description Gets the mathematical constant , accurate to 15 digits. Returns The number 3.14159265358979. Category Mathematical functions Function syntax Pi() See also ASin Example <h3>Pi Example</h3> <!--- By default, ColdFusion displays only 11 significant digits. Use NumberFormat to display all 15. ---> The Pi function Returns the number <cfoutput>...
  • Page 791 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, array- variable, and structure-variable references within a tag body or block.
  • Page 792 You code this function correctly as follows: <cfquery sql = "select * from foo where bar in (#preserveSingleQuotes(list0)#)"> This function ensures that ColdFusion evaluates the code as follows: '1', '2', '3' Example <h3>PreserveSingleQuotes Example</h3><p>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.
  • Page 793 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.
  • Page 794 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...
  • Page 795 QueryAddColumn query. This function is useful for generating a query object from the arrays of output parameters that Oracle stored procedures can generate. Macromedia recommends that you use the optional parameter. Without this datatype parameter, ColdFusion must try to determine the column’s data type when it uses the query object in a query of queries.
  • Page 796 <th align = "left">Health Food</th> </tr> <cfoutput query = "myQuery"> <tr> <td>#FastFood#</td> <td>#FineCuisine#</td> <td>#HealthFood#</td> </tr> </cfoutput> </table> Chapter 3: ColdFusion Functions...
  • Page 797 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 ; “Creating a record set with a QueryAddColumn QueryAddRow QuerySetCell QueryNew function”...
  • Page 798 QueryAddColumn function to add columns to the query. Macromedia recommends that you use the optional parameter. Without this columntypelist parameter, ColdFusion must try to determine data types when it uses the query object in a query of queries.
  • Page 799 Example The following example uses the function to create an empty query with three columns. QueryNew It populates two rows of the query and displays the contents of the query object and its metadata. <!--- Create a new three-column query, specifying the column data types ---> <cfset myQuery = QueryNew("Name, Time, Advanced", "VarChar, Time, Bit")>...
  • Page 800 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 ;...
  • Page 801 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,...
  • Page 802 Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section (except the default algorithm). The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.
  • Page 803 Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section (except the default algorithm). The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.
  • Page 804 Example The following example calls the function to seed the random number generator and Randomize generates 10 random numbers. To show the effect of the seed, submit the form with the same value multiple times. <h3>Randomize Example</h3> <!--- Do the following only if the form has been submitted. ---> <cfif IsDefined("Form.myRandomInt")>...
  • Page 805 Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section (except the default algorithm). The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.
  • Page 806 Example The following example contains a form that requires random number range values, and lets you optionally specify a random number seed value. It uses controls and attributes to specify a cfform default range, ensure that the range fields have values, and validate that the field values are in a specified integer range.
  • Page 807 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 ColdFusion MX Developer’s Guide. Returns Depends on the value of the parameter:...
  • Page 808 Parameter Description start Optional. A positive integer, or a variable that contains one. Position in the string at which to start search. The default value is 1. returnsubexpressions Optional. Boolean. Whether to return substrings of reg_expression, in arrays named • True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match.
  • Page 809 <p>The first call to REFind to search this string is: <b>REFind("[A-Za-z]+",testString,1,"TRUE")</b></p> <p>This function returns a structure that contains two arrays: pos and len.</p> <p>To create this structure you can use a CFSET statement, for example: </p> &lt;CFSET st = REFind("[[:alpha:]]",testString,1,"TRUE")&gt; <cfset st = REFind("[[:alpha:]]",testString,1,"TRUE")>...
  • Page 810 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 ColdFusion MX Developer’s Guide. Returns Depends on the value of the parameter:...
  • Page 811 Parameter Description start Optional. A positive integer or a variable that contains one. Position at which to start search. The default value is 1. returnsubexpressions Optional. Boolean. Whether to return substrings of reg_expression, in arrays named • True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match.
  • Page 812 <p>The first call to REFindNoCase to search this string is: <b>REFindNoCase("[[:alpha:]]+",testString,1,"True")</b></p> <p>This function returns a structure that contains two arrays: pos and len.</p> <p>To create this structure you can use a CFSET statement, for example:</p> &lt;CFSET st = REFindNoCase("[[:alpha:]]+",testString,1,"True")&gt; <cfset st = REFindNoCase("[[:alpha:]]+",testString,1,"True")> <p>...
  • Page 813 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 function CreateObject tag.
  • Page 814 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 Parameters Parameter Description...
  • Page 815 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.
  • Page 816 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...
  • Page 817 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...
  • Page 818 <h3>Replacelist Example Two</h3> <cfset stringtoreplace = "The quick brown fox jumped over the lazy dog."> <cfoutput> #ReplaceList(stringtoreplace,"dog,brown,fox,black", "cow,black,ferret,white")# </cfoutput> Chapter 3: ColdFusion Functions...
  • Page 819 ReplaceNoCase Description Replaces occurrences of substring1 with substring2, in the specified scope. The search is case- insensitive. 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...
  • Page 820 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 parameter is set to , returns a string with the first occurrence of the regular scope expression replaced by the value of substring.
  • Page 821 Usage For details on using regular expressions, see Chapter 7, “Using Regular Expressions in Functions,” in ColdFusion MX Developer’s Guide. Example <p>The REReplace function returns <i>string</i> with a regular expression replaced with <i>substring</i> in the specified scope. Case-sensitive search. <p>REReplace("CABARET","C|B","G","ALL"): <cfoutput>#REReplace("CABARET","C|B","G","ALL")#</cfoutput>...
  • Page 822 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 • : returns a string with the first occurrence of the regular expression replaced scope = "one" by the value of substring.
  • Page 823 <cfoutput>#REReplaceNoCase("cabaret","C|B","G","ALL")#</cfoutput> <p>REReplaceNoCase("cabaret","[A-Z]","G","ALL"): <cfoutput>#REReplaceNoCase("cabaret","[A-Z]","G","ALL")#</cfoutput> <p>REReplaceNoCase("I LOVE JELLIES","jell(y|ies)","cookies"): <cfoutput>#REReplaceNoCase("I LOVE JELLIES","jell(y|ies)","cookies")# </cfoutput> <p>REReplaceNoCase("I LOVE JELLY","jell(y|ies)","cookies"): <cfoutput>#REReplaceNoCase("I LOVE JELLY","jell(y|ies)","cookies")# </cfoutput> REReplaceNoCase...
  • Page 824 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...
  • Page 825 Right Description Gets a specified number of characters from a string, beginning at the right. Returns the specified number of characters from the end (or right side) of the specified string. Returns • If the length of the string is greater than or equal to , the rightmost characters of count...
  • Page 826 </cfoutput> </cfif> <cfelse> <p style="color: red; font-weight: bold">Please enter a string of more than 0 (zero) characters.</p> </cfif> </cfif> <form action="<cfoutput>#CGI.ScriptName#</cfoutput>" method="POST"> <p>Type in some text<br /> <input type="Text" name="myText"></p> <p>How many characters from the right do you want to show? <select name="RemoveChars">...
  • Page 827 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.
  • Page 828 Round Description Rounds a number to the closest integer that is larger than the input parameter. Returns An integer. Category Mathematical functions Function syntax Round(number) See also Ceiling Parameters Parameter Description number Number to round Usage Use this function to round a number. This function rounds numbers that end with .5 up to the nearest integer.
  • Page 829 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 <h3>RTrim Example</h3>...
  • Page 830 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.
  • Page 831 SendGatewayMessage Description Sends an outgoing message through a ColdFusion MX event gateway. Returns String. The value returned depends on the gateway type. Category Extensibility functions Function syntax SendGatewayMessage(gatewayID, data) See also “IM gateway message sending commands”, “SMS Gateway CFEvent GetGatewayHelper structure and commands”, “CFML event gateway SendGatewayMessage data...
  • Page 832 Gateway type Return values If the gateway is in asynchronous mode, returns the empty string immediately. If the gateway is in synchronous mode, the function waits for the gateway to return a response. If the message was succesfully sent to the short message service center (SMSC), returns the message ID from the SMSC.
  • Page 833 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,...
  • Page 834 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. This function resets URL and Form variables, so you should call it before using these variables (typically, in the Application.cfm page or Application.cfc file).
  • Page 835 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,...
  • Page 836 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 ColdFusion determines the locale value as follows:...
  • Page 837 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...
  • Page 838 <hr size = "2" color = "red"> <p>Timeout value should be greater than zero in order to provide time for user response.</p> <hr size = "2" color = "red"> </cfif> <cfelse> <p>The timeout value in your initialization file is already <cfoutput>#MyTimeout#</cfoutput>.</p>...
  • Page 839 SetVariable Description This function is no longer required in well-formed ColdFusion pages. Sets a variable in the parameter to the value of the parameter. name value Returns The new value of the variable. Category Dynamic evaluation functions Function syntax SetVariable(name, value) See also DE, Evaluate, Parameters...
  • Page 840 <cfset varNameValue = Evaluate(myName)> <cfoutput> <p>Your variable, #varName# <p>The value of #varName# is #varNameValue# </cfoutput> </cfif> Chapter 3: ColdFusion Functions...
  • Page 841 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 Parameters Parameter Description number A number Example <h3>Sgn Example</h3>...
  • Page 842 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 ACos Parameters Parameter Description number Angle, in radians for which to calculate the sine. Usage The range of the result is -1 to 1.
  • Page 843 </cfif> </cfif> <form action = "#CGI.script_name#" method="post"> Enter an angle in degrees to get its sine: <br><input type = "Text" name = "sinNum" size = "15"> <br><br> <input type = "Submit" name = "">&nbsp;&nbsp; <input type = "RESET" </form>...
  • Page 844 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...
  • Page 845 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...
  • Page 846 Description Calculates the square root of a number. Returns Number; square root of number. Category Mathematical functions Function syntax Sqr(number) See also Parameters Parameter Description number A positive integer or a variable that contains one. Number whose square root to get. Usage The value in must be greater than or equal to 0.
  • Page 847 StripCR Description Deletes return characters from a string. Returns A copy of string, after removing return characters. Category Display and formatting 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 tags) HTML display of data entered in...
  • Page 848 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,” in ColdFusion MX Developer’s Guide History ColdFusion MX: Changed behavior: this function can be used on XML objects.
  • Page 849 <cfset addrCLK.city="Watertown"> <cfset addrCLK.state="MA"> <cfset addrCLK.zip="02472"> <!---- Create a Person structure ---> <cfset personCLK=StructNew()> <cfset personCLK.name=#nameCLK#> <cfset personCLK.addr=#addrCLK#> <!--- Display the contents of the person struct before the Append ---> <p> The person struct <b>before</b> the Append call:<br> <cfloop collection=#personCLK# item="myItem"> <cfoutput>...
  • Page 850 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,” in ColdFusion MX Developer’s Guide History ColdFusion MX: Changed behavior: this function can be used on XML objects.
  • Page 851 StructInsert(employee, "lastname", Form.lastname); StructInsert(employee, "email", Form.email); StructInsert(employee, "phone", Form.phone); StructInsert(employee, "department", Form.department); </cfscript> </cfoutput> <!--- Call the custom tag that adds employees ---> <cf_addemployee empinfo = "#employee#"> <cfscript>StructClear(employee);</cfscript> </cfif> StructClear...
  • Page 852 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.
  • Page 853 The following table shows how variables are assigned: Variable type Assigned by structure.any_simple_value Value Boolean Binary Base64 structure.array Value structure.nested_structure Reference structure.object Reference structure.query Reference Example <!--- This code shows assignment by-value and by-reference. ---> // This script creates a structure that StructCopy copies by value. <br> <cfscript>...
  • Page 854 <hr> <b>Modified Original Values</b><br> <cfoutput> // Simple values <br> s.number = #s.number#<br> s.string = #s.string#<br> // Array value <br> s.array[1][1] = #s.array[1][1]#<br> s.array[1][2] = #s.array[1][2]#<br> </cfoutput> <hr> <b>Copied structure values should be the same as the original.</b><br> <cfoutput> // Simple values <br> copied.number = #copied.number#<br>...
  • Page 855 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)"; </cfscript> <hr> <b>Modified Original Values</b><br> <cfoutput> // Simple values <br> s.nested.number = #s.nested.number#<br> s.nested.string = #s.nested.string#<br> // Array value <br> s.nested.array[1][1] = #s.nested.array[1][1]#<br> s.nested.array[1][2] = #s.nested.array[1][2]#<br>...
  • Page 856 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 857 </cfquery> </cfif> <cfoutput><hr>Employee Add Complete <p>#StructCount(attributes.EMPINFO)# columns added.</cfoutput> </cfcase> </cfswitch> ---> StructCount...
  • Page 858 StructDelete Description Removes an element from a structure. Returns Boolean value. The value depends on the parameter value. indicatenotexisting Category Structure functions Function syntax StructDelete(structure, key [, indicatenotexisting ]) See also Structure functions; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 859 StructInsert(employee, "phone", phone); StructInsert(employee, "department", department); </CFScript> Before deletion, employee structure looks like this: <cfdump var="#employee#"> <br> <cfset rc = StructDelete(employee, "#form.field#", "True")> <cfoutput> Did I delete the field "#form.field#"? The code indicates: #rc#<br> The structure now looks like this:<br> <cfdump var="#employee#">...
  • Page 860 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;...
  • Page 861 </cfquery> </cfif> <cfoutput><hr>Employee Add Complete</cfoutput> </cfcase> </cfswitch> ---> StructFind...
  • Page 862 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...
  • Page 863 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 parameter. value Returns An array that contains structures with values that match the search key value. If none are found, returns an array of size 0.
  • Page 864 StructGet Description Gets a structure(s) from a specified path. Returns An alias to the variable in the pathDesired parameter. If necessary, creates structures or StructGet arrays to make pathDesired a valid variable "path." Category Structure functions Function syntax StructGet(pathDesired) See also Structure functions;...
  • Page 865 <cfif NOT Isdefined("dog.myscope.test.foo")> Dog.Myscope.Test.Foo is not defined<br> </cfif> <cfoutput> #dog.myscope.test.foo#<br> </cfoutput> <cfset test = StructGet( "request.myscope[1].test" )> <cfset test.foo = 2> <cfoutput> #request.myscope[1].test.foo#<br> </cfoutput> <cfset test = StructGet( "request.myscope[1].test[2]" )> <cfset test.foo = 3> <cfoutput> #request.myscope[1].test[2].foo#<br> </cfoutput> StructGet...
  • Page 866 StructInsert Description Inserts a key-value pair into a structure. Returns True, upon successful completion. If does not exist, or if exists and structure , ColdFusion throws an exception. allowoverwrite = "False" Category Structure functions Function syntax StructInsert(structure, key, value [, allowoverwrite ]) See also Structure functions;...
  • Page 867 StructInsert(employee, "lastname", FORM.lastname); StructInsert(employee, "email", FORM.email); StructInsert(employee, "phone", FORM.phone); StructInsert(employee, "department", FORM.department); </CFScript> <p>First name is #StructFind(employee, "firstname")#</p> <p>Last name is #StructFind(employee, "lastname")#</p> <p>EMail is #StructFind(employee, "email")#</p> <p>Phone is #StructFind(employee, "phone")#</p> <p>Department is #StructFind(employee, "department")#</p> </cfoutput> <!--- Call the custom tag that adds employees ---> <CF_ADDEMPLOYEE EMPINFO = "#employee#">...
  • Page 868 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 869 </cfoutput> </cfquery> </cfif> <cfoutput><hr>Employee Add Complete</cfoutput> </cfcase> </cfswitch> StructIsEmpty...
  • Page 870 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 871 <hr size = "2" color = "#0000A0"> <form action = "structkeyarray.cfm"> <table cellspacing = "2" cellpadding = "2" border = "0"> <tr> <td>First Name:</td> <td><input name = "firstname" type = "text" value = "" hspace = "30" maxlength = "30"></td> </tr>...
  • Page 872 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;...
  • Page 873 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 874 <body> <h3>StructKeyList Function</h3> <h3>Listing the Keys in the Employees Structure</h3> <p>This example uses StructNew function to create structure "employee" that supplies employee information. The fields are filled with the contents of the following form.</p> <p>After you enter employee information into structure, example uses <b>StructKeyList</b>...
  • Page 875 StructNew Description Creates a structure. Returns A structure. Category Structure functions Function syntax StructNew() See also Structure functions; “Structure functions” in Chapter 5, “Using Arrays and Structures,” in ColdFusion MX Developer’s Guide Parameters None Example <!--- Shows StructNew. Calls CF_ADDEMPLOYEE, which uses the | addemployee.cfm file to add employee record to database.
  • Page 876 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...
  • Page 877 employee = StructNew() ; employee["salary"] = salary ; // employee.salary = salary ; employees["employee#i#"] = employee ; departments["department#i#"] = StructNew() ; departments["department#i#"].boss = employee ; </cfscript> <cfoutput> <p>list of employees based on the salary (text search): <br> 1) #ArrayToList( StructSort( salaries ) )#<br> 2) #ArrayToList( StructSort( salaries, "text", "ASC"...
  • Page 878 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; “Modifying a ColdFusion XML object” in Chapter 35, “Using XML and WDDX,”...
  • Page 879 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 ACos ASin Parameters Parameter Description number Angle, in radians, for which to calculate the tangent. Usage To convert degrees to radians, multiply degrees by /180.
  • Page 880 </cfif> </cfif> <form action = "#CGI.script_name#" method="post"> Enter an angle in degrees to get its tangent: <br><input type = "Text" name = "tanNum" size = "15"> <br><br> <input type = "Submit" name = "">&nbsp;&nbsp; <input type = "RESET" </form> Chapter 3: ColdFusion Functions...
  • Page 881 TimeFormat Description Formats a time value using U.S. 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...
  • Page 882 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 functions to DateFormat TimeFormat format date and time values from queries.
  • Page 883 TimeFormat function. For example: dateformat(now(), "yyyy-mm-dd")#T#TimeFormat(now(), "HH:mm:ss") produces:</p> <cfoutput>#dateformat(now(), "yyyy-mm-dd")#T#TimeFormat(now(), "HH:mm:ss")#</ cfoutput> </body> TimeFormat...
  • Page 884 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. Returns The Base64 representation of a string or binary object. Category Conversion functions,...
  • Page 885 Usage Macromedia recommends that you use the function to convert binary data to BinaryEncode Base64-encoded data in all new applications. <h3>ToBase64 Example</h3> <!--- Initialize data. ----> <cfset charData = ""> <!--- Create string of ASCII characters (32-255); concatenate them --->...
  • Page 886 Description string_in_Base64 A string in Base64 format to convert to binary. Usage Macromedia recommends that you use the function to convert Base64 encoded BinaryDecode data to binary data in all new applications. If you pass a binary value to this function, it returns the input value.
  • Page 887 <!--- Convert string to binary. ----> <cfset binaryData = toBinary(data64)> <!--- Convert binary back to Base64. ---> <cfset another64 = toBase64(binaryData)> <!---- Compare another64 with data64 to ensure that they are equal. ----> <cfif another64 eq data64> <h3>Base64 representation of binary data is identical to the Base64 representation of string data.</h3>...
  • Page 888 ToScript Description Creates a JavaScript or ActionScript expression that assigns the value of a ColdFusion variable to a JavaScript or ActionScript variable. This function can convert ColdFusion strings, numbers, arrays, structures, and queries to JavaScript or ActionScript syntax that defines equivalent variables and values.
  • Page 889 Usage To use a ColdFusion variable in JavaScript or ActionScript, the function must be in a ToScript region and be surrounded by number signs (#). For example, the following code uses cfoutput function to convert a ColdFusion variable to a JavaScript variable: ToScript <cfset thisString="hello world">...
  • Page 890 An ActionScript-style array does not require you to include the wddx.js file, and creates a variable that you can use in ActionScript on a Flash format form, for example, in an attribute. onChange If the parameter is False, setting to True causes to use the outputformat ASFormat...
  • Page 891 document.write("myArray[" + i + "]: " + jsArray[i] + "<br>"); </script> <br> <h3>Converting a query</h3> This section converts the following query object to both WDDX format and ActionScript type Javascript objects.<br> <!--- Query a database ---> <cfquery name="thisQuery" datasource="cfdocexamples"> SELECT FirstName,LastName FROM employee WHERE FirstName = 'John' </cfquery>...
  • Page 892 ToString Description Converts a value to a string. Returns A string. Category Conversion functions, String functions Function syntax ToString(value[, encoding]) See also ; Chapter 35, “Using XML and WDDX,” in ColdFusion ToBase64 ToBinary CharsetEncode MX Developer’s Guide History ColdFusion MX: •...
  • Page 893 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 also convert an XML document object to a string XML representation. Macromedia recommends that you use the function to convert binary data to a CharsetEncode string.
  • Page 894 <cfset dataBinary = toBinary(data64)> <!---- Create the string representation of the binary data. -----> <cfset dataString = ToString(dataBinary)> <p>The following is the string representation of the binary data.<br> <cfoutput>#dataString#</cfoutput></p> Chapter 3: ColdFusion Functions...
  • Page 895 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 <h3>Trim Example</h3>...
  • Page 896 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 <h3>UCase Example</h3>...
  • Page 897 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 ; “Tags and functions for globalizing” in Chapter 17, “Developing Globalized URLEncodedFormat Applications,” in ColdFusion MX Developer’s Guide ColdFusion MX 6.1: Changed the default charset: the default charset is the character encoding of the URL scope.
  • Page 898 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 space is encoded with a plus sign. Query strings in HTTP are always URL-encoded. Example This example creates, encodes, and decodes a string that contains ASCII character codes: <cfscript>...
  • Page 899 URLEncodedFormat Description Generates a URL-encoded string. For example, it replaces spaces with , and non- alphanumeric 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.
  • Page 900 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 space is encoded with a plus sign. Query strings in HTTP are always URL-encoded. Example <h3>URLEncodedFormat Example</h3>...
  • Page 901 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.
  • Page 902 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: •...
  • Page 903 value = "Is the beginning numeric?" name = ""> </form>...
  • Page 904 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 List functions, Query functions Function syntax ValueList(query.column [, delimiter ]) See also QuotedValueList...
  • Page 905 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...
  • Page 906 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...
  • Page 907 WriteOutput Description Appends text to the page-output stream. This function writes to the page-output stream regardless of conditions established by the tag. cfsetting Category Other functions, System functions Function syntax WriteOutput(string Parameters Parameter Description string A string or a variable that contains one Usage Within the tags, this function does not output to the current page;...
  • Page 908 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 XML functions Function syntax XmlChildPos(elem, childName, N) See also ;...
  • Page 909 <first>Laura</first> <last>Ingalls</last> </name> </employee> </cfxml> <!--- Find the second Status child of the first employee.name element ---> <cfscript> elempos=XMLChildPos(xmlobject.employee.name[1], "Status", 2); ArrayDeleteAt(xmlobject.employee.name[1].XmlChildren, elempos); </cfscript> <!--- Dump the resulting document object to confirm the deletion ---> <cfdump var="#xmlobject#"> XmlChildPos...
  • Page 910 XmlElemNew Description Creates an XML document object element. Returns An XML document object element. Category XML functions Function syntax XmlElemNew(xmlObj[, namespace], childName) See also ; Chapter 35, “Using XML and cfxml IsXmlElem XmlChildPos XmlFormat XmlNew XmlParse WDDX” in ColdFusion MX Developer’s Guide History ColdFusion MX 7: Added the parameter.
  • Page 911 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 &"."; </cfscript> <cfdump var=#MyDoc#> XmlElemNew...
  • Page 912 XmlFormat Description Escapes special XML characters in a string so that the string can be used as text in XML. Returns A copy of the parameter that is safe to use as text in XML. string Category String functions, XML functions Function syntax XmlFormat(string) See also...
  • Page 913 <someXML> <someElement someAttribute="#XmlFormat("'a quoted value'")#"> #XmlFormat("Body of element with <, >, "" and & goes here.")# </someElement> </someXML> </cfoutput> XmlFormat...
  • Page 914 XmlGetNodeType Description Determines the type of an XML document object node. Returns A string identifying the XML node type. The following values are valid: ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE PROCESSING_INSTRUCTION_NODE TEXT_NODE If the argument is not a document object node, the function generates an error. Category XML functions Function syntax...
  • Page 915 <items> <item id="43"> <!-- This item is coded to show several node types --> <![CDATA["Our Best" hammer & chisel set!!!]]> Imported from France <quantity>1</quantity> <unitprice>15.95</unitprice> </item> </items> </order> </cfxml> <!--- Display the node types ---> <cfoutput> <h3>Node Types</h3> xmlobject: #XMLGetNodeType(xmlobject)#<br> xmlobject.order: #XMLGetNodeType(xmlobject.order)#<br>...
  • Page 916 XmlNew Description Creates an XML document object. Returns An empty XML document object. Category XML functions Function syntax XmlNew([caseSensitive]) See also ; Chapter 35, “Using XML cfxml IsXmlDoc ToString XmlFormat XmlParse XmlValidate and WDDX” in ColdFusion MX Developer’s Guide History ColdFusion MX: Added this function.
  • Page 917 Example The following example creates and displays a ColdFusion document object: <cfset testVar = True> <cfscript> 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;...
  • Page 918 XmlParse Description Converts XML text into an XML document object. Returns An XML document object. Category Conversion functions, XML functions Function syntax XmlParse(xmlText [[, caseSensitive ], validator]) See also cfxml IsXML ToString XmlFormat XmlNew XmlSearch XmlTransform XmlValidate Chapter 35, “Using XML and WDDX” in ColdFusion MX Developer’s Guide History ColdFusion MX 7: •...
  • Page 919 parameter value determines whether identifiers whose characters are of caseSensitive varying case, but are otherwise the same, refer to different components; for example: • If true, the element or attribute names “name” and “NAME” refer to different elements or attributes. •...
  • Page 920 <name>Standard paint thinner</name> <quantity>3</quantity> <unitprice>8.95</unitprice> </item> </items> </order> The custorder.dtd file is as follows: <!ELEMENT order (customer, items)> <!ATTLIST order id CDATA #REQUIRED> <!ELEMENT customer EMPTY> <!ATTLIST customer firstname CDATA #REQUIRED lastname CDATA #REQUIRED accountNum CDATA #REQUIRED> <!ELEMENT items (item+)> <!ELEMENT item (name, quantity, unitprice)>...
  • Page 921 XmlSearch Description Uses an XPath language expression to search an XML document object. Returns An array of XML object nodes that match the search criteria. Category XML functions Function syntax XmlSearch(xmlDoc, xPathString) See also ; Chapter 35, “Using XML and WDDX” cfxml IsXML XmlChildPos...
  • Page 922 <name EmpType="Contract"> <first>Laura</first> <last>Ingalls</last> </name> </employee> The CFML file contains the following lines: <cfscript> myxmldoc = XmlParse("C:\CFusionMX7\wwwroot\examples\employeesimple.xml"); selectedElements = XmlSearch(myxmldoc, "/employee/name/last"); for (i = 1; i LTE ArrayLen(selectedElements); i = i + 1) writeoutput(selectedElements[i].XmlText & "<br>"); </cfscript> Chapter 3: ColdFusion Functions...
  • Page 923 XmlTransform Description Applies an Extensible Stylesheet Language Transformation (XSLT) to XML. The XML can be in string format or an XML document object. Returns A string containing the results of applying the XSLT to the XML. Category Conversion functions, XML functions Function syntax XmlTransform(xml, xsl[, parameters]) See also...
  • Page 924 If the XSLT code contains include statements with relative paths, ColdFusion resolves them relative to the location of the XSLT file, or for an XSL string, the location of the current ColdFusion page. Example The following example converts an XML document that represents a customer order into an HTML document with the customer name and a table with the order items and quantities: The custorder.xml file that represents a customer order has the following lines: <?xml version="1.0"...
  • Page 925 </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> The CFML file has the following lines: <cffile action="read" file="C:\CFusionMX7\wwwroot\examples\custorder.xsl" variable="xmltrans"> <cfset xmldoc = XmlParse("C:\CFusionMX7\wwwroot\examples\custorder.xml")> <cfoutput>#XmlTransform(xmldoc, xmltrans)#</cfoutput> XmlTransform...
  • Page 926 XmlValidate Description Uses a Document Type Definition (DTD) or XML Schema to validate an XML text document or an XML document object. Returns The following validation structure: Field Description Errors An array containing any validator error messages. These messages indicate that the document does not conform to the DTD or Schema (is not valid).
  • Page 927 Usage If you specify a relative URL or filename in a parameter, ColdFusion uses the directory (or, for URLs, the virtual directory) that contains the current ColdFusion page as the path root. r parameter specifies a DTD or Schema to use to validate the document. If you validato omit the parameter, the XML document must contain one of the following: •...
  • Page 928 </item> </items> </order> The custorder.xsd file is as follows: <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="customer"> <xs:complexType> <xs:attribute name="firstname" type="xs:string" use="required"/> <xs:attribute name="lastname" type="xs:string" use="required"/> <xs:attribute name="accountNum" type="xs:string" use="required"/> </xs:complexType> </xs:element> <xs:element name="name" type="xs:string"/> <xs:element name="quantity" type="xs:string"/> <xs:element name="unitprice" type="xs:string"/> <xs:element name="item">...
  • Page 929 Did custorder.xml validate against custorder.xsd? #results.status#<br><br> </cfoutput> Dump of myResults structure returned by XMLValidate<br> <cfdump var="#myResults#"> XmlValidate...
  • Page 930 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.
  • Page 931 YesNoFormat Description Evaluates a number or Boolean value. Returns Yes, for a nonzero value; No for zero, , and Boolean values, and an empty string ( false "") Category Decision functions, Display and formatting functions Function syntax YesNoFormat(value) See also IsBinary IsNumeric Parameters...
  • Page 932 Chapter 3: ColdFusion Functions...
  • Page 933: Chapter 4: Coldfusion Mx Flash Form Style Reference

    CHAPTER 4 ColdFusion MX Flash Form Style Reference This chapter describes the styles that you can specify in Macromedia ColdFusion MX 7 forms tags when you display the form or form element in Flash format. Contents Styles valid for all controls ........... 934 Styles for cfform.
  • Page 934: Styles Valid For All Controls

    Styles valid for all controls The following styles are valid for all ColdFusion Flash format form tags except for cfformitem tags with the following attributes, which do not take attributes: type style • html • space • text These styles do not cause errors when used in all other tags. However, many styles do not have any effect when used in some tags.
  • Page 935 Style Description dropShadow Format: Boolean; controls the visibility of the component's drop shadow. The default value is false. This style must be used with borderStyle="solid". For drop shadows to appear on containers, set backgroundColor or backgroundImage. Otherwise, since the default background of a container is transparent, the shadow appears behind the container.
  • Page 936: Styles For Cfform

    Style Description themeColor Format: color; background color of a component. The possible values are: • haloGreen • haloBlue • haloOrange • haloSilver verticalGap Format: length; number of pixels between children in the vertical direction. Styles for cfform The following styles apply to the tag: cfform Style...
  • Page 937: Styles For Box-Style Cfformgroup Elements

    Style Description marginTop Format: length; number of pixels between the container`s top border and its content area. The default value is 0. verticalGap Format: length; number of pixels between children in the vertical direction. The default value is 6. Styles for box-style cfformgroup elements The following styles apply to the tag with the following attributes.
  • Page 938: Styles For Cfformgroup With Accordion Type Attribute

    Style Description dividerColor Format: color; color of the dividers in their up state. The default value is ##AAAAAA. dividerThickness Format: length; thickness in pixels of the dividers. The default value is 4. Styles specific to cfformgroup with panel type attribute The following additional styles apply to the tag with cfformgroup...
  • Page 939: Styles For Cfformgroup With Tabnavigator Type Attribute

    Style Description openDuration Format: time; duration, in milliseconds, of the transition from one child panel to another. The default value is 250. verticalGap Format: length; number of pixels between children in the vertical direction. The default value is -1. Styles for cfformgroup with tabnavigator type attribute The following styles apply to the tag with the cfformgroup...
  • Page 940: Styles For Cfinput With Radiobutton, Checkbox, Button, Image, Or Submit Type Attributes

    Style Description shadowColor Format: color; shadow color of the line, as follows:. • If is 1, does nothing. strokeWidth • If is 2 (default), the color of the bottom line. strokeWidth • If is greater than 2, the color of the bottom and right strokeWidth edges of the rectangle.
  • Page 941: Styles For Cftextarea Tag And Cfinput With Text, Password, Or Hidden Type Attributes

    Style Description symbolBackground Format: color; background color of check boxes and radio buttons PressedColor when pressed. The default value is ##FFFFFF (white). symbolColor Format: color; the check mark of a check box or the dot of a radio button. The default value is ##000000 (black). symbolDisabledColor Format: color;...
  • Page 942: Styles For Cfselect With Size Attribute Value Greater Than 1

    Styles for cfselect with size attribute value greater than 1 The following styles apply to the tag when the attribute is greater than 1; that is, cfselect size if the control is a list box that displays two or more options at a time: Style Description alternatingRowColors...
  • Page 943: Styles For The Cfgrid Tag

    Styles for the cfgrid tag The following styles apply to the tag: cfgrid Style Description horizontalAlign Horizontal alignment of children in the container. The default value is left. Possible values are left, center, and right. horizontalGap Number of pixels between children in the horizontal direction. The default value is 8.
  • Page 944 Chapter 4: ColdFusion MX Flash Form Style Reference...
  • Page 945: Chapter 5: Application.cfc Reference

    CHAPTER 5 Application.CFC Reference This chapter describes the methods that you implement in Application.cfc to handle Macromedia ColdFusion MX 7 application events. It also describes the variables that you set in the CFC to configure application characteristics. Contents Application variables ............945 Method summary .
  • Page 946: Method Summary

    The application first starts: the first request for a page is processed or the onApplicationStart first CFC method is invoked by an event gateway instance, or a web services or Macromedia Flash Remoting CFC. An exception occurs that is not caught by a try/catch block. onError method finishes.
  • Page 947 Method name Method runs when A request starts onRequestStart A session ends onSessionEnd A session starts onSessionStart All parameters to these methods are positional. You can use any names for these parameters. When a request executes, ColdFusion MX runs the CFC methods in the following order: (if not run before for this application) onApplicationStart (if not run before for this session)
  • Page 948 onApplicationEnd Description Runs when an application times out or the server is shutting down. Syntax <cffunction name="onApplicationEnd" returnType="void"> <cfargument name="ApplicationScope" required=true/> </cffunction> See also , “Managing the application with Application.cfc” in onApplicationStart Method summary Chapter 13, “Designing and Optimizing a ColdFusion Application,” in ColdFusion MX Developer’s Guide Parameters ColdFusion MX passes the following parameters to the method:...
  • Page 949 onApplicationStart Description Runs when ColdFusion MX receives the first request for a page in the application. Syntax <cffunction name="onApplicationStart" returnType="boolean"> <cfreturn Boolean> </cffunction> See also , “Managing the application with Application.cfc” in onApplicationEnd Method summary Chapter 13, “Designing and Optimizing a ColdFusion Application,” in Chapter 5, “Application.CFC Reference,”...
  • Page 950 <cfoutput> This application encountered an error<br> Please contact support. </cfoutput> <cflog file="#This.Name#" type="error" text="cfdocexamples DB not available. message: #cfcatch.message# Detail: #cfcatch.detail# Native Error: #cfcatch.NativeErrorCode#" > <cfreturn False> </cfcatch> </cftry> <cflog file="#This.Name#" type="Information" text="Application Started"> <!--- You do not have to lock code in the onApplicationStart method that sets Application scope variables.
  • Page 951 onError Description Runs when an uncaught exception occurs in the application. Syntax <cffunction name="onError" returnType="void"> <cfargument name="Exception" required=true/> <cfargument name="EventName" type="String" required=true/> </cffunction> See also Method summary, “Handling errors in Application.cfc” in ColdFusion MX Developer’s Guide Parameters ColdFusion MX passes the following parameters to the method: Parameter Description Exception...
  • Page 952 If an exception occurs while processing the method, or if the method uses a onError onError tag, the ColdFusion MX standard error handling mechanisms handle the exception. cfthrow These mechanisms include: any error handlers specified by tags in the Application.cfc cferror initialization code, the site-wide error handler specified in the ColdFusion MX Administrator, and ColdFusion MX default error page.
  • Page 953 onRequest Description Runs when a request starts, after the event handler. If you implement this onRequestStart method, it must explicitly call the requested page to process it. Syntax <cffunction name="onRequest" returnType="void"> <cfargument name="targetPage" type="String" required=true/> <cfinclude template="#Arguments.targetPage#"> </cffunction> See also Method summary, “Managing requests in Application.cfc”...
  • Page 954 • Code in this method that precedes the call to the target page can perform the same functions as method, and shares the Variables scope with the target page. onRequestStart • Code in this method that follows the call to the target page can perform the same functions as method, and shares the Variables scope with the target page.
  • Page 955 onRequestEnd Description Runs at the end of a request, after all other CFML code. Syntax <cffunction name="onRequestEnd" returnType="void"> <cfargument type="String" name="targetPage" required=true/> </cffunction> See also Method summary, “Managing requests in Application.cfc” in onRequestStart onRequest ColdFusion MX Developer’s Guide Parameters ColdFusion MX passes the following parameters to the method: Parameter Description targetPage...
  • Page 956 <cfinclude template="authuserfooter.cfm"> <cfelse> <cfinclude template="noauthuserfooter.cfm"> </cfif> </cffunction> A very simple authuserfooter.cfm page consists of the following code: <cfoutput> <h3>Thank you for shopping at our store, #theAuthUser#!</h3> </cfoutput> A very simple noauthuserfooter.cfm page consists of the following code: <cfoutput> <h3>Remember, only registered users get all our benefits!</h3> </cfoutput>...
  • Page 957 onRequestStart Description Runs when a request starts. Syntax <cffunction name="onRequestStart" returnType="boolean"> <cfargument type="String" name="targetPage" required=true/> <cfreturn Boolean> </cffunction> See also Method summary, “Managing requests in Application.cfc” in onRequest onRequestEnd ColdFusion MX Developer’s Guide Parameters ColdFusion MX passes the following parameters to the method: Parameters Description targetPage...
  • Page 958 <!--- Regular maintenance is done late at night. During those hours, tell people to come back later, and do not process the request further. ---> <cfscript> if ((Hour(now()) gt 1) and (Hour(now()) lt 3)) { WriteOutput("The system is undergoing periodic maintenance. Please return after 3:00 AM Eastern time.");...
  • Page 959 onSessionEnd Description Runs when a session ends. Syntax <cffunction name="onSessionEnd" returnType="void"> <cfargument name="SessionScope" required=True/> <cfargument name="ApplicationScope" required=False/> </cffunction> See also Method summary, “Managing sessions in Application.cfc” in ColdFusion MX onSessionStart Developer’s Guide Parameters ColdFusion MX passes the following parameters to the method: Parameter Description SessionScope...
  • Page 960 • You must use the parameter to access the Application scope. You cannot ApplicationScope reference the Application scope directly; for example, use Arguments.ApplicationScope.myVariable, not Application.myVariable. Use a named lock when you reference variables in the Application scope, as shown in the example. •...
  • Page 961 onSessionStart Description Runs when a session starts. Syntax <cffunction name="onSessionStart" returnType="void"> </cffunction> See also Method summary, “Managing sessions in Application.cfc” in ColdFusion MX onSessionEnd Developer’s Guide Returns This method does not return a value; do not use the tag. cfreturn Usage This method is useful for initializing Session scope data, such as a shopping cart, or setting session-specific Application scope variables, such as for tracking the number of active sessions.
  • Page 962 Chapter 5: Application.CFC Reference...
  • Page 963: Chapter 6: Coldfusion Mx Event Gateway Reference

    CHAPTER 6 ColdFusion MX Event Gateway Reference This chapter describes the Java interfaces available for building Macromedia ColdFusion MX 7 custom CFXs in Java. Contents Gateway development interfaces and classes ........963 CFML CFEvent structure .
  • Page 964 Gateway interface coldfusion.eventgateway.Gateway Interface for implementing ColdFusion MX event gateways. A class that implements this interface defines a ColdFusion MX event gateway type that you can use in ColdFusion MX applications. The class must implement the following methods: Signature Description The gateway constructor.
  • Page 965 Constructor Description Instantiates a gateway. Category Event Gateway Development Syntax public void gatewayName() public void gatewayName(String id) public void gatewayName(String id, String configFile) See also , “Class constructor” in Chapter 45, “Creating Custom Event Gateways” in setGatewayID ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 966 getGatewayID Description Returns the gateway ID that identifies the Gateway instance. Category Event Gateway Development Syntax public String getGatewayID() See also , “Providing Gateway class service and information routines” in Chapter 45, setGatewayID “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Usage This method returns a string value that is set by the method.
  • Page 967 getHelper Description Returns an instance of the gatewayHelper class, if any for the gateway type. Category Event Gateway Development Syntax public GatewayHelper getHelper() See also ; “Providing Gateway class service and information routines” in GatewayHelper interface Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns A coldfusion.eventgateway.GatewayHelper class instance, or null if the gateway does not have a GatewayHelper class.
  • Page 968 getStatus Description Returns the gateway status. Category Event Gateway Development Syntax public int getStatus() See also “Providing Gateway class service and information routines” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns An integer status value. The Gateway interface defines the following status constants: •...
  • Page 969 outgoingMessage Description Sends a message from ColdFusion to a message receiver. Category Event Gateway Development Syntax public String outgoingMessage(coldfusion.eventgateway.CFEvent message) See also “Responding to a ColdFusion function or listener CFC” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 970 retcode="failed"; else if (data.get("OriginatorID") != null && message != null) SocketServerThread st = ((SocketServerThread)socketRegistry.get(data.get("OriginatorID"))); if(st != null) st.writeOutput(message); else log.error("Cannot send outgoing message. OriginatorID '" + data.get("OriginatorID") + "' is not a valid socket id."); retcode="failed"; else log.error("Cannot send outgoing message. OriginatorID/MESSAGE is not available.");...
  • Page 971 restart Description Stops a gateway if it is running and starts it up. Category Event Gateway Development Syntax public void restart() See also start stop Usage In most cases, you implement this method as a call to the stop method followed by a start method, but you may be able to optimize the restart method based on the type of gateway.
  • Page 972 setCFCListeners Description Sets the array of listener CFCs that the gateway sends messages to. Category Event Gateway Development Syntax public void setCFCListeners(String[] listeners) See also , “Providing Gateway class service and information Constructor getGatewayID setCFCPath routines” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 973 setGatewayID Description Sets the gateway ID that uniquely identifies the Gateway instance. Category Event Gateway Development Syntax public void setGatewayID(String id) See also , “Providing Gateway class service and information routines” in Constructor getGatewayID Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 974 start Description starts a gateway running. Category Event Gateway Development Syntax public void start() See also , “The start method” in Chapter 45, “Creating Custom Event Gateways” in restart stop ColdFusion MX Developer’s Guide Usage Start a gateway by performing any required initialization. This method starts any listener thread or threads that monitor the gateway’s event source.
  • Page 975 stop Description Stops a gateway if it is running. Category Event Gateway Development Syntax public void stop() See also , “The stop method” in Chapter 45, “Creating Custom Event Gateways” in restart start ColdFusion MX Developer’s Guide Usage Stops a gateway by performing any required clean-up operations. This method stops any listener thread or threads that monitor the gateway’s event source and releases any other resources.
  • Page 976 GatewayHelper interface coldfusion.eventgateway.GatewayHelper ColdFusion MX includes a coldfusion.eventgateway.GatewayHelper Java marker interface, with no methods. Implement this interface to define a class that provides gateway-specific utility methods to the ColdFusion application or listener CFC. For example, an instant messaging event gateway might use a helper class to provide buddy list management methods to the application. The Gateway class must implement a method that returns the helper class, or null if getHelper...
  • Page 977 GatewayServices class coldfusion.eventgateway.GatewayServices The Gateway class uses the coldfusion.eventgateway.GatewayServices class to interact with the ColdFusion event gateway services. This class has the following methods: Signature Description GatewayServices getGatewayServices() Static method that returns the GatewayServices object. Sends a instance to ColdFusion for dispatching boolean addEvent(CFEvent CFEvent to a listener CFC.
  • Page 978 getGatewayServices Description Static method that returns the GatewayServices object. Gateway code can call this method at any time, if required. Category Event Gateway Development Syntax GatewayServices getGatewayServices() See also “GatewayServices class” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns The GatewayServices object.
  • Page 979 addEvent Description Sends a CFEvent instance to ColdFusion for dispatching to a listener CFC. Category Event Gateway Development Syntax boolean addEvent(CFEvent msg) See also , “Responding to incoming messages” in Chapter 45, getMaxQueueSize getMaxQueueSize “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 980 getLogger Description Returns a ColdFusion Logger object that the event gateway can use to log information in a file. Category Event Gateway Development Syntax coldfusion.eventgateway.Logger getLogger([String logfile]) See also , “Logging events and using log files” in Chapter 45, “Creating Custom Event Logger class Gateways”...
  • Page 981 getMaxQueueSize Description Returns the maximum size of the ColdFusion event queue, as set in the ColdFusion MX Administrator. Category Event Gateway Development Syntax int getMaxQueueSize() See also addEvent getQueueSize Returns The integer maximum number of messages that the gateway services queue can hold. Usage If the queue length reaches this value, the method will not add its message to the...
  • Page 982 getQueueSize Description Returns the current size of the ColdFusion event queue that handles all messages for all gateways. Category Event Gateway Development Syntax getQueueSize() See also addEvent getMaxQueueSize Returns The integer number of messages in the gateway message queue that are waiting to be delivered to CFCs.
  • Page 983 CFEvent class coldfusion.gateway.CFEvent The Gateway class sends and receives instances to communicate with the ColdFusion CFEvent listener CFC or application. The instances correspond to CFML CFEvent structures CFEvent that ColdFusion application listener CFC methods receive and contain the message structures that ColdFusion application code sends to the gateway.
  • Page 984 CFEvent Description CFEvent constructor. Category Event Gateway Development Syntax CFEvent(String gatewayID) See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, getGatewayID “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description gatewayID The ID of the gateway. This parameter indicates the source of the message and must be the value that is passed in the Gateway constructor or set using the Gateway method.
  • Page 985 getCFCMethod Description Gets the name of the CFC method that processes the message. Category Event Gateway Development Syntax String getCFCMethod() See also “CFML CFEvent structure” on page 1004, getCFCPath getCFCTimeout setCFCMethod “CFEvent class” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns For incoming messages, the name of the method that gateway services will call in the listener...
  • Page 986 getCFCPath Description Gets the path to the listener CFC that processes this message. Category Event Gateway Development Syntax String getCFCPath() See also “CFML CFEvent structure” on page 1004, getCFCMethod getCFCTimeout setCFCPath “CFEvent class” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns An absolute path to the application listener CFC that will process the event, as set by the...
  • Page 987 getCFCTimeout Description Gets the time-out, in seconds, for the listener CFC to process the event request. Category Event Gateway Development Syntax String getCFCTimeout() See also “CFML CFEvent structure” on page 1004, getCFCMethod getCFCPath setCFCTimeout “CFEvent class” in Chapter 45, “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns The listener CFC time-out, in seconds, as set by the...
  • Page 988 getData Description Returns the data Map that contains the message contents and other gateway-specific information. Category Event Gateway Development Syntax Map getData() See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, “Creating setData Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns The event data structure, or null.
  • Page 989 getGatewayID Description Returns the gateway ID field of the CFEvent object. Category Event Gateway Development Syntax String getGatewayID(CFEvent event) See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, “Creating CFEvent Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns The gateway ID of the CFEvent object, or null.
  • Page 990 getGatewayType Description Returns the gateway type field of the CFEvent object. Category Event Gateway Development Syntax String getGatewayType() See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, setGatewayType “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Returns The gateway type of the CFEvent object, or null.
  • Page 991 getOriginatorID Description Identifies the originator of an incoming message. Some gateway types also use this field for the destination of an outgoing message. Category Event Gateway Development Syntax String getOriginatorID() See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, setOriginatorID “Creating Custom Event Gateways”...
  • Page 992 Gateways that use a single CFC listener method do not need to use this method if the listener CFC method is named . For the sake of consistency, Macromedia onIncomingMessage recommends that any event gateway with a single listener not override this default.
  • Page 993 setCFCPath Description Specifies the listener CFC that will process this event. Category Event Gateway Development Syntax void setCFCPath(String path) See also , “CFEvent class” in Chapter 45, “Creating getCFCPath setCFCMethod setCFCTimeout Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description path...
  • Page 994 setCFCTimeout Description Sets the time-out, in seconds, during which the listener CFC must process the event request and return before ColdFusion gateway services terminates the request. Category Event Gateway Development Syntax void setCFTimeout(String timeout) See also , “CFEvent class” in Chapter 45, “Creating getCFCTimeout setCFCMethod setCFCPath...
  • Page 995 setData Description Adds the gateway-specific data, including any message contents, as a Java Map to the CFEvent object Category Event Gateway Development Syntax void setData(Map data) See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, “Creating getData Custom Event Gateways”...
  • Page 996 setGatewayType Description Identifies the type of event gateway. Category Event Gateway Development Syntax void setGatewayType(String gatewayType) See also Parameters Parameter Description gatewayType A gateway type identifier. “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, getGatewayType “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Usage For the sake of consistency, use the same name in this method and in the Type Name field when you add the event gateway type in the ColdFusion MX Administrator.
  • Page 997 setOriginatorID Description Identifies the originator of an incoming message. Category Event Gateway Development Syntax void setOriginatorID(String originatorID) See also “CFML CFEvent structure” on page 1004, “CFEvent class” in Chapter 45, getOriginatorID “Creating Custom Event Gateways” in ColdFusion MX Developer’s Guide Parameters Parameter Description...
  • Page 998 Logger class coldfusion.eventgateway.Logger Note: This class is in the coldfusion.log package, not the coldfusion.eventgateway package, which contains all other event gateway-related interfaces and classes. The Logger class logs messages to a file in the ColdFusion logs directory. (You set this directory on the ColdFusion MX Administrator Logging Settings page.) The method returns an instance of coldfusion.eventgateway.GatewayServices.getLogger()
  • Page 999 debug Description Writes a log entry with a debugging severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message. Category Event Gateway Development Syntax debug(String message) debug(Throwable th) debug(String message, Throwable th) See also , “Logging events and using log files”...
  • Page 1000 error Description Writes a log entry with an error severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message. Category Event Gateway Development Syntax error(String message) error(Throwable th) error(String message, Throwable th) See also , “Logging events and using log files”...

This manual is also suitable for:

Colfusion mx 7 - installing and using coldfusion mx

Table of Contents