Home > Articles

This chapter is from the book

Expanding to an If-Then-Else Rule

The basic <cfif> tag lets you do something if the associated Boolean condition evaluates to TRUE, but you can't do anything if the condition turns out to have a value of FALSE. This can tie your hands in situations in which you need to respond differently to a false condition. To alleviate this constraint, ColdFusion supports the addition of a <cfelse> tag to your <cfif> statement, thereby extending it to an "if-then-else" rule.

You can expand the simple example you saw in the previous section to the following:

<cfif Form.age gt 29>
   <p>You don't look a day over 29!</p>
<cfelse>
   <p>Hope you look that good at 30!</p>
</cfif>

Note that <cfelse> is positioned between the <cfif> and </cfif> tags. <cfelse> acts as a separator between the code you want processed if the condition is true and the code you want processed if the condition is false.

CAUTION

The <cfelse> tag does not take any attributes, nor is there a closing </cfelse> tag. The only correct way to use <cfelse> is as you see it in the preceding example.

This added flexibility in your <cfif> statements lets you code things a little more cleanly, as demonstrated in the following examples.

Example: Revisiting Color Selection

Recall the background and foreground color selection example from earlier in the chapter. When processing the user's submission, the colorpage.cfm script had to use the <cfabort> tag to stop processing in the event that the background and foreground colors were the same. In so doing, the script never sent the document structure tags (<html>, <head>, and <body>) to the browser. You can work around this inelegant solution by adding <cfelse> to the <cfif> statement in colorpage.cfm, as shown in Listing 3.8.

Listing 3.8 An Improved colorpage.cfm Script

<html>

<head>
<title>Customized Color Page</title>
</head>

<!---

   Use a <cfif> to see if the chosen colors are the same. If they are,
   use a plain <body> tag. Otherwise, use a <body> tag that incorporates
   the chosen colors.

--->

<cfif Form.bgcolor eq Form.fgcolor>

   <body>

<cfelse>

   <cfoutput>
   <body bgcolor="#Form.bgcolor#" text="#Form.fgcolor#">
   </cfoutput>

</cfif>

<!---

   Next determine which message to show the user using similar
   if-then-else logic.

--->

<cfif Form.bgcolor eq Form.fgcolor>

   <h1>Color choice error!</h1>

   <p>You chose the same foreground and background color! 
   This would make the text on your pages unreadable. 
   Please use your browser's Back button and choose 
   another color combination.</p>

<cfelse>

   <p>Here is your custom color combination!</p>

</cfif>

</body>

</html>

Here, the script is expanded to two <cfif> statements—one to drop in the appropriate <body> tag and another to drop in the appropriate message to the user. You can, of course, handle both tasks by using a single <cfif> statement, as shown in Listing 3.9.

Listing 3.9 Improved colorpage.cfm Script with a Single <cfif>

<html>

<head>
<title>Customized Color Page</title>
</head>

<!---

   Use a <cfif> to see if the chosen colors are the same. If they are,
   use a plain <body> tag and show an error message. Otherwise, use a
   <body> tag that incorporates the chosen colors and tell the user that
   you've customized the page.

--->

<cfif Form.bgcolor eq Form.fgcolor>

   <body>

   <h1>Color choice error!</h1>

   <p>You chose the same foreground and background color! 
   This would make the text on your pages unreadable. 
   Please use your browser's Back button and choose 
   another color combination.</p>

<cfelse>

   <cfoutput>
   <body bgcolor="#Form.bgcolor#" text="#Form.fgcolor#">
   </cfoutput>

   <p>Here is your custom color combination!</p>

</cfif>

</body>

</html>

Both scripts will produce the same output on the browser screen, but the version in Listing 3.9 is more efficient because it evaluates the condition only once.

Example: Making a Form Field Required

Sometimes a user needs to fill out a form field but doesn't for one reason or another. In this case, you can use <cfif> to determine whether the field was completed and, in the event that it wasn't, ask the user to return to the form page and fill out that field. Consider the mailing list sign-up form in Listing 3.10.

Listing 3.10 A Form with a Required Field

<html>

<head>
<title>An HTML Form with a Required Field</title>
</head>

<body>

