Welcome!

ColdFusion Authors: Dmitry Sotnikov, Maureen O'Gara, Yakov Fain, David Strom, Elizabeth White

Related Topics: ColdFusion

ColdFusion: Article

ColdFusion Forms Part 1.

ColdFusion Forms Part 1.

Using Forms
In the previous two articles (CFDJ, Vol. 2, issues 2 and 3) on "ColdFusion Basics," you learned how to create ColdFusion templates that dynamically display data retrieved from ODBC data sources. The A2Z Employees table has just 10 rows, so the data fits easily within a Web browser window.

What do you do if you have hundreds or thousands of rows? Displaying all that data in one long list is impractical. Scrolling through lists of names to find the one you want just doesn't work well. The solution is to enable users to search for names by specifying what they are looking for. You can allow them to enter a first name, a last name, or part of a name, and then you can display only the employee records that meet the search criteria.

To accomplish this solution, you need to do two things. First, you need to create your search form using the HTML form tags. Second, you need to create a template that builds SQL SELECT statements dynamically based on the data collected and submitted by the form. Creating Forms

Before you can create a search form, you need to learn how ColdFusion interacts with HTML forms. Listing 1 contains the code for a sample form that prompts for a first and last name. Create this template and save it in the C:\A2Z\SCRIPTS\12 directory as FORM1.CFM.

In your browser, type http://your-server.com/a2z/12/FORMS1.cfm to display the form as shown in Figure 1.

This form is simple, with just two data entry fields and a submit button, but it clearly demonstrates how forms are used to submit data to ColdFusion. Using HTML Form Tags
You create HTML forms by using the

tag. usually takes two parameters passed as tag attributes. The ACTION attribute specifies the name of the script or program that the Web server should execute in response to the form's submission. To submit a form to ColdFusion, you simply specify the name of the ColdFusion template that will process the form. The following example specifies that the template forms2.cfm should process the submitted form: ACTION="forms2.cfm"

The METHOD attribute specifies how data is sent back to the Web server. All ColdFusion forms must be submitted as type POST.

Caution: The default submission type is not POST; it is usually GET. If you omit the METHOD="POST" attribute from your form tag, you run the risk of losing form data — particularly in long forms or forms with TEXTAREA controls.

Your form has only two data entry fields:

<INPUT TYPE="text" NAME ="FirstName">
and
<INPUT TYPE ="text" NAME="LastName">.

Both create simple text fields. The NAME attribute in the <INPUT> tag specifies the name of the field, and ColdFusion uses this name to refer to the field when it is processed.

Each form in a field is typically given a unique name. If two fields have the same name, both sets of values are returned to be processed and are separated by a comma. You usually want to be able to validate and manipulate each field individually, so each field should have its own name. The notable exceptions are the check box and radio button input types, which are described later in this chapter.

The last item in the form is an INPUT submit type. The submit input type creates a button that, when clicked, submits the form contents to the Web server for processing. Almost every form has a submit button (or a graphic image that acts like a submit button). The VALUE attribute specifies the text to display within the button, so <INPUT TYPE="submit" VALUE="Process"> creates a submit button with the text Process in it.

Understanding ColdFusion Error Messages
If you enter your name into the fields and submit the form right now, you receive a ColdFusion error message like the one shown in Figure 2. This error says that template C:\A2Z\ SCRIPTS\12\FORMS2.CFM cannot be found.

This error message, of course, is perfectly valid. You submitted a form to be passed to ColdFusion and processed with a template, but you have not created that template yet. Your next task, then, is to create a template to process the form submission.

Processing Form Submissions
To demonstrate how to process returned forms, you need to create a simple template that echoes the name you enter. The template is shown in Listing 2.

Processing Text Submissions
By now the CFOUTPUT tag should be familiar to you; you use it to mark a block of code that ColdFusion should parse and process. The line Hello #FirstName# #LastName# is processed by ColdFusion. #FirstName# is replaced with the value you entered into the FirstName field, and #LastName# is replaced with the value in the LastName field in Form 1. See CFDJ, Vol. 2, issue 3 for a detailed discussion of the ColdFusion CFOUTPUT tag.

Create a template called FORMS2.CFM that contains the code in Listing 2 and save it in the C:\A2Z\SCRIPTS\12 directory. Resubmit your name by clicking the form's submit button once again. This time you should see a browser display similar to the one shown in Figure 3. Whatever name you enter into the First Name and Last Name fields in Form 1 is displayed.

Processing Check Boxes and Option Buttons
Other input types that you will frequently use are check boxes and option buttons. Check boxes are used to select options that have one of two states: on or off, yes or no, and true or false. To ask a user if he wants to be notified of book availability via e-mail, for example, you would create a check box field. If the user selects the box, his name is added to the mailing list; if the user does not select the box, his name is not added. The code example in Listing 3 creates a form that uses both option buttons and check box fields.

Figure 4 shows how this form appears in your browser.

Before you create FORMS4.CFM to process this form, you should note a couple of important points. First look at the four lines of code that make up the Payment Type option button selection. Each one contains the exact same NAME attribute — NAME="PaymentType". The four input fields clearly have the same name, so your browser knows that they are part of the same field. If each option button has a separate name, the browser does not know that these buttons are mutually exclusive and thus allows the selection of more than one button.

Another important point is that, unlike INPUT type text, option buttons have no associated text or data entry area. Therefore, you must use the VALUE attribute in order for the browser to associate a particular value with each option button. The code VALUE="Cash" instructs the browser to return the value Cash in the PaymentType field if that button is selected.

Now that you can accept option button and check box fields, you're ready to create a template to process them. Create a template called FORMS4.CFM in the C:\A2Z\SCRIPTS \12 directory using the template code in Listing 4.

The form processing code in Listing 4 displays the payment type you select. The field PaymentType is fully qualified with the FORM field type to prevent name collisions.(See "Specifying Field Types" [CFDJ, Vol. 2, Issue 3] for an explanation of name collisions and how to avoid them.)

When the check box is selected, the value specified in the VALUE attribute is returned; in this case the value is Yes. If the VALUE attribute is omitted, the default value of on is returned.

Now load form FORMS3.CFM on your browser, select a payment option, and then select the check box. Click the Process button. Your browser display should look like the one shown in Figure 5.

That process worked exactly as intended, so now get ready to complicate things a little. Reload template FORMS3.CFM and submit it without selecting a payment type or with the MailingList field not selected. As a result, ColdFusion generates an error message, as shown in Figure 6. The field you do not select generates a "Form Field Not Found" error.

Check the code in Listing 3 to verify that the form fields do in fact exist. Why does ColdFusion report that the form field does not exist? That is one of the quirks of HTML forms. If you select a check box, the on value is submitted; nothing is submitted if you do not select the check box — not even an empty field. The same is true of option buttons: if you make no selection, the field is not submitted at all. (This behavior is the exact opposite of the text INPUT type, which returns empty fields as opposed to no field.)

How do you work around this limitation? You can choose from two solutions. The first: modify your form processing script to check which fields exist by using the #Is defined()# function and, if the field exists, process it.

The second: the simpler solution is to prevent the browser from omitting fields that are not selected. You can modify the option button field so that one option is preselected. The users cannot avoid making an option button selection, so they have to make a selection or use the preselected options. To preselect an option button, just add the attribute CHECKED to one of the buttons.

Check boxes are trickier because by their nature they have to be able to be turned off. Check boxes are used for on/off states, and, when the check box is off, there is no value to submit. The solution is to set a default value in the action template. This is done using a ColdFusion tag called <CFPARAM>, which allows you to create variables on-the-fly if they do not already exist. Look at this code:

<CFPARAM NAME="MailingList" DEFAULT="No">

When ColdFusion encounters this line, it checks to see if a variable named MailingList exists. If yes, processing continues. If it does not exist, ColdFusion creates the variable and sets the value to whatever is specified in the DEFAULT attribute. The key here is that either way — whether the variable existed or not — the variable does exist once the tag is processed. It is therefore safe to refer to that variable further down the template code.

The updated form is shown in Listing 5. The first option button in the PaymentType field is modified to read <INPUT TYPE="radio" NAME="PaymentType" VALUE="Cash" CHECKED>. The CHECKED attribute ensures that a button is checked. The MailingList check box has a VALUE of Yes when it is checked, and the in the action page ensures that if MailingList is not checked, the value will automatically be set to No. Create and save this template as C:\A2Z\SCRIPTS\12\FORMS5.CFM and then add the following code to the top of FORMS4.CFM:

<CFPARAM NAME="MailingList" DEFAULT="No">

Try using it and experiment with the two fields. You'll find that this form is reliable and robust, and it does not generate ColdFusion error messages.

Processing List Boxes
Another field type you will frequently use is the list box. Using list boxes is an efficient way to enable users to select one or more options. If a list box is created to accept only a single selection, you can be guaranteed that a value is always returned. If you don't set one of the options to be preselected, the first one in the list is selected. An option always has to be selected.

List boxes that allow multiple selections also allow no selections at all. If you use a multiple selection list box, you once again have to find a way to ensure that ColdFusion does not generate "Form Field Not Found" errors.

Listing 6 contains the same data entry form you just created but replaces the option buttons with a list box. Save this template as C:\A2Z\ SCRIPTS\12\FORMS6.CFM and then test it with your browser.

For this particular form, the browser display shown in Figure 7 is probably a better user interface. The choice of whether to use option buttons or list boxes is yours, and no hard and fast rules exist as to when to use one versus the other. The following guidelines, however, may help you determine which to use:

  • If you need to allow the selection of multiple items or of no items at all, use a list box.
  • List boxes take up less screen space. With a list box, one hundred options take up no more precious real estate than a single option.
  • Option buttons present all the options to the users without requiring mouse clicks.

Processing Text Areas
Text area fields are boxes in which the users can enter free-form text. When you create a text area field, you specify the number of rows and columns of screen space it should occupy. This area, however, does not restrict the amount of text that users can enter. The field scrolls both horizontally and vertically to enable the users to enter more text.

Listing 7 creates an HTML form with a text area field for user comments. The field's width is specified as a number of characters that can be typed on a single line; the height is the number of lines that are displayed without scrolling.

Listing 8 contains ColdFusion code that displays the contents of a TEXTAREA field.

Figure 8 shows the TEXTAREA field you created, and Figure 9 shows how ColdFusion displays the field.

Try entering line breaks (by pressing the Enter key) in the text field and then submit it. What happens to the line breaks? Line break characters are considered whitespace characters, just like spaces, by your browser, and all whitespace is ignored by browsers. "WHITESPACE IS IGNORED" is displayed no differently than "WHITESPACE IS IGNORED."

The only way to display line breaks is to replace the line break with an HTML paragraph tag: <P>. You therefore have to parse through the entire field text and insert <P> tags wherever needed. Fortunately, ColdFusion makes this task a simple one. The ColdFusion #ParagraphFormat()# function automatically replaces every double line break with a <P> tag. (Single line breaks are not replaced because ColdFusion has no way of knowing if the next line is a new paragraph or part of the previous one.)

The code in Listing 9 contains the same comments form as the one in Listing 7, with two differences. First, default field text is provided. Unlike other INPUT types, <TEXTAREA> default text is specified between <TEXTAREA> and </TEXTAREA> tags — not in a VALUE attribute.

Second, you use the WRAP attribute to wrap text entered into the field automatically. WRAP="VIRTUAL" instructs the browser to wrap to the next line automatically, just as most word processors and editors do.

Note: Many browsers do not support the TEXTAREA WRAP attribute. These browsers ignore the attribute and require the users to enter line breaks manually. Because the attribute is ignored when not supported, you can safely use this option when necessary; your forms do not become incompatible with older browsers.

Listing 10 shows the template to display the user-supplied comments. The Comments field code is changed to #ParagraphFormat(FORM.Comments)#, ensuring that all line breaks are maintained and displayed correctly, as shown in Figure 10.

Processing Buttons
The HTML forms specification supports only two types of buttons. Almost all forms, including all the forms that you create in both parts of this article, have a submit button. Submit, as its name implies, instructs the browser to submit the form fields to a Web server.

The second supported button type is reset. Reset clears all form entries and restores default values if any existed. Any text entered into INPUT TYPE="text" or TEXTAREA fields is cleared, as are any check box, list box, and option button selections. Many forms have reset buttons, but you never need more than one.

On the other hand, you may want more than one submit button. For example, if you're using a form to modify a record, you could have two submit buttons: one for Update and one for Delete. (Of course, you also could use two forms to accomplish this task.) If you create multiple submit buttons, you must name the button with the NAME attribute and make sure to assign a different VALUE attribute for each. The code in Listing 11 contains a reset button and two submit buttons.

The result of this code is shown in Figure 11. When you name submit buttons, you treat them as any other form field. Listing 12 demonstrates how to determine which submit button was clicked. The code <CFIF FORM.Operation IS "Update"> checks to see if the Update button was clicked, and <CFELSEIF FORM.Operation IS "Delete"> checks to see if Delete was clicked, but only if Update was not clicked.

More Stories By Ben Forta

Ben Forta is Adobe's Senior Technical Evangelist. In that capacity he spends a considerable amount of time talking and writing about Adobe products (with an emphasis on ColdFusion and Flex), and providing feedback to help shape the future direction of the products. By the way, if you are not yet a ColdFusion user, you should be. It is an incredible product, and is truly deserving of all the praise it has been receiving. In a prior life he was a ColdFusion customer (he wrote one of the first large high visibility web sites using the product) and was so impressed he ended up working for the company that created it (Allaire). Ben is also the author of books on ColdFusion, SQL, Windows 2000, JSP, WAP, Regular Expressions, and more. Before joining Adobe (well, Allaire actually, and then Macromedia and Allaire merged, and then Adobe bought Macromedia) he helped found a company called Car.com which provides automotive services (buy a car, sell a car, etc) over the Web. Car.com (including Stoneage) is one of the largest automotive web sites out there, was written entirely in ColdFusion, and is now owned by Auto-By-Tel.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.