Programming with ColdFusion

This chapter describes conditional logic and how to program for page control. During chapter practices, you will add programming logic to your action pages to perform conditional processing, program for code reuse, and redirect users automatically within your applications.

Contents

  • Using Programming Logic 82

  • Coding Conditional Logic 83

  • Writing Conditional Logic Expressions 83

  • Using Decision Functions to Build Expressions 84

  • Using Operators to Build Expressions 86

  • Conditional Logic Notes and Considerations 91

  • Redirecting Users 91

  • Reusing Code 93

  • Development Considerations 95

Using Programming Logic

Even though ColdFusion is almost as easy to code as HTML, it has the same programming features found in rich scripting languages.

For example, you can you can use CFML language constructs to:

  • Perform conditional processing

  • Maintain code in one location and use it in many locations

  • Automatically redirect users within your application pages

Note ColdFusion also supports programatic looping. See the ./CFML Language Reference for ColdFusion Express to learn about the CFLOOP tag.

Using ColdFusion Conditional Logic

ColdFusion provides simple branching structures that you use to code conditional logic expressions. In its simplest form, you will use conditional logic to:

  • Test for a condition.

  • Define what procedure to perform if a condition is true.

  • Define what procedure to perform if a condition is not true.

Programming with ColdFusion - 图1

For example, you will use conditional logic on action pages to test for a form variable’s existence so that your users will not get an error when they submit a form without a checkbox enabled.

Programming with ColdFusion - 图2

Coding Conditional Logic

There are two branching structures that you can use to code conditional logic:

  • The CFIF and CFELSE tags

  • The CFSWITCH and CFCASE block tags

Note During this guide, you will learn to code for conditional logic using the CFIF and CFELSE block tags. See the ./CFML Language Reference for ColdFusion Express to learn about CFSWITCH and CFCASE tags.

CFIF Syntax

<CFIF Expression> True procedure

<CFELSE>

Not true procedure

</CFIF>

  • Write an expression using ColdFusion functions and operators.

  • Define the procedure that ColdFusion should perform if the condition

    is true directly after the start CFIF tag.

  • Define the procedure that ColdFusion should perform if the condition

    is false within a CFELSE block within the CFIF block.

Writing Conditional Logic Expressions

Within the begin CFIF tag, write an expression to define the condition to test. Expressions can include a variety of data types such as:

  • Numeric

  • Boolean

  • Time-date

  • Strings

The conditional logic expressions that you write will usually include a combination of:

  • Variables - You learned about these in Chapter 4, “Creating and

    Manipulating Variables,” on page 29.

  • ColdFusion decision functions - You learned about functions in

    Chapter 6, “Formatting and Manipulating Data,” on page 61 and you will use decision functions here.

  • ColdFusion operators - You’ll learn about these here.

Using Decision Functions to Build Expressions

Use decision functions to test for the presence of ColdFusion elements such as form variables, queries, and their simple values so that you can perform conditional processing.

When you use decision functions:

  • The test will return a Boolean value.

  • The actual Boolean value will be either true or false but, when used

    in a CFIF expression, it is converted to either yes or no.

The table below describes the most frequently used decision functions. Refer to the ./CFML Language Reference for ColdFusion Express

Function

Usage

IsDefined

Tests if a variable by a specific name exists.

IsDebugMode

Tests if debugging is enabled on the page.

IsDate

Tests if a variable value is time-date.

IsNumeric

Tests if a variable value is numeric.

IsQuery

Tests if a variable contains query data.

IsStruct

Tests if a variable contains structure data.

Usage example

Checkbox and radio button form variables only pass to action pages when an option is enabled on the form.

The code below is added to a form’s action page to check for the existence of a checkbox variable.

<CFIF IsDefined("Form.Contract") IS "YES"> Status: Contract Employee

<CFELSE>

Status: Permanent Employee

</CFIF>

  • If Form.Contract is defined, the test returns yes and displays

    Status: Contract Employee.

  • If Form.Contract is not defined, the test returns no and displays

    Status: Permanent Employee.

  • After, peforming the conditional processing, ColdFusion continues

    processing the page.

NoteDuring the next procedure, use this expression syntax on your action page to check for the existence of a checkbox before trying to process it.

To test for a variable’s existence:

  1. Open ActionPage.cfm in HomeSite.

  2. Title the page Chapter 8 Action Page.

  3. Delete the line Contract Status: #Form.Contract#<BR> within

    the CFOUTPUT block.

You will replace it with new code as you go.

  1. Add an opening CFIF tag immediately after the ending CFOUTPUT tag to

    test if #Form.Contract# is defined:

<CFIF IsDefined("Form.Contract") IS "YES">

  1. Add a true procedure after the tag to output a label and a value:

Status: Contract Employee

  1. Add a CFELSE tag.

  2. Add a false procedure after this tag to output a label and a value:

Status: Permanent Employee

  1. Add an ending CFIF to end the conditional logic statement.

  2. Your output block should look like this:

<CFIF IsDefined("Form.Contract") IS "YES"> Status: Contract Employee

<CFELSE>

Status: Permanent Employee

</CFIF>

  1. Save the page.

  2. View FormPage.cfm in a browser.

  3. Fill out each field and submit the form.

ActionPage.cfm should return all the values that you entered on the form. The status field should appear as Contract Employee.

If you receive errors, read the error message and check for spelling mistakes on the action page.

  1. Return to the form in the browser.

  2. Reset the form.

  3. Do not check the checkbox and submit the form again. The status

    field should appear as Pemanent Employee.

http://localhost/CFDOCS/exampleapp/TutorialSolutions/Chapter8/ FormPageexists.cfmClick here/a to see what results you should get.

http://localhost/CFDOCS/exampleapp/TutorialSolutions/Chapter8/ ActionPageexist.txtClick here/a to see the new code on the action page.

Move on in this chapter to learn how to use operators to perform conditional logic testing.

Using Operators to Build Expressions

CFML provides a variety of operators that you can use to build expressions. Operators fall into four category types:

  • Arithmetic - perform operations on numeric values.

  • String - perform operations on text values.

  • Comparison - compare values and return true or false. Frequently

    used when coding conditional logic.

  • Compound Boolean - perform logical connective and negation

    operations and return true or false.

Frequently used when coding conditional logic.

The table below describes operators by type and symbol.

ColdFusion Operators
Type

Symbol

Description

Arithmetic

+, -, *, /

Add, subtract, multiply, and divide.

In the case of division, the right operand cannot be zero.

For example, 9/4 is 2.25

\

Divides two integer values and returns a whole number.

For example, 9\4 is 2.

^

Returns the result of a number raised to a power (exponent).

Use the ^ (caret) to separate the number from the power.

The left operand cannot be zero.

For example, 2^3 is 8.

MOD

Returns the remainder (modulus) after a number is divided.

The result has the same sign as the divisor.

The right operand cannot be zero.

For example, 11 MOD 4 is 3.

+ or -

Set a number to either positive or negative.

For example, +2 is 2 and -2 is (-1)*2.

String

&

Concatenates text strings including those returned from variables and functions.

88 Developing Web Applications with ColdFusion Express

ColdFusion Operators (Continued)
Type

Symbol

Description

Comparison

IS

Performs a case-insensitive comparison of two values. Returns true or false.

For example, this code tests for equal values. The condition is true only if the FirstName value is Jeremy.

<CFIF Form.FirstName IS "Jeremy">

IS NOT

Opposite behavior of IS.

For example, this code tests for inequal values. The condition is true only if the FirstName value is not Jeremy.

<CFIF Form.FirstName IS NOT "Jeremy">

CONTAINS

Checks to see if the value on the left is contained in the value on the right.

Returns true or false.

For example this code tests for a value condition. The condition is true only if the FirstName value contains Jeremy.

<CFIF Form.FirstName CONTAINS "Jeremy">

DOES NOT CONTAIN

Opposite behavior of CONTAINS.

GREATER THAN

Checks to see if the value on the left is greater than the value on the right.

Returns true or false.

LESS THAN

Opposite behavior of GREATER THAN.

GREATER THAN OR EQUAL TO

Checks to see if the value on the left is greater than or equal to the value on the right.

Returns true or false.

LESS THAN OR EQUAL TO

Checks to see if the value on the left is less than or equal to the value on the right.

Returns true or false.

ColdFusion Operators (Continued)
Type

Symbol

Description

Compound Boolean

NOT

Reverses the value of an argument.

For example, NOT TRUE is FALSE and vice versa.

AND

Returns true if both arguments are true; returns false otherwise.

For example, TRUE AND TRUE is true, but TRUE AND FALSE is false.

OR

Returns true if any argument is true; returns false otherwise.

For example, TRUE OR FALSE is true, but FALSE OR FALSE is false.

XOR

Returns true if either argument is exclusively true; returns false otherwise.

For example, TRUE XOR TRUE is false, but TRUE XOR FALSE is also true.

EQV

Returns true if both arguments are true or both are false.

For example, TRUE EQV TRUE is true, but TRUE EQV FALSE is false.

Note You can replace some conditional operators with shorthand notations. Refer to the ./

CFML Language Reference for ColdFusion Express for more information.

Usage example

Although form variables may pass to action pages, their values may not always be usable - for example a value of null.

The code below would be added to a form’s action page to check for a value other than null ("") in a LastName form variable.

<CFIF Form.LastName IS NOT "">

Last Name: <CFOUTPUT>#Form.LastName#<BR></CFOUTPUT>

<CFELSE>

Last Name Not Entered!<BR>

</CFIF>

  • If Form.LastName is not null, the test returns yes, and displays its

    value to the user.

  • If Form.LastName is null, the test returns no. and displays a

    message back to the user.

  • After performing the conditional processing, ColdFusion continues

    processing the page.

During the next procedure, use this expression syntax on your action page to check for the value of a variable before trying to use it.

To test for a variable’s value:

  1. Open ActionPage.cfm in HomeSite

  2. Delete Last Name: #Form.LastName#<BR> code from within the

    CFOUTPUT block.

You will replace this code as you go.

  1. Add a CFIF tag directly above the existing CFOUTPUT block to test

    whether or not the user entered information in the LastName text field:

<CFIF Form.LastName IS NOT "">

  1. Add a true procedure after the CFIF tag to output a label and the

    form variable.

Last Name:

<CFOUTPUT>

#Form.LastName#<BR>

</CFOUTPUT>

  1. Add a CFELSE tag.

  2. Add a false procedure after this tag to output a message to the

    user.

Last Name Not Entered!<BR>

  1. Add an ending CFIF tag to end the conditional logic statement.

  2. Your conditional logic statement should look like this:

<CFIF Form.LastName IS NOT ""> Last Name:

<CFOUTPUT>

#Form.LastName#<BR>

</CFOUTPUT>

<CFELSE>

Last Name Not Entered!<BR>

</CFIF>

  1. Save the page.

  2. View FormPage.cfm in a browser.

  3. Fill out each field and submit the form.

ActionPage.cfm should return all the values that you entered on the form.

If you receive errors, read the error message and check for spelling mistakes on the action page.

  1. Return to the form in the browser.

  2. Reset the form.

  3. Do not enter a last name and submit the form again.

You should see the message that you coded.

Move on in this chapter to learn how to automatically redirect users from within your applications.

Conditional Logic Notes and Considerations

  • You can nest CFIF tags within conditional logic blocks, but,

    remember, that you will need to track the logic and, also, complex nesting requires processing time.

  • When nesting tags, indent the nested code to make it more readable.

  • Only one CFELSE tag can be inside each CFIF block.

  • You can have many CFELSEIF tags.

Refer to the ./CFML Language Reference for ColdFusion Express for more information about this tag.

  • When creating conditional logic blocks, always list the most likely

    to occur at the top of the block and work downward to the least likely.

  • ColdFusion exits the CFIF block once it evaluates a true expression.

Redirecting Users

When a user submits a form that adds or updates records, the action page should automatically go to a page that lists records , including the new or updated records.

Use the CFLOCATION tag to automatically redirect users from the current page to a different URL.

CFLOCATION Syntax

<CFLOCATION URL="file.cfm">

  • The URL attribute describes the page to redirect users to from the

    current page.

  • The URL attribute can include either a page’s relative path or an

    absolute path.

Use a relative path to describe the page to redirect users to relative to the current page.

Use an absolute path to describe the page to redirect users to from the Web root.

  • When this tag is encountered, ColdFusion immediate redirects the

    user to another URL and any code after it will not be processed.

Note When using absolute pathing, the pages that you redirect users to must be mapped for ColdFusion use. Refer to Configuring ColdFusion Express Server to learn about using mapping directories.

Usage example

In this example, the action page updates the CFExpress database and redirects the user to the EmpList.cfm page.

<CFQUERY NAME="UpdateEmployee" DATASOURCE="HRApp">

UPDATE Employees

SET FirstName = ’#Form.FirstName#’, LastName = ’#Form.LastName#’, Department_ID = #Form.Department_ID#, StartDate = #Form.StartDate#,

Salary = #Form.Salary#, Contract= ’#Local.Contract#’

WHERE Employee_ID = #Form.Employee_ID#

</CFQUERY>

<CFLOCATION URL="EmpList.cfm">

  • Update the Employees table columns using variables described in the

    SQL UPDATE statement and the match criteria described in the SQL WHERE clause.

  • Redirect the user to Emplist.cfm after the update is complete.

During the next procedure, use CFLOCATION on your action page to redirect users to

Emplist.cfm.

Note This guide covers just enough SQL to get you going with ColdFusion Express. Refer to Chapter 9, “Building Search Interfaces,” on page 97 to learn about WHERE clause basics and refer to Chapter 10, “Building Web Front-Ends,” on page 107 to learn about the UPDATE statement.

