<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.
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.
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.
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:
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.
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:
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.
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.
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">
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.
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>
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.
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.
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.
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.
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.
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.
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.
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.
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.
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".
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.
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.
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.
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.
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">
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.
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.
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>.
<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.
<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.
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">
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.
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">
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>
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:
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.
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>
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:
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.
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>.
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.
<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:
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.
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.
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:
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.
<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">
The built-in image types for use in the TYPE attribute are:
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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">
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.
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:
A method return value can be specified using the RETURNVAIRABLE attribute. See Table B.83 for a list and description of <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.
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>.
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">
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.
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.
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.
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">
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.
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.
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:
Table B.94 shows attributes for this tag.
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.
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.
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.
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.
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.
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.
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" >
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.
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.
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.
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:
nameExample: 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.
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">
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.
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.
Syntax: <cfprocparam type="In|Out|Inout" variable="variable" dbVarName="variable" value="value" cfSqlType="type" maxLength="length" null="Yes or No" scale="decimal places">
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.
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.
Syntax: <cfproperty name="Name of property" type="Data type name" >
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.
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>
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.
Syntax: <cfqueryparam cfSqlType="Param type" maxLength="Number" null="Yes or No" scale="Number of decimal places" separator="Delimiter character" value="Param value">
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.
Syntax: <cfregistry action="action" branch="branch" entry="entry" name="query" sort="sort order" type="type" value="value" variable="variable">
When the action is getAll, the following query result is returned:
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.
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:
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.
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.
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.
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">
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.
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">
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.
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.
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.
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.
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">
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.
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.
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>
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.
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.
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.
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:
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.
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.
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.
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.
Syntax: <cftry> <cfcatch type="type"> </cfcatch> </cftry>
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.
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">
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.
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.
Syntax: <cfxml variable="Name of variable" caseSensitive="Yes or No" > Example: The first example demonstrates the production of an XML document object.
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.
|