21 Time-Saving Snippets for Any ColdFusion Developer

ColdFusion SnippetsWeb developers often do repetitive tasks, some of these tasks can be saved as snippets in IDE’s such as Dreamweaver, Eclipse and Homesite to name a few. Here are 21 snippets for ColdFusion developers that will save you time.

Import all of these ColdFusion snippets into your IDE and save some keystrokes and frustration of searching for commonly used chunks of code.

Display

Alternating Row Color - There are several methods to get the same result. I feel this snippet is the most condensed.

1
2
<tr bgcolor="###iif(SCOPE.currentrow MOD 2,DE('efefef'),
DE('ffffff'))#">

Grouped Output - The basic mechanics of using cfoutput to group a result set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<cfquery name="getCustomer" datasource="#APPLICATION.DSN#">
SELECT Fieldname1, Fieldname2
FROM TableName
WHERE FieldName4 = <cfqueryparam value = "#query.ID#"
cfsqltype = "cf_sql_integer">
ORDER BY Fieldname1, Fieldname2
</cfquery>
 
<cfoutput query="getCustomer" group="Fieldname1">
<b>#getCustomer.Fieldname1#</b&gt;
<cfoutput>
#getCustomer.Fieldname2#
</cfoutput>
</cfoutput>

Forms

CFForm, Basic - This is good, basic <cfform> with an input and submit button. I use this as a framework to get me going.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<cfform action="#CGI.SCRIPT_NAME#"
        method="post"
        name="form1">
 
<cfinput type="text"
         name="Field1"
         value=""
         required="yes"
         message="Field1 is required"
         maxlength="255"
         size="30" />
 
<cfinput type="submit"
	    value="Submit" />
 
</cfform>

CFInput, Basic - A <cfinput> with all the common elements. Saves on retyping.

1
2
3
4
5
6
7
<cfinput type="text"
         name="Field1"
         value=""
         required="yes"
         message="Field1 is required"
         maxlength="255"
         size="30" />

CFParam, Basic - Speed up adding <cfparam> to the top of a form processing script.

1
<cfparam name="SCOPE.varName" default="">

Functions

CFC, Basic - Everything you need to get going on component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<cffunction name="getCustomer" access="public" output="false">
 
	<cfargument name="FieldName4" type="numeric" required="yes">
 
     <cfquery name="getCustomer" datasource="#APPLICATION.DSN#">
     SELECT FieldName1, FieldName2, FieldName3
     FROM TableName
     WHERE FieldName4 = <cfqueryparam value = "#query.ID#" 
     cfsqltype = "cf_sql_integer">
     </cfquery>
 
	<cfreturn getCustomer&gt;
 
</cffunction>

CFInvoke CFC - Nice time-saver for coding the invoke statements at the top of pages.

1
2
3
4
<cfinvoke component="componentdirectory.componentname"
 		method="getCustomers">
	<cfinvokeargument name="CustomerID" value="#FORM.ID#">
</cfinvoke&gt;

Queries

DELETE Statement - A simple DELETE statement in MSSQL.

1
2
3
4
5
6
<cfquery name="DELETECustomer" datasource="#APPLICATION.DSN#">
DELETE FROM  TableName
WHERE FieldName4 = <cfqueryparam value = "#query.ID#"
cfsqltype = "cf_sql_integer">
</cfquery>
<!--- ALWAYS remember your WHERE statement! --->

INSERT Statement - A simple INSERT statement in MSSQL with the various types of values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<cfquery name="INSERTCustomer" datasource="#APPLICATION.DSN#">
INSERT INTO TableName
	(
      Fieldname1,
      Fieldname2,
      Fieldname3
      )
VALUES
	(
      '#trim(StringValue)#',
      #NumericValue#,
      #createodbcdate(now())#      <!--- Properly formated date --->
      )
</cfquery>

UPDATE Statement - A simple UPDATE statement in MSSQL with the various types of values and <cfqueryparam> to prevent SQL injections.

1
2
3
4
5
6
7
8
9
<cfquery name="UPDATECustomer" datasource="#APPLICATION.DSN#">
UPDATE TableName SET 
Fieldname1 = '#trim(StringValue)#',
Fieldname2 = #NumericValue#,
Fieldname3 = #createodbcdate(now())#
WHERE FieldName4 = <cfqueryparam value = "#query.ID#"
              cfsqltype = "cf_sql_integer">
</cfquery>
<!--- ALWAYS remember your WHERE statement! --->

UPDATE Statement - A simple SELECT statement in MSSQL with the <cfqueryparam> to prevent SQL injections.

1
2
3
4
5
6
<cfquery name="getCustomer" datasource="#APPLICATION.DSN#">
SELECT Fieldname1, Fieldname2, Fieldname3
FROM TableName
WHERE FieldName4 = <cfqueryparam value = "#query.ID#"
              cfsqltype = "cf_sql_integer">
</cfquery>

Increment count - A condensed version on adding a count to a database field in MSSQL.

