Alphabetical List of ColdFusion Tags


<cfabort>

Description: The <cfabort> tag is used to halt processing of a ColdFusion template immediately. It optionally presents a user-defined error message. See Table B.14 for attributes.

Table B.14. <cfabort> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

showError

Error message text

Optional.


Syntax:

 <cfabort showError="Error text"> 

Example: The following example aborts the template processing if the user has not properly logged in, as evidenced by the existence of a session variable:

 <!--- If a user is not logged in, an error is thrown ---> <cfif NOT IsDefined("SESSION.LoggedIn")>  <cfabort showError="You are not authorized to use this function!"> </cfif> 

TIP

<cfabort> can be used to terminate the processing of a template safely if an error condition occurs. For example, if your template was expecting a URL parameter to be passed, you could use the ParameterExists or IsDefined function to verify its existence and terminate the template with an appropriate error message if it did not exist.


See also <cfexit>, <cfbreak>


<cfapplet>

Description: <cfapplet> is used to embed user-supplied Java applets in CFFORM forms. Table B.15 shows the complete list of attributes supported by <cfapplet>. In addition, you can pass your own attributes as long as they have been registered along with the applet itself.

Table B.15. <cfapplet> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

align

Applet alignment

Optional; valid values are Left, Right, Bottom, Top, Texttop, Middle, Absmiddle, Baseline, and Absbottom.

appletSource

Name of the registered applet

Required

height

Number of pixels

Optional; height of applet.

hSpace

Number of pixels

Optional; horizontal space around applet.

name

Form field name

Required.

notSupported

Text to display on browsers that do not support Java

Optional.

vSpace

Number of pixels

Optional; vertical space around applet.

width

Number of pixels

Optional; width of applet.

Paramn

Parameter names

Optional; parameter names registered with the applet.


Syntax:

 <cfapplet align="Alignment"  appletSource="Registered Name"  height="Height"  hSpace="Horizontal Spacing"  name="Field Name"  notSupported="Text for non-Java browsers"   vSpace="Vertical Spacing"  width="Width"> 

Example: The following example embeds a Java calculator applet into <cfform>:

 <!--- Creates form ---> <cfform action="process.cfm">  <!--- Creates calculator applet --->  <cfapplet appletSource="copytext"   name="calc"   notSupported="Your browser does not support Java."   vSpace=400  width=200> </cfform> 

NOTE

Before you can use an applet with <cfapplet>, it must be registered with the ColdFusion Administrator.


NOTE

<cfapplet> must be used within <cfform> and </cfform> tags.


NOTE

Controls embedded with <cfapplet> are accessible only by users with Java-enabled browsers.


See also <cfform>, <cfgrid>, <cfslider>, <cftextinput>, <cftree>


<cfapplication>

Description: <cfapplication> is used to define the scope of an application and to specify several aspects of the application's configuration. These include the use of session and client variables. This tag should be included in all templates that are part of the application and therefore intended for use in your application.cfm template or your application.cfc component. See Table B.16 for <cfapplication> attributes.

Table B.16. <cfapplication> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

applicationTimeout

Time interval

Optional; application variable timeout; defaults to value in ColdFusion Administrator.

clientManagement

Yes or No

Optional; defaults to No. Enable or disable client variables.

clientStorage

Mechanism for storage of client ODBC data source name

Optional; defaults to Registry; other values are Cookie and any information.

name

Name of application

Required if you are using application variables; can be up to 64 characters long.

sessionManagement

Yes or No

Optional; defaults to No. Enable or disable session variables.

sessionTimeout

Time interval

Optional; session variable timeout; defaults to value in ColdFusion Administrator.

Setclientcookies

Yes or No

Optional; enable or disable client cookies; defaults to Yes.

setDomainCookies

Yes or No

Enables use of CFID and CFTOKEN cookies across an entire domain, rather than just a single host. Intended for use in a CF Server cluster.


Syntax:

 <cfapplication applicationtimeout ="Timeout"   clientManagement ="Yes or No"  clientStorage="Storage Type"  loginStorage="Cookie or Session"  name="Application Name"  scriptProtect="None", "All" or "List"  sessionManagement ="Yes or No"   sessionTimeout ="Timeout"  setclientCookies="Yes or No"   setdomainCookies="Yes or No"> 

Example: The following example is designed for use in an Application.cfm file. It names part of an application Administration and enables session variables. It then looks for the presence of a particular session variable and redirects the user to the specified directory if the session variable doesn't exist:

[View full width]

<!--- creates ColdFusion application, enables session management, and sets session timeout ---> <cfapplication name="Administration" sessionManagement="Yes" sessionTimeout="CreateTimeSpan(0,0,45,0)"> <!--- If user is not logged in, he or she is sent to the login page ---> <cfif Not IsDefined("SESSION.LoggedIn")> <cflocation URL="/Login"> </cfif>

TIP

Use the CreateTimeSpan() function to create the time interval parameters required in the Sessiontimeout and Applicationtimeout attributes. See Appendix C, "ColdFusion Function Reference," for further details.


See also <cfcookie>, <cfset>


<cfargument>

Description: <cfargument> is used inside <cffunction> to define arguments to the function. <cffunction> is used to define methods within a ColdFusion component, so these three tags are frequently used together. Note that a component method does not require arguments, but <cfargument> can be used only within a <cffunction> body. Use the ARGUMENT scope to reference argment variables. <cfargument> attributes are shown in Table B.17.

Table B.17. <cfargument> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Time interval

Required; name of argument; string.

type

Data type name

Optional; indicates type of data that this argument uses.

required

Yes or No

Optional; defaults to No. Indicates whether or not this argument is required.

default

Data value

The default value to be used by this argument. When this attribute is used, Required must be set to No.


Syntax:

 <cfargument name ="Argument name"  displayname="Descriptive string"  hint="Extended description string"   type ="Data type of argument"  required="Yes or No"   default="Default value for argument"> 

Values of the type attribute include:

Any

Numeric

Array

Query

Binary

String

Boolean

Struct

Component Name

UUID

Date

Variablename

GUID

XML


Example: In the following example, a ColdFusion component is defined with one function that has one argument. This component is used to search for all merchandise for a specified film. If merchandise is found, it returns a query result containing the merchandise. The FilmID is passed to the component with <cfargument>:

 <!--- Looks for merchandise for specified film and returns what   it finds ---> <cfcomponent>  <cffunction name="CheckMerchandise">  <cfargument name="FilmID" type="Integer" required="Yes">  <!--- Find all merchandise for specified film --->  <cfquery name="GetMerchandise" dataSource="ows">  SELECT MerchID, MerchName, MerchDescription, MerchPrice  FROM Merchandise  WHERE FilmID=#ARGUMENTS.FilmID#   </cfquery>  <!--- Return query result --->  <cfreturn #GetMerchandise#>  </cffunction> </cfcomponent> 

See also <cffunction>, <cfcomponent>, <cfreturn>


<cfassociate>

Description: The <cfassociate> tag is used to associate subtags, or child tags, with base tags. This tag can be used only inside custom tag templates. It is used in the subtag to make the subtag data available in the base tag. The subtag data is stored in a structure in the base tag. See Table B.18 for <cfassociate> attributes.

Table B.18. <cfassociate> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

baseTag

Base tag name

Required; name of base tag associated with this subtag.

dataCollection

Name of the structure in the base tag to store attributes

Optional; defaults to structure of AssocAttribs if used.


Syntax:

 <cfassociate baseTag="CF_TAG"   dataCollection="structure"> 

Example: The following example associates a subtag with a base tag:

 <!--- In the subtag CF_USERINFO ---> <cfparam name="ATTRIBUTES.LoginName" Default=""> <cfparam name="ATTRIBUTES.Password" Default=""> <cfparam name="ATTRIBUTES.Privilege" Default=""> <cfassociate baseTag="CF_CHECKUSER"> <!--- In the base tag, CF_CHECKUSER ---> <cfif Len(AssocAttribs.ATTRIBUTES.LoginName) EQ 0>  <cfexit> </cfif> 

See also <cfmodule>


<cfbreak>

Description: <cfbreak>, which must be used inside the <cfloop> and </cfloop> tag, is used to break out of a looping process. Unlike <cfabort>, it does not stop ColdFusion processing. <cfbreak> has no attributes.

Syntax:

 <cfbreak> 

Example: The following example queries all films from the Films table. It then loops through the list, comparing them to a FORM parameter, FORM.LastFilmID. If it finds a match, it saves the title of the selected film, breaks out of the loop, and continues processing:

 <!--- Queries database ---> <cfquery name="GetMovies" dataSource="#DSN#">  SELECT FilmID, MovieTitle  FROM Films </cfquery> <!--- Loops through query results ---> <cfloop query="GetMovies">  <!--- Tests for equality between query results and form variable --->  <cfif GetMovies.FilmID EQ FORM.LastFilmID>  <!--- If equality found, variable is set --->  <cfset SelectedFilm=GetMovies.MovieTitle>  <!--- Stops only loop processing --->  <cfbreak>  </cfif> </cfloop> 

See also <cfloop>, <cfabort>, <cfexit>


<cfcache>

Description: The <cfcache> tag is used to improve the performance on pages in which content doesn't need to be dynamically created each time the page is requested by storing copies on the client or server. ColdFusion instead returns static HTML output created during the last run of the page; so this tag should only be used when dynamic content is not required. Table B.19 shows the complete list of <cfcache> attributes. Available action attribute values are shown in Table B.20.

Table B.20. <cfcache> Actions

ACTION

DESCRIPTION

Cache

Indicates that server-side caching is to be used. This is the default action.

Flush

Cached page is to be refreshed.

Clientcache

Indicates that client-side caching is to be used.

Optimal

Indicates that an optimal combination of client- and server-side caching is to be used.

Servercache

Indicates serve-rside caching only.


This tag can now cache pages that have been secured through ColdFusion's authentication framework as well as pages that depend on session state. You use this tag in pages that are to be cached. The combination of a page's URL and its parameters are evaluated as unique.

Syntax:

 <cfcache action="action"   directory="server directory for cache"   expireURL="URL wildcard"  port="port number"  protocol="HTTP or HTTPS"  username="user name"  passWord="password"  timeSpan="time value"> 

Table B.19. <cfcache> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Optional. See Table B.19.

directory

Absolute path

Optional. The absolute path to the server directory that holds the cached pages. Defaults to Cache below the directory in which ColdFusion was installed.

expireURL

URL wildcard

Optional; used with action=Flush. ColdFusion matches against URLs in the cache. You can include wildcard such as "*/dirname/file.*"

passWord

Password

Optional; this password will be used if basic authentication is required.

port

Web server port

Optional; defaults to 80. Port from which page is being requested.

protocol

HTTP or HTTPS

Optional; defaults to HTTP. Identifies protocol used to create pages from cache.

timeSpan

Time value

Interval before page is automatically flushed from cache. Can use either an integer (or fraction) for days or a value created by CreateTimeSpan().

username

User name

Optional; can be used if basic authentication is required.


Example: This example caches the static content from a dynamic template for up to 36 hours (unless it's explicitly flushed sooner):

 <!--- Cache page for 1 and one half days ---> <cfcache timeSpan="1.5" action="cache"> <html> <head> <title>Page to be Cached</title> </head> <body> <h1>This page is cached</h1> <P>The last version of this page was on: <cfoutput>#DateFormat(Now())#</cfoutput> </body> </html> 

NOTE

<cfcache> uses <cfhttp> to retrieve the contents of your page, so if there is an HTTP error accessing the page the contents are not cached. If ColdFusion generates an error, the error result will be cached.


<cfcalendar>

Description: <cfcalendar>, creates a Flash calendar user interface object inside either Flash or HTML based forms (XML-based forms are not supported). See Table B.21 for the complete list of <cfcase> attributes.

Table B.21. <cfcalendar> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

dayNames

Case value

This attribute is required.

disabled

True, False or NULL

Optional; Defaults to false. Setting to true disables user input to the calendar.

endRange

Date

Optional, but used with STARTRANGE. Ending date of range of disabled dates.

firstDayOfWeek

Integer between 0 and 6

Optional; defaults to 0, where 0 represents Sunday.

height

Pixels

Optional; control height.

mask

Format specification

Optional; defaults to MM/DD/YYYY. Specifies the format of the submitted date. D applies a 'day' mask to 0-2 characters. M applies a 'month' mask to 0-4 characters. Y applies a 'year' mask to 0, 2, or 4 characters. E applies a 'day-of-week' mask to 0-4 characters. Any other characters are treated as literals.

onChange

Actionscript

Optional. Actionscript code that is executed when a user changes the control value.

startRange

Date

Optional but used with ENDRANGE to specify a range of dates that can't be selected.

selectedDate

Date

Optional; The date that is initially selected. No default, but current month is displayed by default. Must be in a format indicated by current locale (either mm/dd/yyyy or dd/mm/yyyy).

sytle

Actionscript

Optional, Actionscrip-type style specification. Applies a Flash skin to entire calendar.

width

Pixels

Optional; control width.


Syntax:

 <cfcalendar  dayNames="Days-of-week Labels"  disabled="True or False or NULL"  endRange="Last disabled date"  firstDayOfWeek="Integer from 0-6"  height="Pixels"  mask="Format spec"  monthNames="Month labels"  name="Text name"  onChange="Actionscript"  startRange="First disabled date"  selectedDate="Initial date"  style="Actionscript style"  width="width"> 

Example: The following code produces a calendar and restricts a range of dates covering Thanks-giving 2004 and selects Nov 1, 2004 when the calendar is initially displayed:

 <cfform name="DeliveryCalForm" action="process.cfm"> <cfcalendar   name="DeliveryCal"   height="200"   width="200"   firstDayOfWeek="1"   startRange="11/25/2004"   endRange="11/26/2004"   selectedDate="#dateFormat('11/1/2004', 'mm/dd/yyyy')#"> <br/> <input type="Submit"> </cfform> 

<cfcase>

Description: <cfcase>, which must be used with <cfswitch>, specifies individual case statements. A default case can be specified using the <cfdefaultcase> tag. See Table B.22 for The complete list of <cfcase> attributes.

Syntax:

 <cfswitch expression="expression">  <cfcase value="value">  HTML or CFML code here  </cfcase>  <cfdefaultcase>  HTML or CFML code here  </cfdefaultcase> </cfswitch> 

Table B.22. <cfcase> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

value

Case value

This attribute is required.

delimiters

Character separator

Optional; Defaults to "," (comma).


Example: The following example checks whether a state is a known state and displays an appropriate message:

 <!--- Evaluates passed expression (UCase(state)) ---> <cfswitch expression="#UCase(state)#">  <!--- If case matches CA, California is used. --->  <cfcase value="CA">California</cfcase>  <!--- If case matches AR, Arkansas is used. --->  <cfcase value="AR">Arkansas</cfcase>  <!--- If case matches MI, Michigan is used. --->  <cfcase value="MI">Michigan</cfcase>  <!--- If case doesn't match, the following message is displayed. --->  <cfdefaultcase>One of the other 47 states</cfdefaultcase> </cfswitch> 

See also <cfswitch>, <cfdefaultcase>


<cfcatch>

Description: <cfcatch>, which must be used with <cftry>, catches exceptions thrown by ColdFusion or explicitly with <cfthrow> or <cfrethrow>. All code between <cftry> and </cftry> can throw exceptions, and exceptions are caught by <cfcatch> blocks. Explicit <cfcatch> blocks can be created for various error types, or one block can catch all errors. <cfcatch> attributes are listed in Table B.23 A special structure variable, CFCATCH, is available in your <cfcatch> blocks. Its elements are described in Table B.24, and its variable elements are described in Table B.25.

Table B.23. <cfcatch> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

type

Exception type

Optional; values listed in Table B.22.


Table B.24. <cfcatch> TYPE Values

TYPE

Any

Application

Custom_Type

Database

Expression

Lock

Missinginclude

Object

Security

Synchronization

Template


Table B.25. CFCATCH Variable Elements

TYPE

ONLY FOR TYPE

DESCRIPTION

Detail

 

A detailed error message; helps determine which tag threw the exception.

Errnumber

Expression

Internal expression error number.

Errorcode

Custom type

Developer-specified error code.

Extendedinfo

Application

Developer's custom error Custom type message.

Lockname

Lock

Name of the affected lock; set to anonymous if the lock was unnamed.

Lockoperation

Lock

Operation that failed; Timeout, Create Mutex, or Unknown.

Message

 

Diagnostic message; can be null.

Missingfilename

Missinginclude

Name of file that could not be included.

Nativeerrorcode

Database

The native error code from the database driver; -1 if no native code provided.

Sqlstate

Database

Another error code from the database driver; -1 if no native code provided.

Tagcontext

 

Tag stack; name and position of each tag in the stack.

Type

 

Exception type, as specified in <cfcatch>.


Syntax:

 <cftry>   <cfcatch type="type">   </cfcatch> </cftry> 

Example: This example traps for an error when attempting to create a new directory programmatically:

 <!--- Sets the trap for errors ---> <cftry>  <!--- Creates directory --->  <cfdirectory action="Create" Directory="#FORM.UserDir#">  <!--- Catches any type of error --->  <cfcatch type="Any">  <!--- Tests output for certain phrase --->  <cfif cfcatch.Detail Contains "when that file already exists">  <P>Can't create directory: this directory already exists.  <!--- If the output doesn't contain phrase, it outputs the error   details and aborts --->  <cfelse>  <cfoutput>#cfcatch.Detail#</cfoutput>  </cfif>  <cfabort>  </cfcatch> </cftry> <P>Directory created. 

You will find other useful examples in the entries for <cfrethrow>, <cfauthenticate>, and <cftransaction>.

See also <cftry>, <cfthrow>, <cfrethrow>


<cfchart>

Description: <cfchart> enables you to create charts rendered as JPG, PNG or Flash objects in your Web pages. It largely replaces <cfgraph> from previous versions of ColdFusion. You can produce dynamic bar (vertical or horizontal), line, and pie charts built from query results. Three sets of similar attributes are available to support the three types of charts. You also can employ the child tags <cfchartdata> and <cfchartseries> to add individual data points and series of data points to the chart. Table B.26 shows <cfchart> attributes.

Table B.26. <cfchart> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

backgroundColor

Web color or hex value

Optional. Color to use on background of chart.

chartHeight

Integer number of pixels

Optional. Width of border in pixels.

chartWidth

Integer number of pixels

Optional. Width of chart in pixels.

dataBackgroundColor

Web color or hex value

Optional. Hex color value or Web color name.

font

Font name

Optional. Name of font to be used on chart. Defaults to Arial.

fontBold

Yes or No

Optional. Indicates whether to bold the fonts. Defaults to No.

fontItalic

Yes or No

Optional. Indicates whether to italicize the fonts. Defaults to No.

fontSize

Font size in points

Optional. Integer, font size.

foregroundColor

Web color or hex value

Optional, Hex color value or Web color name for font and other foreground items (e.g., legend border color). Defaults to Black.

format

Flash or Jpg or Png

Optional. Indicates file format for graphical image. Defaults to Flash.

gridLines

Integer

Optional, number of lines.

labelFormat

Number, Currency, Percent, Date

Optional, label format, defaults to as is.

markerSize

Integer

Optional. Number of pixels.

name

String, var name

Optional. Name of string variable required for storing binary graph data java.io.ByteArrayInputStream. Used primarily by Flash gateways.

pieSlicestyle

Text

Optional. Sliced or Solid; defaults to Sliced.

scaleFrom

Integer

Optional. Lowest value for Y axis in chart.

scaleTo

Integer

Optional. Highest value for Y axis in chart.

seriesPlacement

Text

Optional. Default, Cluster, Stacked, Percent. Default value is "Default".

Show3D

Yes or No

Optional. Defaults to No. Gives chart data a 3-D appearance.

showBorder

Yes or No

Optional. Defaults to No. Puts border around perimeter of chart.

showLegend

Yes or No

Optional. Defaults to Yes. Results in the display of a data item legend.

showMarkers

Yes or No

Optional. Defaults to No. Results in data item markers being displayed.

showXGridlines

Yes or No

Optional. Defaults to No. Displays horizontal grid lines.

sortxAxis

Yes or No

Optional; defaults to No. It is ignored if the xAxistType is set to Scale.

tipBgColor

Web color or hex value

Optional. Hex color value.or Web color name.

tipStyle

Text

Optional. Must be either MouseDown, MouseOver, or Off. Defaults to MouseOver.

title

Text

Optional; title for chart.

URL

URL

Optional. Address of page to go to on click of the chart. You can use the following variable values as URL variable values in the URL that is being invoked: $VALUE$ - Value of selected row. $ITEMLABEL$ - Label of the selected item. $SERIESLABEL$ - Label of selected series. Note that any of these may be blank if the item was not selected. You can also specify Javascript in the URL.

xAxisTitle

Text

Optional. Title for X-Axis.

xAxisType

Category or Scale

Optional; defaults to Category. The axis indicates the data category. The SORTXAXIS attribute is used to sort data. When set to Scale, the X-axis must be numeric and each CHARTDATA ITEM attribute values must be numeric. The X-axis will automatically be sorted numerically.

xOffset

Number

Optional; defaults to .1. Number between -1 and 1. Applies only if SHOW3D is true and determines the degree to which the chart will be angled horizontally.

yAxisTitle

Text

Optional Title for Y-Axis

yAxisType

Category

Optional; defaults to Category. However, setting to Category currently has no effect as the Y-Axis can only display numeric values.

yOffset

Number

Optional; defaults to .1. Number between -1 and 1. Applies only if SHOW3D is true and determines the degree to which the chart will be angled vertically.


Syntax:

 <cfchart \ width= backgroundColor="Hex or web color" chartHeight="Integer number of pixels"  chartWidth="Integer number of pixels"   dataBackgroundColor="Web color or hex value"  font="Arial or Courier or Times" fontBold="Yes o No" fontItalic="Yes or cNo"  fontSize="Integer font size in points"   foregroundColor="Web color or hex value"   format="Flash or Jpg or Png" gridLines="Integer number of lines" labelFormat="Number, Currency, Percent, Date"  markerSize="Number of pixels, integer"  name="Text name of chart"  pieSliceStyle=="Solid, Sliced"scaleFrom="Integer minimum value"  scaleTo="Integer maximum value"   seriesPlacement="Defult, cluster, Stacked, Percent"  show3D="Yes or No"  showBorder="Yes or No"  showLegend="Yes or No"  showMarkers="Yes or No"   showXGRidlines = "Yes or No"  sortXAxis="Yes or No"  style="XML string or stylssheet" tipBgColor="Web color or hex value"  tipStyle="mouseDown, mouseOver or off"  title="Title text"  URL="address of page to go to on Click"  xAxisTitle="Title for X-Axis"  xAxisType="Scale or Category" xOffset=number between 1 and 1"  yAxisTitle="Title for Y-Axis"  yAxisType="Scale or Category" yOffset="number between 1 and 1"> 

Example: The following example creates a chart with a series. The query displays the top ten salaries paid to directors for films they worked on. Note that as a few directors appear in this list of top ten more than once, <cfchart> would eliminate the duplicates from the series if it was just based on director name, for example. To insure that each entry is unique, we've concatenated the film name to the director's name.

 <!--- Note that query concatenates director name and movie title.  This is done to insure unique entries on the X-Axis, otherwise, the   cfchart would eliminate duplicate director names from the X-Axis. ---> <cfquery name="GetDirectorSalary" dataSource="ows">   SELECT TOP 10 Salary, LastName & ' - ' & MovieTitle as DirectorFilm   FROM (FilmsDirectors FD INNER JOIN Directors D on FD.DirectorID = D.DirectorID)   INNER JOIN Films F on FD.FilmID = F.FilmID   ORDER BY Salary DESC </cfquery> <cfchart    format="Flash"   xAxisTitle="Directors"   yAxisTitle="Salaries"   font="Arial"   backgroundColor="##CCCC99"   scaleFrom=90000   scaleTo=1100000   chartWidth=800   chartHeight=600   title="Top 10 Directors Salary"   showBorder="yes"   show3D="Yes"   xOffset="-.01" > <cfchartseries  query="GetDirectorSalary"  itemColumn="DirectorFilm"  valueColumn="Salary"  seriesLabel="Salaries"  seriesColor="aqua"   type="pyramid"  markerstyle="diamond"> </cfchart> 

See also <cfchartdata>, <cfchartseries>


<cfchartdata>

Description: The <cfchartdata> tag is used to produce graphs from hard-coded data items (as opposed to data points generated from query results). The <cfchartdata> tag must be used in the body of a <cfchartseries> tag. And <cfchartseries> tags are used within the body of a <cfchart> tag, which defines the "shell" of the chart. See Table B.27 for <cfchartdata> attributes.

Table B.27. <cfchartdata> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

item

Text label

Optional; label for the data point.

value

Number

Required; data point value; number.


Syntax:

 <cfchartdata  item="Text"  value="Number"> 

Example: The following example presents a simple pie chart in which the data points are hard-coded.

 <!--- Create pie chart itself ---> <cfchart   showBorder="Yes"  Show3D="Yes"  pieSliceStyle="solid"  backgroundColor="Gray"  foregroundColor="blue"  chartwidth="640"  chartheight="480"  format="png" >  <!--- create pie slices --->  <cfchartSeries type="pie" seriesLabel="Genre"  colorList="White,##00ff6e,Blue,Red,##eeff33">  <!--- Specifies individual data points --->  <cfchartdata item="Drama" value="85000">  <cfchartdata item="Comedy" value="37500">  <cfchartdata item="Action" value="125000">  <cfchartdata item="Horror" value="95000">  <cfchartdata item="Sci-Fi" value="95000">  </cfchartseries> </cfchart> 

See also <cfchart>, <cfchartseries>


<cfchartseries>

Description: The <cfchartseries> tag, which must be used with the <cfchart> tag, enables you to define series of data points to your charts. This series can be produced dynamically from query results or can be added as individual points using <cfchartdata>. See Table B.28 for the <cfchartseries> attributes.

Table B.28. <cfchartdata> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

type

Text label

Optional. Type of chart. Choices include Bar, Column, Line, Pyramid, Area, Cone, Curve, Cylinder, Step, Scatter, and Pie.

dataLabelStyle

Style spec

Optional; determines where text for data label comes from. Chose from one of the following: ColumnLabel, RowLabel, Pattern, Value or None.

query

Number

Optional. Query name to use to build series dynamically.

itemColumn

Text

Optional. Name of column from query from which to get data item names.

valueColumn

Text

Optional. Name of column from query from which to get data item values.

seriesColor

Text

Optional. Can specify from the 256 standard Web colors in any valid HTML format.

paintStyle

Text

Optional. Specifies a chart style from one of the following: Plain, Raise, Shade or Light.

markerStyle

Text

Optional. Defaults to Rectangle. Indicates style of marker to be used from one of the following: Rectangle, Triangle, Diamond, Circle, LetterX, Mcross, Snow, Rcross.

colorList

Comma-delimited list

Optional. Specifies colors for data points from the 256 for each data standard Web colors. If there are more colors than data points, the list starts over.


Syntax:

 <cfchartseries   type="Chart type"  query="Query name"  itemColumn="Query column name"  valueColumn="Query column name"  dataLabelStyle="Label style specification"seriesLabel="Label Text"  seriesColor="Hex value or Web color"   paintStyle="Plain, Raise, Shade, Light"  markerStyle="style"  colorList = "List"> </cfchartseries> 

Example: The following example builds on the example in <cfchart> by adding a second series. So in this chart, one series presents budget per film and another provides actual expenses per film and enables the viewer to visually compare the expenses to the budget.

 <!--- Get expense and then budget data;   expenses are summed by film ---> <cfquery name="GetExpenses" dataSource="OWS">  SELECT E.FilmID, MovieTitle, Sum(ExpenseAmount) As Amt  FROM Films F INNER JOIN Expenses E ON F.FilmID = E.FilmID  GROUP BY E.FilmID, MovieTitle  order by E.filmID </cfquery> <cfquery name="GetBudget" dataSource="OWS">  SELECT FilmID, MovieTitle, AmountBudgeted AS Amt  FROM Films  order by filmID </cfquery> <!--- Define chart ---> <cfchart xAxisTitle="Film"  yAxisTitle="Dollars"  font="Arial"  backgroundColor="##CCCC99"  gridLines="20"  scaleFrom=10000  scaleTo=500000  chartwidth=800  chartheight=600 >  <cfchartseries  type="bar"  query="GetExpenses"  itemColumn="MovieTitle"  valueColumn="Amt"  seriesLabel="Expenses"  >  <cfchartseries  type="Bar"  query="GetBudget"  itemColumn="MovieTitle"  valueColumn="Amt"  seriesLabel="Budget"  > </cfchart> 

See also <cfchart>, <cfchartdata>


<cfcol>

Description: <cfcol>, which must be used with <cftable>, defines table columns. The <cfcol> attributes are listed in Table B.29.

Table B.29. <cfcol> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

header

Header text

Optional; text for header.

width

Number of characters

Data wider than this for column width value will be truncated.

align

Column alignment

Left, Right, or Center.

text

Text that is to be displayed in the column

This can be a combination of text and ColdFusion variables.


Syntax:

 <cfcol Header="Header Text"   width="Width"   Align="Alignment"   text="Body Text"> 

Example: This example queries a database and displays the output using <cftable> and <cfcol>:

 <!--- Query gets data ---> <cfquery name="GetFilms" dataSource="OWS">  SELECT FilmID, MovieTitle   FROM Films </cfquery> <h1>Use of cftable and cfcol</h1> <!--- Table is created from query results ---> <cftable query="GetFilms">  <!--- Table columns are specified --->  <cfcol header="Film ID" width="8" align="Right" text="<em>#FilmID#</em>">  <cfcol header="Name" width="30" align="Left" text="#MovieTitle#"> </cftable> 

See also <cftable>, <cfoutput>, <cfquery>


<cfcollection>

Description: The <cfcollection> tag can be used to create and administer Verity collections programmatically. The complete list of <cfcollection> attributes is shown in Table B.30. Table B.31 lists the values for the action attribute. Table B.32 describes the columns in the result set that is produced when the action attribute is set to List.

Table B.30. <cfcollection> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required; see Table B.31. Default is List.

categories

Yes or No

Optional; Defaults to No. Indicates whether or not this collection of documents will include categories. Also has the effect of enabling or disabling the use of CategoryList as one of the action values.

collection

Collection name

Name of the collection to be indexed. If using external collections, this must be a fully qualified path to the collection. It is required when action is Create, Map, Optimize, Repair, Delete, or CategoryList.

language

Collection language

Defaults to English. Its use is optional when action is Map or Create.

name

Query result name

Required if action is LIST or CategoryList. The name of the query result set.

path

Collection path

Required if action is Create or Map.


Table B.31. <cfcollection> Actions

ACTION

DESCRIPTION

Categorylist

Returns a structure of structures. These list categories that were used when the collection was created. The entry for each category will indicate the number of documents in that category.

Create

Creates and registers collections in the CF Administrator. If the collection doesn't exist, it will be created. If it does, then a map to it is created.

Delete

Deletes a collection and un-registers it from CF.

List

Produces a query result listing the Verity and K2 collections registered with the ColdFusion server. Query result will be named with the value of the name attribute.

Map

This action has been deprecated.

Optimize

Purges and reorganizes a collection.

Repair

Fixes a corrupt collection.


Table B.32. Result Set Produced By The List action

COLUMN

DESCRIPTION

Categories

Yes or No indicating whether or not categories were enabled when the collection was created.

Charset

Character set for the collection.

Created

Date/Time collection was created.

DocCount

Number of documents in the collection.

External

Yes, No or Not found. Yes if the collection is external, No if it's not, Not found if the registered collection's directory path couldn't be found.

Language

Locale setting for the collection.

LastModified

Date and time the collection was last changed.

Mapped

No longer in use.

name

The collection's name.

Online

No longer in use.

Path

Absolute path to the collection.

Registered

No longer in use.

Size

Collection size in KB.


Syntax:

 <cfcollection   action="action"   categories="Yes or No"collection="collection"   language="lAnguage"  path="path"> 

The action Create creates a directory for the use of Verity, using the path attribute value. The Collection attribute is used to create a subdirectory within the PATH directory. So, if path=MyDir and Collection=MyCollection, the Create action would create a directory named c:\MyDir\MyCollection\.

The Map action enables ColdFusion to reference a collection with an alias. This alias can be used in <cfindex> and to reuse a collection from an earlier installation of ColdFusion. The Path attribute specifies the fully qualified path to the collection. Based on the example in the preceding paragraph, this would be c:\MyDir\MyCollection\.

NOTE

The Verity server must be running in order for the LIST action to work or it will throw an error.


Example: This example provides a form you can use to invoke any <cfcollection> action.

 <!--- Here is the form page ---> <html> <head>  <title>cfcollection Example</title> </head> <body> <!--- Form is created ---> <form action="CollectionProcessor.cfm"   method="post"> <!--- Hidden form field that is passed to action page ---> <input type="Hidden" name="CollectionName_required"> <!--- Text input field is created ---> <P>Collection name: <input type="Text" name="CollectionName"> <br>(note: When Action is Map, enter the collection Alias name to use.) <!--- Menu is created that selects the <cfcollection> action ---> <P>Action: <select name="Actions">  <option selected>Create  <option>Delete  <option>Map  <option>Optimize  <option>Repair </select> <!--- Submit button is created ---> <P><input type="Submit"> </form> </body> </html> <!--- This is the form's action template, CollectionProcessor.cfm. ---> <!--- Form passes ACTION and COLLECTION attributes to <cfcollection> tag ---> <cfcollection action="#FORM.Actions#"  collection="#FORM.CollectionName#"> 

NOTE

Different language packs are required to support collections in different groups of languages.


NOTE

<cfcollection> works at the collection level only. To add content to a collection, use <cfindex>.


See also <cfindex>, <cfsearch>


<cfcomponent>

Description: The <cfcomponent> tag is used to create ColdFusion components. These are much like objects that can have their own behaviors (methods) and properties. Again, like objects, ColdFusion components can inherit functionality from "parent" components identified by the Extends attribute. The Extends attribute identifies the current component's parent, from which it inherits methods and properties. Any text or CFML output within the tag body can be suppressed by setting the Output attribute to No. <cfcomponent> attributes are shown in Table B.33.

Table B.33. <ccfcomponent> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

extends

Text

Optional; implements object-oriented notion of inheritance. Name or pathname (dot notation, see following example) to another component that this component is based on.

output

Yes or No

defaults to No. "No" suppresses output from the body of the tag and "Yes" enables it.


Syntax:

 <cfcomponent extends="Component name" output="Yes or No"> 

Example:

 <!--- This component inherits functionality from  a component named Merchandise and adds a new  function to it. ---> <cfcomponent extends="Merchandise">  <cffunction name="CheckFilmOrderCount">  <cfargument name="FilmID" type="Integer" required="Yes">  <!--- Find count of orders for merch for specified film --->  <cfquery name="OrdersCount" dataSource="ows">  SELECT Distinct Count(MOI.OrderID) AS OrdersForFilm  FROM MerchandiseOrdersItems MOI   INNER JOIN Merchandise M ON MOI.ItemID = M.MerchID  WHERE M.FilmID=#ARGUMENTS.FilmID#   </cfquery>  <!--- Return count --->  <cfreturn #OrdersCount.OrdersForFilm#>  </cffunction> </cfcomponent> 

NOTE

Components stored in the same directory are part of a package. They can be addressed with dot notation to indicate each sub-directory. For example, to invoke mycomponent.cfm in the directory c:\inetpub\webroot\components\myapp\, you could address it, components.myapp.mycomponent.


See also <cfargument>, <cffunction>, <cfreturn>, <cfmodule>


<cfcontent>

Description: The <cfcontent> tag enables you to send non-HTML documents to a client's browser. <cfcontent> lets you specify the MIME type of the file and an optional filename to transmit. See Table B.34 for the complete list of supported attributes.

Table B.34. <cfcontent> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

type

Content MIME Type

Required.

file

Filename

Optional attribute that specifies the fully qualified path of a file to be transmitted to the user's browser.

reset

Yes or No

Optional. It discards output preceding call to <cfcontent>. Defaults to Yes.

deleteFile

Yes or No

Optional; deletes file once sent; useful if serving dynamically created graphics.


Syntax:

 <cfcontent type="MIME Type"   file="File Name"   deleteFile="Yes or No"   reset="Yes or No"> 

NOTE

Because <cfcontent> needs to write to the HTTP header, you can't use it if you've already flushed the header from the ColdFusion output buffer with <cfflush>.


NOTE

If you use the <cfcontent> tag in a distributed ColdFusion environment where the Web server and ColdFusion Server run on different systems, the file attribute must refer to a path on the Web server system, not the ColdFusion Server system.


Example: The following example sends tab-delimited output (which can be easily read by a spreadsheet) to the browser. Note the use of tab-delimited field titles immediately following the <cfcontent> tag:

 <!--- Query gets the data ---> <cfquery name="GetFilmBudgets"   dataSource="OWS">  SELECT DISTINCT FilmID, MovieTitle, AmountBudgeted  FROM Films  WHERE AmountBudgeted > 1000000.00 </cfquery> <!--- If the query does not return any results, a message is displayed  and processing stops. ---> <cfif GetFilmBudgets.RecordCount EQ 0>  <P>No films with budgets over one million dollars  <cfabort> </cfif> <!--- Content is set to tab-delimited ---> <cfcontent type="TEXT/TAB-DELIMITED"   RESET> FilmID#chr(9)#Title#chr(9)#Budget <!--- Query results are outputted and formatted ---> <cfoutput query="GetFilmBudgets"> #FilmID##chr(9)##MovieTitle#[ic:ccc]#chr(9)##AmountBudgeted# </cfoutput> 

This next example sends a Microsoft Word document:

 <cfcontent type="application/msword"   file="C:\MyDocs\Proposal.DOC"> 

This final example sends a dynamically created map to the user and deletes it upon completion of the transmission:

 <cfcontent type="image/gif"   File="C:\Images\Maps\Temp123.gif"   Deletefile> 

<cfcookie>

Description: <cfcookie> lets you set cookies, persistent client-side variables, on the client browser. Cookies enable you to set variables on a client's browser, which are then returned every time a page is requested by a browser. Cookies can be sent securely if required. The tag attributes are described in Table B.35.

Table B.35. <cfcookie> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

domain

The domain for which the cookies are valid

Required only if PATH is used. Separate multiple domains with a ; character.

expires

Cookie expiration date

Optional; the cookie expiration date can be specified as a date (as in "10/1/97"), or as relative days (as in "100"), NOW, or NEVER.

name

Name of cookie

Required.

path

Subset of the specified domain to which the cookie applies

Optional; separate multiple paths with a ; character.

secure

Yes or No

Optional; specifies that cookie must be sent securely. If it is specified and the browser does not support SSL,the cookie is not sent.

value

Cookie value

Required.


To access a returned cookie, specify its name and precede it with the COOKIE designator, as in #COOKIE.USER_ID#.

Users can configure their browsers to refuse cookies. You must never make assumptions about the existence of the cookie. Always use the IsDefined function to check for the existence of the cookie before referencing it.

Syntax:

 <cfcookie name="Cookie Name"   value="Value"   expires="Expiration"   secure="Yes/No"  path="URL Path"   domain=".domain"> 

Example: The following example assumes a login form (not presented here) has been used to capture a user's name and password. These are then compared to what is in the database. If there's a match, a secure UserID cookie is created on the user's browser; the cookie will expire in 60 days:

 <!--- Query gets the data ---> <cfquery name="CheckUser"   dataSource="OWS">  SELECT UserID, UserName  FROM Users  WHERE UserName = '#FORM.UserName#'  AND Password = '#FORM.UserPassword#' </cfquery> <!--- If the query returns no results, a cookie is placed  on the user's system ---> <cfif RecordCount EQ 1>  <cfcookie name="USER_ID"   value="CheckUser.UserID"  expires="#DateFormat(DateAdd('d', 60, Now()), 'mm/dd/yy')#"   Secure="Yes">  <!--- If a result is returns, an error is thrown and message displayed. ---> <cfelse>  <cfabort showError="Invalid login. Go back and try again."> </cfif> 

This next example deletes the UserID cookie:

 <cfcookie name="OrderID" expires="Now"> 

NOTE

Starting in MX, it is okay to use <cfcookie> and <cflocation> on the same page. In earlier versions of ColdFusion, the cookie would not be created.


TIP

If you use the Secure attribute to specify that the cookie must be sent securely, it is sent only if the browser supports SSL. If the cookie can't be sent securely, it is not sent at all.


NOTE

Cookies are domain-specific, meaning they can be set so just the server that set them can retrieve them.


NOTE

Because <cfcookie> needs to write to the HTTP header, you can't use it if you've already flushed the header from the ColdFusion output buffer with <cfflush>.


See also <cfapplication>, <cfflush>


<cfdefaultcase>

Description: <cfdefaultfcase>, which must be used with a <cfswitch> statement, specifies a default case. <cfcase> can specify individual cases. <cfdefaultcase> has no attributes.

Syntax:

 <cfdefaultcase> HTML or CFML </cfdefaultcase> 

Example: The following example checks to see whether a state is a known state and displays an appropriate message:

 <!--- Evaluates passed expression (UCase(state)) ---> <cfswitch expression="#UCase(state)#"> <!--- If case matches CA, California is used. ---> <cfcase value="CA">California</cfcase> <!--- If case matches AR, Arkansas is used. ---> <cfcase value="AR">Arkansas</cfcase> <!--- If case matches MI, Michigan is used. ---> <cfcase value="MI">Michigan</cfcase> <!--- If case doesn't match, the following message is displayed. ---> <cfdefaultcase>One of the other 47 states</cfdefaultcase> </cfswitch> 

See also <cfswitch>, <cfcase>


<cfdirectory>

Description: <cfdirectory> is used for all directory manipulation, including obtaining directory lists and creating or deleting directories. <cfdirectory> is a flexible and powerful tag and has many attributes, some of which are mutually exclusive. The values passed to the action attribute dictate what other attributes can be used.

The attributes for <cfdirectory> are listed in Table B.36. The possible action values for <cfdirectory> are listed in Table B.37. List is assumed if no action is specified. Table B.38 contains the list of columns returned if action="List".

Table B.36. <cfdirectory> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Tag action

Optional; defaults to LIST if omitted.

directory

Directory name

Required.

filter

Filter spec

Optional; only valid if action="List". It can contain wildcard characters.

listInfo

Yes or No

Limits results query to just filenames. Improves performance.

mode

Permissions mode

Optional; only valid if action="Create". It is used only by the Solaris version of ColdFusion and is ignored by the Windows versions.

name

Query name

Required if action="List". Query to hold retrieved directory listing.

newDirectory

New directory name

Required if action="Rename"; ignored by all other actions.

recurse

"Yes or No"

Works when action="List or Delete" to perform action recursively.

sort

Sort order for use when action="List"

Optional comma-delimited list of columns to sort by; each can use Asc for ascending or Desc for descending. Default is ascending.


Table B.37. <cfdirectory> Actions

ACTION

DESCRIPTION

Create

Creates a new directory.

Delete

Deletes a directory. Will recurse when RECURSE="Yes"

List

Obtains a list of directory contents. Will recurse when RECURSE="Yes"

Rename

Renames a directory.


Table B.38. <cfdirectory> LIST Columns

ACTION

DESCRIPTION

Attributes

File attributes.

Datelastmodified

Last modified date.

Directory

Name of directory

Mode

Permissions mode (Solaris, HP-UX, and Linux only).

name

File or directory name

Size

Size in bytes.

Type

Type F for file or D for directory.


When action="LIST" is specified, the tag creates a query containing the file list from the specified directory.

Syntax:

 <cfdirectory   action="Action Type"   directory="Directory Name"  filter="Search Filter"  listInfo="Yes or No"   mode="Unix Permissions Mode"   name="Query Name"  newDirectory="New Directory Name"   recurse="Yes or No"  sort="Sort Order"> 

Example: This first example is a template that processes a form in which the user has specified a directory name. The example traps for errors:

 <!--- Sets trap for errors ---> <cftry>  <!--- Creates directory --->  <cfdirectory action="Create" Directory="#FORM.UserDir#">  <!--- Catches all errors --->  <cfcatch type="Any">  <!--- If error contains certain phrase, an error message   is displayed and processing stops --->  <cfif Cfcatch.Detail Contains "when that file already exists">  <P>Can't create directory: this directory already exists.  <!--- If error doesn't contain certain phrase, error details   are displayed. --->  <cfelse>  <cfoutput>#Cfcatch.Detail#</cfoutput>  </cfif>  <!--- Processing stops --->  <cfabort>  </cfcatch> </cftry> <P>Directory created. 

This next example retrieves a directory list, sorted by filename and while it is recursing sub-directories, it is including filenames. The resulting query is displayed in a table:

 <!--- Creates directory ---> <cfdirectory action="List"   directory="C:\INETPUB\WWWROOT\TEST\"  name="Stuff"  recurse="Yes"  listInfo="Yes"   SORT="Name"> <!--- Creates table from query ---> <cftable query="Stuff" colHeaders="Yes" htmlTable="Yes" border="Yes">  <cfcol header="<B>Name</b>" align="Left" text="Name">  <cfcol header="<B>Size</b>" align="Left" text="Size"> </cftable> 

CAUTION

Due to the inherent danger in using it, this tag can be disabled in the ColdFusion Administrator using Sandbox Security.


See also <cffile>


<cfdocument>

Description: <cfdocument> creates documents from ColdFusion output in either PDF or Flahspaper format. The attribute for this tag is presented in Table B.39.

Table B.39. <cfdocument> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

backgroundVisible

Yes or No

Optional; defaults to No. Yes will cause background to be printed when user prints the document.

encryption

128-bit or 40-bit or None

Optional; only works with PDF format. Defaults to None.

fontEmbed

Yes or No or Selective

Optional; defaults to Yes. Tell ColdFusion whether or not to embed fonts in output.

format

PDF or FlashPaper

Required.

filename

File name

Optional. Fully-qualified path to a file into which output should be saved. If omitted, output is streamed to the browser.

marginTop

Size in In. or cm

Optional. Size of top margin in inches (default). Set UNIT to cm to use centimeters instead.

marginBottom

Size in In. or cm

Optional. Size of bottom margin in inches (default). Set UNIT to cm to use centimeters instead.

marginLeft

Size in In. or cm

Optional. Size of left margin in inches (default). Set unit to cm to use centimeters instead.

marginRight

Size in In. or cm

Optional. Size of right margin in inches (default). Set Unit to cm to use centimeters instead.

name

Variable name

Optional. The output will be saved in this variable.

orientation

Portrait or Landscape

Optional; defaults to Portrait.

overwrite

Yes or No

Optional; defaults to No. Tells ColdFusion whether or not to overwrite the file (specified in Filename) if it already exists.

ownerPassword

Password

Optional when using PDF format. Specifies the file owner's password.

pageType

Page type

Optional; defaults to A4. The choices include: A4 (8.27 x 11.69 in), A5 (5.81 x 8.25 in), B5 (9.81 x 13.88 in), legal (8.5 x 14 in), letter (8.5 x 11) and Custom. When specifying Custom, you just provide PageHeight and pageWidth attributes.

Pageheight

Size in In. or cm

Optional. Specifies a custom height. Use with pageType=Custom.

pageWidth

Size in In. or cm

Optional. Specifies a custom width. Use with pageType=Custom.

permissions

Permission list

Optional. Use with PDF format. You can include one or more (separated in a comma-delimited list): AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly or AllowDegradedPrinting. Separate multiple permissions with a comma.

scale

Percentage less than 100

Optional, normally calculated by ColdFusion. It is used to reduce the size of the HTML output for display purposes.

unit

In or cm

Optional; defaults to In (inches).

userPassword

Password

Optional when using PDF format. Specifies the user password for the file.


Syntax:

 <cfdocument  backgroundVisible="Yes or No"  encryption="128-bit or 40-bit or None"  fileName="file name"  fontEmbed="Yes or No or Selective"  format="PDF or FlashPaper"  marginTop="Number of Inches or Centimeters"  marginBottom=" Number of Inches or Centimeters "  marginLeft=" Number of Inches or Centimeters "  marginRight="Number of Inches or Centimeters"  name="Variable name"  orientation="Portrait or Landscape"  overWrite="Yes or No"  ownerPassword="Password"  pageType="Page type"  pageheight=" Number of Inches or Centimeters "  pagewidth=" Number of Inches or Centimeters "  permissions="Permission list"  scale="percentage less than 100"  unit="In or CM"  userPassword="Password"> CFML And HTML </cfdocument> 

You can nest <cfdocumentitem> and <cfdocumentsection> tags in the body to specify page breaks, headers, footers, and different sections (with their own headers and footers).

Example: The following example demonstrates the creation of a multi-section document. Each section has its own header and footer. A page break is placed between the two sections. The document is being streamed to the browser as a PDF document.

 <!--- Get data for report ---> <cfquery name="GetDirectorSalary" dataSource="ows">   SELECT TOP 10 Salary, LastName & ' - ' & MovieTitle as DirectorFilm   FROM (FilmsDirectors FD INNER JOIN Directors D on FD.DirectorID = D.DirectorID)   INNER JOIN Films F on FD.FilmID = F.FilmID   ORDER BY Salary DESC </Cfquery> <!--- Produce document with 2 sections, each with its own  header and footer. Put a page break between them ---> <cfdocument  format="Pdf"  pageType="Letter"  orientation="landscape"  marginTop="1.5"  marginRight="1"  marginBottom="1.5"  fontEmbed="yes"> <!--- Create first section ---> <cfdocumentsection> <cfdocumentitem type="header"><H1>Section 1 Header</H1> </cfdocumentitem> <cfdocumentitem type="footer"> <cfoutput>#cfdocument.currentpagenumber# of  #cfdocument.totalpagecount#</Cfoutput></Cfdocumentitem> <table border="1" bgcolor="#00ffff" bordercolor="#0000ff"> <tr>   <th>Director - Film</th>   <Th>Salary</Th> </tr> <cfoutput query="getDirectorSalary"> <tr>   <td>#DirectorFilm#</Td>   <td>#DollarFormat(Salary)#</Td> </tr> </cfoutput> </table>  </cfdocumentsection> <!--- Create second section after pagebreak ---> <cfdocumentitem type="pagebreak" /> <cfdocumentsection> <Cfdocumentitem type="header"><h2>Section 2 Header</h2> </cfdocumentitem> <cfdump var="#GetDirectorSalary#"> <cfdocumentitem type="footer"> <cfoutput>#cfdocument.currentpagenumber# of  #cfdocument.totalpagecount#</cfoutput></cfdocumentitem> </cfdocumentsection> </cfdocument> 

See also <cfdocumentitem>, <cfdocumentsection>, <cfreport>, <cfoutput>


<cfdocumentitem>

Description: <cfdocumentitem> creates page breaks, headers, and footers inside <cfdocument> tag body. When used inside the body of a <cfdocumentsection> tag, headers and footers you create will apply just to that section. The one attribute, type, is required and can be set to either PAGEbREAK or Header or Footer. When set to either Header or Footer, you place the HTML, CFML or text that you want to appear in the header or footer.

Syntax 1:

 <cfdocumentitem type="Pagebreak" /> 

Syntax 2:

 <cfdocumentitem type="Header or Footer"> CFML / HTML </cfdocumentitem> 

Example: See <cfdocument> example.

See also <cfdocument>, <cfdocumentsection>, <cfreport>, <cfoutput>


<cfdocumentsection>

Description: <cfdocumentsection> is used in the body of a <cfdocument> tag to define a section, which may have its own header and/or footer and page margins. The attribute for this tag is presented in Table B.40.

Table B.40. <cfdocumentsection> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

marginTop

Size in In. or cm

Optional. Size of top margin in inches (default). Set UNIT to cm to use centimeters instead.

marginBottom

Size in In. or cm

Optional. Size of bottom margin in inches (default). Set UNIT to cm to use centimeters instead.

marginLeft

Size in In. or cm

Optional. Size of left margin in inches (default). Set UNIT to cm to use centimeters instead.

marginRight

Size in In. or cm

Optional. Size of right margin in inches (default). Set UNIT to cm to use centimeters instead.


Syntax:

 <cfdocumentsection  marginTop="Number of Inches or Centimeters"  marginBottom=" Number of Inches or Centimeters "  marginLeft=" Number of Inches or Centimeters "  marginRight="Number of Inches or Centimeters"> 

Example: See <cfdocument> example.

See also <cfdocument>, <cfdocumentitem>, <cfreport>, <cfoutput>


<cfdump>

Description: <cfdump> enables you to debug variable values. It can output the contents of simple variables, queries, structures, arrays, and serialized WDDX packets. The attribute for this tag is presented in Table B.41.

Table B.41. <cfdump> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

expand

Yes or No

Optional. Defaults to Yes. This expands the display when viewing structure data. Works in Mozilla and MSIE. May not work in some browsers.

label

Text label

Optional. A header label for the output produced.

var

Variable name

Required; name of variable to dump.


Syntax:

 <cfdump  exapnd="Yes or No"  label="Text label"   var="Variable Name"> 

Example: The following example dumps the contents of a variable immediately after it executes. The values being dumped get progressively more complex. Note how you must enclose variable names in the number sign. Note also that <cfdump> will work on nested types of variables.

 <!--- Creates variable ---> <cfset TheTime=Now()> <!--- Dumps content of variable ---> <cfdump VAR="#TheTime#"> <!--- Query gets data ---> <cfquery name="GetContacts"   dataSource="OWS">  SELECT LastName, FirstName  FROM Contacts </cfquery> <!--- Dumps contents of query ---> <cfdump VAR="#GetContacts#"> <!--- Creates variable with structure---> <cfset Meals=StructNew()> <!--- Populates variable ---> <cfset Meals["Breakfast"]="Cereal"> <cfset Meals["Lunch"]=StructNew()> <cfset Meals["Lunch"]["MainCourse"]="Sandwich"> <cfset Meals["Lunch"]["Beverage"]="Bloody Mary"> <!--- Dumps contents of variable ---> <cfdump var="#Meals#" expand="Yes"> 

See also <cftrace>, <cftimer>


<cfelse>

Description: The <cfelse> tag, which must be used with the <cfif> set of tags, is used to provide conditional branching logic. Like the <cfelseif> tag, the <cfelse> tag is entirely optional. Although you can use as many <cfelseif> tags as necessary in a <cfif> statement, you can use only one <cfelse>. If it is used, <cfelse> must always be the last compare performed.

Syntax:

 <cfif Condition>  <cfelseif Condition>  <cfelse> </cfif> 

Example: This example checks whether a FORM variable named Lastname exists:

 <!--- If the condition is met, a variable is set ---> <cfif IsDefined("FORM.LastName")> <cfset Lname=FORM.LastName)> <!--- If the condition is not met, an alternative variable is set ---> <cfelse> <cfset Lname="")> 

