Creating and Using Structures

This section explains how to use the structure functions to create and use structures in ColdFusion. The sample code in this section uses a structure called employee, which is used to add new employees to a corporate information system.

Creating structures

You create structures by assigning a variable name to the structure with the StructNew function:

<cfset mystructure=StructNew()>

For example, to create a structure named employee, use this syntax:

<cfset employee=StructNew()>

Now the structure exists and you can add data to it.

Adding data elements to structures

After you create a structure, you add key-value pairs to the structure using the StructInsert function:

<cfset value=StructInsert(structure_name, key, value

  [, AllowOverwrite])>

The AllowOverwrite parameter is optional and can be either True or False. You can use it to specify whether an existing key should be overwritten. The default is False.

When adding string values to a structure, enclose the string in quotation marks. For example, to add a key, John, with a value, Sales, to an existing structure called Departments, use this syntax:

<cfset value=StructInsert(Departments, "John", "Sales")>

The following example shows how to add content to a sample structure named employee, building the content of the value fields dynamically using form variables:

<cfset rc=StructInsert(employee, "firstname", "#FORM.firstname#")>

<cfset rc=StructInsert(employee, "lastname", "#FORM.lastname#")>

<cfset rc=StructInsert(employee, "email", "#FORM.email#")>

<cfset rc=StructInsert(employee, "phone", "#FORM.phone#")>

<cfset rc=StructInsert(employee, "department", "#FORM.department#")>

Updating values in structures

You can update structure element values in a cfset tag or a SructUpdate function.

Updating a structure with cfset

You can use the cfset tag to update structure values (but not keys). For example, the following code uses cfset and Object.property notation to change John's department from Sales to Marketing. It then uses associative array notation to change his department to Facilities. Each time the department changes, it outputs the results:

<cfset departments=structnew()>

<cfset value=StructInsert(departments, "John", "Sales")>

<cfoutput>

  Before the first change, John was in the #departments.John#

    Department<br>

</cfoutput>

<cfset Departments.John = "Marketing">

<cfoutput>

  After the first change, John is in the #departments.John#

    Department<br>

</cfoutput>

<cfset Departments.John = "Facilities">

<cfoutput>

  After the second change, John is in the #departments.John#

    Department<br>

</cfoutput>

Updating a structure with StructUpdate

You can also use the StructUpdate function to change the value associated with a specific key. Because StructUpdate is a ColdFusion function, you must use it inside a ColdFusion tag. In some cases, you can use the cfoutput or cfset tag. You can also use the cfscript tag to tell ColdFusion to run a function. The following example uses a StructUpdate function in a cfscript tag to change a structure value. Note that you must follow a statement in a cfscript tag with a semicolon.

<cfset departments=structnew()>

<cfset value=StructInsert(departments, "John", "Sales")>

<cfoutput>

  Before the change, John was in the #departments.John# Department<br>

</cfoutput>

<cfscript>StructUpdate(Departments, "John", "Marketing"); </cfscript>

<cfoutput>

  After the change, John is in the #departments.John# Department<br>

</cfoutput>

For more information on using cfscript, see Chapter 13, "Extending ColdFusion Pages with CFML Scripting"

Getting information about structures

To find out if a given value represents a structure, use the IsStruct function:

IsStruct(variable)

This function returns True if variable is a structure.

Structures are not indexed numerically, so to find out how many name-value pairs exist in a structure, use the StructCount function, as in this example:

StructCount(employee)

To discover whether a specific Structure contains data, use the StructIsEmpty function:

StructIsEmpty(structure_name)

This function returns True if the structure is empty and False if it contains data.

Finding a specific key and its value

To learn whether a specific key exists in a structure, use the StructKeyExists function:

StructKeyExists(structure_name, key)

If the name of the key is known in advance, you can use the ColdFusion function IsDefined, as in this example:

<cfset temp=IsDefined("structure_name.key")>

But if the key is dynamic, or contains special characters, you must use the StructKeyExists function:

<cfset temp=StructKeyExists(structure_name, key)>

You can also use the StructFind function to find a key and return its value, as in this example:

<cfset keyvalue=StructFind(structure_name, key)>

Getting a list of keys in a structure

To get a list of the keys in a CFML structure, you use the StructKeyList function:

<cfset temp=StructKeyList(structure_name, [delimiter] )>

The delimiter can be any delimiter, but the default is a comma ( , ).

The StructKeyArray function returns an array of keys in a structure:

<cfset temp=StructKeyArray(structure_name)>


Note

The StructKeyList and StructKeyArray functions do not return keys in any particular order. Use the ListSort or ArraySort function to sort the results.


Copying structures

