Author Archives: Misty Spears

ColdFusion Error Handling and Debugging

Debugging and Error HandlingNo matter how good you think you are as a developer, there will most likely be times when an exception happens in your application. Exceptions in ColdFusion will typically display a technical and confusing error message to your user. While these error messages may be great for developers to troubleshoot the problem, to a user they are often left wondering what went wrong.

As a developer, your job is to catch these exceptions and of course correct them, but it is also your job to make sure that your user isn’t presented with a scary technical error message or even worse, a message that could possibly give critical details about the code behind your application. Using ColdFusion, we can find a much more user friendly way of displaying an error message to the user and still receive all of the information we need to correct the issue.

Catching Errors with CFTRY and CFCATCH

By using the <cftry> and <cfcatch> tags we are going to catch errors and handle them appropriately before the user sees them. Instead of letting the user experience a messy glitch in the application we are going to display a nice user friendly screen letting them know an exception occurred and that we are doing our best to correct the issue. At no point will they ever see an actual error message produced by the ColdFusion error system.

The first thing you will need to is identify where in your application you have potential for error. You obviously wouldn’t need to catch any errors within a block of text, but you might want to watch out for areas where you are connecting to a data source or doing complex math processing. Complicated processing code blocks and database connections are two of my more standard types of code to use a <cftry> with. Let’s take a look at a snippet of code that will grab the ID and Name of a user based on the username that they entered on a previous form.

<cftry>    
      <cfquery name="GetUserInfo">
      SELECT ID, Name
      FROM userAccounts
      WHERE Username = '#form.username#'
      </cfquery>
			
      <cfcatch type="any">
          <cfmail to="howtocoldfusion@gmail.com" from="howtocoldfusion@gmail.com" subject="An Error Has Occurred" type="html">
          Error Message: #cfcatch.message#<br>
          Error Detail: #cfcatch.detail#<br>
          Error Location: #GetBaseTemplatePath()#<br>
          </cfmail>
          
          <p>We're sorry, an error has occurred and our developers have been notified.</p>
      </cfcatch>
</cftry>

In the above example, I’ve chosen to check and catch any errors that happen within the <cfquery> call to my database. I’ve wrapped the entire block inside of a <cftry> and </cftry> tag set. After the query is attempted to be called, if anything happens that would cause an exception it will run whatever is located in the <cfcatch> tag.

I have decided to do two things with this error handling. To be sure I am notified of the error, I will first send an email to myself using the <cfmail> tag. I’ve included details that I need to know to be able to find and correct the error that the user received. For example, I am collecting the ColdFusion error message that is generated, the detail of the error and the actual path to the file that the error occurred on.

The second thing I am doing is displaying a nice message to the user instead of the error message. This means you can keep your application looking clean with a standard header and footer, and a nicely formatted message that will fit nicely in the center of your page, or however you wish to design it.

You will notice I currently have the <cfcatch> tag set to catch the error types of “any”. That means, no matter what goes wrong, it will catch it and process the error as I have defined in the <cfcatch> tag. You may have instances where you want to handle errors differently based on the type of error it is. With our example containing only a database call, it will most likely be a “database” type of error, for example if the data source can’t connect to the database. But we are also looking for a form variable called username. If you were to run this code on your ColdFusion server and go directly to this page instead of submitting a form, you would produce an “expression” error as it would be missing the form variable.

This time let’s set up some error handling that still sends us an email if it’s a database error, but if it’s only missing the form variable, we can just send them back to the login page.

<cftry>

    <cfquery name="GetUserInfo">
    SELECT ID, Name
    FROM userAccounts
    WHERE Username = '#form.username#'
    </cfquery>

    <cfcatch type="expression">
    <!--- Missing the form element --->
    <cflocation url="login.cfm">
    </cfcatch>

    <cfcatch type="database">
        <cfmail to="howtocoldfusion@gmail.com" from="howtocoldfusion@gmail.com" subject="A database Error Has Occurred" type="html">
        Error Message: #cfcatch.message#<br>
        Error Detail: #cfcatch.detail#<br>
        Error Location: #GetBaseTemplatePath()#<br>
        Error Time: #timeformat(Now(), 'hh:mm:ss')#<br>
        </cfmail>
        <p>We're sorry, an error has occurred and our developers have been notified.</p>
</cfcatch>

</cftry>

In this example, we’ve used two new error types: expression and database. In the expression error catch, I’ve set it do a <cflocation> to direct the user immediately to the login.cfm page. A <cflocation> is simply a basic redirect that can send the user to any page you specify in the url variable.

If we get a database error, such as a connection issue, it will use the code block within the <cfcatch> using the type of database.

If you are wanting to test for other possible errors, ColdFusion makes the following error types available to test for:

  • Any
  • Application
  • Database
  • Expression
  • Lock
  • MissingInclude
  • Object
  • SearchEngine
  • Security
  • Template

Debugging Tool: CGI Variables

One of the most useful tools within ColdFusion that will help you to debug your application is the built in CGI variable structure. CGI variables can let you know many important things about your application such as the referring url, the server name, IP address, script file names and much more.

For example, if you wanted to capture the browser that the user is using to browse your application you could output the CGI variable for HTTP_USER_AGENT as shown:

