Looping

an article added by: Carmela Herandez at 03312008


In: Root » Computers and technology » Programming » Looping

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

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). CFLOOP can also loop over a list of items, as shown in the code. Unlike query objects, you do surround the list name with pound signs.

<cfset myList = “this,that,the other”>
   <cfoutput>
   <cfloop list=”#myList#” index=”theItem”>
   #theItem#<br>
   </cfloop>
 </cfoutput>

This type of loop iterates over each element in a list and executes a block of code once for each element. Each time that the loop iterates, index contains the value of the current element. List loops are discussed in detail later. Structures are complex objects that store collections of key-value pairs. You can loop over a structure with CFLOOP by using the collection loop syntax shown in the code.

<cfset myStruct = StructNew()>
   <cfset myStruct.keyA = “value A”>
   <cfset myStruct.keyB = “value B”>
   <cfset myStruct.keyC = “value C”>
   <cfoutput>
   <cfloop collection=”#myStruct#” item=”theKey”>
   #theKey#: #myStruct[theKey]#
   </cfloop>
 </cfoutput>

Collection is another term for structure in most computer languages, and it is the term used for such objects in COM. Hence, the name of the attribute. item contains the name of the current key each time that the loop iterates. Only top-level keys are considered in the loop, so if the structure being looped over has nested structures, the keys from those nested structures do not populate item. To loop over a nested structure, you must pass its dot path to the collection attribute. Sometimes, you may want to end a loop prematurely. In the next code, for example, ColdFusion ends the index loop prematurely if a particular random number comes up.

<cfoutput>
   <cfloop from=”1” to=”10” index=”i”>
   #i#<br>
   <cfif RandRange(1,10) EQ 10>
   <cfbreak>
   </cfif>
   </cfloop>
 </cfoutput>

The CFBREAK in the code prematurely breaks out of the CFLOOP. If, during the normal course of this loop, RandRange() returns 10, CFBREAK ends the loop before i reaches 10. Another technique that often accompanies CFBREAK is the infinite loop, as shown in the code.

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

This code does the same thing as the other one, but in less code. The condition=”TRUE” attribute of CFLOOP means that the loop executes forever, but CFBREAK instructs the loop to terminate if RandRange() returns 10. Just make absolutely sure that your code eventually reaches the break condition if you choose to code by using the infinite-loop technique. (Just the term alone is enough to make us shudder!) Some elements of your site may be common to many pages, such as a standard header or footer. By using CFINCLUDE, you can have one template that contains the header or footer code and then include that template in another, as shown in the code.

<cfinclude template=”header.cfm”>
   This is the main page content.
 <cfinclude template=”footer.cfm”>

Before ColdFusion outputs This is the main page content., it pulls the code from header.cfm and footer.cfm into the current template. The header code, therefore, appears before the text This is the main page content., and the footer code appears after it. You can also use variables in the included source, as the following example shows:

<cfinclude template=”#Client.Theme#/header.cfm”>

Paths to included templates are relative; the included files in the code would need to exist in the same directory as the template that called them. To include a file in a parent directory, use the following syntax:

<cfinclude template=”../template.cfm”> 

The two dots tell ColdFusion to go up a level in the directory structure to find a file. You cannot use a disk path for the template attribute of CFINCLUDE. You can also include a file based on a directory mapping, as follows:

<cfinclude template=”/template.cfm”>

Whenever the template path begins with a slash, ColdFusion uses the directory mappings defined in ColdFusion Administrator to locate the template. Our server has two directory mappings defined. Our directory mappings show that / maps to C:\inetpub\wwwroot\ and /pro/ maps to C:\pro\. Suppose, therefore, that we call the following:

<cfinclude template=”/template.cfm”>

ColdFusion includes the file C:\inetpub\wwwroot\template.cfm because / maps to the Web root. Suppose now that, on the other hand, we call the following instead:

<cfinclude template=”/pro/template.cfm”>

ColdFusion includes C:\pro\template.cfm because /pro/ maps to C:\pro. Your path can also add directories after the mapping, as in the following example:

<cfinclude template=”/myIncludes/template.cfm”>