The following example is a complete conditional statement that uses <cfelseif> to perform additional comparisons. It also uses <cfelse> to specify a default for values that pass none of the compares:

 <!--- Checks if a value meets a condition ---> <cfif State IS "MI">  Code for Michigan only goes here <!--- If first condition is not met, checks if the value meets a second  condition ---> <cfelseif State IS "IN">  Code for Indiana only goes here <!--- If first or second conditions are not met, checks if a value meets  a third condition ---> <cfelseif (State IS "OH") OR (State IS "KY")>  Code for Ohio or Kentucky goes here <!--- If first, second, or third conditions are not met, the value is set ---> <cfelse>  Code for all other states goes here </cfif> 

See also <cfif>, <cfelseif>


<cfelseif>

Description: The <cfelseif> tag, which must be used with the <cfif> set of tags and the <cfelse> tag, is used to provide conditional branching logic. Like the <cfelse> tag, the <cfelseif> tag is entirely optional. Although you can use as many <cfelseif> tags as necessary in a <cfif> statement, you can use only one <cfelse>. If it is used, <cfelse> must always be the last compare performed.

Syntax:

 <cfif Condition>  <cfelseif Condition>  <cfelse> </cfif> 

Example: This example checks to see whether a FORM variable named Lastname exists:

 <!--- If the condition is met, a variable is set ---> <cfif IsDefined("FORM.LastName")>  <cfset Lname=FORM.LastName)> <!--- If the condition is not met, an alternative variable is set ---> <cfelse>  <cfset Lname="")> 

The following example is a complete conditional statement that uses <cfelseif> to perform additional comparisons. It also uses <cfelse> to specify a default for values that pass none of the compares:

 <!--- Checks if a value meets a condition ---> <cfif State IS "MI">  Code for Michigan only goes here <!--- If first condition is not met, checks if the value meets a second  condition ---> <cfelseif State IS "IN">  Code for Indiana only goes here <!--- If first or second conditions are not met, checks if a value meets  a third condition ---> <cfelseif (State IS "OH") OR (State IS "KY")>  Code for Ohio or Kentucky goes here <!--- If first, second, or third conditions are not met, the value is set ---> <cfelse>  Code for all other states goes here </cfif> 

See also <cfif>, <cfelse>


<cferror>

Description: <cferror> enables you to override the standard ColdFusion error messages and replace them with special error-handling templates that you specify. <cferror> requires that you specify the type of error message to be overridden and the template containing the error message to be displayed. Table B.42 provides attribute values.

Table B.42. <cferror> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

exception

Identifies the exception type

Required if the type is exception or monitor.

mailto

The administrator's email address

The email address of the administrator to be notified of error messages. This value is available with the error message template as #ERROR.MailTo#.

template

Error message template

Required; name of the template containing the error-handling code.

type

Type of error message

Optional; values are request, validation, and exception. If this attribute is omitted the default value of request is used. An error variable is created for REQUEST, monitor, and exception types. This is described in Table B.43. The values for validation errors are presented in Table B.44.


Four types of error messages are available in ColdFusion. REQUEST errors occur while processing a template, and VALIDATION errors occur when FORM field validation errors occur. Trapping for EXCEPTION errors enables you to trap any unhandled errors. You also can specify an EXCEPTION- handling template in the ColdFusion Administrator. Table B.43 shows the available error message variables for REQUEST, MONITOR, EXCEPTION error types. Table B.44 shows the available error message variables for VALIDATION error types.

You can't use CFML in error-handling templates for REQUEST errors; only HTML/JavaScript is allowed. Templates that handle EXCEPTION errors, however, are capable of using CFML. MONITOR, REQUEST, and EXCEPTION error-handling templates also have access to a special error structure named ERROR.

Syntax:

 <cferror type="Error Type"   template="Error Message Template  mailto="Administrator's email address"   exception="Exception type"> 

Table B.43. ColdFusion Error Message Variables for REQUEST, MONITOR, and EXCEPTION Error Types

VARIABLE

DESCRIPTION

ERROR.BROWSER

The browser the client was running, with version and platform information if provided by the browser.

ERROR.DATETIME

The date and time that the error occurred; can be passed to any of the date/time manipulation functions as necessary.

ERROR.DIAGNOSTICS

Detailed diagnostic error message returned by ColdFusion.

ERROR.GENERATEDCONTENT

Content generated by the failed template. This variable is not available to REQUEST error types.

ERROR.HTTPREFERER

URL of the page from which the template was accessed.

ERROR.MAILTO

Administrator's email address; can be used to send notification of the error.

ERROR.QUERYSTRING

The URL query string of the request.

ERROR.REMOTEADDRESS

Client's IP address.

ERROR.TEMPLATE

Template being processed when the error occurred.


Table B.44. ColdFusion Error Message Variables for the VALIDATION Error Type

VARIABLE

DESCRIPTION

ERROR.InvalidFields

List of the invalid form fields.

ERROR.ValidationFooter

Text for footer of error message.

ERROR.ValidationHeader

Text for header of error message.


Example: The following example establishes an error-message template for REQUEST errors in the application.cfm file and shows what an error template might look like:

 <!--- Application.cfm template ---> <!--- Application is created ---> <cfapplication name="MyApp"> <!--- Request errors ---> <cferror type="REQUEST"   name="ERROR_REQUEST.CFM"  mailto="admin@orangeWhipStudios.com"> <!--- Exception errors ---> <cferror type="EXCEPTION"   name="ERROR_EXCEPTION.CFM"> <!--- Error_Exception.cfm template ---> <!--- Mail with error details is sent to the administrator ---> <cfmail  from="system@orangeWhipStudios.com"  to="admin@orangeWhipStudios.com"  subject="Error on OWS application">  An error has occurred:  #ERROR.Detail# </cfmail> <html> <head>  <title>Application Error</title> </head> <body> <!--- If certain template is returned, an error message is displayed ---> <cfif Error.Template EQ "GetCustomers.cfm">  <h2>An error occurred getting customer records.</h2> <!--- If certain template is not returned, an alternative message is displayed ---> <cfelse>  <h2>An Error Has Occurred</h2> </cfif> <P>The administrator has been notified. </body> </html> </html> 

NOTE

The <cferror> tag is best used in the Application.cfm template.


<cfexecute>

Description: <cfexecute> enables you to execute processes on the ColdFusion server machine. <cfexecute> is frequently used to execute a server program at a regular interval using <cfschedule>. Table B.45 describes the tag attributes.

Table B.45. <cfexecute> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Name of executable

Required.

arguments

Any command-line parameters that must be passed

Optional; only used if the program needs to be passed command-line arguments.

outputFile

Pathname to file into which output from program should be written

Optional; if not specified, any output appears on the page in which this tag is used.

timeout

Number of seconds program should be given before it's timed out

Optional; defaults to 0. If 0 ColdFusion spawns another thread to execute the program.

variable

Variable name

Optional. Output is saved to the variable that you identify here.


NOTE

Don't put any CFML tags or functions between the start and end tags.


Syntax:

 <cfexecute name="ExecutableName"   arguments="CommandLine"  outputfile="Pathname For Output"   timeout="Time interval in seconds">  variable="Variable name" </cfexecute> 

Example: This example invokes PKZip to produce a user-specified Zip file by passing it an array of arguments:

 <!--- args array is created ---> <cfscript>  args = ArrayNew(1);  args[1] = "-a";  args[2] = "c:\temp\test.zip";  args[3] = "c:\inetput\wwwwroot\MyApp\UTIL.*"; </cfscript> <!--- Executes pkzip, passes arg array, and specifies output file ---> <cftry>  <cfexecute name="c:\utils\pkzip.exe "   arguments="#args#"  outputFile="C:\TEMP\TESTOUT.TXT">  </cfexecute> <!--- Catches and outputs any arguments ---> <cfcatch type="Any">  <cfoutput>#CFCATCH.Message#</cfoutput> </cfcatch> </cftry> 

NOTE

The arguments can be passed as an array or as a string.


See also <cfschedule>


<cfexit>

Description: <cfexit> aborts the processing of a custom tag without aborting processing of the calling template. When used in a regular template, <cfexit> acts just like <cfabort>. When called within a custom tag, however, <cfexit> does not terminate processing of the calling template (like <cfabort>), but instead returns processing to it. Table B.46 presents the values for the method attribute.

Table B.46. Methods Used in <cfexit>

METHODS

DESCRIPTION

ExitTag

Default; aborts current tag processing, similar to <cfabort>. If used in a custom tag, this causes processing to continue after end tag.

ExitTemplate

Exits the currently processing tag. If used where a custom tag's execution mode is Start, this will continue processing from the first child tag in the current custom tag's body. If used where a custom tag's execution mode is End, it will continue processing after the end tag.

Loop

Re-executes body in current custom tag. This method can be used only when a custom tag's execution mode is End. In this case, it will continue processing from the first child tag in the current custom tag's body. In all other contexts, it will return an error.


Syntax:

 <cfexit method="Method"> 

Example: This example checks whether a particular attribute was passed. It stops the custom tag's processing if the attribute is missing but enables processing to continue in the calling template after the custom tag:

 <!--- if attribute is not present, the custom tag stops processing ---> <cfif NOT IsDefined("ATTRIBUTES.MyAttrib")>  <cfexit> </cfif> 

See also <cfabort>


<cffile>

Description: <cffile> is used to perform file-management operations, including uploading files from a browser; moving, renaming, copying, and deleting files; and reading and writing files. Table B.47 shows the tag attributes for <cffile>.

Table B.47. <cffile> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

accept

File type filter

This optional attribute restricts the types of files that can be uploaded, and can be used only if action is UPLOAD. The filter is specified as a MIME type ("image/*", which allows all image types, but nothing else); multiple MIME types can be specified separated by commas.

action

Desired action

This attribute is required.

destination

Destination file location

This attribute can be used only if action is one of the following: COPY, MOVE, REname, or UPLOAD. Destination can be a filename or a fully qualified file path.

file

Name of local file to access

This attribute can be used only if action is APPEND, DELETE, READ, READBINARY, or WRITE, in which case it is required.

fixNewLine

Use OS-specific end-of-line characters

Optional; defaults to No, which means that default line-ending characters will be embedded in strings. Works in conjunction with action="Write" and action="Append".

fileField

Name of the file type

This attribute can be used only if <input> containing action is upload, in which case it is the file required.

mode

Identifies file access permissions for uploaded file

This is used only in Unix-type installations. See Table B.48.

nameConflict

What to do in case of name conflicts

This optional attribute can be used if action is upload. It specifies the course to take if a name conflict arises from the upload.If this attribute is omitted, the default value of "ERROR"is used.

output

Text to output to file

This attribute can be used only if action is write or append.

result

Variable name

Alternate name for variable which stores results.

source

Source filename

Name of the source file to be written to, copied, or moved. Can be used only if action is copy, move, or rename.

variable

Variable to store file

This attribute can be used only if contents of read action is read or readbinary, in which case it is required.


<cffile> is a flexible and powerful tag; it has several attributes, many of which are mutually exclusive. The values passed to the action attribute dictate which other attributes can be used. These values are described in Table B.48. Table B.49 describes the options you have when dealing with filename conflicts arising from file upload operations.

Table B.49. File Upload Name Conflict Options

OPTION

DESCRIPTION

error

The file will not be saved, and ColdFusion will immediately terminate template processing.

skip

Neither saves the file nor generates an error message.

overwrite

Overwrites the existing file.

makeunique

Generates a unique filename and saves the file with that new name. To find out what the new name is, inspect the #FILE.ServerFile# field.


<cffile> creates a FILE object after every <cffile> operation. You can use the variables in this object as you would any other ColdFusion variables, enabling you to check the results of an operation. You can provide your own name for this variable using the RESULT attribute. However, only one FILE object exists, and as soon as you execute a new <cffile> tag, the prior FILE object is overwritten with the new one. FILE object variables are described in Table B.50.

Table B.50. <cffile> FILE Object Variables

FIELD

DESCRIPTION

FILE.ATTEMPTEDSERVERFILE

The original attempted filename; will be the same as FILE.ServerFile unless the name had to be changed to make it unique.

FILE.CLIENTDIRECTORY

The client directory from where the file was uploaded, as reported by the client browser.

FILE.CLIENTFILE

The original filename as reported by the client browser.

FILE.CLIENTFILEEXT

The original file extension, as reported by the client browser.

FILE.CLIENTFILEname

The original filename as reported by the client browser, but without the file extension.

FILE.CONTENTSUBTYPE

The MIME subtype of an uploaded file.

FILE.CONTENTTYPE

The primary MIME type of an uploaded file.

FILE.DATELASTACCESSED

The last date and time the file was accessed.

FILE.FILEEXISTED

Yes if file already existed; No if not.

FILE.FILESIZE

Size of file that was uploaded.

FILE.FILEWASAPPENDED

Yes if file was overwritten; No if not.

FILE.FILEWASOVERWRITTEN

Yes if file was overwritten; No if not.

FILE.FILEWASREnameD

Yes if file was renamed; No if not.

FILE.FILEWASSAVED

Yes is file was saved; No if not.

FILE.OLDFILESIZE

Size of file that was overwritten.

FILE.SERVERDIRECTORY

The server directory in which the uploaded file was saved.

FILE.SERVERFILEEXT

The file extension of the uploaded file on the server (does not include period).

FILE.SERVERFILE

The name of the file as saved on the server (takes into account updated filename if it was modified to make it unique).

FILE.SERVERFILEname

The name of the uploaded file on the server, without an extension.

FILE.TIMECREATED

Time when the file was uploaded.

FILE.TIMELASTMODIFIED

Date and time uploaded file was last modified.


Syntax:

 <cffile accept="Filter"   action="Action Type"  destination="Destination Directory or File Name"   file="File Name"  fixnewline="Yes or No"  fileField="Field Containing File Name"   nameConflict="Conflict Option"  output="Text To Output"  result="Variable name"  source="Source File Name"  variable="Variable Name"> 

Table B.48. <cffile> Actions

ACTION

DESCRIPTION

append

Appends one text file to the end of another.

copy

Copies a file.

delete

Deletes a specified file.

move

Moves a specified file from one directory to another, or from one filename to another.

read

Reads the contents of a text file.

readbinary

Reads the contents of a binary file.

rename

Does the same thing as MOVE; see MOVE.

upload

Receives an uploaded file.

write

Writes specified text to the end of a text file.


NOTE

If you do not specify a fully qualified file path, the path is assumed to be relative to the ColdFusion temporary directory. The GetTempDirectory() function can be used to determine the ColdFusion temporary directory.


NOTE

When you use <cffile> to read a file, if the file starts with a byte order mark, ColdFusion will use the BOM to determine the characters set for the file.


Note that when you're uploading files under a Unix-type operating system, you also can use the optional MODE attribute. The possible values for MODE are described in Table B.51.

Table B.51. Mode Values Used When Uploading to Unix Systems

MODE

DESCRIPTION

644

Assigns owner read/write and assigns other/group read permissions.

666

Assigns read/write permissions to all.

777

Assigns read, write, and execute permissions to all.


Example: The two basic categories of use for <cffile> are uploading files and file management, including copying, moving, renaming, and so on.

The following example includes both types of use. It includes a form that is used to specify a file to be uploaded and the <cffile> code from the form's action template that does the uploading.

It checks to ensure the file is less than 50K (this arbitrary file size was chosen just to illustrate the use of the CFFILE variable). The example uses <cftry> and <cfcatch> tags to trap this user-defined error. If the file is less than 50K, the progress is reported to the user.

It then checks the file extension to ensure that it is a GIF. This again is arbitrary and is included just to demonstrate this technique for limiting file types that can be uploaded.

The last part of the example moves the file to a different directory and reports to the user.

 <!--- Code in the upload form. Must use ENCtype=MULTIPART/FORM-DATA ---> <form enctype="MULTIPART/FORM-DATA"   action="Upload_Action.cfm"   method="POST"> <!--- An INPUT of type FILE is required ---> <P>File to upload:  <input type="FILE"   name="UploadFile"   SIZE="40"> <P><input type="submit"   name="Upload"   value="Upload"> </form> <!--- Code in the upload form's action template ---> <cftry> <cffile  action="Upload"  filefield="UploadFile"  destination="D:\TEMP\"  nameconflict="MakeUnique"> <!--- Make sure file isn't more than 50k ---> <cfif cffile.FileSize GT 51250>  <cfthrow type="SizeError"   message="File too large. Can't be more than 50k."> </cfif> <cfif CFFILE.ClientFileExt NEQ "gif">  <cfthrow type="ExtError"  message="File is wrong type. You can only upload GIF files."> </cfif> <cfcatch type="SizeError">  <cfabort showerror="#CFCATCH.Message#"> </cfcatch> <cfcatch type="ExtError">  <cfabort SHOWERROR="#CFCATCH.Message#"> </cfcatch> </cftry> <!--- Report on status to user ---> <P>File uploaded successfully: <cfoutput>  <P>Filename on client: #CFFILE.ClientFile#  <P>Filename on server: #CFFILE.ServerFile#  <P>File size: #CFFILE.FileSize# </cfoutput> <!--- Now move file to a different folder ---> <cffile  action="Move"  source="D:\TEMP\#CFFILE.ServerFile#"  destination="D:\JUNK\#CFFILE.ServerFile#"> <P>File successfully moved to D:\JUNK\<cfoutput>#CFFILE.ServerFile#</cfoutput> 

CAUTION

