February 11, 2021
ColdFusion 101: Different ways to create and add data to structures
Comments
(0)
February 11, 2021
ColdFusion 101: Different ways to create and add data to structures
Wizard 43 posts
Followers: 23 people
(0)

Preamble

I love ColdFusion. I’ve been developing websites, applications, and software using ColdFusion for over 20 years. I’ve struggled with the reputation ColdFusion has, and I’ve watched the customer and developer base dwindle. I believe that bringing new developers into the fold starts with the basics. We all started programming somewhere, and I believe there is a dearth of “basic training” available for ColdFusion newcomers. This series is intended to help with that and provide a resource to developers who are just getting started with ColdFusion.

Assumptions

Articles written in this series will assume a few things:

  • You have little to no knowledge or experience building web based applications.
  • You are using a modern version of ColdFusion. As of the time of this writing, I will assume that new developers and new development will be utilizing ColdFusion 2021 or ColdFusion 2018.
  • As such, please understand that there may be some limitations in older versions. Consult documentation for the version of ColdFusion you are coding against for compatibility.

What is a structure?

Structures are a named collection of related data represented as key/value pairs. For example, imagine you’re describing a person. That person has a first name and a last name. They have a gender. They have a birthdate. A height, a weight, eye color, and hair color. They have a nationality. They have many different features that are all related to the same thing; the person in question.

If you were to have a single variable that contained all of that information, it might look something like this:

Creating Structures using ColdFusion

Creating structures in ColdFusion can be done in several ways. Think of it like using the copy and paste functions of your computer. You can press Cmd/CTRL-C and Cmd/CTRL-V. You can use the “Edit > Copy” and “Edit > Paste” menu. You can highlight, right click and select “copy” and “paste” from the context menu. Each of these do exactly the same thing, but are different approaches to accomplishing the same task. Creating a structure in ColdFusion is no different. There’s different ways to do it.

There are at least three ways I know of to create a structure using ColdFusion. Hey community, if there’s more ways to do this, advise in the comments.

Use the structNew() function.

There is a function in ColdFusion named structNew() that creates a structure in a variable. Consider the following code examples:

Tag based:

	<cfset person = structNew()>

Script based:

	person = structNew();

Try it yourself:
https://trycf.com/gist/1597b98676f33509e239394880dea4d9/acf2018

Use JSON bracket notation.

Alternatively, you can create a structure using bracket notation. Consider the following code examples:

Tag based:

	<cfset person = {}>

Script based:

	person = {};

Try it yourself:
https://trycf.com/gist/e76eb3742655c3ecbce5d612742c1095/acf2018

Both of the methods mentioned above will create an empty structure called person, and will look like this:

Set a key!

ColdFusion is smart enough to imply the variable type based on how it’s used. Consider the following code examples, and assume the variables named “person” has not already been defined on the page:

Tag based:

	<cfset person.first_name = "Bart">

Script based:

	person.first_name = "bart";

Try it yourself:
https://trycf.com/gist/1c371effc63f47532bbd1dac5efb8d46/acf2018

Both of these code examples will create a structure called person pre-populated with a key called “first_name” and set to a value of “Bart”, and will look like this:

Setting values in a structure using ColdFusion

There are at least five ways I know of to set values in a structure in ColdFusion. And again… “Hey community, if there’s more ways to do this, advise in the comments.”

Using the structInsert() function

ColdFusion’s structInsert() function inserts a key/value pair into a structure. It takes four arguments:

  • Structure – the structure the key is being inserted into
  • Key – the name of the key
  • Value – the value of the key
  • allowOverwrite – a n optional boolean value, defaulting to false, that determines how to handle duplicate key inserts.

Consider the following code examples:

Tag based:

	<cfset person = structNew()>
	<cfset structInsert(person,"first_name","Bart")>

Script based:

	person = structNew();
	structInsert( person, "first_name", "Bart" );

Try it yourself:
https://trycf.com/gist/afa59177ad3d9c5d7a85928d4c1dcf78/acf2018

Using member functions

As of ColdFusion 11, CFML supports the use of what are called member functions. Think of the use of member functions like stringing a series of functions together in a single statement. Consider the following code examples:

Tag based:

	<cfset person = structNew().insert( "first_name", "Bart" )>

Script based:

	person = structNew().insert( "first_name", "Bart" );

Try it yourself:

https://trycf.com/gist/865a6e6f2175827f91c2fc0462e545d2/acf2018

Using dot notation

Dot notation allows you to set a key within a structure. You set the variable using the structure name, a dot, and then the key name. Consider the following code examples:

Tag based:

	<cfset person = structNew()>
	<cfset person.first_name = "Bart">

Script based:

	person = structNew();
	person.first_name = "Bart";

Try it yourself:
https://trycf.com/gist/baab9c5aeb6d56b2fb5b3b6a7dd3b54f/acf2018

Using bracket notation

Another way to insert a key into a structure is to use bracket notation. Typically, I’ve only seen bracket notation used when the name of the key is variable and to prevent the use of the evaluate() function to establish the value of the variable. Consider the following code examples:

