- Implementing Conditional Logic
- Basic If-Then Rules
- Expanding to an If-Then-Else Rule
- Adding More Conditions to Your If-Then-Else Rule
- Considering Multiple Cases
- What's Next
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> statementsone 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 <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.