Be careful to use <cflock> when using <cffile> because it uses a shared resource (the server's file system) that multiple ColdFusion threads can try to access simultaneously.


See also <cfdirectory>, <cfftp>, <cflock>


<cfflush>

Description: <cfflush> flushes ColdFusion's output buffer, sending the contents back to the Web browser. You can control the point at which the flush takes place with the INTERVAL attribute by entering the number of bytes. The attributes for this tag are presented in Table B.52.

Syntax:

 <cfflush interval="number of bytes"> 

Table B.52. <cfflush> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

interval

Number of bytes

Optional; specifies number of bytes that must be accumulated before buffer is flushed.


NOTE

Several ColdFusion tags are used to write data into the ColdFusion output buffer, including <cfheader>, <cfhtmlhead>, <cfcookie>, <cfform>, <cfcontent>, and <cflocation>. A run error will be generated if you try to use these tags after having flushed part of the HTML document (such as the HTTP header or HTML <head>) to which these tags need to write.


Example: The following example employs <cfflush> to get some output out of the buffer as a page with many queries is built. This gives the user some intermediate feedback as to what is taking place.

 <!--- Query gets all films ---> <cfquery name="GetAllFilms" dataSource="OWS">  SELECT *  FROM Films </cfquery> <!--- Query results are flushed to browser ---> <h1>Retrieved all Films</h1> <cfflush> <!--- Query gets all actors ---> <cfquery name="GetAllActors" dataSource="OWS">  SELECT *  FROM Actors </cfquery> <!--- Query results are flushed to the browser ---> <h1>Retrieved all Actors</h1> <cfflush> <!--- Query gets all films and actors ---> <cfquery name="GetAllFilmsActors" dataSource="OWS">  SELECT *  FROM FilmsActors </cfquery> <h1>Retrieved Everything</h1> 

<cfform>

Description: <cfform> is an alternative to the standard HTML <form> tag. The <cfform> tag is not useful by itself. However, it enables you to use other tags (<cfgrid>, <cfinput>, <cfselect>, <cfslider>, <cftree>, or any Java applets of your own using <cfapplet>), which do add a great deal of functionality to HTML forms. The code generated by <cfform> can be either standard HTML (and JavaScript code), Flash, or XML (formatted with an XSLT file). The attributes for this tag are presented in Table B.53.

Note that ColdFusion can create JavaScript functions and event handlers in the code that is returned to the browser. These functions are necessary to provide the functionality you specify in your input objects, such as required fields and other validations.

Syntax:

 <cfform   name="form name"   action="Action Page"  method="Post or Get"  format=" HTML or Flash or XML"  style=" specification"   preserveData="Yes or No"  onSubmit="Javascript"  scriptsrc="/books/2/448/1/html/2/path to JS file"  codeBase="URL"  archive="URL"  width="pixels or %"  height="pixels or %"  skin="Flash skin or XSL file"  preloader="Yes or No"  timeout="seconds"    encType="Internet media type"    onLoad="onLoad event routine"  ONrESET="onReset event routine"  TARGET="window or frame name" >…</cfform> 

Table B.53. <cfform> Attributes

ATTRIBUTE

AVAILABLE

DESCRIPTION

NOTES

name

All

Form name

Optional; if used, you must ensure that the form name is unique. ColdFusion will generate a name if you don't specify either a name or an ID. Defaults to CFForm_n.

action

All

Form action page

Optional; page to be invoked when this form is submitted..

method

All

Post or Get

Optional; defaults to Post.

format

All

HTML, Flash, XML

Optional; defaults to HTML. When HTML, child tags like <cfgtree> can be rendered in Flash or applet format. When Flash, all child controls are in Flash. When XML, generates XForms compliant XML in a results variable specified by name. You can specify a skin in skin attribute.

style

All

Style specification

Optional; passed as attribute when FORMAT=HTML or XML. When format=Flash, must be in CSS form.

preserveData

All

Yes or No

Optional; defaults to No. Determines values of some form controls when form submits to itself. When set to No, submitted values will not be reflected when form is displayed after submission. When set to Yes, the form values will reflect the submitted values. Applies to <cfslider>, <cfinput>, <cfselect>, <cftree>, <cfgrid>.

onSubmit

All

JavaScript onSubmit code

Optional; JavaScript to be executed prior to form submission.

scriptSrc

All

URL to script file

Optional; URL, relative to web-root, to Javascript code file (cfform.js), used by this tag and its children. Defaults to XSL skins directory for XML forms. It's normally in the /CFIDE/scripts/ directory, but some hosting situations may prevent using the script there.

width

Flash, XML

Width of form

Optional; defaults to 100% in Flash. Specify in pixels in XML.

height

Flash, XML

Height of form

Optional; defaults to 100% in Flash. Specify in pixels in XML.

skin

Flash, XML

Skin format instructions

When format=Flash, skin determines color for highlighted and selected elements. Defaults to haloGreen. When format=XML, defaults to default.xsl, but can be set to a ColdFusion skin name, XSL file name, "none", "default" or omitted. CF skins are located in cf_webroot\CFIDE\scripts\xs

preLoader

Flash

Yes or No

Defaults to Yes. Specifies whether or not to display progress bar when form is loading.

timeout

Flash

Integer in seconds

Defaults to 0, which prevents data from being cached. Indicates how long to keep form in Flash cache on server.

archive

HTML, XML

URL to Java classes

Optional; may be needed in some hosting situations. Used for <cfgrid>, <cfslider> and <cftree>. Defaults to /CFIDE/classes/cfapplets.jar. If this is inaccessible, you can specify an alternate URL.

codebase

HTML, XML

URL to plugin for IE

Optional; may be needed in some hosting situations. Defaults to /CFIDE/classes/cf-j2re-win.cab. If this is inaccessible, you can specify an alternate URL.

class

HTML, XML

  

enctype

HTML, XML

MIME type used to

Optional; default value is encode data sent via application/x-www-form-urlencoded.

nameID

HTML, XML

  

onLoad

HTML, XML

JavaScript OnLoad code

Optional ;Javascript code to be executed when form is loaded.

onReset

HTML, XML

JavaScript onReset code

Optional; JavaScript to be executed when form is reset.

TARGET

HTML, XML

Target window

Optional target window.


Example: The following is a simple <cfform>:

 <!--- ColdFusion form with class PASSTHROGH ---> <cfform action="Test_Action.cfm""DataEntry"""> <P>First Name: <cfinput name="FirstName" required="Yes"  MESSAGE="You must enter a First Name."> <P>Last Name: <cfinput name="LastName" required="Yes"  message="You must enter a Last Name."> <input type="Submit" value="Save"> </cfform> 

Note that the CLASS attribute and value will be passed through ColdFusion to the browser. Here is some of the code that is returned to the browser by ColdFusion:

 <!--- ColdFusion form with JavaScript ---> <form name="DataEntryTest"   action="Test_Action.cfm"   method=POST  onSubmit="return CF_checkCFForm_1(this)"   > <P>First Name: <input type="Text" name="FirstName"> <P>Last Name: <input type="Text" name="LastName"> <input type="Submit" value="Save"> </form> 

You can see that ColdFusion passed the CLASS attribute/value pair through to the browser. Also note how it added the onSubmit() JavaScript event to the <form> tag. This is due to the use of <cfinput> to produce required fields. ColdFusion also creates the JavaScript function CF_CheckCFForm_1() to process the required field validation.

NOTE

<cfform> automatically embeds method="POST" in your form.


NOTE

Because <cfform> must write to the HTML <head>, you can't use it if you've already flushed the <head> from the ColdFusion output buffer with <cfflush>.


See also <cfapplet>, <cfgrid>, <cfinput>, <cfselect>, <cfslider>, <cftextarea>, <cftree>, <cfformgroup>, <cfformitem>


<cfformgroup>

Description: <cfformgroup> is used in the body of <cfform> tag to break down the display of the various form elements into groups. It works only in Flash and XML format forms. Its use is ignored in HTML forms.

Note that <cfformgroup> must be used with </cfformgroup>. It can contain any of these as child tags in its body:

  • <cfformgroup>

  • <cfformitem>

  • <cfcalendar>

  • <cfgrid>

  • <cfinput>

  • <cfselect>

  • <cftextarea>

  • <cftree>

When used in XML format forms, it is the responsibility of the XSLT skin to format the <cfformgroup> and other tags. The basic skin employed by ColdFusion supports only the horizontal, vertical, and dualselectlist styles, but you can use any XForms group type that is defined in the XSLT.

Table B.54 lists its attributes. There are two syntax options. Set TYPE to Repeater to create the groups based on a query result. When you want to create the groups one at a time, use Syntax 2 and specify the appropriate value for TYPE, based on whether you are using a Flash or XML format form. When TYPE is set to Repeater, ColdFusion will build a group (containing all of the child tags in the body of <cfformgroup>) for each row in the query result.

Table B.54. <cfformgroup> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

height

in Pixels

Optional; used in non-repeater type groups. Specifies height of the group container.

label

Text label

Optional; provides a label for the tab or page when any of the following types are used: Page, Panel. It is ignored when TYPE is Repeater, Hbox, Hdividedbox, Vbox, Vdividedbox, Tile, Accordion, or Tabnavigator.

maxRows

Integer

Optional; used in Repeater type groups. Indicates the maximum number or query result rows to use to build the form repeater.

query

Query name

Required in Repeater type form groups.

selectedIndex

Integer

Optional; only works when TYPE is set to Accordion or TabNavigator. Indicates which tab or page to display by default.

startRow

Query row number

Optional; defaults to 0. Indicates which row in the query result should be used to begin the display of repeaters. Only useful in Repeater type groups. Note that the first row is considered 0, unlike in other ColdFusion functions in which 1 is considered the first.

style

Style specification

Optional. In Flash forms, it must be CSS type specification. In XML forms, the attribute is passed through to the XML.

type

Type of group

Required. In XML forms, it can be any XForms group type defined in you XSLT. In Flash forms, you must use a type specified below. All the type options are described in Table B.55 below.

width

in Pixels

Optional; used in non-repeater type groups. Specifies width of the group container.


Syntax 1:

 <cfformgroup    type="Repeater"   query="Query"   startRow="Integer"   maxRows="Integer"> Various form elements </cfformgroup> 

Syntax 2:

 <cfformgroup    type="Type for Flash or XML"   label="Label"   style="Style Specification"   selectedIndex="Page number">   width="Pixels"   height="Pixels"> Various form elements </cfformgroup> 

Table B.55. TYPE Attribute Values

FORMAT

TYPE

DESCRIPTION

XML

Horizontal

Aligns child tags horizontally within form. Each child tag's label is placed to its left.

XML

Vertical

Aligns child tags vertically within form. Each child tag's label is placed to its left.

XML

FieldSet

Groups children by drawing a box around them, like the HTML <fieldset> tag. The value you use in the LABEL attribute will be used as a "legend" at the top of the group. You can use another <cfformgroup> inside this group to align tags vertically, for example.

Flash

Repeater

Generates a new instance of <cfformgroup> child tags for each row in the query result.

Flash

Horizontal

Aligns child tags horizontally. This tag's LABEL value will appear to the left of the children tags.

Flash

Vertical

Aligns child tags vertically. This tag's LABEL value will appear to the left of the children tags.

Flash

HBox

Used to align children groups horizontally. Not used to align individual controls (use Horizontal for that purpose).

Flash

VBox

Used to align children groups vertically. Not used to align individual controls (use Vertical for that purpose).

Flash

HDividedBox

Aligns each child horizontally, in a bordered box. Each bordered box also provides user with ability to move and change the relative sizes of the children. It is to be used to align groups, not individual tags.

Flash

VDividedBox

Aligns each child vertically, in a bordered box. Each bordered box also provides user with ability to move and change the relative sizes of the children. It is to be used to align groups, not individual tags.

Flash

Panel

Creates a bordered panel container. Text in its title bar is determined by the value of LABEL. Child tags are arranged vertically in the content area.

Flash

Tile

Child tags are aligned in a grid.

Flash

TAbNavigator

Creates a tab type container for child tags. Each tab is to be defined with a child <cfformgroup type="Page" …>.

Flash

Accordion

Presents a pleated accordion container. Each pleat can be expanded or contracted. Each pleat is to be defined with a child <cfformgroup type="Page" …>.

Flash

Page

Aligns child tabs vertically in a parent <cfformgroup> of TYPE Accordion or TabNavigator.


Example: This example builds a <cfform> using Flash with a number of <cfformgroup> tags an other children tags. Note that a group of radio buttons is built dynamically from a query result:

[View full width]

<!--- Get list of user roles for radio buttons ---> <cfquery name="getUserRoles" dataSource="ows"> SELECT UserRoleID, UserRoleName FROM UserRoles </cfquery> <html> <head>CFFormGroup and CFFormItem Example</head> <body> <!--- If the form has been submitted (to itself), Then the form.beenHere var will exist. In this case we'll display the form contents ---> <Cfif IsDefined("form.beenHere")> <H3>You submitted this info:</H3> <cfdump var="#Form#"><Br><Br><br> </cfif> <cfform name="myform" height="450" width="500" format="Flash"> <!--- This item just presents formatted text ---> <cfformitem type="html"> <b>This form has two sections:</B> <Ul> <Li>Contact information</Li> <Li>Security information</Li> </Ul> </cfformitem> <!--- Use a accordion with two pages ---> <cfformgroup type="accordion" height="310"> <!--- First page is contact information ---> <cfformgroup type="page" label="Contact Information"> <!--- Align the first and last name fields horizontally ---> <cfformgroup type="horizontal" label="Name"> <cfinput type="text" required="Yes" name="FirstName" label="First" value="" width="100"/> <cfinput type="text" required="Yes" name="LastName" label="Last" value="" width="160"/> </cfformgroup> <cfinput type="text" name="Email" label="email" size="30" maxlength="100"> <cfinput type="text" name="phone" validate="telephone" required="Yes" size="30" label="Phone Number"> </Cfformgroup> <!--- Second page is for security info ---> <cfformgroup type="page" label="Security Infomration"> <cfformitem type="HTML" height="30"> <b>Security info</B> </Cfformitem> <cfformgroup type="hbox"> <!--- User name and password ---> <cfformgroup type="vbox"> <cfformitem type="text" height="20"> User name: </cfformitem> <cfformgroup type="Vertical"> <cfinput type="text" name="Username" label="User name" bind="{FirstName.text}.{LastName.text}"> <cfinput type="text" name="password" label="Password"> <cfinput type="password" name="Confirm" label="Confirm"> <cfformitem type="html"> <font size="-2">Username is bound to firstname and lastname using the Flash BIND syntax</font> </cfformitem> </cfformgroup> </cfformgroup> <!--- Group for user roles ---> <cfformgroup type="vbox"> <cfformitem type="text" height="20"> User role: </cfformitem> <cfformgroup type="tile" width="200" label="Tile box"> <!--- a grid is used to align a group of radio buttons ---> <cfoutput query="getUserRoles"> <!--- the radio buttons are populated by a query result ---> <cfinput type="Radio" name="Role" label="#UserRoleName#" checked="#Iif(userRoleID EQ 5, de('True'), de('False'))#" value="#UserRoleID#"> </cfoutput> </cfformgroup> </cfformgroup> </cfformgroup> </cfformgroup> </cfformgroup> <!--- Preent buttons to submit or reset ---> <cfformgroup type="horizontal"> <cfinput type = "submit" name="submit" width="120" value = "Show Form Data"> <cfinput type = "reset" name="reset" width="120" value = "Reset"> <cfinput type = "hidden" name="beenHere" value = "Yes"> </cfformgroup> </cfform> </body> </html>

See also <cfapplet>, <cfgrid>, <cfinput>, <cfselect>, <cfslider>, <cftextarea>, <cftree>, <cfformitem>


<cfformitem>

Description: <cfformitem> is used in the body of <cfform> or <cfformgroup> tags to text, spacers and lines within forms. It works only in Flash and XML format forms. Its use is ignored in HTML forms. When TYPE is hrule, VRule or Spacer, you don't include </cfformitem>. When TYPE is HTML or Text, you do include </cfformitem>. Table B.56 lists its attributes.

Table B.56. <cfformitem> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

bind

Flash bind expl

Optional; a bind expression. This is used to populate the item based on the contents of other items.

height

in Pixels

Optional; indicates item height in pixels.

style

Style specification

Optional. In Flash forms, it must be CSS type specification. In XML forms, the attribute is passed through to the XML.

type

Type of item

Required; indicates what type of item is being employed. These are described in detail in Table B.57.

width

in Pixels

Optional; indicates item width in pixels.


Table B.57. (CONTINUED)

FORMAT

TYPE

DESCRIPTION

Flash

HTML

Enables you to include HTML formatted text in the form. In Flash forms you are limited to using the following formatting tags: <a>, <b>, <br>, <font>, <i>, <img>, <li>, <p>, <textformat>, and <u>.

Flash

Text

Enables you to include plain text, verbatim (including white space) but no formatting.

Flash

Spacer

Enables you to include blank space of specified height and width.

Flash

hrule

Childless tag that simply includes a horizontal rule in the form.

Flash

VRule

Childless tag that simply includes a vertical rule in the form.

XML

HTML

Includes the CFML tag's body text in a CDATA section in an XML xf:output element.

XML

Text

Formats the CFML tag's body text for XML and puts it in a CDATA section. Generates an XML xf:output element.

XML

Spacer

Enables you to include blank space of specified height and width.

XML

hrule

Puts an <hr> tag in the output. Use STYLE to specify rule characteristics, including height and width. This tag must not have any children. Include no children in the tag.

XML

any other string

Generates an XML xf:group element with the TYPE name as the appearance attribute. The CFML tag body is put in a CDATA section in a cf:attribute name="body" element. These are ignored by the XSL transforms provided with ColdFusion.


Syntax 1:

 <cfformitem    height="Pixels"   style="Specification"   type="HRule or VRule or Spacer"    width="Pixels" /> 

Syntax 2:

 <cfformitem    bind="Flash bind expression"   height="Pixels"   style="Specification"   type="Text or HTML"   width="Pixels"> …Text or HTML… </cfformitem> 

Example: See the example in <cfformgroup>.

See also <cfapplet>, <cfgrid>, <cfinput>, <cfselect>, <cfslider>, <cftextarea>, <cftree>, <cfformgroup>


<cfftp>

Description: <cfftp> is the ColdFusion interface to the Internet standard file transfer protocol. It enables your ColdFusion program to function as an FTP client, interacting with remote file systems. It is a very powerful and complex tag; Table B.58 lists its attributes. Values for the action attribute are presented in Table B.59. Table B.60 lists the status variables for <cfftp>.

Table B.58. <cfftp> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required.

asciiExtensionList

ASCII extensions

Optional; semicolon-delimited list of extensions to be treated as ASCII extensions if using transferMode of "AutoDetect," default is "txt;htm;html;cfm;cfml;shtm; shtml;css;asp;asa."

attributes

Attributes list

Comma-delimited list of attributes; specifies the file attributes for the local file. Possible values are Readonly, Hidden, System, Archive, Directory, Compressed, Temporary, and Normal.

connection

Connection name

Optional; used to cache connections to perform operations without logging in again.

directory

Directory on which operation is to be performed

Required if action is Changedir, Createdir, Listdir, or Existsdir.

existing

Current name of file or directory on remote system

Required if action is Rename.

failIfExists

Yes or No

Optional; indicates whether a Getfile action will fail if a local file with the same name already exists; defaults to Yes.

Item

Item (file) name

Required if action is Exists or Remove.

localFile

Local filename

Required if action is Getfile or Putfile.

name

Query name

Required if action is LISTDIR; see Table B.52 for column list.

new

New item (file) name when file is being renamed

Required if action is rename.

passive

Allows you to enable or disable passive mode

Optional; defaults to No.

password

Login password

Required when action is OPEN.

proxyserver

Name of proxy server

Used if you must go through a proxy server.

port

Server port

Optional attribute; defaults to 21.

remotefile

Remote filename

Required if action is Existsfile, Getfile, Or Putfile.

result

Variable name

Optional. Enables you to specify an alternative variable name to store result information. The default is CFFTP, but this attributes enables you to specify a different variable name.

retryCount

Number of retries

Optional retry count; defaults to 1.

server

Server name; DNS or address of FTP server.

Required when not using an IP cached connection.

stopOnError

Yes or No

Optional; defaults to No. When it's No, tHRee status variables are produced, as found in Table B.53.

timeout

Timeout seconds

Optional; timeout value in seconds.

transferMode

Transfer mode

Optional; values can be ASCII, Binary, or Autodetect (default).

userName

Login username

Required when action is OPEN.


Table B.59. <cfftp> Actions

ACTION

DESCRIPTION

changeDir

Changes directory.

close

Closes a cached connection.

createDir

Creates a directory.

exists

Checks whether an object exists.

existsDir

Checks for a directory's existence.

existsFile

Checks for a file's existence.

getCurrentDir

Gets current directory.

getcurrentUrl

Gets current URL.

getFile

Retrieves a file.

listDir

Retrieves directory list.

open

Opens a cached connection.

putFile

Sends a file.

remove

Deletes a file.

removeDir

Removes a directory.

rename

Renames a file.


Table B.60. <cfftp> Status Variables

VARIABLE

DESCRIPTION

CFFTP.ErrorCode

Error codes (see Table B.62).

CFFTP.ErrorText

Error text.

CFFTP.ReturnValue

One of several values, described below, based on the value of the action attribute.

CFFTP.Succeeded

Success; Yes or No.


When calls to <cfftp> are completedassuming stopOnError is set to No (the default)a series of variables is set so you can determine the success or failure of the operation. Table B.61 lists the complete set of error codes and their meanings.

Table B.61. <cfftp> Query Columns

COLUMN

DESCRIPTION

ATTRIBUTES

Comma-delimited list of attributes.

ISDIRECTORY

Yes if directory; No if file.

LASTMODIFIED

Date and time last modified.

LENGTH

File length.

MODE

An octal format string listing Unix permissions.

name

Object name.

PATH

Full path to object.

URL

Full URL to object.


<cfftp> can be used to retrieve remote directory lists. Lists are returned in ColdFusion query format, and Table B.62 lists the query columns.

<cfftp> is designed to be used in two ways: either for single operations or to batch operations together. To use the batch mode (called cached mode), you must specify a unique name in the connection attribute that you can use in future <cfftp> calls.

Syntax:

 <cfftp action="Action"   agentNAme=""  asciiExtensionList="List"  attributes="Attributes"   connection="Connection Name"   directory="Directory"  existing="Name"   failIfExists="Yes or No"   item="Name"   localFile="Name"  name="Query Name"   new="Name"   passWord="Password"   port="Port" proxyServer="IP/server name"   remoteFile="Name"  result="Variable name"  retryCount="Count"  server="Server Address"  stopOnError="Yes or No"  timeOut="Seconds"   transferMode="Mode"   userName="User Name"> 

Here are the possible values of CFFTP.ReturnValue. Which gets returned is a function of the value of the action attribute:

  • A string is returned when action=getCurrentDir or action=getCurrentUrl

  • A Yes or No is returned if the action is set to exists, existDir or existsFile

NOTE

The status variables in Table B.60 are produced only when the stopOnError attribute is set to No. It's set to Yes by default.


Table B.62. <cfftp> Error Codes

CODE

DESCRIPTION

0

Operation succeeded.

1

System error (OS or FTP protocol error).

2

An Internet session could not be established.

3

FTP session could not be opened.

4

File transfer mode not recognized.

5

Search connection could not be established.

6

Invoked operation valid only during a search.

7

Invalid timeout value.

8

Invalid port number.

9

Not enough memory to allocate system resources.

10

Can't read contents of local file.

11

Can't write to local file.

12

Can't open remote file for reading.

13

Can't read remote file.

14

Can't open local file for writing.

15

Can't write to remote file.

16

Unknown error.

18

File already exists.

21

Invalid retry count specified.


CAUTION

Because it can be rather dangerous, <cfftp> can be disabled using the Basic Security settings in the ColdFusion Administrator.


Example: The following example opens a connection and caches it using the CONNECTION attribute. It reads the directory and outputs the resulting query (identified by the name attribute). This query is then displayed with a simple <cftable>.

The next call to <cfftp> uses the cached connection named in the first call. It is used to upload a file from the local ColdFusion server to the remote FTP server by using the putfile action. It then displays the value of the CFFILE.Succeeded to verify the success.

If the file was uploaded successfully, the file is deleted and the operation's success is displayed. A new directory listing is displayed.

 <!--- FTP server is queried for directory listing ---> <cfftp server="ftp.someserver.com"  username="joeuser"  passWord="myPassword"  action="LISTDIR"  directory="c:\temp\"  name="MyDocs"  connection="MyConn"> <html> <head>  <title>CFFTP Example</title> </head> <body> <!--- Contents of FTP query is displayed in a table ---> <P>Directory of files <cftable border="Yes" htmltable="yes" query="MyDocs">  <cfcol header="Name" text="#Name#" align="LEFT">  <cfcol header="Length" text="#Length#" align="RIGHT"> </cftable> <!--- Uploads file and outputs results ---> <cfftp  action="putfile"  localFile="c:\temp\tcmnote.txt"  remoteFile="c:\temp\tcmnote.txt"> <p>Uploaded? <cfoutput>#CFFTP.Succeeded#</cfoutput> <!--- If upload succeeds, temp file is removed ---> <cfif CFFTP.Succeeded>  <cfftp action="remove" item="c:\temp\tcmnote.txt"> <!--- If delete succeeds, temp file is removed and results  are outputted---> <p>tcmote.txt Deleted? <cfoutput> #CFFTP.Succeeded#</cfoutput> <!--- Contents of FTP query is displayed in a table ---> <cfftp action="LISTDIR"  directory="c:\temp\"  name="MyDocs"> <P>Directory of files <cftable border="Yes" HTMLTABLE="yes" query="MyDocs">  <cfcol header="Name" text="#Name#" align="Left">  <cfcol header="Length" text="#Length#" align="Right"> </cftable> </cfif> </body> </html> 

See also <cfhttp>, <cffile>


<cffunction>

Description: This tag is used to define a function or method in a ColdFusion component. It defines one of the components behaviors. It must be used in the body of a <cfcomponent>.

Table B.63 describes the different ways that a component method defined with <cffunction> can be executed. You can executes methods using <cfinvoke> or by calling the methods from URLs, form submission, CFScripts, Flash gateways, or from web services. You can pass parameters to methods (by using <cfargment> tags to specify the parameters) and you can return values from them (by using <cfreturn> within the body of the <cffunction>). See Table B.64 for a list of <cffunction> attributes.

Table B.63. Different ways of executing methods defined by <cffunction>

INVOCATION METHOD

DESCRIPTION

<cfinvoke>

Used in ColdFusion templates or other ColdFusion components to execute a method. Parameters are directly passed as attributes. Return value defined in an attribute.

URL

You use the component name as part of the URL before the query string and specify the method name and params as part of the query string.

Form submission

The FORM's action attribute points to the path of the .cfc that contains the method. INPUT fields are used to pass parameter values.

CFScript

You use the CreateObject() CFscript function to first create an object for the component. Then you invoke that component's methods as you would the functions of any object.

Flash gateway

You use the Netservices functions in your ActionScript. You need to use the Flash MX authoring environment and the Flash 6 player.

Web services

Web service can invoke remote ColdFusion component methods as other web services.


Table B.64. <cffunction> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

description

Description of function

Optional. Short text description.

displayName

alt. name

Optional. This name will be displayed when the function is being 'introspected'. This value is displayed in parentheses following the function name.

hint

Description

Optional. Displayed as description of function when it is being introspected.

name

Text

Required; name of function.

returnType

Text

Optional; name of data type that will be returned.

roles

List

Optional; comma-delimited list of security roles who have access to this function.

access

List

Optional; comma-delimited list of access types from which this function can be invoked. The complete list is private, package, public, remote.

output

Yes or No

Optional; indicates whether output from this function is to be processed as HTML or hidden as if the function ran in the body of <cfsilent>.


To return a value from a function you should specfy a data type to be returned (using the returnType attribute) and <cfreturn> to return the data.

Syntax:

 <cffunction  name="Function name"  description="Fucntion description"  displayName="Name"  hint="Text hint"  returnType="Data type to be returned"  roles="Comma-delimited list of roles"  access="Access type"  output="Yes or No">…</cffunction> 

returnType can be:

Any

Numeric

Array

Query

Binary

String

Boolean

Struct

Component Name

UUID

Date

Variablename

GUID

XML


NOTE

Because <cffunction> tags are only used in the body of <cfcomponent> tags, they can't be run in .cfm files, only in ColdFusion components or .cfc files.


Example: The following example demonstrates a method that produces the value of all outstanding orders. Use of this method is restricted to users who have authenticated with the application in the Manager role.

 <!--- Returns the value of all outstanding orders, but only   for users how have authenticated as managers. ---> <cfcomponent>  <cffunction name="GetOpenOrderTotal"  hint="Calculates order total on non-shipped orders"   returnType="Number" roles="Manager">  <cfquery name="GetOpenOrderTtl" dataSource="OWS">  SELECT SUM(OI.ItemPrice) AS OpenOrderTotal  FROM MerchandiseOrders O   INNER JOIN MerchandiseOrdersItems OI  ON O.OrderID = OI.OrderID  WHERE  O.ShipDate IS NULL  </cfquery>  <cfreturn #GetOpenOrderTtl.OpenOrderTotal#>  </cffunction> </cfcomponent> 

See also <cfcomponent>, <cfargument>, <cfreturn>, <cfinvoke>, <cfobject>


<cfgraph>

The <cfgraph> tag has been deprecated. See <cfchart> and related tags.

<cfgraphdata>

The <cfgraphdata> tag has been deprecated. See <cfchart> and related tags.

<cfgrid>

Description: <cfgrid> embeds a Java grid control in your <cfform> forms. Grids are similar to spreadsheet-style interfaces, and <cfgrid> grids can be used to browse, select, and even edit data. Grids can be populated either by a query or by specifying each row using the <cfgridrow> tag. <cfgridcolumn> can be used to configure the individual columns with a grid. <cfgrid> attributes are presented in Table B.65.

Table B.65. <cfgrid> Attributes

ATTRIBUTE

AVAILABLE

DESCRIPTION

NOTES

align

Applet

Control alignment

Optional; possible values are Top, Left, Bottom, Baseline, Texttop, Absbottom, Middle, Absmiddle, and Right.

appendKey

Applet

Yes or No

Optional; appends item key to URL. If the value is Yes, a variable named gridkey is appended to the URL containing the item selected. It defaults to Yes.

autoWidth

Applet

Yes or No

Optional; sizes grid based on the width of the data, within the height and width attributes.

bgColor

All

Background color

Optional; possible values are Black, Blue, Red, Cyan, Darkgray, Gray, Lightgray, Magenta, Orange, Pink, White, Yellow, or any color specified in RGB form.

bold

All

Yes or No

Optional; boldfaces grid control text; defaults to NO.

colHeaderAlign

Applet

Column header alignment

Optional; can be Left, Center, or Right; default is Left.

colHeaderBold

All

Yes or No

Optional; boldfaces column header text; defaults to No.

colHeaderFont

All

Column header font

Optional font to use for column header.

colHeaderFontSize

All

Column header font size in points

Optional font size to use for column header.

colHeaderItalic

All

Yes or No

Optional; italicizes column header text; defaults to No.

colHeaders

All

Yes or No

Optional; displays column headers; default is Yes.

colHeaderTexTcolor

All

Color for text

Optional; can be specified as Black (default), Blue, Red, Magenta, Cyan, Orange, Darkgray, Pink, Gray, White, Lightgray, or Yellow. It can also be specified as a hex value, such as ##999999 (a hex value preceded by two number signs).

delete

All

Yes or No

Optional; if Yes, allows records to be deleted from the grid. Default is NO.

deleteButton

Applet

Delete button text

Optional text to use for the Delete button; default is Delete.

font

All

Font face

Optional font face to use.

fontSize

All

Font size

Optional font size.

format

All

Applet, Flash, XML

Defaults to Applet. In HTML forms, specifying XML will put the XML in a variable named by the name attribute.

gridDataAlign

Applet

Data alignment

Data alignment; can be LEFT, RIGHT, or CENTER; can be overridden at the column level.

gridLines

All

Yes or No

Optional; displays grid lines; default is Yes.

height

All

Control height

Optional height in pixels.

highlightHref

Applet

Yes or No

Optional attribute; if Yes, links are highlighted and underlined; defaults to Yes.

HRef

Applet

URL

Optional URL to go to upon item selection; if populated by a query, this can be a query column.

hrefKey

Applet

Primary key column

Optional name of column to be used as the primary key.

hspace

Applet

Control horizontal spacing

Optional horizontal spacing in pixels.

insert

All

Yes or No

Optional; if Yes, allows records to be added to the grid; default is NO.

insertButton

Applet

Insert button text

Optional text to use for the Insert button; default is INSERT.

italic

All

Italic face text

Optional attribute; must be Yes or No if specified; defaults to No.

maxRows

All

Number

Optional; number of rows you want to show in the grid.

name

Flash, Applet

Unique control

Required.

notSupported

Applet

Text to be used for non-Java browsers

Optional text (or HTML code) to be displayed on nonJava-capable browsers.

onChange

Flash

Actionscript

Script code to execute when user changes value

onError

Applet

JavaScript error function

Optional override to your own JavaScript error message function.

onValidate

Applet

JavaScript validation function

Optional override to your own JavaScript validation function.

pictureBar

Applet

Displays picture bar with icons

Optional; if Yes, a button bar with icons is displayed for insert, delete, and sort; default is No.

query

All

Query to populate grid

Optional name of query to be used to populate the grid.

rowHeaders

Applet

Yes or No

Optional; displays row header if Yes; default is Yes.

rowHeaderAlign

Applet

Row header alignment

Optional; can be Left, Center, or Right; default is Left.

rowHeaderBold

Applet

Yes or No

Optional; displays row header in bold font; defaults to No.

rowHeaderFont

Applet

Row header font

Optional font to use for row header.

rowHeaderFontSize

Applet

Row header

Optional font size to use for row header. font size

rowHeaderItalic

Applet

Yes or No

Optional; displays row header in italics; default is No.

rowHeaderTextColor

Applet

Color for text

Optional; can be specified as Black (default), Blue, Red, Magenta, Cyan, Orange, Darkgray, Pink, Gray, White, Lightgray, or Yellow. Can also be specified as a hex value, such as ##999999 (a hex value preceded by two number signs).

rowHeight

All

Row height

Optional height of row in pixels.

selectColor

Applet

Selection color

Optional attribute; possible values are Black (default), Blue, Red, Cyan, Darkgray, Gray, Lightgray, Magenta, Orange, Pink, White, Yellow, or any color specified in RGB form.

selectMode

All

Selection mode

Optional attribute; can be Edit, Single, Row, Column Or Browse; default is Browse.

sort

Applet

Yes or No

Optional; if Yes, allows grid data to be sorted; defaults to No.

sortAscendingButton

Applet

Sort ascending button text

Optional text to use for the sort ascending button; default is A -> Z.

sortDescendingButton

 

Sort descending button text

Optional text to use for the sort descending button; default is Z -> 1.

style

Flash

Specification

CSS format style specification

target

Applet

URL to target window

Optional name of target window for hrEF URL.

textColor

All

Color for text

Optional; can be specified as black (default), Red, Blue, Magenta, Cyan, Orange, Darkgray, Pink, Gray, White, Lightgray, or Yellow. Can also be specified as a hex value, such as ##999999 (a hex value preceded by two number signs).

vSpace

Applet

Control vertical spacing

Optional vertical spacing in pixels.

width

All

Control width

Optional width in pixels.


<cfgrid> must be used between <cfform> and </cfform> tags.

Syntax:

 <cfgrid   align="Alignment"   appendKey="Yes or No"  autoWidth="Yes or No"  bgColor="Color"   bold="Yes or No"  colHeaderAlign="Alignment"   colHeaderBold="Yes or No"   colHeaderFont="Font Face"  colHeaderFontSize="Font Size"   colHeaderItalic="Yes or No"   colHeaders="Yes or No"  colHeaderTextColor="Color specification"  delete="Yes or No"  deleteButton="Button Text"  font="Font Face"   fontsize="Font Size"  format="Applet, Flash or XML"  gridDataAlign="Alignment"  gridLines="Yes or No"  height="Control Height"  highlightHref="Yes or No"   href="URL"   hrefKey="Key"   hSpace="Horizontal Spacing"  insert="Yes or No"   insertButton="Button Text"   italic="Yes or No"   maxrows="Number"   name="Field Name"  notSupported="Text"   onChange="Actionscript"  onError="Error Function"  onValidate="Validation Function"   pictureBar="Yes or No"   query="Query"  rowHeaders="Yes or No"   rowHeaderAlign="Alignment"   rowHeaderBold="Yes or No"  rowHeaderFont="Font Face"   rowHeaderFontSize="Font Size"  width=rowHeaderItalic="Yes or No"   rowHeaderTextColor="Color specification"  selectColor="Color"   selectMode="Mode"   sort="Yes or No"  sortAscendingButton="Button Text"   sortDescendingButton="Button Text"  style="style"  target="Target Window"   textColor="Color specification"   vSpace="Vertical Spacing"   width="Control Width"> 

Example: The following example creates two grids based on query results. The first query is then used to produce a read-only, Flash-based grid containing film budget information. The second query is used to produce a grid in which the user can edit and delete expense records. The last example demonstrates a grid produced with hard-coded data using <cfgridrow>.

 <!--- Queries get raw data ---> <cfquery name="GetBigBudgetFlicks" dataSource="ows">  SELECT FilmID, MovieTitle, AmountBudgeted  FROM Films </cfquery> <cfquery name="GetExpenses" dataSource="ows">  SELECT E.ExpenseID, E.FilmID, F.MovieTitle, E.ExpenseAmount, E.Description  FROM Expenses E INNER JOIN Films F ON E.FilmID = F.FilmID </cfquery> <html> <head> <title>CFGRID Example</title> </head> <body> <!--- Form created ---> <cfform action="CFGRID_Action.cfm"   method="Post"   name="GridForm"> <h3>Films Budgets</h3> <!--- Grid created from first query in Flash ---> <cfgrid   name="FilmBudgets"  format="Flash"  query="GetBigBudgetFlicks"  colheaderbold="Yes"  colheaderfont="Gill Sans MT"  selectmode="BROWSE"  width="400"  height="300"> <!--- Grid column created ---> <cfgridcolumn name="FilmID"   header="Film ID"> <!--- Grid column created ---> <cfgridcolumn name="MovieTitle"   header="Title"> <!--- Grid column created ---> <Cfgridcolumn name="AmountBudgeted"  numberformat="___,___,___,___.__"  dataAlign="Right"  header="Budget"  headerAlign="Right"> </cfgrid> <H3>Film Expenses</h3> <!--- Editable grid, uses applet format ---> <cfgrid name="FilmExpenses"  query="GetExpenses"  COLHEADERBOLD="Yes"  COLHEADERFONT="Gill Sans MT"  SELECTMODE="EDIT"  width="580"  height="300"  DELETE="Yes"  DELETEBUTTON="Del?"> <!--- key column created but not displayed ---> <cfgridcolumn name="ExpenseID"   display="No"> <!--- selectable columns created ---> <cfgridcolumn SELECT="Yes"   name="FilmID"   header="Film ID"> <cfgridcolumn SELECT="Yes"   name="MovieTitle"   header="Title"> <cfgridcolumn name="ExpenseAmount"  select="Yes"  numberFormat="___,___,___,___.__"  dataAlign="RIGHT"  header="Amount"  headerAlign="RIGHT"> <cfgridcolumn SELECT="yes"   name="Description"> </cfgrid> <P><input type="Submit" value="Save"> <!--- grid created from hard-coded data---> <cfgrid name="AnnualBudget"> <!--- grid columns created --->  <cfgridcolumn name="Q1">  <cfgridcolumn name="Q2">  <cfgridcolumn name="Q3">  <cfgridcolumn name="Q4"> <!--- grid row populated ---> <cfgridrow DATA="400000, 500000, 600000, 700000"> </cfgrid> </cfform> </body> </html> 

The action template (cfgrid_action.CFM) for the form developed in the previous example is presented in the following example for <cfgridupdate>.

NOTE

The <cfgrid> control is accessible only by users with Java-enabled browsers.


See also <cfgridcolumn>, <cfgridrow>, <cfform>, <cfgridupdate>, <cfinput>, <cfselect>, <cfslider>, <cftextarea>, <cftree>


<cfgridcolumn>

Description: <cfgridcolumn>, which must be used with <cfgrid>, can be used to configure the individual columns in a grid. <cfgridcolumn> attributes are presented in Table B.66.

Syntax:

 <cfgridcolumn bold="Yes or No"   bgColor="Color specification"  colHeaderTextColor="Color specification"  dataAlign="Alignment"   display="Yes or No"  font="Font Face"   fontsize="Font Size"   header="Header Text"  headerAlign="Alignment"   headerBold="Yes or No"   headerFont="Font Face"  headerFontSize="Font Size"   headerItalic="Yes or No"   href="URL"   hrefKey="Key"  italic="Yes or No"   mask="date fomrat"  name="Column Name"   numberfOrmat="Format Mask"   select="Yes or No"  target="Target Window"   type="Type"   width="Column Width"  textColor="Color specification"  VALUES="Values list"   VALUESDISPLAY="List of values"  VALUESDELIMITER="Delimiter character"> 

Table B.66. <cfgridcolumn> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

bgColor

Color for text

Optional; can be specified as Black (Default), Red, Blue, Magenta, Cyan, Orange, Darkgray, Pink, Gray, White, Lightgray, or Yellow. Can also be specified as a hex value, such as ##999999 (a hex value preceded by two number signs).

bold

Boldface text

Optional; must be YES or NO if specified; defaults to NO.

headerTextColor

Color for text

Optional; can be specified as Black (Default), Red, Blue, Magenta, Cyan, Orange, Darkgray, Pink, Gray, White, Lightgray, or Yellow. Can also be specified as a hex value, such as ##999999 (a hex value preceded by two number signs).

dataAlign

Data alignment

Optional; can be Left, Center, or Right; default is Left.

display

Display column

Optional; if No, column is hidden; default is Yes.

font

Font face

Optional font face to use.

fontSize

Font size

Optional font size.

header

Header text

Optional header text; defaults to column name. Value is significant only when the <cfgrid> COLHEADERS attribute is Yes (default).

headerAlign

Header alignment

Optional; can be Left, Center, or Right; default is Left.

headerBold

Header in bold

Optional; if Yes, header is displayed in a bold font; default is No.

headerFont

Header font

Optional font to use for header.

headerFontSize

Header font size

Optional font size to use for header.

headerItalic

Header in italics

Optional; if Yes, header is displayed in an italic font; default is No.

href

URL

URL for selection in this column; can be absolute or relative.

hrefKey

Primary key

Optional primary key to use for this column.

italic

Italic face text

Optional; must be Yes or No if specified; defaults to No.

mask

Date format

Used to specify date format in Flash forms.

name

Column name

Required; if using a query to populate the grid, this must be a valid column name.

numberFormat

Number formatting

Optional; uses NumberFormat() function masks; see that function for mask details.

select

Allow selection

Optional; if No, selection or editing is not allowed in this column.

target

Target window

Optional target window for HREF.

textColor

Color for text

Optional; can be specified as Black (default), Red, Blue, Magenta, Cyan, Orange, Darkgray, Pink, Gray, White, Lightgray, or Yellow. Can also be specified as a hex value, such as ##999999 (a hex value preceded by two number signs).

type

Data type

Optional; can be image or numeric. If it's an image, an appropriate graphic is displayed for the cell value. Built-in images are in the following bulleted list.

values

List or range

Optional; enables you to format a column as a drop-down box. You specify a hard-coded list of delimited values (for example, Joe,Bob,Jenny) or a range of values, such as 1-10.

valuesDisplay

List to display

Optional; this is used with the VALUES attribute to specify the list to be displayed.

valuesDelimiter

Delimiter character

Optional; character to act as delimiter in values and valuesDisplay lists. Defaults to a comma, ",".

width

Column width

Optional column width in pixels. Columns are sized as wide as the longest value by default.


The built-in image types for use in the TYPE attribute are:

Image

Folder

CD

Floppy

Computer

Fixed

Document

Remote

Element

 


Example: The following example creates two grids based on query results. The first query is then used to produce a read-only grid containing film budget information. The second query is used to produce a grid in which the user can edit and delete expense records.

 <!--- Queries get raw data ---> <cfquery name="GetBigBudgetFlicks" dataSource="ows">  SELECT FilmID, MovieTitle, AmountBudgeted  FROM Films </cfquery> <cfquery name="GetExpenses" dataSource="ows">  SELECT E.ExpenseID, E.FilmID, F.MovieTitle, E.ExpenseAmount, E.Description  FROM Expenses E INNER JOIN Films F ON E.FilmID = F.FilmID </cfquery> <html> <head>  <title>CFGRID Example</title> </head> <body> <!--- Form created ---> <cfform action="CFGRID_Action.cfm"   method="POST"   name="GridForm"> <h3>Films Budgets</h3> <!--- Grid created from first query ---> <cfgrid name="FilmBudgets"  query="GetBigBudgetFlicks"  colHeaderBold="Yes"  colHeaderFont="Gill Sans MT"  selectMode="BROWSE"  width="400"  height="300"> <!--- Grid column created ---> <cfgridcolumn name="FilmID"   header="Film ID"> <!--- Grid column created ---> <cfgridcolumn name="MovieTitle"   header="Title"> <!--- Grid column created ---> <cfgridcolumn name="AmountBudgeted"  numberFormat="___,___,___,___.__"  dataAlign="RIGHT"  header="Budget"  headerAlign="RIGHT"> </cfgrid> <H3>Film Expenses</h3> <!--- Editable grid ---> <cfgrid name="FilmExpenses"  query="GetExpenses"  colHeaderBold="Yes"  colHeaderFont="Gill Sans MT"  selectMode="EDIT"  width="580"  height="300"  delete="Yes"  deleteButton="Del?"> <!--- key column created but not displayed ---> <cfgridcolumn name="ExpenseID"   display="No"> <!--- selectable columns created ---> <cfgridcolumn select="Yes"   name="FilmID"   header="Film ID"> <cfgridcolumn SELECT="Yes"   name="MovieTitle"   header="Title"> <cfgridcolumn name="expenseamount"  select="Yes"  numberFormat="___,___,___,___.__"  dataAlign="RIGHT"  header="Amount"  headerAlign="RIGHT"> <cfgridcolumn SELECT="yes"   name="Description"> </cfgrid> <P><input type="Submit" value="Save"> </cfform> </body> </html> 

See also <cfgrid>, <cfgridrow>


<cfgridrow>

Description: <cfgridrow>, which must be used with the <cfgrid> tag, can be used to populate rows in a grid with a comma-delimited list of data. Table B.67 shows <cfgridrow> attributes.

Table B.67. <cfgridrow> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

data

Row data

Comma-delimited list of data to be displayed; one item for each column in the grid.


Syntax:

 <cfgridrow DATA="Data"> 

Example: The following example demonstrates a grid produced with hard-coded data using <cfgridrow>.

 <html> <head>  <title>CFGRID Example</title> </head> <body> <!--- Form created ---> <cfform action="CFGRID_Action.cfm"   method="POST"   name="GridForm"> <!--- grid created from hard-coded data---> <cfgrid name="AnnualBudget"> <!--- grid columns created --->  <cfgridcolumn name="Q1">  <cfgridcolumn name="Q2">  <cfgridcolumn name="Q3">  <cfgridcolumn name="Q4"> <!--- grid row populated ---> <cfgridrow DATA="400000, 500000, 600000, 700000"> </cfgrid> </cfform> </body> </html> 

See also <cfgrid>, <cfgridcolumn>


<cfgridupdate>

Description: <cfgridupdate> provides the action backend to support <cfgrid> in edit mode. <cfgridupdate> performs all inserts, deletes, and updates in one simple operation. <cfgridupdate> can be used only in an action page to which a form containing a <cfgrid> control was submitted. <cfgridupdate> attributes are listed in Table B.68.

Table B.68. <cfgridupdate> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

connectString

Deprecated

This attribute has been deprecated.

dataSource

ODBC data source

Required.

dbName

Sybase database name

Optional; used only if using native Sybase drivers.

dbPool

Database pool name

Optional.

dbServer

Deprecated

This attribute has been deprecated.

dbType

Deprecated

This attribute has been deprecated.

grid

Grid name

Required; the name of the grid in the submitted form with which to update the table.

keyOnly

WHERE clause construction

If Yes, the WHERE clause generated by <cfgrid> contains just the primary; default is Yes.

passWord

ODBC login password

Optional ODBC login password.

provider

OLE-DB COM provider

Optional; only used if using OLE-DB.

providerDsn

DSN Provider name

Optional; used only if using OLE-DB.

tableName

Table name

Required.

tableOwner

Table owner

Optional ODBC table owner.

tableQualifier

Table qualifier

Optional ODBC table qualifier.

userName

ODBC username

Optional ODBC username.


Syntax:

 <cfgridupdate dataSource="ODBC Data Source Name"   dbName="database name"  dbPool="pool"   gr  keyOnly="Yes or No""  passWord="Password"   provider="provider"   providerDsn="data source"  tableName="Table Name"   tableOwner="Table Owner Name"  tableQualifier="Table Qualifier"   userName="User Name"> 

Example: The following example updates an Expenses table based on a grid in the calling form named FilmExpenses. See the example in <cfgrid>:

 <!--- Updates database with values entered in grid ---> <cfgridupdate dataSource="OWS"   tableName="Expenses"   gr> 

See also <cfform>, <cfgrid>


<cfheader>

Description: <cfheader> enables you to control the contents of specific HTTP headers. You can either provide values for HTTP header elements or specify an HTTP response code and text. The attributes for this tag are presented in Table B.69.

Table B.69. <cfheader> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Name for header to be set

Required if you're not supplying a statusCode.

value

Header value

Optional; Used in conjunction with name attribute to specify header value.

statusCode

HTTP number code

Required if you're not specifying a name.

statusText

Explains statusCode

Optional; Used in conjunction with statusCode attribute to supply explanation of statusCode.


Syntax:

 <cfheader name="Header Name"   value="Value"> 

or

 <cfheader statusCode="HTTP code number"   statusText="Explanation of code"> 

Example: The following example sets several header values to prevent the template from being cached:

 <!--- header value is set to no cache ---> <cfheader name="Pragma"   value="no-cache"> <!--- header value sets cache to expire immediately ---> <cfheader name="Expires"   value="0"> <!--- header value is set to no cache in multiple ways ---> <cfheader name="cache-control" value="no-cache, no-store,  must-revalidate, max-age=0"> <!--- writes expiration date into http header ---> <cfhtmlhead text='<meta HTTP-EQUIV="Expires"  content="Mon, 01 Jan 2001 00:00:01 GMT">'> 

NOTE

There is usually little need to use <cfheader> because ColdFusion sets the HTTP headers automatically to optimum values.


NOTE

Because <cfheader> needs to write to the HTTP header, you can't use it if you've already flushed the header from the ColdFusion output buffer with <cfflush>.


See also <cfflush>


<cfhtmlhead>

Description: <cfhtmlhead> writes text into the header section of your Web page. It can be placed anywhere in your page, effectively enabling you to write your <head> section from in or below the <body> section of a page. The <head> section can contain <meta> tags and well as <script> tags (JavaScript) and <cfhtmlhead> is frequently used to do this write these sorts of tags. Attributes for this tag are presented in Table B.70.

Table B.70. <cfhtmlhead> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

text

Text to place in <head>

Required.


Syntax:

 <cfhtmlhead text="Text"> 

NOTE

Because <cfhtmlhead> needs to write to the HTML <head>, you can't use it if you've already flushed the <head> section from the ColdFusion output buffer with <cfflush>.


Example: See <cfheader>.

See also <cfflush>


<cfhttp>

Description: <cfhttp> enables you to process HTTP GET, POST and other common requests within your ColdFusion code, making ColdFusion perform like a browser. If you're using the POST method, parameters can be passed using the <cfhttpparam> tag. <cfhttpparam> can be used only between <cfhttp> and </cfhttp> tags. It includes support for HTTPS and HTTPS proxy tunneling in addition to multi-part forms. In addition to common Get and Post requests, you can set the method attribute to Put to upload files to the server via HTTP or Delete to remove them. Setting method to Options requests instructions on what HTTP requests the server can deal with.

Note that when multiple headers of the same type are returned, they're returned in an array.

<cfhttp> attributes are listed in Table B.71. <cfhttp> sets special variables upon completion that you can inspect; they are listed in Table B.72.

Table B.71. <cfhttp> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

charset

Character encoding set

Optional; defaults to utf-8 for request. For response, defaults to charset specified in the response CONTENT-TYPE header. Describes character encoding for URL query string and form/file data and response. Examples include: iso-8859-1, us-ascii, shift_jis, utf-8, euc-jp, euc-kr, windows-1252.

columns

Query columns

Optional; comma-separated list of column names for query object returned via QUERY attribute. Note that ColdFusion will generate an error if the number of columns specified does not equal the number included in the response body.

delimiter

Column delimiter

Required if name is used; default delimiter is a comma.

file

Filename

Required only if PATH is used; file to save. For Get method, it defaults to file name specified in URL. Note that CFHTTP.FILECONTENT will be empty if you use the FILE attribute.

firstrowAsHeaders

Yes or No

Optional; Yes value causes first row of results to be processed as headers if the COLUMNS attribute is NOT specified. If No and columns is NOT specified, ColdFusion processes first row of query results and creates column names. If columns is specified then firstrowAsHeaders attribute is ignored.

getAsBinary

Yes, No or Auto

Optional; defaults to No. Yes means always convert response to binary data. Auto tells ColdFusion to create the response as binary if it doesn't recognize it as text. ColdFusion will treat the response as text if either the header doesn't specify a content-type, the content-type starts with text or message or the content type is application/octet-stream.

method

Method name

Optional; defaults to Get. Using Post requires at least one <cfhttpparam>. Delete requests server to delete the URL. Put is a request to send a file to a server. Head is similar to Get, but server won't reply with message ody. TRace is a request to include received headers in message body. Using Options requests that the server return specifications on the servers capabilities and requirements for requests to this URL.

multiPart

Yes or No

Optional; defaults to No. Used when method=Put to indicate how <cfhttparam type="Formfield"> data are to be handled. If set to Yes, these data are treated as multi-part form data and sent with a content-type of multi-part/form-data.

name

Query name

Optional; name of query to be constructed with HTTP results.

password

User password

Optional; user password if required by server for Basic Authentication only.

path

File path

Optional; path to save file if method is Post, Get, Put, Options, trace or Delete.

port

TCP/IP port number

Optional; defaults to 80 for HTTP, 443 for HTTPS.

proxyServer

Server name

Optional name of proxy server to use.

proxyPort

TCP/IP port number

Optional; defaults to 80.

redirect

Yes or No

Optional; defaults to Yes. Specifies whether or not a redirect should be executed in the event that a response header includes a redirection status-code. No stops redirection and returns response in CFHTTP variable, or will throw error if THROWONERROR is set to Yes. Note that CFHTTP.RESPONSEHEARDER.LOCATION will contain path of redirect.

resolveUrl

Resolve URL

Optional; defaults to No. If Yes, fully resolves embedded URLs. If No, relative path information in the response body URLs will be left as relative links and may not function properly.

result

Variable name

Optional. The result is normally put in a variable named CFHTTP; this enables you to specify your own variable name.

textQualifier

Text qualifier

Required if name is used; delimiter indicating start and end of column. Defaults to a double quote mark (").

timeOut

Timeout period in seconds

Optional; timeout period can be defined in the browser URL, the CF Administrator, and this tag; ColdFusion uses the lesser value if it's specified in multiple places. If the URL also contains the RequestTime=value pair, ColdFusion will use the lesser value.

tHRowOnError

Yes or No

Optional; defaults to No. Indicates whether an exception should be thrown on an error; enables you to trap an error with a <cftry>...<cfcatch> block. The error codes are found in the CFHTTP.StatusCode variable.

URL

Host URL

Required; must be DNS name or IP address of a valid host.

userAgent

User agent request

Optional; enables your <cfhttp> call to spoof a specific browser.

userName

Username

Optional; username if required by server for Basic Authentication only.


Table B.72. <cfhttp> Returned Variables

FIELD

DESCRIPTION

CFHTTP.CHARSET

Character set of the response header.

CFHTTP.ERRORDETAIL

Error messages in the event the request failed.

CFHTTP.FILECONTENT

Content returned by HTTP request.

CFHTTP.HEADER

This is the raw response header.

CFHTTP.MIMETYPE

MIME type of returned data.

CFHTTP.RESPONSEHEADER

Response header name/value pair(s). If there are more than one, they're returned in an array.

CFHTTP.HEADER

Raw response header.

CFHTTP.STATUSCODE

HTTP error code associated with the error that occurs if ThrOWONERROR is set to Yes.

CFHTTP.TEXT

If the response body is text, this is true. The body will be recognized as text if the header specifies no content type, the content type starts with text or message or the content type is application/octet-stream.


Syntax:

 <cfhttp   charset="Character encoding set name"  columns="Column Names"   delimiter="Delimiter Character"   file="File Name"  firstRowAsHeaders = "Yes or No"  getAsBinary="Yes or No"  method="Method name"   multipart="Yes or No"  name="Query Name"   passWord="Password"   path="Directory"  port="Port number"   proxyPort="Port number"   proxyServer="Host Name/IP"   proxyUser="Username for proxy server"  proxyPassword="Password for proxy server"  redirect="Yes or No"  resolveUrl="Yes or No"  result="Variable name"  textQualifier="Text Qualifier"  throwOnError="Yes or No"  timeout="Number of seconds"  URL="Host Name"   userAgent="Brower's user agent value"  userName="User Name"> </cfhttp> 

Example: This example uses Altavist1.com's Babblefish to translate the expression "Say 'Hello' in French" into French. It does this by mimicking the Altavist1.com form found at http://world.altavist1.com/. It will work as long as Altavist1.com doesn't change the URLs or names of fields in this form.

The example uses a <cfhttp> call with METHOD set to POST, passing the parameters on to the form's action page (identified in the URL attribute as http://world.altavist1.com/tr) using calls to <cfhttpparam>.

The action page is itself a form and is returned in the CFHTTP.FileContent variable. This variable is parsed looking for two values that were determined to delimit the translated value in the action page.

 <P>Say 'Hello' in French. <!--- cftry sets trap for errors ---> <cftry> <!--- mimics altavista form --->  <cfhttp method="POST"  URL="http://world.altavist1.com/tr"  throwOnError="Yes">  <cfhttpparam type="formfield" name="doit" value="done">  <cfhttpparam type="formfield" name="tt" value="urltext">  <cfhttpparam type="formfield" name="lp" value="en_fr">  <cfhttpparam type="formfield" name="urltext"  "value="Say 'Hello' in French.">  </cfhttp> <!--- if any errors are returned, details are displayed  and processing stops. ---> <cfcatch type="Any">  <cfoutput>#cfhttp.StatusCode#</cfoutput>  <P>Failure!<cfabort>  </cfcatch> </cftry> <!--- if no errors are returned, success message is displayed ---> <P>Success! <!--- Now parse the French out of the action page's form.  The value we're looking for is inside a textarea named 'q'  in the action page. ---> <cfset nStart=Find('name="q"', CFHTTP.FileContent) +9> <cfset nEnd=Find('</Textarea>', CFHTTP.FileContent, nStart+1) > <cfset French=Mid(CFHTTP.FileContent, nStart, nEnd-nStart)> <!--- answer is displayed ---> <P><em><cfoutput>#French#</cfoutput></em> 

NOTE

For the TIMEOUT attribute (or the TimeOut URL parameter) to work, you must enable Timeout in the ColdFusion Administrator.


See also <cfhttpparam>, <cfftp>


<cfhttpparam>

Description: <cfhttpparam>, which must be used with the <cfhttp> tag, enables you to pass parameters. <cfhttpparam> can be used only between <cfhttp> and </cfhttp> tags. You can use multiple <cfhttpparam> tags under most circumstances, but with some limitations:

  • The formfield type attribute is only useful with the <cfhttp>'s method attribute is Get or Post.

  • You can't use multiple XML or Body type attributes.

  • You can't combine XML, body, file or formfield type attributes in one <cfhttp> call.

  • body and XML type attributes can't be used when <cfhttp method="Trace">

When type="File" the body of the multi-part form request contains the file content. When the receiving URL is a CFML page, a variable is created in the form scope that contains the path to the temporary file that you sent. The variable will be named with the value you provided in the name attribute. It will appear in the formFields list.

Raw HTTP messages can be sent by using <cfhttpparm> tags with type=Header for headers and type=Body for message content.

<cfhttpparam> attributes are listed in Table B.73.

Table B.73. <cfhttpparam> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

encoded

Yes or No

Optional; defaults to Yes. Applies when TYPE is Formfield or CGI. Specifies whether or not to URL-encode the form field or header.

file

Filename

Required if TYPE is File.

mimeType

Mime type

Optional; applies only when type is File. Indicates the MIME media type of the file being transmitted. The value can include a charset descriptor for the file too, separated from the MIME type by a semicolon.

name

Field name

This attribute is required except when type is Body or XML.

type

Field type

This attribute is required; must be URL, Formfield, Cookie, CGI, Header, Body, XML or File. When you specify a Header, CF will not URL-encode it, but when you specify CGI, CF will URL-encode it. Use Body to specify the body of the HTTP request. You can specify the content-type with an addition <cfhttpparam> with type=Header. When type=XML, use the VALUE attribute for the body of the HTTP request. XML data will not URL-encoded. When type=File, the contents of the specified file will be sent, and not URL-encoded. type=URL enables you to send a query string parameter. type=Cookie sends a cookie header, which is URL-encoded.

value

Field value

This attribute is optional unless TYPE is File.


Syntax:

 <cfhttpparam   encoded="Yes or No"  file="File Name"   mimeType="Mime type spec"  name="Field Name"   type="Type"   value="Value"> 

Example: See <cfhttp>.

See also <cfhttp>


<cfif>

Description: The <cfif> set of tags is used to provide conditional branching logic (along with <cfswitch>, <cfcase>, and related tags).

Every <cfif> tag must have a matching </cfif> tag. The <cfelseif> and <cfelse> tags are entirely optional. You can use as many <cfelseif> tags as necessary in a <cfif> statement, but only one <cfelse>. If it is used, <cfelse> must always be the last compare performed.

<cfif> uses operators to compare values. Table B.74 shows these operators. Conditions can also be combined to perform more complex comparisons using the Boolean operators shown in Table B.75.

Table B.74. ColdFusion Conditional Operators

OPERATOR

ALTERNATIVE

DESCRIPTION

IS

EQUAL, EQ

Checks that the right value is equal to the left value.

IS NOT

NOT EQUAL, NEQ

Checks that the right value is not equal to the left value.

CONTAINS

 

Checks that the right value is contained within the left value.

DOES NOT CONTAIN

 

Checks that the right value is not contained within the left value.

GREATER THAN

GT

Checks that the left value is greater than the right value.

LESS THAN

LT

Checks that the left value is less than the right value.

GREATER THAN OR EQUAL

GTE

Checks that the left value is greater than or equal to the right value.

LESS THAN OR EQUAL

LTE

Checks that the left value is less than or equal to the right value.


Table B.75. ColdFusion Boolean Operators

OPERATOR

DESCRIPTION

AND

Conjunction; returns trUE only if both expressions are true.

OR

Disjunction; returns trUE if either expression is true.

NOT

Negation.


You can compare any values, including static text and numbers, ColdFusion fields, database column values, and function results.

Syntax:

 <cfif Condition>  <cfelseif Condition>  <cfelse> </cfif> 

Example: This example checks to see whether a FORM variable named Lastname exists:

 <!--- If the condition is met, a variable is set ---> <cfif IsDefined("FORM.LastName")>  <cfset Lname=FORM.LastName)> <!--- If the condition is not met, an alternative variable is set ---> <cfelse>  <cfset Lname="")> </cfif> 

