Using the cfparam tag



You can ensure that a variable exists by using the cfparam tag, which tests for the variable’s existence and optionally supplies a default value if the variable does not exist. The cfparam tag has the following syntax:

<cfparam name="VariableName" 
    type="data_type" 
    default="DefaultValue">
Note: For information on using the type attribute to validate the parameter data type, see the CFML Reference.

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 the cfparam tag with the name attribute 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.

For example, the following cfparam tags indicate that this page expects two form variables named StartRow and RowsToFetch:

<cfparam name="Form.StartRow"> 
    <cfparam name="Form.RowsToFetch">

If the page with these tags is called without either one of the form variables, an error occurs and the page stops processing. By default, ColdFusion displays an error message; you can also handle the error as described in Handling Errors.

Example: setting default values

The following example uses the cfparam tag to see if optional variables exist. If they do exist, processing continues. If they do not exist, the ColdFusion server creates them and sets them to the default values.

<cfparam name="Cookie.SearchString" default="temple"> 
<cfparam name="Client.Color" default="Gray"> 
<cfparam name="ShowExtraInfo" default="No">

You can use the cfparam tag to set default values for URL and Form variables, instead of using conditional logic. For example, you could include the following code on the action page to ensure that a SelectedDepts variable exists:

<cfparam name="Form.SelectedDepts" default="Marketing,Sales">