User Guide

82 Chapter 6 Making Variables Dynamic
Dynamically Populating List Boxes
In Chapter 4, you hard-coded a forms list box options. Instead of manually entering
the information on a form, you can dynamically populate a list box with database
fields. When you code this way, the form page automatically reflects the changes that
you make to the database.
You use two tags to dynamically populate a list 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 list box:
1 Open the file formpage.cfm in ColdFusion Studio.
2 Modify the file so that it appears as follows:
<html>
<head>
<title>Input form</title>
</head>
<body>
<cfquery name="GetDepartments" datasource="CompanyInfo">
SELECT DISTINCT Location
FROM Departmt
</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>
<!-- list box -->
City
<select name="City">
<cfoutput query="GetDepartments">
<option value="#GetDepartments.Location#">
#GetDepartments.Location#
</option>
</cfoutput>
</select>