The following example checks to see whether both the Firstname and Lastname FORM variables exist:

 <!--- Checks if two conditions are met ---> <cfif (IsDefined("FORM.FirstName")) AND (IsDefined("FORM.LastName"))> 

You could use the following to check for either a first name or a last name:

 <!--- Checks if either of two conditions are met ---> <cfif (IsDefined("FORM.FirstName")) OR (IsDefined("FORM.LastName"))> 

Often, you will want to verify that a field is not empty and that it does not contain blank spaces. The following example demonstrates how this can be accomplished:

 <!--- Checks that a condition is not met ---> <cfif Trim(FORM.LastName) IS NOT ""> 

You can use the CONTAINS operator to check whether a value is within a range of values. Take a look at both of these examples:

 <!--- Checks if a value contains certain sets of characters ---> <cfif "KY,MI,MN,OH,WI" CONTAINS State> <!--- Checks if a value contains certain sets of characters ---> <cfif TaxableStates CONTAINS State> 

By combining conditions within parentheses, more complex expressions can be created. For example, the following condition checks to see whether payment is by check or credit card; if payment is by credit card, it checks to ensure that there is an approval code:

 <!--- Checks if multiple values fulfill multiple conditions ---> <cfif (PaymentType IS "Check") OR ((PaymentType IS "Credit")  AND (ApprovalCode IS NOT ""))> 

The following example is a complete conditional statement that uses <cfelseif> to perform additional comparisons. It also uses <cfelse> to specify a default for values that pass none of the compares:

 <!--- Checks if a value meets a condition ---> <cfif State IS "MI">  Code for Michigan only goes here <!--- If first condition is not met, checks if the value meets   a second condition ---> <cfelseif State IS "IN">  Code for Indiana only goes here <!--- If first or second conditions are not met, checks if a value meets   a third condition ---> <cfelseif (State IS "OH") OR (State IS "KY")>  Code for Ohio or Kentucky goes here <!--- If first, second, or third conditions are not met, the value is set ---> <cfelse>  Code for all other states goes here </cfif> 

Note that <cfparam> can be used as a shortcut for this functionality. The code

 <cfparam name="MyVariable"   default="123"> 

is the same as this code:

 <cfif NOT IsDefined("MyVariable")>  <cfset MyVariable=123> </cfif> 

See also <cfelse>, <cfelseif>, <cfswitch>, <cfparam>, Iif()


<cfimpersonate>

This tag has been deprecated and is no longer in use. Please refer to ColdFusion's new security framework tags: <cflogin>, <cflogout>, and <cfloginuser>.

<cfimport>

Description: <cfimport> enables you to import and use the JSP tag library (that conforms to the JSP 1.1. tag extension API) on a ColdFusion template. The JSP tags can only be accessed on the page that imported them. When importing multiple tag libraries, if tags with the same name are imported more than once, the first import takes precedence. You can define a prefix to use when accessing the imported tags. <cfimport> attributes are shown in Table B.76.

Table B.76. <cfimport> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

tagLib

URI or path

Required; you can use a URL to point to a JAR application or you can use a path to point to a tag library descriptor file.

prefix

Name

Optional; this value will be used as a prefix to access all imported JSP tags on current page.


Syntax:

 <cfimport tagLib="Location of tag library"   prefix="Prefix name for imported tags" /> 

NOTE

This tag must be included at the top of each page in which you intend to use the imported tags; it should not be <cfinclud>ed in the page. Also note that it should not be placed in application.cfm as it will not be propagated from there.


Example: The following code imports a library of JSP tags in a .jar file. In the bottom half of the example, an imported JSP tag is employed using its imported prefix.

 <!--- Import a library of statistics functions ---> <cfimport tagLib="/myjavaserverpages/libraries/statstags.jar"  prefix="Math"> <!--- Now we'll use one of the math tags. This one produces  the standard deviation based on a list of values. ---> <cfoutput> <MATH:stddev hi="2032,493,34,3673,232,45232,24,333,4335,32"/> </cfoutput> 

See also <cfinvoke>


<cfinclude>

Description: <cfinclude> includes the contents of another template in the one being processed. This is one mechanism ColdFusion developers can employ to reuse code. Table B.77 shows the <cfinclude> attributes.

Table B.77. <cfinclude> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

template

Name of template to include

This attribute is required. Only relative paths are supported.


Syntax:

 <cfinclude template="Template File Name"> 

Example: The following example includes the footer file in the current directory if it exists and a default footer if not:

 <!--- if file exists, it is included in the page  being processed ---> <cfif FileExists("FOOTER.CFM")>  <cfinclude template="FOOTER.CFM"> <!--- if file doesn't exist, a default template is used ---> <cfelse>  <cfinclude template="/DEFAULT/FOOTER.CFM"> </cfif> 

NOTE

<cfinclude> can help you reuse templates. You can use <cfinclude> to break out common components (such as page headers and footers or commonly used queries), which enables you to share them among multiple templates.


CAUTION

Be careful about defining variables in templates that are being included in other templates because their variables share the same scope. If the included template defines a variable that is previously defined in the including template, the original variable value will be overwritten. Note that ColdFusion custom tags enable you to avoid these problems and reuse code.


See also <cflocation>


<cfindex>

Description: <cfindex> is used to populate Verity collections with index data. A collection must be created with either the ColdFusion Administrator or <cfcollection> before it can be populated. <cfindex> can be used to index physical files (in which case, the filename is returned in searches) or query results (in which case the primary key is returned in searches). Table B.78 lists <cfindex> attributes. Table B.79 shows the values for the action attribute.

Table B.78. <cfindex> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required attribute.

body

Body to index

Required if type is Custom; invalid if Type is Delete. ASCII text to be indexed. If indexing a query, this must be the column (or comma-delimited list of columns) to be indexed.

categoryName

Name of category

Optional

categoryTree

Category tree

Series of categories for searching. You identify the hierarchy and use "/" as a delimiter to identify the path through the tree.

collection

Collection name

Required; name of the collection to be indexed; if using external collections, this must be a fully qualified path to the collection.

custom1

Custom data

Optional attribute for storing data during indexing; specify a valid query column name.

custom2

Custom data

Optional attribute for storing data during indexing; usage is the same as Custom1.

custom3

Custom data

Optional attribute for storing data during indexing; usage is the same as Custom1.

custom4

Custom data

Optional attribute for storing data during indexing; usage is the same as Custom1.

extensions

File extensions

Optional; comma-delimited list of extensions of files to be indexed; only used if Type is Path.

external

Deprecated

This attribute has been deprecated.

key

Unique key

Optional; used to indicate what makes each record unique. If type is File, this should be the document filename; if type is Path, this should be a full path to the document; if type is Custom, this should be any unique identifier (for example, key field in a query result).

language

Specify a language

Optional; requires installation of the International Search Pack.

query

Query name to be indexed

Optional; use when type=Custom.

recurse

Yes or No

Optional; used when type=Path; if it's Yes, all subdirectories are indexed, too.

status

Structure name

ColdFusion will return status information in the structure you name in this attribute.

title

Document title

Required if Type is Custom; specified title for collection or query column name. Enables searching collections by title and the display of a title other than the actual key.

type

Index type

Optional attribute, must be File, Path, or Custom. If Path is used, specify the full filepath.

urlPath

URL path

Optional attribute; specifies the URL path for files when type=File or type=Path.


Table B.79. <cfindex> Actions

ACTION

DESCRIPTION

Delete

Deletes a key from a collection.

Purge

Clears all data from a collection.

Refresh

Clears all data from a collection and repopulates it.

Update

Updates a collection and adds a key if it does not exist.


Syntax:

 <cfindex action="Action"   body="Text"   collection="Collection Name"   category="Category name"  categorytree="Category tree"  custom1="Data"  custom2="Data"   custom3="Data"  custom4="Data"  extensions="File Extensions"   key="Key"  language="Language from optional International Search Pack"  query="Query Name"   recurse="Yes or No"   status="structure name"  title="Text"   type="Type"   urlPath="Path"> 

Example: The first example updates an existing collection built from a query. This index enables users to search for Orange Whip Studios merchandise based on merchandise name, description, or film name:

 <!--- query gets raw data ---> <cfquery name="GetFilmsMerchandise" dataSource="ows">  SELECT M.MerchID, F.MovieTitle, M.MerchName, M.MerchDescription  FROM Merchandise M, Films F  WHERE M.FilmID = F.FilmID </cfquery> <!--- updates collection with query results ---> <cfindex  action="UPDATE"  body="MerchName, MerchDescription, MovieTitle"  collection="FilmsMerchandise"  key="MerchID"  query="GetFilmsMerchandise"  type="Custom"> 

The second example creates a collection and populates it with the contents of documents in a specific path:

 <!--- collection is created ---> <cfcollection action="Create" collection="CFInstallTest"  path="C:\CFUSION\Verity\Collections"> <!--- collection is updated with files from a specific directory ---> <cfindex action="Update"  type="Path"  collection="CFInstallTest"  extensions=".htm, .html, .cfm"  key="C:\Inetpub\wwwroot\CFDOCS\testinstallation"  recurse="Yes"  urlPath="http://localhost/CFDOCS/testinstallation"> 

See also <cfcollection>, <cfsearch>


<cfinput>

Description: <cfinput> is an enhancement to the standard HTML <input> tag. <cfinput> enables you to embed JavaScript client-side validation code in your HTML forms automatically. <cfinput> must be used between <cfform> and </cfform> tags; it is not a Java control. Attributes are presented in Table B.80.

Table B.80. <cfinput> Attributes

ATTRIBUTE

AVAILABLE

DESCRIPTION

NOTES

bind

Flash

Flash bind expression

Optional; it populates the field based on other form fields.

checked

All

Yes, No or null

Defaults to False. Optional; only valid if type is RADIO or CHECKBOX and if present radio button or check box is prechecked.

dayNames

All

Comma-delimited list

Optional; applies to Datefield. Provides a comma-delimited list that displays names of week days. Sunday is the first.

disabled

All

Yes, No, or null

Optional; disables user input.

height

Flash, HTML

Control height in pixels

Optional; works with most Flash type controls and HTML Image type.

label

Flash, XML.

Field label

Label for use in form. Do not use when TYPE is Button, Hidden, Image, Reset, or Submit.

mask

Flash, HTML

Input mask

An optional pattern that determines what data can be entered. When type=Text and the form is HTML or Flash, a value of A indicates alphabetic characters (case insensitive), X is the same but includes 0-9. A value of 9 indicates 0-9. A ? is a wild card permitting any character. Any other characters are treated literal masks. In Flash forms, there also masks for when type=Datefield. D can be used for up to 2 day characters. M can be used for up to 4 month characters. Y can be used to indicate 2- or 4-digit years. E can be used for up to 4 characters for day-of-week.

maxLength

All

Maximum number of characters

Optional; used when TYPE is Text or Password. Note that this will not prevent users from pasting in longer values. To prevent that, set VALIDATE to Maxlength.

message

All

Validation failure message

Optional message to display upon validation failure.

monthNames

All

Comma-delimited list

Optional; applies to Datefield only. Month names.

name

All

Unique control name

Required.

onChange

HTML, XML

Javascript, actionscript

Optional; runs when control is changed by user. In Flash, only applies when TYPE is Datefield, Text, or Password.

onClick

HTML, XML

Javascript, actionscript

Optional; runs when users clicks the mouse. In Flash, only applies when TYPE is Button, Checkbox, Image Reset, Radio, and Submit.

onError

HTML, XML

JavaScript error function

Optional; JavaScript function used if validation fails.

onKeyUp

HTML, XML

Javascript, actionscript

Optional; runs when user releases a key.

onKeyDown

HTML, XML

Javascript, actionscript

Optional; runs when user presses a key.

onMouseUp

HTML, XML

Javascript, actionscript

Optional; runs when user releases the mouse button.

onMouseDown

HTML, XML

Javascript, actionscript

Optional; runs when user clicks the mouse button down.

onValidate

HTML, XML

JavaScript validation function

Optional; used to specify your own JavaScript validation function. Should return true or false. When used, the VALIDATE attribute is ignored.

pattern

All

Javascript regex pattern

Optional, but required if VALIDATE=Regex (or regular_expression). Leading and trailing slashes should be omitted.

range

All

Min and max values

Optional range for numeric values only;must be specified as two numbers separated by a comma. Use in conjunction with VALIDATE=Range.

required

 

Yes or No

Optional; indicates that value must be supplied; defaults to No.

size

All

Field size

Optional number of characters to display before needing horizontal scrolling. Ignored if TYPE is Radio or Checkbox.

src

Flash

URL to image

Optional; enables you to specify the source image when TYPE is Button, Reset, Submit, and Image in a Flash form.

style

All

CSS or XSL style

Optional. STYLE attribute is passed to the browser when TYPE is HTML or XML. In Flash forms, STYLE must contain a CSS.

type

All

Input type

Must be Button, Checkbox, File, Hidden, Image, Password, Radio, Reset, Submit, or Text Datefield.

validate

All

Field validation

Optional field validation type (see Table B.81).

validateAt

All

Validation location

Optional; indicates what event(s) should result in validation. Set to one or more values from this list, separated by commas: onSubmit, onServer, onBlur.

value

HTML, Flash

Initial value

Optional initial field value. In HTML, it is the same as the VALUE attribute. In Flash it is used to specify text for Button, Submit and Image type inputs.

width

Flash, HTML

Control width in pixels

Optional; works with most Flash type controls and HTML Image type.


Syntax:

 <cfinput   bind="Binding exp"  checked="Yes, No, NULL"  dayNames="day of week labels"  disabled="Yes, No, NULL"  height="Number in pixels"  label="Text"   mask="Mask pattern"  maxLength="Length"   message="Message Text"  monthNames="month labels"   name="Field Name"  onChange="Javascript or Actionscript"  onClick="Javascript or Actionscript"   onError="JavaScipt Error Function"   onKeyDown="Javascript or Actionscript"  onKeyUp="Javascript or Actionscript"  onMouseDown=" Javascript or Actionscript" onMouseUp="Javascript or Actionscript"  onValidate="JavaScript Validation Function"   pattern="Regex exp" range="Max,Min"   required="Yes or No"   size="Field Size"   src="/books/2/448/1/html/2/URL to image"  style="spec"  type="Type"  validate="Validation Type"   validateat="onBlur, onServer, onSubmit"  value="Initial Value"  width="Number in pixels"> 

Table B.81. <cfinput> Validation Types

TYPE

DESCRIPTION

BOOLEAN

Must be convertible to a number, Yes, No, True, or False.

CREDITCARD

Correctly formatted credit card number verified using mod10 algorithm. Must have between 13 and 16 digits.

DATE

Same as USDATE format unless your validateAt setting includes onServer. In this case, it will return True if the isDate() function would return True.

EMAIL

Verifies email format, not validity of actual address.

EURODATE

Looks for months preceding days with /, - or . delimiters. Days and months can have 1-2 digits, years can be 1-4 digits.

FLOAT/NUMERIC

Number with decimal point. Can be an integer.

GUID

A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number

INTEGER

Number with no decimal point.

MAXLENGTH

Limits maximum number of characters that can be input.

NOBLANKS

Prohibits entry of all blanks.

RANGE

Provides min and max values, separated by a comma.

REGEX/REGULAR_EXPRESSSION

Matches input against value of PATTERN attribute.

SOCIAL_SECURITY_NUMBER/SSN

Social security number formatted as 999-99-9999 (using hyphens or spaces as separators).

SUBMITONCE

Prevents user from submitting form multiple times. Only useful with Image and Submit types.

TELEPHONE

Phone number in standard US format (999-999-9999). Will accept hyphens or spaces as separators. Area code and exchange must not begin with 0 or 1. Can include a long distance digit and up to a 5-digit extension, which should begin with x.

TIME

Time in hh:mm or hh:mm:ss format.

URL

Requires a valid URL pattern. Supports HTTP, HTTPS, FTP, FILE, MAILTO, and NEWS URLs.

USDATE

Looks for days preceding months, then years with / delimiters. Days and months can have 1-2 digits, years can be 1-4 digits.

UUID

Requires input formatted like a universally unique identifier in ColdFusion: xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx. Each x must be from the hexadecimal characterset.

ZIPCODE

U.S. ZIP code, in either 99999 or 99999-9999 format. Separator can be either a hyphen or a space.


