User Guide
88 Chapter 6 Making Variables Dynamic
Ensuring that Variables Exist
The sample code in the previous sections is incomplete. Either the form or the action
page should make sure that the SelectDepts variable has a value before it is used in
the SQL Select statement. Otherwise, users who do not select any department get an
error message. There are several ways to ensure that a variable exists before you use
it:
• You can use the
IsDefined function, as described in the section “Testing for a
variable's existence,” in Chapter 4.
• You can use the
cfparam tag to test for a variable and set it to a default value if it
does not exist.
• You can use a form
input tag with a hidden attribute to tell ColdFusion to display
a helpful message to any user who does not enter data in a required field.
Using cfparam to test for variables and set default values
One way to ensure a variable exists is to use the cfparam tag, which tests for the
variable’s existence and optionally supplies a default value if the variable does not
exist. The following code shows the syntax of the
cfparam tag:
<cfparam name="VariableName"
type="data_type"
default="DefaultValue">
Note
For information on using the type attribute to validate the parameter data type, see
the “Using cfparam to validate the data type” section of this chapter.
There are two ways to use the
cfparam tag to test for variable existence, depending
on how you want the validation test to proceed:
• With only the
name attribute to test that a required variable exists. If it does not
exist, the ColdFusion Server stops processing the page and displays an error
message.
• With the
name and default attributes to test for the existence of an optional
variable. If the variable exists, processing continues and the value is not changed.
If the variable does not exist, it is created and set to the value of the
default
attribute, and processing continues.
The following example shows how to use the cfparam tag to check for the existence of
an optional variable and to set a default value if the variable does not already exist:
<cfparam name="Form.Contract" default="Yes">
Example: Testing for variables
Using cfparam with the name variable is one way to clearly define the variables that a
page or a custom tag expects to receive before processing can proceed. This can
make your code more readable, as well as easier to maintain and debug.