Dynamically Populating Select Boxes

During the last procedure, you hard-coded a form's select box options.

Instead of manually entering department information on a form, you can dynamically populate a select box with database column 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:

Usage example

This code retrieves department data for a form page and stores it in the GetDepartments query variable:

    SELECT     Department_Name
    FROM     Departments

This code dynamically populates the Department_Name select box with the GetDepartments query data:

<SELECT NAME="Department_Name">
    <CFOUTPUT QUERY="GetDepartments">
        <OPTION VALUE="#Department_Name#">
Note To dynamically populate a select box:
  1. Open FormPage.cfm in HomeSite.
  2. Build a query to retrieve the Department_Name column from the HRExpress Departments table by adding this code between the opening BODY tag and the opening FORM tag:
  3. <CFQUERY NAME="GetDepartments" DATASOURCE="HRExpress">
        SELECT Department_Name
        FROM Departments
  4. Locate the select box on the form.
  5. Change the select box NAME attribute to DEPARTMENT_NAME:
  6. <SELECT NAME="Department_Name">
  7. Delete all current select box OPTION blocks.
  8. Add an OPTION block within the SELECT block so that users can select ALL departments.
  10. Add a second OPTION block within the SELECT block that dynamically populates the select box with the GetDepartments query result set:
  11. <CFOUTPUT QUERY="GetDepartments">
        <OPTION VALUE="#Department_Name#">
  12. Save the page.
  13. View FormPage.cfm in a browser.
  14. The changes that you just made appear in the form.

    Remember that you need an action page to submit values.

Click here to see how the page should look at this time.

Click here to see the code behind the scenes.

Move on in this chapter to learn how to create action pages and work with form variables.

Note Note:The behind the scenes code refers to a different action page than the one that you are building.

You will receive errors if you submit the form for processing at this time. You will learn about action pages and the characteristics of form variables later on in this chapter.