Example: The following example creates a simple form with several fields. These fields employ several types of data validation using <cfinput>.

 <html> <body> <cfif isDefined("FORM.BeenThere")>   <cfdump var="#FORM#"> </cfif> <!--- creates form ---> <cfform method="POST"> <!--- creates text field ---> <P>Enter your name: <cfinput type="text" name="name" required="Yes"  message="Name is required!" /> <P>Enter your phone number: <!--- creates text field and validates telephone number format---> <cfinput type="text" name="phone" VALIDATE="telephone"  message="You entered an invalid phone number!" /> <!--- creates menu ---> <P>Select credit card: <Cfselect name="ccnumber">  <option>MasterCard  <option>Visa  <option>Amex </cfselect> <!--- creates text field and validates credit card format ---> <P>CC#: <cfinput type="text" name="ccnumber" VALIDATE="creditcard"   maxLength="12"  message="Please enter a valid credit card number!" /> <!--- Get expiration date and validate ---> <P>Expiration date: <cfinput     type = "Text" NAME = "MyDate"     message = "Enter a correctly formatted date (dd/mm/yy)"     validate = "date" required = "no" /> </p> <!--- creates submit button ---> <P><input type="Submit" value="Save" /> </cfform> </body> </html> 

NOTE

<cfinput> does not support input fields of type HIDDEN.


See also <cfform>, <cfgird>, <cfselect>, <cfslider>, <cftextarea>, <cftree>


<cfinsert>

Description: <cfinsert> adds a single row to a database table. <cfinsert> requires that the data source and table names be provided. All other attributes are optional. Table B.82 shows the attributes for this tag. The data source can be a preconfigured data source or defined dynamically by using the value "query". In this case, you also must provide a CONNECTSTRING.

Table B.82. <cfinsert> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

dataSource

Name of ODBC data source or "Query"

Required; can be an existing data source or defined dynamically. In the latter case, use "Query."

formFields

List of fields to insert

Optional attribute; specifies the fields to be inserted, if they are present. Any fields present that are not in the list will not be inserted.

password

ODBC data source password

Optional; used to override the ODBC login password specified in the ColdFusion Administrator.

tableName

Name of table to insert data into

Required; some ODBC data sources require fully qualified table names.

tableOwner

Table owner name

Optional; used by databases that support table ownership.

tableQualifier

Table qualifier

Optional; used by databases that support full qualifiers.

userName

 

Optional; used to override the ODBC login name specified in the ColdFusion Administrator.


Syntax:

 <cfinsert dataSource="ODBC data source"  dbName="database name"  formFields="List of File to Insert"  passWord="Password"   provider="provider"   providerDsn="data source"  tableName="Table Name"   tableOwner="owner"   tableQualifier="qualifier"  userName="User Name"> 

NOTE

Your form field names must match the column names in the destination table for <cfinsert> to work correctly.


TIP

If your form contains fields that are not part of the table into which you are inserting data, use the formFields attribute to instruct ColdFusion to ignore those fields.


TIP

For more control over the insertion of rows into a database table, use the <cfquery> tag, specifying INSERT as the SQL statement.


Example: In the first example, a simple data entry form is used to collect data to be inserted into the Merchandise table:

 <!--- creates form ---> <form action="testinsert_act.cfm" method="post">  <P>film id: <input type="Text" maxlength="5" name="filmid" value="18">  <P>merchandise name: <input type="Text" name="MerchName" maxLength="100">  <P>merchandise desc: <input type="Text" name="Merchdescription">  <P>merchandise price: <input type="Text" name="merchprice">  <p><input type="Submit"> </form> 

This <cfinsert> tag inserts this form data:

 <!--- inserts data into database ---><cfinsert dataSource="OWS" tableName="Merchandise"> 

However, if the form contains additional fields that don't correspond to the fields in the Merchandise table, you must use the formFields attribute to identify the form fields to be inserted:

 <!--- inserts certain form fields into database ---> <cfinsert dataSource="OWS" tableName="Merchandise"  formFields="FilmID,MerchName,MerchDescription,MerchPrice"> 

See also <cfquery>, <cfupdate>, <cfstoredproc>


<cfinvoke>

Description: <cfinvoke> is used to instantiate a ColdFusion component and execute a method in the component. It can also be used to execute a method on a component that was previously instantiated. Note that you can pass values to the method three ways:

  1. As additional, custom attributes in the <cfinvoke> tag.

  2. Through the ARGUMENTCOLLECTION attribute.

  3. Through use of <cfinvokeargument> tag in the body of the <cfinvoke> tag.

A method return value can be specified using the RETURNVAIRABLE attribute. See Table B.83 for a list and description of <cfinvoke> attributes.

Table B.83. <cfinvoke> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

component

Name of component

Optional; required if method is not specified.

method

Name of method

Optional; required if Component is not specified.

returnVariable

Name of variable

Optional; name of a variable that will contain a return value from the method being invoked. That method must contain a <cfreturn>.

argumentCollection

Structure name

Optional; name of a structure containing argument name/value pairs. This is an alternative to explicitly including all of the arguments as individual <cfinvoke> attributes.


NOTE

There are several methods to instantiate components. You can use <cfinoke>, you can use CFScript's CreateObject() function or you can use <cfobject>.


NOTE

Components invoked with <cfinoke> are extant only long enough to execute whatever method is being called. If you need the component to remain extant, use <cfobject> or CreateObject() (in a CFScript) to instantiate it.


Syntax:

 <cfinvoke component="Name of component"  method="Name of method"   returnVariable="Name of return variable"  argumentCollection="Name of a structure containing arguments">...</cfinvoke> 

NOTE

You must specify both the Component and Method attributes to invoke a method on an component that has not yet been instantiated.


Example: The first example demonstrates the use of <cfinvoke> to create an instance of the component, Orders.cfc and to execute its OrderTotal method, passing it a pair of date ranges through the use of <cfinvokeargument> tags:

 <!--- Invokes Orders component and passes some values to   the OrderTotal method. ---> <cfinvoke component="Orders" method="OrderTotal"  returnVariable="OpenOrderTotal">  <cfinvokeargument name="StartDate" value="1/1/2002">  <cfinvokeargument name="EndDate" value="3/22/2002"> </cfinvoke> <!--- Display the returned value ---> <cfoutput>#OpenOrderTotal#</cfoutput> 

This next example demonstrates use of arguments as attributes to <cfinvoke>:

 <!--- Invokes Orders component and passes some values to   the OrderTotal method. ---> <cfinvoke component="Orders" method="OrderTotal"  returnVariable="OpenOrderTotal" StartDate="1/1/2002"  EndDate="3/22/2002"> </cfinvoke> <!--- Display the returned value ---> <cfoutput>#OpenOrderTotal#</cfoutput> 

The last example demonstrates the use of CreateObject() to instantiate the component. It also demonstrates use of an argument structure with <cfinvoke>:

 <!--- Create structure for passing arguments and instantiate  object. ---> <cfscript>  DateRange = StructNew();  DateRange.StartDate = "1/1/2002";  DateRange.EndDate = "3/22/2002";  CreateObject("Component", "Orders"); </cfscript> <!--- Now execute the method and pass it the structure of   arguments. ---> <cfinvoke component="Orders" method="OrderTotal"  returnVariable="OpenOrderTotal"  argumentCollection="#DateRange#"> </cfinvoke> <cfoutput>#OpenOrderTotal#</cfoutput> 

See also <cfinvokeargument>, <cfcomponent>, <cffunction>, <cfarguemnt>, <cfreturn>


<cfinvokeargument>

Description: <cfinvokeargument> is used to pass parameters to a ColdFusion component. See Table B.84 for a list and description of <cfinvokeargument> attributes. Arguments passed to component methods are referenced with the ARGUMENTS scope inside the component.

Table B.84. <cfinvokeargument> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Name of argument

Required; name of argument to be passed.

omit

Forces omission

Optional; defaults to No. Indicates whether or not argument should be omitted.

value

Name of method

Required; value to be passed to method.


NOTE

There are other methods of passing values to ColdFusion components. These include including your own custom attributes in a <cfinvoke> tag and using the CFARGUMENTCOLLECTION attribute in <cfinvoke>.


Syntax:

 <cfinvokeargument   name="Name of argument"  omit="Yes or No"  value="Value to be passed"> 

NOTE

Arguments are passed by value, not by reference, meaning that any changes the invoked method makes to the argument will not be reflected in the value of the argument once control returns from the component.


Example: This example demonstrates the use of <cfinvokeargument> to pass to an actor's name, which is used as a selection criteria in the Films component:

 <!--- Here it the code that invokes the comopnent,   passing it the actor's name. ---> <cfinvoke component="Films" method="GetFilms">  <cfinvokeargument name="NameFirst" value="Sam">  <cfinvokeargument name="NameLast" value="Gold"> </cfinvoke> <!--- Here is the component that processes this request ---> <cfcomponent>  <cffunction name="GetFilms">  <cfargument name="NameLast" required="Yes">  <cfargument name="NameFirst" required="Yes">  <cfquery name="FindActorsFilms" dataSource="OWS">  SELECT FilmID   FROM FilmsActors FA INNER JOIN Actors A  ON FA.ActorID = A.ActorID  WHERE  A.NameFirst = '#ARGUMENTS.NameFirst#'  AND A.NameLast = '#ARGUMENTS.NameLast#'  </cfquery>  <cfreturn #FindActorsFilms.FilmID#>  </cffunction> </cfcomponent> 

See also <cfinvoke>, <cfcomponent>, <cffunction>, <cfarguemnt>, <cfreturn>


<cfldap>

Description: <cfldap> is used for all interaction with LDAP servers. It can be used to search an LDAP server, as well as to add, change, or delete data. Table B.85 lists the attributes for <cfldap>.

Table B.85. <cfldap> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required; specifies one of the actions in Table B.86.

attributes

Desired attributes

Required if action is Query, Add, Modify, or Modifydn; comma-delimited list of desired attributes; query specified in name attribute will contain these columns.

dn

Distinguished name

Required if action is Add, Modify, Modifydn, or Delete.

maxRows

Maximum rows to

Optional attribute. modifyType Adds, deletes, or replaces attribute Optional; Add, Delete, or Replace. Used to modify an attribute.

name

Query name

Name of query for returned data; required if action is QUERY.

passWord

User password

Optional user password; might be required for update operations. Required if SECURE is set to CFSSL_BASIC.

port

Port number

Optional port number; defaults to 389 if not specified.

rebind

Rebinds referral callback

Optional; Yes or No; reissues query using original credentials.

referral

Number of hops

Optional; specifies number of hops a referral is limited to.

returnAsBinary

Return data format

Optional; defaults to No.

scope

Search scope

Optional; search scope if action is Query; valid values are Onelevel, Base, and Subtree; default is Onelevel.

secure

Type of security

Optional; CFSSL_BASIC. Must include additional information specified in Table B.87.

separator

Separator character

Optional; the character LDAP will use to separate values in multivalued attributes.

server

Server name

Required DNS name or IP address of LDAP server.

sort

Sort order

Optional attribute; used if action is Query; specifies the sort order as a comma-delimited list; can use Asc for ascending and Desc for descending; default is Asc.

sortControl

How to sort query results

Optional; enter Nocase; default is case-sensitive Asc or Desc.

start

Start name

Required if action is Query; distinguished name to start search at.

startRow

Start row

Optional start row; defaults to 1.

timeout

Timeout value

Optional timeout value; defaults to 1 minute.

userName

User login name

Optional user login name; might be required for update operations. Required if SECURE is set to CFSSL_BASIC.


Syntax:

 <cfldap action="Action"  attributes="Attributes List"  dn="Name"  filter="Filter"  maxRows="Number"  modifyType="Modification type"  name="Query Name"  passWord="Password"  port="Port Number"  rebind="Yes or No"   referral="Hops"  returnAsBinary="Yes or No"  scope="Scope"  secure="Security type"  separator="Separator character"  server="Server Address"  sort="Sort Order"  sortControl="Ascending or Descending"  start="Start Position"  startrow="Number"  timeout="Timeout"  username="Name"> 

Table B.86. <cfldap> Actions

ACTION

DESCRIPTION

ADD

Adds an entry to an LDAP server.

DELETE

Deletes an entry from an LDAP server.

MODIFY

Updates an entry on an LDAP server.

MODIFYDN

Updates the distinguished name of an entry on an LDAP server.

QUERY

Performs a query against an LDAP server (default action).


Table B.87. Variables for Use with the SECURE Attribute

SECURE VALUE

DESCRIPTION

CFSSL_BASIC

You must provide the name of the certificate database file (in Netscape cert7.db format).

Certificate_db

Actual name of certificate database file. Can be an absolute path or simple filename.


Example: The following example retrieves a list of names from a public directory:

 <!--- creates variable ---> <cfset name="John Doe"> <!--- queries LDAP server, starts and filters on variable,  sorts results ---> <cfldap server="ldap.bigfoot.com"  action="QUERY"  name="results"  start="cn=#Name#,c=US"  filter="(cn=#Name#)"  attributes="cn,o,mail,p"  SORT="cn ASC"> <cftable query="results" border="yes" htmlTable="Yes">  <cfcol header="Name" text="#cn#">  <cfcol header="Org" text="#o#">  <cfcol header="Email" text="<a href='mailto:#mail#'>#mail#</a>"> </cftable> 

<cflocation>

Description: <cflocation> is used to redirect a browser to a different URL. See Table B.88 for a description of this tag's attributes.

Table B.88. <cflocation> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

addToken

Adds session tokens

Optional attribute; default is Yes.

URL

URL (or relative URL) to redirect to

This attribute is required.


Syntax:

 <cflocation addToken="Yes or No"   URL="URL"> 

Example: The following example redirects the user to a login page if they are not already logged in (as indicated by the presence of a session variable named LoggedIn):

 <!--- checks for user's login status ---> <cfif NOT IsDefined("SESSION.LoggedIn")>  <!--- if not logged in, user is sent to login page --->  <cflocation URL="login.cfm"> </cfif> 

NOTE

Because <cflocation> needs to write to the HTTP header, you can't use it if you've already flushed the header from the ColdFusion output buffer with <cfflush>.


NOTE

If your template creates cookies and then redirects the user to another template with <cflocation>, the cookies will not be created. In this situation, use <meta HTTP-EQUIV="refresh">, JavaScript, or some other directive to redirect the user.


NOTE

Unlike <cfinclude>, any text or CFML after the <cflocation> tag is ignored by ColdFusion.


See also <cfinclude>


<cflock>

Description: <cflock> is used to synchronize access to blocks of code. Once inside a locked block of code, all other threads are queued until the thread with the exclusive lock relinquishes control. Table B.89 lists the <cflock> attributes.

Table B.89. <cflock> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Name for a lock

Optional; only one request with a given name can execute at a time.

scope

Scope of lock

Optional; should not be used with name. SCOPE is set to Application, Server, or Session. This identifies the scope of the shared item being locked.

timeout

Timeout interval

This attribute is required.

type

Lock type

Optional; Readonly or Exclusive.

throwOnTimeout

Timeout handling

This optional attribute specifies how timeouts should be handled; an exception is thrown if Yes; processing continues if No; defaults to Yes.


Syntax:

 <cflock name="lock name"   scope="Application or Session or Server"  type="Readonly or Exclusive"   timeout="timeout"   throwOnTimeout="Yes or No"> </cflock> 

This tag is intended for use over small sections of code in which you are accessing a shared resource, such as certain types of variables (SESSION, APPLICATION, and SERVER variables), server filesystems, or other shared resources (for example, <cffile>). Set TYPE to READONLY when you're just checking and not updating a session variable, and use type=Exclusive when you're writing to a variable.

Example: The following example locks a session variable to check for its existence. Then, if the SESSION variable isn't defined, an exclusive lock is issued for the purpose of writing to it and the user is redirected to the login part of the application:

 <!--- locks LoggedIn session variable ---> <cflock type="ReadOnly" scope="SESSION"> <!--- sets LoggedIn variable according to whether  or not the user is logged in ---> <cfset LoggedIn=IsDefined("SESSION.LoggedIn")> </cflock> <!--- if the user is not logged in, variable is  locked and set to False ---> <cfif NOT LoggedIn>  <cflock type="Exclusive" scope="SESSION">  <cfset Session.LoggedIn=False>  </cflock>  <!--- user is directed to login page --->  <cflocation URL="/Login/Login_Form.cfm"> </cfif> 

CAUTION

Avoid unnecessary use of <cflock>. Restricting access to chunks of code can affect performance.


See also <cfcatch>, <cftry>


<cflog>

Description: <cflog> enables you to produce user-defined log files. They can be targeted to run only for specified applications or tasks. This ability to produce logs on an application basis is intended primarily for ISPs. The attributes for this tag are presented in Table B.90.

Table B.90. <cflog> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

application

Yes or No

Optional; indicates whether to log the application name (from <cfapplication>) if one was used. Defaults to Yes.

date

Yes or No

Optional; indicates that you want to log the system date. No option has been deprecated.

file

Full filename

Optional; specifies the name of a custom log file.

log

Log type

Optional; User, Application, or Scheduler. It defaults to User if FILE is specified but LOG isn't; it defaults to Application if neither FILE nor LOG is specified. Application logs information only for the application named in the current <cfapplication> tag. Scheduler logs execution of tasks in the ColdFusion scheduler.

text

Message for log

Required; text of entry to be written to log.

thread

Yes or No

Optional; causes thread ID to be logged. No option has been deprecated.

time

Yes or No

Optional; causes system time to be logged. No option has been deprecated.

type

Message type

Optional; see Table B.91 for a list of message types.


Syntax:

 <cflog application="Yes or No"   text="text"   log="log type"   file="filename"  type="message type"   thread="yes"   date="yes"  time="yes"   application="yes or no"> 

Table B.91. Message Types in Order of Severity

TYPE

DESCRIPTION

INFORMATION

Simple informational message.

WARNING

A problem of some sort might have occurred.

ERROR

An error has occurred.

FATAL INFORMATION

Fatal error has occurred.


Example: This example involves writing to a custom log for the current application. It is invoked when a user makes more than three unsuccessful login attempts:

 <!--- checks whether login attempts are greater than 3 ---> <cfif FORM.LoginAttempts GT 3>  <!--- creates log with user's IP address --->  <cflog text="Invalid login attempt: #CGI.REMOTE_ADDR#"  file="C:\INETPUB\WWWROOT\OWS\OWS_SECURITY.LOG"  type="Information"> </cfif> 

<cflogin>

Description: <cflogin> is part of ColdFusion's security framework. This tag acts as a shell for authenticating users. When you authenticate users within the body of this tag, ColdFusion can track their authentication properties, such as the roles or groups that they are in. This tag has no attributes. You write the code that does the authenticating in the body of <cflogin>. Use <cfloginuser> after authenticating the user to pass the user's user name and roles to ColdFusion's security framework. The attributes for <cflogin> are presented below in Table B.92.

Table B.92. <cflogin> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

applicationToken

Unique application name

Optional; unique name identifying this ColdFusion application. Logins will be limited to the scope of this application.

cookieDomain

Domain name

Optional; indicates the domain in which a security cookie is valid.

idleTimeout

Seconds

Optional; defaults to 1800. Number of seconds that a login can remain idle (no activity) before user is logged out.


NOTE

You must include <cfloginuser> in the body of the <cflogin> tag.


Syntax:

 <cflogin  idleTimout="seconds"  applicationToken="Application name"  cookieDomain="Domain of security cookie" >  <cfloginuser> </cflogin> 

Example: The following example resides within an application's application.cfm file. It makes sure that a user has successfully authenticated before he or she can retrieve any ColdFusion templates within the scope of the application. It can also insure that a user is logged out after a specified amount of idle time.

Here's how it works. Assume that prior to authenticating, a user requests a ColdFusion template from an application. The application.cfm file executes first, as always.

ColdFusion only executes the <cflogin> block if the user's authentication information is not present. If the user hasn't been presented with the authentication form yet, it is presented. Note that the action attribute of the form simply points to the originally requested URL. So when the user submits the form (after filling in a user login name and password), the form is submitted back to itself. This causes the APPLICATION.CFM to be called again, but as a result of the form submission, the FORM.UserLogin variable will be present.

The presence of the FORM.UserLogin variable causes the next section to execute. This section performs a database query to attempt to authenticate the user. This could be replaced by a query into an LDAP directory or some other data store used for security information for this application.

Assuming the user has authenticated properly, then <cfloginuser> is used to log the user into the ColdFusion security framework. If the user didn't authenticate properly, he or she would be presented with a message to that effect and a link to try again. Note that the link just points to the template that the user originally requested, and this will simply force the whole process to run again.

 <!--- The CFLOGIN block is executed if user has not  logged in yet. ---> <cflogin>   <!--- Only execute this section if user needs to log in --->   <cfif not isdefined("Form.UserLogin")>     <!--- Create login form --->     <cfoutput><form action="#CGI.SCRIPT_NAME#" method="post">     </cfoutput>     <p>Domain: <input type="Text" name="Domain">     <p>User Login: <input type="Text" name="UserLogin">     <p>Password: <input type="Password" name="PW">     <p><input type="Submit">     </form>     <cfabort>   <cfelse>     <!--- If this section executes, then the user     has filled in the login form. This section     authenticates the user against the NT Domain     on the CF Server, which the user mus specify --->     <cfntauthenticate       username="#FORM.UserLogin#"       pasSword="#FORM.PW#"       domain="#FORM.Domain#"       result="Authenticated"     >     <!--- If user authenticated, log him/her in to     the ColdFusion security framework. --->      <cfif authenticated.auth>       <cfloginuser name="#Form.UserLogin#"        roles="Manager" passWord="#Form.PW#">     <cfelse>       <!--- User didn't authenticate. Let him/her try again --->       <p>You have not authenticated properly.</p>        <cfoutput><p>#Authenticated.Status#</p>       <p><a href="#CGI.SCRIPT_NAME#">Try again</a></p>       </cfoutput>       <cfabort>     </cfif>   </cfif> </cflogin> 

NOTE

Using CGI.SCRIPT_name to determine the requested URL is not enough. A more thorough approach would handle the presence of query strings.


NOTE

In this example, the user's roles were simply hard-coded. In an actual production system, you would probably retrieve this information from the security data repository.


NOTE

The IsUserInRole() function is used to on pages where either the entire page or some part of it is restricted to only users in specific roles. It works as part of the ColdFusion security framework to complete the authorization side of the framework.


See also <cfloginuser>, <cflogout>, <cffunction>, <cfapplication>, <cfntauthenticate>


<cfloginuser>

Description: <cfloginuser> is part of ColdFusion's security framework. This tag must be used in a <cflogin> block. It is used to provide login information (user name and user roles) to the ColdFusion security framework. The attributes for <cfloginuser> are presented in Table B.93.

Table B.93. <cfloginuser> attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

User name

Required; this is the user name or ID by which this user will be recognized throughout the security framework.

passWord

User password

Required; the user's password is required to log in.

roles

List of user roles

Required; this is an array of roles for the authenticated user. It can be referenced in calls to <cffunction> or with use of the IsUserInRole() function when you need to check user access to restricted functionality within your application.


ColdFusion uses the SESSION scope to make this authentication information persist. You must have SESSION variables enabled in your ColdFusion Administrator and in your application's <cfapplication> tag.

Syntax:

 <cfloginuser  name="User name or ID"  passWord="User's password"  roles="Array of user's security roles"> 

Example: Please see the example in <cflogin>.

See also <cflogin>, <cflogout>, <cffunction>, <cfapplication>, <cfntauthenticate>


<cflogout>

Description: <cflogout> is used to log a user out of ColdFusion's security framework. It has no attributes. In the ColdFusion security framework, you log users into your system (and into the framework) with the <cflogin> and <cfloginuser> tags. When you want log them out, you provide a link to a page that executes the <cflogout> tag. Note that there are no attributes.

Syntax:

 <cflogout> 

Example: Begin by reviewing the immediately preceding example in <cflogin>. Assuming you wanted to provide users with the ability to log out, you could include a link on a page that logs a user out. The page can consist only of the <cflogout> tag.

 <!--- Log out of CF security framework ---> <cflogout> <!--- Display link enabling user to log back in ---> <html> <head>  <title>Logout Page</title> </head> <body> <P>You have been logged out. <!--- Note that you can point to any CF page in  the authenticated part of your application if   you're using <cflogin> in the APPLICATION.CFM  page. ---> <P><a href="SomeAuthenticatedPage.cfm">Log back in.</a> </body> </html> 

See also <cflogin>, <cfloginuser>, <cffunction>, <cfapplication>, <cfntauthenticate>


<cfloop>

Description: <cfloop> enables you to create loops within your code. Loops are blocks of code that are executed repeatedly until a specific condition is met. <cfbreak> enables you to terminate a loop unconditionally. ColdFusion supports five types of loops:

  • For. These loops repeat a specific number of times.

  • While. These loops repeat until a set condition returns FALSE.

  • Query. These loops go through the results of a <cfquery> once for each row returned.

  • List. These loops go through the elements of a specified list.

  • Collection. These loops are used to loop over collections.

Table B.94 shows attributes for this tag.

Table B.94. <cfloop> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

collection

Collection to loop through

This attribute is required for Collection or structure loops.

condition

While loop condition

This attribute is required for While loops and must be a valid condition.

delimiters

List loop delimiters

This is an optional List loop attribute; if it is omitted, the default delimiter of a comma is used.

endRow

Query loop end position

This is an optional Query loop attribute; if it is omitted, all rows are processed.

from

For loop start position

This attribute is required for For loops and must be a numeric value.

index

Current element

This attribute is required for For loops and List loops, and holds the name of the variable that will contain the current element.

item

Current item

This attribute is required for Collection loops.

list

List loop list

This attribute is required for List loops and can be a ColdFusion list field or a static string.

query

Query loop query

This attribute is required for Query loops and must be the name of a previously executed <cfquery>.

startRow

Query loop start position

This is an optional Query loop attribute; if it is omitted, the loop will start at the first row.

step

For loop step value

This is an optional For loop attribute; if it is omitted, the default value of 1 is used.

to

For loop end position

This attribute is required for For loops and must be a numeric value.


Syntax:

For loop:

 <cfloop index="Index"   from="Loop Start"   to="Loop End"   step="Step Value"> </cfloop> 

While loop:

 <cfloop condition="Expression"> </cfloop> 

Query loop:

 <cfloop query="Query Name"   startRow="Start Row Value"   endRow="End Row Value"> </cfloop> 

List loop:

 <cfloop index="Index"   list="List"   delimiters="Delimiters"> </cfloop> 

Collection loop:

 <cfloop collection="Collection"   item="Item"> </cfloop> 

NOTE

The syntax and use of <cfloop> varies based on the type of loop being executed.


Example: The following is a For loop used in a form to populate a select field with the years 1901and 2000. The alternative would have been to enter 100 option values manually:

 <!--- creates select field ---> <select name="year"> <!--- loop populates select field with years sequentially ---> <cfloop index="YearValue" from="1901" to="2000">  <option><cfoutput>#YearValue#</cfoutput> </cfloop> </select> 

The next example does the exact same thing but presents the list in reverse order. This is done by specifying a STEP value of -1:

 <!--- creates select field ---> <select name="year"> <!--- loop populates select field with years in reverse ---> <cfloop index="YearValue" from="2000" to="1901" step="-1">  <option><cfoutput>#YearValue#</cfoutput> </cfloop> </select> 

This example loops until any random number between 1 and 10, excluding 5, is generated:

 <!--- sets variable ---> <cfset RandomNumber=0> <!--- loop generates random number greater than or equal to zero and not equal to 5 ---> <cfloop condition= "(RandomNumber GTE 0) AND (RandomNumber NEQ 5)">  <cfset RandomNumber=RandRange(1, 10)> </cfloop> 

This example creates a Query loop that processes an existing <cfquery> named Orders, but it processes only rows 100150:

 <!--- gets raw data from database ---> <cfquery name="Orders"   dataSource="OWS" > SELECT OrderNum, OrderDate, Total FROM Orders </Cfquery> <!--- loops over query from row 100 to row 150 ---> <cfloop query="Orders" startRow="100" endRow="150">  <!--- djsplays results --->  <cfoutput>  #OrderNum# - #DateFormat(OrderDate)# - #DollarFormat(Total)#<br>  </cfoutput> </cfloop> 

This example loops through a user-supplied list of titles, displaying them one at a time:

 <!--- loops over titles passed from form ---> <cfloop index="Title" list="#FORM.Titles#">  <!--- displays results --->  <cfoutput>  Title: #Title#<br>  </cfoutput> </cfloop> 

This example uses <cfbreak> to terminate a loop when a specific row is reachedin this case, an order number greater than 10,000:

 <!--- gets raw data from database ---> <cfquery name="Orders"   dataSource="OWS" > SELECT OrderNum, OrderDate, Total FROM Orders </Cfquery> <!--- loops over query ---> <cfloop query="Orders">  <!--- if orders number greater than 10,000, loop processing stops --->  <cfif OrderNum GT 10000>  <cfbreak>  </cfif>  <!--- displays results --->  <cfoutput>  #OrderNum# - #DateFormat(OrderDate)# - #DollarFormat(Total)#<br>  </cfoutput> </cfloop> 

This last example involves nesting a COLLECTION loop inside an INDEX loop.

 <!--- creates color structure ---> <cfscript>  Colors = StructNew();  Colors["Red"] = 1;  Colors["Green"] = 2;  Colors["Blue"] = 3;  Colors["Yellow"] = 4;  Colors["Orange"] = 5;  Colors["Pink"] = 6;  Colors["Brown"] = 7;  Colors["Black"] = 8;  Colors["Tan"] = 9;  Colors["White"] = 10; </cfscript> <!--- loops over collection loop ---> <cfloop FROM="1" TO="4" INDEX="ii">  <!--- loops over color structure --->  <cfloop collection="#Colors#" ITEM="Color">  <br><cfoutput><font COLOR="#Color#" SIZE="#ii#">#Color# = #Colors[Color]#  </font></cfoutput>  </cfloop> </cfloop> 

TIP

Using <cfloop> to process queries is slower than using <cfoutput>. Whenever possible, use <cfoutput> to loop through query results.


NOTE

The <cfloop> tag can be nested, and there is no limit placed on the number of nested loops allowed.


See also <cfbreak>


<cfmail>

Description: <cfmail> generates SMTP mail from within ColdFusion templates. <cfmail> can be used to output query results, just like <cfoutput>, or on its own. The <cfmail> tag itself is used to set up the mail message, and all text between the <cfmail> and </cfmail> tags is sent as the message body. <cfmail> requires that you specify a sender address, recipient address, and subject. All other attributes are optional. Table B.95 shows the attributes for this tag.

Table B.95. <cfmail> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

bcc

Blind carbon copy addresses

Optional; blind carbon copy addresses.

cc

Carbon copy addresses

Optional; one or more carbon copy addresses separated by commas.

charset

Character encoding

Optional; defaults to UTF-8. Specifies encoding for the message and headers.

contentId

Globally unique ID

Unique identifier used to identify the file, IMG or other tag in the message body that references file content.

disposition

Attachment or Inline

Indicates how attached file shall be handled.

failTo

Email address

Optional address to which delivery failure notifications should be sent.

from

Sender's address

Required; sender's email address.

group

Query column to group on

Optional; column to group on. See <cfoutput> for more information on grouping dat1.

groupCaseSensitive

Enables grouping with respect to case

Optional. If the specified QUERY was generated from case-insensitive SQL, setting this to NO (it defaults to Yes) will preserve order of query.

mailerId

ID for X-Mailer SMTP header

Optional; enables you to specify an X-Mailer ID for the SMTP header. Defaults to Allaire ColdFusion Application Server.

maxRows

Maximum messages to send

Optional attribute specifying the maximum number of email messages to generate.

mimeAttach

Fully qualified filename

Optional; pathname to file that will be attached as a MIME-encoded attachment.

passWord

User's password

Optional; used in conjunction with USERname when the server requires authentication.

port

TCP/IP SMTP port

Optional TCP/IP SMTP port; overrides the default value of 25 if specified.

query

<cfquery> to draw data from

Email can be generated based on the results of a <cfquery>; to do this, specify the name of the <cfquery> here. This is an optional attribute.

replyTo

Email address

Optional address to which replies should be sent.

server

SMTP mail server

Optional; SMTP mail server name; overrides the default setting if specified.

spoolEnable

Yes or No

Optional. Yes stores a copy of the message until sending is complete. No simply places message in queue (no copy made) for sending.

subject

Message subject

Required; message subject.

timeout

Connection timeout interval

Optional; SMTP connection timeout interval overrides the default setting if specified.

to

Recipient's address

Required; recipient's email address.

type

Message type

Optional message type; currently the only supported type is HTML, indicating that HTML code is embedded in the message.

userId

User's account name

Optional; used in conjunction with passWord when the server requires authentication.

WRAPTEXT

Integer length of line

Optional; indicates the length a line in the message body can be before it is wrapped.


Syntax:

 <cfmail   bcc="Blind CC Addresses"   cc="Carbon Copy Addresses"  charset="Char encoding"  content  disposition="Attachment or Inline"  failTo="Email address"  from="Sender Address"  group="Group Name"   groupCasesenSitive="Yes or No"  mailer  maxRows="Maximum Mail Messages"  mimeAttach="Pathname"   passWord="Password text"  port="SMTP TCP/IP Port"   query="Query Name"  replyTo="Email address"  server="SMTP Server Address"   spoolEnable="Yes or No"  startRow="Query row to start from"  subject="Subject"   timeout="SMTP Connection Timeout"  to="Recipient Address"   type="Message Type"  user  wrapText="Max Length"> </cfmail> 

Example: The following is a simple email message based on a form submission. It uses form fields in both the attributes and the message body itself:

 <!--- creates email ---> <cfmail from="#FORM.EMail#"  TO="sales@orangewhipstudios.com"  subject="Customer inquiry">  <!--- email body --->  The following customer inquiry was posted to our Web site:  Name: #FORM.name#  email: #FORM.EMail#  Message:  #FORM.Message# </cfmail> 

This next example sends an email message based on <cfquery> results. The message is sent once for each row retrieved:

 <!--- gets raw data from database ---> <cfquery name="GetInquiries" dataSource="OWS">  SELECT * FROM WebQueries </cfquery> <!--- creates email ---> <cfmail from="sales@orangewhipstudios.com"  TO="sales@orangewhipstudios.com"  subject="Customer inquiry"  query="GetInquiries">  <!--- email body --->  The following customer inquiry was posted to our Web site:  Name: #GetInquiries.name#  email: #GetInquiries.EMail#  Message:  #GetInquiries.Message# </cfmail> 

The next example sends an email message based on <cfquery> results. The message is sent once for each row retrieved. Note that it also specifies a mail server other than the default SMTP server defined in the ColdFusion Administrator.

 <!--- gets raw data from database ---> <cfquery name="GetMailingList" dataSource="OWS">  SELECT FirstName, Email  FROM Contacts  WHERE MailingList = 1 </cfquery> <!--- creates email ---> <cfmail query="GetMailingList"  from="Sales@orangewhipstudios.com"  to="#Email#"  subject="Buy our stuff"  server="mail.orangewhip.com"  mimeAttach="C:\OWS\Catalog\Catalog2001.pdf">  <!--- email body --->  Dear #FirstName#,  We sure would appreciate it if you'd visit our  Web site and buy some of our junk.  Please find our catalog attached.  Thanks.  The Management   Orange Whip Studios </cfmail> 

NOTE

Unlike Web browsers, email programs do not ignore white space. Carriage returns are displayed in the email message if you embed carriage returns between the <cfmail> and </cfmail> tags.


NOTE

If you specify HTML in the TYPE attribute, you can send email consisting of HTML code. This has become popular in recent years because it gives users much more control over the formatting, but users must still consider whether the recipients' email client software supports HTML.


NOTE

To use <cfmail>, the ColdFusion SMTP interface must be set up and working. If email is not being sent correctly, use the Cold Fusion Administrator to verify that ColdFusion can connect to your SMTP mail server.


NOTE

The PORT, SERVER, and TIMEOUT attributes will never be used in normal operation. These are primarily used for debugging and troubleshooting email problems.


NOTE

Email errors are logged to the \CFUSION\MAIL\LOG directory. Messages that can't be delivered are stored in the \CFUSION\MAIL\UNDELIVER directory.


See also <cfmailparam>, <cfpop>


<cfmailparam>

Description: <cfmailparam> is used inside <cfmail> </cfmail> tags and is used to specify additional headers and file attachments. Note that you can use several <cfmailparam> tags within each <cfmail>. Table B.96 shows attributes for this tag.

Table B.96. <cfmailparam> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

contentId

Identifier for attached file

Optional; used to identify attached file in IMG or other tag in mail body that references FILE content.

disposition

How attached file is to be handled

Optional; indicates handling of attached file specified in FILE attribute. Defaults to Attachment. Can be set to Inline.

file

Full pathname to file to be attached

Required if name is not specified.

name

Name of SMTP mail header

Required if FILE is not specified. Do not use both type and name attributes.

type

MIME media type abbreviation

Optional; indicates type of file. Use Text or Plain to specify text/plain, HTML to specify text/html. Do not use both type and name attributes.

value

Header value

Required if name is specified.


Syntax:

 <cfmailparam   content  disposition="Attachment or Inline"  file="FileName"   name="Header name"  type="MIME Type"   value="Header value"> 

Example: This example sends an email to a specific address, specifying a particular reply-to header and attaching two files:

 <!--- creates email ---> <cfmail from="MrBig@OrangeWhipStudios.com"  TO="you@domain.org"   subject="We need your eyes">  <!--- email body --->  Please consider putting your eyeballs on our Web site:  www.orangewhipstudios.com  Thank you,  The Management  <!--- attaches two files and a reply-to address to email --->  <cfmailparam file="c:\temp\tcmnote.txt">  <cfmailparam file="c:\temp\more.HTM">  <cfmailparam name="Reply-To" value="John Doe <JOHN@doe.com>"> </cfmail> 

See also <cfmail>, <cfmailpart>


<cfmailpart>

Description: <cfmailpart> is used inside <cfmail> </cfmail> tags and is used to specify one part of a multi-part message. Table B.97 shows attributes for this tag.

Table B.97. <cfmailpart> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

charSet

Character encoding

Optional; defaults to UTF-8. Specifies encoding for the message and headers.

type

MIME media type abbreviation

