Handy Coldfusion tips and tricks

I’ve got some free time to kill so I’d like to take a few moments to pass on little tricks or things about Coldfusion that I’ve learned along the way.

Working With LIsts

Using ListAppend


<cfset myList = "one,two,three">
<cfset myList = ListAppend(myList,"somevalue")>

as opposed to


<cfset myList = myList & "somevalue,">

============
Taking full advantage of List delimiters
As you might know, Coldfusion can turn ANY string into a list, simply by defining a delimiter. The comma is the standard delimiter and one that most people use. However, you might now know that you can use the pipe character “|” as a delimiter along with the comma to build a flexible string that allows you to use Coldfusion’s powerful List functions. Here’s some code:


<cfset couples = "andy,jaime|matt,aimee|shawn,leslie">
<cfoutput>
	<cfloop index="couple" list="#couples#" delimiters="|">
		couple: #couple#<br>
			<cfloop index="person" list="#couple#" delimiters=",">
				-----person: #person#<br>
			</cfloop>
	</cfloop>
</cfoutput>

What if you wanted to get a count of all of the words in a string. Some people might do some sort of loop over the string and count the number of spaces but that’s a lot of code. Why not do it in one line like so:


<cfset gettysburg = "Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.">
<cfset totalwords = ListLen(gettysburg," ")>

Handy Code Shortcuts

When performing a CFIF statement when working with values that will be either true/false, yes/no, 1/0 etc. you can save a tiny snippet of code each time by stating this:


<cfset amITrue = "yes">
<cfif amITrue>
	print me
</cfif>

instead of this


<cfset amITrue = "yes">
<cfif amITrue IS "yes">
	print me
</cfif>

This one’s not directly Coldfusion related but it does have to do with coding. If you’re like me and handcode everything then finding yourself a good text editor is essential. Just as important is finding a text editor that offers code completion. My text editor, EditPlus (EP), offers user defined code snippets. Type a word and EP completes the rest of the code for you AND in some cases places the cursor where you’d need to start typing next. Here’s an example.