Tag based:

	<cfset person = structNew()>
	<cfset person[‘first_name'] = "Bart">

Script based:

	person = structNew();
	person[‘first_name'] = "Bart";

Try it yourself:
https://trycf.com/gist/792151cffd1746b1911d0155f406e2d4/acf2018

Using JSON bracket notation

The final way to set structure variables in ColdFusion is to do so using JSON bracket notation when you’re setting the variable. Consider the following code examples:

Tag based:

	<cfset person = { first_name: "Bart }>

Script based:

	person = { first_name: "Bart" };

Try it yourself:
https://trycf.com/gist/06ef01cc58d5f182210aff1d855d6583/acf2018

All of the examples above will create a structure called person, then populate that structure with a key called “first_name” and set to a value of “Bart”, and will look like this:

You could also use JSON bracket notation to create and populate multiple keys within the structure all at once!

person = {
	first_name: "Bart",
	last_name: "Gooch",
	birth_date: createDateTime(1980,3,1,10,30,0),
	gender: "Male",
	hair_color: "blonde",
	eye_color: "blue",
	height: 186,
	height_units: "cm",
	weight: 100,
	weight_units: "kg",
	nationality: "Canadian"
};

Try it yourself:
https://trycf.com/gist/b21d4a5691cd9d47765dcbcb35abf839/acf2018

Questions and Answers

But what if I wanted the case of the keys I create to be preserved?

You may have noticed that despite the example setting the key as “first_name” it appears in the results as “FIRST_NAME”. This is because Adobe ColdFusion, by default converts all the key names to UPPERCASE.

Not to worry! There are three ways I’m aware of to preserve structure key case when creating structures.

Use a scalpel: use JSON bracket notation and put quotes around your key assignments

Consider the following script based, JSON bracket notation code example:

person = {
	"first_name": "Bart",
	"last_name": "Gooch"
};

Try it yourself:
https://trycf.com/gist/67acd2daa0a60a9a47ff1a75f2e68916/acf2018

By wrapping the key assignments in quotes, ColdFusion will explicitly preserve the case of those keys. This approach also works with bracket notation as shown here:

	person = structNew();
	person["first_name"] = "Bart";
	person["last_name"] = "Gooch";

Try it yourself:
https://trycf.com/gist/d6461ed6d6d1adc13a1d8b6691b53a36/acf2018

Use the ColdFusion 2021 approach

ColdFusion 2021 introduced a new approach to case sensitive structures by using a dollar-sign token in the variable declaration. Consider the following code example:

	person = $ { first_name: "Bart" };

The use of the dollar-sign prior to the declaration of the structure results in a case-sensitive structure and the results will look like this:

Note: this requires your server to be running the latest version (as of the time of this writing) of ColdFusion 2021. Also note that the dump itself recognizes this structure as a case-sensitive structure.

Nuke the city: Set the preference in the ColdFusion Administrator

In the Server Settings of the ColdFusion Administrator, there is a setting called “Preserve case for Struct keys for Serialization” that will make all of your structures key cases maintain the values they are set.

But what if I wanted the order of the keys I create to be preserved?

You may have also noticed that when I assigned a value to multiple keys, they didn’t appear in the order they were added to the structure. By default, keys appear in a structure alphabetically rather than the order they were created. Creating a structure, then adding keys for c, a, and b will result in the keys being displayed in a, b, c order when dumped.

Say, for example that you are sending data to an API that looks for key structures to be provided in a particular order. This is possible as well with the creation of ordered structures. An ordered structure is just that; a structure whose order of insertion is preserved.

When using the structNew() function, you pass an attribute of “ordered” into the structure to create an ordered structure. Consider the following code examples:

Tag based:

	<cfset person = structNew("ordered")>
	<cfset person.first_name = "Bart">
	<cfset person.last_name = "Gooch">
	<cfset person.birth_date = createDateTime(1980,3,1,10,30,0)>

Script based:

	person = structNew("ordered");
	person.first_name = "Bart";
	person.last_name = "Gooch";
	person.birth_date = createDateTime(1980,3,1,10,30,0);

When creating a structure using JSON bracket notation, the syntax is a little different. In this manner, you create an ordered structure by opening and closing the structure with braces [, and ], instead of brackets {, and }. Consider the following code examples:

Tag based:

	<cfset person = [
		first_name = "Bart",
		last_name = "Gooch",
		birth_date = createDateTime(1980,3,1,10,30,0)
	]>

Script based:

	person = [
		first_name = "Bart",
		last_name = "Gooch",
		birth_date = createDateTime(1980,3,1,10,30,0)
	];

Conclusion

In this post, we discussed what structures are, and how to declare a variable as a structure in ColdFusion. We discussed case sensitive and ordered structures, and you now are armed with examples of each. You’re ready to go forth and use structures to their full potential in your applications!

Who the hell is Bart Gooch?

Funny story. A TV station in Pittsburgh decided to play an April Fool’s joke one year by airing a John Wayne film festival. Except; in all the credits, they blacked out the name John Wayne and replaced it with Bart Gooch.

The prank backfired when people were furiously calling into the station to ask why they would disrespect and desecrate the memory of John Wayne by replacing him with Bart Gooch. Lesson learned. You don’t !@#$% with the Duke.

More ways to learn ColdFusion

For more information on learning ColdFusion, https://www.learncfinaweek.com is an excellent information source that covers many of the basic concepts of ColdFusion development.

http://trycf.com and http://cffiddle.org are both websites that allow you to execute ColdFusion code without having to run an instance of ColdFusion.

CommandBox from Ortus Solutions is an excellent, free way to spin up and execute ColdFusion code locally.

Happy coding!

0 Comments
Add Comment