Optional; indicates type of file. Use Text of text/plain, HTML to specify text/html.

wrapText

Integer length of line

Optional; indicates the length a line in the message body can be before it is wrapped.


Syntax:

 <cfmailpart  charSet="Character set name"  type="MIME type"   wrapText="Line length integer"> 

Example: This example sends an email that has two parts, HTML and plain text:

 <cfmail from="Bill@yahoo.com" to="John@msn.com"   subject = "Here's the same message, twice. Almost...">   <cfmailpart type="html">     <h3>This is the HTML part</h3>     <p>This section of the email is brought to you in <em>HTML format</em>     for your viewing pleasure.</p>   </cfmailpart>   <cfmailpart type="Text" wraptext="16">     This part is just text.     This section of the email is brought to you in plain old text and     will break after 16 characters.   </cfmailpart> </cfmail> 

See also <cfmail>, <cfmailparam>


<cfmodule>

Description: <cfmodule> is used to call a custom tag explicitly by stating its full or relative path. This is necessary when the custom tag template is not in the current directory. Table B.98 lists the <cfmodule> attributes. Your own tag attributes also can be added to this list.

Table B.98. <cfmodule> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Fixed path to tag file

Either Template or name must be used, but not both at once; use a period for directory delimiters.

template

Relative path to tag file

Either Template or name must be used, but not both at once.

attribute_n

Your attribute/value pairs

Optional; you add your custom tag's attributes to your call.

attributeCollection

Key/value pairs stored in a structure

Optional; alternative to specifying your attributes one at a time.


Syntax:

 <cfmodule name="Path"   template="Path"   attribute_n=value_n  attributeCollection="Structure"> 

NOTE

When using the name attribute, you place the custom tag template either in the ColdFusion custom tags directory (which by default is in C:\CFUSION\CUSTOMTAGS) or in a directory beneath ColdFusion's custom tags directory. Use periods (.) as delimiters between subdirectories.


NOTE

When using TEMPLATE, you must specify either a path relative to the current directory or a path that has been mapped in the ColdFusion Administrator.


Example: This example calls a custom tag named DUMPQUERY.CFM in the directory C:\CFUSION\CUSTOMTAGS\OUTPUT:

 <!--- gets raw data from database ---> <cfquery dataSource="OWS" name="GetContacts">  SELECT FirstName, LastName, Address  FROM Contacts  WHERE State IS NOT NULL </cfquery> <!--- calls custom tag DUMPQUERY and passes attributes to it ---> <cfmodule name="OUTPUT.DUMPQUERY"   query="GetContacts"   border="1"   maxrows="2"> 

See also <cfassociate>


<cfntauthenticate>

Description: <cfntauthenticate> is used to authenticate a username and password against the NT Domain of the server on which CF is running. It will optionally lists the groups which the user belongs to. It is intended for use within the <cflogin> tag to authenticate the user. It produces output in a struct variable, which you name in RESULT attribute. Table B.99 lists the <cfntauthenticate> attributes. Table B.100 describes the elements in the result variable.

Table B.99. <cfntauthenticate > Attributes

ATTRIBUTE

DESCRIPTION

NOTES

domain

NT Domain name

Required. Must name the NT Domain on which the CF server is running.

listGroups

Lists user's groups

Optional; defaults to No. Indicates whether or not you want the tag to return a list of the user's NT groups. It will be a comma-delimited list in the variable (structure) specified in RESULT.

passWord

User's password

Required.

result

Variable name

Optional; results will be returned in this structure variable.

throwOnError

Yes or No

Optional; defaults to No. Indicates whether or not a CF error should be thrown if authentication fails.

userName

User's login name

Required.


Table B.100. Structure of variable specified in RESULT attribute

VARIABLE

DESCRIPTION

Auth

Yes or No. Indicates whether or not authentication was successful.

Groups

Comma-delimited list of group that the user is part of. This variable is only included in the structure if the tag's listgRoups attribute is set to Yes.

Status

Will be one of three values, depending on user's authentication status: Success, UserNotInDirFailure, or AuthenticationFailure (password isn't valid).


Syntax:

 <cfntauthenticate   domain="NT Domain"  listGroups="Yes or No"  passWord="Password"  result="Variable name"  throwOnError="Yes or No"  userName="Username"> 

NOTE

This tag only works for CF installed on Windows systems. It won't work when CF is installed, for example, on Linux or Unix.


Example: Please see the example provided for <cflogin>

See also <cflogin>, <cflogout>, <cfloginuser>


<cfobject>

Description: <cfobject> enables you to use COM, Java, CORBA objects, and ColdFusion components within your ColdFusion applications. You need to know an object's ID or filename to use it, as well as its methods and properties. <cfobject> attributes vary depending on the type of object with which you are working. The attributes for each type are listed in the Tables B.101 through B.104.

Table B.101. <cfobject> Attributes for COM

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required; must be either CREATE to instantiate an object or CONNECT to connect to a running object.

class

Component ProgID

Required attribute.

context

Operation context

Optional attribute; must be INPROC, LOCAL, or REMOTE. User's Registry setting is not specified.

name

Object name

Required attribute.

server

Valid server name

Server name as UNC, DNS, or IP address; required only if CONTEXT = "remote".

type

Object type

Required; set to COM.


NOTE

You should use <cfobject> to instantiate a ColdFusion component on which you plan to call methods several times in the same page, rather then simply calling <cfinvoke>. When you use <cfinvoke>, the object is instantiated only long enough to execute the specified method and is then immediately destroyed.


To use an object with <cfobject>, that object must be already installed on the server.

Syntax:

 <cfobject type="COM"  action="Action"      context="Context"   name="Name of instantiated object"  server="Server Name"> <cfobject type="JAVA"  action="Action"      name="Name of instantiated object"> <cfobject type="CORBA"     context="Context"   name="Name of instantiated object"  locale="Type/value pairs"> <cfobject component="ColdFusion component name"   name="Name of instantiated object" > 

Table B.102. <cfobject> Attributes for CORBA

ATTRIBUTE

DESCRIPTION

NOTES

class

Component ProgID

Required; if CONTEXT is IOR, this names the file containing the IOR; must be readable by ColdFusion; if CONTEXT is nameSERVICE, specifies period-delimited class name.

context

Operation context

Required; IOR or nameService.

locale

Type/value pair

Optional, specific arguments to VisiBroker orbs.

name

Object name

Required attribute.

type

Object type

Required; set to CORBA.


Table B.103. <cfobject> Attributes for Java

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required; set to CREATE for creating objects under WebLogic.

class

Component ProgID

Required; name of Java class.

name

Object name

Required; name used in CFML to address object.

type

Object type

Required; set to JAVA.


Table B.104. <cfobject> Attributes for ColdFusion components

ATTRIBUTE

DESCRIPTION

NOTES

component

Component name

Required; name of .CFC file.

name

Name for object

Required; name by which this instantiated object will be addressed.


Example: The first example instantiates a COM object named NT.Exec and invokes a method:

 <!--- instantiates COM object ---> <cfobject type="COM"      action="CREATE"   name="Exec"> <!--- sets variables to invoke method ---> <cfset Exec.Command="DIR C:\"> <cfset temp=Exec.Run()> 

The next example instantiates an object based on a ColdFusion component:

 <!--- Instantiates ColdFusion component object based on Films.cfc component ---> <cfobject component="FilmsObject"   name="Films"> <!--- Invoke two methods in the Films object ---> <cfinvoke component="FIlmsObject" method="GetAllFilms"> 

NOTE

Use of <cfobject> can be disabled in the ColdFusion Administrator.


<cfobjectcache>

Description: <cfobjectcache> clears ColdFusion's query cache in the Application scope. The attribute is described in Table B.105.

Table B.105. <cfobjectcache> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Clear

Required; must be CLEAR.


Syntax:

 <cfobjectcache action="Clear"> 

Example: The following example flushes the queries in memory:

 <cfobjectcache action="Clear"> 

<cfoutput>

Description: <cfoutput> is used to output the results of a <cfquery> or any time text includes variables that are to be expanded. If <cfquery> is used to process the results of a <cfquery> tag, any code between <cfoutput> and </cfoutput> is repeated once for every row. When outputting query results, an additional set of variables is available. These are documented in Table B.106. <cfoutput> can be used with the GROUP attribute to specify a data group from a query. Data that is grouped together is displayed so that only the first occurrence of each value is output. The attributes for this tag are shown in Table B.107.

Table B.106. <cfoutput> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

group

Column to group on

This optional attribute allows you to define output groups.

groupCaseSensitive

Yes or No

Optional; indicates whether the same values but in different case should be treated as separate entries.

maxRows

Maximum rows to display

This optional attribute specifies the maximum number of rows to display. If omitted, all rows are displayed.

query

Query name

Optional; query name refers to the query results within <cfoutput> text.

startRow

First row to display

Optional; specifies the output start row.


Table B.107. <cfoutput> Fields Available when Using the QUERY Attribute

FIELD

DESCRIPTION

COLUMNLIST

Comma-delimited list of columns with a query.

CURRENTROW

The number of the current row, starting at 1, and incremented each time a row is displayed.

RECORDCOUNT

The total number of records to be output.


Syntax:

 <cfoutput query="Query Name"   maxRows="Maximum Rows"   startRow="Start Row"  group="Group Column"   groupCaseSensitive="Yes or No"> </cfoutput> 

Example: Any time you use variables or fields within your template, you must enclose them within <cfoutput> tags, as shown in this example. Otherwise, the field name is sent as is and is not expanded:

 <!--- displays client variables --->  <cfoutput>  Hi #CLIENT.Name#, thanks for dropping by again.<P>  You have now visited us #NumberFormat(CLIENT.Visits)#  since your first visit on #DateFormat(CLIENT.FirstVisit)#. </cfoutput> 

This example uses <cfoutput> to display the results of a query in an unordered list:

 <!--- gets raw data from database ---> <cfquery name="GetContacts" dataSource="ows">  SELECT FirstName, LastName, Phone  FROM Contacts </cfquery> <!--- query results is displayed in a bulleted list ---> <ul> <cfoutput query="GetContacts">  <li>#LastName#, #FirstName# - Phone: #Phone# </cfoutput> </ul> 

You can use the GROUP attribute to group output results. This example groups contacts by whether they're on the mailing list:

 <!--- gets raw data from database ---> <cfquery name="GetContacts" dataSource="ows">  SELECT FirstName, LastName, Phone, MailingList  FROM Contacts  ORDER BY MailingList </cfquery> <!--- displays query results by group ---> <ul> <cfoutput query="GetContacts" GROUP="MailingList"> <li><B>#Iif(MailingList EQ 1, DE("On"), DE("Not On"))# Mailing List</b>  <ul>  <cfoutput>  <li>#LastName#, #FirstName# - Phone: #Phone#  </cfoutput>  </ul> </cfoutput> </ul> 

NOTE

There is no limit to the number of nested groups you can use in a <cfoutput>. However, every column used in a GROUP must be part of the SQL statement ORDER BY clause.


NOTE

The Startrow and Maxrows attributes can be used to implement a "display next n of n" type display. Even though only a subset of the retrieved data is displayed, it has all been retrieved by the <cfquery> statement. So, although the page might be transmitted to the browser more quickly because it contains less text, the SQL operation itself takes no less time.


See also See also <cfloop>, <cfmail>, <cfquery>, <cftable>


<cfparam>

Description: <cfparam> lets you specify default values for parameters and specify parameters that are required. <cfparam> requires that you specify a variable name. If a VALUE is passed as well, that value will be used as the default value if the variable is not specified. If VALUE is not specified, <cfparam> requires that the named variable be passed; it will generate an error message if it is not. The attributes are shown in Table B.108.

Table B.108. <cfparam> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Name of variable

Required; name should be fully qualified with scope.

default

Default variable value

Optional; the value is used as the default value if the variable is not already defined.

min

Min value

Optional, used with type="Range"

max

Max value

Optional, used with type="Range"

pattern

JS regex pattern

Pattern will be matched by REGEX attrib.

type

Data type

Optional; type of data required; see the following list.


It is commonly used to ensure that variables are defined with default values. Used in this way, it replaces this conditional logic:

 <cfif NOT IsDefefined("MyVar")>  <cfset MyVar="SomeValue"> </cfif> 

with:

 <cfparam name="MyVar" DEFAULT="SomeValue"> 

<cfparam> is also commonly used to validate the type and format of incoming data.

Syntax:

 <cfparam   name="Parameter Name"  default="Default"  max="Min value"  min="Max value"  pattern="JS regex epxression"  type="Data Type"> 

Valid choices for TYPE are presented in Table B.109 below:

Table B.109. Values for the TYPE attribute of <cfparam>

TYPE

DESCRIPTION

ANY

Accepts value of any data type

ARRAY

Value must be an array

BINARY

Must be a binary value

BOOLEAN

Must be convertible to a number, Yes, No, True, or False.

CREDITCARD

Correctly formatted credit card number verified using mod10 algorithm. Must have between 13 and 16 digits.

DATE

Same as USDATE format unless your VALIDATEAT setting includes onServer. In this case, it will return True if the isDate() function would return True.

EMAIL

Verifies email format, not validity of actual address.

EURODATE

Looks for months preceding days with /, - or . delimiters. Days and months can have 1-2 digits, years can be 1-4 digits.

FLOAT/NUMERIC

Number with decimal point. Can be an integer.

GUID

A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number

INTEGER

Number with no decimal point.

QUERY

Must be a CF query object.

RANGE

Provides min and max values, separated by a comma.

REGEX/REGULAR_EXPRESSSION

Matches input against value of PATTERN attribute.

SOCIAL_SECURITY_NUMBER/SSN

Social security number formatted as 999-99-9999 (using hyphens or spaces as separators).

STRING

Data must be a string of one or more characters.

STRUCT

Data must be a CF structure.

TELEPHONE

Phone number in standard US format (999-999-9999). Will accept hyphens or spaces as separators. Area code and exchange must not begin with 0 or 1. Can include a long-distance digit and up to a 5-digit extension, which should begin with x.

URL

Requires a valid URL pattern. Supports HTTP, HTTPS, FTP, FILE, MAILTO, and NEWS URLs.

USDATE

Looks for days preceding months, then years with / delimiters. Days and months can have 1-2 digits, years can be 1-4 digits.

UUID

Requires input formatted like a universally unique identifier in ColdFusion: xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx. Each x must be from the hexadecimal characterset.

VARAIBLEname

Must be a string that conforms to CF variable naming rules.

XML

Must be valid XML data.

ZIPCODE

U.S. ZIP code, in either 99999 or 99999-9999 format. Separator can be either a hyphen or a space.


name

Example: The following specifies a default value for a field that is to be used in a <cfquery> tag, making it unnecessary to write conditional code to build a dynamic SQL statement:

 <!--- if form variable is not passed, it is set to 10 ---> <cfparam name="Form.Minimum" default="10"> <!--- gets raw data from the database ---> <cfquery name="OverDue" dataSource= "ows">  SELECT MerchID, MerchName  FROM Merchandise  WHERE MerchPrice <= #Form.Minimum# </cfquery> 

This example makes the Minimum field required and indicates that it must be numeric and fall with the range 0-100; an error is generated if you request the template and the Minimum field is not specified, is non-numeric and is not within the range identified with the Min and Max attributes:

 <!--- if form variable is not passed or not numeric  and within range ---> <cfparam name="URL.Minimum"   default="10"  type="Range"  max="100"  min="0"> <!--- gets raw data from the database ---> <cfquery name="OverDue" dataSource="ows">  SELECT MerchID, MerchName  FROM Merchandise  WHERE MerchPrice <= #URL.Minimum# </cfquery 

See also <cfset>


<cfpop>

Description: <cfpop> retrieves and manipulates mail in a POP3 mailbox. You must know three things to access a POP mailbox: the POP server name, the POP login name, and the account password. <cfpop> has three modes of operation: It can be used to retrieve just mail headers and entire message bodies and to delete messages. POP messages are not automatically deleted when they are read and must be deleted explicitly with a DELETE operation. Table B.110 lists the <cfpop> attributes; Table B.111 lists the columns returned when retrieving mail or mail headers.

Table B.110. <cfpop> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Optional; one of the values in Table B.111.

attachmentsPath

Attachment path

Optional path to store mail attachments.

maxRows

Maximum messages to retrieve

Optional attribute; ignored if messageNumber is used.

messageNumber

Message number

Optional message number (or comma-delimited list of message numbers); required if action is Delete; specifies the messages to be deleted or retrieved.

name

Query name

Required if action is Getall or Getheaderonly; name of query to be returned. Query columns are listed in Table B.112.

passWord

Password

Optional POP account password; most POP servers require this.

port

Mail server port

Optional attribute; defaults to port 110.

server

Mail server

Required; DNS name or IP address of the POP mail server.

startRow

Start row

Optional start row; defaults to 1; ignored if messageNumber is used.

timeout

Timeout value

Optional timeout value.

userName

Login name

Optional POP login name; most POP servers require this.


Syntax:

 <cfpop action="Action"   attachmentsPath="Path"   maxRows="Number"  messageNumber="Messages"   name="Query Name"   passWord="Password"  port="Port Number"  server="Mail Server"   startRow="Number"   timeout="Timeout"   userName="User Name"> 

Table B.111. <cfpop> Actions

ACTION

DESCRIPTION

DELETE

Deletes messages from a POP mailbox.

GETALL

Gets message headers and body.

GETHEADERONLY

Gets only message headers.


Table B.112. <cfpop> Query Columns

COLUMN

DESCRIPTION

ATTACHMENTFILES

List of saved attachments; present only if action is Getall and an ATTACHMENT path was specified.

ATTACHMENTS

List of original attachment names; only present if action is Getall and an ATTACHMENT path was specified.

BODY

Body of the message.

CC

List of any carbon copy recipients.

DATE

Message date.

FROM

Sender name.

HEADER

Mail header.

MESSAGENUMBER

Message number for use in calls with future calls.

REPLYTO

Email address to reply to.

SUBJECT

Message subject.

TO

Recipient list.


Example: This example retrieves a list of waiting mail in a POP mailbox and then displays the message list in an HTML list:

 <!--- retrieves email headers from server ---> <cfpop server="mail.a2zbooks.com"   username=#username#   passWord=#pwd#  action="GETHEADERONLY"   name="msg"> <!--- displays emails in bulleted list ---> <ul> <cfoutput query="msg">  <li>From: #from# - Subject: #subject# </cfoutput> </ul> 

NOTE

<cfpop> is used to retrieve mail only. Use the <cfmail> tag to send mail.


See also <cfmail>


<cfprocessingdirective>

Description: <cfprocessingdirective> enables you to suppress all white space between the start and end tags. If this tag is nested, the settings on the innermost tag are used. It also enables you to specify a type of character encoding to be used in the body of the tag (on just the page including the tag). It is recommended that you use this tag for only one of these two functions at a time. In other words, don't use it to suppress white space and to specify an alternative character encoding. Don't code a separate PROCESSINGDIRECTIVE tag when employing this tag to specify PAGEENCODING.

When ColdFusion encounters a byte order mark on the page it is processing, it uses the UTF-8 encoding scheme specified when parsing the page. If there is no byte order mark on the page, ColdFusion processes the page using the system's default page encoding scheme. If you use PAGEENCODING to specify a different page encoding scheme than is specified in a page's byte order mark, the ColdFusion will throw an error.

TIP

You should use this tag within the first 4096 bytes of a page.


NOTE

When using this to suppress white space, you must include a tag body and an ending </cfprocessingdirective> tag. When you use the PAGEENCODING attribute, you should leave off the final </cfprocessingdirective> but you can use the abbreviated closing tag: <cfprocessingdirective PAGEENCODING="xxx"/> where xxx is your desired canonical encoding name.


Table B.113 shows <cfprocessingdirective> attributes.

Table B.113. <cfprocessingdirective> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

pageEncoding

Character encoding to be used on this page

Optional; you can use the same canonical names for page encoding used by the Java language.

suppressWhiteSpace

Yes or No

Required; indicates whether white space is to be eliminated.


Syntax (for suppressing white space):

 <cfprocessingdirective suppressWhiteSpace="Yes or No"> CFML code </cfprocessingdirective> 

Syntax (for producing encoded content):

 <cfprocesingdirective pageEncoding="Name of character encoding method"/> 

NOTE

You can find a list of Java's canonical names for page encoding here: http://java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html


Example: The following example suppresses white space. To see the effects, try changing the value of the SUPPRESSWHITESPACE attribute to NO and view the source of the rendered page.

 <!--- suppress whitespace ---> <cfprocessingdirective suppressWhiteSpace="Yes"> <!--- gets raw data from database ---> <cfquery name="GetContacts" dataSource="OWS">  SELECT LastName, Phone  FROM CONTACTS </cfquery> <!--- sets variable ---> <cfset MyVar="This is a variable containing white space"> <!--- displays variable ---> <P><cfoutput>#MyVar#</cfoutput> <!--- displays query results in HTML table ---> <table> <cfoutput query="GetContacts"> <tr>  <td>#LastName#</td>  <td>  <cfif Phone IS NOT "">  #Phone#  <cfelse>  n/a  </cfif>  </td> </tr> </cfoutput> </table> </cfprocessingdirective> 

The next example demonstrates the use of the PAGEENCODING attribute to produce Japanese characters. If you try to reproduce this example, you must save the template using UTF file format rather than traditional ANSI file format, or the example won't work.

 <cfprocessingdirective pageEncoding="utf-8"/> <!--- What follows is a set of Japanese characters that are  supported by the specified encoding. ---> EC9C? 88EC?"EB"9CEC--? EB8C80ED95B4 

See also <cfsetting>, <cfsilent>


<cfprocparam>

Description: <cfprocparam>, which must be used with <cfstoredproc>, passes parameters to stored procedures on relational database management systems. <cfprocparam> attributes are shown in Table B.114.

Table B.114. <cfprocparam> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

cfSqlType

Variable type

Required. See Table B.115 for a list of supported types.

dbVarName

Database variable name

Required to support named notation; corresponds to name of parameter in stored procedure.

maxLength

Number

Optional; maximum parameter length.

null

Yes or No

Optional; indicates whether parameter passed is NULL.

scale

Number

Optional; number of decimal places in parameter.

type

Parameter type

Optional; valid values are In, Out, and Inout; defaults to In.

value

Parameter value

Required for In and Inout parameters.

variable

ColdFusion variable name

Required for Out or Inout parameters.


Syntax:

 <cfprocparam type="In|Out|Inout"  variable="variable"  dbVarName="variable"  value="value"  cfSqlType="type"  maxLength="length"  null="Yes or No"  scale="decimal places"> 

Table B.115. CFSQLTYPE Types

TYPE

CF_SQL_BIGINT

CF_SQL_INTEGER

CF_SQL_BIT

CF_SQL_LONGVARCHAR

CF_SQL_BLOB

CF_SQL_MONEY

CF_SQL_CHARCF_SQL_CLOB

CF_SQL_MONEY4

CF_SQL_DATE

CF_SQL_NUMERIC

CF_SQL_DECIMAL

CF_SQL_REAL

CF_SQL_DOUBLE

CF_SQL_REFCURSOR

CF_SQL_FLOAT

CF_SQL_SMALLINT

CF_SQL_IDSTAMP

 

CF_SQL_TIME

CF_SQL_TINYINT

CF_SQL_TIMESTAMP

CF_SQL_VARCHAR


Example: See the example for <cfstoredproc>

See also <cfstoredproc>, <cfprocresult>


<cfprocresult>

Description: The <cfprocresult> tag, which must be used with the <cfstoredproc> tag, specifies a particular resultset returned from a database stored procedure called with the <cfstoredproc> tag. Table B.116 describes the available tag attributes.

Table B.116. <cfprocresult> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

maxRows

Maximum number of rows

Optional.

name

Query name

Required.

resultSet

Resultset number

Optional attribute; specifies the desired resultset; defaults to 1.


Syntax:

 <cfprocresult name="name"  resultSet="set"  maxRows="rows"> 

Example: See the example for <cfstoredproc>

See also <cfstoredproc>, <cfprocparam>


<cfproperty>

Description: <cfproperty>, which must be used within <cfcomponent>, defines the component's properties. These properties can be accessed by ColdFusion templates that instantiate the component. Table B.117 shows <cfproperty> attributes.

Table B.117. <cfproperty> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

name

Property name

Required; this is the name used to refer to this property in the ColdFusion templates that employ the ColdFusion component that this <cfproperty> is part of.

type

Data type name

Required; the data type of this property; the types are listed in Table B.118.

value

Data value

Optional; the value of the property.


Syntax:

 <cfproperty name="Name of property"  type="Data type name" > 

Table B.118. <cfproperty> type Attribute Values

TYPE

Any (default)

Query

Array

String

Binary

Struct

Boolean

UUID

Date

Variable name

Guid

Numeric

Component name (default if TYPE is not specified)


NOTE

<cfproperty> must be positioned at the beginning of a <cfcomponent>, before function definitions and any other code.


Example: The following example includes two files. The first is named film.cfc and it provides a definition of a ColdFusion component named Film. This component creates two properties: MovieTitle, and AmountBudgeted. The second file is named show_filmcomponent.cfm and it displays the contents of the component's metadata and properties:

 <!--- This file defines the film component ---> <cfcomponent OUTPUT="NO">  <cfproperty name="MovieTitle" type="string" value="Monsters, LLC">  <cfproperty name="AmountBudgeted" type="numeric" value="10000.00">  <cffunction name="GetMetaDataStruct">  <cfargument name="MyArgument">  <!--- Get metadata for this function --->  <cfset var = GetMetaData(this)>  <cfreturn var>  </cffunction> </cfcomponent> <!--- This file displays film component metadata and property values. ---> <cfscript> Film = CreateObject("component", "Film_Component"); Filmcount = Film.GetMetaDataStruct("component"); </cfscript> <cfdump VAR="#FilmCount#"> <cfoutput> <P>Property 1 <P>name: #Filmcount.properties[1].name#<br> type: #Filmcount.properties[1].type#<br> value: #Filmcount.properties[1].value#<br> <P>Property 2 <P>name: #Filmcount.properties[2].name#<br> value: #Filmcount.properties[2].value#<br> type: #Filmcount.properties[2].type#<br> </cfoutput> 

See also <cfcomponent>, <cffunction>


<cfquery>

Description: <cfquery> submits SQL statements to a data source that is either previously configured or dynamically generated, or to another query. SQL statements can include SELECT, INSERT, UPDATE, and DELETE, as well as calls to stored procedures. <cfquery> returns results in a named set if you specify a query name in the name attribute.

The <cfquery> attributes set up the query, and any text between the <cfquery> and </cfquery> tags becomes the SQL statement that is sent to the ODBC driver. ColdFusion conditional code can be used between the <cfquery> and </cfquery> tags, allowing you to create dynamic SQL statements. Table B.119 shows the attributes for this tag.

Table B.119. <cfquery> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

blockFactor

 

Optional; available if using native or Oracle drivers. Valid values are 1100; the default value is 1.

cachedAfter

Cache date

Optional; specifies that query is to be cached and cached copy is to be used after specified date.

cachedWithin

Cache time span

Optional; specifies that query is to be cached and cached copy is to be used within a relative time span.

dataSource

Data source

Required when data source is an existing database. Name of the datasource. Optional when DBTYPE is QUERY.

dbType

Query (literal)

Optional; indicates that the data source is an earlier query result.

debug

Enable query debugging

Optional attribute; turns on query debugging output.

maxRows

Number of rows

Optional; specifies maximum number of rows to retrieve.

name

Query name

Required; used to refer to the query results in <cfoutput>, <cfmail>, or <cftable> tags.

password

Password

Optional; overrides the password specified in the ColdFusion Administrator.

result

Variable name

Optional; will store information about the query and result in a structure that uses the name you provide. The structure is described in table B.120 below.

timeout

Timeout value

Optional; the maximum number of seconds for the query to execute before returning an error indicating that the query timed out. ColdFusion sets this attribute for ODBC drivers and for the DB2 and Informix native drivers; it ignores this attribute for all other native drivers. This attribute is supported by the SQL Server 6.x or later ODBC drivers. Many ODBC drivers do not support this attribute; check the documentation for your ODBC driver to determine if it is supported.

userName

User name

Optional; overrides the login name specified in the ColdFusion Administrator.


Syntax:

 <cfquery  blockFactor="Number of rows"  name="Parameter Name"  dataSource="Data Source" =dbType="Query"  userName="User Name"  passWord="Password"  result="Variable name"   timeout="timeout value"  cachedAfter="date"  cachedWithin="time span"  debug="Yes or No">  SQL statements </cfquery> 

Table B.120. RESULT structure elements

ELEMENT

DESCRIPTION

Cached

True or False indicating whether or not the query is cached.

Columnlist

Array enumerating the columns in the query result.

Execution time

Milliseconds.

Recordcount

Number of rows returned.

SQL

The SQL that was used to execute the query.

SQLParameters

Array enumerating values of any query parameters that may have been used (with <cfqueryparam>).


Example: The following example is a simple data retrieval query:

 <!--- gets raw data from database ---> <cfquery dataSource="OWS" name="Contacts">  SELECT FirstName, LastName, Phone  FROM Contacts </cfquery> 

The next example demonstrates the technique of querying against an existing query result. The second query uses DBTYPE of QUERY. The table it queries uses the name of the previous query resultset.

 <!--- gets raw data from database ---> <cfquery dataSource="OWS" name="GetAllContacts">  SELECT * FROM Contacts </cfquery> <!--- queries GetAllContacts query ---> <cfquery name="GetMailingList" DBtype="Query">  SELECT LastName, FirstName, MailingList  FROM GetAllContacts  WHERE MailingList = 1 </cfquery> <h2><cfoutput>#GetAllContacts.RecordCount#</cfoutput> Contact Records</h2> <!--- displays results of GetAllContacts query in HTML table ---> <cftable query="GetAllContacts" border="Yes" htmlTable="Yes">  <cfcol header="Last Name" text="#LastName#">  <cfcol header="First Name" text="#FirstName#">  <cfcol header="On List" text="#Iif( MailingList EQ 1,DE('Y'), DE(''))#"> </cftable> <h2><cfoutput>#GetMailingList.RecordCount#</cfoutput> Contact Records on Mailing List</h2> <!--- displays results of GetMailingList query in HTML table ---> <cftable query="GetMailingList" border="Yes" htmlTable="Yes">  <cfcol header="Last Name" text="#LastName#">  <cfcol header="First Name" text="#FirstName#">  <cfcol header="On List" text="#Iif( MailingList EQ 1,DE('Y'), DE(''))#"> </cftable> 

This example demonstrates how dynamic SQL statements can be constructed using the ColdFusion conditional tags. Note that you can see the SQL that actually executed by inspecting the value of the SQL element in the QueryInfo result structure.

 <!--- gets raw data from database ---> <cfquery name="GetContacts" dataSource="OWS" result="QueryInfo">  SELECT FirstName, LastName, Phone, ContactID  FROM Contacts  WHERE 1=1  <!--- determines if the FirstName variable passed from  a form is not blank and matches a pattern present in the  FirstName database column --->  <cfif FORM.FirstName IS NOT "">  AND FirstName LIKE '#FORM.FirstName#%'  </cfif>  <!--- determines if the LastName variable passed from  a form is not blank and matches a pattern present in the  LastName database column --->  <cfif FORM.LastName IS NOT "">  AND LastName LIKE '#FORM.LastName#%'  </cfif>  <!--- determines if the Phone variable passed from  a form is not blank and matches a pattern present in the  Phone database column --->  <cfif FORM.Phone IS NOT "">  AND PhoneExtension LIKE 'FORM.#Phone#%'  </cfif>  <!--- if all conditions are met, query results are displayed  last name first --->  ORDER BY LastName, FirstName </cfquery> 