#CGI.HTTP_USER_AGENT#

On my own system this would return the following value:

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36

There is a large number of CGI variables that are available to you but don’t worry, I don’t expect you to memorize them all. You can easily output all of the CGI variables available to you on your own server and view what the possible value of those variables are by dumping the entire structure using the <cfdump> tag.

Debugging Tool: CFDUMP

The <cfdump> tag is used to created a grid like display of the contents of any variable that you pass it. This is especially useful as you are debugging your ColdFusion code and need to quickly see what is happening in your errors.

As a developer, you will pass to it variables for queries, CGI variables as mentioned above or just simply variables passed from a form. To use the <cfdump> tag you will simply pass in the value of the variable you want to process through the parameter called “var” as shown below.

<cfdump var=”#cgi#”>

If you were to run the above code, you would see a grid structure of all of the available CGI variables as well as the current value for each variable as it processes the user viewing it.

Along with sending through CGI variables and simple variables, you can also dump the contents of a complex query variable. Dumping the results of a query is as simple as changing out the variable name to the name of your query.

<cfquery name="GetCourses" datasource="MytestDB">
select * from courses
</cfquery>
<cfdump var=”GetCourses”>

This would result in a nested grid structure that would output the results of the entire recordset from the courses table noted in our query.


Basic ColdFusion Database Interaction

Now that we have successfully set up a data source that ColdFusion can connect to, we can perform queries to access data located within the database. To perform these queries we are going to use the <cfquery> tag.

If you have worked with any other server side technologies you may know that most of them require several lines of code. For example, in ASP you would have a line of code to perform each of the following:

  • Declare the variable that will hold the connection object, connection string and SQL statement
  • Create an ADO connection object
  • Declare the recordset variable
  • Define the connection string, specify the database driver and location
  • Define the SQL statement
  • Open the connection to the database and execute the SQL statement
  • Loop through the recordset and output the information
  • Close the object

In ColdFusion, everything is done under the hood for you. You do not need to declare any connection objects, strings or recordsets. Instead, you simply wrap your SQL statement inside a <cfquery> tag that you will provide a name value for and a data source (that you created previously).

<cfquery name="GetCourses" datasource="DBTest">
    SELECT courseid, coursename
	FROM CourseList
</cfquery>

As you can see, this is a much less complicated way of accessing a database and doesn’t require you to remember the many steps required in other languages.

What about authentication?

When we setup our original data source you may have noticed that we provided a username and password in the initial values. By providing that information, it will always be available to any connection to that data source without specifically stating the username and password in the actual query. However, if you aren’t able to include those details in the data source setup, but still need to provide them to be able to connect, you can set their values in the <cfquery> tag as shown:

<cfquery name="GetCourses" datasource="DBTest" username="myusername" password="mypassword">
    SELECT courseid, coursename
	FROM CourseList
</cfquery>

Filtering Data

In the above example, we have selected all the data from the table without any filter or criteria to be processed. If we want to retrieve data that meets a specific criteria, we would use a standard SQL WHERE clause to pass a certain condition to the recordset being returned. Using ColdFusion, we can take advantage of filters on a dynamic level and filter recordsets based on a user specified selection.

For example, if instead of returning all the course names for all courses, let’s only return the course name for the record that has a courseid of “2”.

<cfquery name="GetCourses" datasource="DBTest">
    SELECT courseid, coursename
	FROM CourseList
	WHERE courseid = 2
</cfquery>

Now for the dynamic aspect. This time let’s pass the value of courseid as a variable from a previous page. This time we would pass the value as a variable to the query.

<cfquery name="GetCourses" datasource="DBTest">
    SELECT courseid, coursename
	FROM CourseList
	WHERE courseid = #courseid#
</cfquery>

As you can see by the above SQL statement we have now created a filter for the recordset that can be changed depending on the value that you pass to it.

Displaying Your Data

Now that we have sent the query to our database and it has sent us back a recordset, we need a way to display that data to the user. ColdFusion makes this incredibly easy with the <cfoutput> tag. You should remember this tag from the previous section on variables, only this time we will be passing an extra parameter to it to display our data. In the query we showed above, we passed a “name” to the cfquery tag and called it “GetCourses”. We are going to pass this same name to the <cfoutput> tag through the query attribute.

<cfoutput query="GetCourses">
#courseid# - #coursename#<br />
</cfoutput>

As you can see from the code above, we are using the <cfoutput> tag to loop through our returned recordset and are using the “#” sign around each column name just as we did when we were displaying the values of variables.

Using a Query Loop

There may be instances where using the <cfoutput> tag isn’t practical to use to output the recordset to the user. For example, if you are already using the <cfoutput> tag to do other processing, you can’t put another <cfoutput> tag within it. In these cases, you can still output results within a <cfoutput> tag by using the <cfloop> tag.

The best part about using the <cfloop> tag for queries is that the syntax isn’t all that different from the <cfoutput> tag.

<cfloop query="GetCourses">
#courseid# - #coursename#<br />
</cfloop>

The important thing to remember when using <cfloop> is that because you are using “#” signs around variable names to display to the screen, they must reside inside of a <cfoutput> tag.


How to Create a ColdFusion Data Source – Tutorial!

