Adobe 38043740 - ColdFusion Standard - Mac Development Manual
Adobe 38043740 - ColdFusion Standard - Mac Development Manual

Adobe 38043740 - ColdFusion Standard - Mac Development Manual

Developing applications
Hide thumbs Also See for 38043740 - ColdFusion Standard - Mac:
Table of Contents

Advertisement

Quick Links

Developing Applications
COLDFUSION 9
ADOBE
®
®

Advertisement

Table of Contents
loading

Summary of Contents for Adobe 38043740 - ColdFusion Standard - Mac

  • Page 1 Developing Applications COLDFUSION 9 ADOBE ® ®...
  • Page 2 This guide is licensed for use under the terms of the Creative Commons Attribution Non-Commercial 3.0 License. This License allows users to copy, distribute, and transmit the guide for noncommercial purposes only so long as (1) proper attribution to Adobe is given as the owner of the guide; and (2) any reuse or distribution of the guide contains a notice that use of the guide is governed by these terms.
  • Page 3: Table Of Contents

    ..............11 About Adobe ColdFusion 9 documentation .
  • Page 4 DEVELOPING COLDFUSION 9 APPLICATIONS Contents Building a Search Interface ................... 476 Using Verity Search Expressions .
  • Page 5 DEVELOPING COLDFUSION 9 APPLICATIONS Contents Chapter 13: Working with Documents, Charts, and Reports Manipulating PDF Forms in ColdFusion ................914 Assembling PDF Documents .
  • Page 6: Chapter 1: What's New

    Chapter 1: What’s New The following sections explain what is new and changed in ColdFusion 9 and ColdFusion 9 update. What’s new in ColdFusion 9.0 Update 1 Area What’s new and changed Language Support for the following: • for-in construct (for arrays) in CFScript •...
  • Page 7 DEVELOPING COLDFUSION 9 APPLICATIONS What’s New Area What’s new and changed ColdFusion Ajax • Support for CFCs outside webroot • ColdFusion.FileUpload.getselectedfiles returns the status of upload operation • While using , the attribute is now optional and it defaults to cffileupload cgi.script_name •...
  • Page 8 DEVELOPING COLDFUSION 9 APPLICATIONS What’s New Area What’s new and changed • Supports multiple data sources for ORM in ColdFusion applications • The following enhancements: • New attribute added to MappedSuperClass cfcomponent component • New attributes added to skipCFCWithError automanagesession struct in the THIS scope of Application.cfc ormsettings •...
  • Page 9 DEVELOPING COLDFUSION 9 APPLICATIONS What’s New Area What’s new and changed BlazeDS 4 and LCDS Support for the following: • LCDS 3 and LCDS 3.1 • BlazeDS 4 • New methods in ColdFusion Messaging Gateway allowSend allowSubscribe CFCs Solr Apart from overall improvement in the accuracy of indexing, the following enhancements: •...
  • Page 10: What's New In Coldfusion 9

    ColdFusion ORM. Flex and AIR integration Adobe AIR applications Offline application support for AIR applications includes data persistence and synchronization. Offline capabilities ColdFusion uses SQLite in the client and ORM on the server to automatically manage conflict resolution and data synchronization when the application comes back online.
  • Page 11 DEVELOPING COLDFUSION 9 APPLICATIONS What’s New This release has introduced the following new functions implemented as CFCs: Script functions query mail http , and storedproc This release has introduced keywords for abort, exit, include, param, property, rethrow, and throw. Keywords CFScript now supports import and new operations.
  • Page 12 SharePoint integration. Office file interoperability ColdFusion provides interfaces to work with PDF, Adobe Flash, and Adobe Connect. ColdFusion now extends the integration support to Office applications such as Excel and PowerPoint. Using this feature, you can: • Create, read, and update MS Excel spreadsheets using the cfspreadsheet •...
  • Page 13 Note: By default, the datasource property MaxPooledStatements is set to 100 (and not 1000 as in the previous releases) for the drivers DB2, Informix, MSSQLServer, Oracle, Sybase, and MySQL(DataDirect). Adobe recommends that you maintain the default number of max pooled statements to avoid memory-related issues.
  • Page 14 DEVELOPING COLDFUSION 9 APPLICATIONS What’s New Service features ColdFusion as a service ColdFusion exposes many existing enterprise services as web services. You can access these services using SOAP and AMF/Flash remoting. The following are the exposed services: • cfpdf • cfImage •...
  • Page 15 DEVELOPING COLDFUSION 9 APPLICATIONS What’s New PDF functionality The following list includes new features and improved functionality: • FDF support in PDF forms • PDF package • Size optimization • Adding headers and footers to PDF documents using the cfpdf •...
  • Page 16: Chapter 2: Introduction

    The Developing Adobe® ColdFusion® 9 Applications guide provides tools for developing Internet applications using Adobe ColdFusion. The guide is intended for web application programmers who are learning ColdFusion or want to extend their ColdFusion programming knowledge. It provides a solid grounding in the tools that ColdFusion provides to develop many different types of web applications of varying complexity.
  • Page 17: Chapter 3: Introducing Coldfusion

    Adobe ColdFusion is a rapid application development environment that lets you build dynamic websites and Internet applications quickly and easily. It lets you develop sophisticated websites and Internet applications without knowing the details of many complex technologies, yet it lets advanced developers take advantage of the full capabilities of many of the latest Internet technologies.
  • Page 18: About Coldfusion

    • Return the results of keyword searches. About ColdFusion Adobe ColdFusion is a rapid scripting environment server for creating dynamic Internet Applications. ColdFusion Markup Language (CFML) is a tag-based scripting language that is easy to learn. CFML provides connectivity to enterprise data and powerful built-in search and charting capabilities.
  • Page 19 DEVELOPING COLDFUSION 9 APPLICATIONS Introducing ColdFusion ColdFusion pages are plain text files that you use to create web applications. You can create your ColdFusion applications by writing all the code manually or by using wizards (provided with some editors) to generate the majority of the code for you.
  • Page 20 DEVELOPING COLDFUSION 9 APPLICATIONS Introducing ColdFusion For more information, see “Elements of CFML” on page 17. CFML tags CFML looks like HTML—it includes starting and, in most cases, ending tags, and each tag is enclosed in angle brackets. All ending tags are preceded with a forward slash (/) and all tag names are preceded with ;...
  • Page 21: About J2Ee And The Coldfusion Architecture

    HTML-like text format, and you often use HTML in ColdFusion pages, you can also use an HTML editor or a text editor, such as Notepad, to write ColdFusion applications. ColdFusion 9 includes a line debugger that you can use to debug your ColdFusion applications in Eclipse™ or Adobe Flex™ Builder™.
  • Page 22: Chapter 4: The Cfml Programming Language

    Chapter 4: The CFML Programming Language Elements of CFML The basic elements of CFML, including tags, functions, constants, variables, expressions, and CFScript, make it a powerful tool for developing interactive web applications. CFML Basics CFML is a dynamic application development tool with many of the features of a programming language. These features include functions, expressions, variables and constants, and flow-control constructs, such as if-then and loops.
  • Page 23 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Note: You cannot embed comments inside a tag name or function name, such as <cf_My<!--- New --->CustomTag> You also cannot embed comments inside strings, as in the following example: IsDefined("My<!--- New --- >Variable") Tags ColdFusion tags tell the ColdFusion server that it must process information.
  • Page 24 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <!--- Configure dynamic attribute variables. ---> <cfparam name="theURL" default="http://www.adobe.com"> <cfparam name="resolveURL" default="yes"> <!--- Code that dynamically changes values for attributes can go here. ---> <!--- Create an arguments structure using variables. --->...
  • Page 25 They provide an easy way to distribute your code to others. You can even distribute encrypted versions of the tags to prevent access to the tag logic. You can access a variety of free and commercial custom tags on the Adobe ColdFusion Exchange (www.adobe.com/go/learn_cfu_cfdevcenter_en). They perform tasks ranging from checking if Cookies and JavaScript are enabled on the client browser to moving items from one list box to another.
  • Page 26 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • Service tags with bodies, such as cfmail and cfquery • Tags for defining and using components and functions: cfcomponent, cfinterface, cfimport, cffunction, cfproperty, cfargument. For more information, see “Defining components and functions in CFScript”...
  • Page 27 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language lock scope = "request" timeout = "30" type = "Exclusive" { request.number = 1; writeoutput("E-Turtleneck has now sold "& request.number &" turtlenecks!"); cftransaction To use the transaction operation you specify a begin action parameter. A transaction has the following general form: TRANSACTION action="begin"...
  • Page 28 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language THREAD name="text" [action="run"] [priority="priorityValue" application-specific attributes] { thread code The code in the thread operation body executes in a single ColdFusion thread. Code outside the body is not part of the thread. You can use the following methods to manage the thread: •...
  • Page 29 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Execute one or more actions on the object. Note: Unlike the corresponding tags, you cannot use application-specific parameters in these functions. You can only use the parameters that ColdFusion supports directly. Step 1: Instantiate a service object To create a function object, such as a mail object, use the operator or function, as in the...
  • Page 30 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language mailObj.addparam(file="#ExpandPath('test.txt')#"); mailObj.addPart(name="foo",type="html",charset="utf-8", body="This is a test message."); You can also clear child tag settings by calling the following functions. • httpObj.clearParams • mailObj.clearParams • mailObj.clearParts • pdfObj.clearParams • queryObj.clearParams • storedProcObj.clearParams • storedProcObj.clearProcResults If you used multiple add methods on an object, the clear method clears all values set in all the methods.
  • Page 31 The CFML Programming Language <!---mail and ftp service ---> <cfscript> m = new mail(); <!---mail service ---> m.setTo("x@adobe.com"); <!---set attribute using implicit setter ---> m.setSubject("Hi"); m.setBody("test mail"); <!---users need to use 'body' to specify cfmail and cfmailpart content ---> m.addparam(file="#E xpandPath('test.txt')#");...
  • Page 32 ColdFusion to return a query object. Query service example <cfscript> qryObj = new createObject("component","com.adobe.coldfuison.query").init(); <!---r here is no longer the query recordset but a component ---> r = qryObj.execute(sql="select * from art", datasource="cfdocexamples",result="myresult",name="myquery"); <!---new way to access the data --->...
  • Page 33 Duck"}#", destination="#destfolder#pdfinfo.pdf", overwrite="yes"); pdfObj.write(source="myBook", destination="#destfolder#write1.pdf", version="1.4", overwrite="yes"); pdfObj.protect(source="MyPdfVar", password="adobe", permissions="none", newuserpassword="newuserpw", newownerpassword="newownerpw"); </cfscript> Storedproc example The following code shows sample usage of the storedproc service object. <cfscript> sp = new storedproc(); <!---add cfprocparam tags --->...
  • Page 34 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Returns any variables set by the procedure. INOUT Functions Functions typically manipulate data and return a result. You can also create user-defined functions (UDFs), sometimes referred to as custom functions. Functions have the following general form: functionName([argument1[, argument2]]...) Some functions, such as the function take no arguments.
  • Page 35 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Features of properties with setter and getter methods include the following: • Component properties you assign with the set method are in the Variables scope that is private to the CFC. You can get or reset the properties only by calling get or set methods.
  • Page 36 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • max: Maximum value if the validate is integer/numeric/ • minLength: Minimum length of the string if the validate is string • maxLength: Maximum length of the string if the validate is string •...
  • Page 37: Data Types

    DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Constants The value of a constant does not change during program execution. Constants are simple scalar values that you can use within expressions and functions, such as “Robert Trent Jones” and 123.45. Constants can be integers, real numbers, time and date values, Boolean values, or text strings.
  • Page 38: Flow Control

    DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Category Description and types Simple Represents one value. You can use simple data types directly in ColdFusion expressions. ColdFusion simple data types are: • strings A sequence of alphanumeric characters enclosed in single or double quotation marks, such as “This is a test.”...
  • Page 39 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language cfif, cfelseif, and cfelse , and tags provide if-then-else conditional processing, as follows: cfif cfelseif cfelse tag tests a condition and executes its body if the condition is True. cfif If the preceding ) test condition is False, the tag tests another condition and executes cfif...
  • Page 40 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfoutput query = "GetEmployees"> <cfswitch expression = #Department#> <cfcase value = "Sales"> #FirstName# #LastName# is in <b>Sales</b><br><br> </cfcase> <cfcase value = "Accounting"> #FirstName# #LastName# is in <b>Accounting</b><br><br> </cfcase> <cfcase value = "Administration"> #FirstName# #LastName# is in <b>Administration</b><br><br>...
  • Page 41 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset myArray = ArrayNew(1)> <!--- Use ArraySet to initialize the first ten elements to 123 ---> <cfset ArraySet(myArray, 1, 10, 123)> <cfset myArray[4] = "kumquats"> <cfset foundit = False> <cfset i = 0> <cfloop condition = "(NOT foundit) AND (i LT ArrayLen(myArray))">...
  • Page 42: Reserved Words

    DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Special characters The double-quotation marks ("), single-quotation mark ('), and number sign (#) characters have special meaning to ColdFusion. To include any of them in a string, double the character; for example, use ## to represent a single # character.
  • Page 43: Using Coldfusion Variables

    Using ColdFusion Variables Adobe ColdFusion variables are the most frequently used operands in ColdFusion expressions. Variable values can be set and reset, and can be passed as attributes to CFML tags. Variables can be passed as parameters to functions, and can replace most constants.
  • Page 44: Creating Variables

    DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • How to use variables correctly Creating variables You create most ColdFusion variables by assigning them values. (You must use the function to create ArrayNew arrays.) Most commonly, you create variables by using the tag.
  • Page 45 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Variable characteristics You can classify a variable using the following characteristics: • The data type of the variable value, which indicates the kind of information a variable represents, such as number, string, or date •...
  • Page 46 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language ColdFusion provides the following functions for identifying the data type of a variable: • IsArray • IsBinary • IsBoolean • IsImage • IsNumericDate • IsObject • IsPDFObject • IsQuery • IsSimpleValue • IsStruct •...
  • Page 47 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Real numbers Real numbers, numbers with a decimal part, are also known as floating point numbers. ColdFusion real numbers can range from approximately -10300 to approximately 10300. A real number can have up to 12 significant digits. As with integers, you can assign a variable a value with more digits, but the data is stored as a string.
  • Page 48 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language "This is a number sign ##" Lists ColdFusion includes functions that operate on lists, but it does not have a list data type. In ColdFusion, a list is just a string that consists of multiple entries separated by delimiter characters. The default delimiter for lists is the comma.
  • Page 49 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language When you do this, ColdFusion stores the information as a string. If you use a date-time function, ColdFusion stores the value as a date-time object, which is a separate simple data type. When possible, use date-time functions such as to specify dates and times, because these functions can prevent you from specifying the CreateDate CreateTime...
  • Page 50 Converts most simple data types to string data. It can convert numbers, date-time objects, and Boolean values. (It converts date-time objects to ODBC timestamp strings.) Adobe recommends that you use the CharsetEncode function to convert binary data to a string in new applications.
  • Page 51 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Arrays Arrays are a way of storing multiple values in a table-like format that can have one or more dimensions. You create arrays using a function or an assignment statement: • The ColdFusion function creates an array and specifies its initial dimensions.
  • Page 52 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language For example, the following line creates a new variable, myStructure2, that is a reference to the same structure as the myStructure variable: <cfset myStructure2=myStructure> When you change the contents of myStructure2, you also change the contents of myStructure. To copy the contents of a structure, use the ColdFusion function, which copies the contents of structures and other complex Duplicate...
  • Page 53 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Multiple references to an object When multiple variables reference a structure or query object, the object continues to exist as long as at least one reference to the object exists. The following example shows how this works: <cfscript>...
  • Page 54 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language ColdFusion behavior is less straightforward, however, when you use the query column references myQuery.Firstname and myQuery["Firstname"] without using an array index. The two reference formats produce different results. If you reference myQuery.Firstname, ColdFusion automatically converts it to the first row in the column. For example, the following lines print the word "ben": <cfset myCol = myQuery.Firstname >...
  • Page 55 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language If myVar is the name of a complex object, checks whether a is a complex object. If a or myVar.a is the name of a complex object, checks whether b is the name of a simple variable, and returns the value of b.
  • Page 56 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Creating variables with periods Avoid creating the names of variables (except for dot notation in structures) that include periods. However, ColdFusion provides mechanisms for handling cases where you must do so, for example, to maintain compatibility with names of variables in external data sources or to integrate your application with existing code that uses periods in variable names.
  • Page 57 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language ColdFusion processes expressions and functions in the following sequence: For each operator in an expression, it determines the required operands. (For example, the multiplication operator requires numeric operands and the CONTAINS operator requires string operands.) For functions, it determines the type required for each function argument.
  • Page 58 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The cfoutput tag tag always displays data as a string. As a result, when you display a variable using the tag, cfoutput cfoutput ColdFusion applies the type conversion rules to any non-string data before displaying it. For example, the cfoutput tag displays a date-time value as an ODBC timestamp.
  • Page 59 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Comparing variables to True or False You might expect the following two tag examples to produce the same results: cfif <cfif myVariable> <cfoutput>myVariable equals #myVariable# and is True </cfoutput> </cfif> <cfif myVariable IS True> <cfoutput>myVariable equals #myVariable# and is True </cfoutput>...
  • Page 60 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language You can also use the function to determine whether a string can be interpreted as a date-time value, or to add IsDate characters to a string before comparison to avoid incorrect interpretation. Date-time functions and queries when ODBC is not supported Many CFML functions, including the , and...
  • Page 61 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Example 1 2 * True + "YES" - ('y' & "es") Result value as string: "2" Explanation: (2*True) is equal to 2; ("YES"- "yes") is equal to 0; 2 + 0 equals 2. Example 2 "Five is "...
  • Page 62 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Scope Description Client Contains variables that are associated with one client. Client variables let you maintain state as a user moves from page to page in an application, and are available across browser sessions. By default, Client variables are stored in the system registry, but you can store them in a cookie or a database.
  • Page 63 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Scope Description thread local Variables that are available only within a ColdFusion thread. For more information, see “Using ColdFusion Threads” on page 328. Contains parameters passed to the current page in the URL that is used to call it. The parameters are appended to the URL in the format ?variablename = value[&variablename=value...];...
  • Page 64 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Scope prefix Prefix required to Where available Created by reference (type) Flash A ColdFusion page or ColdFusion component The ColdFusion Client access. You assign a value called by a Flash client. to Flash.You can assign values to the Flash.result and Flash.pagesize variables.
  • Page 65 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Scope prefix Prefix required to Where available Created by reference (type) thread-local (no none Within a thread created by the cfthread Using no prefix when you create the variable. prefix) You can also use the keyword var before the variable name.
  • Page 66 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The Java Response interface method and C++ method return data to the setVariable CCFX::SetVariable Variables scope of the calling page. Therefore, they are equivalent to setting a Caller scope variable in a custom ColdFusion tag.
  • Page 67 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language To test whether an element exists in an array before you display its value, use a format such as the following: </cfoutput> <cfloop index="i" from="1" to="#Arraylen(myArray)#"> <cfif ArrayIsDefined(myArray, i)> #i#: #myArray[i]#<br> </cfif> </cfloop>...
  • Page 68: Validating Data

    DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language For example, the following tags indicate that this page expects two form variables named StartRow and cfparam RowsToFetch: <cfparam name="Form.StartRow"> <cfparam name="Form.RowsToFetch"> If the page with these tags is called without either one of the form variables, an error occurs and the page stops processing.
  • Page 69: Using Expressions And Number Signs

    Using Expressions and Number Signs In CFML, you create expressions by using number signs to indicate expressions in Adobe ColdFusion tags such as , in strings, and in expressions. You also use variables in variable names and strings to create dynamic cfoutput expressions, and dynamic variables.
  • Page 70 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Operator types ColdFusion has Five types of operators: • Arithmetic • Boolean • Decision (or comparison) • String • Ternary Functions also can be viewed as operators because they act on operands. Arithmetic operators The following table describes the arithmetic operators: Operator...
  • Page 71 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Operator Description Reverse the value of an argument. For example, NOT True is False and the inverse. or ! Return True if both arguments are True; return False otherwise. For example, True AND True is True, but True AND False is False.
  • Page 72 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Note: In CFScript expressions only, you can also use the following decision operators. You cannot use them in expressions in tags. == (EQ), != (NEQ), > (GT), < (LT), >= (GTE), and <= (LTE). Decision operator rules The following rules apply to decision operators: •...
  • Page 73 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The parentheses can contain any expression that evaluates to a Boolean value, and can be any valid expression. You can nest this operator inside other expressions. Operator precedence and evaluation ordering The order of precedence controls the order in which operators in an expression are evaluated. The order of precedence is as follows.
  • Page 74 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language All functions return values. In the following example, the tag sets a variable to the value returned by the cfset function: <cfset myDate = DateFormat(Now(), "mmmm d, yyyy")> You can use the values returned by functions directly to create more complex expressions, as in the following example: Abs(Myvar)/Round(3.14159) For more information on how to insert functions in expressions, see “Using number...
  • Page 75 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language //The following line is valid. var a = var b = c = d*5 //The following line is not valid. // a = b = var c = d*5 Using number signs Number signs (#) have a special meaning in CFML.
  • Page 76 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Note: You do not need to use number signs when you use the cfset tag to assign one variable’s value to another value. For example, the following tag assigns the value of the variable to the new variable, oldVar newVar...
  • Page 77 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset TheString = "Hello, FirstName!"> <cfset TheString = "Hello, " & "First" & "Name!"> As with the statement, two expressions can be adjacent to each other in strings, as in the following example: cfoutput <cfset TheString = "Monk is #Left("Moon", 2)##Mid("Monkey", 3, 2)#">...
  • Page 78 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language About dynamic variables Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. For example, the following example dynamically constructs the variable name from a variable prefix and a static suffix: <cfset "#flavor#_availability"...
  • Page 79 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language This does not mean that you must always avoid dynamic evaluation. However, given the substantial performance costs of dynamic evaluation, first ensure that one of the following techniques cannot serve your purpose: •...
  • Page 80 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Using dynamic evaluation Dynamic evaluation and dynamic expressions have several features and consideratons. ColdFusion dynamic evaluation functions The following table describes the functions that perform dynamic evaluation and are useful in evaluating dynamic expressions: Function Purpose...
  • Page 81 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The following example shows the function and how it works with ColdFusion variable processing: Evaluate <cfset myVar2="myVar"> <cfset myVar="27/9"> <cfoutput> #myVar2#<br> #myVar#<br> #Evaluate("myVar2")#<br> #Evaluate("myVar")#<br> #Evaluate(myVar2)#<br> #Evaluate(myVar)#<br> </cfoutput> Reviewing the code The following table describes how ColdFusion processes this code: Code Description <cfset myVar2="myVar">...
  • Page 82 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Example 1 You might be inclined to use the function in code such as the following: Evaluate <cfoutput>1 + 1 is #Evaluate(1 + 1)#</cfoutput> Although this code works, it is not as efficient as the following code: <cfset Result = 1 + 1>...
  • Page 83 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language SetVariable function considerations You can avoid using the function by using a format such as the following to set a dynamically named SetVariable variable. For example, the following lines are equivalent: <cfset SetVariable("myVar" & i, myVal)> <cfset "myVar#i#"...
  • Page 84 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfoutput> <table border="1" cellpadding="3"> <cfloop index="i" from="1" to="10"> <cfif i mod 2 EQ 0> <cfset Color = "white"> <cfelse> <cfset Color = "gray"> </cfif> <tr bgcolor="#color#"> <td> hello #i# </td> </tr> </cfloop> </table>...
  • Page 85 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language When you are ready to order, click submit.<br> <br> <cfform name="ShoppingCart" action="ShoppingCartAction.cfm" method="post"> <table> <tr> <td>Order?</td> <td>Product</td> <td>Code</td> <td>Quantity</td> </tr> <cfloop index="i" from="1" to="#cartItems#"> <tr> <cfset productName= "product_" & Cart[i].ID> <cfset skuName= "sku_" & Cart[i].ID> <cfset qtyname= "qty_"...
  • Page 86 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Code Description <cfscript> Create a shopping cart as an array of structures, with each structure CartItems=4; containing the cart item ID, product name, SKU number, and quantity Cart = ArrayNew(1); ordered for one item in the cart. Populate the shopping cart by for ( i=1;...
  • Page 87: Using Arrays And Structures

    Adobe ColdFusion supports dynamic multidimensional arrays. Using arrays can enhance your ColdFusion application code. Adobe ColdFusion also supports structures for managing lists of key-value pairs. Because structures can contain other structures or complex data types as it values, they provide a flexible and powerful tool for managing complex data.
  • Page 88 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language About arrays Traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions. In ColdFusion, you typically use arrays to temporarily store data. For example, if your site lets users order goods online, you can store their shopping cart contents in an array.
  • Page 89 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The following figure represents a ColdFusion 2D array: a[1][4] a[1][1] a[1][2] a[1][3] a[1] a[2][1] a[2][5] a[2] a[3][1] a[3][2] a[3] a[4][1] a[4][3] a[4] A ColdFusion 3D array is essentially three nested sets of 1D arrays. The differences between traditional and ColdFusion 3D arrays are similar, but much harder to show on a page.
  • Page 90 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Creating arrays using functions To create an array explicitly, you use the function and specify the array dimensions, as in the following arrayNew example: <cfset myNewArray=ArrayNew(2)> This line creates a two-dimensional array named myNewArray. You use this method to create an array with up to three dimensions.
  • Page 91 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset i="CP"> <cfset "#i#"=["Charlie","Parker"]> Creating complex multidimensional arrays ColdFusion supports dynamic multidimensional arrays. When you declare an array with the function, you ArrayNew specify the number of dimensions. You can create an asymmetrical array or increase the number of dimensions by nesting arrays as array elements.
  • Page 92 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Code Description <cfset biggestarray=ArrayNew(3)> Create a second 3D array. Make the [3][1][1] element of this <cfset biggestarray[3][1][1]=biggerarray> array a copy of the biggerarray array, and assign element <cfset biggestarray[3][1][1][2][3][1]="This is complex"> [3][1][1][2][3][1]. The resulting array is complex and asymmetric.
  • Page 93 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Adding an array element with a function You can use the following array functions to add data to an array: Function Description ArrayAppend Creates an array element at the end of the array. ArrayPrepend Creates an array element at the beginning of the array.
  • Page 94 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Copying arrays You can copy arrays of simple variables (numbers, strings, Boolean values, and date-time values) by assigning the original array to a new variable name. You do not have to use to create the array first.
  • Page 95 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • Populating an array with the cfloop • Populating an array from a query Populating an array with the ArraySet function You can use the function to populate a 1D array, or one dimension of a multidimensional array, with some ArraySet initial value, such as an empty string or zero.
  • Page 96 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset my2darray=arraynew(2)> <cfloop index="loopcount" from=1 to=12> <cfloop index="loopcount2" from=1 to=2> <cfset my2darray[loopcount][loopcount2]=(loopcount * loopcount2)> </cfloop> </cfloop> <p>The values in my2darray are currently:</p> <cfloop index="OuterCounter" from="1" to="#ArrayLen(my2darray)#"> <cfloop index="InnerCounter" from="1"to="#ArrayLen(my2darray[OuterCounter])#"> <cfoutput> <b>[#OuterCounter#][#InnerCounter#]</b>: #my2darray[OuterCounter][InnerCounter]#<br> </cfoutput>...
  • Page 97 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <!--- Do the query ---> <cfquery name="test" datasource="cfdocexamples"> SELECT Emp_ID, LastName, FirstName, Email FROM Employees </cfquery> <!--- Declare the array ---> <cfset myarray=arraynew(2)> <!--- Populate the array row by row ---> <cfloop query="test"> <cfset myarray[CurrentRow][1]=Emp_ID>...
  • Page 98 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Function Description ArraySet Sets the elements in a 1D array in a specified range to a specified value. Returns the specified array with elements sorted numerically or alphanumerically. ArraySort ArraySum Returns the sum of values in the specified array. Swaps array values in the specified indexes.
  • Page 99 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Notation Description Object.property You can reference a property, prop, of an object, obj, as obj.prop. This notation, also called dot notation, is useful for simple assignments, as in this example: depts.John="Sales" Use this notation only when you know the property names (keys) in advance and they are strings, with no special characters, numbers, or spaces.
  • Page 100 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset myArray=ArrayNew(1)> <cfset myArray[1]="2"> <cfset myArray[2]="3"> <cfset myStruct2=StructNew()> <cfset myStruct2.struct2key1="4"> <cfset myStruct2.struct2key2="5"> <cfset myStruct=StructNew()> <cfset myStruct.key1="1"> <cfset myStruct.key2=myArray> <cfset myStruct.key3=myStruct2> <cfdump var=#myStruct#><br> <cfset key1Var="key1"> <cfset key2Var="key2"> <cfset key3Var="key3"> <cfset var2="2"> <cfoutput> Value of the first key<br> #mystruct.key1#<br>...
  • Page 101 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Code Description <cfoutput> Output the value of the key1 (string) entry using the following Value of the first key<br> notation: #mystruct.key1#<br> #mystruct["key1"]#<br> • object.property notation #mystruct[key1Var]#<br> <br> • associative array notation with a constant •...
  • Page 102 You can also create a structure by assigning data to a variable. For example, each of the following lines creates a structure named with one element, , that has the value Adobe Systems Incorporated. myStruct name <cfset coInfo.name = "Adobe Systems Incorporated">...
  • Page 103 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset departments=structnew()> <cfset departments.John = "Sales"> <cfoutput> Before the first change, John was in the #departments.John# Department<br> </cfoutput> <cfset Departments.John = "Marketing"> <cfoutput> After the first change, John is in the #departments.John# Department<br> </cfoutput>...
  • Page 104 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfloop query="GetEmployees"> <cfif StructKeyExists(myStruct, LastName)> <cfoutput>#LastName#: #mystruct[LastName]#</cfoutput><br> </cfif> </cfloop> If the name of the key is known in advance, you can also use the ColdFusion function, as follows: IsDefined IsDefined("structure_name.key")> However, if the key is dynamic, or contains special characters, use the function.
  • Page 105 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Create a structure<br> <cfset myNewStructure=StructNew()> <cfset myNewStructure.key1="1"> <cfset myNewStructure.key2="2"> <cfset myArray=ArrayNew(1)> <cfset myArray[1]="3"> <cfset myArray[2]="4"> <cfset myNewStructure.key3=myArray> <cfset myNewStructure2=StructNew()> <cfset myNewStructure2.Struct2key1="5"> <cfset myNewStructure2.Struct2key2="6"> <cfset myNewStructure.key4=myNewStructure2> <cfdump var=#myNewStructure#><br> <br> A StructCopy copied structure<br> <cfset CopiedStruct=StructCopy(myNewStructure)>...
  • Page 106 If you use to delete a structure that has multiple references, the function deletes the contents of the StructClear structure and all references point to the empty structure, as the following example shows: <cfset myStruct.Key1="Adobe"> Structure before StructClear<br> <cfdump var="#myStruct#"> <cfset myCopy=myStruct>...
  • Page 107 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <!--- Create a structure and set its contents. ---> <cfset departments=structnew()> <cfset val=StructInsert(departments, "John", "Sales")> <cfset val=StructInsert(departments, "Tom", "Finance")> <cfset val=StructInsert(departments, "Mike", "Education")> <!--- Build a table to display the contents ---> <cfoutput>...
  • Page 108 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfelse> <cfoutput> <cfscript> employee=StructNew(); employee.firstname = Form.firstname; employee.lastname = Form.lastname; employee.email = Form.email; employee.phone = Form.phone; employee.department = Form.department; </cfscript> <!--- Display results of creating the structure. ---> First name is #StructFind(employee, "firstname")#<br> Last name is #StructFind(employee, "lastname")#<br>...
  • Page 109 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Code Description <cfparam name="Form.firstname" default=""> Set default values of all form fields so that they exist the first <cfparam name="Form.lastname" default=""> time this page is displayed and can be tested. <cfparam name="Form.email" default=""> <cfparam name="Form.phone"...
  • Page 110 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfif StructIsEmpty(attributes.empinfo)> <cfoutput> Error. No employee data was passed.<br> </cfoutput> <cfexit method="ExitTag"> <cfelse> <!--- Add the employee ---> <cfquery name="AddEmployee" datasource="cfdocexamples"> INSERT INTO Employees (FirstName, LastName, Email, Phone, Department) VALUES ( '#attributes.empinfo.firstname#' , '#attributes.empinfo.lastname#' , '#attributes.empinfo.email#' , '#attributes.empinfo.phone#' ,...
  • Page 111: Extending Coldfusion Pages With Cfml Scripting

    Extending ColdFusion Pages with CFML Scripting Adobe ColdFusion offers a server-side scripting language, CFScript, that provides ColdFusion functionality in script syntax. This JavaScript-like language gives developers the same control flow as ColdFusion, but without tags. You can also use CFScript to write user-defined functions that you can use anywhere that a ColdFusion expression is allowed.
  • Page 112 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language CFScript provides a compact and efficient way to write ColdFusion logic. Typical uses of CFScript include the following: • Simplifying and speeding variable setting • Building compact JavaScript-like flow control structures • Creating user-defined functions Because you use functions and expressions directly in CFScript, you do not have to surround each assignment or function in a tag.
  • Page 113 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Using CFScript <cfscript> if (IsDefined("Form.submit")) { if ((Form.lastname NEQ "") AND (Form.department NEQ "")) { employee=StructNew(); employee.firstname=Form.firstname; employee.lastname=Form.lastname; employee.email=Form.email; employee.phone=Form.phone; employee.department=Form.department; WriteOutput("Adding #Form.firstname# #Form.lastname# <br>"); else WriteOutput("You must enter a Last Name and Department.<br>"); </cfscript>...
  • Page 114 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Equivalent in CFScript cfthrow throw trace cftrace cftransaction transaction Script Functions added in ColdFusion 9 The following table has the list of script functions introduced in ColdFusion 9. Function Equivalent ColdFusion Tag cfftp http cfhttp...
  • Page 115 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language CFScript equivalent cfdirectory The directory functions DirectoryCreate DirectoryDelete DirectoryList , and DirectoryRename Only for <Cfdirectory action=list/> writedump cfdump cfelse else cfelseif elseif cfexit exit cffile The file functions FileDelete FileSeek FileSkipBytes , and FileWriteLine finally cffinally...
  • Page 116 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language CFScript equivalent cfthread thread throw cfthrow cftrace trace transaction cftransaction cftry Example The following example loops through a query in CFScript: <cfscript> // Loop through the qGetEmails RecordSet for (x = 1; x <= qGetEmails.RecordCount; x=x+1) { This_id = qGetEmails.Emails_id[x];...
  • Page 117 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfscript> a = 2; </cfscript> Variables CFScript variables can be of any ColdFusion type, such as numbers, strings, arrays, queries, and objects. The CFScript code can read and write any variables that are available in the page that contains the script. These variables include all shared scopes, such as session, application, and server variables.
  • Page 118 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language if(score GT 0) result = "positive"; Positives = Positives + 1; In this example, both assignment statements are executed if the score is greater than 0. If they were not in the code block, only the first line would execute.
  • Page 119 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • All statements end with a semicolon, and line breaks in the code are ignored. • Assignments are statements, not expressions, and therefore cannot be used in situations that require evaluating the assignment operation.
  • Page 120 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language if(score GT 1) result = "positive"; else result = "negative"; CFScript does not include an elseif statement. However, you can use an statement immediately after an else statement to create the equivalent of a tag, as the following example shows: cfelseif if(score GT 1)
  • Page 121 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • The statement does not have to follow all statements, but it is good programming practice to do so. default case If any statements follow the statement, you must end the block code with a case default default...
  • Page 122 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • Empty Note: The test expression is re-evaluated before each repeat of the loop. If code inside the loop changes any part of the test expression, it can affect the number of iterations in the loop. The statement can be a single semicolon terminated statement or a statement block in curly brackets.
  • Page 123 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The example also shows two issues with index arithmetic: in this form of loop you must make sure to initialize the index, and keep track of where the index is incremented. In this case, because the index is incremented at the top of the loop, initialize it to 0 so it becomes 1 in the first loop.
  • Page 124 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Because the loop index increment follows the array value assignment, the example initializes the loop variable to 1 and tests to make sure that it is less than or equal to 10. The following example generates the same results as the previous two examples, but it increments the index before assigning the array value.
  • Page 125 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • The statement exits the current loop or statement. break case Using continue statement ends the current loop iteration, skips any code following it in the loop, and jumps to the continue beginning of the next loop iteration.
  • Page 126 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Example public String foo(array a) for(var item in a) writedump(item); var declaration within for loop Note: This feature applies only if you have installed ColdFusion 9 Update 1. You can use inline with for-in construct to bind variable to the local scope for both structs and arrays. Example public String foo(struct s) for(var item in s)
  • Page 127 In this case, cfscript the component keyword can be preceded only by comments (including metadata assignments) and import operators. Adobe recommends this format as a best practice. You specify component properties as follows: /*@default defaultValue * @attrib1Name attrib1Value * ...
  • Page 128 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language For example: public function funcname(required string argument1) Interface definitions follow the same pattern as components, with the same general rules and limitations that apply to the interfaces you define using cfinterface tags. The following simple code defines an interface with a single function that takes one string argument, with a default argument value of "Hello World!": interface { function method1(string arg1="Hello World!");...
  • Page 129 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language // this is a component *@hint "this is a hint for component" component displayname="My Component" { pageencoding "Cp1252" ; // The rest of the component definition goes here. Note: Currently, you cannot use CFScript to specify the suppresswhitespace processing directive. Accessing component metadata To access metadata of a component, function, parameter, or property, use the GetMetadata function.
  • Page 130 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language * custom metadata for a cfc defined using annotation as well as key-value pairs * @cfcMetadata1 "cfc metadata1" component cfcMetadata2 = "cfc metadata2" * custom metadata for a property defined using annotation as well as key-value pairs * @propMetadata1 "property metadata1"...
  • Page 131 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • writelog • location • trace You can call these functions by passing the argument as name=”value” pairs or positional notations. For positional notations, the sequence of arguments must be followed. The sequence of arguments for each construct is mentioned in the CFML Reference Guide.
  • Page 132: Handling Exceptions

    Component Cache button. To prevent ColdFusion from caching resolved component paths, clear the Component Cache option. Click the Clear Component Cache button to remove any resolved component paths from the cache. Note: In all cases, ColdFusion automatically imports the com.adobe.coldfusion.* name space for CFCs. You do not have to import this path explicitly.
  • Page 133 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language try { Code where exceptions will be caught catch(exceptionType exceptionVariable) { Code to handle exceptions of type exceptionType that occur in the try block catch(exceptionTypeN exceptionVariableN) { Code to handle exceptions of type exceptionTypeN that occur in the try block finally { Code that will execute whether there is an exception or not.
  • Page 134 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • functions WriteOutput • Switch statements The example uses CFScript without any other ColdFusion tags. It creates a structure of course applicants. This structure contains two arrays; the first has accepted students, the second has rejected students. The script also creates a structure with rejection reasons for some (but not all) rejected students.
  • Page 135 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language applicant=applicants.rejected[j]; WriteOutput(applicant & "<br>"); if (StructKeyExists(rejectCode,applicant)) { switch(rejectCode[applicant]) { case "score": WriteOutput("Reject reason: Score was too low.<br>"); break; case "late": WriteOutput("Reject reason: Application was late.<br>"); break; default: WriteOutput("Rejected with invalid reason code.<br>"); } //end switch } //end if else {...
  • Page 136: Using Regular Expressions In Functions

    Ends the for loop that handles each rejected applicant. Ends the CFScript. Using Regular Expressions in Functions Regular expressions let you perform string matching operations using Adobe ColdFusion functions; in particular. regular expressions work with the following functions: • REFind •...
  • Page 137 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The next example uses a regular expression to perform the same search. This example searches for the first occurrence in the search string of any string pattern that consists entirely of uppercase letters enclosed by spaces: <cfset IndexOfOccurrence=REFind("...
  • Page 138 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language <cfset IndexOfOccurrence=REFind(" [A-Z]+ ", "Some BIG string")> <!--- The value of IndexOfOccurrence is 5 ---> The literal characters of the regular expression consist of the space characters at the beginning and end of the regular expression.
  • Page 139 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The regular expression [T]* can match empty strings. It first matches the empty string before “H” in “Hello”. The “ALL” argument tells to replace all instances of an expression. The empty string before “e” is matched, and REReplace so on, until the empty string before “o”...
  • Page 140 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • java • Java • jAva • All other combinations of case Using subexpressions Parentheses group parts of regular expressions into subexpressions that you can treat as a single unit. For example, the regular expression "ha"...
  • Page 141 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Special Character Description If the caret is at the beginning of a regular expression, the matched string must be at the beginning of the string being searched. For example, the regular expression "^ColdFusion" matches the string "ColdFusion lets you use regular expressions"...
  • Page 142 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Special Character Description (?i) If at the beginning of a regular expression for REFind() , it specifies to perform a case-insensitive compare. For example, the following line would return an index of 1: #reFind("(?i)hi", "HI")# If you omit the (?i), the line would return an index of zero to signify that it did not find the regular expression.
  • Page 143 In character sets within regular expressions, you can include a character class. You enclose the character class inside brackets, as the following example shows: REReplace ("Adobe Web Site","[[:space:]]","*","ALL") This code replaces all the spaces with *, producing this string: Adobe*Web*Site You can combine character classes with other expressions within a character set.
  • Page 144 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language The following table shows the character classes that ColdFusion supports. Regular expressions using these classes match any Unicode character in the class, not just ASCII or ISO-8859 characters. Character class Matches :alpha: Any alphabetic character.
  • Page 145 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Using backreferences in replacement strings You can use backreferences in the replacement string of both the functions. For REReplace REReplaceNoCase example, to replace the first repeated word in a text string with a single word, use the following syntax: REReplace("There is is a cat in in the kitchen", "([A-Za-z ]+)\1","\1") This results in the sentence:...
  • Page 146 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Escaping special characters in replacement strings You use the backslash character, \, to escape backreference and case-conversion characters in replacement strings. For example, to include a literal "\u" in a replacement string, escape it, as in "\\u". Omitting subexpressions from backreferences By default, a set of parentheses will both group the subexpression and capture its matched text for later referral by backreferences.
  • Page 147 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Element one of the array contains the starting index in the search string of the string that matched the regular expression. Element one of the array contains length of the matched string. For this example, the index of the first "...
  • Page 148: Regular Expression Examples

    DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language For a full discussion of subexpression usage, see the sections on in the ColdFusion REFind REFindNoCase functions chapter in the CFML Reference. Specifying minimal matching The regular expression quantifiers ?, *, +, {min,} and {min,max} specify one or both of a minimum and maximum number of instances of a given expression to match.
  • Page 149 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language Expression Description A URL parameter value in a URL. [\?&]value= [A-Z]:(\\[A-Z0-9_]+)+ An uppercase DOS/Windows path in which (a) is not the root of a drive, and (b) has only letters, numbers, and underscores in its text. A ColdFusion variable with no qualifier.
  • Page 150 DEVELOPING COLDFUSION 9 APPLICATIONS The CFML Programming Language • In replacement strings, use \n instead of $n for backreference variables. ColdFusion escapes all $ in the replacement string. • You do not have to escape backslashes in replacement strings. ColdFusion escapes them, except in case conversion sequences or escaped versions (for example, \u or \\u).
  • Page 151: Chapter 5: Building Blocks Of Coldfusion Applications

    About CFML elements that you create Adobe ColdFusion provides you with several techniques and elements to create sections of code that you can use multiple times in an application. Many of the elements also let you extend the built-in capabilities of ColdFusion.
  • Page 152 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications The model of an included page is that it is part of your page; it just resides in a separate file. The tag cannot cfinclude pass parameters to the included page, but the included page has access to all the variables on the page that includes it. The following image shows this model: <html>...
  • Page 153 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <html> <head> <title>Test for Include</title> </head> <body> <cfinclude template="header.cfm"> </body> </html> Save the file as includeheader.cfm and view it in a browser. The header appears along with the logo. Recommended uses Consider using the tag in the following cases: cfinclude...
  • Page 154 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Consider using UDFs in the following circumstances: • You want to pass in arguments, process the results, and return a value. UDFs can return complex values, including structures that contain multiple simple values. •...
  • Page 155 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Using custom CFML tags Custom tags written in CFML behave like ColdFusion tags. They can do all of the following: • Take arguments. • Have tag bodies with beginning and ending tags. •...
  • Page 156 CFML-like design scheme for your code. You can easily distribute your custom tags and share tags with others. For example, the ColdFusion Developer Exchange includes a library of custom tags that perform a wide variety of often-complex jobs; see www.adobe.com/go/learn_cfu_exchange_en. Consider using CFML custom tags in the following circumstances: •...
  • Page 157: For More Information

    DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Recommended uses CFX tags provide one way of using C++ or Java code. However, you can also create Java classes and COM objects and access them using the tag. CFX tags, however, provide some built-in features that the tag does not have: cfobject cfobject...
  • Page 158: Writing And Calling User-Defined Functions

    Writing and Calling User-Defined Functions Creating custom functions for algorithms or procedures that you call frequently lets you organize and reuse the functions in your Adobe ColdFusion application pages. About user-defined functions You can create your own custom functions, known as user-defined functions, or UDFs. You then use them in your application pages the same way you use standard ColdFusion functions.
  • Page 159 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Determining where to create a user-defined function You can define a function in the following places: • In a ColdFusion component. If you organize your functions in ColdFusion components, you use the functions as described in “Using ColdFusion components”...
  • Page 160 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Function variable Description functionName The name of the function. You cannot use the name of a standard ColdFusion function or any name that starts with “cf”. You cannot use the same name for two different function definitions. Function names cannot include periods.
  • Page 161 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications About creating functions by using tags You use the tag to define a UDF in CFML. The tag syntax has the following features and cffunction cffunction limitations: • Developers who have a background in CFML or HTML, but no scripting or programming experience are more familiar with the syntax.
  • Page 162 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Attribute Description The function name. name returnType (Optional) The type of data that the function returns. The valid standard type names are: any, array, binary, Boolean, date, guid, numeric, query, string, struct, uuid, variableName, xml, and void. If you specify any other name, ColdFusion requires the argument to be a ColdFusion component with that name.
  • Page 163 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Using a CFML tag in a user-defined function The most important advantage of using the tag over defining a function in CFScript is that you can cffunction include CFML tags in the function. Thus, UDFs can encapsulate activities, such as database lookups, that require ColdFusion tags.
  • Page 164 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications You can call a UDF in two ways: • With unnamed, positional arguments, as you would call a built-in function • With named arguments, as you would use attributes in a tag You can use either technique for any function.
  • Page 165 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • Arrays As a result, any changes that you make in the function to these arguments do not affect the variable that was used to call the function, even if the calling code is on the same ColdFusion page as the function definition. ColdFusion passes queries, structures, and external objects such as COM objects into the function by reference.
  • Page 166 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications This solution is simple, but it is not always optimal: • This technique requires ColdFusion to copy the entire array twice, once when you call the function and once when the function returns. Doing so is inefficient for large arrays and can reduce performance, particularly if the function is called frequently.
  • Page 167 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications The contents of the Arguments scope The following rules apply to the Arguments scope and its contents: • The scope contains all the arguments passed into a function. • If you use to define the function, the scope always contains an entry “slot”...
  • Page 168 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • If you use a name to pass an optional argument that is not declared in the function definition, the array index of the argument is the sum of the following: •...
  • Page 169 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • If you do not name an optional argument in the function definition, but do use a name for it in the function call, use the name specified in the function call For example, if you have an unnamed optional argument and call the function using the name myOptArg for the argument, you can reference the argument as Arguments.myOptArg in the function body.
  • Page 170 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications In CFScript, you create function-only variables with the statement. Unlike other variables, you never prefix function-only variables with a scope name. Using function-only variables Make sure to use the statement in CFScript UDFs to declare all function-specific variables, such as loop indexes and temporary variables that are required only for the duration of the function call.
  • Page 171 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • Because ColdFusion passes structures, queries, and objects such as COM objects by reference, the argument name exists only while the function executes, but the underlying data persists after the function returns and can be accessed by using the variable name of the caller.
  • Page 172 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Code Description <cfform method="POST" action="#CGI.script_name#"> Creates a simple form requesting you to enter your name. <p>Enter your Name:&nbsp; Uses the script_name CGI variable to post to this page <input name="name" type="text" hspace="30" maxlength="30">...
  • Page 173 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfscript> function TotalInterest(principal, annualPercent, months, status) { Var years = 0; Var interestRate = 0; Var totalInterest = 0; principal = trim(principal); principal = REReplace(principal,"[\$,]","","ALL"); annualPercent = Replace(annualPercent,"%","","ALL"); if ((principal LE 0) OR (annualPercent LE 0) OR (months LE 0)) { Status.errorMsg = "All values must be greater than 0";...
  • Page 174 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfset status = StructNew()> <cfset myInterest = TotalInterest(Form.Principal, Form.AnnualPercent,Form.Months, status)> <cfif myInterest EQ -1> <cfoutput> ERROR: #status.errorMsg#<br> </cfoutput> <cfelse> <cfoutput> Loan amount: #Form.Principal#<br> Annual percentage rate: #Form.AnnualPercent#<br> Loan duration: #Form.Months# months<br> TOTAL INTEREST: #myInterest#<br>...
  • Page 175 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Handling exceptions in UDFs Use try/catch blocks to handle exceptions in a UDF under the same conditions that any other ColdFusion application uses try/catch blocks. These conditions are typically circumstances where the function uses an external resource, such as a Java, COM, or CORBA object, a database, or a file.
  • Page 176 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cftry> <cfset status = StructNew()> <cfset myInterest = TotalInterest(Form.Principal, Form.AnnualPercent, Form.Months, status)> <cfoutput> Loan amount: #Form.Principal#<br> Annual percentage rate: #Form.AnnualPercent#<br> Loan duration: #Form.Months# months<br> TOTAL INTEREST: #myInterest#<br> </cfoutput> <cfcatch type="InvalidData"> <cfoutput> #cfcatch.message#<br>...
  • Page 177 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Code Description function TotalInterest(principal, annualPercent, months) { Starts the function definition. TotalInterest Requires three variables: the principal amount, the annual percentage rate, and the loan duration in months. Var years = 0; Declares intermediate variables used in the function Var interestRate = 0;...
  • Page 178 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Using Application.cfm and function include files Consider the following techniques for making your functions available to your ColdFusion pages: • If you consistently call a small number of UDFs, consider putting their definitions on the Application.cfm page. •...
  • Page 179 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications This way you only include the functions once per request and they are available throughout the life of the request. For example, create a myFuncs.cfm page that defines your functions and assigns them to the Request scope using syntax such as the following: function MyFunc1(Argument1, Argument2) { Function definition goes here }...
  • Page 180 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfscript> function binop(operation, operand1, operand2) { return (operation(operand1, operand2)); } function sum(addend1, addend2) { return addend1 + addend2;} x = binop(sum, 3, 5); writeoutput(x); </cfscript> Handling query results using UDFs When you call a UDF in the body of a tag that has a attribute, such as a tag, any function argument that query...
  • Page 181 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Identifying and checking for UDFs You can use the function to determine whether a name represents a UDF. The IsCustomFunction function generates an error if its argument does not exist. As a result, ensure that the name exists IsCustomFunction before calling the function, for example, by calling the function.
  • Page 182: Building And Using Coldfusion Components

    A ColdFusion component (CFC) file contains data and functions that you define in related, multiple methods. You use CFC pages to organize related actions in one file, which provide can simplify your programming. For more information on creating applications that use CFCs, see the Adobe website: www.adobe.com. About ColdFusion components A ColdFusion component (CFC) is a file saved with the extension .cfc.
  • Page 183 Building Blocks of ColdFusion Applications CFCs support introspection; that is, they can provide information about themselves. If you display a component page directly in an HTML browser, inspect it in the ColdFusion and Adobe Dreamweaver CS3 component browsers, or use the CFML function, you see information about the component.
  • Page 184 Creating Flash Remoting elements Adobe® Flash® applications that use Flash Remoting can easily take advantage of ColdFusion components for business logic. In a CFC, the cffunction tag names the function and contains the application logic, and the cfreturn tag returns the result to Flash.
  • Page 185 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • You use the cffunction tag to define CFC methods. The CFScript statement can create simple methods, function but it does not provide options to control access to the method, provide metadata, specify a return type, or control generated output.
  • Page 186 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications For detailed reference information on the cffunction tag, see the CFML Reference. Defining CFCs with related methods When defining CFCs, it is good programming practice to organize related methods in one CFC. For example, you could place all methods that perform operations related to a user, such as , and addUser...
  • Page 187 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfscript> serverTime=now(); utcTime=GetTimeZoneInfo(); utcStruct=structNew(); utcStruct.Hour=DatePart("h", serverTime); utcStruct.Minute=DatePart("n", serverTime); utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet; utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet; if (utcStruct.Minute LT 10) utcStruct.Minute = "0" & utcStruct.Minute; </cfscript> In the example, the method definition calls the getUTCTime.cfm file with the cfinclude tag. The getUTCTime getUTCTime.cfm code calculates the UTC time representation of the current time and populates a structure with hour and minute values.
  • Page 188 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfcomponent displayname="shoppingCart"> <cffunction name="init" access="public" output="no" returntype="shoppingCart"> <cfargument name="shoppingCartID" type="UUID" required="yes"> <cfset variables.shoppingCartID = arguments.shoppingCartID> <cfreturn this> </cffunction> <!--- Additional methods go here. ---> </cfcomponent> In this example, the method uses the variables scope to make the shopping cart ID available anywhere in the init() CFC.
  • Page 189 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Code Description Defines the component. <cfcomponent> <cffunction name="ctof" output="false"> Defines the ctof method. Indicates that this method does not display output. Creates the parameter of the method. Indicates that it is required and <cfargument name="temp"...
  • Page 190 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfif #form.conversionType# is "CtoF"> <cfinvoke component="convertTemp" method="ctof" returnvariable="newtemp" temp=#form.temperature#> <cfoutput>#form.temperature# degrees Celsius is #newtemp# degrees Farenheit.</cfoutput> <cfelseif #form.conversionType# is "FtoC"> <cfinvoke component="convertTemp" method="ftoc" returnvariable="newtemp" temp=#form.temperature#> <cfoutput>#form.temperature# degrees Fahrenheit is #newtemp# degrees Celsius.</cfoutput>...
  • Page 191 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications To access the parameter values in the component method definition, use structure- or array-like notation with the Arguments scope. The following example refers to the argument as ; it could also lastName Arguments.lastname refer to it as...
  • Page 192 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications You can use either technique, or a combination of both, in your applications. The best technique to use depends on your application’s needs and your coding methodologies. For example, many CFC methods that perform business logic return the results as a variable, and many CFC methods that display output directly are designed as modular units for generating output, and do not do business logic.
  • Page 193 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications For information on displaying the information, see “Using introspection to get information about components” on page 205. The displayname and hint attributes The cfcomponent, cffunction, cfargument, and cfproperty tags have attributes. displayname hint attribute lets you provide a more descriptive name for a component, attribute, method, or property.
  • Page 194 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Saving and naming ColdFusion components The following table lists the locations in which you can save component files and how they can be accessed from each location: Form Flash Remoting Web services ColdFusion page Current directory Web root...
  • Page 195 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications You can create persistent CFCs by assigning the CFC instance to a persistent scope, such as the Session or Application scope. This way, you can create CFCs for objects, such as shopping carts or logged-in users, that must persist for sessions.
  • Page 196 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Invoking CFC methods with the cfinvoke tag The cfinvoke tag can invoke methods on a CFC instance or invoke CFC methods transiently. You can also use the tag to invoke CFC methods from within a CFC. cfinvoke Invoking methods of a CFC instance To invoke a component method of a CFC instance, use the...
  • Page 197 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Invoking component methods transiently In ColdFusion pages or components, the tag can invoke component methods without creating a persistent cfinvoke CFC instance. To invoke a component method transiently, use the tag and specify the following: cfinvoke •...
  • Page 198 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Invoking methods by using dynamic method names tag is the only way to efficiently invoke different component methods based on variable data (for cfinvoke example, form input). In this case, you use a variable name, such as Form.method, as the value of the attribute.
  • Page 199 To pass multiple parameters within a URL, use the ampersand character (&) to delimit the name-value pairs; for example: http://localhost:8500/corpQuerySecure.cfc?method=getAuth&store=women&dept=shoes Note: To ensure data security, Adobe strongly recommends that you not pass sensitive information over the web using URL strings. Potentially sensitive information includes all personal user information, including passwords, addresses, telephone numbers, and so on.
  • Page 200 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications If the CFC method that you invoke from the form displays output directly, the user’s browser shows the output. (You can use the cffunction tag attribute to disable displaying output.) If the CFC returns a result using the cfreturn output tag, ColdFusion converts the text to HTML edit format, places it in a WDDX packet, and includes the packet in the HTML that it returns to the client.
  • Page 201 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Specifying the CFC location When you instantiate or invoke a component, you can specify the component name only, or you can specify a qualified path. To specify a qualified path, separate the directory names with periods, not backslashes. For example, myApp.cfcs.myComponent specifies the component defined in myApp\cfcs\myComponent.cfc.
  • Page 202 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Passing parameters by using attribute format You can pass parameters in the tag as tag attribute name-value pairs, as the following example shows: cfinvoke <cfinvoke component="authQuery" method="getAuthSecure" lastName="#session.username#" pwd="#url.password#"> In the example, the parameters are passed as the attributes.
  • Page 203 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications You can pass the parameters in an structure. The following code is equivalent to the argumentCollection previous example: argsColl = structNew(); argsColl.username = "Almonzo"; argsColl.password = "LauRa123"; authorized = securityCFC.getAuth(argumentCollection = argsColl); You can pass positional parameters to a method by separating them with commas.
  • Page 204 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications The CFC Variables scope does not include any of the Variables scope variables that are declared or available in the page that instantiates or invokes the CFC. However, you can make the Variables scope of the page that invokes a CFC accessible to the CFC by passing Variables as an argument to the CFC method.
  • Page 205 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Before invoking the CFC, Variables.Myname is: Wilson. Passing Variables scope to hello method. It returns: Hello Wilson. After invoking the CFC, Variables.Myname is: Wilson. Within the VarScopeInCfc method, Variables.MyName is: Tuckerman The Arguments scope The Arguments scope exists only in a method, and is not available outside the method.
  • Page 206 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Using CFCs effectively Several techniques let you effectively use CFCs in your applications: • Structure and reuse code • Build secure CFCs • Use introspection to get information about components Structuring and reusing code Component inheritance and the Super keyword are two important tools for creating structured, object-oriented ColdFusion components.
  • Page 207 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Create the inherit.cfm file with the following content, and save it in the same directory as the components you created in the previous steps: <cfobject name="empObj" component="employee"> <cfobject name="mgrObj" component="manager"> <cfobject name="prezObj" component="president"> <cfoutput>...
  • Page 208 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Create the president.cfc file with the following content: <cfcomponent extends="manager"> <cffunction name="getPaid" returntype="numeric"> <cfset var salary=1.5 * Super.getPaid()> <cfreturn salary> </cffunction> </cfcomponent> Create the payday.cfm file with the following content, and save it in the same directory as the components that you created in the previous steps: <cfobject name="empObj"...
  • Page 209 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <!--- Create the component instance. ---> <cfobject component="appResources.components.tellTime2" name="tellTimeObj"> <!--- Invoke the methods. ---> <cfinvoke component="#tellTimeObj#" method="getLocalTime" returnvariable="localTime" > <cfinvoke component="#tellTimeObj#" method="getUTCTime" returnvariable="UTCTime" > <!--- Display the results. ---> <h3>Time Display Page</h3> <cfoutput>...
  • Page 210 Using introspection to get information about components ColdFusion provides several ways for you to get information about components: • Request a component page from the browser • Use the ColdFusion component browser • Use the Adobe® Dreamweaver® Components panel Last updated 1/20/2012...
  • Page 211 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • Use the function GetMetaData Development teams can use the information about components as up-to-date API reference information. Note: For information about how to include documentation in CFCs for display by using introspection, see “Documenting CFCs”...
  • Page 212 CFCs, these examples invoke the appropriate method in the CFC that appears in the following example. Although Adobe recommends using CFCs to create structured, reusable code, some code examples in this manual contain queries within a CFML page, rather than invoking a CFC, in order to clearly illustrate a particular element of ColdFusion.
  • Page 213: Creating And Using Custom Cfml Tags

    DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfquery name="deptquery" datasource="cfdocexamples"> SELECT Dept_ID, FirstName || ' ' || LastName AS FullName FROM Employee ORDER BY Dept_ID </cfquery> </cffunction> <cffunction name="employeebyURLID" access="public" output="false" returntype="query"> <cfset var GetRecordtoUpdate=""> <cfquery name="GetRecordtoUpdate" datasource="cfdocexamples"> SELECT * FROM Employee WHERE Emp_ID = #URL.Emp_ID# </cfquery>...
  • Page 214 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications When ColdFusion processes the page containing this tag, it could output the message: December 5, 1987 is Ted Cantor's Birthday. Please wish him well. A custom tag can also have a body and end tag, for example: <cf_happybirthdayMessge name="Ellen Smith"...
  • Page 215 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications • The cfusion\CustomTags directory • A subdirectory of the cfusion\CustomTags directory • A directory that you specify in the ColdFusion Administrator To share a custom tag among applications in multiple directories, place it in the cfusion\CustomTags directory. You can create subdirectories to organize custom tags.
  • Page 216 ColdFusion. Accessing existing custom tags Before creating a custom tag in CFML, review the free and commercial custom tags available on the Adobe developer’s exchange (www.adobe.com/go/learn_cfu_cfdevcenter_en).You might find a tag that does what you want. Tags are grouped in several broad categories and are downloadable as freeware, shareware, or commercial software.
  • Page 217 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cf_getmd Name=#NameYouEntered#> To pass multiple attributes to a custom tag, separate them with a space in the tag as follows: <cf_mytag Firstname="Thadeus" Lastname="Jones"> In the custom tag, you use the Attributes scope to access attributes passed to the tag. Therefore, in the getmd.cfm page, you access the passed attribute as .
  • Page 218 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Using tag attributes summary Custom tag attribute values are passed from the calling page to the custom tag page as name-value pairs. CFML custom tags support required and optional attributes. Custom tag attributes conform to the following CFML coding standards: •...
  • Page 219 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <html> <head> <title>Enter Name</title> </head> <body> <!--- Enter a name, which could also be done in a form. ---> <!--- This example simply uses a cfset. ---> <cfset NameYouEntered="Smith"> <!--- Display the current name. ---> <cfoutput>...
  • Page 220 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Code Description <cfset NameYouEntered="Smith"> In the calling page, create a variable and assign NameYouEntered it the value Smith <cfoutput> In the calling page, display the value of the NameYouEntered Before you leave this page, you're variable before calling the custom tag.
  • Page 221 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications ---custom tag ---<br> <cfoutput>#attributes.a# #attributes.x# #attributes.y# #attributes.foo#</cfoutput><br> --- end custom tag --- its output is the following statement: ---custom tag --- blab -X- -Y- 16 --- end custom tag --- One use for is to pass the entire Attributes scope of one custom tag to another.
  • Page 222 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Variable Description Contains the execution mode of the custom tag. Valid values are "start", "end", and "inactive". ExecutionMode HasEndTag Distinguishes between custom tags that are called with and without end tags. Used for code validation. If the user specifies an end tag, HasEndTag is set to...
  • Page 223 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Determining the tag execution mode The variable contains the mode of invocation of a custom tag page. The variable has one of thisTag.ExecutionMode the following values: Mode for processing the end tag. Start Mode for processing the end tag.
  • Page 224 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications You can access the body text within the custom tag using the variable. The variable thisTag.GeneratedContent contains all body text passed to the tag. You can modify this text during processing of the tag. The contents of the variables are returned to the browser as part of the tag’s output.
  • Page 225 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications The following example shows a tag nested within a tag: cftreeitem cftree <cftree name="tree1" required="Yes" hscroll="No"> <cftreeitem value=fullname query="engquery" queryasroot="Yes" img="folder,document"> </cftree> The calling tag is known as an ancestor, parent, or base tag; the tags that ancestor tags call are known as descendant, child, or sub tags.
  • Page 226 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications To preserve encapsulation, place all tag data access and modification operations in custom tags. For example, rather than documenting that the variable MyQueryResults in a tag's implementation holds a query result and expecting users to manipulate MyQueryResults directly, create a nested custom tag that manipulates MyQueryResult.
  • Page 227 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <!--- Get base tag instance data ---> <cfset data = getBaseTagData(baseTag)> <!--- Create a string with the attribute collection name ---> <cfset collection_Name = "data.#dataCollection#"> <!--- Create the attribute collection, if necessary ---> <cfif not isDefined(collectionName)>...
  • Page 228 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Create the first custom tag page Create a ColdFusion page with the following content: <cf_nesttag2> Save the page as nesttag1.cfm. Create the second custom tag page Create a ColdFusion page with the following content: <cfif thisTag.executionmode is 'start'>...
  • Page 229: Building Custom Cfxapi Tags

    DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications <cfoutput> I'm running in the context of a custom tag named #inCustomTag#.<p> </cfoutput> <!--- Get the tag instance data. ---> <cfset tagdata = getbasetagdata(incustomtag)> <!--- Find out the tag's execution mode. ---> I'm located inside the <cfif tagdata.thisTag.executionmode neq 'inactive'>...
  • Page 230 You can use a wide range of Java development environments, including the Java Development Kit (JDK) from Sun, to build Java CFX tags. You can download the JDK from Sun http://java.sun.com/j2se. Adobe recommends that you use one of the commercial Java IDEs, so you have an integrated environment for development, debugging, and project management.
  • Page 231 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications After you finish with development and testing, you can deploy your Java CFX tag anywhere on the classpath visible to ColdFusion. Customizing and configuring Java Use the ColdFusion Administrator > Server Settings > JVM and Java Settings page to customize your Java development environment by customizing the classpath and Java system properties, or by specifying an alternate JVM.
  • Page 232 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications You can now call the tag from a ColdFusion page. Call a CFX tag from a ColdFusion page Create a ColdFusion page (.cfm) in your editor with the following content to call the HelloColdFusion custom tag: <html>...
  • Page 233 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Method Description getIntAttribute Retrieves the value of the passed attribute as an integer. getQuery Retrieves the query that was passed to this tag, if any. getSetting Retrieves the value of a global custom tag setting. For detailed reference information on each of these interfaces, see the CFML Reference.
  • Page 234 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications ZipBrowser example The following example shows the use of the , and objects. The example uses the java.util.zip Request Response Query package to implement a Java CFX tag called , which is a ZIP file browsing tag. cfx_ZipBrowser Note: The Java source file that implements cfx_ZipBrowser, ZipBrowser.java, is included in the cf_root/cfx/java/distrib/examples (server configuration) or cf_webapp_root/WEB-...
  • Page 235 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications ZipInputStream zin = new ZipInputStream( new FileInputStream(strArchive) ) ; ZipEntry entry ; while ( ( entry = zin.getNextEntry()) != null ) { // Add a row to the results. int iRow = files.addRow() ; // populate the row with data files.setData( iRow, iName, entry.getName() ) ;...
  • Page 236 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Debugging in a Java IDE You can use a Java IDE to debug your Java CFX tags. As a result, you can develop your Java CFX tag and debug it in a single environment.
  • Page 237 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications import java.util.Hashtable ; import com.allaire.cfx.* ; public class OutputQuery implements CustomTag { // debugger testbed for OutputQuery public static void main(String[] argv) { try { // initialize attributes Hashtable attributes = new Hashtable() ; attributes.put( "HEADER", "Yes"...
  • Page 238 Select Build > Start Debug > AttachProcess. Select jrunsvc.exe. Adobe recommends that you shut down all other Java programs. Execute any ColdFusion page that calls the CFX tag. Select File > Open to open a file in VisualDev in which to set a breakpoint.
  • Page 239 DEVELOPING COLDFUSION 9 APPLICATIONS Building Blocks of ColdFusion Applications Registering CFX tags To use a CFX tag in your ColdFusion applications, first register it in the Extensions, CFX Tags page in the ColdFusion Administrator. In the ColdFusion Administrator, select Extensions > CFX Tags. Click Register C++ CFX.
  • Page 240: Chapter 6: Developing Cfml Applications

    Chapter 6: Developing CFML Applications Designing and Optimizing a ColdFusion Application Application elements and how you structure an application on your server make your Adobe ColdFusion pages an effective Internet application. You use the Application.cfc and Application.cfm files and various coding methods to optimize the efficiency of your application.
  • Page 241 239. Note: For one example of an application framework, see “ColdFusion Methodologies for Content Management,” available at www.adobe.com/go/learn_cfu_content_mgmt_en. Reusable application elements ColdFusion provides a variety of reusable elements that you use to provide commonly used functionality and extend CFML.
  • Page 242 Application.cfc” on page 241. Other application-level settings and functions Adobe recommends that when defining application-level settings, variables, and functions in new code, you do not use the techniques used previous to ColdFusion MX 7. Instead, use the Application.cfc file and its variables and methods, which provide more features and include logical, hierarchical structure.
  • Page 243 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications The Application.cfm page can define the application. It can contain the tag that specifies the cfapplication application name, and code on this page is processed for all pages in the application. This page can define application- level settings, functions, and features.
  • Page 244 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Application security and user identification All applications must ensure that malicious users cannot make improper use of their resources. Additionally, many applications require user identification, typically to control the portions of a site that the user accesses, to control the operations that the user performs, or to provide user-specific content.
  • Page 245 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • If you do not have an Application.cfc, but do have an Application.cfm page, ColdFusion looks for an OnRequestEnd.cfm in the same directory as the Application.cfm page ColdFusion uses for the current page. ColdFusion does not search beyond that directory, so it does not run an OnRequestEnd.cfm page that resides in another directory.
  • Page 246 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • In the example on the right, Bandwidth Associates uses the settings in individual Application.cfc files to create individual ColdFusion applications at the departmental level. Only the Products application pages are processed using the settings in the root Application.cfc file. The Consulting, Marketing, and Sales directories each have their own Application.cfc file.
  • Page 247 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Naming the application Define the application and give it a name by setting the This.name variable in the Application.cfc initialization section, before the method definitions. By using a specific application name, you define a set of pages as part of the same logical application.
  • Page 248 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Attribute showDebugOutput Specifies whether to show debugging output. This setting cannot enable debugging if it is disabled in the ColdFusion Administrator. However, this option ensures that debugging output is not displayed, even if the Administrator enables it. requestTimeout Specifies the page request time-out.
  • Page 249 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Method When run onRequestEnd All pages and CFCs in the request have been processed: equivalent to the OnRequestEnd.cfm page. onMissingTemplate When ColdFusion receives a request for a nonexistent page. onError When an exception occurs that is not caught by a try/catch block. When ColdFusion receives a request, it instantiates the Application CFC and runs the Application.cfc code in the following order: •...
  • Page 250 If your application requires utility functions that are used by multiple pages, not just by the methods in Application.cfc, and you do not use an method, Adobe recommends that you place them in a separate CFC and access them onRequest by running that CFC.
  • Page 251 For detailed information on security and creating logins, see “Securing Applications” on page 339 For an example that uses authentication code generated by the Adobe Dreamweaver CF Login Wizard, see onRequestStart in the CFML Reference. Last updated 1/20/2012...
  • Page 252 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using the onRequest method method differs from the method in one major way: the method onRequest onRequestStart onRequest intercepts the user’s request. This difference has two implications: • ColdFusion does not process the request unless you explicitly call it, for example, by using a tag.
  • Page 253 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cferror type="VALIDATION" template="validationerrorhandler.cfm"> • The ColdFusion default error mechanisms handle any errors that are not handled by the preceding techniques. These mechanisms include the site-wide error handler that you specify in the ColdFusion Administrator and the built-in default error pages.
  • Page 254 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfcomponent> <cfset This.name = "BugTestApplication"> <cffunction name="onError"> <!--- The onError method gets two arguments: An exception structure, which is identical to a cfcatch variable. The name of the Application.cfc method, if any, in which the error happened.
  • Page 255 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfcomponent> <cfset This.name = "TestApplication"> <cfset This.Sessionmanagement=true> <cfset This.Sessiontimeout="#createtimespan(0,0,10,0)#"> <cfset This.applicationtimeout="#createtimespan(5,0,0,0)#"> <cffunction name="onApplicationStart"> <cftry> <!--- Test whether the DB that this application uses is accessible by selecting some data. ---> <cfquery name="testDB" dataSource="cfdocexamples" maxrows="2"> SELECT Emp_ID FROM employee </cfquery>...
  • Page 256 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications </cfscript> </cffunction> <cffunction name="onRequest"> <cfargument name = "targetPage" type="String" required=true/> <cfsavecontent variable="content"> <cfinclude template=#Arguments.targetPage#> </cfsavecontent> <!--- This is a minimal example of an onRequest filter. ---> <cfoutput> #replace(content, "report", "MyCompany Quarterly Report", "all")# </cfoutput>...
  • Page 257 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- Some exceptions, including server-side validation errors, do not generate a rootcause structure. ---> <cfif isdefined("exception.rootcause")> <cflog file="#This.Name#" type="error" text="Root Cause Message: #exception.rootcause.message#"> </cfif> <!--- Display an error message if there is a page context. ---> <cfif NOT (Arguments.EventName IS onSessionEnd) OR (Arguments.EventName IS onApplicationEnd)>...
  • Page 258 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Naming the application Use the tag to specify the application name and define a set of pages as part of the same logical cfapplication application. Although you can create an application by placing a tag with the application name on cfapplication each page, you normally place the tag in the Application.cfm file;...
  • Page 259 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Handling errors Use the tag on your Application.cfm page to specify application-specific error-handling pages for request, cferror validation, or exception errors, as shown in the following example. This way you include application-specific information, such as contact information or application or version identifiers, in the error message, and you display all error messages in the application in a consistent manner.
  • Page 260 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications </cfif> </cflock> </cfif> <!--- Set a Session variable.---> <cflock timeout="20" scope="Session" type="exclusive"> <cfif not IsDefined("session.pagesHit")> <cfset session.pagesHit=1> <cfelse> <cfset session.pagesHit=session.pagesHit+1> </cfif> </cflock> <!--- Set Application-specific Variables scope variables. ---> <cfset mainpage = "default.cfm"> <cfset current_page = "#cgi.path_info#?#cgi.query_string#">...
  • Page 261 For information on debugging techniques that help you identify slow pages, see “Debugging and Troubleshooting Applications” on page 378. For additional information on optimizing ColdFusion, see the Adobe ColdFusion support center at www.adobe.com/go/learn_cfu_support_en. Caching ColdFusion pages that change infrequently Some ColdFusion pages produce output that changes infrequently. For example, if you have an application that extracts a vendor list from a database or produces a quarterly results summary.
  • Page 262 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Place the tag before any code on your page that generates output, typically at the top of the page body. For cfcache example, the following tag tells ColdFusion to cache the page on both the client and the server. On the server, the page is cached in the e:/temp/page_cache directory.
  • Page 263 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- Greet the us er. ---> <cf output> W elcome to our home page.<br> The time is #TimeFormat(Now())#.<br> Your lucky number is: #RandRa nge(1,1000)#<br> <hr> </cfoutput> <!--- If the flag is false, query the DB, and save an image of the results output to a variable.
  • Page 264 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfscript> this.name ="Object Operations"; this.s3.accessKeyId = "key_ID"; this.s3.awsSecretKey = "secret_key"; this.s3.defaultLocation="location"; </cfscript> For example, <cffile action="write" output="S3 Specification" file="s3://testbucket/sample.txt"/> • s3://accessKeyId:awsSecretKey@bucket/x/y/sample.txt • This format has the specified in it. accessKeyID awsSecretKey • acts as the token to indicate the end of authentication information. Note: If you have specified the in both the URL and Application.cfc, then value accessKeyID...
  • Page 265 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Operation Tag used Function Example Create <cfdirectory action="create" directory="s3://bucket1"/> cfdirectory DirectoryC action="create" reate attribute can directory only take the path of the bucket. Any additional path results in an error. All other attributes are ignored.
  • Page 266 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications The following are the supported functions: • FileIsEOF • FileReadBinary • Filecopy • FileReadLine • FileExists • FileWriteln • FileOpen • FileClose • FileRead • FileDelete New attributes in cfdirectory action="create" tag Attribute Added Description Example Used to change the location of the created bucket.
  • Page 267 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications ACLObject is an array of struct where each struct represents an ACL grant. The grantee details are as follows: ACLObject Must have the keys (with value , or ) and group Group authenticated log_delivery permission Must have the keys...
  • Page 268 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Example <cftry> <cfset dir = "s3://bucket_name"> <cfif !directoryExists(dir)> <cfset directorycreate(dir)> </cfif> <cfset perm = structnew()> <cfset perm.group = "all"> <cfset perm.permission = "read"> <cfset perm1 = structnew()> <cfset perm1.email = "email ID"> <cfset perm1.permission = "FULL_CONTROL"> <cfset myarrray = arrayNew(1)>...
  • Page 269 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Example <cftry> <cfset dir = "s3://bucket_name/"> <cfset perm = structnew()> <cfset perm.group = "authenticated"> <cfset perm.permission = "READ"> <cfset perm1 = structnew()> <cfset perm1.email = "email_ID"> <cfset perm1.permission = "READ_ACP"> <cfset myarrray = [perm,perm1]> <cfif NOT DirectoryExists(dir)>...
  • Page 270 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using metadata Amazon S3 allows you to specify metadata for both objects and buckets. The following two functions let you get and set the metadata on objects or buckets. StoreGetMetadata Description Returns the metadata related to the object or bucket. Returns Object metadata or bucket metadata Syntax...
  • Page 271 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications History ColdFusion 9 Update 1: Added this function Example <cfscript> mydate = #Now()#; hello = structNew(); hello.color = "grey"; /cfscript> <cfset dir = "s3://mycfbucket"> <cffile action="write" file="#dir#/hello5.txt" output="Sample s3 text"> <cfset StoreSetMetadata("#dir#/hello5.txt","#hello#")> <cfset test = StoreGetMetadata("#dir#/hello5.txt")> <cfdump var="#test#">...
  • Page 272 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications directoryExists directoryList imageNew imageRead imageWrite imageWriteBase64 isImageFile isPDFFile Supported tags cffile actions cfdirectory actions cfdocument cffeed (except rename) cfftp cfimage cfloop cfimage actions Limitations • The following tags are not supported: • cfpdf •...
  • Page 273 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Example The following code describes how to write an image as an in-memory file: <cffile action="readBinary" variable="myImage" file="#ExpandPath('./')#/blue.jpg"> <cffile action="write" output="#myImage#" file="ram:///a.jpg"> <cfif FileExists("ram:///a.jpg")> <cfoutput>a.jpg exists</cfoutput> <cfelse> <cfoutput>a.jpg Doesn't exists</cfoutput> </cfif> Writing and instantiating dynamic CFC files The following syntax explains how you can write CFC code in to an in-memory file: <cffile action="write"...
  • Page 274 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Supported functions The following file functions are supported for in-memory files: • FileIsEOF • FileReadBinary • Filemove • Filecopy • FileReadLine • FileExists • FileOpen • FileWriteln • FileClose • FileRead • FileDelete •...
  • Page 275: File Operations

    DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications File operations The following file operations are supported for in-memory files: • Directory-specific operations: create, delete, list, and rename. • File-specific operations: copy, create, write, append, delete, rename, create attributes, modes move, and read. Example The following code illustrates the file and directory operations: <cfdirectory action = "create"...
  • Page 276 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • cfpresentation • cfprint • cfreport • cfzip Example using the tag cfcontent <cfcontent file="ram:///a.jpg" type="image/jpeg" deletefile="yes"> Adding permissions ColdFusion lets you add permissions for directories/files on RAM using an existing sandbox security setup. You can only set up sandbox security for disk directories and not for RAM directories.
  • Page 277 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Limitations • File names/Directory names on RAM are case sensitive. • In-memory files must be accessed using mapping or absolute path. Relative paths to files/directories are not supported. • Correct: ram:///a/b/ • Incorrect: ram:///a/b/../..
  • Page 278 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using stored procedures tag lets ColdFusion use stored procedures in your database management system. A stored cfstoredproc procedure is a sequence of SQL statements that is assigned a name, compiled, and stored in the database system. Stored procedures encapsulate programming logic in SQL statements, and database systems are optimized to execute stored procedures efficiently.
  • Page 279 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Reviewing the code The following table describes the code and its function: Code Description <cfstoredproc procedure = "foo_proc" dataSource = Runs the stored procedure foo_proc on the "MY_SYBASE_TEST" username = "sa" password = "" returnCode = MY_SYBASE_TEST data source.
  • Page 280: Handling Errors

    ColdFusion 5, it also applies to later versions of ColdFusion.) Handling Errors Adobe ColdFusion includes many tools and techniques for responding to errors that your application encounters. These tools include error handling mechanisms and error logging tools.
  • Page 281 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • How to use the tag to specify error-handling pages cferror • How to log errors • How to handle ColdFusion exceptions Note: Information about using the tags is provided, but not the equivalent CFScript cftry cfcatch statements.
  • Page 282 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Type Description Exception An error that prevents normal processing from continuing. All ColdFusion exceptions are, at their root, Java exceptions. Missing template An HTTP request for a ColdFusion page that cannot be found. Generated if a browser requests a ColdFusion page that does not exist.
  • Page 283 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications ColdFusion exception types ColdFusion exceptions have types that you specify in the , and error-handling tags. A cferror cfcatch cfthrow tag handles only exceptions of the specified type. You identify an exception type by using an cferror cfcatch identifier from one (or more) of the following type categories:...
  • Page 284 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Custom exceptions You can generate an exception with your own type by specifying a custom exception type name, for example MyCustomErrorType, in a tag. You then specify the custom type name in a tag to cfthrow cfcatch...
  • Page 285 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Compiler exception errors If ColdFusion encounters a compiler exception, how it handles the exception depends on whether the error occurs on a requested page or on an included page: • If the error occurs on a page that is accessed by a tag, or on a custom tag page that cfinclude cfmessagebox...
  • Page 286 The Java stack at the time of the exception, including the specific Java class of the exception. This is helpful if you must contact Adobe Technical Support. The stack trace is collapsed by default. Click the heading to display the trace.
  • Page 287 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Handling form field validation errors When you use server-side form field validation, the default validation error message describes the error cause plainly and clearly. However, to give the error message a custom look or provide additional information such as service contact phone numbers and addresses, use the tag with the attribute in the Application.cfc...
  • Page 288 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Technique cferror with exception- Use the cferror tag to specify error pages for specific exception types. These pages cannot recover from errors, specific error handler but they can provide the user with information about the cause of the error and the steps to take to prevent the pages problem.
  • Page 289 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Attribute Description Type The type of error that causes ColdFusion to display this page: Exception, Request, or Validation. Exception Use only for the Exception type. The specific exception or exception category that causes the page to display. This attribute can specify any of the types described in “About ColdFusion exceptions”...
  • Page 290 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications In general, production Exception and Request pages should not display detailed error information, such as that supplied by the variable. Typically, Exception pages e-mail detailed error information to an error.diagnostics administrative address or log the information using the tag instead of displaying it to the user.
  • Page 291 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications ColdFusion automatically logs errors to the default logs if you use the default error handlers. In all other cases, use the tag in your error handling code to generate log entries. cflog tag lets you specify the following information: cflog •...
  • Page 292 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications "Error","web-13","12/19/01","11:29:07",MYAPP,"Exception error -- Exception type: coldfusion.runtime.CfErrorWrapper Template: /MYStuff/MyDocs/exceptiontest.cfm, Remote Address: 127.0.0.1, HTTP Reference: Diagnostics: Cannot find CFML template for custom tag testCase. Cannot find CFML template for custom tag testCase. ColdFusion attempted looking in the tree of installed custom tags but did not find a custom tag with this name."...
  • Page 293 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using cftry and cfcatch tags tag lets you go beyond reporting error data to the user: cftry • You can include code that recovers from errors so your application can continue processing without alerting the user.
  • Page 294 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cftry> code that may cause an exception <cfcatch ...> <cftry> First level of exception handling code <cfcatch ...> Second level of exception handling code </cfcatch </cftry> </cfcatch> </cftry> If an exception occurs in the first level of exception-handling code, the inner block can catch and handle cfcatch it.
  • Page 295 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Property variable Description A detailed message from the CFML compiler. This message, which can contain HTML formatting, can help cfcatch.Detail to determine which tag threw the exception. value is available in the CFScript statement as the cfcatch.Detail catch...
  • Page 296 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Property variable Description The native error code associated with this exception. Database drivers typically provide cfcatch.NativeErrorCode error codes to assist in the diagnosis of failing database operations. The values assumed by are driver-dependent. cfcatch.NativeErrorCode If no error code is provided, the value of is -1.
  • Page 297 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- Wrap code you want to check in a cftry block ---> <cfset EmpID=3> <cfparam name="errorCaught" default=""> <cftry> <cfquery name="test" datasource="cfdocexamples"> SELECT Dept_ID, FirstName, LastName FROM Employee WHERE Emp_ID=#EmpID# </cfquery> <html> <head> <title>Test cftry/cfcatch</title> </head>...
  • Page 298 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications </cfoutput> <cfset errorCaught = "Database"> </cfcatch> <!--- Use cfcatch with type="Any" ---> <!--- to find unexpected exceptions. ---> <cfcatch type="Any"> <cfoutput> <hr> <h1>Other Error: #cfcatch.Type#</h1> <ul> <li><b>Message:</b> #cfcatch.Message# <li><b>Detail:</b> #cfcatch.Detail# </ul> </cfoutput> <cfset errorCaught = "General Exception"> </cfcatch>...
  • Page 299 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications "Severity","ThreadID","Date","Time","Application","Message" "Information","web-0","11/20/01", "16:27:08",, "cf_root\runtime\servers\default\logs\ MyAppPage.log initialized" "Information","web-0","11/20/01","16:27:08",, "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: MissingInclude" "Information","web-1","11/20/01","16:27:32",," Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: " "Information","web-0","11/20/01","16:27:49",, "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: Database" "Information","web-1","11/20/01","16:28:21",, "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: General Exception" "Information","web-0","11/20/01","16:28:49",, "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: " Reviewing the code The following table describes the code: Code...
  • Page 300 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Code Description <cfcatch type="Database"> Handles exceptions thrown when accessing a database. <h1>Database Error</h1> Displays cfcatch variables, including the ColdFusion basic error message, <cfoutput> <ul> the error code and SQL state reported by the databases system, and the <li><b>Message:</b>...
  • Page 301 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • , which matches any exception that is not caught by a more specific tag. cfcatch Similarly, if you specify any of these types in a tag, the specified error page displays information about the cferror thrown error.
  • Page 302 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cftry> <cftry> Code that might throw a database error <cfcatch Type="Database"> <cfif Error is of type I can Handle> Handle it <cfelse> <cfrethrow> </cfif </cfcatch> </cftry> <cfcatch Type="Any"> General Error Handling code </cfcatch> </cftry>...
  • Page 303 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Reviewing the code The following table describes the code: Code Description <cftry> In a block, calls the cf_getEmps custom tag cftry <cf_getEmps EmpName="Jones"> (getEmps.cfm). <cfcatch type="myApp.getUser.noEmpName"> If the tag throws an exception indicating that it did not receive <h2>Oops</h2>...
  • Page 304 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfset caller.getEmpsResult = getuser> <!--- If still get a database error, just return to the calling page without setting the caller variable. There is no cfcatch body. This might not be appropriate in some cases. The Calling page ends up handling this case as if a match was not found --->...
  • Page 305 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Code Description <cfif NOT IsDefined("attributes.EmpName")> Makes sure the calling page specified an attribute. If EmpName <cfthrow Type="myApp.getUser.noEmpName" not, throws a custom error that indicates the problem and exits message = "Last Name was not supplied to the cf_getEmps the tag.
  • Page 306: Using Persistent Data And Locking

    Using Persistent Data and Locking Adobe ColdFusion provides several variable scopes in which data persists past the life of a single request. These are the Client, Application, Session, and Server scopes. These scopes let you save data over time and share data between pages and even applications.
  • Page 307 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Variable scope Description Client Contains variables that are available for a single client browser over multiple browser sessions in an application. For information about browser sessions, see, “What is a session?” on page 311. Useful for client-specific information, such as client preferences, that you want to store for a significant period of time.
  • Page 308 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications ColdFusion persistent variable issues Variables in the Session, Application, and Server scopes are kept in ColdFusion server memory. This storage method has several implications: • All variables in these scopes are lost if the server stops running. •...
  • Page 309 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications About client and session variables ColdFusion provides two tools for managing the client state: client variables and session variables. Both types of variables are associated with a specific client, but you manage and use them differently, as described in the following table: Variable type Description...
  • Page 310 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications These cookies uniquely identify the client to ColdFusion, which also maintains copies of the variables as part of the Session and Client scopes. You can configure your application so that it does not use client cookies, but in this case, pass these variables to all the pages that your application calls.
  • Page 311 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications To use the function, enclose the request URL in the function. For example, the following URLSessionFormat cfform tag posts a request to another page and sends the client identification, if necessary: <cfform method="Post" action="#URLSessionFormat("MyActionPage.cfm")#> If you use the same page URL in multiple functions, you can gain a small performance URLSessionFormat...
  • Page 312 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • The support for session cookies to be depends on the application server you use: httpOnly • For Tomcat/JBoss, is not supported for JSESSIONID httpOnly • On JRun, add the system property, Dcoldfusion.sessioncookie.httponly=true , in the jvm.config file •...
  • Page 313 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • Some browsers set a size limit of 4K bytes per cookie. ColdFusion encodes nonalphanumeric data in cookies with a URL encoding scheme that expands at a 3-1 ratio, which means you should not store large amounts of data per client.
  • Page 314 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications The following code from an Application.cfm file does the same thing as the previous example: <cfapplication name"SearchApp" clientmanagement="Yes" clientstorage="mydatasource"> Using client variables When you enable client variables for an application, you can use them to keep track of long-term information that is associated with a particular client.
  • Page 315 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Variable Description Client.CFID The client ID, normally stored on the client system as a cookie. Client.CFToken The client security token, normally stored on the client system as a cookie. Client.URLToken Value depends on whether J2EE session management is enabled. No session management or ColdFusion session management: A combination of the CFID CFToken...
  • Page 316 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using client variables with cflocation If you use the tag to redirect ColdFusion to a path that ends with .dbm or .cfm, the cflocation Client.URLToken variable is automatically appended to the URL. You can prevent this behavior by adding the attribute addtoken="No"...
  • Page 317 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Therefore, sessions always terminate after a time-out period of inactivity. If the user does not access a page of the application within this time-out period, ColdFusion interprets this as the end of the session and clears any variables associated with that session.
  • Page 318 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Selecting and enabling session variables in ColdFusion Administrator To use session variables, they must be enabled on the ColdFusion Administrator Memory Variables page. (They are enabled by default.) You can also use the Administrator Memory Variables page to do the following: •...
  • Page 319 ColdFusion might not set the cflocation variables. For more information, see TechNote at www.adobe.com/go/tn_18171. Accessing and changing session variables You use the same syntax to access a session variable as for other types of variables. However, lock any code that accesses or changes session variables.
  • Page 320 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications For example, to display the number of items in a user’s shopping cart, use the following code: <cflock timeout=20 scope="Session" type="Exclusive"> <cfoutput> Your shopping cart has #Session.ShoppingCartItems# items. </cfoutput> </cflock> To increase the number of items in the shopping cart, use the following code: <cflock timeout=20 scope="Session"...
  • Page 321 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications You set the application name in the tag, normally on your application’s Application.cfm page. The cfapplication application name is stored in the variable. Application.applicationName Unlike client and session variables, application variables do not require that a client name (client ID) be associated with them.
  • Page 322 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Because each Application scope variable is shared in memory by all requests in the application, these variables can become bottlenecks if used inappropriately. Whenever a request is reading or writing an Application scope variable, any other requests that use the variable must wait until the code accessing the variable completes.
  • Page 323 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Variable Description Server.OS.BuildNumber The specific operating system build, such as 1381 Server.OS.Name The name of the operating system, such as Windows NT. Server.OS.Version The version number of the operating system, such as 4.0. Locking code with cflock tag controls simultaneous access to ColdFusion code.
  • Page 324 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Suppose that ColdFusion processes two ticket orders at approximately the same time, and that the value of Application.totalTicketsSold is initially 160. The following sequence might happen: Order 1 reads the total tickets sold as 160. Order 2 reads the total tickets sold as 160.
  • Page 325 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications By placing the code that sets all of the related session variables in a single tag, you ensure that all the variables cflock get set together. In other words, setting all of the variables becomes an atomic, or single, operation. It is like a database transaction, where everything in the transaction happens, or nothing happens.
  • Page 326 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Although ColdFusion does not prevent you from setting shared variables inside read-only lock tag, doing so loses the advantages of locking. As a result, be careful not to set any session, application, or server variables inside a read-only tag body.
  • Page 327 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Controlling and minimizing lock time-outs Include a attribute in your tag. The attribute specifies the maximum time, in seconds, to timeout cflock timeout wait to obtain the lock if it is not available. By default, if the lock does not become available within the time-out period, ColdFusion generates a Lock type exception error, which you can handle using tags.
  • Page 328 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications User 1 User 2 Locks the Session scope. Locks the Application scope. Tries to lock the Application scope, but the Application scope is Tries to lock the Session scope, but the Session scope is already locked already locked by User 2.
  • Page 329 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications If it the local variable indicates that the application variables are not initialized, get an exclusive Application scope lock. Inside the lock, again test the Application scope flag, to make sure that another page has not set the variables between step one and step four.
  • Page 330 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfapplication name="ETurtle" sessiontimeout=#createtimespan(0,1,30,0)# sessionmanagement="yes"> <!--- Initialize the Session and Application variables that will be used by E-Turtleneck. Use the Session lock scope for the session variables. ---> <cflock scope="Session" timeout="10" type ="Exclusive"> <cfif not IsDefined("session.size")> <cfset session.size = "">...
  • Page 331 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <html> <head> <title>cflock Example</title> </head> <body> <h3>cflock Example</h3> <cfif IsDefined("Form.submit")> <!--- Lock session variables ---> <!--- Note that we use the automatically generated Session ID as the order ID ---> <cflock scope="Session" timeout="10" type="ReadOnly"> <cfoutput>Thank you for shopping E-Turtleneck.
  • Page 332 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <option>forest green </select> </td> </tr> <tr> <td>Select a size.</td> <td><select type="Text" name="size"> <option>small <option>medium <option>large <option>xlarge </select> </td> </tr> <tr> <td></td> <td><input type="Submit" name="submit" value="Submit"> </td> </tr> </table> </form> </cfif> </body> </html> Note: In this simple example, the Application.cfm page displays the Application.number variable value. Because the Application.cfm file is processed before any code on each ColdFusion page, the number that displays after you click the submit button does not include the new order.
  • Page 333: Using Coldfusion Threads

    </cflock> Using ColdFusion Threads You can use threads in Adobe ColdFusion to simultaneously run multiple streams of execution in a ColdFusion page or CFC. About ColdFusion threads Threads are independent streams of execution. Multiple threads on a page or CFC can execute simultaneously and asynchronously, letting you perform asynchronous processing in CFML.
  • Page 334 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • End a thread. You typically end a running thread if there is an error, or if it is still processing after a long time. • Have the page or a thread wait until one or more other threads have completed processing before proceeding with its processing, called joining the threads.
  • Page 335 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- ThreadA loops to simulate an activity that might take time. ---> <cfthread name="threadA" action="run"> <cfset thread.j=1> <cfloop index="i" from="1" to="1000000"> <cfset thread.j=thread.j+1> </cfloop> </cfthread> <!--- ThreadB loops, waiting until threadA finishes looping 40000 times. the loop code sleeps 1/2 second each time.
  • Page 336 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- Thread1 sleeps to simulate an activity that might hang. ---> <cfthread name="thread1" action="run"> <cfset thread.j=1> <cfset sleep(50000) > </cfthread> <!--- Thread2 loops to simulate an activity that takes less time. ---> <cfthread name="thread2" action="run"> <cfset thread.j=1>...
  • Page 337 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfthread action="join" name="t1,t2,t3" timeout="6000"/> If the attribute value is 0, the default value, the current thread continues waiting until all joining threads timeout finish. In this case, if the current thread is the page thread, the page continues waiting until the threads are joined, even if you specify a page time-out.
  • Page 338 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Thread scope variables are only available to the page that created the thread or to other threads created by that page. No other page can access the data. If one page must access another page’s Thread scope data, you must place the data in a database or file and access it from there.
  • Page 339 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using other scopes Threads have access to all the ColdFusion scopes. All the threads run by a page share the same Variables and This scope. All the threads run in a request share the same Form, URL, Request, CGI, Cookie, Session, Application, Server and Client scopes.
  • Page 340 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Variable Description Priority The thread processing priority, as specified when you created the thread. Starttime The time at which the thread began processing. Status The current status of the thread. For information on using the Status in an application, see “Using the thread status”...
  • Page 341 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using the thread status The Thread scope metadata variable lets the page, or any other thread started by the page, determine the status status of any thread. The page processing code can then take a necessary action, for example, if the thread has terminated abnormally or has hung.
  • Page 342 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Handle the error outside the thread by using the thread error information that is available to the page and other threads in the Thread scope threadName variable. Application code can check this variable for error .Error information.
  • Page 343 </cfif> <!--- The form for entering the feeds to aggregate. ---> <cfform> <h3>Enter three RSS Feeds</h3> <cfinput type="text" size="100" name="Feed1" validate="url" value="http://rss.adobe.com/events.rss?locale=en"><br /> <cfinput type="text" size="100" name="Feed2" validate="url" value="http://weblogs.macromedia.com/dev_center/index.rdf"><br /> <cfinput type="text" size="100" name="Feed3" validate="url" value="http://rss.adobe.com/studio.rss?locale=en"><br /> <cfinput type="submit" name="submit">...
  • Page 344: Securing Applications

    You use the ColdFusion Administrator to configure sandbox or resource security, and structure an application to take advantage of this security. User security depends on a user identity. You can implement user security in Adobe ColdFusion applications. For detailed information on using Administrator-controlled security features, see Configuring and Administering ColdFusion.
  • Page 345: Sandbox Security

    DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications About resource and sandbox security ColdFusion provides two levels of resource-based security: • ColdFusion Standard refers to its resource-based security as resource security. It lets you specify a single set of limitations on access to ColdFusion resources that apply to all ColdFusion applications. •...
  • Page 346 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • Employee pages go in another directory whose rules limit the files they modify and the tags they use. • Pages required for both HR and employee functions go in a third directory with appropriate access rules. About user security User security lets your application use security rules to determine what it shows.
  • Page 347: Authenticating Users

    DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications The following image shows a typical flow of control for user authentication and authorization. Following sections expand on this diagram to describe how you implement user security in ColdFusion. User requests a page. Is a user logged in Display login form.
  • Page 348 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Note: Dreamweaver and Studio MX do not support NTLM security with RDS. Therefore, you cannot use RDS with these applications if the ColdFusion RDS servlet (cf_root/CFIDE/main/ide.cfm) is in a directory that is protected using NTLM security.
  • Page 349 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications ColdFusion authentication storage and persistence How ColdFusion application authentication information is maintained by the browser and ColdFusion, and therefore how long it is available, depends on the following: • Whether the user’s browser enables cookies •...
  • Page 350 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using ColdFusion security tags and functions ColdFusion provides the following tags and functions for user security: Tag or function Purpose cflogin A container for user authentication and login code. The body of the tag runs only if the user is not logged in.
  • Page 351 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications ColdFusion uses the value to generate a unique identifier that enforces this rule. The default applicationToken value is the current application name, as specified by a tag or Application.cfc applicationToken cfapplication unitization code. In normal use, you need not specify an value in the tag.
  • Page 352 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cflogin> <cfif NOT IsDefined("cflogin")> <cfinclude template="loginform.cfm"> <cfabort> <cfelse> <!--- Code to authenticate the user based on the cflogin.user and cflogin.password values goes here. ---> <!--- If User is authenticated, determine any roles and use a line like the following to log in the user.
  • Page 353 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cflogin> <cfif NOT IsDefined("cflogin")> <cfheader statuscode="401"> <cfheader name="www-Authenticate" value="Basic realm=""MM Wizard #args.authtype# Authentication"""> </cfif> <cfabort> <cfelse> <!--- code to authenticate the user based on the cflogin.user and cflogin.password values goes here. ---> </cflogin> Log in a user using Flash Remoting If you are developing a Rich Internet Application with Flash and Flash Remoting, your ColdFusion application does not need to be coded specially for a Flash login.
  • Page 354 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Important: If you use web server–based authentication or any form authentication that uses a Basic HTTP Authorization header, the browser continues to send the authentication information to your application until the user closes the browser, or in some cases, all open browser windows. As a result, after the user logs out and your application uses the tag, until the browser closes, the cflogin structure in the tag will contain the logged-out user’s...
  • Page 355 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications An application authentication security scenario An application that does its own authentication works as follows. The example in “Application-based user security example” on page 356 implements this scenario. Whenever ColdFusion receives a request for a ColdFusion page, it instantiates the Application.cfc and runs the method.
  • Page 356 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications The following image shows this flow of control. For simplicity, it omits the log-out option. Step 1 User requests a page. Applicaton.cfc or Application .cfm runs first. In Application.cfc (or Application.cfm) and related files Is a user logged in? Form posts to...
  • Page 357 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using the Dreamweaver Login Wizard ColdFusion installs a Login Wizard command in the Dreamweaver Commands menu that generates a skeleton set of pages for managing user authentication and authorization. The wizard asks you to select how to authenticate the login information. Select one of the following options: •...
  • Page 358 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications This file contains a ColdFusion login form. The wizard generates this file for all options, but mm_wizard_login.cfm does not use it if you specify Browser Dialog login. The wizard generates an index.cfm page if the directory does not have one; index.cfm or mm_wizard_index.cfm otherwise, creates an mm_wizard_index.cfm page.
  • Page 359 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications With code like the following: <cfquery name="loginQuery" dataSource="#Application.DB#" > SELECT * FROM Users WHERE UserName = <cfqueryparam value="#uUserName#" CFSEQLType= 'CF_SQL_VARCHAR'AND password = <cfqueryparam value="#uPassword#" CFSEQLType='CF_SQL_VARCHAR'> </cfquery> <cfif loginQuery.recordcount gt 0> <cfset retargs.authenticated="YES"> <cfset retargs.roles=loginQuery.roles> <cfelse>...
  • Page 360 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <cfcomponent> <cfset This.name = "Orders"> <cffunction name="OnRequestStart"> <cfargument name = "request" required="true"/> <cflogin> <cfif IsDefined("cflogin")> <cfif cflogin.name eq "admin"> <cfset roles = "user,admin"> <cfelse> <cfset roles = "user"> </cfif> <cfloginuser name = "#cflogin.name#" password = "#cflogin.password#" roles = "#roles#"...
  • Page 361 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Example: securitytest.cfm The securitytest.cfm page shows how any application page uses ColdFusion user authorization features. The web server ensures the existence of an authenticated user, and the Application.cfc page ensures that the user is assigned to roles the page content appears.
  • Page 362 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications This example has three ColdFusion pages: • The Application.cfc page contains the authentication logic that checks whether a user is logged in, requests the login page if the user is not logged in, and authenticates the data from the login page. If the user is authenticated, it logs the user in.
  • Page 363 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications UserID = '#cflogin.name#' AND Password = '#cflogin.password#' </cfquery> <cfif loginQuery.Roles NEQ ""> <cfloginuser name="#cflogin.name#" Password = "#cflogin.password#" roles="#loginQuery.Roles#"> <cfelse> <cfoutput> <H2>Your login information is not valid.<br> Please Try again</H2> </cfoutput> <cfinclude template="loginform.cfm"> <cfabort> </cfif>...
  • Page 364 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Code Description <cfelse> Runs if the user submitted a login form. <cfif cflogin.name IS "" OR cflogin.password IS ""> Tests to make sure that both name and password have data. If either <cfoutput> <h2>You must enter text in both the User Name and variable is empty, displays a message, followed by the login form.
  • Page 365 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <H2>Please Log In</H2> <cfoutput> <form action="#CGI.script_name#?#CGI.query_string#" method="Post"> <table> <tr> <td>user name:</td> <td><input type="text" name="j_username"></td> </tr> <tr> <td>password:</td> <td><input type="password" name="j_password"></td> </tr> </table> <br> <input type="submit" value="Log In"> </form> </cfoutput> Reviewing the code The following table describes the loginform.cfm page CFML code and its function: Code Description <H2>Please Log In</H2>...
  • Page 366 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Security test page</title> </head> <body> <cfoutput> <h2>Welcome #GetAuthUser()#!</h2> </cfoutput> ALL Logged-in Users see this message.<br> <br> <cfscript> if (IsUserInRole("Human Resources")) WriteOutput("Human Resources members see this message.<br><br>"); if (IsUserInRole("Documentation")) WriteOutput("Documentation members see this message.<br><br>");...
  • Page 367 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using an LDAP directory for security information LDAP directories are often used to store security information. The following example of a tag checks an cflogin LDAP directory to authenticate the user and retrieve the user’s roles. For more information on using LDAP directories with ColdFusion, see “Managing LDAP Directories”...
  • Page 368 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications #cflogin.name#")</script> </cfoutput> <cfabort> <cfelse> <cfoutput> <script>alert("Unknown error for user: #cflogin.name# #cfcatch.detail#")</script> </cfoutput> <cfabort> </cfif> </cfcatch> </cftry> <!--- If the LDAP query returned a record, the user is valid. ---> <cfif auth.recordcount> <cfloginuser name="#cflogin.name#" password="#cflogin.password#" roles="#valueList(auth.cn)#">...
  • Page 369: Developing Globalized Applications

    Developing Globalized Applications Adobe ColdFusion lets you develop dynamic applications for the Internet. Users from different countries and geographical areas access many ColdFusion applications. One design detail that you must consider is the globalization of your application so that you can best serve customers in different areas.
  • Page 370 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Introduction to globalization Globalization lets you create applications for all of your customers in all the languages that you support. In some cases, globalization can let you accept data input using a different character set than the one you used to implement your application.
  • Page 371 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Your website can also accept customer feedback or some other form of text input. You might want to support that feedback in multiple languages using a variety of character sets. How ColdFusion supports globalization ColdFusion is implemented in Java.
  • Page 372 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications You use Japanese encodings, such as Shift-JIS, EUC-JP, and ISO-2022-JP, to represent Japanese text. These encodings can vary slightly, but they include a common set of approximately 10,000 characters used in Japanese. The following terms apply to character encodings: Single-byte character set;...
  • Page 373 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications By default, ColdFusion uses UTF-8 to represent text data sent to a browser. UTF-8 represents the Unicode character set using a variable-length encoding. ASCII characters are sent using a single byte. Most European and Middle Eastern characters are sent as 2 bytes, and Japanese, Korean, and Chinese characters are sent as 3 bytes.
  • Page 374 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications For example, en_US represents United States English and es_MX represents Mexican Spanish. For a list of the Java locale identifiers supported in the Sun 1.4.2 JVM and their meanings, see http://java.sun.com/j2se/1.4.2/docs/guide/intl/locale.doc.html. Previous to ColdFusion MX 7, ColdFusion supported a limited set of locales, and used identifiers that consisted of the name of the language, followed, for most languages, by a regional identifier in parentheses, such as English (US) or German (Standard).
  • Page 375 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <p>LSCurrencyFormat returns a currency value using the locale convention. <!--- loop through list of locales; show currency values for 100,000 units ---> <cfloop LIST = "#Server.Coldfusion.SupportedLocales#" index = "locale" delimiters = ","> <cfset oldlocale = SetLocale(locale)> <cfoutput><p><b><I>#locale#</I></b><br>...
  • Page 376 The following procedure describes how ColdFusion recognizes the encoding format of a ColdFusion page. Determine the page encoding (performed by ColdFusion) Use the BOM, if specified on the page. Adobe recommends that you use BOM characters in your files. Use the attribute of the tag, if specified.
  • Page 377 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Tags and functions for controlling character encoding The following tags and functions let you specify the character encoding of text that ColdFusion generates and interprets: Tag or function Attribute or parameter cfcontent type Specifies the encoding in which to return the results to the client browser.
  • Page 378 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Tag or function LSEuroCurrencyFormat Converts a number into a string in a locale-specific currency format. Formats using the euro for all countries that use euro as the currency. Determines whether a string is a valid representation of a currency amount in the current locale. LSIsCurrency LSIsDate Determines whether a string is a valid representation of a date/time value in the current locale.
  • Page 379 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- This example shows LSDateFormat ---> <html> <head> <title>LSDateFormat Example</title> </head> <body> <h3>LSDateFormat Example</h3> <p>Format the date part of a date/time value using the locale convention. <!--- loop through a list of locales; show date values for Now()---> <cfloop list = "#Server.Coldfusion.SupportedLocales#"...
  • Page 380 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • CORBA • Searching and indexing General character encoding issues Applications developed for earlier versions of ColdFusion that assumed that the character length of a string was the same as the byte length might produce errors in ColdFusion. The byte length of a string depends on the character encoding.
  • Page 381 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications One common method used to support non-ASCII characters within a URL is to include a name-value pair within the URL that defines the character encoding of the URL. For example, the following URL uses a parameter called encoding to define the character encoding of the URL parameters: http://company.com/prod_page.cfm?name=Stephen;ID=7645;encoding=Latin-1 Within the prod_page.cfm page, you can check the value of the encoding parameter before processing any of the other...
  • Page 382 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications File data You use the cffile tag to write to and read from text files. By default, the tag assumes that the text that you are cffile reading, writing, copying, moving, or appending is in the JVM default file character encoding, which is typically the system default character encoding.
  • Page 383: Debugging And Troubleshooting Applications

    ColdFusion product CD-ROM includes the Verity language packs that you install to support different languages. Debugging and Troubleshooting Applications Adobe ColdFusion provides detailed debugging information to help you resolve problems with your application. You configure ColdFusion to provide debugging information, and use the tags to provide detailed...
  • Page 384 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Configuring debugging in the ColdFusion Administrator ColdFusion can provide important debugging information for every application page requested by a browser. The ColdFusion Administrator lets you specify which debugging information to make available and how to display it. The Administrator settings briefly described.
  • Page 385 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Option Description Variables Enables the display of ColdFusion variable values. When this option is cleared, disables display of all ColdFusion variables in the debugging output. (Selected by default.) When enabled, ColdFusion displays the values of variables in the selected scopes. You can select to display the contents of any of the ColdFusion scopes except Variables, Attributes, Caller, and ThisTag.
  • Page 386 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Name Description User Agent The identity of the browser that made the HTTP request. Remote IP The IP address of the client system that made the HTTP request. Host Name The name of the host running the ColdFusion server that executed the request. Execution Time The Execution Time section displays the time required to process the request.
  • Page 387 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Tree execution time format The tree execution time format is a hierarchical, detailed view of how ColdFusion processes each page. If a page includes or calls second page, the second page appears below and indented relative to the page that uses it. Each page appears once for each time it is used.
  • Page 388 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Stored Procedures The stored procedures section displays information about the results of using the tag to execute a cfstoredproc stored procedure in a database management system. The output displays the following information: • Stored procedure name •...
  • Page 389 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Similarly, the Client, Session, Application, and Server scope variables show the global state of the application, and can be useful in tracing how each page affects the state of the ColdFusion persistent variables. Using the dockable.cfm output format The dockable.cfm output format has several features that are not included in the classic.cfm debugging display.
  • Page 390 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications attribute can be useful to disable query debugging information generated by queries in custom tags that debug you call frequently, so that you only see the debugging information for queries in pages that call the tags. You can also view stored procedure-specific debugging information by specifying the attribute in the debug...
  • Page 391 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications About the cftrace tag tag provides the following information: cftrace • A severity identifier specified by the attribute cftrace type • A timestamp indicating when the tag executed cftrace • The time elapsed between the start of processing the request and when the current tag executes.
  • Page 392 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Entry Meaning Trace type (severity) specified in the call; in this case, cftrace Information. [CFTRACE 13:21:11.011] Time when the cftrace tag executed. [501 ms] Time taken for processing the current request to the point of the tag.
  • Page 393 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Entry Meaning [UDF End] Value of the cftrace category attribute. [MyStatus = Success] Name and value of the variable specified by the cftrace attribute. If the variable is a complex data type, such as an array or structure, the log contains the variable value and the number of entries at the top level of the variable, such as the number of top-level structure keys.
  • Page 394 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Attribute Purpose abort A Boolean value. If you specify True, ColdFusion stops processing the current request immediately after the tag. This attribute is the equivalent of placing a tag immediately after the tag. The default is False. cfabort cftrace If this attribute is True, the output of the...
  • Page 395 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Using timing Use this tag to determine how long it takes for a block of code to execute. This is useful when ColdFusion debugging output indicates excessive execution time, but does not pinpoint the long-running block of code. To use this tag, enable debugging in the ColdFusion Administrator Debugging Settings page.
  • Page 396 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications <!--- type="comment" ---> <cftimer label="Query and CFOUTPUT Time in Comment" type="comment"> <cfquery name="parkquery" datasource="cfdocexamples"> select * from Parks </cfquery> <p>Select View &gt; Source to see timing information</p> <table border="1" width="100%"> <cfoutput query="parkquery"> <tr> <td>#Parkname#</td>...
  • Page 397 A few common problems that you might encounter and ways to resolve them are described here. For more information on troubleshooting ColdFusion, see the ColdFusion Support Center Testing and Troubleshooting page at www.adobe.com/go/learn_cfu_troubleshoot_en. For common tuning and precautionary measurements that can help you prevent technical problems and improve application performance, see the ColdFusion tech tips article, TechNote number 13810.
  • Page 398: Using The Coldfusion Debugger

    ColdFusion provides a line debugger that you can use when developing ColdFusion applications in Eclipse or Adobe Flash Builder. You can set breakpoints, step over, into, or out of code, and inspect variables. You can also view ColdFusion log files.
  • Page 399 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications About the ColdFusion Debugger The ColdFusion Debugger is an Eclipse plugin. It runs in the Eclipse Debug perspective. You can use the ColdFusion Debugger to perform debugging tasks, including the following: • Setting breakpoints •...
  • Page 400 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications To modify the debug settings, in Eclipse, select Window > Preferences > ColdFusion > Debug Settings. You can specify the home page URL, which points to the page that appears in the Debug Output Buffer of the debugger when you click the Home button.
  • Page 401 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications You can modify RDS configurations easily from the RDS Fileview or RDS Dataview by clicking the Edit RDS Preferences button in the view. About the Debug perspective After you install the ColdFusion Plugin, enable the debugger in ColdFusion, and configure Eclipse, you can use the ColdFusion Debugger in Eclipse.
  • Page 402 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications • Menu - Lets you specify the type of information to display in the Breakpoints pane • Debug Output Buffer - Contains two panes: Browser, which displays what appears in the browser during application execution;...
  • Page 403 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Run the page that you want to debug before setting any breakpoints to compile it before debugging it. This improves performance during debugging. You cannot set a breakpoint in a file that is not part of a project. In Eclipse, open the file in which you want to set a breakpoint.
  • Page 404 DEVELOPING COLDFUSION 9 APPLICATIONS Developing CFML Applications Inspecting variables As you observe execution of your code, you can see the values and scope of variables in the Variables panel. The Variables panel displays the scope and value of variables as the CFML code executes. Only variables whose scopes are those you selected in the Preferences dialog box appear in the Variables pane.
  • Page 405: Chapter 7: Accessing And Using Data

    Introduction to Databases and SQL Adobe ColdFusion lets you create dynamic applications to access and modify data stored in a database. You do not require a thorough knowledge of databases to develop ColdFusion applications, but you need to know some basic database and SQL concepts and techniques.
  • Page 406 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data EmpID LastName FirstName Title DeptID Email Phone Smith John Engineer jsmith x5833 Example employees table The record for employee 4 contains the following field values: • LastName field is “Smith” • FirstName field is “John” •...
  • Page 407 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data EmpID Street City State 4 Main St. Newton 02158 10 Oak Dr. Newton 02161 15 Main St. Newton 02158 56 Maple Ln. Newton 02160 25 Elm St. Newton 02160 Addresses tables In this example, each table contains a column named EmpID. This column associates a row of the employees table with a row in the addresses table.
  • Page 408 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data A database commit occurs when you make a permanent change to a database. For example, when you write a new row to a database, the write does not occur until the database commits the change. Rollback is the process of undoing a change to a database.
  • Page 409 You interpret this statement as "Select all rows from the table employees" where the wildcard symbol (*) corresponds to all columns. If you are using Dreamweaver MX 2004, Adobe Dreamweaver CS3, or HomeSite+, you can use the built-in query builder to build SQL statements graphically by selecting the tables and records to retrieve.
  • Page 410 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Keyword Description WHERE Sets one or more conditions for the operation. ORDER BY Sorts the result set in the specified order. GROUP BY Groups the result set by the specified select list items. Operators The following basic operators specify conditions and perform logical and numeric functions: Operator...
  • Page 411 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data SQL notes and considerations When writing SQL in ColdFusion, keep in mind the following guidelines: • If you use a ColdFusion variable in your SQL expression, and the variable value is a string that contains single quotes, place the variable in a PreserveSingleQuotes function to prevent ColdFusion from interpreting the quotation marks.
  • Page 412 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data You can combine multiple conditions using the WHERE clause. For example, the following example uses two conditions: SELECT * FROM employees WHERE DeptID=3 AND Title='Engineer' Sorting results By default, a database does not sort the records returned from a SQL query. In fact, you cannot guarantee that the records returned from the same query are returned in the same order each time you run the query.
  • Page 413 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data In this case, you extract LastName and FirstName information from the employees table and Street, City, State, and ZIP information from the addresses table. You can use output such as this is to generate mailing addresses for an employee newsletter.
  • Page 414 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data However, if the field does not support Nulls, specify a value for the field as part of the INSERT statement; otherwise, the database issues an error. The LastName and FirstName values in the query are contained within single-quotation marks. This is necessary because the table columns are defined to contain character strings.
  • Page 415: Accessing And Retrieving Data

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cftransaction> <cfquery name="qInsEmp" datasource="cfdocexamples"> INSERT INTO Employees (FirstName,LastName,EMail,Phone,Department) VALUES ('Simon', 'Horwith', 'SHORWITH','(202)-797-6570','Research and Development') </cfquery> <cfquery name="qGetID" datasource="cfdocexamples"> SELECT MAX(Emp_ID) AS New_Employee FROM Employees </cfquery> </cftransaction> Accessing and Retrieving Data Several ColdFusion tags provide a way to retrieve data from a database and work with query data. Use the cfquery to query a data source, the tag to output the query results to a web page, and the...
  • Page 416 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Note: The terms “recordset” and “query object” are often used synonymously when discussing recordsets for queries. For more information, see “Using Query of Queries” on page 428. When retrieving data from a database, perform the following tasks: •...
  • Page 417 </body> </html> Note: Adobe recommends that you create structured, reusable code by placing queries in ColdFusion components; however, for simplicity, the examples here include the query in the body of the ColdFusion page. For more information about using ColdFusion components, see “Building and Using ColdFusion...
  • Page 418 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Reviewing the code The query you just created retrieves data from the cfdocexamples database. The following table describes the highlighted code and its function: Code Description Queries the database specified in the cfdocexamples data source. <cfquery name="EmpList"...
  • Page 419 Although you can include both on cfquery cfoutput the same page, Adobe recommends that you place queries in ColdFusion components and output the results on a separate page. For more information, see “Building and Using ColdFusion Components”...
  • Page 420 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data In your CFML code, use these variables as if they are columns in a database table. Use the attribute to specify result the name of the structure that ColdFusion populates with these variables. You then use that structure name to refer to the query variables as the following example shows: Output information about the query on your page Edit emplist.cfm so that it appears as follows:...
  • Page 421 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Enhancing security with cfqueryparam Some DBMSs let you send multiple SQL statements in a single query. However, hackers sometimes try to modify URL or form variables in a dynamic query by appending malicious SQL statements to existing parameters. Be aware of potential security risks when you pass parameters in a query string.
  • Page 422: Updating Your Database

    Updating Your Database Adobe ColdFusion lets you insert, update, and delete information in a database. About updating your database ColdFusion was originally developed as a way to readily interact with databases. You can quickly insert, update, and delete the contents of your database by using ColdFusion forms, which are typically a pair of pages. One page displays the form with which your end user enters values;...
  • Page 423 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data You can create an insert form with standard HTML form tags or with tags (see “Creating custom forms with cfform the cfform tag” on page 723). When the user submits the form, form variables are passed to a ColdFusion action page that performs an insert operation (and whatever else is called for) on the specified data source.
  • Page 424 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data </tr> <tr> <td>Salary:</td> <td><input type="Text" name="Salary" size="10" maxlength="10"></td> </tr> <tr> <td>Contractor:</td> <td><input type="checkbox" name="Contract" value="Yes" checked>Yes</td> </tr> <tr> <td>&nbsp;</td> <td><input type="Submit" value="Submit">&nbsp;<input type="Reset" value="Clear Form"></td> </tr> </form> <!--- end html form ---> </table>...
  • Page 425 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Input form</title> </head> <body> <!--- If the Contractor check box is clear, set the value of the Form.Contract to "No" ---> <cfif not isdefined("Form.Contract")> <cfset Form.Contract = "N"> </cfif> <!--- Insert the new record ---> <cfinsert datasource="cfdocexamples"...
  • Page 426 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data The following procedure assumes that you have created the insert_action.cfm page, as described in “Creating an insert action page with cfinsert” on page 419. In insert_action.cfm, replace the tag with the following highlighted code: cfinsert cfquery...
  • Page 427: Updating Data

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Inserting into specific fields The preceding example inserts data into all the fields of a table (the Employee table has seven fields). There might be times when you do not want users to add data into all fields. To insert data into specific fields, the SQL statement in must specify the field names following both INSERT INTO and VALUES.
  • Page 428 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Update Form</title> </head> <body> <cfquery name="GetRecordtoUpdate" datasource="cfdocexamples"> SELECT * FROM Employee WHERE Emp_ID = #URL.Emp_ID# </cfquery> <cfoutput query="GetRecordtoUpdate"> <table> <form action="update_action.cfm" method="Post"> <input type="Hidden" name="Emp_ID" value="#Emp_ID#"><br> <tr> <td>First Name:</td> <td><input type="text" name="FirstName" value="#FirstName#"></td> </tr>...
  • Page 429 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following: http://localhost/myapps/update_form.cfm?Emp_ID=3 Note: Although you can view an employee’s information, code an action page before you can update the database. For more information, see “Creating an action page to update data”...
  • Page 430 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data To use the tag, include the primary key fields in your form submittal. The tag automatically cfupdate cfupdate detects the primary key fields in the table that you are updating and looks for them in the submitted form fields. ColdFusion uses the primary key fields to select the record to update (therefore, you cannot update the primary key value itself).
  • Page 431: Deleting Data

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Creating an update action page with cfquery For more complicated updates, you can use a SQL UPDATE statement in a tag instead of a tag. cfquery cfupdate The SQL UPDATE statement is more flexible for complicated updates. The following procedure assumes that you have created the update_action.cfm page as described in “Creating an update action page with...
  • Page 432 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Deleting a single record To delete a single record, use the table’s primary key in the WHERE condition of a SQL DELETE statement. In the following procedure, Emp_ID is the primary key, so the SQL Delete statement is as follows: DELETE FROM Employee WHERE Emp_ID = #Form.Emp_ID# You often want to see the data before you delete it.
  • Page 433: Using Query Of Queries

    When you execute a database query, Adobe ColdFusion retrieves the data in a recordset. In addition to presenting recordset data to the user, you can manipulate this recordset to improve the performance of your application.
  • Page 434 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Creating a recordset with the QueryNew() function In addition to creating a recordset by using a or other CFML tags, you can create it with the cfquery QueryNew function. Create a ColdFusion page with the following content: <html>...
  • Page 435 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Note: Because you can generate a recordset in ways other than using the tag, the term In Memory Query is cfquery sometimes used instead of Query of Queries. Benefits of Query of Queries Performing a Query of Queries has many benefits, including the following: When you have to access the same tables multiple times, you greatly reduce access time, because the data is already in memory (in the recordset).
  • Page 436 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <h1>Employee List</h1> <!--- LastNameSearch (normally generated interactively) ---> <cfset LastNameSearch="Doe"> <!--- Master Query ---> <cfquery datasource="cfdocexamples" name="master" cachedwithin=#CreateTimeSpan(0,1,0,0)#> SELECT * from Employee </cfquery> <!--- Detail Query (dbtype=query, no data source) ---> <cfquery dbtype="query" name="detail"> SELECT Emp_ID, FirstName, LastName FROM master WHERE LastName=<cfqueryparam value="#LastNameSearch#"...
  • Page 437 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <cfoutput query=detail> Uses the detail query to display the list of employee IDs, first names, and #Emp_ID#: #FirstName# #LastName# <br> last names. </cfoutput> <cfoutput> Lists all the columns returned by the master query. #master.columnlist#<br>...
  • Page 438 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <td bgcolor = f0f0f0> <b><i>Salary</i></b> </td> </tr> <!--- Output the query and define the startrow and maxrows parameters. Use the query variable currentRow to keep track of the row you are displaying. ---> <cfoutput query = "GetSals2"...
  • Page 439 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Using Query of Queries with non-SQL recordsets A Query of Queries can operate on any CFML tag or function that returns a recordset; you are not limited to operating results. You can perform queries on non-SQL recordsets, such as a tag, a tag, a cfquery...
  • Page 440 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Images Folder</title> </head> <body> <h2>Image Retrieval with QoQ</h2> <!--- Set the images directory. ---> <cfset dir = ("C:\pix\")> <!--- Retrieve all GIFs. ---> <cfdirectory name="GetGIF" action="list" directory="#dir#" filter="*.gif"> <!--- Retrieve all JPGs ---> <cfdirectory name="GetJPG"...
  • Page 441 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Example If a structure named A contains a field named B, which contains a table named Products, you can refer to the table with dot notation, as follows: SELECT tape_ID, length FROM A.B.Products; Using joins A join operation uses a single SELECT statement to return a result set from multiple, related tables, typically those tables with a primary key - foreign key relationship.
  • Page 442 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data To combine Table1 and Table2, use a UNION statement, as follows: SELECT * FROM Table1 UNION SELECT * FROM Table2 The UNION statement produces the following result (UNION) table: Result table Type(int) Name(varchar) Tennis Baseball...
  • Page 443 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data /* First statement. */ SELECT * FROM TableA UNION ALL (SELECT * FROM TableB UNION SELECT * FROM TableC /* Second statement. */ (SELECT * FROM TableA UNION ALL SELECT * FROM TableB UNION SELECT * FROM TableC In the first statement, there are no duplicates in the union between TableB and TableC.
  • Page 444 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Comparison conditional This conditional lets you compare an expression against another expression of the same data type (Numeric, String, Date, or Boolean). You can use it to selectively retrieve only the relevant rows of a recordset. Syntax comparison_cond ::= expression [>...
  • Page 445 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Syntax like_cond ::= left_string_exp [NOT] LIKE right_string_exp [ESCAPE escape_char] The left_string_exp can be either a constant string, or a column reference to a string column. The right_string_exp can be either a column reference to a string column, or a search pattern. A search pattern is a search condition that consists of literal text and at least one wildcard character.
  • Page 446 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Escaping wildcards You can specify your own escape character by using the conditional ESCAPE clause. Example The following example uses the ESCAPE clause to enable a search for a literal percent sign (%), which ColdFusion normally interprets as a wildcard character: SELECT emp_discount FROM Benefits...
  • Page 447 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Using the CAST function In some cases, the data type of a column is not compatible with the processing you want to do. For example, query columns returned by the tag are all of type CF_SQL_VARCHAR, even if the contents are numeric. In this case, cfhttp use the Query of Queries CAST function to convert a column value into an expression of the correct data type.
  • Page 448 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Using aggregate functions Aggregate functions operate on a set of data and return a single value. Use these functions for retrieving summary information from a table, as opposed to retrieving an entire table and then operating on the recordset of the entire table.
  • Page 449 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Examples The following code is correct: SELECT (lorange + hirange)/2 AS midrange, COUNT(*) FROM roysched GROUP BY midrange; The following code is correct: SELECT (lorange+hirange)/2 AS x, COUNT(*) FROM roysched GROUP BY x HAVING x >...
  • Page 450 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Note: Query of Queries does not support aliases for table names. SELECT FirstName + ' ' + LastName AS fullname from Employee; The following examples rely on these two master queries: <cfquery name="employee" datasource="2pubs"> SELECT * FROM employee </cfquery>...
  • Page 451 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Escaping reserved keywords ColdFusion has a list of reserved keywords, which are typically part of the SQL language and are not normally used for names of columns or tables. To escape a reserved keyword for a column name or table name, enclose it in brackets. Important: Earlier versions of ColdFusion let you use some reserved keywords without escaping them.
  • Page 452 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data LEADING LEFT LEVEL LIKE LOCAL LOWER MATCH MINUTE MODULE MONTH NAMES NATIONAL NATURAL NCHAR NEXT NULL NULLIF NUMERIC OCTET_LENGTH ONLY OPEN OPTION ORDER OUTER OUTPUT OVERLAPS PARTIAL POSITION PRECISION PREPARE PRESERVE PRIMARY PRIOR PRIVILEGES PROCEDURE...
  • Page 453 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data If you want to convert the date to its original format, use the function and apply the "mm/dd/yy" mask. DateFormat Understanding Query of Queries performance Query of Queries performs well on single-table query objects that were accessed directly from a database. This happens because ColdFusion stores meta information for a query object accessed from a database.
  • Page 454: Managing Ldap Directories

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Passing queries by reference A Query of Queries is copied by reference from its related query; which means that ColdFusion does not create a query when you create a Query of Queries. It also means that changes to a Query of Queries, such as ordering, modifying, and deleting data, are also applied to the base query object.
  • Page 455 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data The following image shows a simple directory structure: World Root Italy Country Ferrari Organization Adobe Sales Unit R&D Sales R&D Jack Gina Sophia Individual Marco Laura Enzo This example is fully symmetrical: all the entries at each layer are of the same type.
  • Page 456 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data This complexity and flexibility is a key to the usefulness. of LDAP. With it, you can represent any organizational structure. LDAP offers performance advantages over conventional databases for accessing hierarchical, directory-like information that is read frequently, and changed infrequently. Although LDAP is often used for e-mail, address, telephone, or other organizational directories, it is not limited to these types of applications.
  • Page 457 A multivalued RDN is made up of more than one attribute-value pair. In multivalued RDNs, a plus sign (+) separates the attribute-value pairs. In the sample directories, individuals could have complex RDNs consisting of their common name and their e-mail address, for example, “cn=Robert Boyd + mail=rjboyd@adobe.com”. Schema The concepts of schemas and object classes are central to a thorough understanding of LDAP.
  • Page 458 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data If an entry belongs to a class that derives from another class, the entry’s objectclass attribute lists the lowest-level class and all the superior classes from which the lowest-level class derives. When you add, modify, or delete a directory entry, you must treat the entry’s object class as a possibly multivalued attribute.
  • Page 459 For example, if the start start start attribute is “ou=support, o=adobe” the level below support is searched. You can restrict a query to the level of the entry, or extend it to the entire subtree below the entry. start...
  • Page 460 & (&(o=adobe) Entries in which the organization name is “adobe” and the country is “usa”. (co=usa)) (|(o=adobe) Entries in which the organization name is “adobe” or the surname is “adobe”, or the common name is “adobe”. (sn=adobe) (cn=adobe)) (!(STREET=*)) Entries that do not contain a StreetAddress attribute.
  • Page 461 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data • Using filter operators to construct sophisticated search criteria can degrade performance if the LDAP server is slow to process the synchronous search routines that supports. Use the cfldap cfldap timeout maxRows attributes to control the apparent performance of pages that perform queries, by limiting the number of entries and by exiting the query if the server does not respond in a specified time.
  • Page 462 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <!--- This example shows the use of CFLDAP ---> <html> <head> <title>cfldap Query Example</title> </head> <h3>cfldap Query Example</h3> <body> <p>This tool queries the Airius.com database to locate all people in the company's Santa Clara office whose common names contain the text entered in the form.</p>...
  • Page 463 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data </tr> <tr> <th>Name</th> <th>Department</th> <th>E-Mail</th> <th>Phone</th> </tr> <cfoutput query="results"> <tr> <td>#cn#</td> <td>#listFirst(ou)#</td> <td><a href="mailto:#mail#">#mail#</a></td> <td>#telephonenumber#</td> </tr> </cfoutput> </table> </cfif> </body> </html> Change the attribute from ldap.airius.com to the name of your installation of the Airius database. server Save the page as cfldap.cfm and run it in your browser.
  • Page 464 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <cfif (isdefined("form.name") AND (form.name Ensures that the user has submitted the form. This is necessary because the IS NOT ""))> form page is also the action page. Ensures that the user entered search text. <cfldap Connects anonymously to LDAP server ldap.airius.com, query the directory, and server="ldap.airius.com"...
  • Page 465 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data • Add attributes • Delete attributes • Replace attributes • Change the DN (rename the entry) These actions let you manage LDAP directory contents remotely. You build a ColdFusion page that lets you manage an LDAP directory. The form displays directory entries in a table and includes a button that lets you populate the form fields based on the unique user ID.
  • Page 466 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data organizationalperson, inetOrgPerson; cn=#Trim(Form.fullName)#; sn=#Trim(Form.surname)#; mail=#Trim(Form.email)#; telephonenumber=#Trim(Form.phone)#; ou=Human Resources; uid=#Trim(Form.uid)#"> <cfldap action="add" attributes="#attributeList#" dn="uid=#Trim(Form.uid)#, ou=People, o=Airius.com" server=#myServer# username=#myUserName# password=#myPassword#> <cfoutput><h3>Entry for User ID #Form.uid# has been added</h3> </cfoutput> </cfif> </cfif> </cfif> <html> <head> <title>Update LDAP Form</title>...
  • Page 467 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data size="20" maxlength="20" tabindex="4"></td> </tr> <tr> <td>User ID:</td> <td><cfinput type="Text" name="uid" value="#uidValue#" size="20" maxlength="20" tabindex="5"></td> </tr> <tr> <td colspan="2"> <input type="Submit" name="action" value="Add" tabindex="8"></td> </tr> </table> <br> *All fields are required for Add<br> </cfform>...
  • Page 468 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data At the top of the file, change the , and variable assignments to values that are myServer myUserName myPassword valid for your LDAP server. Save the page as update_ldap.cfm and run it in your browser. Reviewing the code The following table describes the code: Code...
  • Page 469 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <cffo rm action="update_ldap.cfm" Outputs the data entry form, formatted as a table. Each cfinput field method="post"> always has a value, set by the value attribute when the page is called. The <table>...
  • Page 470 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfelseif Form.action is "Retrieve"> <cfldap name="GetEntry" server=#myServer# action="query" attributes="cn,sn,mail,telephonenumber,uid" scope="subtree" filter="uid=#Trim(Form.UID)#" start="o=Airius.com"> <cfset fullNameValue = GetEntry.cn[1]> <cfset surnameValue = GetEntry.sn[1]> <cfset emailValue = GetEntry.mail[1]> <cfset phoneValue = GetEntry.telephonenumber[1]> <cfset uidValue = GetEntry.uid[1]> <cfelseif Form.action is "Delete">...
  • Page 471 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <cfelseif Form.action is "Retrieve"> If the user clicks Retrieve, queries the directory and gets the information for the <cfldap name="GetEntry" specified User ID. server=#myServer# action="query" Sets the form field’s attribute to the corresponding query column. Value attributes="cn,sn,mail,telephonenumber,uid"...
  • Page 472 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data After the end of the Delete button tag, add the following code: input &nbsp <input type="Submit" name="action" value="Update" tabindex="9"></td> Save the file and run it in your browser. Reviewing the code The following table describes the code: Code Description <cfelseif Form.action is "Update">...
  • Page 473: Advanced Topics

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Changing a directory entry’s DN To change the DN of an entry, provide the following information in the cfldap tag: dn="original DN" action="modifyDN" attributes="dn=new DN" For example: <cfldap action="modifyDN" dn="#old_UID#, ou=People, o=Airius.com" attributes="uid=#newUID#"...
  • Page 474 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Viewing a directory schema LDAP v3 exposes a directory's schema information in a special entry in the root DN. You use the directory root attribute to access this information. subschemaSubentry The following ColdFusion query shows how to get and display the directory schema. It displays information from the schema’s object class and attribute type definitions.
  • Page 475 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data thiselement = Trim(thisElement); nameloc = Find("NAME", thisElement); descloc = Find("DESC", thisElement); suploc = Find("SUP", thisElement); mustloc = Find("MUST", thisElement); mayloc = Find("MAY", thisElement); endloc = Len(thisElement); </cfscript> <tr> <td><cfoutput>#Mid(thisElement, nameloc+6, descloc-nameloc-8)# </cfoutput></td> <cfif #suploc# NEQ 0>...
  • Page 476 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data descloc = Find("DESC", thisElement); syntaxloc = Find("SYNTAX", thisElement); singleloc = Find("SINGLE", thisElement); endloc = Len(thisElement); </cfscript> <tr> <td><cfoutput>#Mid(thisElement, nameloc+6, descloc-nameloc-8)# </cfoutput></td> <td><cfoutput>#Mid(thisElement, descloc+6, syntaxloc-descloc-8)# </cfoutput></td> <cfif #singleloc# EQ 0> <td><cfoutput>Yes</cfoutput></td> <cfelse> <td><cfoutput>No</cfoutput></td> </cfif>...
  • Page 477 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <cfldap Gets the value of the subschemaSubentry attribute from the root of name="EntryList" the directory server. The value is the DN of the schema. server="ldap.mycorp.com" action="query" attributes="subschemaSubentry" scope="base" start=""> <cfldap Uses the schema DN to get the objectclasses and attributetypes name="EntryList2"...
  • Page 478 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <h2>Object Classes</h2> Displays the object class name, superior class, required attributes, <table border="1"> and optional attributes for each object class in a table. <tr> <th>Name</th> The schema contains the definitions of all object classes in a comma <th>Superior class</th>...
  • Page 479 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Code Description <h2>Attribute Types</h2> Does the same types of calculations for the attribute types as for the <table border="1" > object classes. <tr> <th>Name</th> <th>Description</th> <th>multivalued?</th> </tr> <cfloop index = "thisElement" list = #ReplaceNoCase(EntryList2.attributeTypes, ", The attribute type field can contain the text ", alias for..".
  • Page 480 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data About LDAP Server Security ColdFusion uses Java Native Directory Interface (JNDI), the LDAP provider, and an SSL package to create the client side of an SSL communication. The LDAP server provides the server side. The LDAP server that the cfldap connects to using SSL holds an SSL server certificate, a certificate that is securely “signed”...
  • Page 481: Building A Search Interface

    Building a Search Interface You can provide a full text search capability for documents and data sources on an Adobe ColdFusion site by enabling the Verity search engine. Verity full text search lets people visiting your site use simple one- and two-word searches to quickly find the information they need.
  • Page 482 • When indexing collections that contain documents in formats such as Adobe Acrobat (PDF) and Microsoft Word, Verity scans for the document title (if one was entered), in addition to the document text, and displays the title in the search results list.
  • Page 483 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Document format Format Version(s) Word processing Adobe Maker Interchange Format (MIF) 5, 5.5, 6, 7 Applix Words (AW) 3.11, 4.2, 4.3, 4.4, 4, 41, 4.2 DisplayWrite (IP) Folio Flat File (FFF) Fujitsu Oasys (OA2)
  • Page 484 Microsoft PowerPoint for PC (PPT) Microsoft PowerPoint for Macintosh (PPT) Microsoft Project (MPP) 98, 2000, 2002 Display formats Adobe Portable Document Format (PDF) 1.1 (Acrobat 2.0) to 1.4 (Acrobat 5.0) Graphics formats AutoCAD Drawing format (DWG) (standalone) (does not extract R13, R14, and R2000...
  • Page 485 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Specify a language when you create the collection. The language you specify should match the language the documents were authored in. By specifying the language your documents are written in, Verity is able to correctly interpret accented characters, and, in many languages, use variations of word stems and roots.
  • Page 486 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Language Language attribute Norwegian norwegian Norwegian (Bokmal) bokmal Norwegian (Nynorsk) nynorsk Polish polish Portuguese portuguese Russian russian Spanish spanish Swedish swedish Turkish turkish Multiple languages You can register collections in the ColdFusion Administrator or by creating a collection with the tag.
  • Page 487 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data For more information on selecting a language, see “Specifying a language” on page 479. (Optional) Select Enable Category Support to create a Verity Parametric collection. For more information on using categories, see “Narrowing searches by using categories”...
  • Page 488 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data • You do not want to expose the ColdFusion Administrator to users. • You want to create indexes on servers that you cannot access directly; for example, if you use a hosting company. When using the tag, you can specify the same attributes as in the ColdFusion Administrator: cfcollection...
  • Page 489 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Save the file as collection_create_form.cfm in the myapps directory under the web root directory. Note: The form does not work until you write an action page for it, which is the next procedure. Create a collection action page Create a ColdFusion page with the following content: <html>...
  • Page 490 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Indexing a collection by using the cfindex tag You can index a collection in CFML by using the tag, which eliminates the need to use the ColdFusion cfindex Administrator. The tag populates the collection with metadata that is then used to retrieve search results. You cfindex can use the tag to index either physical files (documents stored within your website’s root folder), or the...
  • Page 491 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Select the Collection to Index</title> </head> <body> <h2>Specify the index you want to build</h2> <form method="Post" action="collection_index_action.cfm"> <p>Enter the collection you want to index: <input type="text" name="IndexColl" size="25" maxLength="35"></p> <p>Enter the location of the files in the collection: <input type="text"...
  • Page 492 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Enter a file location; for example, C:\ColdFusion9\wwwroot\vw_files. Enter a URL prefix; for example, http://localhost:8500/vw_files (assuming that you are using the built-in web server). Click Index. A confirmation message appears on successful completion. Note: For information about using the tag with a database to index a collection, see “Working with data...
  • Page 493 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data cfquery cfsearch Uses SQL statements to specify search criteria Uses a criteria attribute to specify search criteria Returns variables keyed to database table field names Returns a unique set of variables Uses cfoutput to display query results Uses...
  • Page 494 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Searching a collection</title> </head> <body> <h2>Searching a collection</h2> <form method="post" action="collection_search_action.cfm"> <p>Enter search term(s) in the box below. You can use AND, OR, NOT, and parentheses. Surround an exact phrase with quotation marks.</p> <p><input type="text"...
  • Page 495 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Enter target words and click Search. Note: As part of the indexing process, Verity automatically produces a summary of every document file or every query recordset that gets indexed. The default summary result set column selects the best sentences, based on internal rules, up to a maximum of 500 characters.
  • Page 496 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Search Results</title> </head> <body> <cfsearch name = "codecoll_results" collection = "CodeColl" criteria = "#Form.Criteria#" ContextHighlightBegin="<b>" ContextHighlightEnd="</b>" ContextPassages="1" ContextBytes="500" maxrows = "100"> <h2>Search Results</h2> <cfoutput> Your search returned #codecoll_results.RecordCount# file(s). </cfoutput> <cfoutput query="codecoll_results">...
  • Page 497 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Search Results</title> </head> <body> <cfsearch name = "codecoll_results" collection = "CodeColl" criteria = "#Form.Criteria#"> status = "info" suggestions="5" ContextPassages = "1" ContextBytes = "300" maxrows = "100"> <h2>Search Results</h2> <cfoutput> Your search returned #codecoll_results.RecordCount# file(s).
  • Page 498 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Index the collection, specifying the attributes appropriate to the collection. category categoryTree For more information on indexing Verity collections with support for categories, see “Indexing collections that contain categories” on page 493. Create a search page that lets users search within the categories that you created.
  • Page 499 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfindex collection="#Form.IndexColl#" action="update" extensions=".htm, .html, .xls, .txt, .mif, .doc, .pdf" key="#Form.IndexDir#" type="path" urlpath="#Form.urlPrefix#" recurse="Yes" language="English" category="taste, touch, sight, sound, smell" categoryTree="human/senses/taste"> For more information on using the tag to create Verity collections with support for categories, see cfindex cfindex in the CFML Reference.
  • Page 500 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data status="s" criteria="#form.criteria#" contextPassages="3" contextBytes="300" contextHighlightBegin="<i><b>" contextHighlightEnd="</b></i>" maxrows="100"> <cfdump var="#s#"> <cfoutput> <p>Number of records in query: #sr.recordcount#</P> </cfoutput> <cfdump var="#sr#"> <cfoutput Query="sr"> Title: <i>#title#</i><br> URL: #url#<br> Score: #score#<br> <hr> #context#<br> <br> #summary#<br> <hr> </cfoutput>...
  • Page 501 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data To retrieve information about the categories contained in a collection, you use the tag, and create an cfcollection application page that retrieves category information from the collection and displays the number of documents contained by each category.
  • Page 502 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Working with data returned from a query Using Verity, you can search data returned by a query—such as a database recordset—as if it is a collection of documents stored on your web server. Using Verity to search makes implementing a search interface much easier, as well as letting users more easily find information contained in database files.
  • Page 503 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data When indexing a recordset retrieved from a database, the tag uses the following attributes that correspond cfindex to the data source: Attribute Description Primary key column of the data source table. title Specifies a query column name.
  • Page 504 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Adding Query Data to an Index</title> </head> <body> <!--- Retrieve data from the table. ---> <cfquery name="getEmps" datasource="cfdocexamples"> SELECT * FROM EMPLOYEE </cfquery> <!--- Update the collection with the above query results. ---> <cfindex query="getEmps"...
  • Page 505 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Searching a collection</title> </head> <body> <h2>Searching a collection</h2> <form method="post" action="collection_db_results.cfm"> <p>Collection name: <input type="text" name="collname" size="30" maxLength="30"></p> <p>Enter search term(s) in the box below. You can use AND, OR, NOT, and parentheses.
  • Page 506 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <html> <head> <title>Search Results</title> </head> <body> <cfsearch collection="#Form.collname#" name="getEmps" criteria="#Form.Criteria#" maxrows = "100"> <!--- Output the record set. ---> <cfoutput> Your search returned #getEmps.RecordCount# file(s). </cfoutput> <cfoutput query="getEmps"> <p><table> <tr><td>Title: </td><td>#Title#</td></tr> <tr><td>Score: </td><td>#Score#</td></tr> <tr><td>Key: </td><td>#Key#</td></tr>...
  • Page 507 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Search and display the file ❖ Create a ColdFusion page that contains the following content: <!--- Output the record set.---> <p>Your collection now includes the following items:</p> <cfoutput query="getEmps"> <p>#Emp_ID# #FirstName# #LastName# #Contract_File#</p> </cfoutput>...
  • Page 508 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfquery name="getEmps" datasource="cfdocexamples"> SELECT * FROM EMPLOYEE WHERE Emp_ID = 15 </cfquery> <!--- Update the collection with the above query results. ---> <!--- Key specifies a column that contains a directory path. ---> <cfindex query="getEmps"...
  • Page 509 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data When creating an index from an LDAP query, remember the following considerations: • Because LDAP structures vary greatly, you must know the directory schema of the server and the exact name of every LDAP attribute that you intend to use in a query.
  • Page 510: Using Verity Search Expressions

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data As with the other query types, provide a unique value for the attribute and enter the data fields to index in the body attribute. The following example updates the pop_query collection with the current mail for user1, and searches and returns the message number and subject line for all messages that contain the word action: <!--- Run POP query.
  • Page 511 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Query type Content Use of operators and modifiers CFML example Simple One or more words Uses STEM operator and MANY <cfsearch name = "band_search" modifier, by default collection="bbb" type = "simple" criteria="film"> Explicit Words, operators, Must be specified...
  • Page 512 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data The operators AND and OR, and the modifier NOT, do not require angle brackets (<>). Operators typically require angle brackets and are used in explicit queries. For more information about operators and modifiers, see “Operators modifiers”...
  • Page 513 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data When you specify the search expression must be a valid Verity Query Language expression. As a type="explicit" result, an individual search term must be in explicit quotation marks. The following table shows valid and invalid criteria: Attribute Effect...
  • Page 514 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Using wildcards and special characters Part of the strength of the Verity search is its use of wildcards and special characters to refine searches. Wildcard searches are especially useful when you are unsure of the correct spelling of a term. Special characters help you search for tags in your code.
  • Page 515 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data To search for special characters as literals, precede the following nonalphanumeric characters with a backslash character (\) in a search string: • comma (,) • left parenthesis ( • right parenthesis ) •...
  • Page 516 Using Internet queries With the Internet query parser, users can search entire documents or parts of documents (zones and fields) entering words, phrases, and plain language like what many web search engines use. Adobe ColdFusion supports two Internet query parsers in the attribute.
  • Page 517 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data To search a document field, type the name of the field, a colon (:), and the search term with no spaces. field:term If you enter a minus sign (–) immediately preceding field, documents that contain the specified term are excluded from the search results.
  • Page 518 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Pass-through of terms Search terms are passed through to the VDK-level and are interpreted as Verity Query Language (VQL) syntax. No issues arise if the terms contain only alphabetic or numeric characters. Other kinds of characters might be interpreted by the language you’re using.
  • Page 519 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfsearch name="results" collection="#form.collname#" criteria="#LCase(form.criteria)#" type="#form.type#"> Prefix and infix notation By default, Verity uses infix notation, in which precedence is implicit in the expression; for example, the AND operator takes precedence over the OR operator. You can use prefix notation with any operator except an evidence operator (typically, STEM, WILDCARD, or WORD;...
  • Page 520 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Character Usage < > Left and right angle brackets are reserved for designating operators and modifiers. They are optional for the AND, OR, and NOT, but required for all other operators. " Use double quotation marks in expressions to search for a word that is otherwise reserved as an operator or modifier, such as AND, OR, and NOT.
  • Page 521 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data STARTS ENDS SUBSTRING Concept operators Concept operators combine the meaning of search elements to identify a concept in a document. Documents retrieved using concept operators are ranked by relevance. The following table describes each concept operator: Operator Description Selects documents that contain all the search elements that you specify.
  • Page 522 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Operator Description Example CONTAINS Selects documents by matching the word or phrase that you specify • In a document field named TITLE, to retrieve with the values stored in a specific document field. Documents are documents whose titles contain music, musical, selected only if the search elements specified appear in the same or musician, search for TITLE <CONTAINS>...
  • Page 523 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Year Place Text 1990 Utah Text about Utah 1990 1990 Oregon Text about Oregon 1990 1991 Utah Text about Utah 1991 1991 Oregon Text about Oregon 1991 1992 Utah Text about Utah 1992 The following application page matches records that have 1990 in the TEXT column and are in the Place Utah.
  • Page 524 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data The following table describes the evidence operators: Operator Description Example STEM Expands the search to include the word that you enter and its <STEM>believe retrieves matches such as variations. The STEM operator is automatically implied in any “believe,”...
  • Page 525 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Operator Description Example NEAR Selects documents containing specified search terms. The closer the war <NEAR> peace retrieves documents that search terms are to one another within a document, the higher the contain stemmed variations of these words document’s score.
  • Page 526 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Operator Description Example YESNO Forces the score of an element to 1 if the element’s score is nonzero. <YESNO>mainframe. If the retrieval result of the search on mainframe is 0.75, the YESNO operator forces the result to 1.
  • Page 527 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data Refining your searches with zones and fields One of the strengths of Verity is its ability to perform full-text searches on documents of many formats. However, sometimes you want to restrict a search to certain portions of a document, to improve search relevance. If a Verity collection contains some documents about baseball and other documents about caves, a search for the word bat can retrieve several irrelevant results.
  • Page 528 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <band.xml> <Lead_Guitar>Pete</Lead_Guitar> <Rhythm_Guitar>Roger</Rhythm_Guitar> <Bass_Guitar>John</Bass_Guitar> <Drums>Kenny</Drums> <COMMENT_A>Who knows who's better than this band?</COMMENT_A> <COMMENT_B>Ticket prices correlated with decibels.</COMMENT_B> </band.xml> To retrieve only the files in which Pete is the lead guitarist, perform a zone search using the IN operator according to the following syntax: (query) <IN>...
  • Page 529 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data • cf_custom1 • cf_custom2 • cf_custom3 • cf_custom4 Text comparison operators can also reference the following automatically populated document fields: • title • key • url • vdksummary • author • mime-type To explore how to use document fields to refine a search, consider the following database table, named Calls.
  • Page 530: Solr Search Support

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfindex query = "Calls" collection = "training" action = "UPDATE" type = "CUSTOM" title = "Short_Description" key = "Call_ID" body = "Problem_Description" custom1 = "Product"> To perform the refined search for HomeSite+ problems with the word certain in the problem description, the tag uses the CONTAINS operator in its attribute: cfsearch...
  • Page 531: Language Support

    DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data • Support for MS Office 2007 file formats The ColdFusion installer automatically creates the ColdFusion 9 Solr service, which contains the Solr web application. For UNIX and Linux, you need to start and stop the Solr shell script. CFML tags used to configure Solr To create a collection using this tag, specify with...
  • Page 532 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data • Multiple word search: The following example shows how to search a document or query having words "ColdFusion" and "Green" in it: <cfsearch name="qsearch1" collection="solr_complex" criteria="+Green +Coldfusion"> • Search with at least one word: The following example shows how search for at least "Coldfusion" OR (Green OR Blue): <cfsearch name="qsearch1"...
  • Page 533 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data To search a document whose modification date is between a given range: <cfsearch name="qsearch" collection="solr_srch" criteia="modified:20080101 TO 20500101"> These ranges are inclusive of start and end terms. To exclude them, use curly brackets{} instead. •...
  • Page 534 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfsearch collection="syn1" criteria="Services solr" name="results" status="r" suggestions="always" contextPassages="1"> To highlight contents in the entire document, modify the solrconfig.xml and schema.xml files. These files are available in the following locations: • <Collection Directory>/conf: Modify files in this location to apply the changes to all future Solr collections. •...
  • Page 535 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <field name="contents" type="text" indexed="true" stored="false" required="false" multiValued="true" omitNorms="true"/> with <field name="contents" type="text" indexed="true" stored="true" required="false" multiValued="true" omitNorms="true"/> Restart Solr. Reindex the collection. Note: The modifications to solrconfig.xml and schema.xml will increase the index size. Migrating from Verity to Solr To migrate from Verity to Solr, perform the following tasks: Step1: Migrate collections from Verity to Solr using ColdFusion Administrator...
  • Page 536 DEVELOPING COLDFUSION 9 APPLICATIONS Accessing and Using Data <cfsearch name="qsearch1" collection="solr_complex" criteria ="te?t"> Verity <cfsearch name="qsearch1" collection="Verity_complex" type="explicit" criteria="<WILDCARD>te?t"> • Searching titles Solr: <cfsearch name="qsearch1" collection="solr_complex" criteria ="title:fuzzy?.txt"> Verity: <cfsearch name="qsearch1" collection="Verity_complex" type="explicit"criteria="CF_TITLE<SUBSTRING>fuzzy"> For more examples of how search criteria is set in Solr, see “Solr search examples”...
  • Page 537 Stop Solr. Back up solr.xml available in Solr_Home/multicore. Uninstall Solr. Reinstall the standalone version of Solr available on Adobe download location. Stop Solr (if it has started automatically). Bring back the backed up copy of solr.xml to Solr_Home/multicore. Note: After you upgrade, ensure that you reindex the entire Solr collection before you use the search service.
  • Page 538: Chapter 8: Coldfusion Orm

    Chapter 8: ColdFusion ORM Relational databases are the core of most enterprise applications. However, when you map a relational database to objects, it becomes a challenge. Object relational mapping (ORM) is a programming framework that allows you to define a mapping between application object model and the relational database. In an object model, the application objects are not aware of the database structure.
  • Page 539 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM The following example explains these concepts by building a simple application, which would enable you to jumpstart with ColdFusion ORM. The example uses the cfartgallery data source that is shipped as part of ColdFusion 9 documentation option in the installer.
  • Page 540 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Step 3: Perform CRUD operations. To retrieve data from the ARTISTS table, use EntityLoad() ARTISTS = EntityLoad("ARTISTS") All the records from the ARTISTS table are retrieved as an object array. To add a new artist, create a new artist object and call for this object.
  • Page 541 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfcomponent persistent="true"> <cfproperty name="artid" generator="increment"> <cfproperty name="artname"> <cfproperty name="price"> <cfproperty name="largeimage"> <cfproperty name="mediaid"> <cfproperty name="issold"> </cfcomponent> In cfartgallery, the table ARTISTS has a one-to-many relationship with ART table, which are joined using the foreign key column ARTISTID.
  • Page 542: Architecture

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Architecture In ColdFusion ORM, you need to define an object mapping to create persistent objects. The object mapping includes details such as: • The table name for the object's class • The column name that corresponds to each field in the object •...
  • Page 543: Configure Orm

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM For transactions, a new session is always created at the start of a transaction and ends at the end of a transaction. Any previous open sessions are flushed and closed at the start of the transaction. The Hibernate configuration is created and loaded only when the application starts.
  • Page 544 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Property Name Default Description true Specifies whether ColdFusion should automatically generate mapping for the autogenmap persistent CFCs. If , mapping should be provided in the autogenmap=false form of .HBMXML files. automanageSession true Lets you specify if ColdFusion must manage Hibernate session automatically. Added in ColdFusion 9.0.1 •...
  • Page 545 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Property Name Default Description dialect Specifies the dialect. ColdFusion supports the following dialects: • • DB2AS400 • DB2OS390 • Derby • PostgreSQL • MySQL • MySQLwithInnoDB • MySQLwithMyISAM • Oracle8i • Oracle9i • Oracle10g •...
  • Page 546 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Property Name Default Description savemapping false Specifies whether the generated Hibernate mapping file has to be saved to disc. If you set the value to true, the Hibernate mapping XML file is saved with the filename "CFC name".hbmxml in the same directory as the CFC.
  • Page 547: Define Orm Mapping

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM ###--------------- Hibernate Log Settings ------ ### Set Hibernate log log4j.logger.org.hibernate=ERROR, HIBERNATECONSOLE ### log just the SQL #log4j.logger.org.hibernate.SQL=DEBUG, HIBERNATECONSOLE #log4j.additivity.org.hibernate.SQL=false ### Also log the parameter binding to the prepared statements. #log4j.logger.org.hibernate.type=DEBUG ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=DEBUG, HIBERNATECONSOLE ### log cache activity ### log4j.logger.org.hibernate.cache=ERROR, HIBERNATECONSOLE...
  • Page 548 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfcomponent persistent="true" entityname="Artist" table="Artists"> <cfproperty name="id" column="ARTISTID" generator="increment"> <cfproperty name="firstname"> <cfproperty name="lastname"> <cfproperty name="address"> <cfproperty name="city"> <cfproperty name="state"> <cfproperty name="postalcode"> <cfproperty name="email"> <cfproperty name="phone"> <cfproperty name="fax"> <cfproperty name="thepassword"> </cfcomponent> Map a ColdFusion component The tag defines a persistent CFC by setting .
  • Page 549 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description cacheuse optional none Use this value to specify the caching strategy to be used for caching this component's data in the secondary cache. See Caching for details. Optional Used to specify the database catalog name. catalog discriminatorcolumn optional...
  • Page 550 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description persistent Required false Whether the CFC is a persistent CFC: • true • false readonly Optional false Whether the table is read-only: • true • false This is inserted by the EntitySave() method.
  • Page 551 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Optional Default Description optional This sets the default value on the property when the object is default created. fieldtype optional column This attribute is used to specify the type of the property. Use this attribute to specify the following: •...
  • Page 552 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Syntax <cfproperty name="property_name" fieldType="id" ormtype="type" column="column_name" generator="increment|identity |sequence|sequence-identity|seqhilo |uuid|guid|native|[assigned]|select|foreign" params="{key1=val1,key2=val2...}" sqltype="sql_type" length="column_length" unsavedvalue="instantiated_instance"> Example An example to define an assigned primary key: <cfproperty name="artistid" fieldtype="id" column="ARTISTID" generator="assigned"> An example to define a auto-generated primary key using increment generator: <cfproperty name="artid"...
  • Page 553 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description selectkey optional The column name that is used to retrieve the primary key generated by a database trigger. optional Use this attribute to specify the DB-specific SQLType that sqltype should be used for the column. This attribute is used for table creation only.
  • Page 554 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM • : This is used with a primary key association. In this case, the primary key is the same as foreign <one-to-one> the primary key of the associated object. This generator would need the property parameter, which needs to be specified in the attribute.
  • Page 555 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attributes Attribute Req/Opt Default Description column optional Name of the property Name of the column. This sets the default value of a column in the table when schema is dbdefault exported. fieldType optional column Should be “column”...
  • Page 556 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description optional Specifies the default value of the column in the table. dbdefault index optional Specifies the name of an index that is created using the mapped column. optional Specifies the length value. length notnull optional...
  • Page 557 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Syntax <cfproperty name="fieldname" fieldtype="version" column="column name" ormtype="type" generated="true|[false]" insert="[true]|false"> Example To create a simple version property: <cfproperty name="version" fieldtype="version"> Attribute Attribute Req/Opt Default Description Optional The name of the column that contains versioned data column fieldtype Required...
  • Page 558 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description Optional The name of the column that contains time-stamped column data. fieldtype Required Specifies the field type. Specify the field type value as timestamp for a time- stamped field. Optional Specifies if the timestamp field is generated by the generated false...
  • Page 559 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Escaping SQL keywords in table and column name ColdFusion automatically escapes the table name or column name if it is an SQL keyword or if there is a space in it. The list of SQL keywords are present in file.
  • Page 560 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM You can also use the link table to establish a relationship. A link table contains the foreign key to both tables that participate in the relationship. ORM looks for the map key column using the link table and not the target table. Relationship attributes This table specifies the attribute details for all the relationship types.
  • Page 561 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Applies to Re/Opt Default Description fkcolumn Optional Specifies the foreign key column. In case the relation is established using link table, this specifies the foreign key column in the link table that references the primary key of the source object.
  • Page 562 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Applies to Re/Opt Default Description lazy Optional true Specifies if the association should be loaded lazily. true false extra Lazy Loading for details. linkcatalog Optional Catalog for the link table. Optional Schema for the link table. linkschema linktable Required...
  • Page 563 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Applies to Re/Opt Default Description singularname one-to-many optional property Use this property to define the custom name for generated name relationship methods. See Generated methods for many-to-many relationships between CFCs. one-to-many The column in the target table to use as key if the collection structkeycolumn type is struct.
  • Page 564 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM You can also specify comma separated cascade values in the attribute. For a one-to-one or a one-to-many cascade relationship, the most common values are all-delete-orphan. For an association where the child object can continue to exist even if the parent object is deleted, you can apply the save-update cascade value.
  • Page 565 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM • Unique Foreign Key association Primary key association In this type of association, the primary key of one table references to the primary key of another table. That is, both the tables share the same primary key. The following example shows how to define this mapping.
  • Page 566 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfproperty name="fieldname" fieldtype="one-to-one" cfc="Referenced_CFC_Name" linktable="Link table name" linkcatalog="Catalog for the link table" linkschema="Schema for the link table" fkcolumn="Foreign Key column name" inversejoincolumn="Column name or comma-separated list of primary key columns" mappedby="Mapped_Field_name_in_referenced_CFC" cascade="none" fetch="join|[select]" lazy="[true]|false"> Note: The mappedby attribute can not be specified with the fkcolumn attribute.
  • Page 567 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM A one-to-many relationship between two persistent components is defined using the value fieldtype one-to-many in the tag. The source object contains a collection of target objects. ColdFusion allows the collection to cfproperty be one of the following types: •...
  • Page 568 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfproperty name="field_name" fieldtype="one-to-many" cfc="Referenced_CFC_name" linktable="Link table name" linkcatalog="Catalog for the link table" linkschema="Schema for the link table" fkcolumn="Foreign Key column name" inversejoincolumn="Column name or comma-separated list of primary key columns" type="struct" orderby="order_by_String" structkeycolumn = "Structure_Key_Column" structkeytype="ormtype"...
  • Page 569 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Syntax <cfproperty name="fieldname" fieldtype="many-to-one" cfc="Referenced_CFC_Name" linktable="Link table name" linkcatalog="Catalog for the link table" linkschema="Schema for the link table" fkcolumn="Foreign Key column name" inversejoincolumn="Column name or comma-separated list of primary key columns" column="Foreign_Key_Column" mappedby="Mapped_Field_name_in_referenced_CFC" cascade="cascade_options" fetch="join|[select]"...
  • Page 570 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfproperty name="fieldname" fieldtype="many-to-many" cfc="fully qualified name" linktable="Link table name" linkcatalog="Catalog for the link table" linkschema="Schema for the link table" fkcolumn="Foreign Key column name" inversejoincolumn="Column name or a composite key with comma-separated primary key columns" mappedby="Property in the target component that is referenced by fkcolumn in join table"...
  • Page 571 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Advanced mapping Collection Mapping Collection mapping is similar to a one-to-many relationship mapping. However, in collection mapping, you have a collection of values instead of a collection of persistent target objects. Consider the Artist-Art tables. If you want each Artist object to contain an array of artwork names instead of artwork objects, collection mapping should be used.
  • Page 572 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description fkcolumn Optional The foreign key column in the specified table. If you do not specify the foreign key column and useDBForMapping true ormsettings , ColdFusion automatically determines a foreign key column after inspecting the database.
  • Page 573 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Attribute Req/Opt Default Description Optional An integer value that specifies the " " for batchsize batchsize lazily fetching instances of this collection. elementcolumn Required Specifies the column name that contains the data to be fetched for collection. Required Data type of the value.
  • Page 574 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM • Table per subclass without discriminator • Table per subclass with discriminator Table per hierarchy In this model, the object hierarchy is persisted in a single table. This table includes columns for all the properties of all the CFCs in the hierarchy.
  • Page 575 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Table per subclass without discriminator In this model, there are separate tables for each class in the hierarchy and these tables are joined by a primary key. When the object is persisted, properties of the parent component are stored in the parent table and the remaining properties are stored in the child table.
  • Page 576 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfcomponent persistent="true" table="Payment" discriminatorColumn="paymentType"> <cfproperty name="paymentId"> <cfproperty name="amount"> </cfcomponent> CreditCardPayment.cfc <cfcomponent persistent="true" extends="Payment" table="CreditCardPayment" joinColumn="paymentId" discriminatorValue="CCard"> <cfproperty name="cardNo"> <cfproperty name="cardType"> </cfcomponent> CheckPayment.cfc <cfcomponent persistent="true" extends="Payment" table="CheckPayment" joinColumn="paymentId" discriminatorValue="Check"> <cfproperty name="checkNo"> <cfproperty name="bankName"> <cfproperty name="city"> </cfcomponent>...
  • Page 577 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfcomponent persistent="true"> <cfproperty name="EmployeeID"> <cfproperty name="EmployeeName"> <cfproperty name="Designation"> </cfcomponent> employee.hbmxml <hibernate-mapping > <class name="cfc:Employee" table="Employees"> <id name="EmployeeID" type="integer" column="EmployeeID"> <generator class="native"/> </id> <component name="EmployeeName" class="cfc:Name"> <property name="LastName" type="string" column="LastName"/> <property name="FirstName" type="string" column="FirstName"/> <property name="Title" type="string" column="Title"/> </component>...
  • Page 578 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Emp.cfm <cfscript> employee = EntityNew("Employee"); employee.setEmployeeName("Dan Watson"); imdata1 = new IMData(); imdata1.setType("IMClient1"); imdata1.setID("msngrId1"); imdata2 = new IMData(); imdata2.setType("IMClient 2"); imdata2.setID("msngrId2"); employee.setIMIDs([imdata1, imdata2]); EntitySave(employee); </cfscript> For more details on component mapping in hibernate, see Component Mapping in Hibernate Reference Guide.
  • Page 579 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM The following is an example of Hibernate mapping: <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class lazy="true" name="cfc:artGallery.Art" schema="APP" table="Art"> <id name="artid" type="int"> <column length="10" name="ARTID"/> <generator class="identity"/> </id> <property name="artname" type="string"> <column length="50"...
  • Page 580: Working With Objects

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Working with objects Operations can be performed on an Entity object, and the auto-generated methods in the entity can be called. Generated accessors As described in Define ORM mapping, the persistent fields for an object are defined in the CFC using cfproperty ColdFusion generates the accessor methods (getter and setter) for each property in the CFC that can be invoked.
  • Page 581 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM • boolean Has<relationship_property_name>() This method is generated for all the relationships. For one-to-many and many-to-many, this method checks whether the association collection is empty. If the association collection is empty, it will return true. For one-to-one and many-to-one, this method checks whether the associated object exists.
  • Page 582 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM • hasArt(Art art) Perform create, read, update, delete operations on ORM Objects In any data-centric application, you can perform the following operations on the database: • Insert (Create) • Update • Retrieve • Delete Once the object relational model is defined in a ColdFusion application, you can perform CRUD operations on the objects directly using the methods provided by ColdFusion ORM.
  • Page 583 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Example: <cfset artist = EntityNew("Artist")> <cfset artist.setFirstName("Marcia")> <cfset artist.setlastName("Em")> <cfset EntitySave(artist)> Update objects EntitySave The method to update an object is the same as saving an object. Load the object that needs to be updated, make updates, and save the object.
  • Page 584 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM This example loads the Artist object with PK 100 and returns the artist object. <cfset artistobj = EntityLoad('Artist', 100, true)> Example 3: This example loads the OrderDetail object which has the composite key OrderID=100 and ProductID=1 and returns the orderdetail object.
  • Page 585 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM • : Specifies the timeout value (in seconds) for the query. timeout are used for pagination. Maxresults timeout Example To load first 5 artists whose state is "CA" that are sorted on the firstName. <cfset artists = EntityLoad("Artist",{state='CA"}, "FirstName", {maxResults=5})>...
  • Page 586: Using Queries

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Example 1 <cfset artists = EntityLoad("Artist")> <cfset artistQuery = EntityToQuery(artists)> Example 2 <cfset creditCardPayments = EntityLoad("CreditCardPayment")> <cfset paymentQuery = EntityToQuery(creditCardPayments, "payment")> Merge entities EntityMerge To attach an entity to the current ORM session you can use the entitymerge function. It copies the state of the given object onto the persistent object with the same identifier and returns the persistent object.
  • Page 587 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM ORMExecuteQuery(hql, [,unique] [, queryoptions]) Runs the HQL on the default data source specified for the application. You can specify several options to control the behavior of retrieval using queryoptions: • : Specifies the maximum number of objects to be retrieved. maxResults •...
  • Page 588 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Note: In case of more than one parameter, values are picked up based on the parameter sequence, for example, the first parameter will be replaced by first value and second parameter will be replaced by second value. Examples: named parameters This type of lets you pass named parameters to the query.
  • Page 589: Transaction And Concurrency

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Example: expressions This type of ORMExecuteQuery lets you retrieve data using expressions such as mathematical operators, logical operators, binary comparisons, and many others. For example, the following code is used to retrieve the price of an artwork, which is greater than or equal to 10000 along with the name and description of the artwork.
  • Page 590 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cftransaction> <cfset acct1 = EntityLoad("Account", "101")> <cfset acct2 = EntityLoad("Account", "102")> <cfset acct1.debit(1000)> <cfset acct2.credit(1000)> <cfset EntitySave(acct1)> <cfset EntitySave(acct2)> </cftransaction> Because we have not called commit on the specifically, it is automatically committed when the <cftransaction>...
  • Page 591 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM * @persistent * @table Users component{ property name="id" fieldtype="id" datatype="int" generator="native"; property string fname; property string lname; property name="version" fieldtype="version" datatype="int" ; Whenever a user object is updated, its version number is automatically incremented. The version number is used in the SQL update statement in such a way that updating proceeds only when the version number has not been changed by some other request or some other application.
  • Page 592: Performance Optimization

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM * @persistent * @table Users * @optimistic-lock all component{ property name="id" fieldtype="id" datatype="int" generator="native"; property string fname; property string lname; Apart from defining optimistic lock control at the CFC level, you can also define it at the property level using ' (true|false: default true) attribute.
  • Page 593 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM With this strategy, on loading the artists object, its art object is loaded immediately using a separate SQL query. As a result, this strategy is extremely vulnerable to 'N+1 Select problem'. Lazy fetching In this strategy, the associated object or collection is fetched only when required. Although you need to send a new request to the database each time you need data, this strategy controls how much of data is loaded and when is it loaded.
  • Page 594 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfproperty name="artist" fieldtype="many-to-one" cfc="artist" fkcolumn="artistId" lazy="true"> Important: An entity is loaded only once in the request (in Hibernate session) and there is always only one copy of it in the request. So, for artwork and artist relationship, which is lazy, if the artist is already loaded, calling will not create a proxy object and will return the loaded artist object.
  • Page 595 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM One important thing to understand here is that here does not mean that 10 artworks are loaded at one batchsize time for a artist. It actually means that 10 artwork collections (artworks for 10 artists) are loaded together. When you call on the first artist, artworks for 9 other artists are also fetched along with the one that was getarts()
  • Page 596 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <cache name="Artist" maxElementsInMemory="20" eternal="true" overflowToDisk="false" /> </ehcache> Modifications to ehcache.xml in ColdFusion 9.0.1 ehCache.xml includes the following configuration properties: • : Size to allocate the DiskStore for a spool buffer. diskSpoolBufferSizeMB The default size is 30 MB.
  • Page 597 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM After you have configured the secondary cache, it is critical to identify the objects in your application that can be cached because the data cached by secondary cache is shared by all the sessions of an application. Typically, caching should be enabled for a CFC that represents: •...
  • Page 598 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Cache the association data of a persistent object In this case, the primary key of the associated objects are cached. It does not cache the objects loaded as part of the association unless caching is enabled for those objects. To cache an association, specify the following attributes on the association property.
  • Page 599 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Step 3: <cfscript> //This will cache the Artist Component and also the association. It wouldn't cache the Art objects. artistObj = EntityLoad("CArtists", 3, true); //This will cache the query. availableArts = ORMExecuteQuery("from CArt where issold=0", {}, false, {cacheable=true, cachename="availableArtsCache"});...
  • Page 600: Orm Session Management

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Edit ehCache.xml (cfroot/lib)to set the properties for user-defined caches as shown in the following example: <!--- item to put in user-defined cache ---> <cfset currentTime = Now()> <!--- put item in user-defined cache ---> <cfset timeToLive=createtimespan(0,0,0,30)>...
  • Page 601: Event Handling In Cfc

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM In multiple data source scenarios supported in ColdFusion 9 Update 1, there are multiple sessions (one for each data source) in the same request. For all entity functions, the appropriate sessions are used transparently. ColdFusion exposes a few methods to let CFML developers work with the Hibernate sessions directly.
  • Page 602 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Event handling in a persistent CFC A persistent CFC can have various methods and if these methods are present, callbacks can be sent on those events to the CFC. The CFC can then handle these events. In this case, the event for entity persistence comes to the CFC that the system loads, inserts, updates, or deletes.
  • Page 603: Autogenerating Database Schema

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Note: If event handlers are defined in both persistent CFC and event handler CFC, the persistent CFC is given the callback before calling the application wide event handler. Autogenerating database schema ColdFusion automatically creates tables when ORM is initialized for the application. For auto-generating tables, do the following: In the THIS scope of Application.cfc, in struct, set the...
  • Page 604 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM <cfcomponent persistent="true" table="Art"> <cfproperty name="artid" generator="identity" fieldtype="id"> <cfproperty name="artname" ormtype="string" length="50"> <cfproperty name="price" ormtype="double"> <cfproperty name="largeimage" ormtype="string" length="30"> <cfproperty name="mediaid" ormtype="integer" length="10"> <cfproperty name="issold" ormtype="boolean" dbdefault=1> <cfproperty name="artist" fkcolumn="artistid" fieldtype="many-to-one" cfc="CArtists"> </cfcomponent> Naming strategy When you build a database centric application, typically you would follow some database standard and naming convention.
  • Page 605 This interface is specified in the application using: this.ormsettings.namingstrategy="com.adobe.UCaseStrategy" Note: The naming strategy applies to all the table or column names, which you use in the mapping including link table and fkcolumn, even though there is no CFC or cfproperty associated with them.
  • Page 606: Support For Multiple Data Sources For Orm

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM Support for multiple data sources for ORM Note: This feature applies only if you have installed ColdFusion 9 Update 1. Introduction You can use multiple data sources for ORM in ColdFusion applications. A multiple data source setup is useful in scenarios where your application has multiple modules that interact with each other.
  • Page 607 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM ORM settings The following are the data source-specific ORM settings for which you can specify string or struct values in the Application.cfc: • schema • catalog • dialect • dbcreate • sqlscript For multiple data sources, a struct can be specified with data source name as the key and the appropriate setting as the value.
  • Page 608 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM index.cfm <cfoutput>Original Data<br></cfoutput> <cfset artistObj = EntityLoad("artists", 1, true)> <cfoutput>#artistObj.getArtistID()# | #artistObj.getFirstName()# | #artistObj.getLastName()#<br></cfoutput> <cfset artObj = artistObj.getart()> <cfoutput>#artObj[1].getartname()# <br></cfoutput> <cfset authorObj = EntityLoad("authors", 1, true)> <cfoutput>#authorObj.getFirstName()#</cfoutput> <cfoutput>#authorObj.getLastName()#</cfoutput> ORM Function enhancements Multiple data source support impacts the following ORM functions: ORMGetSession Description Returns the Hibernate session associated with the data source in the request.
  • Page 609 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM ORMFlush Description Flushes the Hibernate session associated with the data source in the request. ORMFlush flushes all pending CRUD operations in the request. Any changes made in the objects, in the current ORM session, are saved to the database. If you do not specify the data source, the Hibernate session associated with the default data source is flushed.
  • Page 610 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion ORM ORMEvictQueries Description This method is used to evict the data of all the queries from the default query cache of the specified data source. If cache name is specified, then the data of all queries belonging to the cache region with the given cache name are evicted. If no data source is specified, the default query cache of the default data source is evicted.
  • Page 611: Chapter 9: Flex And Air Integration In Coldfusion

    ColdFusion Using the Flash Remoting Service Using the Flash Remoting service of Adobe ColdFusion, ColdFusion developers can work together with Flash designers to build dynamic Flash user interfaces for ColdFusion applications. For a complete description of Flash Remoting capabilities, including how ColdFusion interacts with Flash Remoting, see Using Flash Remoting MX 2004 and Flash Remoting ActionScript Dictionary in Flash Help.
  • Page 612 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion The following is a simplified representation of the relationship between Flash and ColdFusion: SWF files .SWFs Mobile phone Computer Interactive TV HTTP Application Server services Flash Remoting Database Planning your SWF application When you are planning ColdFusion application development with Flash UIs, remember the importance of separating display code from business logic.
  • Page 613 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion To use the Flash Remoting service with ColdFusion, you build ColdFusion pages and components or deploy Java objects. In ColdFusion pages, you use the Flash variable scope to interact with SWF applications. ColdFusion components (CFCs) natively support Flash interaction.
  • Page 614 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion ColdFusion MX 7 and later versions of ColdFusion configure Flash gateways differently from previous ColdFusion releases. Parameters that worked before this release are no longer supported, and you specify all configuration parameters in the gateway-config.xml file.
  • Page 615 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Feature Description service adapters By default, the PageableResultSetAdapter, the ColdFusionAdapter, the CFCAdapter (for ColdFusion components), and the CFSSASAdapter (for server-side ActionScript) adapters are enabled in ColdFusion. You can also enable the JavaBeanAdapter, JavaAdapter, EJBAdapter, ServletAdapter, and CFWSAdapter (for web services) by removing their enclosing comment symbols (<!- - and -->).
  • Page 616 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Feature Description logger level You can set the level of logging between None Error Info Warning , and Debug . The following tag is the default logger level tag: <logger level="Error">coldfusion.flash.ColdFusionLogger</logger> redirect URL In the <redirect-url>...
  • Page 617 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion ActionScript data type ColdFusion data type ActionScript Object Structure ActionScript Object (as the only argument passed to a service Arguments of the service function. ColdFusion pages (CFM files): flash function) variable scope, ColdFusion components (CFC files): named arguments Null Null (...
  • Page 618 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Collection ActionScript example Notes Strict array var myArray:Array = new Array(); The Flash Remoting service converts the Array argument to a myArray[0] = "zero"; ColdFusion array. All CFML array operations work as expected. myArray[1] = "one";...
  • Page 619 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Create a ColdFusion page, and save it as helloWorld.cfm in the helloExamples directory. Modify helloWorld.cfm so that the CFML code appears as follows: <cfset tempStruct = StructNew()> <cfset tempStruct.timeVar = DateFormat(Now ())> <cfset tempStruct.helloMessage = "Hello World">...
  • Page 620 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Modify getData.cfm so that the code appears as follows: <cfparam name="pagesize" default="10"> <cfif IsDefined("Flash.Params")> <cfset pagesize = Flash.Params[1]> </cfif> <cfquery name="myQuery" datasource="cfdocexamples"> SELECT * FROM tblParks </cfquery> <cfset Flash.Pagesize = pagesize> <cfset Flash.Result = myQuery>...
  • Page 621 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Using Flash with CFCs CFCs require little modification to work with a SWF application. The tag tag names the method and cffunction contains the CFML logic, the tag names the arguments, and the cfreturn tag returns the result to the SWF cfargument application.
  • Page 622 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion import mx.remoting.*; import mx.services.Log; import mx.rpc.*; // Connect to the Flash component service and create service object var CFCService:Service = new Service( "http://localhost/flashservices/gateway", null, "helloExamples.flashComponent", null, null ); // Call the service helloWorld() method var pc:PendingCall = CFCService.helloWorld();...
  • Page 623 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion package utils; public class UIComponents public UIComponents() public String sayHello() return "Hello"; Note: You cannot call constructors with Flash Remoting. Use the default constructor. In ActionScript, the following call runs the public method of the class: javaService...
  • Page 624: Using Flash Remoting Update

    Using Flash Remoting Update You can use Flash Remoting Update to create Rich Internet Applications by using Adobe ColdFusion with Adobe Flash Builder or earlier versions of Flex Builder, with the advanced data retrieval features of ColdFusion, such as the , and tags.
  • Page 625 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Note: With ColdFusion 9, you will need to install LiveCycle Data Services 2.6.1 manually because it is not available as an option with the ColdFusion installer. However, ColdFusion 9 is available with the BLAZE DS installation, which allows messaging support.
  • Page 626 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Select one of the radio buttons, as follows: • Select ColdFusion Flash Remoting to compile in Flex Builder. • If you installed LiveCycle Data Services and want to compile the application on the server, select LiveCycle Data services in Flex Builder 3.
  • Page 627 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion You do not have to use the ColdFusion destination if you have configured other valid destinations in the configuration file. In this case, the destination definition must specify as the value of its element.
  • Page 628 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <channel-definition id="my-cfamf" class="mx.messaging.channels.AMFChannel"> <endpoint uri="http://{server.name}:{server.port}{context.root}/flex2gateway/" class="coldfusion.flash.messaging.CFAMFEndPoint" /> <properties> <polling-enabled>false</polling-enabled> <serialization> <enable-small-messages>false</enable-small-messages> </serialization> <coldfusion> <access> <use-mappings>true</use-mappings> <method-access-level>remote</method-access-level> </access> <use-accessors>true</use-accessors> <use-structs>false</use-structs> <property-case> <force-cfc-lowercase>false</force-cfc-lowercase> <force-query-lowercase>false</force-query-lowercase> <force-struct-lowercase>false</force-struct-lowercase> </property-case> </coldfusion> </properties> </channel-definition> Restart the ColdFusion server. The following table describes the XML attributes for remoting-config.xml: Element Description...
  • Page 629 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Elements Description use-accessors Whether the Value Object CFC has getters and setters. Set the value of use-accessors to true if there are getters and setters in the Value Object CFC. Set the value of use-structs to true if you don't require any translation of ActionScript to CFCs.
  • Page 630: Offline Air Application Support

    DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Compile and run the application using Flash Builder To compile and run an application using Flash Builder, make sure that Flash Builder is configured as described in “Configure Flex Compilation” on page 620. Compile your application normally to create a SWF file. When you configure your Flash Builder project you can specify the location in which to place it.
  • Page 631 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion To manage interactions with the AIR application and keep the data synchronized, ColdFusion application uses a component called the SyncManager. The SyncManager implements the CFIDE.AIR.ISyncManager interface. The component has two functions: •...
  • Page 632 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion • In case of a conflict, the function returns an array of objects to the client. There are sync "CFIDE.AIR.Conflict" four properties a conflict object can have: operation serverobject clientobject originalobject property of the conflict object must be a user-defined CFC type that represents the server-side serverobject...
  • Page 633 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion package test.basic [Bindable] [RemoteClass(alias="AIRIntegration.employee")] [Entity] public class Employee /** The user id of the employee **/ [Id] public var id:int; public var firstName : String; public var lastName : String; public var displayName : String;...
  • Page 634: Client Side

    DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion private var name:String; // Private property [Column(name="FNAME",columnDefinition="VARCHAR")] public function set fname(name:String):void // accessor function this.name = name; public function get fname():String // accessor function return name; Client Side ColdFusion 9 extends offline application support to the client side of the application by letting you code ActionScript elements on the client side.
  • Page 635 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion tag specifies the foreign key column and all the attributes of the column tag. Do not specify [JoinColumn] for both the entities in the relationship. For example, in the one-to-one relationship between the [JoinColumn] Department and Employee objects, specify only for one of the entities depending on the direction of...
  • Page 636 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion public class Employee [Id] [Column(name="ID")] var id:uint; [ManyToMany(targetEntity="Department", fetchType="EAGER|LAZY(default)")] [JoinTable(name="EMP_DEPT")] [JoinColumn(name="EMPID", referencedColumnName="ID")] [InverseJoinColumn(name="DEPID", referencedColumnName="DEPTID")] var depts:ArrayCollection; The default value is . See “Lazy loading and fetch type” on page 631 for information on fetch types. fetchType LAZY For a many-to-many relationship, you specify metadata like the following only on one of the entities and not both.
  • Page 637 ActionScript 3.0 Reference. Alternatively, you can see the standalone Adobe ColdFusion ActionScript Language Reference, which is accessible through the Documentation link on the Resources page of the ColdFusion Administrator. The AIR application init() function creates and configures a SyncManager instance, and fetches the initial data from...
  • Page 638 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion private function init():void syncmanager = new SyncManager(); //The ColdFusion server and port. Port without double quotes as it is //expected to be integer and IP is taken as String. syncmanager.cfPort = CFServerPort; syncmanager.cfServer = "CFServerIP";...
  • Page 639 For details on the session object methods, see ActionScript 3.0 Reference. Alternatively, you can see the standalone Adobe ColdFusion ActionScript Language Reference, which is accessible through the Documentation link on the Resources page of the ColdFusion Administrator.
  • Page 640 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion • If you call the Method and a record with the specified primary key doesn't exist, the function inserts SaveUpdate the record. The method updates an existing record only if the primary key exists in the client database. •...
  • Page 641 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion : An array of data that was in the client database before the change. There is no conflict in the originalobjects following circumstances: • If your are updating a record and the data on the server is same as the data in the originalobject. The client before the change had the same data as the server.
  • Page 642 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <cfelseif operation eq "DELETE"> <cfset obj = ORMGetSession().merge(originalobject)> <cfset EntityDelete(obj)> </cfif> <cfelse><!----Conflict---> <cflog text = "is a conflict"> <cfset conflict = CreateObject("component","CFIDE.AIR.conflict")> <cfset conflict.serverobject = serverobject> <cfset conflict.clientobject = clientobject> <cfset conflict.originalobject = originalobject>...
  • Page 643 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion • When the client does an update but that record no longer exists on the server. Again, a conflict can be passed to the client from the server by creating an instance of Conflict.cfc and returning it. There is no need to set a serverobject property, as there is no server instance of the inserted data.
  • Page 644 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Customer.as package onetoone [Bindable] [RemoteClass(alias="AIRIntegration.custome r")] [Entity] public class Customer [Id] public var cid:int; public var name: String; [OneToOne(cascadeType='ALL',fetchType="EAGER")] [JoinColumn(name="add_id",referencedColumnName="aid")] public var address:Address; Address.as package onetoone [Bindable] [RemoteClass(alias="AIRIntegration.address")] [Entity] public class Address [Id] public var aid:int;...
  • Page 645 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplic ation xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()"> <mx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.rpc.AsyncToken; import mx.controls.Alert; import coldfusion.air.events.*; import coldfusion.air.*; import onetoone.Address; import onetoone.Customer; private var session:Session; private var dbFile:File;...
  • Page 646 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion private function fetchSuccess(event:SyncResultEvent):void var cus:Array = event.result as Array; cusColl = new ArrayCollection(cus); // Open a Session for the client side SQLite DB dbFile = File.userDirectory.resolvePath("onetoonesync.db"); var sessiontoken:SessionToken =syncmanager.openSession(dbFile,017915); sessiontoken.addResponder(new mx.rpc.Responder(connectSuccess,connectFault));...
  • Page 647 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion private function savesuccess(event:SessionResultEvent):void Alert.show("Customer was Inserted Successfully"); // Load some otehr Customer(ex: id=11) so that we can perform Update on that Customer var loadtoken:SessionToken =session.loadByPK(Customer,{cid:11}); loadtoken.addResponder(new mx.rpc.Responder(loadCustomer,loadFault)) private function loadCustomer(event:SessionResultEvent):void var cus1:Customer = event.result as Customer;...
  • Page 648 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Alert.show("Server has been updated with local changes"); Now that you have completed all the operations, you can close the SQLite DB connection/session. It is a good practice to Close the session, after you complete all the operations.
  • Page 649 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Alert.show("Commit Failed::"+event.error); private function loadFault(event:SessionFaultEvent):void Alert.show("Load Failed::"+event.error); private function updatefualt(event:SessionFaultEvent):void Alert.show("update fault"+event.error); private function savefault(event:SessionFaultEvent):void Alert.show("Save Fault::"+event.error); ]]> </mx:Script> <mx:Button click="commit()" name="commitbutton" label="Commit/write local data to Server"> </mx:Button> </mx:WindowedApplication> Server-side code Create the following cfc files - Application.cfc, Customer.cfc, Address.cfc, and Cusmanager.cfc with code like the following.
  • Page 650 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Cusmanager.cfc <cfcomponent implements="CFIDE.AIR.ISyncManager"> <!----Fetch method---> <cffunction name="fetch" returnType="Array" access="remote"> <cfset cus = ArrayNew(1)> <cfset cus = EntityLoad("customer")> <cfreturn cus> </cffunction> <!----SYNC method---> <cffunction name="sync" returntype="any"> <cfargument name="operations" type="array" required="true"> <cfargument name="clientobjects" type="array" required="true"> <cfargument name="originalobjects"...
  • Page 651 Offline AIR application support in ColdFusion 9.0.1 The AIR integration feature introduced in ColdFusion 9 has an ActionScript ORM for persisting entities in the SQLite database present within Adobe Integrated Runtime (AIR). This release has the following enhancements for this ActionScript ORM: •...
  • Page 652 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Parameters Parameter Description strategy UUID uses the Flash UUID API to generate the ID (used for primary key of type string ) or INCREMENT (for primary key of type Applies only for INCREMENT strategy. Specifies the initial value of the primary key. The default value is 0. initialValue incrementBy Applies only for INCREMENT strategy.
  • Page 653 Using the EncryptionKeyGenerator class to obtain a secure EncryptionKeyGenerator, encryption key in Developing Adobe AIR 1.5 Applications with Flex. Specifying the cache directory The cache directory where you store the cache file can be specified using the...
  • Page 654 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Support for self joins Database table can be related to itself through a foreign key. A typical example is an Employee table with a manager relationship containing the employee id of the managers (who manage the employee). The manager id refers to another row in the same table.
  • Page 655 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion [ManyToMany(targetEntity="onetoone::Customer",fetchType="EAGER")] [JoinTable(name="CUSTOMER_PARENTS_MAPPINGS")] [JoinColumn(name="CUST_ID",referencedColumnName="cid")] [InverseJoinColumn(name="PARENT_ID",referencedColumnName="cid")] public var parents:Array; // Many-to-Many self Join [ManyToMany(targetEntity="onetoone::Customer",fetchType="EAGER")] [JoinTable(name="CUSTOMER_CHILDREN_MAPPINGS")] [JoinColumn(name="CUST_ID",referencedColumnName="cid")] [InverseJoinColumn(name="CHILD_ID",referencedColumnName="cid")] public var children:Array; [OneToMany(targetEntity="onetoone::Order",cascadeType='REMOVE',mappedBy="customer",fetchType ="EAGER")] public var orders:Array; ArrayCollection to hold multiple entities In addition to Array, you can now use ArrayCollection to hold multiple entities in a database relationship. ArrayCollection can also be used in the ActionScript entities as Arrays are used to represent the related entities.
  • Page 656 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Logging SQL statements The ActionScript ORM logs all SQL statements that it executes. The log can be configured as follows: ❖ Add a log target for the AIR applications as shown in the following example: var logTarget:TraceTarget = new TraceTarget();...
  • Page 657 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Returns An instance of associated with call. coldfusion.air.SessionToken keepClientObject Syntax public function keepClientObject(conflict:coldfusion.air.Conflict):SessionToken Parameters Parameter Description coldfusion.air.Conflict The conflict that the server raises. Example See the example in the section keepAllClientObjects. For , the only difference is that you must keepClientObject iterate over each conflict in the conflictarray collection.
  • Page 658: Proxy Actionscript Classes For Coldfusion Services

    DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion the changes in the local database are committed to the server when the true, save saveUpdate, remove methods are used as shown here: private var syncmanager:SyncManager = new SyncManager(); syncmanager.autoCommit = true; This functionality helps you minimize the conflicts during the synchronization with the server, particularly in the case of auto-generation of primary key on client and serverside.
  • Page 659 For details on all ColdFusion service classes, and other classes in the coldfusion.air package, see ActionScript 3.0 Reference. Alternatively, you can see the standalone Adobe ColdFusion ActionScript Language Reference, which is accessible through the Documentation link on the Resources page of the ColdFusion Administrator.
  • Page 660 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Attribute Description cfContextRoot The context root if any for the CF server. secureHTTP Boolean value specifying whether to use http or https to run the service. destination The destination attribute can be used to specify a user defined remoting destination in WEB-INF/flex/remoting- config.xml.
  • Page 661 The following AIR application uses the Mail Service and file upload functionality. It refers to the CFCredentials.mxml file to reference the credentials of the user for authentication. Following is the CFCredentials.mxml file being used for the example: <?xml version="1.0" encoding="utf-8"?> <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" currentState="collapsed" toolTip="Double Click to Collapse/Expand" creationComplete="retrieveCredential()" headerHeight="5" layout="vertical" mouseDown="check Collapse(event )" resizeEffect="Resize"> <mx:Script>...
  • Page 662 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion if(cfserviceusername.text == "" && cfservicepassword.text == "") Alert.show("CF Service UserName and Password are not required to test CF server connectivity but they will be required while using the CF services","Note"); service.url = CF_HTTPURL;...
  • Page 663 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion cfcnxtrt.text = EncryptedLocalStore.getItem('CONTEXT').toString(); cfserviceusername.text = EncryptedLocalStore.getItem('USER').toString(); cfservicepassword.text = EncryptedLocalStore.getItem(' PASS').to String(); catch(e:Error) private function resetCredential():void EncryptedLocalStore.reset(); cfip.text = ""; cfprt.text = ""; cfcnxtrt.text = ""; cfserviceusername.text = "" cfservicepassword.text = ""; ]]>...
  • Page 664 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="com.*" creationComplete="init()" xmlns:cf="coldfusion.service.mxml.*"> <mx:Script> <![CDATA[ import coldfusion.service.events.*; import com.CFCredential; import mx.collections.ArrayCollection; import mx.binding.utils.BindingUtils; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.controls.Alert; import flash.events.*; import flash.net.FileReference; import flash.net.FileReferenceList;...
  • Page 665 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion private function browseFiles(event:Event):void filereflist.browse(fileTypes); called after user selects files form the browse dialogue box. private function selectHandler(event:Event):void {var i:int; for (i=0;i < event.currentTarget.fileList.length; i ++) fileslist.addItem(event.currentTarget.fileList[i]); attachList.text += event.currentTarget.fileList[i].name + ", ";...
  • Page 666 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Alert.show("Mail was delivered Successfully"); public function handleError(event:ColdFusionServiceFaultEvent):void Alert.show("Failure"+ event.toString()); ]]> </mx:Script> <mx:Panel width="100%" height="100%"> <local:CFCredential id="cred" /> <mx:ControlBar> <mx:Spacer width="100%"/> <mx:HBox> <mx:Button label="Send Mail" id="sendbutton"/> <mx:Button label="Attachment" id="attachbutton"/> </mx:HBox> </mx:ControlBar> <mx:VBox width="100%"...
  • Page 667 The Image class is the proxy for the ColdFusion Image service, which provides the functionality of the cfimage tag. You specify the required cfimage attributes for the action as Image tag attributes. The following examples show typical usage, in this case adding a border: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:cf="coldfusion.service.mxml.*" creationComplete="init()"> <mx:Script>...
  • Page 668 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <cf:Config id="configid" cfServer="127.0.0.1" cfPort="80" servicePassword="service" serviceUserName="service"/> <!-- Add border--> <cf:Image id="img" action="addborder" color="red" thickness="5" source="http://127.0.0.1:80/GetExifmetaData.jpg" result="handleResult(event)" fault="handleError(event)"/> <mx:Image id="retImage"/> </mx:Application> Batch operation A batch operation lets you perform multiple image manipulations on an image as part of one operation, instead of performing the operations individually.
  • Page 669 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <!-- Get Info--> <cf:Pdf id="pdftest" action="GETINFO" source="http://localhost:8500/lcds26_devguide_040908.pdf"/> <!-- Delete Pages--> <cf:Pdf id="pdftest1" action="deletepages" source="http://localhost:8500/lcds26_devguide_040908.pdf" pages="1" resultHandler="handleDeleteResult" errorHandler="handleDeleteError"/> <!-- Merge files--><cf:Pdf id="pdftest" action="mergeFiles" source="http://localhost:8500/lcds26_devguide_040908.pdf, http://localhost:8500/EC205W_JoelGeraci.pdf" resultHandler="handleMergeResult" errorHandler="handleMergeError"/> <!-- extract pages--> <cf:Pdf id="pdftest" action="extractpages" source="http://localhost:8500/lcds26_devguide_040908.pdf"...
  • Page 670 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion pdfParam="{pdfparams}" keepBookmark="true" resultHandler="handleExtractResult" errorHandler="handleExtractError"/> <!-- set info--> <cf:Pdf id="pdftest" action="setinfo" source="http://localhost:8500/1page.pdf" info="{elements}" resultHandler="handleExtractResult" errorHandler="handleExtractError"/> <!-- thumbnail--> <cf:Pdf id="pdftest" action="thumbnail" source="http://localhost:8500/EC205W_JoelGeraci.pdf" resultHandler="handleThumbnailResult" errorHandler="handleThumbnailError"/> <!-- ProcessDDX--> <cf:Pdf id="pdftest" action="processddx" ddxString="{ddx}" outputFiles="{outputFiles}" result="handleProcessDDXResult" fault="handleProcessDDXError"/>...
  • Page 671 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cf="coldfusion.service.mxml.*" creationComplete="init()"> <mx:Script> <![CDATA[ import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; [Bindable] public var chaSer:Array; public var chaDat:Array; function init():void chaDat = [{item:"Facilities",value:"35000"}, {item:"Facilities1",value:"32000"}]; chaSer = [{type:"bar",chartdata:chaDat}, {type:"line",chartdata:chaDat}];chartest.execute();...
  • Page 672 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion chartHeight = "500" chartWidth = "600" dataBackgroundColor = "yellow" font = "ariel" fontBold = "yes" fontItalic = "yes" fontSize = "12" foregroundColor = "red" gridLines = "2" labelFormat = "number" markerSize = "10"...
  • Page 673 <td><font size='-1'>John</font></td> <td align='right'><font size='-1'>Guess What</font></td></tr> <tr><td align='right'><font size='-1'>Total</font></td> <td align='right'><font size='-1'>Peanuts</font></td></tr>", documentitem:docItem},{content:"content2",documentitem:docItem}]; cfDoc.documentSection = docSectionItem; The following example shows some typical document use: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:cf="coldfusion.service.mxml.*" creationComplete="init()"> <mx:Script> <![CDATA[ import mx.controls.Alert; import mx.rpc.events.ResultEvent; import coldfusion.service.PdfParam;...
  • Page 674 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion //Alert.show("httpurl= "+event.result.toString()); private function handleError(event:Event):void mx.controls.Alert.show(event.toString()); ]]> </mx:Script> <cf:Config id="configid" cfServer="localhost" cfPort="80" servicePassword="service" serviceUserName="service" /> <!-- simple case--> <cf:Document id="doctestnow" action="generate" format="flashpaper" result="handleResult(event)" fault="handleError(event)" content="&lt;table&gt;&lt;tr&gt;&lt;td&gt;bird&lt;/td&gt;&lt;td&gt; 1&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;fruit&lt;/td&gt;&lt; td&gt;2&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;rose&lt;/td&gt; &lt;td&gt;3&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;"/> <!--doc item case --> <!--<cf:Document id="doctestnow"...
  • Page 675 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cf="coldfusion.service.mxml.*" creationComplete="init()"> <mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; import mx.controls.Alert; import coldfusion.service.events.*; public function init():void poptest.execute(); public function handleResult(event:ResultEvent):void Alert.show("Success" + event.toString()); public function handleError(event:FaultEvent):void Alert.show("Failure");...
  • Page 676: Using The Livecycle Data Services Es Assembler

    Using the LiveCycle Data Services ES Assembler To use Adobe ColdFusion as the back-end data manager for an Adobe Flex application, you use the Adobe LiveCycle Data Services ES assembler. You configure the LiveCycle Data Services ES assembler and write an application that uses the assembler.
  • Page 677 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion The following diagram shows the process that LiveCycle Data Services ES and ColdFusion use when a Flex application calls a method in a ColdFusion component: A Flash client requests data that the LiveCycle Data Management Service adapter handles. Flex calls a , or method in the Data Service.
  • Page 678 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Create the Flex application, in which you define a DataService component in MXML or ActionScript. The DataService component calls methods on a server-side Data Management Service destination to perform activities such as filling client-side data collections with data from remote data sources and synchronizing the client and server versions of data.
  • Page 679 INF\Flex\ WEB-INF\ flex\jar\cfdataserviceadapter.jar For detailed steps on integrating LCDS2.5 with ColdFusion, see the technote on www.adobe.com. Another case here could be that you have integrated LCDS 2.6.1 with ColdFusion 9 and still you want to use old Flash Remoting. You can implement this scenario, but in this case you cannot take advantages offered by enhanced Flash Remoting.
  • Page 680 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Channel-definition ColdFusion 9 Endpoint Class ColdFusion 8 Endpoint Class my-cfamf coldfusion.flash.messaging.CFAMFEndPoint flex.messaging.endpoints.AMFEndpoint cf-polling-amf coldfusion.flash.messaging.CFAMFEndPoint flex.messaging.endpoints.AMFEndpoint my-cfamf-secure coldfusion.flash.messaging.SecureCFAMFEnd flex.messaging.endpoints.SecureAMFEn Point dpoint cf-rtmp coldfusion.flash.messaging.CFRTMPEndPoint flex.messaging.endpoints.RTMPEndpoin Note: For LiveCycle Data Services ES, the cf-polling-amf and cf-rtmp channel definitions are used. •...
  • Page 681 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <channel-definition id="cf-polling-amf" class="mx.messaging.channels.AMFChannel"> <endpoint url="http://{server.name}:{server.port}{context.root}/ flex2gateway/cfamfpolling" class="flex.messaging.endpoints.AMFEndpoint"/> <properties> <polling-enabled>true</polling-enabled> <serialization> <instantiate-types>false</instantiate-types> </serialization> </properties> </channel-definition> <channel-definition id="cf-rtmp" class="mx.messaging.channels.RTMPChannel"> <endpoint url="rtmp://{server.name}:2048" class="flex.messaging.endpoints.RTMPEndpoint"/> <properties> <idle-timeout-minutes>20</idle-timeout-minutes> <serialization> <!-- This must be turned off for any CF channel --> <instantiate-types>false</instantiate-types>...
  • Page 682 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <properties> <idle-timeout-minutes>20</idle-timeout-minutes> <serialization> <enable-small-messages>false</enable-small-messages> </serialization> <coldfusion> <access> <use-mappings>true</use-mappings> <method-access-level>remote</method-access-level> </access> <use-accessors>true</use-accessors> <use-structs>false</use-structs> <property-case> <force-cfc-lowercase>false</force-cfc-lowercase> <force-query-lowercase>false</force-query-lowercase> <force-struct-lowercase>false</force-struct-lowercase> </property-case> </coldfusion> </properties> </channel-definition> Specifying ColdFusion-specific channel definitions LiveCycle Data Services ES transports messages to and from destinations over message channels that are part of the Flex messaging system.
  • Page 683 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Element Description Define the resolution rules and access level of the CFC being invoked access use-accessors Whether the Value Object CFC has getters and setters. Set the value of use- accessors true if there are getters and setters in the Value Object CFC.
  • Page 684 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Element Description scope The scope, which can be application session , or request . The application value specifies that there is only one instance; request specifies that there is a new CFC for each call. ColdFusion does not support session .
  • Page 685 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <!--Optional, If the Assembler fill routine returns a query,you must define an Actionscript type for the rows.--> <query-row-type>samples.contact.Contact</query-row-type> </metadata> <network> <!-- Add network elements here--> </network> <server> <!-- The method declarations are ignored for CFC Assemblers, with the exception of the fill-method settings.
  • Page 686 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion You place the database manipulation functionality directly in the methods in the assembler CFC and create a Value Object CFC, which is a CFC that contains property definitions and related methods.
  • Page 687 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <cffunction name="fill" output="no" returntype="query" access="remote"> Array of structures: <cffunction name="fill" output="no" returntype="array" access="remote"> In addition to specifying the returntype of the function depending on whether you are using Value Objects, a fill query, or an array of structures, you also do the following in the lower level function:...
  • Page 688 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion • Ensure that the query column names match the case of the properties in the ActionScript object. Use the settings in the destination to do so. Set the element to so that property-case force-query-lowercase...
  • Page 689 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion method has the following arguments: fillContains • is a list of arguments to pass to the method. fillArgs fill • is the record to check to determine if it is in the result set. item •...
  • Page 690 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <cffunction name="get" output="no" returnType="samples.contact.Contact" access="remote"> <cfargument name="uid" type="struct" required="yes"> <cfset key = uid.contactId> <cfset ret=variables.dao.read(id=key)> <cfreturn ret[1]> </cffunction> The returntype of a method can be any of the following: • The Value Object CFC •...
  • Page 691 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <cffunction name="count" output="false" access="public" returntype="Numeric"> <cfargument name="id" required="false"> <cfargument name="param" required="false"> <cfset var qRead=""> <cfquery name="qRead" datasource="FDSCFCONTACT"> select COUNT(*) as totalRecords from Contact </cfquery> <cfreturn qRead.totalRecords> </cffunction> Notifying the Flex application when data changes You use the LiveCycle Data Services ES event gateway type provided with ColdFusion, to have ColdFusion applications notify Flex when data that a destination manages has changed.
  • Page 692 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion <destination id="cfcontact"> <adapter ref="coldfusion-dao" /> <channels> <channel ref="cf-dataservice-rtmp" /> </channels> <properties> <source>samples.contact.ContactAssembler</source> <scope>application</scope> <remote-username>wilsont</remote-username> <remote-password>password</remote-password> /properties> </destination> Enabling SSL You encrypt communication between ColdFusion and Flex by enabling Secure Sockets Layer (SSL). Enabling SSL only makes sense if you are running LiveCycle Data Services ES remotely.
  • Page 693: Using Server-Side Actionscript

    If you specify an invalid keystore file or password, ColdFusion does not enable SSL, and disables Flex Data Management Support. Data translation The following table lists the ColdFusion data types and the corresponding Adobe Flash or ActionScript data type: ColdFusion data type Flash data type...
  • Page 694 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion About server-side ActionScript ColdFusion includes a module called the Flash Remoting service that acts as a broker for interactions between Flash and ColdFusion. Flash Remoting supports a range of object types, and lets you reference an ActionScript file that lives on a ColdFusion server.
  • Page 695 • Adobe Flash • ColdFusion • Flash Remoting Components For more information about these products, go to www.adobe.com. Location of server-side ActionScript files You can place ActionScript files ( ) on the server anywhere below the root directory of the web server. To specify *.asr...
  • Page 696 Service” on page 606 and Using Flash Remoting. Connecting to the Flash Remoting service Before you can use functions defined in your server-side ActionScript files, connect the Adobe SWF movie to the server-side Flash Remoting service. Create a Flash Remoting service connection Include the necessary ActionScript classes in the first frame of the SWF movie that uses server-side ActionScript functions.
  • Page 697 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Using server-side ActionScript functions After you connect to the Flash Remoting service, you call functions that are defined in your server-side ActionScript files, and return results. Call a function Create an instance of the server-side ActionScript file using the function.
  • Page 698 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion For more information, see “Using the CF.query function” on page 694. Using results returned by the CF.http function server-side ActionScript function returns data as simple text. You write server-side functions that CF.http reference the properties available in the object returned by the function.
  • Page 699 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Publishing dynamic data You use the server-side ActionScript feature in ColdFusion to publish dynamic data. To do this, you write server-side ActionScript files that perform queries against ColdFusion data sources. Before using ActionScript, you must understand how to do the following: •...
  • Page 700 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion About CF.query function syntax You can write the ActionScript function using either named arguments or positional arguments. The CF.query named argument style is more readable, but it requires more code. Although the positional argument style supports a subset of arguments, it allows a more compact coding style that is more appropriate for simple expressions CF.query...
  • Page 701 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Method Description getLength Returns the total number of records in a RecordSet object getNumberAvailable Returns the number of records that have been downloaded from the server isFullyPopulated Determines whether a RecordSet object can be edited or manipulated isLocal Determines whether a RecordSet object is local or server-associated removeAll...
  • Page 702 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Define a search function that sends user data to the Flash Remoting service. See “Submitting user data to the Flash Remoting service” on page 697. Define a result function that captures the results returned from the Flash Remoting service. See “Capturing Flash Remoting service results”...
  • Page 703 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion #include "NetServices.as" function search() // The search() method is defined in the server-side AS file directoryService.search(firstName.text, lastName.text); dataView.setDataProvider(null); status.text = "waiting..."; Reviewing the code The following table describes the code and its function: Code Description Passes the contents of the firstName and lastName text boxes to server-side...
  • Page 704 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Checking for a Flash Remoting service connection To ensure that the SWF movie is connected to the Flash Remoting service, you use an statement; for example: if (inited == null) inited = true;...
  • Page 705 Raw response header. The following is an example header: HTTP/1.1 200 OK Date: Mon, 04 Mar 2002 17:27:44 GMT Server: Apache/1.3.22 (Unix) mod_perl/1.26 Set-Cookie: MM_cookie=207.22.48.162.4731015262864476; path=/; expires=Wed, 03-Mar-04 17:27:44 GMT; domain=.adobe.com Connection: close Content-Type: text/html Filecontent File contents, for text and MIME files. Mimetype MIME type.
  • Page 706 DEVELOPING COLDFUSION 9 APPLICATIONS Flex and AIR Integration in ColdFusion Parameter Description name The variable name for data that is passed type Transaction type: • • FormField • Cookie • • File value Value of URL, FormField, Cookie, File, or CGI variables that are passed In the following example, the function passes HTTP parameters in an array of objects:...
  • Page 707 CF.http // Returns content of URL defined in url variable // This example uses positional argument style function get() url = "http://www.adobe.com/software/coldfusion/"; //Invoke with just the url argument. Get is the default. result = CF.http(url); return result.get("Filecontent"); For more information about function properties, see CF.http in the CFML Reference.
  • Page 708: Chapter 10: Requesting And Presenting Information

    Introduction to Retrieving and Formatting Data Adobe ColdFusion lets you retrieve and format data. You can use forms to get user data and control the data that a dynamic web page displays. You can also populate a table with query results and use ColdFusion functions to format and manipulate data.
  • Page 709 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information elements as Flash items in an otherwise-HTML form. For more information on Flash forms and form elements, see “Creating Forms in Flash” on page 765. ColdFusion can generate XML forms and apply XSLT skins to format the forms. XML format XML Skinable forms forms let you separate the form presentation from the form logic and data field information.
  • Page 710 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Control Code Check box <cfinput type="Checkbox" name="ControlName" value="Yes|No">Yes Reset button <cfinput type="Reset" name="ControlName" value="DisplayName"> Submit button <cfinput type="Submit" name="ControlName" value="DisplayName"> The following listing shows the form source in detail. To test the form and use it as input for later examples, save this code as formpage.cfm.
  • Page 711 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfinput type="radio" name="Department" value="Training">Training<br> <cfinput type="radio" name="Department" value="Sales">Sales<br> <input type="radio" name="Department" value="Marketing">Marketing<br> </p> <!--- Check box. ---> <p> Contractor? <cfinput type="checkbox" name="Contractor" value="Yes" checked>Yes </p> <!--- Reset button. ---> <cfinput type="Reset" name="ResetForm" value="Clear Form"> <!--- submit button --->...
  • Page 712 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information On the action page, the form variables are in the Form scope, prefix them with “Form.” to explicitly tell ColdFusion that you are referring to a form variable. For example, the following code references the LastName form variable for output on an action page: <cfoutput>...
  • Page 713 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Retrieving Employee Data Based on Criteria from Form</title> </head> <body> <cfquery name="GetEmployees" datasource="cfdocexamples"> SELECT FirstName, LastName, Salary FROM Employee WHERE LastName=<cfqueryparam value="#Form.LastName#" CFSQLType="CF_SQL_VARCHAR"> </cfquery> <h4>Employee Data Based on Criteria from Form</h4> <cfoutput query="GetEmployees">...
  • Page 714 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Code Description #FirstName# Displays the value of the FirstName, LastName, and Salary fields for a #LastName# record, starting with the first record, then goes to the next line. Keeps #Salary#<br> displaying the records that match the criteria you specified in the SELECT statement, followed by a line break, until you run out of records.
  • Page 715 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfinput type="Text" name="FirstName" size="20" maxlength="35" required="Yes" message="You must enter your first name."> If you use a hidden field tag, you customize the message using the attribute of the hidden field, as follows: value <input type="hidden"...
  • Page 716 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Retrieving Employee Data Based on Criteria from Form</title> </head> <body> <cfquery name="GetEmployees" datasource="cfdocexamples"> SELECT FirstName, LastName, Salary FROM Employee WHERE LastName=<cfqueryparam value="#Form.LastName#" CFSQLType="CF_SQL_VARCHAR"> </cfquery> <h4>Employee Data Based on Criteria from Form</h4> <table>...
  • Page 717 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Code Description <tr> For each record in the query, creates a row in the table, with three columns that <td>#FirstName#</td> display the values of the FirstName, LastName, and Salary fields of the record. <td>#LastName#</td>...
  • Page 718 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Retrieving Employee Data Based on Criteria from Form</title> </head> <body> <cfquery name="GetEmployees" datasource="cfdocexamples"> SELECT Departmt.Dept_Name, Employee.FirstName, Employee.LastName, Employee.StartDate, Employee.Salary FROM Departmt, Employee WHERE Departmt.Dept_ID = Employee.Dept_ID <cfif IsDefined("Form.Department")> AND Departmt.Dept_Name=<cfqueryparam value="#Form.Department#" CFSQLType="CF_SQL_VARCHAR">...
  • Page 719 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Code Description SELECT Departmt.Dept_Name, Retrieves the fields listed from the Departmt and Employee tables, joining the Employee.FirstName, tables based on the Dept_ID field in each table. Employee.LastName, Employee.StartDate, Employee.Salary FROM Departmt, Employee WHERE Departmt.Dept_ID = Employee.Dept_ID <cfif IsDefined("Form.Department")>...
  • Page 720 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Retrieving Employee Data Based on Criteria from Form</title> </head> <body> <cfquery name="GetEmployees" datasource="cfdocexamples"> SELECT Departmt.Dept_Name, Employee.FirstName, Employee.LastName, Employee.StartDate, Employee.Salary FROM Departmt, Employee WHERE Departmt.Dept_ID = Employee.Dept_ID <cfif isdefined("Form.Department")> AND Departmt.Dept_Name = <cfqueryparam value="#Form.Department#" CFSQLType="CF_SQL_VARCHAR">...
  • Page 721 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Returning results incrementally You can use the tag to incrementally display long-running requests to the browser before a ColdFusion page cfflush is fully processed. This tag lets you give the user quick feedback when it takes a long time to complete processing a request.
  • Page 722 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Your Magic numbers</title> </head> <body> <h1>Your Magic numbers</h1> <P>It will take us a little while to calculate your ten magic numbers. It takes a lot of work to find numbers that truly fit your personality. So relax for a minute or so while we do the hard work for you.</P>...
  • Page 723 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Dynamically populating list boxes The code in “Creating a basic form” on page 704 hard-coded the form’s list box options. Instead of manually entering the information on a form, you can dynamically populate a list box with database fields. When you write code this way, the form page automatically reflects the changes that you make to the database.
  • Page 724 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Department:<br> <cfinput type="radio" name="Department" value="Training">Training<br> <cfinput type="radio" name="Department" value="Sales">Sales<br> <cfinput type="radio" name="Department" value="Marketing">Marketing<br> <cfinput type="radio" name="Department" value="HR">HR<br> </p> <!--- Check box. ---> <p> Contractor? <cfinput type="checkbox" name="Contractor" value="Yes" checked>Yes </p> <!--- Reset button. ---> <cfinput type="reset"...
  • Page 725 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Note: If the user does not select a check box or make a selection from a list box, no variable is created. The cfinput tags do not work correctly if there are no values. To prevent errors, make the form fields required, use dynamic cfupdate SQL, or use the tag to set a default value for the form field.
  • Page 726 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The first example searched for department information based on a numeric primary key field called Dept_ID. Suppose, instead, that the primary key is a database field called Dept_Name that contains string values. In that case, your code for check boxes should look like the following: <cfinput type="checkbox"...
  • Page 727: Building Dynamic Forms With Cfform Tags

    DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Select one or departments to get more information on: <cfselect name="SelectDepts" multiple> <option value="1">Training <option value="2">Marketing <option value="3">HR <option value="4">Sales </cfselect> If the user selects the Marketing and Sales items, the value of the SelectDepts form field is 2,4. If this parameter is used in the following SQL statement: SELECT * FROM Departmt...
  • Page 728 Linux. Lets you specify an Extensible Stylesheet Language Transformation (XSLT) skin that converts the XML into styled HTML output. Adobe ColdFusion provides several skins that you can use, and you can write your own custom skins and support custom controls.
  • Page 729 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Control Description For more information cfinput Equivalent to the HTML input tag, with the addition of input validation. “Creating a basic form” on page 704 cfselect Displays a selection box. Equivalent to the HTML tag, with the “Building drop-down list boxes”...
  • Page 730 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Because the controls use JavaScript to return data to ColdFusion, if you disable JavaScript in your browser, it cannot properly run forms that contain these controls. In that case, the controls still display, but data return and validation does not work and you can receive a JavaScript error.
  • Page 731 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Reviewing the code The following table describes the highlighted code and its function: Code Description Creates a tree and names it tree1. <cftree name="tree1" required="Yes" Specifies that a user must select an item in the tree. Does not allow horizontal scrolling.
  • Page 732 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Save the page and view it in your browser. Reviewing the code The following table describes the highlighted code and its function Code Description ORDER BY Dept_ID Orders the query results by department. Populates the tree with the department ID, and under each department, the full <cftreeitem value="Dept_ID,FullName"...
  • Page 733 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Structuring tree controls Tree controls built with the tag can be complex. Knowing how to specify the relationship between multiple cftree entries helps you handle the most complex constructs. cftreeitem cftree Creating a one-level tree control The following example consists of a single root and some individual items: <cfquery name="deptquery"...
  • Page 734 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfform name="form2" action="cfform_submit.cfm"> <cftree name="tree1" hscroll="No" vscroll="No" border="No"> <cftreeitem value="Divisions"> <cftreeitem value="Development" parent="Divisions" img="folder"> <cftreeitem value="Product One" parent="Development" img="document"> <cftreeitem value="Product Two" parent="Development"> <cftreeitem value="GUI" parent="Product Two" img="document"> <cftreeitem value="Kernel" parent="Product Two" img="document"> <cftreeitem value="Product Three"...
  • Page 735 <cfform action="submit.cfm"> <cftree name="oak" highlighthref="Yes" height="100" width="200" hspace="100" vspace="6" hscroll="No" vscroll="No" border="No"> <cftreeitem value="Important Links"> <cftreeitem value="Adobe Home" parent="Important Links" img="document" href="http://www.adobe.com"> <cftreeitem value="ColdFusion Developer Center" parent="Important Links" img="document" href="http://www.adobe.com/devnet/coldfusion/"> </cftree> </cfform> Save the page and view it in your browser.
  • Page 736 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Code Description Makes the node of the tree a link. href="http://www.adobe.com"> href="http://www.adobe.com/devnet/mx/coldfu Makes the node of the tree a link. sion/"> Although this example does not show it, the href attribute can refer to the name of a column in a query if that query populates the tree item.
  • Page 737 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Save the file as selectbox.cfm and view it in your browser. Because the tag includes the attribute, the user can select multiple entries in the list box. Also, because the multiple tag specifies Emp_ID, the primary key for the Employee table, Employee IDs (not first names) get passed in the value Form.Employee variable to the application page specified in the attribute.
  • Page 738 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Just as the tag uses the tag, the tag uses the tags. You can cftree cftreeitem cfgrid cfgridcolumn cfgridrow define a wide range of row and column formatting options, as well as a column name, data type, selection options, and so on.
  • Page 739 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Reviewing the code The following table describes the highlighted code and its function: Code Description Creates a grid named employee_grid and populate it with the <cfgrid name="employee_grid" query="empdata" results of the query empdata. If you specify a cfgrid tag with a query attribute defined and no corresponding cfgridcolumn attributes, the grid contains all the columns in the query.
  • Page 740 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information How user edits are returned When a user inserts or deletes a row in a grid or changes any cells in a row and submits the grid, ColdFusion creates the following arrays as Form variables: Array name Description gridname.colname...
  • Page 741 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Example: editing data in a grid The following example creates an editable grid. For code brevity, the example handles only three of the fields in the Employee table. A more realistic example would include, at a minimum, all seven table fields. It can also hide the contents of the Emp_ID column or display the Department name (from the Departmt table), instead of the Department ID.
  • Page 742 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Code Description <cfgrid name="employee_grid" Populates a cfgrid control with data from the empdata query. Selecting a grid cell enables height=425 you to edit it. You can insert and delete rows. The grid is 425 X 300 pixels and has 10 pixels width=300 of space above and below it.
  • Page 743 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Update grid values</title> </head> <body> <h3>Updating grid using cfgridupdate tag.</h3> <cfgridupdate grid="employee_grid" datasource="cfdocexamples" tablename="Employee"> Click <a href="grid2.cfm">here</a> to display updated grid. </body> </html> Save the file as handle_grid.cfm. View the grid2.cfm page in your browser, change the grid, and then submit them. Note: To update a grid cell, modify the cell contents, and then press Return.
  • Page 744 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Catch submitted grid values</title> </head> <body> <h3>Grid values for Form.employee_grid row updates</h3> <cfif isdefined("Form.employee_grid.rowstatus.action")> <cfloop index = "counter" from = "1" to = #arraylen(Form.employee_grid.rowstatus.action)#> <cfoutput> The row action for #counter# is: #Form.employee_grid.rowstatus.action[counter]# <br>...
  • Page 745 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfelseif Form.employee_grid.rowstatus.action[counter] is "I"> <cfquery name="InsertNewEmployee" datasource="cfdocexamples"> INSERT into Employee (LastName, Dept_ID) VALUES (<cfqueryparam value="#Form.employee_grid.LastName[counter]#" CFSQLType="CF_SQL_VARCHAR" >, <cfqueryparam value="#Form.employee_grid.Dept_ID[counter]#" CFSQLType="CF_SQL_INTEGER" >) </cfquery> </cfif> </cfloop> </cfif> Click <a href="grid2.cfm">here</a> to display updated grid. </body>...
  • Page 746 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Code Description <cfelseif Form.employee_grid.rowstatus.action[counter] is "U"> Otherwise, if the action is to update a row, generates a <cfquery name="UpdateExistingEmployee" SQL UPDATE query to update the LastName and datasource="cfdocexamples"> Dept_ID fields for the row specified by the Emp_ID UPDATE Employee primary table key.
  • Page 747 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Registering a Java applet Before you can use a Java applet in your ColdFusion pages, register the applet in the ColdFusion Administrator. Open the ColdFusion Administrator by clicking the Administrator icon in the ColdFusion Program group and entering the Administrator password.
  • Page 748: Validating Data

    ColdFusion does not create a form variable. Validating Data You can validate data in Adobe ColdFusion, including form data, variable data and function parameters. About ColdFusion validation Data validation lets you control data that is entered into an application by ensuring that the data conforms to specific type or formatting rules.
  • Page 749 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Validation technique Applies to Where and when Description performed mask HTML and Flash format On the client as the ColdFusion generates JavaScript or ActionScript tags user enters data to directly control the data a user enters by cfinput attribute) mask...
  • Page 750 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Validation technique Applies to Where and when Description performed IsValid function ColdFusion variables On the server, when ColdFusion tests the variable to determine the function executes whether it follows a specified validation rule and the function returns true or false.
  • Page 751 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Validation technique Features Considerations Security issues mask Directly controls user input. Limited to tags. In HTML and XML format, can be cfinput Provides limited control over circumvented because JavaScript attribute) mask user input patterns. runs directly in the browser.
  • Page 752 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Security considerations Although form-specific validation techniques provide good methods for preventing users from submitting invalid or badly formatted data, they cannot prevent users from submitting maliciously formatted data from HTML forms. Malicious users can circumvent validation techniques that require validation on the browser using JavaScript or submission of validation rules in hidden fields.
  • Page 753 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Type field Description creditcard * Strips blanks and dashes; verifies number using mod10 algorithm. The number must have 13–16 digits. ssn * or social_security_number * US. Social Security number format, ###-##-####. The separator can be a dash (-) or a space. email * A valid e-mail address of the form name@server.domain.
  • Page 754 Validating data in XML skinnable forms If you create an XML skinnable form and use any skin provided by Adobe, such as the basic.xsl or silver.xsl skin, you can use all form validation techniques that are available for HTML forms.
  • Page 755 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfif IsDefined("form.fieldnames")> <cfdump var="#form#"><br> </cfif> <cfform name="myform" preservedata="Yes" > First Name: <cfinput type="text" size="15" name="firstname" required="yes" message="You must enter a first name."><br> Last Name: <cfinput type="text" size="25" name="lastname" required="yes" message="You must enter a last name."><br> Telephone: <cfinput type="text"...
  • Page 756 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information For HTML and XML format forms (using ColdFusion skins), most ColdFusion form tags have an onError attribute that lets you specify a Javascript function to run if an onSubmit error occurs. For the function, you write separate code paths to handle valid and invalid data.
  • Page 757 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Note: You cannot force a user to type an A, X, 9, or question mark (?) character. To ensure that a pattern is all-uppercase or all-lowercase, use the ColdFusion UCase or LCase functions in the action page. Masking cfcalendar and datefield input In the tag and the Flash format...
  • Page 758 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Special characters Because special characters are the operators in regular expressions, to represent a special character as an ordinary one, escape it by preceding it with a backslash. For example, use two backslash characters (\\) to represent a backslash character.
  • Page 759 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Multicharacter regular expressions Use the following rules to build a multicharacter regular expression: • Parentheses group parts of regular expressions into a subexpression that can be treated as a single unit. For example, “(ha)+”...
  • Page 760 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Expression Description [\?&]value= Any string containing a URL parameter value. ^[A-Z]:(\\[A-Z0-9_]+)+$ An uppercase Windows directory path that is not the root of a drive and has only letters, numbers, and underscores in its text. ^(\+|-)?[1-9][0-9]*$ An integer that does not begin with a zero and has an optional sign.
  • Page 761 Several validation rules have two names you can use. The names that do not start with “_cf” were used in earlier releases and are retained for backward compatibility. For consistency and clarity, Adobe recommends using the names that start with “_cf” in new forms.
  • Page 762 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Field name suffix Verifies _cfformURL A valid URL. Must start with http:\\, https:\, ftp:\, file:\, mailto:, or news:. Can include, as appropriate, user name and password designators and query strings. The main part of the address can only have the characters A-Za-z0-9 and -.
  • Page 763 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <title>Simple Data Form</title> </head> <body> <h2>Simple Data Form</h2> <!--- Form part. ---> <form action="datatest.cfm" method="Post"> <input type="hidden" name="StartDate_cfformrequired" value="You must enter a start date."> <input type="hidden" name="StartDate_cfformdate" value="Enter a valid date as the start date."> <input type="hidden"...
  • Page 764 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Because numeric values often contain commas and currency symbols, ColdFusion automatically deletes these characters from fields with _cfforminteger and _cfformfloat rules before it validates the form field and passes the data to the form's action page. ColdFusion does not delete these characters from fields with _cfformnumeric rules. Reviewing the code The following table describes the code and its function: Code...
  • Page 765 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • The attribute of the form element name • The value of the control to validate For example, if you write the tag as the following: cfinput <cfinput type="text" <!--- Do not include () in JavaScript function name. ---> onvalidate="handleValidation"...
  • Page 766 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information //--> </script> </head> <body> <h2>JavaScript validation test</h2> <!--- Form is submitted only if the password is valid. ---> <cfif IsDefined("Form.passwd1")> <p>Your Password if valid.</p> </cfif> <p>Please enter your new password:</p> <cfform name="UpdateForm" preservedata="Yes" > <!--- The onValidate attribute specifies the JavaScript validation function.
  • Page 767 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • The error message text specified by the CFML tag’s attribute message The following example shows a form that uses an attribute to tell ColdFusion to call a showErrorMessage onError JavaScript function that uses the method to display an error message.
  • Page 768 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <!--- Action code. First make sure the form was submitted. ---> <cfif isDefined("form.saveSubmit")> <cfif isValid("integer", form.UserID) and isValid("email", form.emailAddr) and isValid("telephone", form.phoneNo)> <cfoutput> <!--- Application code to update the database goes here ---> <h3>The e-mail address and phone number for user #Form.UserID# have been added</h3>...
  • Page 769 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <!--- Action part of the page. ---> <!--- If an expression exception occurs, run the expresser.cfm page. ---> <cferror type="EXCEPTION" exception="expression" template="expresserr.cfm"> <!--- Make sure the form was submitted. ---> <cfif isDefined("form.saveSubmit")> <!--- Use cfparam tags to check the form field data types.
  • Page 770: Creating Forms In Flash

    <cfinput type="submit" name="saveSubmit" value="Save Data"><br> </cfform> Creating Forms in Flash You can create effective forms in Adobe Flash format, in which Adobe ColdFusion displays forms using Flash, not HTML. About Flash forms ColdFusion can deliver forms to the client in Flash (SWF file) format. ColdFusion automatically generates the Flash binary from your CFML code and displays it on the client.
  • Page 771 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • They let you develop complex, multipart forms that do not require multiple pages, by using tabbed or accordion- style dialog boxes. • They automatically do much of the layout work for you. Note: Flash form configuration requirements differ from ColdFusion requirements.
  • Page 772 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • ColdFusion provides two tags that let you take advantage of Flash features and perform tasks that you would otherwise do in HTML: use the tag to add text blocks and horizontal and vertical rules to your form, cfformitem and you use the tag to structure your form.
  • Page 773 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Adding text, images, rules, and space with the cfformitem tag Because Flash forms do not support inline HTML, you use the tag to add text blocks and horizontal and cfformitem vertical rules to your form. (Flash form controls, such as , use the attribute to specify text cfinput...
  • Page 774 <p><b>The text is preceded and followed by horizontal rules</b></p> It also has a link to a web page.</b><br> <a href="http://www.adobe.com/" target="_blank"> <font color="#0000FF"><u> This link displays the Adobe home page in a new browser window </u></font></a> </cfformitem> <cfformitem type="spacer" height="2"/>...
  • Page 775 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Using the cfformgroup tag to structure forms ColdFusion provides form group container types that provide basic structure to a Flash form. You specify these types in the attribute of the cfformgroup tag. Use the following container types to control the layout of controls and type groups of controls: Type...
  • Page 776 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfif Isdefined("Form.fieldnames")> <cfdump var="#form#" label="form scope"> <br><br> </cfif> <cfform name="myform" height="200" width="460" format="Flash" skin="HaloBlue"> <cfformitem type="html" height="20"> <b>Tell us your preferences</b> </cfformitem> <!--- Put the pet selectors to the left of the fruit selectors. ---> <cfformgroup type="hdividedbox"...
  • Page 777 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Controlling sizes in Flash forms Sizing elements in a Flash form is something of an art, rather than a science. As a general rule, if you don’t specify the attributes, Flash tends to do a good job of laying out the form. However, keep in mind the following height width considerations:...
  • Page 778 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfif IsDefined("Form.fieldnames")> <cfdump var="#form#" label="form scope"> <br><br> </cfif> <cfscript> q1 = queryNew("id,firstname,lastname"); queryAddRow(q1); querySetCell(q1, "id", "1"); querySetCell(q1, "firstname", "Rob"); querySetCell(q1, "lastname", "Smith"); queryAddRow(q1); querySetCell(q1, "id", "2"); querySetCell(q1, "firstname", "John"); querySetCell(q1, "lastname", "Doe"); queryAddRow(q1);...
  • Page 779 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information An accordion container places each logical form page on an accordion pleat. Each pleat has a label bar; when the user clicks a bar, the current page collapses and the selected page expands to fill the available form space. The following image shows a three-pleat accordion, open to the middle pleat, Preferences: A tab navigator container places each logical form page on a tabbed frame.
  • Page 780 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information label="Phone Number"> <cfinput type="datefield" name="mydate1" label="Requested date"> </cfformgroup> <cfformgroup type="page" label="Preferences" style="marginTop: 0"> <cfformitem type="html" height="20"> <b>Tell us your preferences</b> </cfformitem> <!--- Put the pet selectors to the left of the fruit selectors. ---> <cfformgroup type="hdividedbox"...
  • Page 781 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Binding data in Flash forms attribute lets you set the value of the fields using the contents of other form fields. You can use the bind bind attribute with the tag and any type that takes a value, including .
  • Page 782 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information You can use both techniques in combination: you can specify a skin for your form and use styles to specify the appearance (such as input text font) of individual controls. For detailed information on the style names and values that you can use, see ColdFusion Flash Form Style Reference in the CFML Reference.
  • Page 783 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Length format You specify styles that take length or dimension values, including font sizes, in pixels. style property lets you use a set of keywords in addition to numbered units. You can use the following fontSize keywords when you set the style property.
  • Page 784 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Styles can be inheritable or noninheritable. If a style is noninheritable, it only affects the tag, and does not affect any of its children. For example, to maintain a consistent background color in an form group and its children tags, hbox specify the color in all tags.
  • Page 785 ColdFusion Flash forms are described here. However, information on writing ActionScript is not provided. For details on ActionScript and how you can use it, see the Flash ActionScript 2.0 documentation, including the documents available in the Flash and Flex sections of LiveDocs at www.adobe.com/go/learn_cfu_docs_en. Using ActionScript code in CFML You can use ActionScript in the following attribute of tags in CFML Flash format forms: •...
  • Page 786 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Note: You do not use the text property (for example, ) to access hidden fields. To access a hidden field, fieldname text use the format formname fieldname value' Custom ActionScript functions Custom ActionScript functions are the equivalent of CFML UDFs. You can define your own functions in ColdFusion by using the tag with a attribute value of...
  • Page 787 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfformgroup type="vbox" name="buttons"style="verticalAlign:bottom; horizontalAlign:center"> <!--- Use a spacer to position the buttons. ---> <cfformitem type="spacer" height="18" /> <!--- Use the insertRow method in the onClick event to add a row. ---> <cfinput type="button" name="ins" value="Insert a new row" width="125" onClick="GridData.insertRow(mygrid);">...
  • Page 788: Creating Skinnable Xml Forms

    You can create XML skinnable forms, which are forms that generate XForms-compliant XML and are normally formatted using an XSLT (extensible stylesheet language transformations) skin. You can use XML skinnable forms with the skins that Adobe ColdFusion provides without having any knowledge of either XML or XSLT. For information on using XML with ColdFusion, see “Using XML and...
  • Page 789 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information How ColdFusion processes XML skinnable forms When ColdFusion processes a tag that specifies XML format and an XSLT skin, it does the following to the form: cfform Converts the CFML form tags into an XForms-compliant XML text format and makes it available in a variable with the same name as the form.
  • Page 790 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Example: a simple skinnable form The following image shows a simple XML skinnable form that uses the default skin to format the output: This form is used in the examples and description. Building XML skinnable forms You build ColdFusion XML skinnable forms using standard ColdFusion forms tags, including cfformgroup...
  • Page 791 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • cfselect • cfslider • cftextarea Using other skins: If you use any other skin, some attributes are not supported, or the skin supports custom attributes. Get the information about the supported attributes from the XSLT skin developer. Using cfformitem tags ColdFusion does not process inline text or standard HTML tags when it generates an XML form;...
  • Page 792 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfformgroup type="horizontal" label="Name"> <cfinput type="text" name="firstname" label="First" required="yes"> <cfinput type="text" name="lastname" label="Last" required="yes"> </cfformgroup> type corresponds to the HTML tag, and groups its children by drawing a box around them fieldset fieldset and replacing part of the top line with legend text.
  • Page 793 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfform name="comments" format="xml" skin="basiccss" width="400" preservedata="Yes" > <cfinput type="hidden" name="revision" value="12a"> <cfformgroup type="fieldset" label="Basic Information"> <cfformgroup type="vertical"> <cfformgroup type="horizontal" label="Name"> <cfinput type="text" size="20" name="firstname" required="yes"> <cfinput type="text" size="25" name="lastname" required="yes"> </cfformgroup> <cfinput type="text" name="email" label="E-mail" validate="email" maxlength="35"> <cfselect name="satisfaction"...
  • Page 794 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Prefix Used for http://www.w3.org/2002/xforms XForms model (including initial field values) and XForms elements that correspond to cfform tags. http://www.w3.org/2001/xml-events System events. Used for the cfinput type="reset". All ColdFusion extensions, including passthrough of attributes that do not correspond to XForms elements or attributes.
  • Page 795 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The body of each element contains the initial control data from the CFML tag’s attribute or its equivalent. For value example, for a tag, the element body is a comma-delimited list that contains the cfselect xf:instance name...
  • Page 796 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Element Description cf:validate type="valiadationtype" Data validation information. Has one attribute, type , the validation type, and one or more cf:argument cf:trigger children. ColdFusion generates a cf:validate element for each of the following: •...
  • Page 797 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <xf:bind id="firstname" nodeset="//xf:model/xf:instance/cf:data/firstname" required="true()"> <xf:extension> <cf:attribute name="type">TEXT</cf:attribute> <cf:attribute name="onerror">_CF_onError</cf:attribute> </xf:extension> </xf:bind> <xf:bind id="lastname" nodeset="//xf:model/xf:instance/cf:data/lastname" required="true()"> <xf:extension> <cf:attribute name="type">TEXT</cf:attribute> <cf:attribute name="onerror">_CF_onError</cf:attribute> </xf:extension> </xf:bind> <xf:bind id="email" nodeset="//xf:model/xf:instance/cf:data/email" required="false()"> <xf:extension> <cf:attribute name="type">TEXT</cf:attribute> <cf:attribute name="onerror">_CF_onError</cf:attribute> </xf:extension> </xf:bind>...
  • Page 798 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information CFML tag XML tag cfinput type="radio" xf:select1 cfinput type="checkbox" xf:select cfinput type="button" xf:trigger cfinput type="image" xf:submit cfinput type="reset" xf:submit cfinput type="submit" xf:submit cfselect multiple="false" xf:select1 cfselect multiple="true" xf:select cftextarea xf:textarea cfslider xf:range cfgrid cf:grid cftree...
  • Page 799 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Part Description The xf or cf namespace element name, as identified in the table in “CFML to XML tag mapping” on page 792. tagname bindid ID attribute of the model xf:bind element for this control. Specified by the control’s CFML tag name attribute.
  • Page 800 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <xf:group appearance="horizontal"> <xf:label>Accept?</xf:label> <xf:extension/> <xf:select1 appearance="full" bind="YesNo" id="YesNo"> <xf:extension> <cf:attribute name="type">radio</cf:attribute> </xf:extension> <xf:choices> <xf:item> <xf:label>Yes</xf:label> <xf:value>Yes</xf:value> <xf:extension> <cf:attribute name="checked">checked</cf:attribute> </xf:extension> </xf:item> <xf:item> <xf:label>No</xf:label> <xf:value>No</xf:value> <xf:extension/> </xf:item> </xf:choices> </xf:select1> </xf:group> cfgrid tags ColdFusion represents a tag using the XML tag.
  • Page 801 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cf:grid bind="gridname" name="gridname" format="xml" id="gridname> <metadata> <cfgridAttribute1>attributeValue</cfgridAttribute1> (There are an entry for attributes with a specified or default value.) </metadata> <columns> <column cfgridcolumnAttribute1="value" ... /> </columns> <rows> <row> <column1Name>row1Column1Value</column1Name> <column2Name>row1Column2Value</column2Name> </row> <row> <column1Name>row2Column1Value</column1Name>...
  • Page 802 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cf:grid bind="mygrid" format="XML" id="mygrid" name="mygrid"> <metadata> <autowidth>false</autowidth> <insert>false</insert> <delete>false</delete> <sort>false</sort> <italic>false</italic> <bold>false</bold> <appendkey>true</appendkey> <highlughthref>true</highlughthref> <griddatalines>Left</griddatalines> <gridlines>true</gridlines> <rowheaders>true</rowheaders> <rowheaderalign>Left</rowheaderalign> <rowheaderitalic>false</rowheaderitalic> <rowheaderbold>false</rowheaderbold> <colheaders>true</colheaders> <colheaderalign>Left</colheaderalign> <colheaderitalic>false</colheaderitalic> <colheaderbold>false</colheaderbold> <selectmode>Edit</selectmode> <notsupported>&lt;b&gt; Browser must support Java to view ColdFusion Java Applets&lt;/b&gt;</notsupported>...
  • Page 803 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information cf:tree format="XML" id="treename> <metadata> <cftreeAttribute1>attributeValue</cftreeAttribute1> </metadata> <node cfml tree item attributes> <node //nested node with no children cfml tree item attributes /> </node> </cf:tree> The following example shows a minimal tree with two nodes: CFML <cfform name="form2"...
  • Page 804 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The cfformgroup and cfformitem tags tags and all tags, except generate cfformgroup cfformitem type="html" type="text", xf:group elements. The following rules determine the element structure: • The CFML tag attribute determines the attribute. type xf:groupappearance •...
  • Page 805 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <xf:group appearance="horizontal"> <xf:label>name</xf:label> <xf:extension/> <xf:input bind="firstname" id="firstname"> <xf:label>First</xf:label> <xf:extension> <cf:attribute name="type">text</cf:attribute> <cf:attribute name="size">20</cf:attribute> </xf:extension> </xf:input> <xf:input bind="lastname" id="lastname"> <xf:label>Last</xf:label> <xf:extension> <cf:attribute name="type">text</cf:attribute> <cf:attribute name="size">25</cf:attribute> </xf:extension> </xf:input> </xf:group> <xf:input bind="email" id="email"> <xf:label>Email</xf:label> <xf:extension> <cf:attribute name="type">text</cf:attribute>...
  • Page 806 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information </xf:item> </xf:choices> </xf:select1> <xf:textarea bind="thoughts" id="thoughts"> <xf:label>Additional Comments</xf:label> <xf:extension> <cf:attribute name="type">textarea</cf:attribute> <cf:attribute name="rows">5</cf:attribute> <cf:attribute name="cols">40</cf:attribute> </xf:extension> </xf:textarea> </xf:group> <xf:group appearance="horizontal"> <xf:extension/> <xf:submit id="submit" submission="comments"> <xf:label>Tell Us</xf:label> <xf:extension> <cf:attribute name="type">submit</cf:attribute> <cf:attribute name="name">submit</cf:attribute> </xf:extension> </xf:submit>...
  • Page 807 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Format Location <cfform format="xml" skin="basic"> Searches for XML/CSS in the default directory and its subdirectories. <cfform format="xml" skin="c:\foo\bar\basic.xsl"> Uses the absolute path. <cfform format="xml" skin="basic.xsl"> Searches in the current directory. <cfform format="xml" skin="..\basic.xsl:"> Searches the parent of the current directory.
  • Page 808 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information All skins support the same set of CFML tags and tag types, and do a relatively simple transformation from XML to HTML. For example, they do not support horizontal or vertical rules. The ColdFusion skin XSL files have several features that you can use when designing and developing your own transformation.
  • Page 809: Using Ajax User Interface Components And Features

    ColdFusion provides. Using Ajax User Interface Components and Features Use Adobe ColdFusion Ajax-based layout and form controls and other Ajax-based user interface capabilities to create a dynamic application. For information about how ColdFusion uses the Ajax framework in general, or how to use ColdFusion Ajax data and programming capabilities, including binding to form data and managing JavaScript resources, see “Using Ajax Data...
  • Page 810 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Data and development features ColdFusion data and development features help you develop effective Ajax applications that use ColdFusion to provide dynamic data. They include many features that you can use with other Ajax frameworks, including Spry. The following data and development features are important for use with form and layout tags: •...
  • Page 811 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Tag/attribute Description cfgrid format="html" A dynamic, editable, sortable, data grid. An input control that users can fill by selecting a date from a pop-up calendar. cfinput type="datefield" cftextarea richtext="yes" A text area with a set of controls that let users format the displayed text. A dynamic tree-format representation of data.
  • Page 812 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information ColdFusion Ajax user interface features are based on the Yahoo User Interface Library and the Ext JavaScript Library. Also, the rich text editor is based on the FCKeditor text editor. In most situations, you require only cftextarea ColdFusion tags and functions (including JavaScript functions) to create and manage the interface.
  • Page 813 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>cfdiv Example</title> </head> <body> <cfform> <cfinput name="tinput1" type="text"> </cfform> <h3> using a div</h3> <cfdiv bind="url:divsource.cfm?InputText={tinput1}" ID="theDiv" style="background-color:##CCffFF; color:red; height:350"/> </body> </html> The divsource.cfm file that defines the contents of the div region has the following code: <h3>Echoing main page input:</h3>...
  • Page 814 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> <!--- The tabheight attribute sets the height of all tab content areas and therefore the layout height. The width style controls the layout width. ---> <cflayout type="tab" name="mainTab" tabheight="300px" style="width:400px"> <!--- Each layoutarea is one tab.
  • Page 815 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Styling layouts tags have attributes. The attribute controls the style of cflayout cflayoutarea style cflayout style the layout container, and sets default values for many, but not all, styles for the layout areas. For example, the color and background color styles of the tag set the default text and background colors in the layout areas.
  • Page 816 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> </head> <body> <cflayout name="theLayout" type="border" style="height:300;"> <cflayoutarea position="left" size="300" style="float:right;"> <cfpod width="300" name="theNews" title="All the latest news" headerstyle="background-color:##DDAADD; font-size:large; font-style:italic; color:black" bodyStyle="background-color:##FFCCFF; font-family:sans-serif; font-size:80%"> Contents of a news feed would go here. </cfpod>...
  • Page 817 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • They can be modal (users cannot interact with the main window when the pop-up window is displayed) or non- modal (users can interact with both windows). • You can specify that the user can drag, close, or resize the window. •...
  • Page 818 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <form> <!--- Use the API to show and hide Window 1. ---> <input type="button" value="Show Window1" onClick="ColdFusion.Window.show('window1')"> <input type="button" value="Hide Window1" onClick="ColdFusion.Window.hide('window1')"><br /> <!--- Use the API to create, show, and hide Window 2 ---> <input type="button"...
  • Page 819 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <script language="javascript"> //Boolean value tacking the window state. var shown=true; //Functions to display an alert box when function onshow(name) { alert("window shown = " + name); function onhide(name) { alert("window hidden = " + name); //Initialize the window show/hide behavior.
  • Page 820 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The callback handler can be useful to provide information about a successful navigation operation. For example, you could make a pod's title bar italic to indicate loading (just before the navigate call), and use the callback handler to switch it back to normal once the navigate completes.
  • Page 821 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information This is a cfwindow control.<br><br> <a href="javascript:ColdFusion.navigate('windowsource.cfm','w2', mycallBack,myerrorHandler);">Click</a> to navigate Window 2</a> </cfwindow> <cfwindow name="w2" title="CF Window 2" initShow=true x=250 y=200 width="200"> This is a second cfwindow control. </cfwindow> <cfform> <!--- This button only replaces the second window body with the body of the windowsrc.cfm page.
  • Page 822 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The following example shows a simple horizontal menu with submenus that uses JavaScript to change the display contents. When the user selects an end item in a menu, the text in the block below the menu shows the path to the selected menu.
  • Page 823 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information tags provide a hierarchy of CSS style attributes that affect different parts of the menu. cfmenu cfmenuitem The following table describes these attributes in hierarchical order: Attribute Description cfmenu attributes menuStyle Applies to the menu, including any parts of the menu that surround the menu items. If you do not override this style in a cfmenu childStyle...
  • Page 824 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Sending custom response to the callback and error handlers The page/URL that handles the upload operation on the server can send back a with the keys status and struct message as shown here: <cffile action = "upload"...
  • Page 825 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <!--- upload.cfm ---> <!--- <cffile action = "upload" destination = "#Expandpath('./upload')#" nameconflict="makeunique"> ---> <script language="javascript"> var uploadCompleteHandler = function(obj){ var result = "Upload Details:" + "\n\n"; for(var i=0;i < obj.length; i++){ result = result + "FILENAME: " + obj[i].FILENAME + "\n" + "STATUS: " + obj[i].STATUS + "\n"...
  • Page 826 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> <cflayout type="vbox" name="layout1"> <cflayoutarea> <h3>This area is not refreshed when the form is submitted.</h3> <br /> </cflayoutarea> <cflayoutarea> <h3>This form is replaced by the action page</h3> <cfform name="myform" format="html" action="showName.cfm"> <cfinput type = "Text"...
  • Page 827 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The following example shows how to use the tag to submit the contents of a login form. When the user clicks SetForm the Login! button, the doLogin function calls the proxy function and then the setForm AuthenticationSystem.cfc method.
  • Page 828 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Submit action is performed by the doLogin function. ---> <cfform name="loginForm" format="xml"> <cfinput type="text" name="username" label="username" /><br /> <cfinput type="password" name="password" label="password" /> <cfinput type="button" name="login" value="Login!" onclick="doLogin();" /> </cfform> </cfwindow> </cflogin> <p>...
  • Page 829 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • The HTTP method (by default, POST • Whether to submit the form asynchronously (by default, true The following proof of concept example uses the function to submit two form fields ColdFusion.Ajax.submitForm to an asyncFormHandler.cfm page, which simply echoes the form values.
  • Page 830 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Using HTML grids The ColdFusion HTML control lets you use a bind expression to dynamically populate the grid. HTML grids cfgrid that use bind expressions are paged; as users navigate from page to page of the grid, the grid dynamically gets the data for only the required page from the data source.
  • Page 831 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information If you do not want the grid to refresh automatically when other controls change, you can use the specifier on all @none optional bind parameters. Doing this, prevents automatic updating of the grid based on the bound control values. Use the ColdFusion.Grid.refresh JavaScript function to explicitly refresh the grid contents.
  • Page 832 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> <cfform name="form01"> <cfgrid format="html" name="grid01" pagesize=5 sort=true bind="cfc:places.getData({cfgridpage},{cfgridpagesize}, {cfgridsortcolumn},{cfgridsortdirection})"> <cfgridcolumn name="Emp_ID" display=true header="eid" /> <cfgridcolumn name="FirstName" display=true header="Name"/> <cfgridcolumn name="Email" display=true header="Email" /> </cfgrid> </cfform> </body> </html> The places.cfc file looks as follows.
  • Page 833 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The following example shows the getdata.cfm page: <!--- Empty string; the default end of the query SQL. ---> <cfset queryEnd=""> <cfquery name="team" datasource="cfdocexamples"> SELECT Emp_ID, FirstName, EMail FROM Employees <cfif sortcol neq "" or sortdir neq ""> order by #sortcol# #sortdir# </cfif>...
  • Page 834 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information To update or delete data dynamically, do the following: • Specify in the tag. This lets the user edit the grid. selectmode="edit" cfgrid • Specify an attribute in the tag. The attribute must use a bind expression to specify a CFC method, onChange cfgrid JavaScript function, or URL of a page that updates the data source.
  • Page 835 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> function errorhandler(id,message) { alert("Error while updating\n Error code: "+id+"\n Message: "+message); </script> </head> <body> <cfform name="form01"> <cfgrid format="html" name="grid01" pagesize=11 stripeRows=true stripeRowColor="gray" bind="cfc:places.getData({cfgridpage},{cfgridpagesize}, {cfgridsortcolumn},{cfgridsortdirection})" delete="yes" selectmode="edit" onchange="cfc:places.editData({cfgridaction},{cfgridrow},{cfgridchanged})"> <cfgridcolumn name="Emp_ID"...
  • Page 836 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information By default, each time the selected row in the grid changes, the bind parameter is re-evaluated, and the control value changes to the value of the specified column of selected grid cell. Grid JavaScript functions You can use the following JavaScript functions to manage an HTML format grid: Function...
  • Page 837 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfset querysetcell(emps,"salary","100000",8)> <cfset querysetcell(emps,"active","false",8)> <cfset querysetcell(emps,"firstname","Adam",9)> <cfset querysetcell(emps,"department","CF",9)> <cfset querysetcell(emps,"salary","300000",9)> <cfset querysetcell(emps,"active",false,9)> <cfset querysetcell(emps,"firstname","Sean",10)> <cfset querysetcell(emps,"department","CF",10)> <cfset querysetcell(emps,"salary","250000",10)> <cfset querysetcell(emps,"active","No",10)> <cfform name="form01"> <cfgrid format="html" insert="yes" insertButton="Add Row" name="grid01" selectmode="edit" width=600 collapsible="true" title="Employees" autowidth="yes"...
  • Page 838 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <!--- using cfgridcolum type="date" ---> <cfset emps = querynew("firstname,department, salary,startdate")> <cfset queryaddrow(emps,3)> <cfset querysetcell(emps,"firstname","Debra",1)> <cfset querysetcell(emps,"department","Accounting",1)> <cfset querysetcell(emps,"salary","100000",1)> <cfset querysetcell(emps,"startdate","2009/1/1",1)> <cfset querysetcell(emps,"firstname","Doherty",2)> <cfset querysetcell(emps,"department","Finance",2)> <cfset querysetcell(emps,"salary","120000",2)> <cfset querysetcell(emps,"startdate","2005/2/21",2)> <cfset querysetcell(emps,"firstname","Ben",3)> <cfset querysetcell(emps,"department","Law",3)> <cfset querysetcell(emps,"salary","200000",3)>...
  • Page 839 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Using HTML trees An HTML cftree tag creates an Ajax-based tree data representation that you can populate from a query or a bind expression. The behavior with a query is equivalent to the behavior of applet or Flash trees. Bind expressions let you populate the tree based on the values of other controls or Spry data sets.
  • Page 840 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Bind type Return value A ColdFusion array of structures. ColdFusion automatically converts the structure to JSON format when it returns the result to the caller. Alternatively, you can return a JSON representation of the structure. JavaScript A JavaScript Array of Objects.
  • Page 841 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfcomponent> <cffunction name="getNodes" returnType="array" output="no" access="remote"> <cfargument name="nodeitemid" required="true"> <cfargument name="nodeitempath" required="true"> <!--- The initial value of the top level is the empty string. ---> <cfif nodeitemid IS ""> <cfset nodeitemid =0> </cfif>...
  • Page 842 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!--- The loadimage function displays the image of the selected art. It is called when the user clicks the image item. ---> <script> function loadImage(img) { var imgURL = '<img src="/cfdocs/images/artgallery/'+img+'">'; var imgDiv = document.getElementById('image');...
  • Page 843 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfcomponent output="false"> <cfset variables.dsn = "cfartgallery"> <!--- Function to populate the current level of the tree. ---> <cffunction name="getItems" returnType="array" output="false" access="remote"> <cfargument name="path" type="string" required="false" default=""> <cfargument name="value" type="string" required="false" default=""> <cfset var result = arrayNew(1)>...
  • Page 844 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information value="#listLast(arguments.value)#"> </cfquery> <cfloop query="q"> <cfset s = structNew()> <cfset s.value = arguments.value & "," & artid> <cfset s.display = artname & " (" & dollarFormat(price) & ")"> <cfset s.href = "javaScript:loadImage('#largeimage#');"> <cfset s.children=arrayNew(1)> <!--- leafnode=true prevents node expansion and further calls to the bind expression.
  • Page 845 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> <!--- Display the text if the form has been submitted with text. ---> <cfif isdefined("form.text01") AND (form.text01 NEQ "")> <cfoutput>#form.text01#</cfoutput><br /> </cfif> <!--- A form with a basic rich text editor and a submit button. ---> <cfform name="form01"...
  • Page 846 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Follow these rules when you define a toolbar: • Start the definition with FCKConfig.ToolbarSets. • Specify the toolbar name in double quotation marks and brackets ([""]). Use this name, case correct, in the attribute.
  • Page 847 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The following example template defines a title followed by text: <Template title="Title and Text" image="template1.gif"> <Description>A Title followed by text.</Description> <Html> <![CDATA[ <h3>Type the title here</h3> Type the text here ]]> </Html> </Template>...
  • Page 848 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • The month name matches, case correct, the month names specified by the attribute, or, for an monthNames mask, their three-letter abbreviations. • If the date mask specifies yy for the years, the pop-up calendar uses dates in the range 1951-2050, so if the user enters 3/3/49 in the text field, the calendar displays March 3, 2049.
  • Page 849 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Using autosuggest text input fields When you create a text input ( ) in HTML, use the attribute to specify a static or dynamic type="text" autosuggest source that provides field completion suggestions as the user types. Use the attribute to autosuggestMinLength specify the number of characters the user must type before first displaying any suggestions.
  • Page 850 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information To test this example with the cfdocexamples database, type S in the first box and the autosuggest list shows Smith and Stewart. If you select Smith and enter A or J in the First Name box, you get a name suggestion. The following example shows the application: <html xmlns="http://www.w3.org/1999/xhtml">...
  • Page 851 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfcomponent> <cffunction name="getLNames" access="remote" returntype="array" output="false"> <cfargument name="suggestvalue" required="true"> <!--- The function must return suggestions as an array. ---> <cfset var myarray = ArrayNew(1)> <!--- Get all unique last names that match the typed characters. ---> <cfquery name="getDBNames"...
  • Page 852 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information In HTML forms, you can specify maximum, minimum, and increment values, to help you quickly filter complex results. The available slider controls are: Vertical, with controls that can be adjusted to the top or bottom; Horizontal, with controls that can be adjusted to the left or right;...
  • Page 853 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <p> <span id="currentSliderValue">Current Slider Value: <font color="red"><strong>50</strong></font></span><br> </p> </cfform> <p> <br><b>Volume</b>: <cfslider name="s" format="html" min=1 max=100 value="50" tip="yes" onChange="sliderChange" onDrag = "sliderDrag" vertical="no" width="200pt" > </p> Using geographical maps tag lets you embed a geographical map within your ColdFusion page. The following are the supported map cfmap types: •...
  • Page 854 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <br> <cfoutput> <table> <tr> <td bgcolor='red'><h4><font color='white'>URL Bind Example</font></td> </tr> </table> Map Name: #cfmapname#<br> Latitude, Longitude: (#DecimalFormat(cfmaplatitude)#,#DecimalFormat(cfmaplongitude)#)<br> Address: #cfmapaddress#<br> </cfoutput> The following table provides details of the parameters: Parameter name Description cfmapname The name of the map.
  • Page 855 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfcomponent> <cffunction name="getMapData" access="remote"> <cfargument name="cfmapname"> <cfargument name="cfmaplatitude"> <cfargument name="cfmaplongitude"> <cfargument name="cfmapaddress"> <cfsavecontent variable="markup"> <br> <cfoutput> <table> <tr> <td bgcolor='red'><h4><font color='white'>CFC Bind Example</font></td> </tr> </table> Map Name: #cfmapname#<br> Latitude, Longitude: (#DecimalFormat(cfmaplatitude)#,#DecimalFormat(cfmaplongitude)#)<br> Address: #cfmapaddress#<br> </cfoutput>...
  • Page 856 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfmap centeraddress="Hobart, Tasmania, Australia" name="map1" type="map" tip="Hobart, Tasmania, Australia" zoomControl="small3d" markerbind="url:mapdata.cfm?cfmapname={cfmapname}&cfmaplatitude={cfmaplatitude}&cfmaplongitu de={cfmaplongitude}&cfmapaddress={cfmapaddress}" showmarkerwindow = true> <cfmapitem name="m1" address="Taj Mahal, Agra, India" tip="Taj Mahal, Agra, India"> <cfmapitem name="m2" latitude="40.46" longitude="117.05" showmarkerwindow=true tip="Great Wall of China, Bejing"> <cfmapitem name="m3"...
  • Page 857 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • Uses callback and error handlers that give control to the users after the progress bar completes processing or if it encounters any exceptions. • Lets programmatic control over progress bar using JavaScript APIs. Progress bar modes The progress bar supports the following two modes: Dynamic mode...
  • Page 858 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfcomponent> <cffunction name="resetStatus" access="remote"> <!--- Clear count from session so that next time the progress bar runs from the start time. ---> <cfif session.count gte 10> <cfset structdelete(session,"count")> </cfif> </cffunction> <cffunction name="getProgessData" access="remote"> <!--- use a count to track progress --->...
  • Page 859 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <!--- use a count to indicate progress ---> <cfif not isdefined('session.count')> <cfset session.count = 1> <cfelse> <cfset session.count = session.count + 1 > </cfif> <!--- the struct to be sent back; using the populate the status and message components of the progressbar --->...
  • Page 860 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Manual mode In the manual mode, you specify the duration the progress bar takes to complete the display of progress. In the following example, is set to as a result of which the progress bar is not shown when the autodisplay false page is first loaded.
  • Page 861 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfajaxproxy cfc="pbar" jsclassname="pbar"> <head> <script> var utils = new pbar(); var init = function() document.getElementById('cfpbLabel').style.display = 'block'; ColdFusion.ProgressBar.show('pBar'); getProgessData(); var hideProgessBar = function() document.getElementById('cfpbLabel').style.display = 'none'; ColdFusion.ProgressBar.hide('pBar'); var getProgessData = function() for(i=1;i <= 10;i++) var status = parseFloat(i * 0.10);...
  • Page 862 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The following code illustrates styling: style="bgcolor:ADD8E6;progresscolor:6183A6;textcolor:191970" Using the cfmessagebox tag tag lets you define controls for displaying pop-up messages. In addition to the standard alert box, cfmessagebox this tag lets you include a prompt and entry field in the box. Using confirm dialog The following code shows how to build a confirm message box with two buttons YES and NO.
  • Page 863: Using Ajax Data And Development Features

    MessageBox" > Using Ajax Data and Development Features Adobe ColdFusion supports Ajax features to use data dynamically in web pages. For information on ColdFusion Ajax user interface capabilities, see “Using Ajax User Interface Components and Features” on page 804.
  • Page 864 Ajax frameworks or widget sets such as Dojo or Backbase, easily access data from ColdFusion servers. • The tag lets you use bind expressions to dynamically create and update Adobe Spry data sets. cfsprydataset Applications that use Spry framework elements, such as dynamic regions, use this tag to populate the Spry elements with information based on ColdFusion control input.
  • Page 865 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information ColdFusion Ajax tags The following table lists ColdFusion Ajax-related tags and functions, including all tags that support Ajax-based features. It does not include subtags that are used only in the bodies of the listed tags: Data tags UI tags UI tags...
  • Page 866 (arguments) {function body} However, Adobe recommends that you include all custom JavaScript in external JavaScript files and import them on the application’s main page, and not write them inline in code that you get using the source attribute. Imported pages do not have this function definition format restriction.
  • Page 867 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information {[formName:]controlName[.attributeName][@event]} {SpryDataSetName.fieldName} The brackets ([]) indicate optional contents and are not part of the parameter. Note: To include a literal brace character in a bind expression, escape the character with a backslash, as \{, \}. The formname value The formname entry identifies the form that contains the control you are binding to.
  • Page 868 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Note: You can bind to the display text of a select box, instead of the value, by specifying an attribute name of innerHTML Note: When you bind to a check box, use the event specifier to ensure that the bind expression is triggered in @click Internet Explorer when the user selects or deselects the check box, not when the box loses focus.
  • Page 869 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information bind="cfc:mycfc.myfunction(arg1={myform:myfield1},arg2={myform:myfield2})" Support for CFCs outside webroot Note: To use this feature, you must install ColdFusion 9 Update 1. Components outside the webroot can be accessed in bind expressions. This implies that tags such as cfajaxproxy Ajax components such as grid, map, or progress bar can be used in more effective ways.
  • Page 870 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfcomponent> <cfscript> remote any function getEmployees(page,pageSize,gridsortcolumn="EMP_ID",gridsortdirection="ASC"){ var startRow = (page-1)*pageSize; var endRow = page*pageSize; if(!isdefined("arguments.gridsortcolumn") or isdefined("arguments.gridsortcolumn") and trim(arguments.gridsortcolumn) eq "") gridsortcolumn = "EMP_ID"; if(!isdefined("arguments.gridsortdirection") or isdefined("arguments.gridsortdirection") and arguments.gridsortdirection eq "") gridsortdirection = "ASC"; var mysql = "SELECT Emp_ID, FirstName, EMail, Department FROM Employees";...
  • Page 871 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> </head> <body> <cfform name="mycfform"> First Name: <cfinput type="text" name="firstname" value=""><br> Last Name: <cfinput type="text" name="lastname" value=""><br> Domain: <cfinput type="text" name="domain" value=""><br> E-mail: <cfinput type="text" name="email1" size="30" bind="{firstname}.{lastname}@{domain}"> </cfform> </body> </html> The following example shows the results of binding to radio buttons and check boxes with the same attribute but name...
  • Page 872 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • It calls a CFC, which uses only the first letter of the first name when forming the e-mail address, and forces the domain name to be all lowercase. The following example shows the bindapp.cfm page: <html>...
  • Page 873 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • The function handles a valid return from the function or page and updates the display as required with onSuccess the returned information. Binding a function or request by using the tag enables you to perform a server-side action, such as cfajaxproxy updating a database by using bind parameter values based on a user action in some control, and then run a specific action or set of actions in one or more controls based on the server response.
  • Page 874 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <html> <head> <script language="javascript"> function test(x,y){ return "Hello, " + x + "!"; function callbackHandler(result){ alert("Bind expression evaluated. Result: \n" + result); </script> <cfajaxproxy bind="javascript:test({input1@none},{button1@click})" onSuccess="callbackHandler"> </head> <body> <cfform name="mycfform"> <cfinput type="text" value="" name="input1" size="30"> <cfinput type="button"...
  • Page 875 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Using ColdFusion Ajax CFC proxies Use the tag to create a client-side JavaScript proxy for a CFC and its functions. The proxy object has the cfajaxproxy following characteristics: • It provides a JavaScript function that corresponds to each CFC remote function. Calling these functions in your client-side JavaScript code remotely calls the CFC functions on the server.
  • Page 876 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information • You use the function to specify whether to return the result in JSON format (the default), in setReturnFormat WDDX format, or as plain text. Use the function to specify whether to return a JSON format setQueryFormat query as an object with an array of column names and an array of row arrays, or as an object that corresponds to the WDDX query format.
  • Page 877 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <!--- The cfajaxproxy tag creates a client-side proxy for the emp CFC. View the generated page source to see the resulting JavaScript. The emp CFC must be in the components subdirectory of the directory that contains this page.
  • Page 878 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information var e = new emp(); e.setCallbackHandler(populateEmployeeDetails); e.setErrorHandler(myErrorHandler); // This time, pass the employee name to the getEmployees CFC // function. e.getEmployees(id); // Callback function to display the results of the getEmployeeDetails // function. var populateEmployeeDetails = function(employee) var eId = employee.DATA[0][0];...
  • Page 879 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information </script> </head> <body> <!--- The form to display the employee drop-down list and employee data. ---> <form name="simpleAJAX" method="get"> List of Employees:&nbsp;&nbsp;&nbsp; <select name="employee" onChange="getEmployeeDetails(this.value)"> <script language="javascript"> getEmployees(); </script> </select> <br><br> <span id="empData"></span> </form>...
  • Page 880 'POST'}" onBindError="errorHandler"> ColdFusion includes the complete Spry 1.5 framework release in web_root/CFIDE/scripts/ajax/spry directory. For more information about Spry framework, see www.adobe.com/go/learn_spry_framework_en. For more information, see the cfsprydataset tag in the CFML Reference. Spry data set example This example has the following behavior: It uses a CFC function directly to populate a Spry XML data set, from an XML file.
  • Page 881 For this example to display images, create an images subdirectory of your application directory that contains images with the names specified by the BOOKIMAGE column of the cfbookclub database BOOKS table. The roundtrip.cfm page <html xmlns="http://www.w3.org/1999/xhtml" xmlns:spry="http://ns.adobe.com/spry"> <head> <!--- The screen.css style sheet is provided in the Spry distribution. --->...
  • Page 882 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The items are populated by the data from the CFC getFilter method. ---> <div id="FiltersList" spry:region="dsFilters" class="SpryHiddenRegion"> <div spry:repeat="dsFilters" class="ListBoxItemGroup"> <div class="ListBoxItem" onclick="dsFilters.setCurrentRow('{dsFilters::ds_RowID}');" spry:selectgroup="feedsList" spry:select="SelectedListBoxItem" spry:hover="ListBoxItemHover"> {dsFilters::description} </div> </div> </div> <!--- A ColdFusion form with the book list data grid. ---> <cfform name="bookform">...
  • Page 883 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information The gridDataManager.cfc file <cfcomponent name="GridDataManager"> <!--- The getFilter function gets the filter XML to populate the dsFilters Spry data set. It specifies returnFormat=plain to send XML text. ---> <cffunction name="getFilter" access="remote" output="false" returnFormat="plain"> <cffile action="read"...
  • Page 884 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information <cfoutput> <cfxml variable="BookDetailsXML" > <?xml version="1.0" encoding="iso-8859-1"?> <products> <product> <name>#BookDetails.TITLE#</name> <category>#BookDetails.GENRE#</category> <bookimage>#BookDetails.BOOKIMAGE#</bookimage> <desc>#BookDetails.BOOKDESCRIPTION#</desc> </product> </products> </cfxml> </cfoutput> <!--- Convert the XML object to an XML string. ---> <cfset xmldata = xmlparse(BookDetailsXML)> <cfcontent type="text/xml" reset="yes"> <cfreturn xmldata>...
  • Page 885 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Specifying a custom script or CSS location In some situations, you cannot use the default location for the CFIDE directory, because a hosting site blocks access to it to prevent access to the ColdFusion Administrator. Then, move the CFIDE/scripts directory, or the subdirectories that you use in your applications, to a different location.
  • Page 886 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Importing tag-specific JavaScript files In the following situations, ColdFusion does not automatically import the JavaScript files that are required for Ajax- based tags: • If you use a ColdFusion Ajax-based tag on a page that you specify by using a attribute in a container source bind...
  • Page 887 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information If the requested return format is JSON and the function returns a query, ColdFusion serializes the query into a JSON object in either of the following formats: • As a JSON object with two entries: an array of column names, and an array of column data arrays. These entries are returned in the following situations: •...
  • Page 888 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information For more information about these functions and examples, see the CFML Reference. The following example shows how to use ColdFusion JSON functions in a non-Ajax application. It does a Yahoo search for references to "ColdFusion Ajax" and displays these results: •...
  • Page 889 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Ajax plumbing enhancement in ColdFusion 9.0.1 ORM CFCs support the attribute for a property. remotingfetch By default, is set to remotingfetch false While serializing ORM CFCs, ColdFusion introspects the property and if it is , does not return remotingfetch false...
  • Page 890 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Logging information You call the following JavaScript functions to send information to the logger. In most cases, the function corresponds to a severity level, as follows: Function Severity Purpose ColdFusion.Log.debug debug A message that aids in debugging problems. ColdFusion.Log.dump debug A representation of a single variable in a format similar to...
  • Page 891 (arguments) {function body} However, Adobe recommends that you include all custom JavaScript in external JavaScript files and import them on the application’s main page, and not write them in-line in code that you get dynamically. Imported pages do not have this restriction on the function definition format.
  • Page 892 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Improving security ColdFusion includes several capabilities that help to ensure the security of Ajax application. Also, the ColdFusion Administrator disables output to the client-side logging window by default (see “Enable logging output” on page 884). •...
  • Page 893 DEVELOPING COLDFUSION 9 APPLICATIONS Requesting and Presenting Information Programming effectively The following recommendations help improve or customize your ColdFusion Ajax application. • Use the AjaxOnLoad function, which specifies a JavaScript function to run when the page loads, to perform any initialization actions that are required for a page to function properly.
  • Page 894: Chapter 11: Office File Interoperability

    Chapter 11: Office file interoperability Adobe ColdFusion provides interfaces to work with PDF, Adobe Flash, and Adobe Connect. ColdFusion 9 now extends the integration support to OpenOffice and Microsoft Office application formats such as Excel, PowerPoint, and SharePoint. Office interoperability supports both OpenOffice and Apache POI libraries (see http://poi.apache.org/...
  • Page 895: Using Cfpresentation

    You use the tag to convert a PowerPoint presentation to an Adobe Connect presentation or HTML. cfpresentation Browsers like Internet Explorer, Mozilla Firefox, and Safari are all compatible with the conversion from PPT to a Connect presentation or HTML.
  • Page 896 DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability <cfpresentation title = "text string" format= "ppt" destination="#generated#html_to_ppt_01.ppt" backgroundColor = "YELLOW" overwrite = "yes"> <cfpresentationslide Title="Q1 Sales Figures" duration="14"> <h3>Q1 Sales Figures</h3> <cfchart format="png" showborder="yes" chartheight="250" chartwidth="300" pieslicestyle="sliced"> <cfchartseries type="pie"> <cfchartdata item="Europe" value="9"> <cfchartdata item="Asia"...
  • Page 897: Using Cfspreadsheet

    DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability <cfpresentation title="my presentation" directory="C:\presentations" overwrite=true> <cfpresentationslide src="#ppttemplate#backgrounds.ppt" slides="1-3,5"> </cfpresentationslide> <cfpresentationslide duration="4" video="video1.flv"> Sample slide </cfpresentationslide> </cfpresentation> Using cfspreadsheet tag lets you manage Excel spreadsheets. The tag lets you do the following: cfspreadsheet • Read a spreadsheet file (XLS file) and store it in a ColdFusion spreadsheet object, query, CSV string, or HTML string.
  • Page 898: Supported Office Conversion Formats

    DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability <cfspreadsheet action = "read" src="C:\dcuments\template_02.xls" query="excelquery" sheet="1" rows="1-3,4-5" columns="1,4"> <cfoutput query="excelquery" startrow="1" maxrows="#excelquery.recordcount#"> #excelquery.col_1# #excelquery.col_2# </cfoutput> The following example reads a spreadsheet file - template_08_Charts_Graph.xls and stores the spreadsheet data in an HTML string. <cfspreadsheet action = "read"...
  • Page 899: Sharepoint Integration

    DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability Format CFML Tag OpenOffice installation From Connect Presentation cfpresentation optional HTML optional cfpresentation cfdocument optional HTML not required cfpresentation Excel HTML cfspreadsheet not required Excel Query not required cfspreadsheet Excel In-memory Variable cfspreadsheet not required Query Excel...
  • Page 900 DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability <cfsharepoint action="addlist" login="#login#" params="#{ listname ="getpics", description="This a picture library list", templateId= "109 " }#"/> <! --- Creates a folder within the picture library list> < cfsharepoint action ="create new folder" login= "#login#" name="collection1"...
  • Page 901 To make a ColdFusion application available from SharePoint, use the CFSharepoint SSO WebPart template. This template is a customized version of PageViewer WebPart. It enables you to pass SSO credentials to the ColdFusion application. Download this template from the Adobe website or copy it from the ColdFusion 9 DVD. Remember these points: •...
  • Page 902 DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability Deploy the CF9SSOWebPart.wsp Web Part for Microsoft Office SharePoint Server 2007 To configure single sign-on for Microsoft Office SharePoint Server 2007, deploy the CF9SSOWebPart.wsp file to the SharePoint server. Copy the CF9SSOWebPart.wsp file to the BIN folder within the Web Server extensions. It is normally located at Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN in the SharePoint server.
  • Page 903 DEVELOPING COLDFUSION 9 APPLICATIONS Office file interoperability From the CF9SharepointSSOCab.CAB file, copy the template file CFSSO.aspx to the CFSharePointSSO folder that you created in the previous step. In the command prompt, navigate to Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\bin and enter the following command to add the CAB file: stsadm.exe -o addwppack -filename CF9SharepointSSOCab.CAB -globalinstall If the CAB file exists, delete the CAB file and then enter the command to add the CAB file as follows: stsadm.EXE -o deletewppack -name CF9SharepointSSOCab.CAB...
  • Page 904: Chapter 12: Coldfusion Portlets

    Chapter 12: ColdFusion Portlets You can now build your own portlets by leveraging Adobe ColdFusion components (CFCs). You can create your own portlet using ColdFusion and run it on: • JBoss portal server • WebSphere portal server 6.1 Run a ColdFusion portlet on JBoss Portal Server You can run and access ColdFusion portlets on a JBoss portal server, which can be either local or remote.
  • Page 905 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets <cfcomponent extends="CFIDE.portlets.ColdFusionPortlet"> <cffunction name="doView" returntype="void" output="true"> <cfargument name="renderRequest" type="any" required="true" hint="A javax.portlet.RenderRequest java object"> <cfargument name="renderResponse" type="any" required="true" hint="A javax.portlet.RenderResponse java object"> <cfoutput> Hello World ColdFusion Portlet </cfoutput> </cffunction> <cffunction name="doHelp" returntype="void" output="true"> <cfargument name="renderRequest" type="any" required="true" hint="A javax.portlet.RenderRequest java object">...
  • Page 906 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets <JBoss_home>/bin/run.sh On Windows < JBoss_home>\bin\run.bat By default JBoss only binds to localhost. You can have it bind to any IP address by running bin/run.sh -b on UNIX or on Windows. 0.0.0.0 bin/run.bat -b 0.0.0.0 Launch the JBoss portal server.
  • Page 907 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Adding instance of CFHelloPortlet Click the Portal Objects tab. Create a new portal page by specifying the portal name in the Create a portal named box. Creating a portal Select the created portal page from the list of portals. From Actions, select Page Layout.
  • Page 908 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Managing created portal From the Portlet instance associated with this Window list, select the portlet instance you created in step 10. Portal instance selected Last updated 1/20/2012...
  • Page 909 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets In the Page Layout section, click Add for the center region or left region to add the portlet container in the required area. Go back to the Portal Objects > Portals page and select Make Default option to set the new portal as default. Click the Portal option on the upper-right corner to view the new portal page containing the portlet.
  • Page 910 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Configure the WSRP consumer Run the JBoss server by running the command: On UNIX bin/run.sh On Windows bin\run.bat By default JBoss only binds to localhost. You can have it bind to any IP address by running bin/run.sh -b on UNIX or on Windows.
  • Page 911: Common Methods Used In Portlet.cfc

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Common methods used in portlet.cfc Some common methods that are used frequently while creating the ColdFusion component portlet, such as HelloPortlet.cfc, are: Method Description Syntax doView() This method renders the <cffunction name="doView" returntype="void" output="true"> portlet content.
  • Page 912 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Portlet modes Portal servers typically allow three portlet modes: View, Edit, and Help. The View mode is the default state when rendering a portlet. The portlet window has links in the title bar that enable you to change the mode to Help or Edit.
  • Page 913 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets <cfparam name="request.portlet.parameters.page" default=""> <cfif request.portlet.parameters.page IS "somepage"> <cfinclude template="somepage.cfm"> <cfelse> <!--- put step 1 here ---> </cfif> Processing actions using form posts To process a form post, use the function, which generates the form action URL. createActionURL() For example: <cfoutput>...
  • Page 914: Jsr-286 Support

    Some of the capabilities of JSR-286 include the following: Publishing and Processing Events To define an event, you would have to declare it in portlet.xml <event-definition> <qname xmlns:cf="http://adobe.com/coldfusion/portlet/example">cf:HelloEvent </qname> <value-type>java.lang.String</value-type> </event-definition> This code defines an event named cf:HelloEvent, where cf refers to the namespace and HelloEvent is the local name.
  • Page 915 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Processing an event (event consumer) <portlet> …. <supported-processing-event> <qname xmlns:cf="http://adobe.com/coldfusion/portlet/example">cf:HelloEvent</qname> </supported-processing-event> ….. </portlet> Portlet definition can have both publishing and processing tags. file has event definition, publishing portlet.xml event, and processing event tags, as its portlets create and consume events.
  • Page 916: Using Filters

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets <cffunction name="processEvent" returntype="void" access="public" output="false" hint="Called by the portlet container requesting the portlet to process a specific event."> <cfargument name="eventRequest" type="any" required="true" hint="A javax.portlet.EventRequest java object"> <cfargument name="eventResponse" type="any" required="true" hint="A javax.portlet.EventResponse java object"> <cfset var e = StructNew()>...
  • Page 917: Run A Coldfusion Portlet On Websphere Portal Server

    DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets <cfcomponent extends="CFIDE.portlets.filter.ColdFusionPortletFilter"> <cffunction name="doRenderFilter" returntype="void"> <cfargument name="renderRequest"> <cfargument name="renderResponse"> <cfargument name="filterChain"> <cflog file="portlet-filter" type="information" text="doRenderFilter() invoked"> <!--- call the next filter in the chain ---> <cfset arguments.filterChain.doFilter(arguments.renderRequest, arguments.renderResponse)> </cffunction> <cffunction name="doActionFilter" returntype="void"> <cfargument name="actionRequest"> <cfargument name="actionResponse">...
  • Page 918 DEVELOPING COLDFUSION 9 APPLICATIONS ColdFusion Portlets Go to repackage the WAR file using jar cvf cfusion.war Deploy it through WebSphere Portal Server administrator console. The portlets would be visible present in portlet.xml Create a portal page and add the portlets. Last updated 1/20/2012...
  • Page 919: Chapter 13: Working With Documents, Charts, And Reports

    Chapter 13: Working with Documents, Charts, and Reports Manipulating PDF Forms in ColdFusion You can use Adobe ColdFusion to manipulate PDF forms created in Adobe® Acrobat® Professional and Adobe® LiveCycle™ Designer. About PDF forms Adobe ColdFusion lets you incorporate interactive PDF forms in your application. You can extract data submitted from the PDF forms, populate form fields from an XML data file or a database, and embed PDF forms in PDF documents created in ColdFusion.
  • Page 920 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Task Tags and actions Populate a PDF form with XML data action of the cfpdf tag populate Prefill individual fields in a PDF form with data from a data populate action of the cfpdfform tag with the cfpdfsubform source...
  • Page 921 XML data file differs based on whether it was generated from Acrobat or LiveCycle. Acrobat generates an XML Forms Data Format (XFDF) file format. The following example shows the XFDF format: <?xml version="1.0" encoding="UTF-8"?> - <xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve"> - <fields> - <field name="textname">...
  • Page 922 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfpdfform action="populate" source="c:\forms\timsheet.PDF"> <cfpdfformparam name="firstName" value="Boris"> <cfpdfformparam name="lastName" value="Pasternak"> <cfpdfformparam name="department" value="Marketing"> </cfpdfform> Forms created in LiveCycle from the standard blank forms contain a subform called form1. The result structure of a form created in LiveCycle could look like the following example: struct form1...
  • Page 923 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports In ColdFusion, to prefill the fields in forms created in Acrobat, nest the field names as subforms: <cfpdfform action="populate" source="acrobatForm.pdf"> <cfpdfsubform name="form1"> <cfpdfsubform name="x"> <cfpdfformparam name="f1" value="AGuthrie"> <cfpdfformparam name="f2" value="123"> <cfpdfformparam name="f3"...
  • Page 924 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Embedding a PDF form in a PDF document You can use the tag inside the tag to embed an existing interactive PDF form in a PDF cfpdfform cfdocument document. This technique is useful to include additional information with a standard interactive form. For example, a company could have a generic PDF form for maintaining employee information.
  • Page 925 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Extracting data from a PDF form submission Data extraction differs based on how the PDF form is submitted. ColdFusion supports two types of PDF form submission: HTTP post, which submits the form data, but not the form itself, and PDF, which submits the entire PDF file. One use for PDF submission is for archival purpose: because the form is submitted with the data, you can write the output to a file.
  • Page 926 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports ColdFusion XDP files contain the XDP XML code and the PDF image. Therefore, the file size is larger than a PDF file. Only write PDF forms to XDP files if you must incorporate them into the LiveCycle Designer workflow on a LiveCycle server.
  • Page 927 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports struct SUBFORM struct HEADER struct HTTPSUBMITBUTTON1 [empty string] TXTDEPTNAME Sales TXTFIRSTNAME Carolynn TXTLASTNAME Peterson TXTPHONENUM (617) 872-9178 TXTEMPID TXTEMAIL carolynp@company Note: When data extraction using the tag results in more than one page, instead of returning one structure, cfpdfform the extraction returns one structure per page.
  • Page 928 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <h3>Employee Information</h3> <cfoutput> <table> <tr> <td>Name:</td> <td>#fields.txtfirstname# #fields.txtlastname#</td> </tr> <tr> <td>Department:</td> <td>#fields.txtdeptname#</td> </tr> <tr> <td>E-Mail:</td> <td>#fields.txtemail#</td> <tr> <td>Phone:</td> <td>#fields.txtphonenum#</td> </tr> <table> </cfoutput> Application examples that use PDF forms The following examples show how you can use PDF forms in your applications. PDF submission example The following example shows how to populate fields in a PDF form created in LiveCycle Designer based on an employee login information.
  • Page 929 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports On the first processing page, a query retrieves all of the information associated with the user name from the cfdocexamples database. The tag populates an associated PDF form created in LiveCycle Designer (called cfpdfform timesheetForm.pdf) with the employee name, phone number, e-mail address, and department.
  • Page 930 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- The following code reads the PDF file submitted in binary format and generates a result structure called fields. The cfpdfform populate action and the cfoutput tags reference the fields in the structure. ---> <cfpdfform source="#PDF.content#"...
  • Page 931 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- The following code retrieves all of the employee information for the user name entered on the form page. ---> <cfquery name="getEmpInfo" datasource="cfdocexamples"> SELECT * FROM EMPLOYEES WHERE EMAIL = <cfqueryparam value="#FORM.username#"> </cfquery>...
  • Page 932 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <h3>Employee Login Form</h3> <p>Please enter your user name and password.</p> <cfform name="loginform" action="embed2.cfm" method="post"> <table> <tr> <td>user name:</td> <td><cfinput type="text" name="username" required="yes" message="A user name is required."></td> </tr> <tr> <td>password:</td> <td><cfinput type="password"...
  • Page 933 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports value="#getEmpInfo.FIRSTNAME# #getEmpInfo.LASTNAME#"> <cfpdfformparam name="txtDeptName" value="#getEmpInfo.DEPARTMENT#"> <cfpdfformparam name="txtEmail" value="#getEmpInfo.IM_ID#"> <cfpdfformparam name="txtPhoneNum" value="#getEmpInfo.PHONE#"> <cfpdfformparam name="txtManagerName" value="Randy Nielsen"> </cfpdfsubform> </cfpdfform> <!--- The following code creates the last document section. Page numbering resumes in this section.
  • Page 934 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfif #supplyReqs.name# is "NewRequest.pdf"> <cfset #supplyReqs.name# = "---New Supply Request---"> </cfif> <cfform name="fileList" action="supplyReq2.cfm" method="post"> <cfselect name="file" query="supplyReqs" value="name" display="name" required="yes" size="8" multiple="no"/><br/> <cfinput type="submit" name="submit" value="OK"> </cfform> <!--- supplyReq2.cfm ---> <!--- The following code displays the PDF form that the user selected.
  • Page 935: Assembling Pdf Documents

    DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Assembling PDF Documents You can use Adobe ColdFusion to assemble PDF documents. You create a unified document from multiple source files or pages from multiple files by using the tags.
  • Page 936 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports action extends the tag by providing a subset of Adobe LiveCycle Assembler functionality. You processddx cfpdf use the action to process Document Description XML (DDX) instructions explained in “Using DDX to...
  • Page 937 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Task Action Password-protect PDF documents cfpdf action="protect" newUserPassword =" xxxx " Set the initial view for a PDF document with the cfpdf action="processddx" InitialViewProfile element Create different versions of a PDF document Duplicate function to clone PDF variables Using shortcuts for common tasks...
  • Page 938 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Using a variable that contains an image file You can specify a variable that contains an image as a watermark. The following example shows how to create a form from which the user can select an image: <!--- The following code creates a form where you can choose an image to use as a watermark.
  • Page 939 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Create a query to extract artwork from the cfartgallery database. ---> <cfquery name="artwork" datasource="cfartgallery"> SELECT ARTID, ARTNAME, LARGEIMAGE FROM ART ORDER BY ARTNAME </cfquery> <!--- Create a form that lists the artwork titles generated by the query. Set the value to LARGEIMAGE so that the image file is passed to the processing page.
  • Page 940 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Create a blank image that is 500 pixels square. ---> <cfset myImage=ImageNew("",500,500)> <!--- Set the background color for the image to white. ---> <cfset ImageSetBackgroundColor(myImage,"white")> <!---Clear the rectangle specified on myImage and apply the background color. ---> <cfset ImageClearRect(myImage,0,0,500,500)>...
  • Page 941 <cfpdf action = "addheader" source = "../myBook.pdf" destination = "../myBookwithheader.pdf" text = "Adobe" align = "left"> Specify the source where the PDF document is located and the destination where the new PDF document with the header and footer will be saved.
  • Page 942 PDF document, as shown in the extracttext following code snippet: <cfpdf action = "extracttext" source = "../myBook.pdf" pages = "5-20, 29, 80" destination ="../adobe/textdoc.txt" action extracts all images from the specified page number in a PDF document, as shown in the extractimage following code snippet: <cfpdf action = "extractimage"...
  • Page 943 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfpdf action="protect" newOwnerPassword="splunge" source="timesheet.pdf" destination="timesheet.pdf" overwrite="yes" permissions="AllowPrinting"> To password-protect a document, set the user password. A user password controls the ability to open a document. If you set a user password for a document, any person attempting to open the file is prompted to enter a password. The following example sets the user password for a document: <cfpdf action="protect"...
  • Page 944 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfpdf action="write" source="confidential.pdf" password="paSSword1" destination="myDocument.pdf"> Managing PDF document information To retrieve information stored with a source PDF document, such as the creation date, the application used to create the PDF document, and the name of the person who created the document, use the action.
  • Page 945 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports • Create PDF packages To merge the contents of a directory, use the action and specify the directory where the source PDF files are merge located, as the following example shows: <cfpdf action="merge"...
  • Page 946 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Creating PDF Portfolios You can now create PDF packages using the attribute with the action: package = "true" merge <cfpdf action="merge" package="yes" destination="./myBook/adobetest.pdf" overwrite="yes"> <cfpdfparam source="./inputFiles/c.zip" > <cfpdfparam source="./inputFiles/d.jpg" > <cfpdfparam source="./inputFiles/a.pdf"...
  • Page 947 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports myBook_page_1.jpg myBook_page_2.jpg myBook_page_3.jpg myBook_page_100.jpg If you specify a destination, ColdFusion does not create the thumbnails directory and stores the files in the specified directory instead. The following code generates a thumbnail image called myBook_page_1.jpg from the first page of myBook.pdf and stores it in a directory called images, which is relative to the CFM page: <cfpdf action="thumbnail"...
  • Page 948 ColdFusion does not provide complete LiveCycle Assembler functionality. For a list of DDX elements that you can access from ColdFusion, see Supported DDX elements in the CFML Reference. For complete DDX syntax, see the Adobe LiveCycle Assembler Document Description XML Reference. Using DDX instructions with ColdFusion Although you can type DDX instructions directly in ColdFusion, typically you use an external DDX file.
  • Page 949 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- The following code verifies that the DDX file exists and the DDX instructions are valid. ---> <cfif IsDDX("merge.ddx")> To implement the DDX instructions in ColdFusion, you create two structures: an input structure that maps the DDX input instructions to the PDF source files, and an output structure that maps the DDX output instructions to a PDF output file, The following code maps two files called Chap1.pdf and Chap2.pdf to the Doc1 and Doc2 sources that you defined in...
  • Page 950 <_BookmarkTitle/> tag in the DDX file, ColdFusion throws an exception. This is because, the _BookmarkTitle tag is converted to TITLE and DDX is case-sensititve. For more information on the element, see the Adobe LiveCycle Assembler Document Description TableOfContents XML Reference.
  • Page 951 <p>Page <_PageNumber/> of <_LastPageNumber/></p> </StyledText> </Right> </Footer> The first page of the output file is numbered “Page 1 of n”, and so on. For more information on built-in keys, see the Adobe LiveCycle Assembler Document Description XML Reference. Last updated 1/20/2012...
  • Page 952 To apply the style profile, specify the name by using the attribute of the StyleProfile styleReference Header element, as the following example shows: <?xml version="1.0" encoding="UTF-8"?> <DDX xmlns="http://ns.adobe.com/DDX/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.adobe.com/DDX/1.0/ coldfusion_ddx.xsd"> <PDF result="Out1"> <PDF source="Title"/> <TableOfContents> <Header styleReference="TOCheaderStyle"/> </TableOfContents> <PDF source="Doc1"/>...
  • Page 953 To set the initial view of a PDF document, use the DDX element. Setting the initial view InitialViewProfile determines how the PDF output file is displayed on the screen when it is first opened in Adobe Acrobat Reader. You reference the by using the...
  • Page 954 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports For more information on settings, see the Adobe LiveCycle Assembler Document Description IntialViewProfile XML Reference. Adding text-string watermarks You use the action with the DDX elements to create a text-string watermark.
  • Page 955 </PDF> <PDF source="Doc4"/> </PDF> </DDX> For more information on using DDX instructions to create watermarks, see the Adobe LiveCycle Assembler Document Description XML Reference. Extracting text from a PDF document You can use the DDX element to return an XML file that contains the text in one or more PDF DocumentText documents.
  • Page 956 When you specify more than one source document, ColdFusion aggregates the pages into one file. The following example shows the DDX code for combining a subset of pages from two documents into one output file: <?xml version="1.0" encoding="UTF-8"?> <DDX xmlns="http://ns.adobe.com/DDX/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.adobe.com/DDX/1.0/ coldfusion_ddx.xsd">...
  • Page 957: Application Examples

    DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfpdfform source="acroform2.pdf" destinat ion="source_result1 7.pdf" action="populate" overwrite="true" fdf ="true"> <cfpdfsubform name="Text1"> <cfpdf subform name="0"> <cfp dfformparam name="0" val ue="Test1.0.0"> <cfpd fformparam name="1" value ="Test1.0.1"> <cfpdfformparam name="2" value="Test1.0.2"> </cfpdfsubform> <cfpdfsubform name="1"> <cfpdfformparam name="0"...
  • Page 958 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <h3>Downloading Federal Tax Documents</h3> <p>Please choose the type of your business.</p> <!--- Create the ColdFusion form to determine which PDF documents to merge. ---> <table> <cfform action="cfpdfMergeActionTest.cfm" method="post"> <tr><td><cfinput type="radio" name="businessType" Value="Sole Proprieter">Sole Proprietor</td></tr>...
  • Page 959 • Add headers and footers. • Add automatic page numbers. • Apply different styles to the table of contents and the body of the book. The following code shows the DDX file: <?xml version="1.0" encoding="UTF-8"?> <DDX xmlns="http://ns.adobe.com/DDX/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.adobe.com/DDX/1.0/ coldfusion_ddx.xsd"> <PDF result="Out1"> <PDF source="Doc0"/>...
  • Page 960 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports </Right> </Footer> </StyleProfile> <StyleProfile name="FooterStyle"> <Footer> <Left> <StyledText> <p font-size="9pt"><i>CFML Reference</i></p> </StyledText> </Left> <Right> <StyledText> <p font-size="9pt">Page <_PageNumber/> of <_LastPageNumber/></p> </StyledText> </Right> </Footer> </StyleProfile> </DDX> The following code shows the ColdFusion page that processes the DDX instructions: <cfif IsDDX("Book.ddx")>...
  • Page 961 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- The following code creates a simple form for entering a user name and password. The code does not include password verification. ---> <h3>Tax Login Form</h3> <p>Please enter your user name and your social security number.</p> <cfform name="loginform"...
  • Page 962 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- The following code retrieves all of the employee information for the user name entered on the login page. ---> <cfquery name="getEmpInfo" datasource="cfdocexamples"> SELECT * FROM EMPLOYEES WHERE EMAIL = <cfqueryparam value="#FORM.username#"> </cfquery>...
  • Page 963 DDX instructions in the watermark.ddx file to generate a text-string watermark and apply it to the form. The following code shows the contents of the watermark.ddx file: <?xml version="1.0" encoding="UTF-8"?> <DDX xmlns="http://ns.adobe.com/DDX/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.adobe.com/DDX/1.0/ coldfusion_ddx.xsd"> <PDF result="Out1">...
  • Page 964: Creating And Manipulating Coldfusion Images

    Creating and Manipulating ColdFusion Images You can use Adobe ColdFusion to create and manipulate images, retrieve and store images in a database, retrieve image information for indexes and searches, convert images from one format to another, and write images to the hard drive.
  • Page 965 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Task Functions and actions Enforce compression on JPEG images quality attribute of the write action of the cfimage tag or the ImageWrite function Convert an image from one image file format to another (for tag or functions cfimage...
  • Page 966 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Image functions ColdFusion provides more than 50 functions that expand on the functionality of the tag. You can pass Image cfimage images created with the tag to functions or create images with the function.
  • Page 967 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports action writes the file to the specified destination, which can be an absolute or relative path. The following write example shows how to create a ColdFusion image from a URL and write it to a file on the local storage drive: <cfimage source="http://www.google.com/images/logo_sm.gif"...
  • Page 968 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Use the cffile tag to read an image file, convert it to binary format, and write the result to a variable. ---> <cffile action = "readBinary" file = "jeff05.jpg" variable = "aBinaryObj"> <!--- Use the ImageNew function to create a ColdFusion image from the variable.
  • Page 969 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Creating an image from a Base64 string Base64 is a way to describe binary data as a string of ASCII characters. Some databases store images in Base64 format rather than as BLOB data. You can use the tag or the function to read Base64 data directly cfimage...
  • Page 970 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports To create a clone, you can pass a ColdFusion image variable to the function: Duplicate <!--- Use the ImageNew function to create a ColdFusion image from a JPEG file. ---> <cfset myImage=ImageNew("../cfdocs/images/artgallery/paul01.jpg")>...
  • Page 971 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfimage source="../cfdocs/images/artgallery/jeff01.jpg" action="convert" destination="jeff01.gif" name="myImage"> ColdFusion reads and writes most standard image formats. For more information, see Supported image file formats in the CFML Reference. Converting an image to a Base64 string To convert a ColdFusion image to a Base64 string, use the ImageWriteBase64 function.
  • Page 972 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Create a ColdFusion image named "myImage" from a file uploaded to the server. ---> <cfimage action="read" source="#fileUpload.serverFile#" name="myImage"> <!--- Determine whether the file is greater than 300 pixels in width or height. ---> <cfif ImageGetHeight(myImage) gt 300 or ImageGetWidth(myImage) gt 300>...
  • Page 973 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Create a ColdFusion image from a JPEG file. ---> <cfset myImage=ImageNew("../cfdocs/images/artgallery/jeff01.jpg")> <!--- Add a 5-pixel blue border around the outside edge of the image. ---> <cfset ImageAddBorder(myImage,5,"blue")> <!--- Add a 10-pixel magenta border around the blue border. ---> <cfset ImageAddBorder(myImage,10,"magenta")>...
  • Page 974 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- This example shows how to create a CAPTCHA image with the text "rEadMe" and write the image directly to the browser. ---> <cfimage action="captcha" fontSize="25" width="162" height="75" text="rEadMe" fonts="Verdana,Arial,Courier New,Courier"> Note: For the CAPTCHA image to display, the value must be greater than: times the number of...
  • Page 975 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfset ImageDrawText(myImage,"Congratulations!",10,50,attr)> To change the color of the text, use the function. This function controls the color of all ImageSetDrawingColor subsequent drawing objects on an image. In the following example, two lines of text, “Congratulations!” and “Gabriella”, inherit the color magenta.
  • Page 976 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Drawing controls apply to all subsequent drawing functions in an image; therefore, order is important. In the following example, the drawing stroke attributes defined in the attribute collection apply to the square and the two lines. Similarly, the color green applies to the rectangle and the square, while the color red applies only to the two lines.
  • Page 977 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- This example shows how to specify the height and width of an image in pixels. ---> <cfimage source="../cfdocs/images/artgallery/jeff01.jpg" action="resize" width="100" height="100" destination="jeff01_sm.jpg"> <!--- This example shows how to specify the height and width of an image as percentages. ---> <cfimage source="../cfdocs/images/artgallery/jeff02.jpg"...
  • Page 978 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- This example shows how to resize an image to a 100-pixel square, while maintaining the aspect ratio of the source image. ---> <cfimage source="../cfdocs/images/artgallery/jeff05.jpg" name="myImage" action="read"> <!--- Turn on antialiasing. ---> <cfset ImageSetAntialiasing(myImage)>...
  • Page 979 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- This example shows how to create a watermark from an existing image. ---> <!--- Create two ColdFusion images from existing JPEG files. ---> <cfimage source="../cfdocs/images/artgallery/raquel05.jpg" name="myImage"> <cfimage source="http://www.google.com/images/logo_sm.gif" name="myImage2"> <cfimage source="#myImage#"...
  • Page 980 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- This example shows how to draw a red circle with a line through it and use it as a watermark. ---> <!--- Use the ImageNew function to create a ColdFusion image that is 201x201 pixels. ---> <cfset myImage=ImageNew("",201,201)>...
  • Page 981 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Generating thumbnail images The following example shows how to create a form for uploading images. A visitor to the site can use the form to upload an image file and generate a thumbnail image from it. You use ColdFusion image operations to perform the following tasks: •...
  • Page 982 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Save the thumbnail image to a file with the new filename. ---> <cfimage source="#myImage#" action="write" destination="#newImageName#" overwrite="yes"> <cfoutput> <p> Thank you for uploading the image. We have created a thumbnail for your picture.
  • Page 983 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Example <!--- Create a query to extract artwork and associated information from the cfartgallery database. ---> <cfquery name="artwork" datasource="cfartgallery"> SELECT FIRSTNAME, LASTNAME, ARTNAME, DESCRIPTION, PRICE, LARGEIMAGE, ISSOLD, MEDIATYPE FROM ARTISTS, ART, MEDIA WHERE ARTISTS.ARTISTID = ART.ARTISTID AND ART.MEDIAID = MEDIA.MEDIAID ORDER BY ARTNAME...
  • Page 984 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Using CAPTCHA to verify membership The following example shows how to create a simple form to verify whether a person (rather than a computer generating spam) is registering to receive an online newsletter. You generate the CAPTCHA image from a random text string on the form page and verify the response on the action page.
  • Page 985 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Verify whether the text entered by the user matches the CAPTCHA string. ---> <cfif #form.hashval# eq Hash(#form.userInput#)> <cfoutput> <p> Thank you for registering for our online newsletter, #form.firstName# #form.lastName#. </p>...
  • Page 986 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Determine whether a valid image file exists. ---> <cfif IsImageFile("../cfdocs/images/artgallery/#form.art#")> <cfset original=ImageNew("../cfdocs/images/artgallery/#form.art#")> <!--- Use the ImageNew function to create a clone of the ColdFusion image. ---> <cfset clone1=ImageNew(original)> <!--- Use the ImageSharpen function to blur the cloned image. ---> <cfset ImageSharpen(clone1,-1)>...
  • Page 987: Creating Charts And Graphs

    You can create 11 types of charts in Adobe ColdFusion in two and three dimensions. The following figure shows a sample of each type of chart. Last updated 1/20/2012...
  • Page 988 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Note: In two dimensions, bar and cylinder charts appear the same, as do cone and pyramid charts. Creating a basic chart You can create a chart in either of the following ways: •...
  • Page 989 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Description cfchart Specifies the container in which the chart appears. This container defines the height, width, background color, labels, fonts, and other characteristics of the chart. Include at least one tag within the tag.
  • Page 990 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Charting individual data points When you chart individual data points, you specify each data point by inserting a tag in the cfchartdata tag body. For example, the following code creates a simple pie chart: cfchartseries <cfchart>...
  • Page 991 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports This example displays the values in the AvgByDept column of the DataTable query. It displays the Dept_Name column value as the item label by each bar. The following table lists the attributes of the tag that you use when working with queries: cfchartseries Attribute...
  • Page 992 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <!--- Bar chart, from DeptSalaries Query of Queries. ---> <cfchart xAxisTitle="Department" yAxisTitle="Salary Average" font="Arial" gridlines=6 showXGridlines="yes" showYGridlines="yes" showborder="yes" show3d="yes" > <cfchartseries type="bar" query="DeptSalaries" valueColumn="AvgByDept" itemColumn="Dept_Name" seriesColor="olive" paintStyle="plain" /> </cfchart> <br> </body>...
  • Page 993 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Code Description <cfquery name="GetSalaries" datasource="cfdocexamples"> Query the cfdocexamples database to get the Dept_Name SELECT Departmt.Dept_Name, Employee.Salary and Salary for each employee. Because the Dept_Name is FROM Departmt, Employee in the Departmt table and the Salary is in the Employee WHERE Departmt.Dept_ID = Employee.Dept_ID table, you need a table join in the WHERE clause.
  • Page 994 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports One use of combining queries and data points is to provide data that is missing from the database; for example, to provide the data for one department if the data for that department is missing. The example in the following procedure adds data for the Facilities and Documentation departments to the salary data obtained from the query shown in the previous section: Open the chartdata.cfm file in your editor.
  • Page 995 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports You can also combine chart types. The following is a combination bar and line chart: The only chart type that you cannot mix with others is the pie chart. If you define one of the data series to use a pie chart, no other chart appears.
  • Page 996 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports <cfchart backgroundColor="white" xAxisTitle="Department" yAxisTitle="Salary Average" font="Arial" gridlines=6 showXGridlines="yes" showYGridlines="yes" showborder="yes" > <cfchartseries type="line" seriesColor="blue" paintStyle="plain" seriesLabel="Contract Salaries" > <cfchartdata item="HR" value=70000> <cfchartdata item="Marketing" value=95000> <cfchartdata item="Sales" value=80000> <cfchartdata item="Training" value=93000> </cfchartseries>...
  • Page 997 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports • yellow To use any of these styles, specify the style using the attribute of the tag. The following example style cfchart illustrates using the style: beige <cfchart style="beige"> <cfchartseries type="pie"> <cfchartdata item="New car sales"...
  • Page 998 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Chart characteristic Attributes used Description Chart type Labels font font attribute specifies the font for all text. The default value Arial . If you are using a double-byte character set on UNIX, or fontSize using a double-byte character set in Windows with a file type of Flash, specify...
  • Page 999 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Chart characteristic Attributes used Description Chart type Value axis scaleFrom The minimum and maximum points on the data axis. Area scaleTo By default, the minimum is 0 or the lowest negative chart data value, and the maximum is the largest data value.
  • Page 1000 DEVELOPING COLDFUSION 9 APPLICATIONS Working with Documents, Charts, and Reports Chart characteristic Attributes used Description Chart type Multiple series attribute specifies the text that displays for the seriesLabel seriesLabel series label. seriesColor attribute specifies a single color of the bar, line, seriesColor pyramid, and so on.

This manual is also suitable for:

Coldfusion 9

Table of Contents