Conditional processing with switch
You can achieve contextual selection of code segments with <cfIf>
. However, the <cfSwitch>
tag has unique style that will become a conditional processing favorite in certain scenarios. As our goal is language mastery, in this chapter we will again restructure the FAQ example using the switch
statement logic. This is by no means the best use of a switch
statement, but it will help you see how the logic works. You will not see any difference when you look at the browser from the user side.
<!--- Example: 1_22.cfm ---> <!--- Processing ---> <cfparam name="url.faq" default=""> <cfscript> faq = arrayNew(1); faq[1] = structNew(); faq[1].question = "What is the speed limit?"; faq[1].answer = "55"; faq[1].id = "a"; faq[2] = structNew(); faq[2].question = "What is a car?"; faq[2].answer = "Depends who you ask!"; faq[2].id = "b"; faq[3] = structNew(); faq[3].question = "How much is gas?"; faq[3].answer = "more than before"; faq[3].id = "c"; </cfscript> <cfswitch expression="#url.faq#"> <cfcase value="b"> <cfset question = faq[2].question> <cfset answer = faq[2].answer> </cfcase> <cfcase value="c"> <cfset question = faq[3].question> <cfset answer = faq[3].answer> </cfcase> <cfdefaultcase> <cfset question = faq[1].question> <cfset answer = faq[1].answer> </cfdefaultcase> </cfswitch> <!--- Content ---> <cfoutput> <strong>#question#</strong><br /> Answer: #answer#<br /><br /> </cfoutput> All Questions <hr /> <cfloop from="1" to="#arrayLen(faq)#" index="iFAQ"> <cfoutput> <strong>Q</strong>: <a href="?faq=#faq[iFAQ].id#">#faq[iFAQ].question#</a><br /> </cfoutput> </cfloop>
We added an extra structure element to each array item just to make this example do a better job at illustrating the switch
condition. You will note that the hyperlink reference passed to the browser is now based on the value of the ID in each structure element. If url.faq
contains no value, then the default
value will be empty. This is because we are showing how to use the cfdefaultcase
when there is no other match. One of the beauties of this is we were able to eliminate all the protection logic we had in the previous example. In some ways, the page has been made simpler in this example.
When the page comes to the cfswitch
statement, the value of the expression is stored for comparison with each case until a match is found. If no match is found, it will check for a default case code segment. If the default case exists, then that code segment will be executed accordingly. Try it out and see if you understand what we have accomplished with this code. You might at this point even add a couple of new questions just to get a feel of what you have learned.
ColdFusion 9 added another case statement to the switch condition. This would be <cffinally>.