No mapping exists for myIncludes, so ColdFusion includes C:\inetpub\wwwroot\myIncludes\template.cfm. To help solidify these ideas, take a look at a few more examples. Our directory structure looks as follows:

C:
   pro
   inetpub
   wwwroot
   includes
 commonfiles

We’re inside C:\inetpub\wwwroot\commonfiles\mypage.cfm. The following line includes C:\inetpub\wwwroot\commonfiles\myotherpage.cfm, which tells ColdFusion to look for myotherpage.cfm in the same directory as the current template:

<cfinclude template=”myotherpage.cfm”>

The following line includes C:\inetpub\wwwroot\index.cfm, which tells ColdFusion to move up one directory and look for index.cfm:

<cfinclude template=”../index.cfm”>

The following line includes C:\inetpub\wwwroot\includes\myinclude.cfm, which tells ColdFusion to move up one directory, move into the includes subdirectory at that level, and then look for myinclude.cfm:

<cfinclude template=”../includes/myinclude.cfm”>

The following line includes C:\pro\mytemplate.cfm. /pro/ is defined as a mapping in ColdFusion Administrator, so the following code tells ColdFusion to look in the /pro/ mapping and hunt for mytemplate.cfm:

<cfinclude template=”/pro/mytemplate.cfm”>

The following line includes C:\inetpub\wwwroot\commonfiles\mytemplate.cfm. No /commonfiles/ mapping exists, so the following code tells ColdFusion to use the / mapping, look in the commonfiles subdirectory, and then hunt for mytemplate.cfm:

<cfinclude template=”/commonfiles/mytemplate.cfm”>

The following line includes C:\inetpub\wwwroot\includes\myinclude.cfm, which tells ColdFusion to move up two directories (into C:\Inetpub), move into the wwwroot subdirectory, move into the includes subdirectory, and then look for myinclude.cfm:

<cfinclude template=”../../wwwroot/includes/myinclude.cfm”>

Good planning of directory structure ahead of time and applying a root mapping to your application makes your CFINCLUDEs easy to code. You use CFLOCATION to redirect the user after a database action the code shows an example of such a redirect.

<cfquery name=”DeleteCompany”
   datasource=”#Request.MainDSN#”>
   DELETE FROM Company
   WHERE
   CompanyID = #Val(Form.CompanyID)#
   </cfquery>
 <cflocation url=”CompanyList.cfm” addtoken=”Yes”>
 

CFLOCATION takes two attributes: url and addtoken. url specifies where you want to redirect the user, and addtoken tells ColdFusion whether to append CFID and CFTOKEN to the URL. CFID and CFTOKEN are two values that uniquely identify a user’s session. The important thing to remember about CFLOCATION is that it creates a separate request on the server, which means that none of the nonpersistent variables referenced before the CFLOCATION tag are accessible in the destination template. If you want to pass variables to the destination page, add them to the end of CFLOCATION’s url attribute as key-value pairs. Remember to never send secure data (such as credit card numbers) through the URL, as this information is typically collected in Web-server logs. Use CFABORT to halt a request at a specific point in processing and send the output created up to that point back to the user’s browser. CFABORT has an optional attribute, showerror, as shown in the following line:

<cfabort showerror=”This is my error message.”>

Calling CFABORT with the showerror attribute stops processing the page and also throws an error. The showerror attribute is rarely used anymore; CFTHROW is the preferred method of throwing user-defined errors. In this article you’ve learned the various flow control constructs and techniques available in ColdFusion and how to use them effectively. You have available only a few types of flow control—If constructs, Switch constructs, Loop constructs, inclusions, redirections, and aborts—but they appear throughout almost every ColdFusion application, so you must master them if you are to become a proficient developer.

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

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

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

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

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

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

7. Understanding All Relational Result Sets
This article can help you better understand complicated SQL containing multitable joins, group-related clauses, and aggregate functions—by far the most problematic topics for most database developers. You also learn the correct way to handle database exceptions and incorporate them as actual functionality in your ColdFusion application. You learn, too, how to increase performance by caching queries in memory for fast access. You can memorize SQL clauses and Bachus-Naur forms until you’re blue in the face, ...