Loops in CF Sandra Clark Senior Software Developer Constella Group
2 Introduction Loops - many types Many uses
3 Loop Types Here is what we will be covering: For Loops While Loops Query Loops List Loops More advanced loops not covered: Structure Loops COM Loops
4 What to use loops for Use FOR loops when you know exactly how many times a set of statements should be executed Use LIST loops when you want to loop over something other than numbers Use WHILE loops when you want to execute a set of statements as long as a condition is True Use QUERY loops when you want to repeat for all records in a query.
5 Loop uses Repeating HTML Processing text Outputing queries Nested Loops Breaking out of loops Banding report lines
6 1.1 FOR Loops “FOR NEXT” loop <CFLOOP INDEX="parameter_name" FROM="beginning_value" TO="ending_value" STEP="increment"> Lines to repeat Is INDEX LT TO? If so loop INDEX = FROM INDEX = INDEX + STEP
7 FOR CFLOOP Parameters INDEX -name of variable that controls loop execution FROM - starting loop value TO - ending loop value STEP – controls amount index variable is incremented (or decremented) in each loop iteration Note: Loop may execute zero times if backwards - for example FROM 2 TO 1
8 FOR Loop Example 1 The loop index is #LoopCount#. (Assume inside CFOUTPUT tags) This produces…. The loop index is 5. The loop index is 4. The loop index is 3. The loop index is 2. The loop index is 1. Must have CFOUTPUT
9 FOR Loop Example 2 HTML list boxes of hours that goes from 0 to 23 #hour#
10 Nested Loop Example List box with all the hours and minutes of the day. #hour#:#minute# This is 1440 items! Not a good idea for a real site
WHILE Loops “DO WHILE” loop #dice# Is condition true? If so loop again Final loop run has condition false! Same syntax as CFIF conditions
12 WHILE Loop details FOR and LIST loops are executed a certain number of times WHILE loops are executed while a condition is true Statements to loop through
13 WHILE Loop Parameters WHILE Loops CONDITION contains a logical expression that is evaluated before each loop iteration As long as CONDITION is true – the loop is executed Tip - Make sure you change the values of variables used in CONDITION expression in the loop body – otherwise infinite loop!
14 Conditional operators GT, LT, GTE, LTE, EQ, NEQ, IS, CONTAINS are the relational operators supported by ColdFusion (don’t use > etc because CFML uses >) AND, OR, NOT are the logical operators supported by ColdFusion Use ()s to group expressions
15 Operator precedence () IS, EQ, NEQ, LT, LE, GT, GE, CONTAINS NOT AND OR
16 CFBREAK CFBREAK exits the current loop #StopIt# More code here
Query Loops CFOUTPUT CFLOOP CFMAIL
18 CFOUTPUT Query Loop SELECT FROM Customer #Get . # Variable available: –Queryname.currentrow –Queryname.recordcount Any records left? If so loop again Start at first record
19 CFLOOP Query Loop SELECT FROM Customer #Get . # Any records left? If so loop again Start at first record CFOUTPUT required
20 CFMAIL loop Send one for each record in the query SELECT FROM Customer <CFMAIL QUERY="Get " TO="#Get . #" SUBJECT=“Test” SERVER="smtp.mycompany.com"> Hi There Any records left? If so loop again Start at first record
21 Nested Query Loop Example SELECT , SecurityLevel FROM Customer SELECT Text, Subject FROM Messages WHERE SecurityLevel = #Get .SecurityLevel# <CFMAIL QUERY="GetText" TO="#Get . #" SUBJECT="#GetText. Subject#" SERVER="smtp.mycompany.com">#GetText. Text#
22 Other recordsets You can loop over record sets from other tags than CFQUERY: CFDIRECTORY – file list CFPOP – read CFSEARCH – Verity text search CFLDAP – LDAP records CFWDDX
List Loops “FOR EACH” loop <CFLOOP INDEX="ListElement" LIST="#form.state#" DELIMITERS=","> #ListElement# –Other delimiters than comma are allowed Any items left in list? If so loop again Start at first item in list
24 How list loops work LIST loops allow you to list the values for the control variable instead of computing them as in the FOR loop <CFLOOP INDEX=“list_variable” LIST=“value_list”> Statements to loop through
25 List Loop parameters INDEX - variable that controls loop execution LIST - a list of comma separated values INDEX is assigned the values in list one at a time as the loop executes DELIMITERS – optional to give a delimiter other than comma
26 List Loop example List local states <CFLOOP INDEX=“StateName” LIST=“MD, VA, DC”> #StateName# Produces…. MD VA DC
27 Text file as a “list” Text file processing by line can be done using lists Read in text file using CFFILE Use CR as delimiter The list elements are now the lines in the file.
28 Read text file code #line# Count lines is #ListLen(text_file,"#CHR(13)#")#
Structure Loops Loop over all people in the Department #person#, #StructFind(Departments, person#) Any items left in structure? If so loop again Start at first item in structure
COM Loops FOR EACH OBJECT Loops #file2.name#
31 CFSCRIPT Loops CFScript is a JavaScript like language that provides the standard looping features of CFML plus a few more looping features For While Do-while For-in CFScript also includes the continue and break statements that control loop processing.
32 CFSCRIPT Loops syntax FOR loop for (inital-expression; test-expression; final-expression) statement WHILE loop while (expression) statement UNTIL loop – evaluates condition at end of loop do statement while (expression);
33 More CFSCRIPT loops Structure loop for (variable in structure) statement The continue statement tells ColdFusion to skip to the beginning of the next loop iteration. The break statement exits the current loop or case statement. Similar to Note: Still use LTE etc for conditionals in CFSCRIPT and not the JavaScript <
34 CFSCRIPT for for (inital-expression; test-expression; final-expression) statement Evaluates the initial expression. Evaluates the test-expression. If the test-expression is False, exits the loop and processing continues following the statement.If the test-expression is True: –Executes the statement (or statement block). –Evaluates the final-expression. –Loops
35 for loop example Assign array a(1) =1 etc for(index=1; index LT 10; index = index + 1) a[index]=index;
36 Infinite for loop example Search for key using break to stop infinite loop indx=0; for( ; ; ) { indx=indx+1; if(Find("key",strings[indx],1)) { WriteOutput("Found key at " & indx & ". "); break; } else if (indx IS ArrayLen(strings)) { WriteOutput("Exited at " & indx & ". "); break; } }
37 Resources CFDOCS Ben Forta Books
38 Questions