I type “<cfquery” and then a space and EP gives me this (and places my cursor between the two CFQUERY tags.


<cfquery name="" dataSource="#Application.DSN#" dbType="#Application.DBType#" username="#Application.username#" password="#Application.password#">

</cfquery>

I type “INSERT” and a space and EP gives me this:


INSERT INTO table_name (
	var_one,
	var_two)
VALUES (
	'#var_one#',
	'#var_two#')

So you can see that not only does having a text editor with customizable auto complete save time, but it also decreases errors because I’m not having to type those pieces of code each time.

That’s it for right now, more to come later. Feel free to add your own time savers to this post but please make sure to test your code and document how it saves time.

similar to the yes/no trick, i always CFPARAM the form or url variables that i expect to use, defaulting them to an empty string, and then i can test them using the LEN parameter like this –

<cfparam name="form.myfield" default="">
<cfif Len(form.myfield)>
  <!--- there is a value --->
<cfelse>
  <!--- value not submitted --->
</cfif>

andy, this has potential to be a great thread, want me to “sticky” it?

Making it sticky might not be a bad idea. I’ll have to manage it though. Maybe in my first post, I’ll create an index to each tip. Then the user can click to read just that one.

You can minimize the number of files by using self submitting forms…


<cfparam name="myaction" value="form">

<cfif myaction IS "do_form">
 <!--- Insert info into database or something here --->
 <!--- You can use a cflocation when done --->
 <!--- May as well use a cfabort too --->
</cfif>

<form name="#cgi.script_name#" method="post">
 <input type="text" name="test" value="test">
 <input type="hidden" name="myaction" value="do_form">
 <input type="submit" value="Submit">
</form>

CFMLSpecialist…

My personal suggestion for self-submitting forms is to have the form itself in the cfelse portion of the statement. Then at the bottom of the cfif, have a cflocation. That way you don’t have to worry about people hitting refresh and resubmitting the form.

So it would look like this (using some of your code).


<cfparam name="myaction" value="form">

<cfif StructKeyExists(URL,"myaction") AND URL.action IS "do_form">
	<!--- Insert info into database or something here --->
	<!--- You can use a cflocation when done --->
	<!--- May as well use a cfabort too --->
<cfelse>
	<form name="#cgi.script_name#?do=myaction" method="post">
		<input type="text" name="test" value="test">
		<input type="submit" value="Submit">
	</form>
</cfif>

what if you have a form that searches your database, and presents the results under the search form

if you CFLOCATION, where would you go to?

if you show the form only if there was no submission, how do you get back to the search form?

In your post, the url action would not be set to do_form, yet your if statement is checking for that.

In a typical web form that submits to another page, hitting refresh does resubmit the form. You should always have validation to make sure the data doesn’t exist and do something special if it does exist.

My previous example works just like a regular old web form so people who are used to that method don’t have to adjust to something new.

Instead of using the cflocation, just put an output of the database info:


<cfparam name="myaction" value="form">
<cfparam name="searchstring value="">

<form name="#cgi.script_name#" method="post">
  <input type="text" name="searchstring" value="">
  <input type="hidden" name="myaction" value="do_form">
  <input type="submit" value="Submit">
</form>

<cfif myaction IS "do_form">
  <!--- Query database here --->
  <!--- Cfoutput or Cfloop of database info here --->
</cfif>

This way your search box will always show at the top of the page and the results will show under it.

Great thread, Andy - when are you going to starting putting this much effort into your blog :wink: ?

Hah…

My family blog is actually doing pretty well. As soon as I stop adding projects to my own personal list I’ll finish up my professional blog and start posting this sort of thing there.

Give it time grasshopper.

I do enjoy reading the family blog every once and a while, just waiting for some more CF posts, as they’re usually pretty well written. You could always put these little tips & tricks in there, I’ve been trying to add some to mine :slight_smile:

Well www.andyandjaime.com is my family album. www.commadelimited.com is where I’ll have my code, public releases, tips and stuff like that.

Well I’ll have to start popping open CD now too :slight_smile:

I very much prefer this method, as I always test for the name of the button hit. This allows me to have multiple submit buttons on a page and run different routines based on that.

<cfif StructKeyExists(form,"Action-A")>
    You hit A button
    <cfelseif StructKeyExists(form,"Action-B")>
    You hit B button
    </cfif>
    
    <cfform>
    	<input type="submit" value="A" name="Action-A">
    	<input type="submit" value="B" name="Action-B">
    </cfform>

A functional example of this is my crmercado’s admin.
Each ad must be approved. I learned to put the radion button at the top of the page: (x) online ( ) offline [ set status ]. Hit set status and it returns to the view page. Hit the button at the bottom, it takes you to the next page|step. 99% of the time, I use the set status button.

My processing code in this case looks more like this:
<cfif StructKeyExists(form,"Action-A") OR StructKeyExists(form,"Action-B")>
    Form Processing
    <cfif StructKeyExists(form,"Action-A")>
     <cflocation back to view>
     <cfelseif StructKeyExists(form,"Action-B")>
     <cflocation to step 2>
    </cfif>
     </cfif>

Hi, I suggest that you encrypt or pepper your dsn name and password if you are going to store it in application variables and your database doesn’t block unknown IPs.

It is easy to wrestle application variable contents from servers if you really want to.

Structures are my second favorite data type, second only to lists that is. Structures are similar to arrays, but allow you to “name” the indexes, which makes them a perfect choice a wide range of things. Here’s some Structure basics before we get into some of the cooler things.

There are several ways to create a structure.

Explicitly:

<cfset myStructure = StructNew()>

Or implicitly:

<cfset anotherStructure.myVar = "creole rocks">

The above line not only creates a structure named “anotherStructure”, but also creates a variable inside that structure named “myVar” and assigns it the value “creole rocks”.

You can also create a structure from within a cfscript tag:

<cfscript>
	aStruct = StructNew();
</cfscript>

Structures can contain any of Coldfusion’s variables types:

<cfset structOne = StructNew()>
<cfset structOne.myArray = ArrayNew(1)>
<cfset structOne.myArray[3] = "jaime">
<cfset structOne.myFunction = CreateObject("component", "temp")>

The preceding code creates a structure named “structOne” with a 3 index array contained within it. The array could have just as easily been a list, or another structure or even a function assignment, Coldfusion gives you that much power.

Structures are great for containing values that need to be named. Unlike arrays (which have simple numbered elements), structures allow you to name it’s members. How about we create a colors structure? This will contains a “lookup table” of sorts for color names to their corresponding hex values:

<cfset myColors = StructNew()>
<cfset myColors.red = "FF0000">
<cfset myColors["navy blue"] = "0000CC">

<cfset tmpColor = "green">
<cfset myColors[tmpColor] = "006600">

Let’s examine what we did above. The first line creates the structure (we could have just as easily left out this line). The second line creates a variable named “red” in the “myColors” structure and assigns it a value. Now, what’s going on here in the third line? We’re using bracket notation…that’s right, I haven’t shown this one yet. Coldfusion allows you to place a string inside brackets to create a variable. There’s also something special to be said about this particular string…it has a space in it, and it will not throw an error. That’s because structures (and bracket notation) allow for this.

In the last two lines I’m doing something even different. I’m creating a string variable named “tmpColor” and assigning it a value of “green”. Then I’m creating a dynamic variable inside the myColors structure with the value of “green”. Pretty cool eh? I know, I know…what about “real world” application you ask. It’s easy to throw out some examples and forget that you want to know how to use structures in your actual code. Well, here you go.

If we continue using the myColors structure, we can colorize an entire page using just the structure assignments we’ve already made. By calling the color where we want it to appear, the structure will reference the named variable and output it’s value,

<html>
<body>
	<cfoutput>
	<div style="background:###myColors["green"]#">This DIV will have a green background.</div>
	<div style="background:###myColors["red"]#">This DIV will have a red background.</div>
	<div style="background:###myColors["navy blue"]#">This DIV will have a blue background.</div>
	<br><br>
	<span style="color:###myColors["red"]#">This text will be red</span>, <span style="color:###myColors["green"]#">This text green</span>, etc.
	</cfoutput>
</body>
</html>

So let’s all cheer for structures shall we?

A quick extra to Creole’s nice structure summary.

I’m a lazy so’n’so, and like to avoid typing wherever I can. So I wrote the following:


<cfscript>
function struct()

{
    var key = 0;
    var result = structNew();
    
    for (key in Arguments) result[key] = Arguments[key];
    
    return result;
}
</cfscript>

What this gives me is the ability to create a new structure with the following line:

<cfset colour = struct(Red: 30, Green: 80, Blue: 255)>

This replaces the following code:


<cfset colour = structNew()>
<cfset colour.Red = 30>
<cfset colour.Green= 80>
<cfset colour.Blue= 255>

That’s VERY sweet dek. Thanks for sharing!!!

Here’s a CFC that one of my coworkers wrote. It’s actually faster and simpler even than yours:


<cfscript>
	// the function
	function createStruct() {
		return arguments;
	}

	// call it
	myStruct = createStruct(Name='Andy',Address1='123 Lazy Lane',Address2='',City='Nashville',State='TN',Zip='37206',PrimaryPhone='615-555-1212');
</cfscript>

That’s more-or-less identical to my first version, truth be told. Unfortunately, under one of the CF7 versions, it went horribly wrong if a particular argument name was used (might be ‘data’) - I think Macrodobia fixed it with one of the later patches, but these days I play it safe.