Data Source ToolTo connect to an existing database through ColdFusion you will first need to set up a data source through the ColdFusion administrator. You can think of a data source as a sort of interpretor between your ColdFusion code and the database you are connecting to. In the example below, I am using ColdFusion 9 administrator settings, however, if you are on earlier or later versions the process is almost identical to setup so you should be able to follow along easily.

1. Log in to your ColdFusion administrator using your administrator password. If you have followed standard installation procedures you can typically find your administrator log in at http://<www.yoursite.com>/CFIDE/administrator/

ColdFusion Administrator Log In Screen

2. In the left navigation panel, expand the “Data & Services” menu and click on “Data Sources”. The next screen should show you a list of all your current data sources you have created as well as an option to “Add New Data Source”.

3. We are going to connect to a SQL database in this example, so enter a data source name and select the Microsoft SQL Server driver from the drop down menu. If you are creating a data source for a different database type, just select the appropriate database driver for your database. When you are finished click the “Add” button.

Add New Data Source

4. The next screen will allow you to specify all of your server specific settings such as the name of the database you wish to connect to, the server address, your username and password as well as some advanced options. If you aren’t sure of these values or you are not hosting the database yourself, you may need to contact your database administrator to obtain this information. You can click the “Show Advanced Settings” as an optional way to specify other parameters for your connection but usually this isn’t required.

Add New Data Source

5. Once you have filled in the all the required fields, click the “Submit” button and ColdFusion will verify the connection and you will be taken back to the original screen that listed all of your current data sources. If all went well and you supplied the correct information on the previous screen, you should see “ok” next to your data source. However, if you have supplied incorrect information or your data source didn’t connect successfully, you may see an error like the one below.

ColdFusion Data Source Error

If you receive no errors, you can now use this data source to query your database through Coldfusion.


Conditional Processing Using CFSWITCH

If you’ve read through my ColdFusion Programming 101: Basic Concepts: Conditional Processing, you should already be pretty familiar with conditional processing and using the CFIF /CFELSE/CFELSEIF tag combinations to process your ColdFusion code in the order you want it to be processed. If you haven’t read it, I highly recommend it to give you a good understanding of conditional processing. But if you need just a quick refresher on what conditional processing is it simply means that the code is read by the application, will react to any conditions it comes across and will behave the appropriate way.

We can process conditional statements by using the now familiar CFIF statement sets, but there is still another way by using the CFSWITCH tag.

<!--- Set the catalog type to show--->
<cfset catalogtype = "Fashion">

<cfswitch expression="#catalogtype#">

    <cfcase value="Furniture">
    Displaying the Furniture Catalog.
    </cfcase>
    
    <cfcase value="Fashion">
    Displaying the Fashion Catalog.
    </cfcase>
    
    <cfcase value="Children">
    Displaying the Children's Catalog.
    </cfcase>
    
    <cfdefaultcase>
    Displaying all catalogs.
    </cfdefaultcase>
    
</cfswitch>

Taking a look at this code, we start off with setting a variable called catalogtype equal to the value “Fashion”. This will more than likely be dynamic in a finished application but for the purpose of this tutorial, we will just manually set the value so we have something to work.

Next, we start the processing by adding a <cfswitch> tag and the expression which is the value of the variable we just assigned…currently “Fashion”. All we are telling ColdFusion to do at this point is get ready to process some code, based on the value contained in the “expression”.

For each condition we want to check for we are going to use a <cfcase> tag along with the value we want to check. For example, in the first <cfcase> we are simply asking ColdFusion “Is the value ‘Furniture’?” If the answer is yes (or true) it would process that block of code.

<cfcase value="Furniture">
    Displaying the Furniture Catalog.
</cfcase>

We of course know that this block of code would never process in its current state because the value of the expression we are checking is “Fashion” and not “Furniture”. In this case, the <cfwitch> process would skip that particular <cfcase> and move onto the second <cfcase>. The second <cfcase> is checking for the value of “Fashion” and since our expression does return true, it would execute all code within that <cfcase> tag and then exit the entire <cfswitch> processing.

What happens when none of the cases match the expression being sent to it? It could just skip right over the entire block of code and not process anything. However, we have an optional tag <cfdefaultcase> that will execute that block of code if no other cases within the <cfswitch> tag return true.

<cfdefaultcase>
    Displaying all catalogs.
</cfdefaultcase>

The end result of using the <cfswitch> tag is exactly the same as using the <cfif> tag, so why use <cfswitch> over <cfif>? First, <cfswitch> is actually faster to process than using the <cfif> tag. Second, the ColdFusion code for writing <cfswitch> tends to be neater and easier to read by a programmer.

Having said that, the only problem with using <cfswitch> is that you can’t use it in all cases of conditional processing. When using <cfif> you can check for different conditions with each instance of the <cfelseif> tag. For example, I can check if the month is January and if that comes back false it will move onto the next condition to check if the year is 2013. With <cfswitch>, you can only check for one expression and have multiple <cfcase> tags per expression.

Now that you know how to use both CFIF and CFSWITCH to process your application, in the next lesson, we will go over conditional processing using cfscript coding methods.


ColdFusion Code Commenting