<p>To sign up for our mailing list, please fill out the form below 
and click the "Submit" button. The E-Mail Address field is required.</p>

<table>
<form action="listsignup.cfm" method="post">
<tr>
<td><b>E-Mail Address:</b></td>
<td><input type="text" name="email" size="40"></td>
</tr>

<tr>
<td><b>Mail Format:</b></td>
<td>
<input type="radio" name="format" value="Text"> Plain Text&nbsp;&nbsp;
<input type="radio" name="format" value="HTML"> HTML
</td>
</tr>

<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>

</form>
</table>

</body>

</html>

The mail format information is collected by means of a radio button. Even if the user doesn't fill in that field, you can still provide a default value for it using <cfparam>. If the user doesn't provide an e-mail address, however, there's no default value you can assume that will work. You have to get that information from the user.

You can use a <cfif> instruction in the listsignup.cfm script to determine whether the user filled in the e-mail address field. If she didn't fill it in, the browser will submit a blank value (also called the empty string or a string with no characters in it). Thus, your <cfif> should examine the contents of the Form.email variable and see whether it is equal to the empty string. If so, you need to tell the user to go back and fill in her address. Listing 3.11 shows you how to do this.

Listing 3.11 The listsignup.cfm Script

<html>

<head>
<title>Mailing List Sign Up</title>
</head>

<body>

<!---

   First use a <cfparam> to establish a default value for
   the Form.format variable (radio button on sign-up form).

--->

<cfparam name="Form.format" default="Text">

<!---

   Next use a <cfif> to see if the email address field was
   filled in. If not, ask the user to go back and fill it in.

--->

<cfif Form.email eq "">

   <h1>Error!</h1>

   <p>We need your e-mail address to be able to sign you up! 
   Please use the Back button on your browser to return to 
   the sign-up form and enter your e-mail address before submitting.</p>

<cfelse>

   <h1>Sign-up Information</h1>

   <p>You are signing up for our mailing with the following information:</p>

   <ul>
   <cfoutput>
   <li>E-mail address: #Form.email#</li>
   <li>Mail format: #Form.format#</li>
   </cfoutput>
   </ul>

</cfif>

</body>

</html>

By examining the condition Form.email eq "", you are testing to see whether the user filled in the required field. Using this condition isn't the only way to perform the test, though. Another approach involves the use of the ColdFusion Len() function. Len() tells you how many characters a string has, so if you pass Len() the value of Form.email, you can check whether it returns a value of zero as follows:

<cfif Len(Form.email) eq 0>

   <h1>Error!</h1>

   <p>We need your e-mail address to be able to sign you up! 
   Please use the Back button on your browser to return to 
   the sign-up form and enter your e-mail address before submitting.</p>

<cfelse>

   <h1>Sign-up Information</h1>

   <p>You are signing up for our mailing with the following information:</p>

   <ul>
   <cfoutput>
   <li>E-mail address: #Form.email#</li>
   <li>Mail format: #Form.format#</li>
   </cfoutput>
   </ul>

</cfif>

The if-then-else logic in the preceding example is equivalent to what you saw in Listing 3.11.

There is an advantage to using the Len() function versus testing the string to see whether it is equal to the empty string. The Len() function returns a numeric value that is either zero (if the string contains no characters) or some positive number (if the string has some characters). ColdFusion interprets a zero as a Boolean FALSE and any non-zero numbers as a Boolean TRUE. Because <cfif> expects an expression that evaluates to either TRUE or FALSE, you can rewrite the preceding <cfif> instruction as follows:

<cfif Len(Form.email)>

   <h1>Sign-up Information</h1>

   <p>You are signing up for our mailing with the following information:</p>

   <ul>
   <cfoutput>
   <li>E-mail address: #Form.email#</li>
   <li>Mail format: #Form.format#</li>
   </cfoutput>
   </ul>

<cfelse>

   <h1>Error!</h1>

   <p>We need your e-mail address to be able to sign you up! 
   Please use the Back button on your browser to return to 
   the sign-up form and enter your e-mail address before submitting.</p>

</cfif>

Note here that you have to reverse the two blocks of code to match the condition in the <cfif> instruction. If the e-mail field was filled in, Len(Form.email) returns some positive number and is interpreted as TRUE. This compels you to take the code to process when the e-mail address is provided and move it between the <cfif> and <cfelse> tags.


