Basic CFML


ColdFusion is not a difficult language to learn. It's rather easy in fact that's one of its many strengths. CFML is a tag-based language much like the typical HTML that we see in the majority of websites today. As the web becomes more and more interactive and dynamic, tools like ColdFusion enable developers and application users to get the most out of their web browsing experience.

CFML can be written in any text editor, such as Notepad, and can also be constructed by some WYSIWIG (what you see is what you get) tools. It is best to develop your ColdFusion code with an application that enables you to have full control over the code that you write and that does not try to "clean it up" before viewing or saving your files.

Macromedia provides several development tools that are great for writing ColdFusion code. Those tools include Macromedia's ColdFusion Studio, HomeSite, and Dreamweaver UltraDev. As of the writing of this book, the preview release of Dreamweaver MX is out, which now includes the functionality that was in Dreamweaver UltraDev. We've been told that ColdFusion Studio no longer will be sold as a separate product, but that most of the functionality will be rolled into Dreamweaver MX. It remains to be seen what functionality is left out and if Macromedia rolls out subsequent updates to the Dreamweaver MX product.

ColdFusion files are called templates. Your ColdFusion applications can be made up of one or more ColdFusion templates. ColdFusion templates, because they are viewed through a web browser, must be constructed with valid HTML. In other words, you should begin your template with an opening HTML tag and end the template with a closing HTML tag. Of course, you can include ColdFusion tags before or after those because CFML is read by the ColdFusion Server and standard HTML is returned to the web browser. The basic format of a simple HTML document is shown in Listing 4.1.

Listing 4.1 Standard HTML Document Structure
 <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">  <html>  <head>          <title>Example HTML</title>  </head>  <body>     Look Mom! I'm a real web page programmer now!  </body>  </html> 

Before we start to hammer out some code, we need to ensure that we understand some of the most fundamental concepts of ColdFusion development. First and foremost, let's discuss the ColdFusion development process.

ColdFusion Development Process

The ColdFusion development process is the process of creating and testing ColdFusion templates. This process consists of three easy steps:

  1. Code. In this step of the process, you construct your ColdFusion template.

  2. Save. You must now save the template before you can test it.

  3. View. Finally, view the template in a browser to test the accuracy of the code returned from the ColdFusion Server.

I'm sure that you are thinking that the process that I've just described is a no-brainer, but you'd be surprised at how many people forget to save their templates.

ColdFusion templates, like HTML files, should be stored in a directory that is accessible to the web server. The default directory is called the root web directory, or webroot. If you're running on a Windows platform, your default webroot would be c:\inetpub\wwwroot.

You can create another directory to store the sample code that we walk through in this book. Let's call it insidecfmx. Save the code in Listing 4.1 into the c:\inetpub\wwwroot\insidecfmx directory. Save the template as c:\inetpub\wwwroot\insidecfmx\4.1.htm. Now, if you have a web server installed, you should be able to view this template at http://127.0.0.1/insidecfmx/4.1.htm. Of course, we've saved this as an HTML file. Next, let's save it as a CFML template.

CFML templates should always be saved with a .cfm or .cfml extension. This is how the web server knows to pass the template along to the ColdFusion Application Server. Let's save our file as c:\inetpub\ wwwroot\insidecfmx\4.1.cfm. View the file at http://127.0.0.1/insidecfmx/4.1.cfm. If you are able to view this file, your ColdFusion Server is working. You have created a ColdFusion template. However, there is nothing in it that is truly dynamic. Remember that the delivery of dynamic content is one of the strengths of ColdFusion. We take advantage of this strength later on.

Tag Syntax

I mentioned earlier in the chapter that CFML tags closely resemble HTML tags. All ColdFusion tags begin with the letters "CF". Like HTML tags, most CFML tags are written with both opening and closing tags, <CFMYTAG> and </CFMYTAG>, respectively. Check out the following example of a CFQUERY tag used to query a datasource for user records.

Listing 4.2 An Example of ColdFusion Template Syntax
 <!--- Get user records from the database --->  <cfquery name="q_GetUsers" datasource="ICFMX_Data">     SELECT *     FROM Users  </cfquery>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html>  <head>       <title>ColdFusion Template Syntax</title>  </head>  <body>  <!--- Display user records in the browser --->  <table align="center" width="400">     <tr>        <td>Users</td>     </tr>  <cfoutput query="q_GetUsers">     <tr>        <td>#q_GetUsers.FName# #q_GetUsers.LName#</td>     </tr>  </cfoutput>  </table>  </body>  </html> 

In Listing 4.2, we have the opening CFQUERY tag with two of the tag's attributes, a simple SQL statement, and then our closing CFQUERY tag. Notice also that the query name starts with the characters q_. Keep this in mind when we discuss naming conventions later.