Comment Your Code!When you land your first job as a ColdFusion developer, you will most likely be added to a team of developers already in process on a project, or you may be taking the place of someone who is no longer there. With either situation, being able to quickly acclimate yourself to the application you will be developing is important. How do we do that?

It is good programming practice to always leave comments in your ColdFusion code so that others who may need to maintain that code when you aren’t around can easily understand what is going on under the hood. If you’re lucky, the application you will be working on had a good programmer who has done just that. If however, you aren’t that lucky, we can use some basic commenting procedures to go back through and learn the application and document it as you go. These tips will also help you when documenting your own code as well so that nobody ever has to come in behind you and comment your code for you.

There are several methods I use every day to make my code easy to read and understand.

Inline Commenting

You can add your own descriptive comments to your code at any place by simply surrounding the comment with special formatting tags that hide the comment from view. ColdFusion server side commenting will never be visible to the browser, while HTML commenting is client side and always available. See below for examples.

Server Side Commenting

<!--- I am a ColdFusion comment and am processed on the server, so the browser can never see me--->

<cfscript>
    //Single line comment inside a cfscript tag, not visible to the browser
    
    /*
    MULTI
    LINE
    COMMENT
    */
</cfscript>

Client Side Comment
<!-- I am an HTML comment and am visible to browsers via the view source option -->

Descriptive comments using the above coding practices are limitless in size. You can be descriptive as you like, but typically most can be commented in a fairly short and straight forward manner. For example, many times when I am creating a new page within an application I will create a standard comment header to describe what the page I am writing is intended to do.

<!---

Creator: Misty Spears
Date created: 9/9/2013
Last Updated: 9/11/2013
Purpose: This is the action page that the account update form is submitted to. All functions for add, editing and deleting an account is done here.

--->

Within the same page, I have to run a query to check for an active status on an account. To make my code understandable, I am going to leave an inline comment above to let the reader know what I’m doing. You’ll also notice I named the query a very understandable name to make it fairly obvious what the query does.

<!--- Check if this account is active --->
<cfquery name="CheckforActiveStatus">
    Select id, isactive
    from Accounts
    where username = '#username#'
</cfquery>

Variable Naming Practices

You most likely use variables in your code on a daily basis. If you remember, from Basic Concepts: Variables and Data Types, a variable is a method to store data to use later on in your code. Because it is such a common coding practice, you should name your variables in a way that “self comments” and is obvious what the data holds.

For example, take a look at the following code.

<cfset var1 = “January”>

Does the variable name “var1” tell you anything about what the value January is? It certainly doesn’t. There is nothing about that line of code that could tell someone reading your code what the variable is holding, other than actual value. However, by simply renaming it to something a little more useful, you are making it clear what the variable is and no additional comments would even be necessary.

<cfset mybirthmonth = “January”>

Page Naming Conventions

Along the same lines as the variable naming conventions, your page names should also be descriptive as to what they do. This will make it easier for other codes to work in the same folder with 100 pages in it and find the one they are looking for easily. For example, the name “account_update.cfm” is pretty obvious that the function of that page is to update an account.

By following these simple practices now, your fellow coders will appreciate being able to understand your code and enjoy working with you. You may even appreciate it yourself when you come back to edit that page in 6 months and can easily pick that code back up and be able to follow your own comments.

 


What is ColdFusion?

According to the dictionary and Google:

What is ColdFusion?

So…I am going to be teaching you about nuclear fusion. Ya right!

ColdFusionThat may be one definition of ColdFusion but the one we’re interested in is a rapid web application development platform. What does that mean? ColdFusion was designed to make connecting regular HTML pages to databases easy and fast. It certainly accomplished that, but since ColdFusion 2.0 it has become a full-fledged scripting language capable of many other powerful functions for developing web applications.

ColdFusion is easy to learn and can be used to create any number of server-side web applications, quickly and typically with less code than you might see in ASP (Active Server Pages) or PHP. Before I learned ColdFusion I developed primarily in ASP and couldn’t believe how few lines of code I would use in ColdFusion when compared to doing the same task in ASP.

That code I’m talking about is called CFML, ColdFusion Markup language. Because CFML is a tag based language, it is very easy for someone who knows HTML to make the transition to CFML.  But that’s just the starting point!

Since ColdFusion MX was released, the language has evolved to accept a more object oriented scripting syntax, similar to that of Java. If you’ve dealt with any programming language before, including Java, or want to do more advanced things in ColdFusion, you now have access to this more standardized way of coding through the <cfscript> tag. I will be showing examples of both tag based and cfscript syntax in many of the tutorials on How to Program with ColdFusion.

Whichever method of scripting you choose to use, the ColdFusion server will process it server-side and display the output via HTML to the browser. Your users will never see the actual CFML or script in the “view source” option in their browser. They will only see regular HTML syntax.

What Can You Do With ColdFusion?

Anything your heart desires! Well, almost anything. ColdFusion can be used to build dynamic websites and applications that are efficient and easy to maintain. With the scripting capabilities of ColdFusion you can create almost any function a web application could need including:

  • File and directory manipulation to add, edit and delete files and folders
  • Connect to a database to manage data
  • Utilize FTP services through a web interface
  • Create a security infrastructure that will allow for a “member only” area requiring a log in.
  • Send email and even check email from a web interface
  • Create an entire e-commerce system with shopping cart capabilities
  • Customize a user’s interface based on their preferences
  • Schedule tasks to happen on a regular basis
  • Create a message board to engage social interaction
  • Plus tons more!