→ To learn how to add JavaScript to your HTML forms, see "Making Fields Required," in Chapter 10.


You can use <cfif> instructions to enforce the required fields on your forms, but the price you pay is an increased load on the server. It would be better if you knew that the form data submitted was complete so that you don't have to use ColdFusion to check it. You can accomplish this by including JavaScript code in your code for the HTML form. When the user clicks the Submit button, JavaScript can inspect the required fields, flag any of them that aren't filled out, and suppress the submission of the form data. This way, you know that if the form data was submitted, it has to be complete. Even if you don't know JavaScript, ColdFusion can help you implement it in your forms. You'll learn how to use JavaScript in Chapter 10, "Adding JavaScript to Your Forms."

Example: Creating Grammatically Correct Output

When you're focused on building a dynamic, database-driven Web site, you can easily overlook good grammar in the HTML pages you generate. In particular, developers often miss using the plural forms of nouns and verbs in their output. Have you ever seen a sentence on a Web page like the following?

1 records found!

The word records doesn't match the number 1. Sometimes developers try to gloss over this mistake with output like this:

1 record(s) found!

But you don't need to do that with ColdFusion because you can use <cfif> to determine which words are grammatically correct. Consider the pizza order form in Listing 3.12.

Listing 3.12 Pizza Order Form

<html>

<head>
<title>Pizza Order Form</title>
</head>

<body>

<p>Please choose the toppings you'd like on your pizza 
and click the "Continue Order" button.</p>

<form action="processtoppings.cfm" method="post">

<input type="checkbox" name="toppings" value="Extra Cheese"> Extra Cheese<br>
<input type="checkbox" name="toppings" value="Pepperoni"> Pepperoni<br>
<input type="checkbox" name="toppings" value="Anchovies"> Anchovies<br>
<input type="checkbox" name="toppings" value="Mushrooms"> Mushrooms<br>
<input type="checkbox" name="toppings" value="Peppers"> Peppers<br>
<input type="checkbox" name="toppings" value="Olives"> Olives<br>
<input type="checkbox" name="toppings" value="Sausage"> Sausage<br>
<input type="checkbox" name="toppings" value="Onions"> Onions<br>

<input type="submit" value="Continue Order">

</form>

</body>

</html>

The form uses a series of check boxes to ask the user which toppings to put on the pizza. The processing script processtoppings.cfm needs to be prepared for two possibilities:

  • The user chose no toppings, in which case Form.toppings is undefined.

  • The user chose one or more toppings, in which case Form.toppings is passed to ColdFusion as a comma-delimited list of the toppings selected.

In the second case, you also have to be sensitive to the possibility that the user chose only one topping. If so, you need to use the singular forms of nouns and verbs. The script in Listing 3.13 shows you one way to do so.

Listing 3.13 The processtoppings.cfm Script

<html>

<head>
<title>Pizza Topping Processor</title>
</head>

<body>

<!---

   Assign a default value for Form.toppings
   in case the user did not choose any.

--->

<cfparam name="Form.toppings" default="">

<!---

   Form.toppings can be interpreted as a list, so use
   the ListLen() function to see how many toppings are
   in the list.

--->

<cfif ListLen(Form.toppings)>

   <!---

     If you're here, Form.toppings had a length that was
     greater than zero, so the user wants at least one
     topping. Use a second <cfif> to determine the
     grammatically correct choice of words.

   --->

   <p>Your

   <cfif ListLen(Form.toppings) eq 1>
     topping is:
   <cfelse>
     toppings are:
   </cfif>

   <cfoutput>#Form.toppings#</cfoutput>.</p>

<cfelse>

   <!---

     If you're here, Form.toppings had a length of zero,
     meaning the user wanted no toppings.

   --->

   <p>Are you sure you want a plain pizza?</p>

</cfif>

</body>

</html>

→ To learn more details about ListLen() and other ColdFusion list functions, see "ColdFusion Lists" in Chapter 6.


The ListLen() function tells you how many items are in the comma-delimited list stored in Form.toppings. If Form.toppings takes on the default value of the empty string, it is considered to be a list with zero items.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020