The last example demonstrates the use of <cfquery> to execute a stored procedure in a SQL Server database:

 <!--- queries database using stored procedure and URL variable ---> <cfquery name="GetContact" dataSource="ContactSystem">  <!--- calls stored procedure --->  {Call GetContacts(#URL.ContactID#)} </cfquery> 

Note that the preferred mechanism for executing stored procedures involves using <cfstoredproc> and related tags. This older technique will work but is limited to returning one recordset.

See also <cfqueryparam>, <cfoutput>, <cfmail>, <cftable>, <cfstoredproc>


<cfqueryparam>

Description: <cfqueryparam> is embedded within the SQL of a <cfquery>. It enables you to define query parameters and their data types. Queries may execute more quickly when passed data-typed parameters.

<cfqueryparam> attributes are listed in Table B.121.

Table B.121. <cfqueryparam> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

cfSqlType

Type

Optional; data type specified from list in Table B.122.

maxLength

Bytes

Optional; maximum length of parameter value.

null

Yes or No

Optional; Yes if passed parameter is null.

scale

Number of decimals

Optional; applicable for type=CF_SQL_NUMERIC and CF_SQL_DECIMAL. Specifies number of decimals; defaults to 0.

separator

Character

Optional; character to be used as a delimiter in lists.

value

Param value

Required; the parameter's value.


Syntax:

 <cfqueryparam cfSqlType="Param type"  maxLength="Number"  null="Yes or No"  scale="Number of decimal places"  separator="Delimiter character"  value="Param value"> 

Table B.122. CF SQL Types

ATTRIBUTE

CF_SQL_BIGINT

CF_SQL_LONGVARCHAR

CF_SQL_BIT

CF_SQL_MONEY

CF_SQL_BLOB

CF_SQL_MONEY4

CF_SQL_CHAR

CF_SQL_NUMERIC

CF_SQL_CLOB

CF_SQL_REAL

CF_SQL_DATE

CF_SQL_REFCURSOR

CF_SQL_DECIMAL

CF_SQL_SMALLINT

CF_SQL_DOUBLE

CF_SQL_TIME

CF_SQL_FLOAT

CF_SQL_TIMESTAMP

CF_SQL_IDSTAMP

CF_SQL_TINYINT

CF_SQL_INTEGER

CF_SQL_VARCHAR


Example: In the following example, <cfqueryparam> is used to validate the data type being passed:

 <!--- sets default value for URL variable ---> <cfparam name="URL.ContactID" DEFAULT="q"> <!--- sets trap for errors ---> <cftry> <!--- gets raw data from database as interger ---> <cfquery name="GetContacts" dataSource="ows">  SELECT LastName, FirstName  FROM Contacts  WHERE ContactID = <cfqueryparam value="#URL.ContactID#"  cfSqlType="CF_SQL_INTEGER"> </cfquery> <!--- catches and displays any errors ---> <cfcatch type="Any">  <P>An error has occurred:  <cfoutput>  <P>#CFCATCH.Detail#  <P>#CFCATCH.Type#  </cfoutput> </cfcatch> </cftry> 

TIP

Use <cfqueryparam> to prevent malicious database access via URL tampering.


See also <cfquery>, <cfstoredproc>, <cfprocparam>


<cfregistry>

Description: <cfregistry> can be used to directly manipulate the system Registry. The <cfregistry> action attribute specifies the action to be performed, and depending on the action, other attributes might or might not be necessary. This tag is available on any Unix platforms but its use is deprecated on Unix and related platforms.

<cfregistry> attributes are listed in Table B.123. Values for the action attribute are listed in Table B.124.

Table B.123. <cfregistry> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required; one of the values in Table B.124.

branch

Registry branch

Required.

entry

Branch entry

Required for Get, Set, and Delete actions.

name

Name of record to contain keys and values

Required if action is Getall.

sort

Sort order

Optional; can be used if action is Getall. Enables sorting on specified column(s): Entry, Type, and Value. You also can specify ASC for ascending sorts or DESC for descending sorts.

type

Value type

Optional; can be used for all actions except Delete; valid types are String, Dword, and Key; default is String.

value

Value to set

Required if action is Set.

variable

Variable to save

Required if action value is Get.


Syntax:

 <cfregistry action="action"  branch="branch"  entry="entry"  name="query"  sort="sort order"  type="type"  value="value"  variable="variable"> 

Table B.124. <cfregistry> Actions

ACTION

DESCRIPTION

DELETE

Deletes a Registry key.

GET

Gets a Registry value.

GETALL

Gets all Registry keys in a branch.

SET

Sets a Registry value.


When the action is getAll, the following query result is returned:

  • Entry. Name of a registry entry in the specified key

  • Type. Data type of the entry

  • Value. Value of the entry

Example: This example retrieves all the keys beneath the Liquid Audio branch.

 <!--- queries system registry ---> <cfregistry action="GETALL"   name="reg"  branch="HKEY_LOCAL_MACHINE\SOFTWARE\Liquid Audio Settings"> <!--- displays number of registry keys ---> <P>Number of Liquid Audio entries: <cfoutput>#reg.RecordCount#</cfoutput> <!--- displays each key's details in an HTML table ---> <table cellPadding="3"> <cfoutput query="reg"> <tr ALIGN="left">  <th>Entry</th>  <th>Type</th>  <th>Value</th> </tr> <tr align="left">  <td>#Entry#</td>  <td>#Type#</td>  <td>#Value#</td> </tr> </cfoutput> </table> 

NOTE

Only Windows platforms use the Registry concept. This tag works only on Windows platforms.


CAUTION

Take great care when using this tag, particularly when writing to the Registry. It is not hard to corrupt the integrity of the Registry. You might want to consider turning off the use of this tag in the ColdFusion Administrator, in the Tag Restrictions section under Security.


<cfreport>

Description: <cfreport> enables you to produce reports built with Crystal Reports or with ColdFusion's own Report Builder. This tag employs two distinct syntaxes, one for Crystal, one for the CF Report Builder. The full list of supported attributes is in Table B.125, categorized by usage.

Table B.125. <cfreport> Attributes

ATTRIBUTE

USE WITH

DESCRIPTION

NOTES

fileName

Report Builder

Filename to hold the report

Full-qualified filename. Optional; can't specify both name and FILEname.

format

Report Builder

PDF or FlashPaper

Required.

name

CF variable

Holds report output

Optional; can't specify both name and FILEname.

overwrite

Report Builder

Yes or No; overwrites or doesnlt overwrite output file.

Optional; defaults to No.

query

Report Builder

CF Query name

Optional; provides data to report. If omitted, report's data must come from <cfreportparam> or enclosed SQL.

template

Report Builder

Path to report definition file

Required; path relative to web-root.

dataSource

Crystal

Data source name

Optional.

formula

Crystal

Crystal Reports formula

Optional; enables you to specify values for Crystal Reports formulas used in the report. Can use multiple formulas, each terminated with a semi-colon.

orderBy

Crystal

Report sort order

Optional; overrides the default sort order specified when the report was created.

passWord

Crystal

Report's data source password

Optional; used to override the login password specified in the ColdFusion Administrator.

report

Crystal

Path to RPT file to process

Required.

timeout

Crystal

Time in seconds

Optional. Maximum duration of a request before timing out.

type

Crystal

Standard, Netscape or Microsoft.

Optional. Defaults to Standard, but Standard is not valid for Crystal Reports 8.x.


Syntax 1 (with ColdFusion's Report Builder):

 <cfreport   template="Report File" format="PDF or FlashPaper" name="Variable name"  fileName="Path to output file"  query="Query name"  overwrite="Yes or No"> </cfreport> 

Syntax 2 (with Crystal Reports):

 <cfreport  report="Report File"  dataSource="DSN"  type="Standard, Netscape or Microsoft"  timeout="Seconds"  orderBy="Sort Order"  userName="User Name"  passWord="Password"  formula="Formula"> </cfreport> 

Example: The following example processes a report created with Crystal Reports Professional and passes it an optional filter condition:

 <!--- retrieves report entries with ContactID of 3 ---> <cfreport report="\ows\scripts\Contact.rpt">  {Contacts.ContacID} = "3" </cfreport> 

This example processes a report and specifies parameters to override the ODBC data source, user login name and password, and a formula named @Title derived from an HTML form:

 <!--- retrieves report entries using @Title formula and ContractID Sales ---> <cfreport report="\ows\scripts\ContactList.rpt"  dataSource="OWSInternal"  username="Sales"  passWord="bigbucks"  @Title="#FORM.title#">  {Contacts.ContactID} = "Sales" </cfreport> 

The next example uses a report built with the ColdFusion Report Builder:

[View full width]

<!--- Invokes a report built by the CF Report Builder. Uses a query and one input parameter. ---> <cfset userName="Joe 'the Report Dude' Shmo"> <cfquery name="MyQuery" dataSource="ows"> SELECT Merchandise.MerchID, Merchandise.FilmID, Merchandise.MerchDescription, Merchandise.MerchPrice, Films.MovieTitle, FilmsRatings.Rating FROM Merchandise, Films, FilmsRatings WHERE Merchandise.FilmID = Films.FilmID AND Films.RatingID = FilmsRatings.RatingID ORDER BY FilmsRatings.Rating, Merchandise.MerchPrice DESC </cfquery> <cfreport template="CFREPORTTest.cfr" format="flashpaper" query="#MyQuery#"> <cfreportparam name="UserName" value="#VARIABLES.UserName#"> </cfreport>

See also <cfreportparam>, <cfdocument>, <cfdocumentsection>


<cfreportparam>

Description: <cfreportparam> tags are used within the <cfreport> tag body to provide parameters to a report. The attributes are described in Table B.126, below.

Table B.126. <cfreportparam> Attributes

ATTRIBUTE

DESCRIPTION

name

Required; the name of the parameter to be passed.

value

Required; the value of the parameter to be passed.


Syntax:

 <cfreportparam  name="Param name"  value="Param value"> 

Example: See <cfreport> example.

See also <cfreport>, <cfdocument>, <cfdocumentsection>


<cfrethrow>

Description: <cfrethrow> enables you to force the current error to be invoked again within <cfcatch> ... </cfcatch> block. It generally is used when you have error-trapping logic that traps an error that your code isn't capable of handling. In this case, you want to rethrow the error.

Syntax:

 <cfrethrow> 

Example: In the following example, a query attempts to insert a new record using key values entered through a form. This can result in a key violation. The <cfcatch> block is used to trap this type of error, but if some other type of database error occurs, you rethrow the error:

 <!--- sets error trap ---> <cftry> <!--- gets raw data from database ---> <cfquery name="InsertContactOrder" dataSource="OWS">  INSERT INTO ContactOrders (ContactID,OrderID)  VALUES (#FORM.ContactID#,#FORM.OrderID#) </cfquery> <cfcatch type="DATABASE">  <!--- If the database throws anything other  than a 23000 error, the error is rethrown. --->  <cfif CFCATCH.sqlstate neq 23000>  <cfrethrow>  </cfif> </cfcatch> </cftry> 

See also <cfcatch>, <cfthrow>, <cftry>


<cfreturn>

Description: <cfreturn> enables you to return a value from a <cffunction> in a ColdFusion component. You use it to return expressions. Note that while there are no attributes per se, you must return an expression.

Syntax:

 <cfreturn expression> 

Example: Please refer to the examples in <cffunction> and <cfcargument>.

See also <cfcomponent>, <cffunction>, <cfcfargument>


<cfsavecontent>

Description: <cfsavecontent> enables you to save the output of a page or portion of a page in a variable. It is valuable when you need to process the output in some way before it is complete. It saves the results of evaluated expressions and custom tag output in the body. The attribute is described in Table B.1127.

Table B.127. <cfsavecontent> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

variable

CFML variable name

Required; name of the variable in which to save content.


Syntax:

 <cfsavecontent variable="variablename"> 

Example: In this example, <cfsavecontent> is used to save the page output in a variable. The phrase "Profit and Loss Q1" is then replaced with the phrase "Profit and Loss Q2":

 <!--- saves custom tag output to a variable ---> <cfsavecontent variable="ReportTitle">     <!--- custom tag producs p&l ---> <cf_ProducePandL StartDate="4/1/2001" EndDate="6/30/2001"> </cfsavecontent> <!--- replaces text string ---> <cfoutput> #Replace(ReportTitle, "Profit and Loss Q1", "Profit And Loss Q2", "all")# </cfoutput> 

<cfschedule>

Description: <cfschedule> enables you to create, update, delete, and execute tasks programmatically in the ColdFusion Administrator's scheduler. The scheduler enables you to run a specified page at scheduled times and intervals.

You have the option to direct page output to static HTML pages. This enables you to offer users access to pages that publish data, such as reports, without forcing them to wait while a database transaction that populates the data on the page is performed.

ColdFusion-scheduled events must be registered using the ColdFusion Administrator before they can be executed. Information supplied by the user includes the scheduled ColdFusion page to execute, the time and frequency for executing the page, and whether the output from the task should be published. A path and file are specified if the output is to be published.

<cfschedule> attributes are listed in Table B.128. The values for the action attribute are described in Table B.129.

Table B.128. <cfschedule> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action (refer to Table B.129)

Required attribute.

endDate

Event end date

Optional attribute; date the scheduled task should end.

endTime

Event end time

Optional attribute; time the scheduled task should end; enter value in seconds.

file

File to create

Required if PUBLISH is Yes.

interval

Execution interval

Required if action is Update; can be specified as number of seconds; as daily, weekly, or monthly; or as execute.

limitTime

Maximum execution time

Optional attribute; maximum number of seconds allowed for execution.

operation

Operation

Required if action is Update. Currently only HTTPRequest is supported.

passWord

Password

Optional password for protected URLs.

path

Path to save published files

Required if PUBLISH is Yes.

port

Port number on server

Optional; used with RESOLVEURL set to Yes to properly execute URLs that specify a port other than 80 (default).

proxyServer

Proxy server name

Optional name of proxy server.

proxyPort

Port number on proxy server

Optional; used with resolveUrl set to Yes to properly execute URLs that specify a port other than 80 (default).

publish

Publish static files

Optional attribute; Yes if the scheduled task should publish files; default is No.

requestTimeout

Seconds

Before timeout Optional; used to extend the default timeout for long tasks.

resolveUrl

Resolve URLs

Optional attribute; resolve URLs to fully qualified URLs if Yes; default is No.

startDate

Event start date

Optional attribute; date the scheduled task should start.

startTime

Event start time

Optional attribute; time the scheduled task should start; enter value in seconds.

task

Task name

Required attribute; the registered task name.

URL

URL

Required if action is Update; the URL to be executed.

userName

Username

Optional username for protected URLs.


Syntax:

 <cfschedule action="Action"  endDate="Date"  endTime="Time"  file="File Name"  interval="Interval"  limiTime="Seconds"  operation="HTTPRequest"  passWord="Password"  path="Path"  port="Port Number"  proxyServer="Server Name"  proxyPort="port number"  publish="Yes or No"  resolveUrl="Yes or No"  requesTimeout="seconds"  startDate="Date"  startTime="Time"  task="Task Name"  URL="URL"  userName="User Name"> 

Table B.129. <cfschedule> Actions

ACTION

DESCRIPTION

DELETE

Deletes a task.

UPDATE

Updates a task or creates it if it doesn't exist.

RUN

Executes a task.


Example: This example creates a recurring task that runs every 10 minutes (600 seconds). The output is saved in C:\INETPUB\WWWROOT\SAMPLE.HTML:

 <!--- schedules update task ---> <cfschedule action="UPDATE"  TASK="TaskName"  operation="HTTPRequest"  URL="http://127.0.0.1/testarea/test.cfm"  startDate="3/13/2001"  startTime="12:25 PM"  interval="600"  resolveUrl="Yes"  publish="Yes"  file="sample.html"  path="c:\inetpub\wwwroot\"  requestTimeout="600"> 

This example deletes the task created in the previous example:

 <!--- deletes TaskName scheduled task ---> <cfschedule action="delete"  task="TaskName"> 

NOTE

Execution of <cfschedule> can be disabled in the ColdFusion Administrator.


<cfscript>

Description: <cfscript> and </cfscript> are used to mark blocks of ColdFusion script. ColdFusion script looks similar to JavaScript and enables you to produce certain functions of ColdFusion tags (and use many ColdFusion functions) and avoid all the wordy syntax associated with tags. Note that one major limitation of <cfscript> is that you can't execute SQL (or other) queries with it. Each line must be terminated with a semicolon.

Syntax:

 <cfscript> script </cfscript> 

Example: The following example creates a structure and then uses it in place of a <cfswitch> to select a value.

 <!--- creates structure and displays results ---> <cfscript>  Meals = StructNew();  Meals["Breakfast"]="Bacon,Eggs,Toast,Fruit,Coffee";  Meals["Lunch"]="Soup,Sandwich";  Meals["Dinner"]="Pasta,Garlic bread,Red wine";  WriteOutput("We'll be having " & Meals[Form.Meal] & " for " & Form.Meal); </cfscript>  

<cfsearch>

Description: <cfsearch> performs searches against Verity collections (in much the same way <cfquery> performs searches against ODBC data sources). It returns a query object with columns described in Table B.131. To use <cfsearch>, you must specify the collection to be searched and the name of the query to be returned. You can search more than one collection at once, and you also can perform searches against Verity collections created with applications other than ColdFusion. Table B.130 lists the <cfsearch> attributes.

Table B.131. <cfsearch> Result Columns

COLUMN

DESCRIPTION

Category

List of categories used in CFSEARCH.

CategoryTree

Hierarchical tree that was specified in CFSEARCH.

ColumnList

List of column names within the recordset.

Context

Context summary, with search terms bolded.

CurrentRow

Current row that CFOUTPUT is processing.

Custom1

Name of first custom field that was used to populate the collection.

Custom2, 3, 4 the collection.

Names of second, third and fourth custom fields that were used to populate

Key

Value of KEY that was used to populate the collection.

Rank

Number indicating how this document ranks in the results.

RecordsSearched

Number of document searched.

Author

Author value which can be extracted from certain types of documents (e.g., Word, PDF).

Score

The relevancy score of the document in the current row.

Size

Number of bytes in the indexed document.

Summary

Contents of the summary generated by <cfindex>.

RecordCount

Number of records returned in the record set. Note that this value is the same in each row in the result set.

Title

Value of the TITLE attribute (in <cfindex>) that was used when the collection was populated.

Type

Current document's MIME type.

URL

Provides the value of the URLPath attribute in <cfindex>.


Table B.130. <cfsearch> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

category

Comma-separated list

Optional. Note that CF will throw an error if categories are not enabled for this collection.

categorytree

Start location in tree

Optional. This is the name of a node in the collection's category tree at which you want the search to begin. Note that CF will throw an error if categories are not enabled in this collection.

collection

Collection name

Required attribute; the name of the collection or collections to be searched. Multiple collections must be separated by commas; for external collections, specify the full path to the collection.

contextBytes

Number of bytes

Optional. Defaults to 300. Indicates number of bytes of contextual information that Verity will return.

contextPassages

Number of sentences

Optional. Defaults to 3. Indicates how much contextual information you want to appear with search results, in sentences/passages.

contextHighlightBegin

HTML tags

Optional. Defaults to <b>. This HTML expression will be tacked on at the beginning of where a search term is found in the context information returned by Verity. It is used to highlight the search term in the context information. Use this in conjunction with CONTEXTHIGHLIGHTEND.

contextHighlightEnd

HTML tags

Optional. Defaults to </B>. This HTML expression will be tacked on at the end of where a search term is found in the context information returned by Verity. It is used to highlight the search term in the context information. Use this in conjunction with contextHighlightBegin.

criteria

Search criteria

Optional attribute; search criteria as shown in Appendix E.

external

Deprecated

This attribute is no longer available.

language

Language

Optional; requires installation of International Search Page.

maxrows

Maximum rows to retrieve

Optional attribute; defaults to all.

name

Value column

Optional; column to be used for OPTION value attribute.

previousCriteria

Result name

Optional. Name of result set from a previous Verity search. This is used for searching within the previous result, in order to narrow the search. This result set will be searched for the criteria value; there will be no regard for rank within the previous result set.

startRow

Start row

Optional; default is first row.

status

Structure variable name

Optional. Variable name that will be used to store information about the status of the search. See Table B.132 for a list of the elements in this structure.

suggestions

Spelling suggestion spec

Optional. Values are Never, Always or a positive integer value. Defaults to Never. Used to indicate whether or not Verity should return spelling suggestions (see Table B.132, suggestedQuery). When you supply an integer value, Verity will only return spelling suggestions when the number of documents found is at or below this number. Note that there is a performance hit associated with using suggestionss.

type

Search type

Optional; can be SIMPLE or EXPLICIT.


Syntax:

 <cfsearch   category="Category List"  categoryTree="Start location in tree"  collection="Collection Name"  contextBytes = "Number of bytes"  contextPassages = "Number of passages"  contextHighlightBegin = "HTML pre-context"  contextHighlightEnd = "HTML post-context"criteria="Search Criteria"   language="language"  maxRows="Number"  name="Name"  previousCriteria = "name of previous result"  startRow="Number"  status="Structure variable"  suggestions="Suggestion spec"  type="Type"> 

Table B.132. Status Return Variable Structure Elements

ELEMENT

DESCRIPTION

found

Indicates the number of documents in which the search criteria was found

searched

Indicates the number of documents searched. Same as the recordsSearched column in the search results.

time

How long the search took, as reported by the Verity K2 search service, in milliseconds.

suggestedQuery

Verity will suggest an alternative query that may yield better/more results. This often contains corrected spellings of search terms. Only present when the suggestions attribute criteria is met.

keyWords

This is a structure in which each search term is a key to an array of up to five possible alternative terms, in order of preference. Only present when the suggestions attribute criteria is met.


Example: This example performs a search with a user-supplied search criterion. It searches the collection built in the example for <cfcollection>.

 <!--- schedules update task ---> <cfif IsDefined("FORM.Searchfield")>  <cfsearch collection="FilmsMerchandise"  type="SIMPLE"  criteria="#Form.SearchField#"  name="GetMerch"> </cfif> <!--- submits search value ---> <form action="#CGI.SCRIPT_NAME#" method="post">  <P>Find film merchandise: <input name="searchfield" type="Text">  <p><input type="Submit" value="Search"> </form> <!--- checks for presense of form variable ---> <cfif IsDefined("Form.searchfield")>  <!--- if RecordCount is greater than zero, displays results --->  <cfif GetMerch.RecordCount GT 0>  <ul>  <cfoutput query="GetMerch">  <li>#Key# - #NumberFormat(Score, "__.__" )# - #Summary#  </cfoutput>  </ul>  <!--- if RecordCount is zero, message is displayed --->  <cfelse>  <P>Nothing matching your criteria  </cfif> </cfif> 

See also <cfcollection>, <cfindex>


<cfselect>

Description: <cfselect> is used inside a <cfform> body to simplify the process of creating data-driven SELECT controls. <cfselect> will be rendered in HTML, Flash or XML depending on the value of the FORMAT attribute in the <cfform> tag that it is used within. <cfselect> options can be added one at a time using HTML <option> tags, or by specifying a query, or both. <cfselect> attributes are listed in Table B.133.

Table B.133. <cfselect> Attributes

ATTRIBUTE

APPLIES TO

DESCRIPTION

NOTES

display

All

Column to display

Optional query column to use as the displayed text.

group

HTML, XML

Column name

Optional. Uses the values in the named column to group options.

height

Flash

Number of pixels

Optional. Control height in pixels.

label

Flash, XML

Label text

Used in Flash forms to label the <select> list.

message

All

Validation failure message

Optional message to display upon validation failure.

multiple

All

Yes or No

Optional attribute; defaults to No. Indicates whether or not to enable selection of multiple items.

name

All

Unique field name

This attribute is required. Name of <select> control.

onChange

All

Command/function

Use Javascript for XML and HTML, Actionscript for Flash.

onClick

All

Command/function

Use Javascript for XML and HTML, Actionscript for Flash.

onKeyDown

All

Command/function

Use Javascript for XML and HTML, Actionscript for Flash.

onKeyUp

All

Command/function

Use Javascript for XML and HTML, Actionscript for Flash.

onMouseDown

All

Command/function

Use Javascript for XML and HTML, Actionscript for Flash.

onMouseUp

All

Command/function

Use Javascript for XML and HTML, Actionscript for Flash.

onError

HTML

JavaScript error function

Optional override to your own JavaScript error message function.

query

All

Query name

Optional attribute; query to be used to populate the <select> box.

queryPosition

All

Above or Below

Optional. When you combine HTML <option> tags with <option> tags from query output, this indicates whether the query output will appear above or below the HTML <option> tags.

required

All

Yes or No

Optional; defaults to No. If SIZE is 1 or you omit SIZE, this is meaningless, as item 1 will always be selected.

selected

All

Value or list

Value of the OPTION to be preselected. You can provide a comma-separated list of selected values, but only if options are generated by a query.

size

All

List size

Optional; number of options to display without scrolling. Defaults to 1, causing the <select> to display as a drop-down list.

style

All

CSS or XSL style

Optional. In XML and HTML, this attribute is passed to the browser. In Flash, you must use a CSS-type style specification.

value

All

Value column

Optional; column name to provide values for option value attribute.

width

Flash

Pixels

Optional. Control width in pixels.


Note that you can set PRESERVEDATA="Yes" in the <cfform> tag (containing this <cfselect>) to preserve selections between form submissions, but this only works when you're generating <option> tags with a query.

Syntax:

 <cfselect  display="Column Name"  group="Column Name"  height="Pixels"  label="Label text"  message="Message Text"  multiple="Yes or No"  name="Field Name"  onChange="Javascript or Actionscript"  onClick="Javascript or Actionscript"  onError="JavaScript Error Function"  onKeyDown="Javascript or Actionscript"  onKeyUp="Javascript or Actionscript"  onMouseDown=" Javascript or Actionscript"  onMouseUp="Javascript or Actionscript" query="Query Name"  QUERYPOSITION="Above or Below"  required="Yes or No"  selected="Value or List"  size="Size"  style="Style spec"  value="Column Name"  width="Pixels">  <option...> </cfselect> 

Use group to place the value column entries from each group in an indented list under the specified column's field value. This option will generate an HTML optgroup tag for each entry in the group column. Note that your SQL should should include an ORDER BY clause to order the results based on the GROUP column.

Example: This example creates a simple data-driven SELECT control in which the user is required to make a selection:

 <!--- gets raw data from database ---> <cfquery name="GetActors" dataSource="OWS">  SELECT ActorID, NameLast  FROM Actors </cfquery> <!--- creates menu from query ---> <cfform action="process.cfm" FORMAT="Flash"> <!--- Produces flast multi-select list ---> <cfselect name="Actors"  query="GetActors"  value="ActorID"  display="NameLast"  SIZE="8"  required="Yes"  multiple="Yes"  width="150"  selected="2,4,6"  label="Waiters & Waitresses:"> </cfselect> </cfform 

See also <cfform>, <cfgrid>, <cfinput>, <cfslider>, <cftextarea>, <cftree>


<cfservlet>

This tag is deprecated and is no longer in use.

<cfservletparam>

This tag is deprecated and is no longer in use.

<cfset>

Description: <cfset> assigns values to variables. <cfset> can be used for both client variables (type CLIENT) and standard variables (type VARIABLES). <cfset> takes no attributesother than the name of the variable being assigned and its value.

Syntax:

 <cfset "Variable"="Value"> 

Example: The following example creates a local variable containing a constant value:

 <!--- sets local variable ---> <cfset MaxDisplay=25> 

The following example creates a client variable called #BGColor#, which contains a user-specified value and explicitly states the variable type (CLIENT):

 <!--- sets client variable ---> <cfset CLIENT.BGColor=FORM.Color> 

This example stores tomorrow's date in a variable called Tomorrow:

 <!--- sets variable for tomorrow's date ---> <cfset Tomorrow =Now() + 1> 

<cfset> can also be used to concatenate fields:

 <!--- sets variable that contains two other variables ---> <cfset VARIABLES.Fullname=FORM.FirstName FORM.LastName> 

Values of different data types also can be concatenated:

 <!--- sets variable that contains three variables of different data types ---> <cfset Sentence=FORM.FirstName FORM.LastName & "is" & FORM.age & "years old"> 

Note that when creating complex variables, such as arrays, structures, and queries, you must use a function to create the variables before you can set their values:

 <!--- sets variable and creates array ---> <cfset myBreakfast=ArrayNew(1)> <!--- populates array with a value ---> <cfset myBreakfast[1]="Chipped Beef on Toast"> <!--- creates structure ---> <cfset myLunch=StructNew()> <!--- populates structure with a value ---> <cfset myLunch["MainCourse"]="Chili"> <!--- creates array columns ---> <cfset myDinner=QueryNew("Monday,Tuesday,Wednesday,Thursday,Friday")> <!--- adds row ---> <cfset temp=QueryAddRow(myDinner)> <!--- populates cell in myDinner ---> <cfset temp=QuerySetCell(myDinner, "Monday", "Lasagna")> 

TIP

If you find yourself performing a calculation or combining strings more than once in a specific template, you're better off doing it once and assigning the results to a variable with <cfset>; you can then use that variable instead.


See also <cfapplication>, <cfcookie>, <cfparam>


<cfsetting>

Description: <cfsetting> is used to control various aspects of page processing, such as controlling the output of HTML code in your pages or enabling and disabling debug output. One benefit is managing white space that can occur in output pages that are served by ColdFusion. <cfsetting> attributes are listed in Table B.134.

Table B.134. <cfsetting> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

enableCfOutputOnly

Yes or No

Required; forces ColdFusion to only output content in <cfoutput> blocks.

requestTimeout

Seconds

Optional; indicates the amount of time that can elapse before CF treats the thread as unresponsive.

showDebugOutput

Yes or No

Optional. When set to No, suppresses debugging information that normally appears at bottom of page. Defaults to Yes.


When using <cfsetting> to disable an option, be sure you have a matching enable option later in the file.

Syntax:

 <cfsetting  enableCfOutputOnly="Yes or No"  requestTimeout="Seconds"  showDebugOutput="Yes|No"> 

NOTE

For each use of <cfsetting> with enableCfOutputOnly set to Yes, you must include a matching enableCfOutputOnly set to No. That is, if you used it twice with enableCfOutputOnly set to Yes, you must use it two more times set to No to get Cold Fusion to display regular HTML output.


Example: The following demonstrates how <cfsetting> can be used to control generated white space:

 <!--- text is displayed ---> This text will be displayed <!--- suppresses all output not inside <cfoutput> tags ---> <cfsetting enableCfOutputOnly="Yes"> <!--- text is not displayed because it lies outside of <cfoutput> ---> This text will not be displayed as it is not in a CFOUTPUT block <!--- text is displayed because it lies within <cfoutput> block ---> <cfoutput>This will be displayed</cfoutput> <!--- does not suppress output outside of <cfoutput> block ---> <cfsetting enableCfOutputOnly="No"> <!--- test is displayed ---> This text will be displayed even though it is not in a CFOUTPUT block 

See also <cfsilent>


<cfsilent>

Description: Similar to <cfsetting enableCfOutputOnly ="Yes">, <cfsilent> is a mechanism for suppressing output. However, it simply suppresses all output that ColdFusion produces within the tag's scope.

Syntax:

 <cfsilent> any code or text</cfsilent> 

Example: This example demonstrates that <cfsilent> suppresses all included output in <cfoutput> blocks. However, it does not suppress the execution of code in <cfoutput> blocks, so the variables #X# and #SENTENCE# are still created and processed:

 <!--- suppresses display of <cfoutput> ---> <cfsilent>  <cfset x="value">  <cfset sentence="This is a #x# to be output.">  <P><cfoutput>#sentence#</cfoutput> </cfsilent> <!--- variable is displayed ---> <P><cfoutput>#sentence#</cfoutput> 

See also <cfsetting>


<cfslider>

Description: <cfslider> embeds a Java slider control in your HTML forms. Slider controls typically are used to select one of a range of numbers. <cfslider> must be used between <cfform> and </cfform> tags. Table B.135 lists the entire set of <cfslider> attributes.

Table B.135. <cfslider> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

align

Control alignment

Optional; possible values are Top, Left, Bottom, Baseline, Texttop, Absbottom, Middle, Absmiddle, and Right.

bgColor

Background color

Optional; possible values are Black, Blue, Red, Cyan, Darkgray, Gray, Lightgray, Magenta, Orange, Pink, White, Yellow, or any color specified in hex format.

bold

Bold face text

Optional attribute; must be Yes or No if specified; defaults to No.

font

Font face

Optional font face to use.

fontSize

Font size

Optional font size.

grooveColor

Deprecated

This attribute is no longer in use.

height

Control height

Optional height in pixels.

hSpace

Control horizontal spacing

Optional horizontal spacing in pixels.

img

Deprecated

This attribute is no longer in use.

imgStyle

Deprecated

This attribute is no longer in use.

italic

Italic face text

Optional attribute; must be Yes or No if specified; defaults to No.

label

Slider label

Optional; can contain the variable %VALUE%, in which case the current value is displayed as the slider is moved.

lookAndFeel

Look style name

Optional; can be Motif, Windows, or Metal (Java Swing style). Defaults to Windows.

message

Validation failure message

Optional message to display upon validation failure.

name

Unique control name

Required.

notSupported

Text to be used for non-Java browsers

Optional text (or HTML code) to be displayed on nonJava-capable browsers.

onError

JavaScript error function

Optional override to your own JavaScript error message function.

onValidate

JavaScript validation function

Optional override to your own JavaScript validation function.

range

Range minimum and maximum

Optional range for numeric values only; must be specified as two numbers separated by a comma; defaults to "0,100".

refreshLabel

Yes or No

Optional; if No and slider is moved, label is not refreshed; default is Yes.

sscale

Increment scale integer

Optional; increment amount to use when slider is moved; defaults to 1.

textColor

Text color

Optional; possible values are Black, Blue, Red, Cyan, Darkgray, Gray, Lightgray, Magenta, Orange, Pink, White, Yellow, or any color specified in hex format.

tickmarkImages

URL list

Optional; comma-separated list of URLs of images to use for tick marks.

tickmarkLabels

Yes or No, or Numeric or list

Optional; Yes or NUMERIC results in tick marks based on values of RANGE and SCALE attributes. No (default) prevents the display of label tick marks. It can also provide a list of labels to be used, such as 25, 50, 75, 100.

tickmarkMajor

Yes or No

Optional; defaults to No. Renders major tick marks based on value of SCALE attribute.

tickmarkMinor

Yes or No

Optional; defaults to No. Renders major tick marks based on value of SCALE attribute.

value

Initial value

Optional; initial field value; this value must be within the specified range if RANGE is used.

vSpace

Control vertical spacing

Optional vertical spacing in pixels.

width

Control width

Optional width in pixels.


Syntax:

 <cfslider align="Alignment"  bgColor="Background Color"  bold="Yes or No"  font="Font Face"  fontSize="Font Size"  height="Control Height"  hSpace="Horizontal Spacing"  italic="Yes or No"  label="Slider Label"  lookAndFeel="Motif or Windows or Metal"  message="Error Message"  name="Field Name"  notSupported="Non Java Browser Code"  onError="Error Function"  onValidate="Validation Function"  range="Numeric Range"  refreshLabel="Yes or No"  scale="Increment Value"  textColor="Text Color"  tickmarkImages="URL list"  tickmarkLabels="Yes or No or Numeric or label list"  tickmarkMajor="Yes or No"  tickmarkMinor="Yes or No"  value="Initial Value"  vertical="Yes or No"  vSpace="Vertical Spacing"  Width="Control Width"> 

Example: The following example displays a form for searching for contacts based on last name. <cfslider> enables the user to set the maximum rows that will be returned by the query.

 <h2>Search Contacts</h2> <!--- creates form ---> <cfform action="ContactSearch.cfm"> <!--- creates text field ---> <P>Last name: <cfinput FONT="Verdana"  bgColor="white"  TEXTCOLOR="Blue"  name="LastName"  required="Yes"> <!--- creates slider control ---> <P><cfslider name="volume"  height="100"  width="200"  font="Verdana"  bgColor="lightgray"  textColor="Blue" label="Maximum rows %value%"  range="0,50"  scale="5"> <!--- creates submit button ---> <P><input type="Submit" value="Search"> </cfform> 

NOTE

The <cfslider> control is accessible only by users with Java-enabled browsers and must be used in a <cfform>.


See also <cfform>, <cfgrid>, <cfinput>, <cfselect>, <cftextarea>, <cftree>


<cfstoredproc>

Description: <cfstoredproc> provides sophisticated support for database-stored procedures. Unlike <cfquery>, which can also call stored procedures, <cfstoredproc> and its supporting tags (<cfprocparam> and <cfprocresult>) can pass and retrieve parameters and access multiple resultsets. <cfstoredproc> attributes are listed in Table B.136.

Table B.136. <cfstoredproc> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

blockFactor

Number of rows to retrieve at once

Optional; available if using ODBC or Oracle drivers; valid values are 1 to 100; default value is 1.

dataSource

Data source name

Optional; used to override the data source specified when the report was created.

debug

Yes or No

Optional; turns on query debugging output.

passWord

Password

Optional; used to override the password provided in the ColdFusion Administrator.

procedure

Stored procedure name

Name of stored procedure to execute.

result

Variable name

Optional; will store information about the query and result in a structure that uses the name you provide. The structure is described in table B.137 below.

returnCode

Yes or No

Optional; indicates whether to populate cfstoredproc.statusCode returned by stored procedure. Defaults to No.

userName

user name

Optional; used to override the login name specified in the ColdFusion Administrator.


Syntax:

 <cfstoredproc   dataSource="Data Source Name"  username="User Name"  passWord="Password"  procedure="Procedure"  blockFactor="factor"  debug="Yes or No"  result="Variable name"  returnCode="Yes or No"> 

Table B.137. RESULT structure elements

ELEMENT

DESCRIPTION

Execution time

Milliseconds


Example: The first example executes a simple stored procedure named GETEMPLOYEES. This is just a SELECT query that builds a resultset named GETEMPLOYEES:

 <!--- calls stored procedure ---> <cfstoredproc dataSource="OWS"  procedure="GetEmployees">  <!--- names stored procedure result --->  <cfprocresult name="GetEmployees"> </cfstoredproc> 

The next example invokes a stored procedure named GETNEXTNUMBER, which increments a value in a table by 1 and then sends the new number back to the calling routine. It takes an input parameter named Tblname and generates a value named BUDGETCATEGORYID, which you can then use in your application.

 <!--- calls stored procedure ---> <cfstoredproc procedure="GetNextNumber"  dataSource="OWS"  returnCode="YES">  <!--- passes parameter to stored procedure --->  <cfprocparam type="IN"  dbVarName="@TblName"  value="#KeyName#"  cfSqlType="CF_SQL_CHAR"  maxLength="20"  null="no">  <!--- passes parameter to stored procedure --->  <cfprocparam type="OUT"  variable="BudgetCategoryID"  dbVarName="@intNextNmbr"  cfSqlType="CF_SQL_INTEGER">  <!--- names stored procedure results and selects   partcular resultset--->  <cfprocresult name="Set1"  resultSet="2" </cfstoredproc> <!--- displays results from stored procedure results ---> <cfoutput query="Set1">  <P>Total Actor Salary Budget=#Set1.ActorSalary#</p> </cfoutput> 

See also <cfprocparam>, <cfprocresult>, <cfquery>


<cfswitch>

Description: <cfswitch> is used to create case statements in ColdFusion. Every <cfswitch> must be terminated with a </cfswitch>. The individual case statements are specified using the <cfcase> tag; a default case can be specified using the <cfdefaultcase> tag.<cfswitch> attributes are shown in Table B.138.

Table B.138. <cfswitch> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

expression

Case expression

This attribute is required.


Syntax:

 <cfswitch expression="expression">  <cfcase value="value">  HTML or CFML code  </cfcase>  <cfdefaultcase>  HTML or CFML code  </cfdefaultcase> </cfswitch> 

Example: The following example checks to see whether a state is a known state and displays an appropriate message:

 <cfswitch expression="#UCase(state)#">  <cfcase value="CA">California</cfcase>  <cfcase value="FL">Florida</cfcase>  <cfcase value="MI">Michigan</cfcase>  <cfdefaultcase>One of the other 47 states</cfdefaultcase> </cfswitch> 

You can replace some long <cfswith><cfcase...> statements with a structure. Look at this code:

 <cfswitch expression="#FORM.Meal#">  <cfcase value="Breakfast">  <cfset Drink="Coffee">  </cfcase>  <cfcase value="Lunch">  <cfset Drink="Iced Tea">  </cfcase>  <cfcase value="Snack">  <cfset Drink="Coke">  </cfcase>  <cfcase value="Dinner">  <cfset Drink="Wine">  </cfcase> </cfswitch> 

Now, assume you have built this structure:

 <cfset Beverages=StructNew()> <cfset Beverages["Breakfast"]="Coffee"> <cfset Beverages["Lunch"]="Iced Tea"> <cfset Beverages["Snack"]="Coke"> <cfset Beverages["Dinner"]="Wine"> <cfset meal=FORM.Lunch> 

NOTE

Given this structure, the following single line of code eliminates the need for the lengthy switch/case logic shown previously:


 <cset Drink=Beverages["#meal#"]> 

See also <cfif>, <cfcase>, <cfdefaultcase>


<cftable>

Description: <cftable> enables you to easily create tables in which dynamically generated query data is displayed. <cftable> can create HTML tables (using the <table> tag) or preformatted text tables (using <pre>, </pre>) that display on all browsers. Using <cftable> involves two tags: <cftable> defines the table itself, and one or more <cfcol> tags define the table columns. The <cftable> attributes are listed in Table B.139.

Table B.139. <cftable> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

border

Adds border to HTML table

Optional; use when specifying htmlTable.

colHeaders

Displays column headers

Optional; column headers are displayed as specified in <cfcol>.

colSpacing

Spaces between columns

Optional; overrides the default column spacing of 2 if present.

headerLines

Number of header lines

Optional; defaults to 2; one for the header and a blank row between the header and the body. You can increase this number if needed.

htmlTable

Creates an HTML table

Optional; an HTML table is created if this attribute is present. If not, a preformatted text table is created.

maxRows

Maximum number of table rows

Optional; specifies the maximum number of rows to be displayed in the table.

query

<cfquery> name

Required; the name of the query from which to derive the table body text.


Syntax:

 <cftable query="Query Name"  maxRows="Maximum Rows"  colSpacing="Column Spacing"  border="Border Size"  headerLines="Header Lines"  htmlTable  colHeaders> <cfcol header="Header Text"  width="Width"  align="Alignment"  text="Body Text"> </cftable> 

Example: This example queries a database and then displays the output using <cftable> and <cfcol>:

 <!--- Gets raw data from database ---> <cfquery name="GetFilms" dataSource="OWS">  SELECT FilmID, MovieTitle  FROM Films </cfquery> <h1>Use of cftable and cfcol</h1> <!--- creates table from query results ---> <cftable query="GetFilms">  <!--- creates table column --->  <cfcol header="Film ID"  width="8"  align="Right"  text="<em>#FilmID#</em>">  <!--- creates table column --->  <cfcol header="Name"  width="30"  align="Left"  text="#MovieTitle#"> </cftable> 

NOTE

The <cftable> tag is an easy and efficient way to create tables for displaying query results. You should create HTML tables manually for greater control over table output, including cell spanning, text and background colors, borders, background images, and nested tables.


See also <cfcol>, <cfoutput>, <cfquery>


<cftextarea>

Description: <cftextarea> lets you provide a large field in a form for text entry. It can be multiple columns wide and multiple rows high, like an HTML <textarea> tag. Like <cfinput>, it is used inside <cfform> tag body and provides many advanced validation functions. Like <textarea>, it is used with an end tag with text in the tag body. The <cftextarea> attributes are listed in Table B.141.

Syntax:

 <cftextarea  bind="Bind exp"  disabled="Yes, No or NULL"  height="Number in pixels"  label="text"  message="Message text"  maxLength="Length"  name="name"  onChange="JavaScript or ActionScript"  onClick="JavaScript or ActionScript"  onError="JavaScript Error Function"  onKeydown="JavaScript or ActionScript"  onKeyup="JavaScript or ActionScript"  onMousedown="JavaScript or ActionScript"  onMouseup="JavaScript or ActionScript"  onValidate="JavaScript Validation Function"  pattern="Regex exp"  range="Max,Min"  required="Yes or No"  style="Specification"  validate="Type"  validateAt="onBlur and/or onServer and/or onSubmit"  value="Initial value"  width="Number in pixels"> Text here </cftextarea> 

Table B.140. <cftextarea> Attributes

ATTRIBUTE

AVAILABLE

DESCRIPTION

NOTES

bind

Flash

Flash bind expression.

Optional; it populates the field based on other form fields.

cols

All

Integer

Optional; indicates the number of columns to display. You'll certainly want to provide a value; the text-area display will be useless without a value.

disabled

All

Yes, No, or null

Optional; disables user input.

height

Flash, HTML

Control height in pixels

Optional; works with most Flash type controls and HTML Image type.

LABeL

Flash, XML

Label for use in form.

Do not use when TYPE is Button, Hidden, Image, Reset, or Submit.

maxLength

All

Maximum number of characters

Optional; used when TYPE is Text or Password Note that this will not prevent users from pasting in longer values. To prevent that, set VALIDATE to Maxlength.

message

All

Validation failure message

Optional message to display upon validation failure.

name

All

Unique control name

Required.

onChange

HTML, XML

Javascript, actionscript

Optional; runs when control is changed by user. In Flash, only applies when TYPE is Datefield, Text, or Password.

onClick

HTML, XML

Javascript, actionscript

Optional; runs when users clicks the mouse. In Flash, only applies when TYPE is Button, Checkbox, Image Reset, Radio, and Submit.

onError

HTML, XML

Javascript, actionscript

Optional; JavaScript function used if validation fails.

ONKEYUP

HTML, XML

JavaScript error function

Optional; runs when user releases a key.

onKeyDown

HTML, XML

Javascript, Actionscript

Optional; runs when user presses a key.

onKeyUp

HTML, XML

Javascript, actionscript

Optional; runs when user releases a key.

onMouseUp

HTML, XML

Javascript, actionscript

Optional; runs when user releases the mouse button.

onMouseDown

HTML, XML

Javascript, Actionscript

Optional; runs when user clicks the mouse button down.

onValidate

HTML, XML

JavaScript validation function

Optional; used to specify your own JavaScript validation function. Should return True or False. When used, the VALIDATE attribute is ignored.

pattern

All

Javascript regex pattern

Optional, but required if validate=Regex (or regular_expression). Leading and trailing slashes should be omitted.

range

All

Min and max values

Optional range for numeric values only; must be specified as two numbers separated by a comma. Use in conjunction with VALIDATE=Range.

required

Yes or No

Require and Flag

Optional; indicates that value must be supplied; defaults to No.

rows

All

Integer No

Optional; number of rows to display in the text area. Defaults to 1.

style

All

CSS or XSL style

Optional. STYLE attribute is passed to the browser when TYPE is HTML or XML. In Flash forms, STYLE must contain a CSS.

validate

All

Field validation

Optional field validation type (see Table B.141).

validateAt

All

Validation Location

Optional; indicates what event(s) should result in validation. Set to one or more values from this list, separated by commas: onSubmit, onServer, onBlur.

value

HTML, Flash

Initial value

Optional initial field value. In HTML, it's the same as the VALUE attribute. In Flash it is used to specify text for Button, Submit and Image type inputs.

width

Flash, HTML

Control width in pixels

Optional; works with most Flash type controls and HTML Image type.


Table B.141. <cftextarea> Validation Types

TYPE

DESCRIPTION

BOOLEAN

Must be convertible to a number, Yes, No, True, or False.

CREDITCARD

Correctly formatted credit card number verified using mod10 algorithm. Must have between 13 and 16 digits.

DATE

Same as USDATE format unless your VALIDATEAT setting includes onServer. In this case, it will return True if the isDate() function would return True.

EMAIL

Verifies email format, not validity of actual address.

EURODATE

Looks for months preceding days with /, - or . delimiters. Days and months can have 1-2 digits, years can be 1-4 digits.

FLOAT/NUMERIC

Number with decimal point. Can be an integer.

GUID

A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number

INTEGER

Number with no decimal point.

MAXLENGTH

Limits maximum number of characters that can be input.

NOBLANKS

Prohibits entry of all blanks.

RANGE

Provides min and max values, separated by a comma.

REGEX/REGULAR_EXPRESSSION

Matches input against value of PATTERN attribute.

SOCIAL_SECURITY_NUMBER/SSN

Social security number formatted as 999-99-9999 (using hyphens or spaces as separators).

SUBMITONCE

Prevents user from submitting form multiple times. Only useful with Image and Submit types.

TELEPHONE

Phone number in standard US format (999-999-9999). Will accept hyphens or spaces as separators. Area code and exchange must not begin with 0 or 1. Can include a long-distance digit and up to a 5-digit extension, which should begin with x.

TIME

Time in hh:mm or hh:mm:ss format.

URL

Requires a valid URL pattern. Supports HTTP, HTTPS, FTP, FILE, MAILTO, and NEWS URLs.

USDATE

Looks for days preceding months, then years with / delimiters. Days and months can have 1-2 digits, years can be 1-4 digits.

UUID

Requires input formatted like a universally unique identifier in ColdFusion: xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx. Each x must be from the hexadecimal characterset.

ZIPCODE

U.S. ZIP code, in either 99999 or 99999-9999 format. Separator can be either a hyphen or a space.


If your form posts to itself and you want to preserve the user input (as opposed to what ever value was originally displayed via the VALUE attribute), use the <cfform preserveData="Yes"...>.

See the discussion of the <cfinput> tag for more on the validation capabilities of <cftextarea>.

You can't use the value attribute if you set a value with text in the body of the <cftextarea>. You must choose to use either the value attribute or the body. If you don't use the body, you must use ending "/" syntax: <cftextarea ... />.

Example: The following example displays a form for updating summary information about a film. The summary field is required.

 <!--- Get desired movie info ---> <Cfparam name="URL.FilmID" default="4" type="Integer"> <cfquery name="getFilms" dataSource="ows">   SELECT FilmID, MovieTitle, Summary   FROM Films   WHERE FilmID = #URL.FilmID# </Cfquery> <html> <head>   <title>CFTEXTAREA Example</title> </head> <body> <!--- Display form with film name and text area ---> <cfform name="SummaryForm" method="POST"> <p><cfoutput>#getFilms.MovieTitle#</cfoutput> <!--- Make summary value in textarea required ---> <p><cftextarea name="Summary" required="Yes"      message="You must enter a summary" rows="5"     cols="30"><Cfoutput>#getFilms.Summary#</cfoutput></cftextarea> </cfform> </p> </body> </html> 

<cftextinput>

This tag has been deprecated. See <cfinput>.

<cfthrow>

Description: <cfthrow> is used to force an error condition in a <cftry>, </cftry> block. Program control is then handed to a <cfcatch> in which TYPE is set to APPLICATION, ANY, or a custom type. You can optionally use this tag to invoke a Java exception. <cfthrow> attributes are listed in Table B.142.

Table B.142. <cfthrow> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

detail

Description of error

Optional; detailed description of error.

errorCode

Custom error code

Optional; developer-specified error code.

extendedInfo

Additional info

Optional; additional information on the error.

message

Error message

Optional; developer-specified description.

object

Name of object

Optional; mutually exclusive with all other tag attributes. This is the value of the name attribute from an object invoked with <cfobject>.

type

Type of error

Optional; must be either APPLICATION or a condition custom type. If you use APPLICATION, you do not have to specify a TYPE for <cfcatch>.


Syntax for throwing a normal exception:

 <cfthrow   detail="Error description"  errorCode="Code"  extendedInfo="More error information"  message="message" type="Error type"> 

Syntax for throwing Java exception:

 <cfthrow  object="object name"> 

Example: This code checks for the existence of a specified SESSION variable. If it doesn't exist, a custom, developer-specified error is thrown and trapped in the <cfcatch> of the specified, custom type:

 <!--- sets trap for errors ---> <cftry>  <!--- if variable is not present --->  <cfif NOT IsDefined("SESSION.UserID")>  <!--- creates custom error type --->  <cfthrow type="AppSecurity"  message="Invalid auhthorization"  errorCode="210"  detail="Access is restricted to authenticated users">  </cfif> <!--- catches app security errors ---> <cfcatch type="AppSecurity">  <!--- displays error messages --->  <cfoutput>  <p>(#CFCATCH.ErrorCode#) <B>#CFCATCH.Message#</b>  <p>#CFCATCH.Detail#  </cfoutput> </cfcatch> </cftry> 

See also <cftry>, <cfcatch>


In this second example, a Java object is instantiated for the purpose of handling the error that you throw:

 <cfobject  type="Java"  action="Create"    name="MyObj"> <cfset MyObj.init("SomeAttribute", "SomeValue")>  ... <cfthrow OBJECT=#MyObj#> 

<cftimer>

Description: <cftimer> lets you determine the execution time of the code in its body. You place <cftimer>...</cftimer> around the section of code you want to time. Use the attributes in Table B.143 to indicate how you want the output displayed.

Table B.143. <cftimer> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

label

Descriptive label

Optional. A label will help you identify a particular instance of <cftimer> in the event that you use it multiple times in one page.

style

Inline or Comment or Debug or Outline

Optional; defaults to Debug. Use inline to display <cftimer> output inline with your HTML. Use Comment to include <cftimer> output in a comment in the HTML source, like this: <!-- label: elapsed-time ms -->. When you use Outline, <cftimer> will cause a line to be displayed around the section within the <cftimer> body. Note that your browser must support the fieldset tag for this to work. Use Debug to have <cftimer> output included with other debug output at the bottom of the rendered page.


Syntax:

 <cftimer  label="Descriptive label"  style="Inline or Comment or Debug or Outline">  Your code here </cftimer> 

NOTE

In order for <cftimer> information to appear you must not only have debugging enabled (in the CF Administrator in the Debugging and Logging section) but you must explicitly enable Timer information type debugging, which is another setting on the same page.


Example: This examples uses <cftimer> twice, first to provide information on an <cfoutput> loop then on a <cfloop>:

 <cfquery name="GetActors" dataSource="ows">   SELECT nameFirst, NameLast   FROM Actors </cfquery> <html> <head>     <title>CFTimer test</title> </head> <body> <h1>output</h1> <cftimer label="cfoutput execution" style="outline"> <cfoutput query="GetActors"> <p>#NameFirst# #NameLast#</P> </cfoutput> </cftimer> <h1>loop</h1> <cftimer label="<Strong>cfloop execution</Strong>" style="inline"> <cfloop query="GetActors"> <p><cfoutput>#NameFirst# #NameLast#</Cfoutput></P> </cfloop> </cftimer> </body> </html> 

See also <cfdump>, <cftracfe>


<cftrace>

Description: <cftrace> logs and provides debugging information about the state of the application when it is called. Output is logged to the file logs\cftrace.log, in the directory in which ColdFusion was installed. It provides a variety of useful information including variable values, logic flow and execution time. This information can be displayed with the page output and in Dreamweaver 5 (or later). The <cftrace> attributes are list in Table B.144.

Table B.144. <cftrace> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

abort

Yes or No

Optional; indicates whether or not processing is to be aborted after <cftrace> execution.

category

User-defined value

Optional; user-defined name of category for identifying related traces. Enables you to identify purpose of related traces in the generated log file.

inLine

Yes or No

Optional; when set to Yes, output is flushed to page as tag executes, even if used in <cfsilent>.

text

User-defined value

Optional; is output to the Text column in the log file attribute. Used for tracking related tag traces.

type

Optional

Optional; indicates output format as one of the following types: Information, Warning, Error, Fatal Information. Populates CFLOG column with the same name.

var

Variable name

Optional; name of specific variableeither simple or complexwhich is to be displayed. Complex variables are displayed in same format as using <cfdump>.


Syntax:

 <cftrace abort="Yes or No"  category="Category name"  inLine="Yes or No"  text="String to be logged"  type="Output format type"  var="Variable name"> 

NOTE

Note that in order for <cftrace> to work, you must enable debugging (on the Debugging settings page) in the ColdFusion Administrator.


Example: This example logs the value of a the OpenOrderTotal variable and logs it with the CATEGORY set to the name of the current application:

 <!--- Create structure for passing arguments and instantiate object. ---> <cfscript>  DateRange = StructNew();  DateRange.StartDate = "1/1/2002";  DateRange.EndDate = "3/22/2002";  CreateObject("Component", "Orders"); </cfscript> <!--- Now execute the method and pass it the structure of arguments. ---> <cfinvoke Component="Orders" method="OrderTotal"  RETURNVARIABLE="OpenOrderTotal" argumentCollection="#DateRange#"> </cfinvoke> <cftrace var="OpenOrderTotal" type="information"   category="My Variables" text="This is a trace operation."> 

The resulting cftrac.log entry looks like this:

[View full width]

"Information","web-7","03/24/02","19:17:48","OWS","[{ts '2002-03-24 19:17:48'}] [0 ms] [] - [My Variables] [OpenOrderTotal = 83.99] This is a trace operation. "

See also <cfdump>, <cftimer>


<cftransaction>

Description: <cftransaction> enables you to group multiple <cfquery> uses into a single transaction. Any <cfquery> tags placed between <cftransaction> and </cftransaction> tags are rolled back if an error occurs. The <cftransaction> attributes are listed in Table B.145.

Table B.145. <cftransaction> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Type of action

Optional; BEGIN (default), COMMIT, or ROLLBACK.

isolation

Type of ODBC lock

Optional lock type; possible values are Read_Uncommitted, Read_Committed, Repeatable_Read, and Serializable.


Syntax:

 <cftransaction isolation="Lock Type"  action="Action"> Queries </cftransaction> 

The Action "begin" signifies the start transaction. You can nest <cftransaction> tags and force commits or rollbacks by setting action to COMMIT or ROLLBACK in your nested transactions.

NOTE

When <cftransaction> is used in combination with ColdFusion's error handling, you can tell when a database transaction fails. This gives you control over whether queries grouped into transactions are to be committed or rolled back.


NOTE

Not all lock types are supported by all ODBC drivers. Consult your database documentation before using the ISOLATION attribute.


Example: The first example demonstrates a simple use of <cftransaction> to ensure that either both queries succeed or the transaction is canceled:

 <!--- encapsulates queries into one unit ---> <cftransaction>  <!--- gets raw data from database --->  <cfquery name="InsertContact" dataSource="OWS">  INSERT INTO Contacts (FirstName, LastName, Phone, UserLogin)  VALUES ('Joe', 'Blow', '333-112-1212', 'JoeBlow')  </cfquery>  <!--- gets raw data from database --->  <cfquery name="InsertActor" dataSource="OWS">  INSERT INTO Actors (NameFirst, NameLast, Gender)  VALUES ('Joe', 'Blow', 'M')  </cfquery> </cftransaction> 

The second example does the same thing but demonstrates the use of <cftransaction action= "Rollback"> and <cftransaction action="Commit">. Note that these aren't really required in this simple example; we're just doing it this way to demonstrate the technique.

 <!--- sets variable ---> <cfset DoCommit="Yes"> <!--- starts code execution ---> <cftransaction action="BEGIN"> <!--- sets trap for errors ---> <cftry> <!--- gets raw data from database ---> <cfquery name="InsertContact" dataSource="OWS">  INSERT INTO Contacts (FirstName, LastName, Phone, UserLogin)  VALUES ('Joe', 'Blow', '333-112-1212', 'JoeBlow')  </cfquery>  <!--- gets raw data from database ---> <cfquery name="InsertActor" dataSource="OWS">  INSERT INTO Actors (NameFirst, NameLast, Gender)  VALUES ('Joe', 'Blow', 'M')  </cfquery> <!--- catches erros ---> <cfcatch type="DATABASE">  <!--- starts transaction over --->  <cftransaction action="ROLLBACK"/>  <!--- sets variable --->  <cfset DoCommit="No"> </cfcatch> </cftry> <!--- if variable is Yes, transaction is processed ---> <cfif DoCommit EQ Yes>  <cftransaction action="COMMIT"/> <!--- if variable doesn't equal Yes, message is displayed ---> <cfelse>  <p>Failure </cfif> </cftransaction> 

NOTE

The use of abbreviated ending tag syntax, as shown in the previous example, enables you to omit the ending tag. It's valid in this situation because there is no body between the beginning and ending tag.


See also <cfstoredproc>


<cftree>

Description: <cftree> embeds a heirarchical tree control in your HTML forms constructed within a <cfform> tag body. The tree control is similar to the Explorer window used in several versions of Windows and is in fact used in the ColdFusion Administrator (when browsing for an ODBC data source). The tree is made of root entries and branches that can be expanded or closed. Branches can be nested. Each branch has a graphic displayed next to it; you can select from any of the supplied graphics or use any of your own.

The control can be rendered as Flash, XML, a Java applet, or a CF object.

<cftree> trees are constructed using two tags. <cftree> creates the tree control, and <cftreeitem> adds the entries into the tree. Trees can be populated one branch at a time or by using query results. <cftreeitem> must be used between <cftree> and </cftree> tags. <cftree> attributes are listed in Table B.146. Some of its attributes will work only in one of these formats; these exceptions are noted in the table.

Table B.146. <cftree> Attributes

ATTRIBUTE

AVAILABLE

DESCRIPTION

NOTES

align

Applet

Control alignment

Optional. Possible values are Top, Left, Bottom, Baseline, Texttop, ABSbottom, Middle, ABSmiddle, and Right.

appendKey

All

Yes or No

Optional; appends item key to URL. If Yes, variable named CFTREEITEMKEY is appended to the URL containing the item selected; defaults to Yes.

bold

Applet

Yes or No

Optional; makes text bold; defaults to No.

border

Applet

Yes or No

Optional; displays border; defaults to Yes.

completePath

Applet

Yes or No

Optional; passes the full tree path to the selected item when set to Yes; defaults to No.

delimiter

All

Path delimiter character

Optional; defaults to \.

font

Applet

Font face name

Optional font face to use.

fontSize

All

Number of pixels

Optional font size.

format

All

Flash, XML, Applet or Object

Optional; defaults to Applet. Indicates how you want the control rendered. Object causes the tree to be returned as a ColdFusion object. XML creates an XML version of the tree.

height

All

Number of pixels

Optional height in pixels. Defaults to 320 in applet format.

highlightHref

Applet

Yes or No

Optional; links are highlighted and underlined if Yes; defaults to Yes.

hSpace

Applet

Number of pixels

Optional; horizontal spacing in pixels.

hScroll

Applet

Yes or No

Optional; displays horizontal scrollbar; default is Yes.

italic

Applet

Yes or No

Optional; italicizes text; defaults to No.

lookAndFeel

Applet

Motif, Windows, Metal

Optional; defaults to Windows. The tag will default to the platform's default style if the platform doesn't support a style option.

message

Applet

Validation failure message

Optional; message to display upon validation failure.

name

All

Unique control name

Required.

notSupported

Applet

Text message

Optional; text (or HTML code) to be displayed on non-Javacapable browsers.

onChange

Flash

ActionScript

This actionscript is executed when the control value changes based on user interaction. When this attribute is used, Information about the selected items will not be available in the FORM scope of the action page for the form containing this controls.

onError

Applet

JavaScript error function

Optional override to your own JavaScript error message function.

onValidate

Applet

JavaScript function

Optional override to your own JavaScript validation function.

reQuired

All

Yes or No

Optional; a selection will be required when set to Yes; defaults to No.

style

Flash

CSS style spec

Optional.

vSpace

Applet

Number of pixels

Optional; vertical spacing in pixels.

vScroll

Applet

Yes or No

Optional; displays a vertical scrollbar when set to Yes; default is Yes.

width

All

Number of pixels

Optional; width of control. Defaults to 200 when used in applet format.


Syntax:

 <cftree  align="Alignment"  appendKey="Yes or No"  bold="Yes or No"  border="Yes or No"  completePath="Yes or No"  delimiter="Delimiter Character"  font="Font Face"  fontSize="Font Size"   format="Applet or Flash or XML or Object"  height="Control Height"   highlightHref="Yes or No"  hSpace="Horizontal Spacing"   hScroll="Yes or No"   ITALIC="Yes or No"  lookAndFeel="Windows or Motif or Metal"  message="Error Message"   name="Field Name"   notSupported="Non Java Browser Code"  onChange="ActionScript"  onError="Error Function"   onValidate="Validation Function"   required="Yes or No"  style="CSS style"  vScroll="Yes or No"  vSpace="Vertical Spacing"   width="Control Width"> 

When a form containing a tree is submitted, ColdFusion will create a two-element structure in the action template named for the name attribute of the tree. The two elements are Path and Node. Path lists the path from the root to the selected node, using the character defined in delimiter. Node contains the value of selected node in the tree.

If you want the user's tree selections to persist after the form is submitted rather than being set based on default values when the tree is produced again, use the PreserveData attribute in the <cfform> and design the process so that the form submits to itself. If you set format to OBJECT, ColdFusion will produce the tree as a structure variable; it will not be returned to the browser. The structure will be named after the value of the name attribute. At the top level, the structure has entries which represent the values of the attributes that were used in the <cftree> tag. It also contains an element named Children, which is an array containing a structure which in turn contains an array with an element for each <cftreeitem>. Each of these array elements contains a structure representing the values of the <cftreeitem> attributes that were used to produce it. The first example below uses <cfdump> to display this structure.

NOTE

When rendering the tree as Flash in an HTML form, the Flash tree may take up a lot of room if you don't specify a width and height.


Example: This example creates a simple tree in Flash, then uses <cftree> a second time to render a structure by setting format=object:

 <html> <head>   <title>CF Tree Example</title> </head> <body> <!--- creates form ---> <cfform action="process.cfm"> <!--- populates tree branches with data ---> <cftree name="states" format="Flash" height="150" width="210">  <cftreeitem value="US">  <cftreeitem value="CA" display="California" parent="US">  <cftreeitem value="MI" display="Michigan" parent="US">  <cftreeitem value="NY" display="New York" parent="US"> </cftree> <cftree name="states2" format="object">  <cftreeitem value="US">  <cftreeitem value="CA" display="California" parent="US">  <cftreeitem value="MI" display="Michigan" parent="US">  <cftreeitem value="NY" display="New York" parent="US"> </cftree> <input type="Submit" value="Select a State"> </cfform> <cfdump var="#states2#"> </body> </html 

This next example populates a tree with a query called Users:

 <!--- gets raw data from database ---> <cfquery name="GetUsers" datasource="ows">  SELECT ContactID, FirstName & ' ' & LastName as userName, UserLogin  FROM Contacts </cfquery> <!--- creates form ---> <cfform action="process.cfm"> <!--- creates tree ---> <cftree name="peopletree" hSpace="20" hscroll="no" vScroll="Yes"   delimiter="?" border="Yes"> <!--- populates tree with query results ---> <cftreeitem value="UserName" queryAsRoot="Yes" query="GetUsers"  img="folder,document" href="EditUser.cfm"> </cftree> </cfform> 

The last example demonstrates the use of <cftree> to produce a tree with nested branches. In this case, it displays a list of movies and the actors in the movies.

 <!--- gets raw data from database ---> <cfquery name="GetFilmActors" datasource="ows">  SELECT FA.FilmID, A.NameFirst, A.NameLast, F.MovieTitle  FROM (Actors A INNER JOIN FilmsActors FA ON A.ActorID = FA.ActorID)   INNER JOIN Films F ON FA.FilmID = F.FilmID </cfquery> <!--- creates form ---> <cfform action="process.cfm"> <!--- creates tree ---> <cftree name="FilmActors" height="150" width="300"   highlightHref="Yes">   <!--- displays one branch for each film--->   <cfoutput query="GetFilmActors" group="FilmID">     <cftreeitem value="#MovieTitle#" expand="No">     <cfoutput>       <!--- creates a node for actor in the film --->       <cftreeitem img="Document" value="#NameFirst# #NameLast#"        href="ViewActor.cfm" parent="#MovieTitle#">     </cfoutput>   </cfoutput> </cftree> </cfform>note 

The <cftree> control is accessible only by users with Java-enabled browsers.

See also <cfform>, <cfgrid>, <cfinput>, <cfselect>,<cfslider>, <cftextarea>, <cftreeitem>


<cftreeitem>

Description: <cftree> trees are constructed using two tags. <cftree> creates the tree control, and <cftreeitem> adds the entries into the tree. Trees can be populated one branch at a time or by using query results. <cftreeitem> must be used between <cftree> and </cftree> tags. <cftree> attributes are listed in Table B.147.

Table B.147. <cftreeitem> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

display

Display text

Optional attribute. Defaults to value is not specified. If populating with a query resultset, this value should be a comma-delimited list of valuesone for each tree item.

expand

Yes or No

Optional; branch is initially expanded if Yes; defaults to No.

HRef

Item URL

Optional; URL to go to when an item is selected; if populating with a query resultset, this value can be a comma-delimited list of URLs (one for each tree item), or it can be a column name. In that case, it is populated dynamically.

img

Image

Optional; image to be displayed; if populating with a query resultset, this value should be a comma-delimited list of images, one for each tree level; images can be Cd, Computer, Document, Element, Fixed, Folder, Floppy, Remote, or any image file of your own.

imgOpen

Open image

Optional; image to be displayed when branch is open; if populating with a query resultset, this value should be a comma-delimited list of images, one for each tree level; same selections as IMG. If omitted, the IMG image is used.

parent

Parent item name

Optional; name of parent item to attach this branch to.

query

Query name

Optional query name to be used to populate the list.

queryAsRoot

Yes or No

Optional; if Yes, query name itself is the tree root branch; defaults to No. Prevents having to create a parent tree item.

target

Target for HREF

Optional; the window in which to open the link; this value can be a comma-delimited list of targets if populating with a query resultset, one for each tree item.

value

Value to be returned

Required; value to be returned when item is selected. Value should be a comma-delimited list of values, one for each tree item, if populating with a query resultset.


Syntax:

 <cftreeitem display="Display Text"   expand="Yes or No"   href="URL"   img="Images"  imgOpen="Images"   query="Query Name"   queryAsRoot="Yes or No"   target="Target Name"  parent="Parent Branch"   value="Values"> 

Example: See example for <cftree>

See also <cftree>


<cftry>

Description: <cftry> is used to catch exceptions thrown by ColdFusion or explicitly with <cfthrow> or <cfrethrow>. All code between <cftry> and </cftry> can throw exceptions, and exceptions are caught by <cfcatch> blocks. <cftry> has not attribute. Explicit <cfcatch> blocks can be created for various error types, or one block can catch all errors. <cfcatch> has one attribute, TYPE, which is described in Table B.148. B.149 lists the acceptable values of the TYPE attribute. A special structure variable, CFCATCH, is available in your <cfcatch> blocks. Its elements are described in Table B.150.

Table B.148. <cfcatch> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

type

Exception type

Optional; values listed in Table B.149.


Table B.150. CFCATCH Variable Elements

TYPE

ONLY FOR TYPE

DESCRIPTION

DETAIL

 

A detailed error message; helps determine which tag threw the exception.

ERRNUMBER

EXPRESSION

Internal expression error number.

ERRORCODE

Custom_Type

Developer-specified error code.

EXTENDEDINFO

APPLICATION Custom Type

Developer's custom error message.

LOCKname

LOCK

Name of the affected lock; set to anonymous if the lock was unnamed.

LOCKOPERATION

LOCK

Operation that failed; TIMEOUT, CREATE MUTEX, or UNKNOWN.

MESSAGE

 

Diagnostic message; can be null.

MISSINGFILEname

MISSINGINCLUDE

Name of file that could not be included.

NATIVEERRORCODE

DATABASE

The native error code from the database driver; -1 if no native code provided.

SQLSTATE

DATABASE

Another error code from the database driver; -1 if no native code provided.

TAGCONTEXT

 

Tag stack; name and position of each tag in the stack.

TYPE

 

Exception type, as specified in <cfcatch>.


Syntax:

 <cftry>   <cfcatch type="type">   </cfcatch> </cftry> 

Table B.149. <cfcatch> TYPE Values

TYPE

ANY

Custom_Type

APPLICATION

DATABASE

EXPRESSION

SEARCHENGINE

LOCK

SECURITY

MISSINGINCLUDE

TEMPLATE

OBJECT

 


Example: This example traps for an error when attempting to create a new directory programmatically:

 <!--- sets trap for errors ---> <cftry> <cfdirectory action="CREATE" DIRECTORY="#FORM.UserDir#">  <!--- catches any errors --->  <cfcatch type="ANY">  <!--- if error contains a certain phrase, message is displayed --->  <cfif CFCATCH.Detail CONTAINS "when that file already exists">  <P>Can't create directory: this directory already exists.  <cfelse>  <!--- if error does not contain specified phrase, the error details   are displayed --->  <cfoutput>#CFCATCH.Detail#</cfoutput>  </cfif>  <cfabort> </cfcatch> </cftry> <P>Directory created. 

You will find other useful examples in the entries for <cfrethrow>, <cfauthenticate>, and <cftransaction>.

See also <cfthrow>, <cfrethrow>


<cfupdate>

Description: <cfupdate> updates a single row to a database table; it requires that the database and table names be provided. All other attributes are optional. The full list of <cfupdate> attributes is explained in Table B.151.

Table B.151. <cfupdate> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

dataSource

Name of data source

Required; data source name.

formFields

List of fields to insert

Optional; specifies which fields are to be updated if they are present. Any fields present that are not in the list will not be updated.

passWord

ODBC data source password

Optional; used to override the ODBC login password specified in the ColdFusion Administrator.

tableName

Name of table to insert data into

Required; some ODBC data sources require fully qualified table names.

tableOwner

Table owner name

Optional; used by databases that support table ownership.

tableQualifier

Table qualifier

Optional; used by databases that support full qualifiers.

userName

ODBC data source login name

Optional; used to override the ODBC login name specified in the ColdFusion Administrator.


Syntax:

 <cfupdate dataSource="Data Source"  formFields="List of File to Update"  passWord="Password"   tableName="Table Name"   tableOwner="owner"   tableQualifier="qualifier"  userName="User Name"> 

NOTE

For <cfupdate> to work correctly, your form field names must match the column names in the destination table, and the primary key value of the row to be updated must be specified.


TIP

If your form contains fields that are not part of the table you are updating, use the formFields attribute to instruct ColdFusion to ignore those fields.


TIP

For more control over updating rows in a database table, use the <cfquery> tag specifying UPDATE as the SQL statement.


Example: In the first example, a simple data entry form is used to collect data to be updated in the Merchandise table:

 <!--- creates form ---> <form action="update_act.cfm" method="post"> <P>film id: <input type="Text" maxLength="5" name="filmid" value="18"> <P>merchandise name: <input type="Text" name="MerchName" maxLength="100"> <P>merchandise desc: <input type="Text" name="MerchDescription"> <P>merchandise price: <input type="Text" name="MerchPrice"> <p><input type="Submit"> </form> 

This <cfupdate> tag updates the table from this form data:

 <!--- updates database ---> <cfupdate dataSource="OWS" tableName="Merchandise"> 

However, if the form contains additional fields that don't correspond to the fields in the Merchandise table, you must use the formFields attribute to identify which form fields are to be inserted:

 <!--- updates database with only the specified variables ---> <cfupdate dataSource="OWS"   tableName="Merchandise"  formFields="FilmID,MerchName,MerchDescription,MerchPrice"> 

See also <cfupdate>, <cfquery>


<cfwddx>

Description: <cfwddx> is used to serialize and deserialize ColdFusion data structures to the XML-based WDDX format. Starting with ColdFusion MX, this tag supports different encoding formats. UTF-8 is the default. It now also preserves the case of column names in JavaScript. The attributes for this tag are shown in Table B.152. The action attribute specifies the action to be performed. The values for the action attribute are shown in Table B.153.

Syntax:

 <cfwddx action="action"  input="input"  output="output"   topLevelVariable="name"  useTimezoneInfo="Yes or No"> 

Table B.152. <cfwddx> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

action

Action

Required; actions are listed in Table B.152.

input

Input value

Required.

output

Output variable

Required if action is WDDX2CFML.

topLevelVariable

JavaScript top-level variable

Required if action is WDDX2JS or FML2JS.

useTImezoneInfo

Yes or No

Optional; indicates whether to include time zone information (in ISO8601 format) when data is being serialized; defaults to Yes.


Table B.1532. <cfwddx> Actions

ACTION

DESCRIPTION

CFML2JS

Serializes CFML to JavaScript format.

CFML2WDDX

Serializes CFML to WDDX format.

WDDX2CFML

Deserializes WDDX to CFML.

WDDX2JS

Deserializes WDDX to JavaScript.


Example: The example demonstrates serializing and deserializing a ColdFusion query result.

 <!--- gets raw data from database ---> <cfquery name="GetContacts" dataSource="OWS">  SELECT ContactID, FirstName, LastName  FROM Contacts </cfquery> <P>The recordset data is: <ul> <!--- displays query results ---> <cfoutput query="GetContacts">  <Li>#ContactID#, #FirstName#, #LastName# </cfoutput> </ul> <!--- Serializes CFML to WDDX packet ---> <P>Serializing CFML data <cfwddx action="cfml2wddx"   input="#GetContacts#"   output="Contacts"> <!--- displays WDDX packet ---> <P>Resulting WDDX packet is: <xmp><cfoutput>#Contacts#</cfoutput></xmp> <!--- deserializes WDDX packet ---> <P>Deserializing WDDX to CMFL <P> <cfwddx action="WDDX2CFML" INPUT="#Contacts#" OUTPUT="NewContacts"> <P>The recordset data is: <ul> <!--- displays query results ---> <cfoutput query="GetContacts">  <li>#ContactID#, #FirstName#, #LastName#<br> </cfoutput> </ul> 

<cfxml>

Description: <cfxml> parses an XML document and creates a ColdFusion XML document object from the tag body. The body of the tag can contain both XML content and CFML tags. If you include CFML tags in the body, they are processed first and the results are converted into a ColdFusion XML document object. A ColdFusion XML document object is a complex structure that breaks down the various parts of the XML document. The attributes for the <cfxml> tag are presented in Table B.154.

Table B.154. <cfxml> Attributes

ATTRIBUTE

DESCRIPTION

NOTES

variable

Variable name

Required; the variable into which the XML document object is to be stored.

caseSensitive

Yes or No

Optional; indicates whether or not the case of the original XML element names and attributes is to be preserved. Defaults to No.


A ColdFusion XML document object is a complex structure that ColdFusion builds from a parsed XML document. All ColdFusion XML document objects are comprised of all the same elements, but the values of and number of elements will change from one object to the next (based on the underlying XML content). Once the XML document has been parsed into this format through <cfxml>, you can then do what ever your application requires using CFML.

The structure of the ColdFusion XML document object can be thought of as consisting of two main levels: a top level, the elements of which are shown in Table B.155, and all levels below the top. Table B.156 shows these elements.

Table B.155. ColdFusion XML document object top-level structure

STRUCTURE ELEMENT

TYPE

DESCRIPTION

XmlRoot

Element

The root of the entire document.

XmlComment

String

The concatenation of the XML document's prologue and epilogue comments. Note that the comments that may be contained in document elements are not included.

XmlDocType

Node

If the XML document included a doctype, it will be contained in this node. This is not displayed through <cfdump>.


Table B.156. ColdFusion XML document object structure for levels below top

STRUCTURE ELEMENT

TYPE

DESCRIPTION

Xmlname

String

Element name.

XmlNsPrefix

String

Namespace prefix.

XmlNsURI

String

Namespace URI.

XmlText

String

All the text in the element (not including any element children). Note that any XML CData is concatenated on.

XmlComment

String

The concatenated comments in the element (not including any element children).

XmlAttributes

Structure

This element's attributes, presented as name/value pairs.

XmlChildren

Array

The children of this element.

XmlParent

Node

This contains the parent DOM node of this element. It is not displayed in <cfdump> output.

XmlNodes

Array

Contains the XML DOM nodes of this element. Does not appear in <cfdump> output of the element.


Syntax:

 <cfxml variable="Name of variable"   caseSensitive="Yes or No" > 

Example: The first example demonstrates the production of an XML document object.

[View full width]

<!--- Produce a ColdFusion XML document object from the the 'orders' XML document ---> <cfxml variable="XMLdoc"> <Orders> <Order order orderdate="3/1/2001" shipaddress="1 Rue Street" shipcity="Brussels" shipzip="1234" shipstate=""> <Orderitem orderitem item orderqty="2" itemprice="30.00"/> <Orderitem orderitem item orderqty="1" itemprice="17.50"/> <Orderitem orderitem item orderqty="1" itemprice="100.00"/> </Order> <Order order orderdate="3/1/2001" shipaddress="21700 Northwestern Hwy" shipcity="Southfield" shipzip="48075" shipstate="Michigan"> <Orderitem orderitem item orderqty="10" itemprice="7.50"/> </Order> </Orders> </cfxml> <!--- Display contents of XML document object ---> <cfdump VAR="#XMLdoc#">

The second example demonstrates the production of the same XML document object, but here the underlying XML document is produced dynamically based on a query result.

[View full width]

<!--- First select data to work with, linking order line items to orders ---> <cfquery name="GetOrders" DATABASE="OWS"> SELECT O.OrderID, OrderDate, ShipAddress, ShipCity ShipZip, ShipState, OrderItemID, ItemID, OrderQty, ItemPrice FROM Orders O INNER JOIN MerchandiseOrdersItems OI ON O.OrderID = OI.OrderID ORDER BY OrderID, OrderItemID </cfquery> <!--- Produce a ColdFusion XML document object from the the 'orders' XML document ---> <cfxml variable="XMLdoc"> <Orders> <!--- Outer CFOUTPUT creates order data ---> <cfoutput query="GetOrders" GROUP="OrderID"> <Order order orderdate="#OrderDate#" shipaddress="#ShipAddress#" shipcity="#ShipCity#" shipzip="#ShipZip#" shipstate="#ShipState#"> <cfoutput> <!--- Line item detail ---> <Orderitem orderitem item orderqty="#OrderQty#" itemprice="#ItemPrice#"/> </cfoutput> <!--- Inner CFOUTPUT (Order lines) ---> </Order> </cfoutput> <!--- Outer CFOUTPUT (Orders) ---> </Orders> </cfxml> <!--- Display contents of XML document object ---> <cfdump VAR="#XMLdoc#">



Macromedia Coldfusion MX 7 Web Application Construction Kit
Macromedia Coldfusion MX 7 Web Application Construction Kit
ISBN: 321223675
EAN: N/A
Year: 2006
Pages: 282

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net