There really is no limit to what you can create with ColdFusion once you learn the language. So be creative, solve a problem and start coding.


Programming ColdFusion 101 – Basic Concepts: Modular Code

ColdFusion Code ReuseThis is the sixth installment of a 6 part series. All sections will help to introduce you to some basic programming concepts that will all carry through and help you as you learn ColdFusion. If you are looking for any of the other installments to this series, you can get to them below.

  1. What is Programming?
  2. Proper Syntax
  3. Variables and Data Types
  4. Conditional Processing
  5. Arrays and Structures
  6. Modular Code

Modular Code

One of the things that I love about ColdFusion is that it gives you plenty of tools to keep from reinventing the wheel. Being able to use the same set of code in multiple places, otherwise known as “code reuse” will not only save you time from doing things over again, but will let you make a change to that code in one place but have it affect everywhere you are using it.

This is one of the most useful things you will use in ColdFusion so let’s take a look at how we can take advantage of the four most common ways to reuse code in ColdFusion.

  • Includes
  • Custom Tags
  • CFModule
  • CFC Functions

Includes

An “include” is a ColdFusion file that is included within another ColdFusion file. These include files work as if you were to copy and paste the code directly into a page, but instead of copying and pasting the entire set of code, we are simply going to include via a <cfinclude> tag.

One of the more common uses of an include is to use them to display your header and footer file on a website application. Imagine you had a website with a navigation bar at the top and let’s assume you have 100 pages in your website. What would happen if you had to add a new item to your navigation bar if you had all your code on each of those individual 100 pages? Aside from spending hours trying to make the change to every page, you’d probably be a little frustrated.

But if you were using an include, you could update the navigation bar in one file and because it’s included on all 100 pages, the change you make in the single file will affect every page in the site.

Let’s look at some code to demonstrate. This is a sample welcome page with some very basic HTML to simply display a welcome message and a navigation bar near the top of the page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome Page</title>
</head>

<body>
<div align="center"><a href="home.cfm">Home</a> | <a href="contact.cfm">Contact</a></div>

<p>Hi and welcome to How to Program with ColdFusion.</p>

</body>
</html>

As you can see this is all located in one single page and would require an update to any page that was using this information. But let’s put this into a header and footer file so we can reuse this code efficiently. To get started we want to copy everything from the <body> tag up to use as our header.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome Page</title>
</head>

<body>

Create a new file and call it header.cfm and paste the above code into it. Next we will do the same thing with the code from the ending </body> tag down.

</body>
</html>

What  you are then left with on the original page:

<div align="center"><a href="home.cfm">Home</a> | <a href="contact.cfm">Contact</a></div>

<p>Hi and welcome to How to Program with ColdFusion.</p>

Next we want to include the header and footer file back into the original document. We do this using the <cfinclude> file along with a parameter called “template”.

<cfinclude template="header.cfm">
<div align="center"><a href="home.cfm">Home</a> | <a href="contact.cfm">Contact</a></div>

<p>Hi and welcome to How to Program with ColdFusion.</p>

<cfinclude template="footer.cfm">

If you were to load that page now, you would find that the page looks exactly the same, only now if you want to add in a new navigation item, you would add it to the header file and it will change that code on every page you use that file in.

Custom Tags

A custom tag is another really powerful way to reuse your code. Most developers use custom tags to create code functions that will process something to be displayed on your page like special formatting or page navigation. To give you just a basic understanding of the concept, however, we are going to use the header example above to create a custom tag.

A custom tag starts off like any other ColdFusion page, just a blank page named with a .cfm extension. In this example, we have a page called header.cfm. Your custom tag name is always going to be the name of the file minus the extension. So in this case our custom tag is called “header”. Custom tags should be placed in either the same directory as the calling page or in the \CustomTags directory located in the ColdFusion installation root.

To call a custom tag you call it using special syntax starting with “<cf_”. This let’s ColdFusion know that you aren’t trying to use any of its ColdFusion tags and should instead look for a file with this particular name. In this case we are going to use <cf_header>. As you can below we have replaced the <cfinclude> of the header and instead are now calling it as a custom tag.

<cf_header>

<div align="center"><a href="home.cfm">Home</a> | <a href="contact.cfm">Contact</a></div>

<p>Hi and welcome to How to Program with ColdFusion.</p>

</body>
</html>

There are more advanced things you can do with a custom tag like passing it parameters that the custom tag will then process and I will show you how to do that in later tutorials. But this example, should have given you a good understanding of how we can use custom tags in our daily programming activities.

CFModule

CFModule is very similar to a custom tag, except that you aren’t required to place your custom tag in the customtags folder. This is useful for example, when using a shared hosting environment and you don’t have access to the custom tag directory or if you just want to easily manage your custom tags on your main website directory. You can call the custom tag using the <cfmodule> tag and passing in any name/value pairs as shown.

<cfmodule template=”header.cfm”>

You can pass variables to the custom tag the same way you would with a standard custom tag call as well.

