Constructs

an article added by: John Fox at 03302008


In: Categories » Computers and technology » Programming » Constructs

If your program did the same thing regardless of how it was called, it wouldn’t be very useful. A real application responds to different situations by calling different code, which is the essence of flow control. In this article, you learn how to use conditional and loop logic to construct efficient flow control for your application. You also learn how to redirect the user to a different template and how to include code from external templates. An If construct consists of a condition and a dependent statement. ColdFusion evaluates the condition to determine whether it is True or False. If the condition is true, ColdFusion executes the dependent statement. Take, for example, the following code:

<cfif myVar GREATER THAN myOtherVar>
   <cfoutput>#myVar#</cfoutput>
   </cfif>

In the preceding If construct, ColdFusion tests to see whether myVar is greater than myOtherVar. If the test result is True, ColdFusion outputs the value of myVar; if the test result is False, ColdFusion doesn’t do anything. You can make ColdFusion execute alternative code if the condition tests False, as follows:

<cfif myVar GREATER THAN myOtherVar>
   <cfoutput>#myVar#</cfoutput>
   <cfelse>
   <cfoutput>#myOtherVar#</cfoutput>
   </cfif>

We’ve extended the original If construct to include a CFELSE tag. Now, if myVar is not greater than myOtherVar, ColdFusion outputs myOtherVar. You can extend CFIF even further by adding additional conditions with CFELSEIF, as follows:

<cfif myVar GREATER THAN myOtherVar>
   <cfoutput>#myVar#</cfoutput>
   <cfelseif myVar EQUAL myOtherVar>
   <cfoutput>#myVar + myOtherVar#</cfoutput>
<cfelse>
   <cfoutput>#myOtherVar#</cfoutput>
 </cfif>

Now, if myVar is equal to myOtherVar, ColdFusion adds the two together and outputs the result. Notice that the CFELSE statement now executes only if both the CFIF and CFELSEIF conditions are False. You can add as many CFELSEIF conditions as you want to a CFIF tag, but if you have more than two or three based on different results from the same conditional test, you should consider using a Switch construct instead. A Switch construct evaluates a single expression against multiple test values and then executes the block of code associated with the test value that matches. Consider the following snippet of code:

<cfif myVar EQ 1>
   One
 <cfelseif myVar EQ 2>
 Two
 <cfelseif myVar EQ 3>
 Three
 </cfif>

This snippet evaluates myVar three times, checking each time to determine whether myVar is a certain value. This code is better written by using a CFSWITCH block:

<cfswitch expression=”#myVar#”>
   <cfcase value=1>
   One
   </cfcase>
   <cfcase value=2>
   Two
   </cfcase>
   <cfcase value=3>
   Three
   </cfcase>
   </cfswitch>

Both snippets do the same thing, but the CFSWITCH construct is more efficient because it evaluates myVar once rather than three times. ColdFusion executes CFSWITCH statements more efficiently than it does CFIF statements, because CFIF evaluates each condition until it finds one that’s true, while CFSWITCH simply chooses the CFCASE block with the matching value. CFCASE values must be constant; in other words, the following construction is illegal:

<cfswitch expression=”#myVar#”>
   ...
 <cfcase value=”#1+1#”>
 Two
 </cfcase>
 ...
 </cfswitch>

This code would throw an error because variables and expressions are not permitted in CFCASE’s value attribute. In the code below, CFDEFAULTCASE is the Switch construct’s equivalent to CFELSE, as the following example shows:

<cfswitch expression=”#myVar#”>
   <cfcase value=1>
   One
   </cfcase>
   <cfcase value=2>
   Two
   </cfcase>
   <cfcase value=3>
   Three
   </cfcase>
   <cfdefaultcase>
   Some other number
   </cfdefaultcase>
   </cfswitch>

If none of the CFCASE values match the expression in CFSWITCH, ColdFusion executes the CFDEFAULTCASE block. Even with the benefits provided by CFSWITCH, at times you must still use CFIF logic. Take, for example, the following code block:

<cfif myVar GREATER THAN myOtherVar>
   <cfoutput>#myVar#</cfoutput>
   <cfelseif myVar EQUAL myOtherVar>
   <cfoutput>#myVar + myOtherVar#</cfoutput>
   <cfelse>
   <cfoutput>#myOtherVar#</cfoutput>
   </cfif>

This code cannot be converted to CFSWITCH because this CFIF construct contains multiple tests rather than a single test with a single expression. CFSWITCH uses its single expression as a “lookup key” to find the matching CFCASE to execute. The simplest type of loop loops from a specific starting point to a specific ending point—for example, from one to ten. This type of loop is called an index loop and is shown in the code.

This is code before the loop.<br>
   <cfloop from=”1” to=”10” index=”i”>
   <cfoutput>
   #i#<br>
   </cfoutput>
   </cfloop>
 This is code after the loop.<br>

Everything between <cfloop> and </cfloop> is the body of the loop. The body is executed once for each loop, and the loop index is incremented by 1 after each execution of the loop’s body. So what exactly does index=”i” mean? The index of a loop is a counter containing the number of the current loop iteration. In other words, for the first time through the loop, i would contain 1. The next time through, i would contain 2 and so on. After i reaches 10, the loop is executed one last time. This type of loop has one additional attribute. If we wanted to loop backwards from 10 to 1, we would include the step attribute, as in the code.