Some CFML tags do not require an end tag. It has been noted that those tags can be written in a format that follows the eXtensible Markup Language (XML) format for tags that do not require end tags. Those tags could be written as <CFMYTAG/>. However, ColdFusion code is interpreted by the ColdFusion Application Server and returned to the browser as HTML, with none of the ColdFusion code visible to the browser, so it might make sense to write tags in this manner only if it is part of your overall coding standard.

Comments

You might have noticed a bit of code in Listing 4.2 that looked like this: <!--- CFML COMMENT --->. This was a ColdFusion comment. Commenting code is a fundamental part of application development. Most seasoned developers make an effort to comment their code thoroughly. They know that commenting their code makes sense for a number of reasons:

  • Comments help to identify a template and its purpose and can note the date that the code was created, any revisions that have been performed, and who performed the revisions.

  • Comments help to break up large chunks of code into smaller, more readable sections.

  • Comments help developers to understand sections of code long after development was completed.

  • Comments help to explain coding standards and development processes.

ColdFusion comments are formatted much like comments in HTML. There are a few differences between HTML and CFML comments. The most noticeable difference is that HTML comments are formatted with one less dash (-) character.

 <!--- HTML COMMENT ---> 

ColdFusion comments again have a very similar structure but have one additional dash as the comment opens and one extra dash when the comment closes.

 <!--- CFML COMMENT ---> 

The other difference is that ColdFusion comments are not visible in the HTML code that is generated by the ColdFusion Application Server. ColdFusion comments, like all ColdFusion tags, are interpreted by the ColdFusion Server and standard HTML is returned to the browser. HTML comments, however, do show up in the HTML code that the browser displays. For this reason, use only CFML comments to make comments in your template that refer to code structure, variables, naming conventions, or anything else that your application or web site users do not need to see.

Data Types

ColdFusion is a typeless language. To ColdFusion, data has no type; however, because many applications depend on tracking the variable type of the data, ColdFusion supports several data types.

Data can be divided into two primary types, simple and complex. A simple data type can be a number or integer. A more complex data type might be a list of numbers or values (the list is actually a string), arrays of values, queries, or structures.

Let's take a closer look at the data types that ColdFusion supports (see Table 4.1).

Table 4.1. Data Types Supported by ColdFusion

Data Type

Description

SIMPLE DATA

 

Booleans

ColdFusion uses Booleans to store logical values, TRUE or FALSE. Boolean values also equate 1 or Yes to TRUE and 0 or No to FALSE.

Date/time

Date values from 100 AD to 9999 AD and times in 24-hour clock format or a.m./p.m. Date/time values can be formatted in numerous ways.

Integers

Whole numbers without decimal points. Numbers can be noted as regular numbers or in scientific notation.

Decimal numbers

Also known as floating-point numbers. Mathematical operations can be performed on integers and decimal numbers with an accuracy of up to 12 decimal points.

Strings

Text values that must be enclosed in single or double quotes.

COMPLEX DATA

 

Arrays

Values that are stored and identified by numeric indexes. Each value is called an element. Arrays can store any ColdFusion data type, including other arrays.

Lists

A string of values that are separated by some delimiter. The values can be numbers or strings. Technically, any sentence could be considered a list that is delimited by a space.

COM objects

Component objects written in component object model (COM), Common Object Request Broker Architecture (CORBA), and Java.

Queries

ColdFusion data objects that often contain a record set. You can manually create query objects or they can be constructed by ColdFusion as the result of a database query, an execution of a stored procedure, or an execution of one of several ColdFusion tags.

Structures

ColdFusion data type that stores values as key-value pairs. Can store simple or complex data types.

CFML offers numerous built-in functions to enable developers to programmatically manipulate the data types listed in Table 4.1. ColdFusion also provides functions that determine the data type of the value.

Variables

Values within a ColdFusion application are stored in variables. Variables are the constructs that hold any of the data types that we looked at in Table 4.1. There are several methods of setting variables within ColdFusion. You can use the CFSET or CFPARAM tag, or you can create the variable within a CFSCRIPT block. The most common of these methods is the use of the CFSET tag.

Unlike creating variables in some languages, ColdFusion enables us to create the variable and assign the value of the variable at the same time. Using CFSET, variables are created in the following manner:

 <cfset version_name="ColdFusion MX"> 

In Table 4.1, we pointed out that strings must be enclosed by single or double quotes. The CFSET tag also does not have an end tag. If we set a variable whose value is numeric, the code would look like this:

 <cfset version_number=6> 

or like this:

 <cfset version_number="6"> 

ColdFusion is a typeless language and does not make a distinction between strings and integers. Be careful when you set the value of one variable to another variable. For example, if we set a variable called firstname to "Neil", we then could set another variable to that same value by referring to the first variable:

 <cfset firstname="Neil">  <cfset myname=firstname> 