To redirect users to another URL:

  1. Open ActionPage.cfm in HomeSite.

  2. Save this file as ActionPageRedirect.cfm.

Delete all of the current output that is displayed to the user.

During the next two chapters, you will learn how to use conditional logic and redirection to return data from, insert data into, and update data in a database.

  1. Add this code to the page to redirect users to the EmpList.cfm page:

<CFLOCATION URL="EmpList.cfm">

The CFLOCATION tag will now immediately redirect users to another page.

  1. Save the page.

  2. Open FormPage.cfm in HomeSite.

  3. Save the page as FormPageRedirect.cfm.

  4. Modify the ACTION attribute of the opening FORM tag to reference

ActionPageRedirect.cfm.

  1. View FormPageRedirect.cfm in a browser.

  2. Submit the form.

You are redirected to EmpList.cfm.

If this was a form used to insert records into a database, you would have coded your action page to insert data within a CFQUERY tag and redirected users to this page.

Move on in this chapter to learn how to reuse the same code across your applications.

Note Remember that the form passes values to the action page that’s named in the opening FORM tag.

If you don’t name the new action page in the ACTION attribute, it will not find

ActionPageRedirect.cfm.

Reusing Code

Often times, you’ll use some of the same elements in multiple pages; for example, navigation, headers, and footer code.

Instead of copying and maintaining it from page to page, ColdFusion allows you to reference the code stored in one file in many pages. This way you can modify one file and recognize the changes throughout an entire application.

Use the CFINCLUDE tag to automatically include an existing file in the current page.

CFINCLUDE Syntax

<CFINCLUDE Template="File.cfm">

  • The page that calls the template is also known as the calling page.

  • The TEMPLATE attribute describes the file or template to include

    in the calling page.

  • The TEMPLATE attribute describes the template - including where it

    resides or its path.

  • Each time the calling page is requested, the template’s file

    contents are included in that page for processing.

Note Refer to the ./CFML Language Reference for ColdFusion Express for CFINCLUDE syntax.

Usage example

In this example, the navigation toolbar is included (not copied) at the top of the calling page, EmpList.cfm:

<CFINCLUDE TEMPLATE="Toolbar.cfm">

  • Each and every time the template page is requested, the contents of

Toolbar.cfm is included for processing.

  • Toolbar.cfm resides in the same directory as Emplist.cfm.

  • If Toolbar.cfm resided in the Templates directory underneath the

    calling page’s directory, the syntax would be:

<CFINCLUDE TEMPLATE="Templates/toolbar.cfm">

During the next procedure, use CFINCLUDE on your EmpList.cfm and

FormAction.cfm pages to reuse the application’s navigation code.

To reference code in a calling page:

  1. Open EmpList.cfm in HomeSite.

  2. Delete the existing toolbar code that begins with this:

<!--- begin application toolbar imported from toolbar.cfm--->

And ends with this:

<!--- end application toolbar --->

  1. Include Toolbar.cfm file in this page:

<CFINCLUDE TEMPLATE="ToolBar.cfm">

  1. Save the page.
  2. View EmpList.cfm in a browser.

  3. The toolbar should still appear at the top of the page.
  4. Return to HomeSite.

  5. Open FormPage.cfm.

  6. Save it as SearchForm.cfm.

You will modify this form during the next chapter’s procedures to create a search form.

  1. Add the CFINCLUDE tag directly below the opening BODY tag.

  2. Save the page.

  3. View EmpList.cfm in a browser and navigate to SearchForm.cfm by

    clicking SEARCH.

The toolbar should now be included.

  1. Click LIST to return to EmpList.cfm.

http://localhost/CFDOCS/exampleapp/TutorialSolutions/Chapter8/ EmpList.cfmClick here/a to see what the Emplist.cfm looks like.

http://localhost/CFDOCS/exampleapp/TutorialSolutions/Chapter8/ SearchForm.cfmClick here/a to see what SearchForm.cfm looks like.

http://localhost/CFDOCS/exampleapp/TutorialSolutions/Chapter8/ SearchForm.txtClick here/a to see the search form’s code.

In the next chapter, you will code the form so that it really does search the database.

Move on in this chapter to review development considerations.

Development Considerations

During this chapter, you learned about:

  • Using the CFIF and CFELSE tags to code conditional logic

  • Working with ColdFusion operators and functions to build expressions

    for conditonal logic constructs

  • Redirecting users using the CFLOCATION tag

  • Reusing code using the CFINCLUDE tag

Where to go from here

  • Refer to Chapter 6, “Formatting and Manipulating Data,” on page 61

    to learn about working with functions.

  • Move on to the next chapter and build a search interface with

    ColdFusion.

96 Developing Web Applications with ColdFusion Express

C HA PT ER 9