This is code before the loop.<br>
   <cfloop from=”10” to=”1” step=”-1” index=”i”>
   <cfoutput>
   #i#<br>
   </cfoutput>
   </cfloop>
 This is code after the loop.<br>

An index loop is appropriate if you know the number of loops in advance. You can, however, also loop an indefinite number of times while a given condition is true, as shown in the code.

<cfset bLoop = TRUE>
   <cfloop condition=”bLoop EQ TRUE”>
   This is one iteration through the loop.<br>
   <cfif RandRange(1, 10) EQ 10>
   <cfset bLoop = FALSE>
   </cfif>
 </cfloop>

RandRange(1,10) returns a random number between 1 and 10. The code keeps looping while bLoop is TRUE, and after RandRange() returns 10, we set bLoop to FALSE. If the loop attempts to execute again, the condition tests FALSE, and execution halts before the loops executes. CFLOOP can also loop over a query, as shown in the code. Remember that when looping over queries, you don’t surround the query object name with pound signs.

<cfquery name=”GetEmployees”
   datasource=”#Request.MainDSN#”>
   SELECT
   CompanyName
   FROM
   Company
   </cfquery>
   <cfoutput>
   <cfloop query=”GetEmployees”>
   #CompanyName#<br>
   </cfloop>
 </cfoutput>

The CFLOOP in the code loops over each row present in the GetEmployees query object and outputs each company name in the query. This type of loop is similar to a CFOUTPUT statement, except that CFLOOP can be nested inside of another CFOUTPUT (something that you cannot do with CFOUTPUT alone).

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. Building the company add action template
In this article, you create the template that puts your form data into the database. Create a file named CompanyAddAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”InsertCompany” datasource=”#Request.MainDSN#”> INSERT INTO Company( CompanyName, Address, City, State, ZipCode, Comments ) VALUES ( ‘#Trim(Form.CompanyName)#’, ‘#Trim(Form.Address)#’, ...

2. Modifying a Company in the Database
The data that CFQUERY requests from the database comes back in a result set, and the Name attribute tells ColdFusion what that result set is to be named. The SQL statement consists of three clauses: SELECT, FROM, and ORDER BY. SELECT tells the database which columns to retrieve from the database; FROM tells the database which table to retrieve those columns from; and ORDER BY tells the database how to sort the results. The result set returned from CFQUERY contains multiple rows of data, and each row has multiple columns. It would ...

3. Building the company edit action template
The code in CompanyEditAction.cfm is like the code in CompanyAddAction.cfm, but the edit action updates rather than inserts. Create a file named CompanyEditAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”UpdateCompany” datasource=”#Request.MainDSN#”> UPDATE Company SET CompanyName = ‘#Trim(Form.CompanyName)#’, Address = ‘#Trim(Form.Address)#’, City = ‘#Trim(Form.City)...

4. Adding a New Employee to the Database
The CFQUERY in CompanyDeleteAction.cfm uses a DELETE statement with two SQL clauses: DELETE and WHERE. DELETE tells the database the table from which to delete a record, and WHERE tells the database which record to delete. You can watch the company delete process in action. Point your Web browser to http://<yourserver>/CFMXBible/Ch02/CompanyGetDeleteForm.cfm and enter a CompanyID. (To get a valid ID, go to the company list and pick a number from the ID column.) Click Submit to see the chosen company’s informatio...

5. Modifying an Employee in the Database
The DateFormat() function around the DateOfBirth column in the codereturns the employee’s birth date reformatted according to a display mask. DateOfBirth normally comes back from the database in the following format: 2002-01-01 00:00:00.0 That format is not very user-friendly. Calling DateFormat() with a mask of “mm/dd/yyyy” returns the date as follows: 01/01/2002 This version is, of course, more natural and easy to read. The same is true for the employee edit process...

6. Removing an Employee From the Database
The user must have the capability to remove employees from the database. The employee delete process is a simple combination of techniques that you have already learned, such as retrieving a record from the database, displaying that record in a template, and so on. The first page in this process is nearly identical to the employee get edit form. Create a file named EmployeeGetDeleteForm.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <html> <head> <ti...

7. Making direct links to the forms
Say that you want to modify or delete a company. Right now, you need to remember the company’s ID, go back to the launch pad, click Company Edit, and enter the company ID, all just to get to the edit form. Wouldn’t you rather click a company in the list and go directly to the edit form? ... <table> <tr> <td><b>ID</b></td> <td><b>Name</b></td> <td><b>Address</b></td> <td><b>City</b></t...

8. Using a Custom Tag
Custom tags are reusable, developer-authored extensions to the ColdFusion language. The custom tag that you create in the following parts displays today’s date in a familiar format. Create a file named TodaysDate.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfoutput>#DateFormat(Now(), “ddd, mmm d, yyyy”)#</cfoutput> Now() returns the current date and time, and DateFormat() reformats the date. To call your custom tag, open index.cfm, a...

9. Creating your physical data model
Physical data models are extracted from their logical counterparts by mapping logical objects to physical objects supported by the target database platform. The following table shows the relationship between logical and physical objects. In many cases, your physical data model almost mirrors your logical data model because entities typically map directly to the tables that store them. Exceptions to this rule are logical data models that contain nonspecific relationships and entity subtypes. Although entity subtypes are an advanced top...