1
2
3
4
5
6
7
<cfquery name="UPDATECount" datasource="#APPLICATION.DSN#">
UPDATE TableName SET 
Fieldname2 = [Fieldname2] + 1
WHERE FieldName4 = <cfqueryparam value = "#query.ID#"
			cfsqltype = "cf_sql_integer">
</cfquery>
<!--- ALWAYS remember your WHERE statement! --->

Record ID of Last Row Inserted - I have been using this one for a while and finally got around to making a snippet out of it.

1
2
3
4
5
6
7
8
9
10
<cfquery name="INSERTCustomer" datasource="#APPLICATION.DSN#">
INSERT INTO TableName
	(Fieldname)
VALUES
	('Value');
SELECT LastID = @@identity
</cfquery>
<!--- Don't forget the semicolon at the end of the value list. 
Also, "LastID can be anything and referenced as 
INSERTCustomer.LastID --->

Return Random Number of Records - Slick way to return a specified number of random records from a SQL record set.

1
2
3
4
5
6
7
8
9
<cfquery name="getCustomer" datasource="#APPLICATION.DSN#">
SELECT TOP 5 Fieldname1, Fieldname2, Fieldname3
FROM TableName
WHERE FieldName4 = <cfqueryparam value = "#query.ID#"
		cfsqltype = "cf_sql_integer">
ORDER BY NEWID()
</cfquery>
<!--- TOP and a number determines how many rows are returned
	 NEWID() picks random records --->

Strings

Credit Card Number Mask - This function will return the 16 digit credit card number with all except the last four numbers masked with astericks.

1
2
3
4
5
6
<cfscript>
function maskcardnumber(creditcardnumber){
	return "#repeatstring("*",val(len(creditcardnumber)-4))#
#right(creditcardnumber,4)#";
}
</cfscript>

Dynamic Copyright Year - Tired of doing a find and replace for copyright dates in January. Replace this code with the year and you won’t have to worry about it again.

1
&copy;#dateformat(now(),'yyyy')#

Today’s Date - A quick way to display today’s date dynamically.

1
#dateformat(now(),'mm/dd/yy')#

Utilities

CFMail, Basic - All the required attributes for a <cfmail> to process.

1
2
3
4
5
6
7
8
9
<cfmail from=""
        to=""
        replyto=""
        failto=""               
        subject=""
        type="html"
        >
Message Here       
</cfmail>

Clear SESSION Variables - This will clear out all the SESSION variables. I suggest placing it on a page and call on that page while testing different scenarios while developing.

1
 <cfset StructClear(session)>

Dump All Variables - Dumps all the variables onto the page. When developing, you can pick and choose the ones you want to display. Best bet is to add this snippet into the footer of your application.

1
2
3
4
5
6
7
8
9
<cfdump var="#FORM#" label="Form" expand="no">
<cfdump var="#URL#" label="URL" expand="no">
<cfdump var="#SESSION#" label="Session" expand="no">
 
<cfdump var="#APPLICATION#" label="Application" expand="no">
<cfdump var="#CGI#" label="CGI" expand="no">
<cfdump var="#CLIENT#" label="Client" expand="no">
<cfdump var="#REQUEST#" label="Request" expand="no">
<cfdump var="#SERVER#" label="Server" expand="no">

Export as Excel (.xls) - A simple way to dump content to an Excel spreadsheet. Just place this code where you would like the export to begin, like the before a table tag set.

1
<cfcontent type="application/msexcel">

Instead of cut and pasting all of those snippets into Dreamweaver, you can install Massimo Foti’s Import/Export Extension to easily import the 21 time-saving ColdFusion snippets.


RSS feed | Trackback URI

13 Comments »

Comment by Alan Subscribed to comments via email
2008-01-08 18:14:54

I found one thing that needs to be said for MSSQL 2005 queries when using SELECT LastID = @@identity - its not reliable.

Using scope_identity() function is your best bet.

@@IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table. You could have a situation where there is a trigger that inserts a new record in a Logs Table, for example, when your Stored Procedure or INSERT SQL Statement inserts a record in the Orders Table. If you use @@IDENTITY to retrieve the identity of the new order, you will actually get the identity of the record added into the Log Table and not the Orders Table, which will create a nasty, nasty bug in your data access layer.

To avoid the potential problems associated with someone adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your INSERT SQL Statement or Stored Procedure.” - http://davidhayden.com/blog/dave/archive/2006/01/17/2736.aspx

Comment by Jason Bartholme
2008-01-08 22:08:30

Hello Alan,

Thanks for your comment. Currently, our production server is MS SQL 2000, we are planning on migrating to 2005 shortly. For the sake of reliability, I’m going to change my code to use the scope_identity() function.

 
 
Comment by Steven Snell Subscribed to comments via email
2008-01-08 18:18:03

Nice info Jason, everyone likes to save time!

 
Comment by Raymond Camden
2008-01-08 23:28:31

A few notes. First off - your first queries are missing cfqueryparam. You do use it later, but you need to be consistent and use it -anywhere- you have dynamic data in your query.