<cfmodule template="header.cfm" title="My Home Page" BackgroundColor="white">

CFC Functions

The last type of code reuse we will talk about is a CFC or ColdFusion Component. With my first two examples of using an include and a custom tag, we were sending data back to the browser. CFC’s, however, typically are used for behind the scenes type functions. This would include things like calculations, database queries and other processing or business rule types of tasks.

The nice thing about CFC’s is that they are plain text files with a .cfc extension and do not require compilation like other programming languages.

A CFC will contain several required parts to it. First, the entire set of code must be wrapped inside of a <cfcomponent> tag. Inside the <cfcomponent> tag there can be one or more <cffunction> tags.  The <cffunction>’s are the methods within the component that you are going to call. Sound confusing? Well, let’s break down the code for you so you can see exactly how it looks.

<cfcomponent>
  <cffunction name="GetCatalog" returntype="query">
      <cfargument name="UserID" required="true">
      
      <cfquery name="qCatalog">
          SELECT CatalogName, CatalogID  
          FROM Catalogs
          WHERE UserID = #arguments.UserID#
      </cfquery>
      <cfreturn qCatalog />
  </cffunction>
</cfcomponent>

This is a basic example of a CFC making a simple call to a database and returning a record set. It starts off with the required component tag. Inside the component tag I have one single <cffunction> with a method I called “GetCatalog”. Inside the function, I am requiring that a variable called UserID be passed so that I can use it to pull the correct catalog for that user.

After I run the query passing in the UserID, I will get back a result set from the query called qCatalog. It is that value that I will pass back to the calling page. I return it back by with the syntax <cfreturn qCatalog />.

Now that we have this CFC how do we go about using it?

You can call a CFC from within the same page the CFC is located in. To do this you would simply reference the component by name in the “component” variable in the tag. However, I like to store my CFC’s in a separate folder called “components”. So in this example, I would save this set of code as CatalogObj.cfc in the components folder I have already created on my server and reference the path with dot notation as “components.CatalogObj” from my root directory. To call a CFC we will be using the <cfinvoke> tag along with the <cfinvokeargument> tag to pass the UserID variable I require.

<cfinvoke component="components.CatalogObj" method="GetCatalog" returnvariable="menuReturn">
<cfinvokeargument name="UserID" value="#userid#">
</cfinvoke>

As you can see by the code above, the code I have to keep on the calling page is minimal but I can return a large set of results back to it via the CFC page. And because I have stored this set of code as a separate object within the website I can reuse the code many times over by using the <cfinvoke> tag anywhere else within the application.

This last lesson in our 6 part series is probably the most useful lesson but can also be the most confusing because it introduces several new ColdFusion tags and code snippets. But don’t panic. We are only introducing them as concepts to you in this tutorial and will go over the actual code in much more detail in later tutorials. After a short time, these will become second nature to you as you use them in your daily programming activities.

I hope you have enjoyed this tutorial and I invite you to browser through our other introduction level tutorials and learn more about the ColdFusion language here at How to Program with ColdFusion. Good luck!


Programming ColdFusion 101 – Basic Concepts: Arrays and Structures

ColdFusion Arrays and StructuresThis is the fifth installment of a 6 part series. All sections will help to introduce you to some basic programming concepts that will all carry through and help you as you learn ColdFusion. If you are looking for any of the other installments to this series, you can get to them below.

  1. What is Programming?
  2. Proper Syntax
  3. Variables and Data Types
  4. Conditional Processing
  5. Arrays and Structures
  6. Modular Code

Arrays and Structures

Now the fun begins! Arrays and structures are complex variables that store data in a way that you can easily and efficiently use them. When I was first learning ColdFusion I will admit, I had a hard time wrapping my head around the concept of exactly what an array/structure was and I was very confused on how to write the code for each. I had never worked with data outside of a database so this was a pretty foreign concept to me. Thankfully, you won’t have to struggle like I did because I’m about to lay it out in a way I wish someone had done for me all those years ago.

Structures

Let’s start with structures because I think they are a bit easier to understand and to code. If you remember when we first talked about variables, I showed you how easily we could store data in it such as our “thishat” variable and the value “red”.  But what if I wanted to collect more details about your hat such as the size, material and brand. Without a structure, I could store them all individually like so:

<cfset hatcolor = "red">
<cfset hatsize = "Large">
<cfset material = "Wool">
<cfset brand = "No Fear">

That works, sure, but it’s a lot of management to keep up with that and you can’t do much with it as far as data manipulation. Instead, I will create a new structure for “thishat”. This doesn’t do anything other than just say “hey, I’m about to make a structure so make a variable to hold it”.

<cfset thishat = structnew()>

Next, I’ll add the separate properties of the structure. This basically tells the variable “thishat” that I’m adding some properties to it.

<cfset thishat.hatcolor = "red">
<cfset thishat.hatsize = "Large">
<cfset thishat.material = "Wool">
<cfset thishat.brand = "No Fear">

Now anytime I want to reference an item in the structure I can simply output like I would any other variable. For example, if I wanted to display the material property:

<cfoutput>#thishat.material#</cfoutput>