In the second CFSET, the value of the variable myname is the first variable that we set firstname. Had we written this:

 <cfset myname="firstname"> 

the double quotes would have indicated to ColdFusion that firstname is a literal string and not a variable that we are evaluating.

There are a few rules that you must follow regarding variables:

  • Start variable names with a letter and have the name contain only letters, numbers, and underscore characters.

  • Do not use reserved words as variable names.

  • Do not use ColdFusion variable scopes as variable names.

  • Be consistent with your naming conventions and styles.

Variables can also be created using the CFPARAM tag. The difference between the CFPARAM and the CFSET tags is that the CFPARAM tag checks whether the variable already exists prior to creating it. If it does exist, the CFPARAM tag creates it and sets a default value. If it does exist, the CFPARAM tag does nothing. The CFPARAM tag is formed like this:

 <cfparam name="version_name" default="ColdFusion MX"> 

For those of you who are accustomed to scripting languages, you might feel more comfortable creating variables and setting their values within a CFSCRIPT block. We get into a much deeper discussion of CFSCRIPT later in the book in Chapter 13, "CFScript." For now, however, let's take a look at the syntax for setting variables in CFSCRIPT:

 <cfscript>     version_name="ColdFusion MX";  </cfscript> 

Inside the CFSCRIPT block, the variable is declared and the value is set at the same time. In addition, the operation ends with a semicolon. If you forget the semicolon or forget to put a string in quotes, you'll get a ColdFusion error.

Variable Scopes

Variable scope refers to the circumstance in which the variable can be used. It tells us facts about the variable, including where it originated, how we can use it, and where and when we can use it. Scope also describes the prefix that is appended to the variable name. This prefix helps to differentiate variables of different scopes that might have the same name.

There are different variable scopes within ColdFusion, and it is important to understand them all. ColdFusion's variable scopes include the following:

  • Local. The variables that we have created so far are local variables. Local variables are accessible only within the template in which they were created or in any template "included" (we'll discuss includes later) into that template after the creation of the variable. Local scoped variables are referred to with the prefix variables. Local variable references are written as variables.variable_name.

     <cfset variables.today="March 1, 2002"> 

  • Form. Form variables are created when a user fills out a form in a ColdFusion template and submits the form. The form can be either an HTML form or a ColdFusion form (which is actually an HTML form). Form variables are passed from the template where the form resides to another template where those variables are acted upon. That template is usually referred to as the action page. The variables are passed as key-value pairs with the key being the name of the form field and the value being the associated value. Form variables are referred to with the prefix form. Form variable references are written as form.form_field_name. There is one form variable that is sent to your action page by default; it is called fieldnames. It can be referred to as form.fieldnames and contains a comma-delimited list of all field names that were sent from the form.

  • URL. URL variables are key-value pairs that are passed along the requested URL. These key-value pairs are referred to as URL parameters. A Hypertext Transfer Protocol (HTTP) request that contains URL parameters might look like this:

     http://www.insidecoldfusionmx.com/index.cfm?display_code=Tips 

    When you make this request, you are requesting that index.cfm be loaded into the browser. You are passing a variable called display_code with a value of Tips into that template. Your index.cfm template would access the URL variable as url.display_code.

  • Query. Query variables exist within a ColdFusion query object. Query variables are referred to as query_name.variable_name. In most cases, this query object is the result of a ColdFusion database query or stored procedure that returns a recordset that includes multiple columns and rows along with their values. For example, if we had a query called getAuthors and we wanted to get the full names and email addresses of the authors from the database, we would refer to those variables as getAuthors.full_name and getAuthors.email. (ColdFusion is not case-sensitive, so it might help to use mixed-case lettering to make your code easier to read.)

  • CGI. The common gateway interface (CGI) scope is made up of readonly server and browser-specific variables. The exact variables that are accessible at any given time depend on the server software and browser client being used. CGI variables are available anywhere in your application. CGI variables are referred to as cgi.variable_name.

    Checking on CGI Variables

    If you want to know which CGI variables are currently accessible to you, drop the following code into your template.

     <cfdump var="#cgi#"> 

    We discuss the CFDUMP tag later in the book.

  • File. File variables are created by ColdFusion as a result of using the CFFILE tag to upload files. File variables are read-only and can be referred to as file.variable_name.

  • Cookie. Cookie variables hold the values of all the cookies that the web server retrieved from the user's browser. Cookies persist on the client machine until they expire or are deleted. Cookie variables can be referred to as cookie.variable_name.

  • Application. Application variables are persistent variables that are available to any template in an application. They are commonly used to set datasource names and directory path references within an application. After they are created, application variables are available to all clients throughout the application until the ColdFusion service is restarted. Application variables can be referenced as application.variable_name.

    Application variables must be enabled prior to use. You enable them within the ColdFusion Administrator as well as within your application rcode.

  • Session. Session variables are another kind of persistent variable. They exist, as you might expect, for the life of a single user session. All information that is stored in the session variable is specific to that single user and is destroyed when the session ends. Session variables are commonly used to store user shopping cart information and to retain user preference information after a login. Session variables can be referred to as session.variable_name.

    Session variables must be enabled prior to use. You enable them within the ColdFusion Administrator as well as within your application code.

  • Server. A server variable is another persistent variable that stores data associated with the server computer on which ColdFusion is installed and running. Server variables are stored in the system memory and are available to all clients on all applications on the server. Server variables persist until the ColdFusion Server is restarted. Server variables are referenced as server.variable_name.

  • Client. As another persistent variable scope, client variables store information related to a particular user. Client variables are used to maintain the client's state within the application. Client variables can persist across multiple sessions and can be stored in the server's registry, in cookies, or in a database. Client variables are referenced as client.variable_name.

  • Attributes. The attributes scope is a variable scope that is unique to custom tags. They enable you to refer to values that are passed into the custom tag from the page that calls the custom tag the calling page. Attributes are always referenced as attributes.variable_name.

  • Caller. The caller scope is another variable scope that is unique to custom tags. The caller scope is similar to the attributes scope but passes values from within the custom tag back to the calling page. Caller scope variables are set as caller.variable_name and are referred to on the calling page as a local scoped variable.

  • Request. The variables in the request scope are stored in a ColdFusion structure. Request variables are accessible for a single request. The request scope is accessible in nested custom tags. All request variables must be referred to with the request prefix, as in request.variable_name.

Sometimes, developers do not specify a scope for every variable that they create. This practice is detrimental to ColdFusion Server performance because it must search for the proper variable scope. ColdFusion searches for it in the following sequence:

  1. Local variables created using CFSET and CFQUERY

  2. CGI

  3. File

  4. URL

  5. For m

  6. Cookie

  7. Client

Expressions

Expressions are the most basic building blocks of ColdFusion code. Very simple expressions can be variable names or values. More complex expressions might include two or more values on which you can use operators to perform calculations and comparisons. Let's take a look at a simple expression:

 <cfset variables.firstval=12> 

We've created a local variable called firstval. The expression that is its value is the number 12:

 <cfset variables.sum=variables.firstval+12>  <cfset variables.sum=12+12> 

Now we've created a local variable called sum. Its value is derived by a complex expression in which we've used the operator for addition to act on the values. Both examples result in the same value.

Operators

Operators are ColdFusion constructs that enable you to perform calculations or compare expressions. There are four basic types of operators in ColdFusion:

  • Arithmetic. Arithmetic operators perform mathematical calculations on expressions. Arithmetic operators include +, -, *, /, MOD, and ^.

  • Boolean. Boolean operators perform local operations on expressions. They return Boolean values of TRUE or FALSE. Boolean operators include NOT, AND, OR, XOR, EQV, and IMP.

  • Comparison. Simply compares two expressions and returns a Boolean of TRUE or FALSE. Comparison operators are also known as decision operators. Comparison operators include IS, IS NOT, CONTAINS, DOES NOT CONTAIN, GREATER THAN, LESS THAN, GREATER THAN OR EQUAL TO, and LESS THAN OR EQUAL TO.

  • String. The string operator is used to concatenate expressions. The only string operator in ColdFusion is the ampersand (&).

Functions

ColdFusion functions enable you to perform defined sets of operations on an expression. Functions also return a value inline. ColdFusion has more than 270 built-in functions and enables developers to write their own functions, known as user-defined functions (UDFs).

Functions serve many purposes within a ColdFusion application. Some ColdFusion functions require that you provide parameter arguments on which they can perform operations. A few functions, such as the Now() function, require no parameters.

ColdFusion functions can be divided into functional groupings:

  • Array functions

  • Authentication functions

  • Conversion functions

  • Date and time functions

  • Decision functions

  • Display and formatting functions

  • Dynamic evaluation functions

  • International functions

  • List functions

  • Mathematical functions

  • Query functions

  • String functions

  • Structure functions

  • System functions

  • XML functions

  • Other functions

By way of example, let's take a look at a couple commonly used ColdFusion functions. For instance, functions are used to determine and format dates:

 <cfset variables.todays_date=DateFormat(Now(), "mm/dd/yyyy")> 

Functions are also used to determine data type:

 <cfset variables.isthisanumber=IsNumeric("Hello")> 

Summary

CFML is a language that is easy to read and understand. We're about ready to start writing code. It's important however to understand the concepts that we've covered thus far:

  • Development process

  • Code syntax

  • Data types

  • Variable scope

  • Expressions

  • Operators

  • Functions



Inside ColdFusion MX
Inside Coldfusion MX
ISBN: 0735713049
EAN: 2147483647
Year: 2005
Pages: 579

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net