Your first function example doesn’t use var scoping. That’s considered _very_ bad practice.

Comment by Jason Bartholme
2008-01-09 00:03:41

Thanks for your comment’s, Ray. I fixed the DELETE statement and the grouped output to utilize the cfqueryparam. Honestly, I didn’t know of var scoping or it’s importance of securing cfcs. I’m going to look into it, revamp my cfcs, and run Mike Schierberl’s varScoper tool that you mentioned in your blog.

 
 
Comment by Adam Fairbanks Subscribed to comments via email
2008-01-09 11:49:24

Jason - great snippets!

Here are a few comments for refinement:

1) Alternate row color

- might want to add the scope to the variable (q.currentrow instead of currentrow)
- if the background is already white (which it often is), you can use a simple instead of #iif(), since iff is generally slower.

bgcolor=”##efefef”>

or with a css class:

class=”row”>

2) Forms

- it might be useful to add a name attribute to the form tag

3) Functions

- I agree with Raymond - use var scoping.

(after the line)

Also, it looks like the value of the variable in the query should be

value=”#arguments.FieldName4#”

rather than

value=”#query.ID#”

4) Delete statement, Update statement, and Increment count

- This is a nit, but the variable name will most likely be #form.ID# (or #url.ID#) instead of #query.ID#

5) Insert statement

- StringValue and NumericValue will probably be form.StringValue and form.NumericValue (or url.StringValue and url.NumericValue)

- #createodbcdate(now())# might more often be #CreateODBCDateTime(Now())# (my capitalization means nothing)

6) Record ID of last row inserted

- another nit.. ‘value’ should be ‘#value#’.. and probably ‘#form.value#’ (or ‘#url.value#’)

7) Cfmail basic

- Technically, from, to, and subject are the only required attributes. =)

- Since emails should generally be smtp authenticated, I suggest adding servername, username, and password (and maybe even cc) as attributes, since they would be commonly used

- And maybe even

servername=”#application.mailservername#” username=”#application.mailusername#” password=”#application.mailpassword#” (or similar variables)

Putting these all into snippets is a great idea!

 
Comment by Adam Fairbanks Subscribed to comments via email
2008-01-09 13:25:17

Jason - great snippets!

Here are a few comments for refinement:

1) Alternate row color

- might want to add the scope to the variable (q.currentrow instead of currentrow)
- if the background is already white (which it often is), you can use a simple instead of #iif(), since iff is generally slower.

bgcolor=”##efefef”>

or with a css class:

class=”row”>

2) Forms

- it might be useful to add a name attribute to the form tag

Comment by Jason Bartholme
2008-01-09 14:38:38

Hello Adam,

Thanks for stopping by. I added “SCOPE” to the alt row color snippet and also a name attribute to the form snip.

Good to know that iif() is slower.

 
 
Comment by Adam Fairbanks Subscribed to comments via email
2008-01-09 15:04:20

Below is the rest of my post…. (Are the posts limited to 500 characters?)

3) Functions

- I agree with Raymond - use var scoping.

(after the line)

Also, it looks like the value of the variable in the query should be

value=”#arguments.FieldName4#”

rather than

value=”#query.ID#”

4) Delete statement, Update statement, and Increment count

- This is a nit, but the variable name will most likely be #form.ID# (or #url.ID#) instead of #query.ID#

 
Comment by Adam Fairbanks Subscribed to comments via email
2008-01-09 15:06:47

5) Insert statement

- StringValue and NumericValue will probably be form.StringValue and form.NumericValue (or url.StringValue and url.NumericValue)

- #createodbcdate(now())# might more often be #CreateODBCDateTime(Now())# (my capitalization means nothing)

6) Record ID of last row inserted

- another nit.. ‘value’ should be ‘#value#’.. and probably ‘#form.value#’ (or ‘#url.value#’)

 
Comment by Adam Fairbanks Subscribed to comments via email
2008-01-09 15:07:49

7) Cfmail basic

- Technically, from, to, and subject are the only required attributes. =)

- Since emails should generally be smtp authenticated, I suggest adding servername, username, and password (and maybe even cc) as attributes, since they would be commonly used

- And maybe even

servername=”#application.mailservername#” username=”#application.mailusername#” password=”#application.mailpassword#” (or similar variables)

Putting these all into snippets is a great idea!

 
Comment by Wen Subscribed to comments via email
2008-03-06 19:30:33

This is related to the Import to excel using . If I want to remove some content prior to exporting to excel, what should I do?

For example, I don’t want to export some radio buttons which are displayed on the top of the table rows for sorting column. I want to skip this sort by row. Thank you!

-Wen

 
Comment by sam
2008-06-20 09:42:48

thanks for taking time to put this together

 
Name (required)
E-mail (required - never shown publicly)
URI
Subscribe to comments via email
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line=""> in your comment.

Trackback responses to this post


Warning: stristr() [function.stristr]: Empty delimiter. in /nfs/c02/h04/mnt/40765/domains/jasonbartholme.com/html/wp-content/plugins/wassup/wassup.php on line 2093