Constructs

an article added by: John Fox at 03302008


In: Root » Computers and technology » Programming » Constructs

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

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 disclaimer

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.

related articles

1. ColdFusion Can Be Extended In Many Ways
In addition to being one of the easiest Web-programming languages, ColdFusion is also one of the most easily extensible languages, because it can interface with many different technologies, as shown in the following list: Java objects, which are standalone packages of code written in the Java language Custom tags written in C++ or Java, which are pieces of code to be used only with ColdFusion, but which are written in either C++ or Java Java Server Page (JSP) tag libraries, which are originally built for use w...

2. First ColdFusion Application
You learn by doing, and then we go back and explain how ColdFusion worked its magic. Before you get started, though, you must learn a few terms, set up the database, and create the Web directory that you’re going to use. These are some terms that you should know: A template is a file with a .cfm extension. ColdFusion executes these templates and produces HTML that is returned to the user’s browser. A page is what appears in your browser. It is rendered from the HTML that ColdFusion Server sends back ...

3. 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)#’, ...

4. 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 ...

5. 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)...

6. 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...

7. 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...