Evaluating Dynamic Expressions ColdFusion Help

In this chapter, you will learn about dynamic expressions. Dynamic expressions provide a way to extend the functionality of basic ColdFusion expressions. Basic ColdFusion expressions are dynamic only insofar as their values can be deteI’Illil1ed at the time of execution by the value of variables. Dynamic expressions take this.level of abstraction one level further, allowing the expression itself to be determined at the time of execution based on the value of variables.

You will learn the mechanics of building dynamic expressions and then will look at the application of dynamic expression using four functions:
• Evaluate
• DE
• SetVariable
• IIf

Understanding Dynamic Expressions

In Chapter 6, “Writing Expressions,” you learned how to build and use ColdFusion expressions. Expressions are powerful in their own right, allowing for a degree of abstraction in your ColdFusion templates. For instance, you can use the expression.

#Form.Nwmber# + 1

to add 1to the value submitted by the user in the form. The expression itself has no value at the time the code is written, but instead evaluates to a different value each time the code is executed, depending on the value entered by the user. Dynamic expressions offer the capability to carry this abstraction one level further. Let’s consider a simple example. Look at the following variable assignments:

<CFSET Numl-l>
<CFSET Num2-2>
<CFSET Num3-3>

How would you increment one of these three values by 1and assign it to another variable where the user can specify which value to increment by submitting a number through a form? .

At first glance, you could achieve this by using a CFIF construct or a CFSWITCH/ CFCASE construct:

<CrSET NewNum – Numl + 1>
<CFSET NewNum ~ Num2 + 1)
<CFSET NewNum – Num3 + 1>

Although this example works, it is far from concise or elegant. In addition, if the number of possible variables you are working with is large, then you have a lot of coding to do to make things work. For instance, if you have 100 variables, numl through numlOO, you would need to write 100 CFCASE blocks.

This is where dynamic expressions come in. The idea here is to create a string that, when evaluated, is the expression you need to increment the desired variable. For instance, the following expression

‘Num#Form.Number# + l’

is a simple string. If the user submits the number 3, then this string evaluates to

Num3 + 1

If you t,hen, in turn, are able to evaluate this new expression, you can effectively add 1 to the desired value without having to use multiple conditions. This is what dynamic expressions are all about: evaluating a string expression to get another expression, which can in turn be evaluated.

Posted on November 16, 2015 in Evaluating Dynamic Expressions

Share the Story

Back to Top
Share This