Try an online ColdFusion class for free!
Additional Resources

ColdFusion Basics

In this lesson of the ColdFusion tutorial, you will learn...
  1. How ColdFusion works.
  2. The basics of ColdFusion Markup Language (CFML).
  3. To write a simple ColdFusion page.
  4. To use ColdFusion operators.
  5. To pass values from one page to another via the URL.
  6. To process a form with ColdFusion.

How ColdFusion Works

ColdFusion MX 7 code is compiled into Java bytecode, making it extremely portable, flexible and powerful. ColdFusion is made up of two parts:

  1. ColdFusion Application Server
  2. ColdFusion Markup Language (CFML)

ColdFusion Application Server

When a user navigates in a browser to a page that ends with a .cfm extension, the request is sent to a Web server, which directs the request to the ColdFusion Application Server (CFAS).

As shown in the diagram above, the CFAS processes the page, communicating with the file systems, databases, and email servers as necessary, and then delivers a web page to the web server to return to the browser.

ColdFusion Markup Language

The ColdFusion Markup Language (CFML) looks very similar to HTML or XML in that it is tag-based. A ColdFusion page generally has a mix of HTML and ColdFusion tags, and may contain other tags as well. ColdFusion tags can be distinguished from all other tags by their first two letters - cf (e.g, <cfloop>).

ColdFusion Variables

ColdFusion is weakly typed, meaning that you do not have to specify the data type that a variable holds. Rather, ColdFusion determines the data type of a variable at the time the variable is used. A common way to set a variable is with the <cfset> tag.

<cfset firstname = "Paul">
<cfset age = 63>

Variable Names

In ColdFusion, variable names:

  • consist of letters, digits, underscores, and dollar signs
  • cannot begin with a digit
  • are case-insensitive

Variable Prefixes and Scope

There are many different flavors of variables in ColdFusion:

  • variables specific to a page
  • variables specific to a user's session
  • variables specific to an entire application
  • etc.

These flavors of variables each have a different scope, which determines where and how long a variable exists. For example, variables specific to a user's session are of the Session scope. They exist for the duration of the session and are accessible on every page that is a part of the session. Variables specific to a page (i.e, Local variables) are of the Variables scope.

A prefix is used to specify the scope of a variable. The syntax is shown below.

Syntax
SCOPE.VariableName

The following table shows several variable scopes and their prefixes. Prefixes are not required for variables of all scopes. Required prefixes are in bold.

Variable Scope
Scope Prefix Description
Local VARIABLES Defined and accessible on the current page only.
CGI CGI Accessible on any page. Contains server environment variables.
URL URL Accessible on the current page. Contains values passed in on the query string.
Form FORM Accessible on the current page. Contains values passed in through a form.
Cookie COOKIE Accessible on any page. Contains variables held in cookies on the client machine.
Client CLIENT Accessible on any page. Contains variables created using the Client prefix.
Arguments ARGUMENTS Defined and accessible within a user-defined function or a ColdFusion Component method.
Session SESSION Prefix Required. Accessible on any page to a single user for the duration of a client session.
Application APPLICATION Prefix Required. Accessible on any page to all users until the application is restarted.
Server SERVER Prefix Required. Accessible on any page that is delivered from specific server.

Variables of different scopes can have the same names. For example, a local variable could have the same name as a form variable. If such a variable is referred to without a prefix, ColdFusion needs to know which variable to use. ColdFusion will search through the scopes in the following order:

  1. Arguments
  2. Local (Variables)
  3. CGI
  4. URL
  5. Form
  6. Cookie
  7. Client

In general, it is a good idea to include the prefix when referring to variables as this will help avoid confusion and could make the page process more quickly as ColdFusion will know exactly where to look for the variable.

Using <cfoutput>

A ColdFusion page is generally a mixture of CFML tags, HTML tags, and plain text. ColdFusion ignores any content that is not contained within a CFML tag. That is, content outside of CFML tags is returned as is to the browser.

