• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Lesson 4. Using Forms with ColdFusion > Generating Default Form Variables

Generating Default Form Variables

There may be times when a user leaves a (non-required) field empty on a form. In some cases, this is not a problem. However, for some, you may want or need to supply a default value. Here we'll create a non-required field in the form and learn about when you need to add a default value.

In the basicform.cfm template, add the following code after the comments form field:

Join mailing list?<br> 
<input type="checkbox" name="mailinglist" value="yes">Yes<br><br>

Now you've created a field that lets users decide whether they want to join a mailing list. Since this will be an optional field, you don't have to add a validation rule for it. If users don't want to join, they just won't check the box.

But if they don't, there is no variable to pass to the action page. And this will result in an error. If you try to access a check box on the action page that was not passed, you get an error message. (In contrast, if you leave a text box empty, the form passes an empty string as the variable, and that won't produce an error.)

Therefore, this field is a good candidate for a default value—in this case, the default value for the variable will be “No,” since if the user does not want to join, they won't have checked the box.

Go to the formoutput.cfm template, and add the following code at the top of the document:

<cfparam name="form.mailinglist" default="No"> 

You have just created the default value “No” for the mailinglist form variable. If the user does not check the mailing list check box, then the form variable mailinglist will be created, and assigned the value “No.”

Still in the formoutput.cfm template, scroll down to where the form values are displayed, and add the following code after Comments:

Join Mailing List: #form.mailinglist# 

Now the variable will display in form output whether or not it was checked on the form. Once again, it always helps for you to see this in practice.


The <cfparam> tag will work on check boxes as well as form boxes.

Open a browser and type the following URL into the address field:

This time when you open the window you see the check box for joining the mailing list.

Fill in all the form fields with your information again, and check the mailing list check box.

If you don't check the check box, the form will still work, but the default value of “no” will be applied to the mailinglist variable. In that case “no” would replace the value “yes” from the above example.

Click Send Comments.

Once again, you should see your information displayed. The only difference is the appearance of the mailinglist variable. It should be yes if you checked the box and no if you didn't.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint