Jump to content

ColdFusion Programming/control structures

From Wikibooks, open books for an open world

As in most programming languages Coldfusion includes control structures to help your program be more useful.

The most basic control structure is the CFIF. It works exactly like an If statement in other programming languages.

A sample CFIF statement would look like this:

<cfif 2 gt 1>
  First
<cfelse>
  Second
</cfif>

The result would be: First

CFSWITCH

[edit | edit source]

Like with other programming languages Coldfusion provides a switch functionality.

Sample CFSWITCH:

<cfswitch expression="bob">
  <cfcase value="george">
    George
  </cfcase>
  <cfcase value="bob">
    Bob
  </cfcase>
</cfswitch>

The result would be: Bob

CFLOOP

[edit | edit source]

Index Loop:

  • Attributes
    • from - starting number
    • to - ending number
    • index - value within the loop
    • step - optional (default 1) - change to make with each iteration

Example:

  <cfloop from="1" to="9" index="i">
    #i#
  </cfloop>

Results: 1 2 3 4 5 6 7 8 9

  <cfloop from="1" to="9" index="i" step="2">
    #i#
  </cfloop>

Results: 1 3 5 7 9

Conditional Loop:

  • Attributes
    • condition - continue looping as long as condition is true

Example:

  <cfset i = 2>
  <cfloop condition="i lt 10">
    #i#
    <cfset i = i + 2>
  </cfloop>

Results: 1 3 5 7 9

Query Loop:

  • Attributes
    • query - query name you want to loop through
    • startrow - optional(default 1) - row to begin with
    • endrow - optional(default last) - row to end with

Query getpeople looks like this:
Age Name
10 Bill
25 Martha
30 Judy

Example:

  <cfloop query="getpeople">
    #Age#, #Name#
  </cfloop>

Results:
10, Bill
25, Martha
30, Judy

List Loop:

  • Attributes
    • index - variable to hold element of list
    • list - list to go through
    • delimiters - optional (default ,) - separator used to break list apart

List people looks like this: (Bill,Martha,Judy)

Example:

  <cfloop list="people" index="i">
    #i#!
  </cfloop>

Results: Bill! Martha! Judy!

Collection Loop:

  • Attributes
    • collection - structure name you want to loop through
    • item - variable to hold element of structure

Structure place looks like this:
Zip Name
55057 Northfield

Example:

  <cfloop collection="#place#" item="i">
    <cfoutput>#i#-#place[i]#</cfoutput>,
  </cfloop>

Results:
Zip-55057, Name-Northfield