The <cfoutput> tag is used to tell ColdFusion to attempt to evaluate any variable or expressions contained within pound signs (#). Let's take a look at an example. You guessed it - "Hello World".

Code Sample: Basics/Demos/HelloWorld.cfm

<cfset VARIABLES.greeting="Hello">

<html>
<head>
 <title>Hello World!</title>
</head>
<body>
 <cfoutput>#VARIABLES.greeting# World!</cfoutput>
</body>
</html>
Code Explanation

The code isn't very exciting. In fact, ColdFusion doesn't buy us anything here as we could have just as easily output the code using HTML. There is nothing dynamic about the script. Let's try something a little more interesting.

Passing Variables on the URL

A common way to pass values from the browser to the server is by appending them to the URL as follows:

http://webucator.com/hello.cfm?greet=Hello&person=World
   

The part of the url that follows the question mark is called the query string. One or more name-value pairs can be passed to the server in this way. Each name-value pair is separated by an ampersand (&). The processing page can read these name-value pairs and use them to determine its response.

The HTML page below shows an example of how these name-value pairs might be passed.

Code Sample: Basics/Demos/HelloHi.html

<html>
<head>
 <title>Preferred Greeting</title>
</head>
<body>
 Do you prefer a formal greeting or an informal greeting?
 <ul>
 <li><a href="HelloHi.cfm?greet=Hello">Formal</a></li>
 <li><a href="HelloHi.cfm?greet=Hi">Informal</a></li>
 <li><a href="HelloHi.cfm?greet=Howdy">Friendly</a></li>
 </ul>
</body>
</html>

Code Sample: Basics/Demos/HelloHi.cfm

<html>
<head>
 <title><cfoutput>#URL.greet#</cfoutput> World!</title>
</head>
<body>
<cfoutput>#URL.greet# World!</cfoutput>
</body>
</html>
Code Explanation

The <cfoutput> tags tell ColdFusion to look for variables and expressions to evaluate. Within <cfoutput> tags, any content not in pound signs (#) is simply ignored. Another way to write this page would be to replace the two sets of <cfoutput> tags with an open <cfoutput> tag before the open <html> tag and a close </cfoutput> tag after the close </html> tag.

Note that <cfoutput> tags, as a general rule, cannot be nested. (see footnote)

ColdFusion Comments

ColdFusion comments are similar to HTML comments except that they take three dashes instead of two.

<!-- This is an HTML comment -->
<!--- This is a ColdFusion comment --->

Exercise: Passing Variables via the Query String

Duration: 10 to 20 minutes.

In this exercise, you will write a script that says hello to different people based on what is passed through the query string.

  1. Open Basics/Exercises/HelloWho.html in your editor.
  2. Modify HelloWho.html so that each Beatle name is a link passing the name of that Beatle (Paul, John, George or Ringo) to HelloWho.cfm.
  3. Open Basics/Exercises/HelloWho.cfm in your editor.
  4. Modify HelloWho.cfm so that it outputs a greeting based on the link that is clicked on HelloWho.html.
  5. Test your solution in a browser.

Code Sample: Basics/Exercises/HelloWho.html

<html>
<head>
 <title>Greeting the Beatles</title>
</head>
<body>
 Choose a Beatle to greet.
 <ul>
 <li><a href="HelloWho.cfm">Paul</a></li>
 <li><a href="HelloWho.cfm">John</a></li>
 <li><a href="HelloWho.cfm">George</a></li>
 <li><a href="HelloWho.cfm">Ringo</a></li>
 </ul>
</body>
</html>

Code Sample: Basics/Exercises/HelloWho.cfm

<html>
<head>
 <title></title>
</head>
<body>

</body>
</html>

Change the links so that each Beatle gets a custom greeting (e.g, Howdy Paul, Hi John, Bye George, Hey Ringo).

HTML Forms and ColdFusion Variables

How HTML Forms Work

A very common way to submit data to a web server is through HTML forms. There are two methods of submitting data through a form: the get method and the post method. The method used is determined by the value of the method attribute of the form tag. The default method is get.

Get Method

When the get method is used, data is sent to the server in name-value pairs as part of the query string. The get method is most commonly used by search pages and is useful when it is important to be able to bookmark the resulting page (i.e, the page that is returned after the form is submitted).

Post Method

When the post method is used, data is sent to the server in name-value pairs behind the scenes. The two major advantages of the post method are:

  1. The name-value pairs are not visible in the location bar, so sensitive data such as passwords are not displayed on the screen.
  2. Files, such as images and Office documents, can be uploaded via the form.

The major disadvantage is that the resulting page cannot be bookmarked.

A Sample HTML Form

The following is a sample HTML form for calculating the time it takes to run a specified distance at a specified speed.

Code Sample: Basics/Demos/Calculator.html

<html>
<head>
 <title>Marathon Time Calculator</title>
</head>
<body>

<h1>Marathon Time Calculator</h1>

<form method="post" action="ProcessCalculator.cfm">
<table>
<tr>
 <td>Your Name:</td>
 <td><input name="yourname" type="text" size="30"></td>
</tr>
<tr>
 <td>Your Speed:</td>
 <td><input name="yourspeed" type="text" size="4"></td>
</tr>
<tr valign="top">
 <td>Friend's Name:</td>
 <td><input name="friendname" type="text" size="30"></td>
</tr>
<tr>
 <td>Friend's Speed:</td>
 <td><input name="friendspeed" type="text" size="4"></td>
</tr>
<tr>
 <td>Units</td>
 <td>
  <select name="units">
   <option value="mph">MPH</option>
   <option value="kph">KPH</option>
  </select>
 </td>
</tr>
<tr>
 <td colspan="2" align="right">
  <input type="submit" value="Calculate">
 </td>
</tr>
</table>
</form>

</body>
</html>
Code Explanation

The above is a simple HTML form and contains no embedded ColdFusion code. Its action page is ProcessCalculator.cfm, which would contain ColdFusion code for processing the submitted form.

Exercise: Processing Form Input

Duration: 15 to 25 minutes.

Next we will create a page that processes the form data. Our form entry page, excalculator- simpleform1.html, is already complete and is identical to democalculator- simpleform1.html above. Filled out, it would look like this:

  1. Our form entry page, Basics/Exercises/Calculator.html, is already complete and is identical to Basics/Demos/Calculator.html above. Filled out, it would look like this:
  2. In this exercise, we will create a page that simply outputs the form entries as a list.
  3. Open Basics/Exercises/ProcessCalculator.cfm in your editor.
  4. Output the form variables as list items using <cfoutput>.
  5. Save your work and test your solution in the browser by navigating to Basics/Exercises/Calculator.html and submitting the form.

Code Sample: Basics/Exercises/ProcessCalculator.cfm

<html>
<head>
 <title>Calculator Entries</title>
</head>
<body>
<h1>Calculator Entries</h1>

You have entered:
<ul>
<!---
 Add list items that display your name,
 your friend's name, your speed,
 your friend's speed, and the units.
--->
</ul>

</body>
</html>

Built-in Functions

ColdFusion has many built-in functions for performing all sorts of tasks, such as manipulating strings, formatting data, managing dates and times, parsing XML, etc.

The syntax of a function is functionname(arguments), where arguments is a list of zero or more values passed to the function.

Like variables, function names are case-insensitive.

It is impossible (at least for this author) to memorize all the function names and the parameters that each function takes. So, every ColdFusion developer should have a good function reference. Following are few suggestions:

ColdFusion Function References

  • Dreamweaver's built-in Macromedia CF Function Reference, which you can get to by pressing shift+F1 or selecting Window > Reference.
  • Macromedia LiveDocs, where the functions are divided neatly into categories. The URL is http://livedocs.macromedia.com/coldfusion/7/htmldocs/00000354.htm
  • Macromedia ColdFusion MX 7 Web Application Construction Kit by Ben Forta and Nate Weiss has an excellent function reference in Appendix C.

We will be looking at many functions throughout this course, but to give you a feel for what they how they work, here are a few date and time functions.

Date & Time Functions

Function Description
Now() Returns the current date and time on the server.
DateFormat("date" [,"mask"]) Formats the date as specified by the mask.
TimeFormat("time" [,"mask"]) Formats the time as specified by the mask.
CreateDate(year, month, day) Creates a date/time object with the time set to 00:00:00.
IsDate(string) Returns true if a string can be converted to a valid date/time object.
DaysInMonth("date") Returns the number of days in a month.

The file below shows these functions in practice:

Code Sample: Basics/Demos/DateFunctions.cfm

<html>
<head>
<title>Date Functions</title>
</head>
<body>
<cfset RightNow = Now()>
<cfoutput>
 #RightNow#<br />
 #DateFormat(RightNow)#<br />
 #DateFormat(RightNow,"mm/dd/yy")#<br />
 #TimeFormat(RightNow)#<br />
 #TimeFormat(RightNow,"hh:mm tt")#<br />
 #IsDate(RightNow)#<br />
 #IsDate("January 31, 2007")#<br />
 #IsDate("foo")#<br />
 #DaysInMonth(RightNow)#
</cfoutput>
</body>
</html>
Code Explanation

The output is shown below:

And here is another demo showing a friendlier page using Now() and DateFormat():

Code Sample: Basics/Demos/HelloWorldDate.cfm

<cfset greeting="Hello">
<cfset today = Now()>

<html>
<head>
 <title>Hello World!</title>
</head>
<body>
 <cfoutput>
  #greeting#, World!<br>
  Today is #DateFormat(Now(),"dddd, mmmm d, yyyy")#.
 </cfoutput>
</body>
</html>
Code Explanation

The output is shown below:

Pound Sign Usage

You may notice that no pound signs are used around the Now() function in the <cfset> tag, while there are pound signs around the DateFormat() function. The use of pound signs to indicate that a variable or expression should be evaluated can be a bit confusing. Here are the rules:

  • Use pound signs when the expression to be evaluated is not within a ColdFusion tag (e.g, <cfoutput>#Now()#</cfoutput>.
  • Use pound signs around expressions that are within a ColdFusion tag ONLY when the expression is also in quotes (e.g, <cfset greeting = "Hello #person#">).
  • With nested functions, use pound signs only around the outermost function (e.g, <cfoutput>#DateFormat(Now())#</cfoutput>).

Examples of Proper and Improper usage of pound signs

Proper Usage

<cfset person = "Paul">
<cfset greeting = "Hello #person#">
<cfoutput>
#greeting#, today is #DateFormat(Now(),"dddd")#.
</cfoutput>

Improper Usage

<!---The improper use is italicized--->
<cfset person = "Paul">
<cfset greeting = "Hello" & #person#>

Improper Usage

<!---The improper use is italicized--->
<cfoutput>
#greeting#, today is #DateFormat(#Now()#,"dddd")#.
</cfoutput>

Arithmetic and String Operators

ColdFusion's arithmetic and string operators are, for the most part, pretty standard.

Operator Type Operator Name Example
Arithmetic + Addition <cfset c = a + b>
- Subtraction <cfset c = a - b>
* Multiplication <cfset c = a * b>
/ Division <cfset c = a / b>
MOD Modulus <cfset c = a MOD b>
^ Exponentiation <cfset c = a^b>
String & Concatenation <cfset greeting = "Hello" & " world!">

Exercise: Performing Calculations

Duration: 20 to 30 minutes.

In this exercise, you will modify the calculator processing page to calculate the time it takes to finish a marathon at certain speeds.

  1. Open Basics/Exercises/ProcessCalculator-2.cfm in your editor.
  2. Beneath the "Calculate Speeds" heading, set a variable called Marathon with the value of 26.2.
  3. Set two more variables, yourmarathontime and friendmarathontime and assign them values as calculated from the form input and the Marathon variable.
  4. For now we will assume the units are in MPH.
  5. Return text to the browser that reads:
           John, at 10
           mph, you would run a marathon in 2.62 hours.
    At 5
           mph, Marylin would run a marathon in 5.24 hours
    . *Replace the highlighted words with variable values.
  6. At the bottom of the page, add a paragraph that reads:
    Form processed at 11:30AM on October 23, 2006.
    *Replace the bold words with the current time and date from the server.

Code Sample: Basics/Exercises/ProcessCalculator-2.cfm

<html>
<head>
 <title>Calculate Speeds</title>
</head>
<body>
<h1>Calculate Speeds</h1>
<!---
 Set a variable called Marathon with
 the value of 26.2
--->

<!---
 Calculate the values for
 yourmarathontime and friendmarathontime
--->

<!---
 Return text to the browser that reads
 "John, at 10 mph, you would run a marathon in 2.62 hours.
 At 5 mph, Marylin would run a marathon in 5.24 hours."
--->
 
<!---
 Add a paragraph that reads:
 Form processed at 11:30AM on February 23, 2007.
--->

</body>
</html>

Return text to the browser that reads:

John, at 10 mph, you would run a marathon in 2 hours and
37 minutes.
At 5 mph, Marylin would run a marathon in 5 hours and 14
minutes.

Hint: you may find it useful to use the Int() function to reformat the marathon times output to show a whole number (e.g, no decimal point). You may also find it useful to use modulus (MOD).

ColdFusion Basics Conclusion

In this lesson of the ColdFusion tutorial, you have learned how to write a simple ColdFusion page, to recognize ColdFusion functions, to work with variables. to pass variables from one page to another via the query string and to process form data.

Footnotes

  1. <cfoutput> tags can only be nested if the outer <cfoutput> tag uses a query and a group attribute. This is an advanced application of <cfoutput> that applies to looping through complex queries.

To continue to learn ColdFusion go to the top of this page and click on the next lesson in this ColdFusion Tutorial's Table of Contents.
Last updated on 2009-02-21

Use of http://www.learn-coldfusion-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm