User Guide
46 Developing Web Applications with ColdFusion
Dynamically Populating Select Boxes
In the previous chapter, you hard-coded a form’s select box options.
Instead of manually entering the information on a form, you can dynamically populate
a select box with database fields. When you code this way, changes that you make to a
database are automatically reflected on the form page.
To dynamically populate a select box:
• Use the CFQUERY tag to retrieve the column data from a database table.
• Use the CFOUTPUT tag with the QUERY attribute within the SELECT tag to
dynamically populate the OPTIONS of this form control.
To dynamically populate a select box:
1. Open the file formpage.cfm in Studio.
2. Modify the file so that it appears as follows:
<HTML>
<HEAD>
<TITLE>Input form</TITLE>
</HEAD>
<BODY>
4 <CFQUERY NAME="GetDepartments" DATASOURCE="CompanyInfo">
4 SELECT Location
4 FROM Departments
4 </CFQUERY>
<!--- define the action page in the form tag. The form variables will
pass to this page when the form is submitted --->
<form action="actionpage.cfm" method="post">
<!-- text box -->
<P>
First Name: <INPUT TYPE="Text" NAME="FirstName" SIZE="20"
MAXLENGTH="35"><BR>
Last Name: <INPUT TYPE="Text" NAME="LastName" SIZE="20"
MAXLENGTH="35"><BR>
Salary: <INPUT TYPE="Text" NAME="Salary" SIZE="10" MAXLENGTH="10">
</P>
<!-- select box -->
City
4 <SELECT NAME="City">
4 <CFOUTPUT QUERY="GetDepartments">
4 <OPTION VALUE="#GetDepartments.Location#>
4 #GetDepartments.Location#
4 </OPTION>
4 </CFOUTPUT>