If you want to get a good start on learning ColdFusion, look no further. This article covers a whole bunch of CFML tags and some basic functions. It is the first of two parts, and excerpted from chapter three of the book ColdFusion Web Development with Dreamweaver MX 2004, written by Jen and Peter deHaan et al. (Apress; ISBN: 1590592379).
Introduction to ColdFusion Markup Language - The cfswitch tag (Page 6 of 7 )
ColdFusion also has another conditional logic mechanism that is usually more efficient and results in more modular and easy-to-read code: the<cfswitch>tag. We could change the series ofif ...statements in the first "thisMonth" <cfif> example into the followingswitchstatement (seecfswitch.cfmin the books downloadable code):
<cfset thisMonth = 1> <cfswitch expression="#thisMonth#"> <cfcase value="1"> It is January. </cfcase> <cfcase value="2"> It is February. </cfcase> <cfcase value="3"> It is March. </cfcase> <cfdefaultcase> It is some other month. </cfdefaultcase> </cfswitch>
If you replace the code from the previous example with this, then you will also seeIt is January.in the browser window.
The expression in the<cfswitch>tag is executed only once, and ColdFusion tries to match the expression to a case. If ColdFusion finds no cases that match, it executes the optional<cfdefaultcase>block if it is present. The<cfdefaultcase>acts as the<cfelse>statement did previously. Once ColdFusion finds a matching<cfcase>statement, it skips over the remaining<cfcase>and<cfdefaultcase>blocks. The case statement also accepts a list of comma-separated values, which allows us to say "If the value is X, Y, or Z, then do this."
Here's an example of this (defaultcase.cfm):
<cfset thisMonth = 1> <cfswitch expression="#thisMonth#"> <cfcase value="1,2,3"> It is January, February or March. </cfcase> <cfcase value="4,5,6"> It is April, May or June. </cfcase> <cfdefaultcase> It is something else. </cfdefaultcase> </cfswitch>
The preceding code block does the following: if#thisMonth#is 1, 2, or 3, then the first case will match and the code block will be executed. Otherwise, the<cfswitch>keeps trying to match the value of#thisMonth#to the values listed within the<cfcase>tags until it finds a match or encounters the<cfdefaultcase>tag.
There is one important difference between using a series of<cfif>statements and a<cfswitch>statement. We can test for multiple expressions by using a<cfif>statement by separating them with anANDorORkeyword.
<cfif (IsDefined("Url.Name")) AND (Url.Name EQ "Larry")> ... <cfelseif (IsDefined("Url.Number")) AND (Url.Number EQ 7)> ... </cfif>
This behavior isn't possible using<cfswitch, which can evaluate only a single expression and match a value or series of values, so it isn't always possible to rewrite a<cfif>block as a<cfswitch>. You can also see that, because you are comparing the value ofUrl.Nameto a string, you do need to enclose the string in a pair of quotes.