You might be wondering why not just set up individual variables like I did in the first example. Well, there are things you can do with a structure that you can’t do with just a simple variable. For example, because a structure is more like a table or recordset, you can sort it. You can also return a list of the properties, known as keys, that exist in the structure. You can also search and clear structures as well as determine if a variable is in fact a structure.

Structures are very versatile and are a great method for storing related together into a single complex variable.

Arrays

Now that you’ve learned about structures it’s time to move onto a more advanced data control called arrays. Arrays are a lot like structure in that they store data in a single variable. However, there are two major differences. First, while a structure simply uses the structure name and property dot delimited syntax (thishat.material), an array is referenced numerically. Second, structures are single dimensional and arrays can be multidimensional. Although you can create a single dimensional array as well.

What the heck does that mean? Let’s break it down so it’s easy to understand. Structures can hold all those details we wanted to store in a single dimensional array, but that means we can only store it for one hat. But if they were in an array, which is multidimensional, we could store those same details, but instead of just 1 hat, we could store it for 10 or 20 or 30 hats and simply reference them by number.

Let’s look at some code examples and see if we can put it together. We will start with a single dimensional array.

<cfset hatcolor=ArrayNew(1)>

Above, I’ve simply created the variable and made a one dimensional array. Next I can add items to the array.

<cfset ArrayAppend(hatcolor, "Red")>
<cfset ArrayAppend(hatcolor, "Blue")>
<cfset ArrayAppend(hatcolor, "Green")>

Of course, ColdFusion is very flexible in it’s coding syntax and there is actually an even shorter way of writing the above:

<cfset hatcolor = ["Red", "Blue", "Green"]>

In the above, I’ve created the array and added values all in one step. Time saver! In both examples, I’ve created an array that visually looks like this:

arrayvisual

And if I wanted to display on screen the third element in the list, which is Green, I would reference the array and the item in the array that corresponds to that number like so:

<cfoutput>#hatcolor[3]#</cfoutput>

Green

Now, this example could just as easily be done using a regular single structure so let’s instead move onto a 2 dimensional array so you can really see how arrays can start look even more like a table. In this example, I want to store several values for multiple hats. Something that would look like this:

arrayvisual2

I’m going to use the shorter method to create the array and just use the following syntax:

<cfset Allhats = [["Red", "Blue", "Green"],["Large", "Small", "Medium"],["Wool", "Cotton", "Leather"]]>

If I were to display this array on your screen, it would look like this:

arrayvisual3

What’s missing that you had in structures? Variable names! Arrays do not reference values by using their name. Taking a look at the ColdFusion dump using <cfdump> that shows us nothing other than values. We don’t know what these value represent. This is part of the problem and why I personally will choose a structure over an array if it’s a single dimensional array.

Now that you’ve read the basics of structures and arrays and understand the concept behind them (don’t worry, the code doesn’t matter at this point) I can now blow your mind and tell you it can get even more confusing (thankfully that’s not part of this tutorial)! Remember when I said structures are one dimensional? Well, there are more advanced techniques we will talk about elsewhere on this blog where we can actually store a structure inside of a structure. But if you’ve made it this far you’ve definitely got the basics down. So let’s cover our last section of this series, Modular Code.


Programming ColdFusion 101 – Basic Concepts: Conditional Processing

Conditional Processing with ColdFusionThis is the fourth installment of a 6 part series. All sections will help to introduce you to some basic programming concepts that will all carry through and help you as you learn ColdFusion. If you are looking for any of the other installments to this series, you can get to them below.

  1. What is Programming?
  2. Proper Syntax
  3. Variables and Data Types
  4. Conditional Processing
  5. Arrays and Structures
  6. Modular Code

Conditional Processing

You have probably dealt with conditional processing on a pretty regular basis but in real life we simply call it making a decision. As an example, if you are going to be home from work on time, then you might decide to make dinner yourself, if you are running late, then you might decide to save time by ordering in.

In the world of programming, conditional processing simply means that as the code is read by the application, it will react to any conditions it comes across and behave the appropriate way. This is the method used to control the flow of any application.

ColdFusion makes conditional processing extremely simple by providing us with the <cfif>/<cfelse>/<cfelseif> tags.

CFIF, CFELSEIF and CFELSEIF

The conditional statement when using any of the tags will always be true or false, so it is as simple as using the tags to surround an event you want to happen if it’s true.

Let’s look at some source code to better explain it. The sample code below shows some conditional processing of code based on our red hat choice previously mentioned. Remember I said I could save your color entry into a variable called “thishat”? Well, here we have some conditional processing that is checking if the hat is red and if it is then show the red hat products.

<cfif thishat is "Red">
    <!--- Show the red hat products--->
</cfif>

If the condition isn’t true, for example if you entered “blue”, it will simply skip over that section of code completely.

What if I wanted to check for other colors and show products based on those choices? There may also be instances where someone entered a color that I hadn’t accounted for. We can add in additional checks for those options as well.

<cfif thishat is "Red">
    <!--- Show the red hat products --->
<cfelseif thishat is "Blue">
    <!--- Show the blue hat products --->
<cfelseif thishat is "Green">
    <!--- Show the green hat products --->
<cfelse>
    <!--- Show all products --->
</cfif>

