
102
DEVELOPING
COLDFUSION 9 APPLICATIONS
The CFML Programming Language
Las
t
upda
te
d 8/5/2010
<!--- Create a structure and set its contents. --->
<cfset departments=structnew()>
<cfset val=StructInsert(departments, "John", "Sales")>
<cfset val=StructInsert(departments, "Tom", "Finance")>
<cfset val=StructInsert(departments, "Mike", "Education")>
<!--- Build a table to display the contents --->
<cfoutput>
<table cellpadding="2" cellspacing="2">
<tr>
<td><b>Employee</b></td>
<td><b>Department</b></td>
</tr>
<!--- Use cfloop to loop through the departments structure.
The item attribute specifies a name for the structure key. --->
<cfloop collection=#departments# item="person">
<tr>
<td>#person#</td>
<td>#Departments[person]#</td>
</tr>
</cfloop>
</table>
</cfoutput>
Structure examples
Structures are useful for grouping a set of variables under a single name. The following example uses structures to
collect information from a form, and to submit that information to a custom tag, named
cf_addemployee
. For
information on creating and using custom tags, see “
Creating and Using Custom CFML Tags
” on page 208.
Example file newemployee.cfm
The following ColdFusion page shows how to create structures and use them to add data to a database. It calls the
cf_addemployee
custom tag, which is defined in the addemployee.cfm file.
<html>
<head>
<title>Add New Employees</title>
</head>
<body>
<h1>Add New Employees</h1>
<!--- Action page code for the form at the bottom of this page. --->
<!--- Establish parameters for first time through --->
<cfparam name="Form.firstname" default="">
<cfparam name="Form.lastname" default="">
<cfparam name="Form.email" default="">
<cfparam name="Form.phone" default="">
<cfparam name="Form.department" default="">
<!--- If at least the firstname form field is passed, create
a structure named employee and add values. --->
<cfif #Form.firstname# eq "">
<p>Please fill out the form.</p>