To copy a structure, use the StructCopy function. This function takes the name of the structure that you want to copy and returns a new structure with all the keys and values of the named structure.

StructCopy(structure)

This function throws an exception if structure does not exist.

Use the StructCopy function when you want to create a physical copy of a structure. You can also use assignment to create a copy by reference.

Deleting structures

To delete an individual name-value pair in a structure, use the StructDelete function:

StructDelete(structure_name, key [, indicatenotexisting ])

This deletes the named key and its associated value. Note that the indicatenotexisting parameter indicates whether the function returns False if the named key does not exist. The default is False, which means that the function returns Yes regardless of whether key exists. If you specify True for this parameter, the function returns Yes if key exists and No if it does not.

You can also use the StructClear function to delete all the data in a structure but keep the structure instance itself:

StructClear(structure_name)

Structure example

Structures are particularly useful for grouping together a set of variables under a single name. In the following example, structures are used to collect information from a form, structinsert.cfm, and to submit that information to a custom tag at addemployee.cfm.

This examples show how you can use a structure to pass information to a custom tag, named cf_addemployee. For information on creating and using custom tags, see "Reusing Code".

Example file structinsert.cfm

<!--- This example shows how to use the StructInsert

      function. It calls the cf_addemployee custom tag,

      which uses 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 firstaname form field is passed, create

   a structure named employee and add values --->

<cfif #form.firstname# eq "">

 <p>Please fill out the form.

<cfelse>

  <cfoutput>

   <cfscript>

     employee=StructNew();

     StructInsert(employee, "firstname", "#FORM.firstname#");

     StructInsert(employee, "lastname", "#FORM.lastname#");

     StructInsert(employee, "email", "#FORM.email#");

     StructInsert(employee, "phone", "#FORM.phone#");

     StructInsert(employee, "department", "#FORM.department#");

  </cfscript> 



<!--- Display results of creating the structure --->

  <p>First name is #StructFind(employee, "firstname")#</p>

  <p>Last name is #StructFind(employee, "lastname")#</p>

  <p>EMail is #StructFind(employee, "email")#</p>

  <p>Phone is #StructFind(employee, "phone")#</p>

  <p>Department is #StructFind(employee, "department")#</p>

  </cfoutput>



  <!--- Call the custom tag that adds employees --->

<cf_addemployee empinfo="#employee#">

</cfif>



<!--- The form for adding the new employee information --->

<hr>

<form action="structinsert.cfm" method="Post">

<p>First Name:&nbsp;

<input name="firstname" type="text" hspace="30" maxlength="30">

<p>Last Name:&nbsp;

<input name="lastname" type="text" hspace="30" maxlength="30">

<p>EMail:&nbsp;

<input name="email" type="text" hspace="30" maxlength="30">

<p>Phone:&nbsp;

<input name="phone" type="text" hspace="20" maxlength="20">

<p>Department:&nbsp;

<input name="department" type="text" hspace="30" maxlength="30">



<p>

<input type="Submit" value="OK">

</form>



</body>

</html>

Example file addemployee.cfm

<!--- This file is an example of a custom tag used to add employees. 

Employee information is passed through the employee structure (the

empinfo attribute). For databases that do not support automatic key

generation, you must also add the Emp_ID. --->



<cfif structisempty(attributes.empinfo)>

  <cfoutput>Error. No employee data was passed.</cfoutput>

  <cfexit method="ExitTag">

<cfelse>

  <!--- Add the employee --->

  <!--- If auto key generation is not supported,

    you must also add the Emp_ID --->

  <cfquery name="AddEmployee" datasource="cfsnippets">

    INSERT INTO Employees

    (FirstName, LastName, Email, Phone, Department)

    VALUES

    <cfoutput>

    (

    '#StructFind(attributes.empinfo, "firstname")#' ,

    '#StructFind(attributes.empinfo, "lastname")#' ,

    '#StructFind(attributes.empinfo, "email")#' ,

    '#StructFind(attributes.empinfo, "phone")#' ,

    '#StructFind(attributes.empinfo, "department")#'

     )

    </cfoutput> 

  </cfquery>

</cfif>

<cfoutput><hr>Employee Add Complete</cfoutput>

Looping through structures

You can loop through a structure to output its contents as illustrated in the following example. Note that when you enumerate key-value pairs using a loop, the keys appear in uppercase.

<!--- 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>



<!--- In cfloop, use item to create a variable

  called person to hold value of key as loop runs --->

  <cfloop collection=#departments# item="person">

    <tr>

    <td>#person#</td>

    <td>#Departments[person]#</td>

    </tr>

  </cfloop>



</table>

</cfoutput>



Banner.Novgorod.Ru