As you can see in the above code, using the <cfelseif> tag lets you check for additional conditions within the same block of code and <cfelse> will be the final remaining option if none of the others are true. Just keep in mind that code is read from left to right and top to bottom. This means that as soon as the condition is met and becomes true, the conditional processing stops, runs that block of code and then picks back up after the ending </cfif> tag.

One final note about those comments I used placeholders within the <cfif> blocks. In standard HTML code, you may have seen double dashes like <!– comment –>. This hides whatever is between those dashes but still makes it available behind the scenes if you were to look at the source code. Since ColdFusion is a server side language, we can use triple dashes like this <!— comment —> and the comment will forever stay on the server side and never be shown on the client side even when viewing the HTML source. This is a great way to comment your code.

ColdFusion Operators

When performing conditional processing, ColdFusion gives us lots of options and operators to use to check for things. For example, I can check if variables equal a certain value, I can determine if a variable exists, I can check if a number is greater than another number and many other operations.

You will notice ColdFusion operators for conditional processing are fairly obvious to understand and are mainly abbreviations for an English word. This is because since ColdFusion is a tag based language and uses the “<” and “>” which makes it impossible to use those same symbols to designate greater than or less than. Instead of using symbols we are going to be using letters.

  • GT – Checks if the value on the left is greater than the value on the right
  • GTE – Same as above but checks if it is greater than OR equal to
  • LT – Checks if the value on the left is less than the value on the right
  • LTE – Same as above but checks if it is less than OR equal to
  • IS/EQ – Both check if a value is equal to the other

In the next section we will be covering arrays and structures, so when you’re ready continue onto the next section.


Programming ColdFusion 101 – Basic Concepts: Variables and Data Types

Variables and Data TypesThis is the third installment of a 6 part series. All sections will help to introduce you to some basic programming concepts that will all carry through and help you as you learn ColdFusion. If you are looking for any of the other installments to this series, you can get to them below.

  1. What is Programming?
  2. Proper Syntax
  3. Variables and Data Types
  4. Conditional Processing
  5. Arrays and Structures
  6. Modular Code

Variables and Data Types

If you’ve never heard of a variable before, get ready to have them drilled into your brain! But what exactly is a variable? A variable is simply a way to store a value to use later on in your code. They are a major part of any programming language and are used in a variety of ways. For example, let’s go back to my famous red hat.

Imagine you came to my website and when you first entered, there was a form asking you what color your hat was. You obviously love the color red like I do, so that’s what you entered.

Variables and Data Types

Upon clicking submit, I could take the value that you typed into that textbox, that I just so happened to name “thishat” and save that value for later. My variable called “thishat” now has a value of “Red”. Later on, you might come to a section of my website where I display awesome hats based on your color preference. To find out what color you prefer, I could grab the value of the variable called “thishat” that I created when you first entered and use that to display only hats of your color choice.

What About Data Types?

Every variable you use in ColdFusion can hold a different type of data. These data types could be numbers, plain text strings, date/time values, Boolean values or one of many other data types.

Full List of Data Types

  • Integers – Whole numbers without anything to the right of the decimal
  • Real Numbers – Numbers that might include a decimal value
  • Strings – Sequence of letters or special characters enclosed by quotes
  • Booleans – A true or false value that can be expressed with True/False or 1/0 values
  • Date/Time – Can be date, time or date/time combination values
  • List – A delimiter separated list of values
  • Array – Complex table like structure with rows and columns
  • Structures – A series of name/value pairs
  • Queries – The result set returned from a database
  • Binary – Raw data
  • Object – Holds advanced data from items such as COM or Java objects

Well, that’s a lot of boring and technical chatter isn’t it? If you think so too, there is good news! In other programming languages, you have to tell your code what kind of data you are sending to it. In other words, if you want to use a variable called “thishat” and have the value as “red”, you would need to tell your code (declare) that you are using a “string” type variable.

Now that you understand what a data type is, I can tell you that for the most part, you won’t worry about telling ColdFusion about the data types too much. With ColdFusion, variables are typeless. This means you simply set the value and you are free to use it how you wish. ColdFusion is designed to evaluate your variables and will automatically determine how it should be used. Of course if you try to use the variable in a way that doesn’t make sense, such as trying to do math on a string, ColdFusion will tell you it doesn’t understand by throwing an error.

Where data types do come into play is when you are checking for a certain data type in ColdFusion. For example, let’s assume you have created a form on your website and one of the fields you have your user fill out is a field called “yearborn”. You’ve also added a column in your database called yearborn with a data type of integer. If your user filled out the value as “nineteen eighty” instead of 1980, how do you think your database would react to that? Using ColdFusion you can check your data types before doing any processing in a database and handle it with finesse.

Variable Output

Once you have a variable and a value stored inside it, you may want to output the value of the variable onto the screen. To do that, we simply need to surround the variable name with pound symbols and place that within a <cfoutput></cfoutput> tag set. Pound symbols are what ColdFusion uses to tell the application “hey I’m a piece of dynamic content, be sure to process me”. So if I wanted to show you the value of “thishat” variable onto the screen:

My hat is: <cfoutput>#thishat#</cfoutput>

The result on screen would simply be:

My hat is: Red

In the next section we will talk about how we can process a page based on certain conditions, so when you’re ready let’s move on.