Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Creating Variables in CFML

The basis of many CF programming projects

Welcome to CF101, a new column I'll be writing for ColdFusion Developer's Journal. This column is dedicated to all of you beginners out there, to teach you the basics of ColdFusion development. You don't need to have a prior understanding of programming, HTML, or Web development to read this column, although if you do, it's a great way to help reinforce the basics.

For the first column, I thought I'd talk a bit about what variables are and how we can create and use them in ColdFusion. Before we jump into that, I thought you might like to know a little bit about my development experience.

Who is Jeffry Houser?
My experience in the IT world started over seven years ago. I was the "tech guy" at a small advertising firm. I did a bit of everything, but most of the development was in Lotus Notes. I worked with very early versions of the Lotus Domino Web Server. Back then, building Web sites in Domino was like trying to tie your shoes while wearing two pairs of gloves and some mittens. It was possible, just not very easy.

Around 4:59 one Friday evening, I was handed a project with a Monday morning deadline. Another developer had left the company for greener pastures and one of his projects had been left unfinished. The project was being built in ColdFusion with Microsoft Access in the database. Although I had no previous ColdFusion training, I was able to complete the project in 10 hours on a rainy Saturday. I haven't looked backed since.

I left that small advertising firm in 1999 to start DotComIt, a Web consulting company. Since starting DotComIt, I've written three ColdFusion books, including ColdFusion: A Beginner's Guide; spoken at a bunch of user groups; and written a handful of articles. I've dealt with a lot of technologies over the years, but ColdFusion remains my favorite Web development technology because of its simplicity. I've always had a knack for describing the complex in a straightforward way, and that is why the folks at CFDJ thought of me when they decided to create this column. I have also been a musician for over 20 years and own a recording studio. I mention that only because many people find it more interesting than my Web development adventures. Hopefully my life story doesn't stick in your head for too long; let's talk about variables.

Understanding What a Variable Is
Before I explain how to use variables within CFML (CFML is the programming language of ColdFusion and BlueDragon; whereas ColdFusion specifically refers to the Macromedia server product), I want to make sure that you understand what variables are. A variable in programming is very similar to a variable in algebra. It has two parts: a name and a value. You can use the variable's name to refer to the variable's value. In computing, the variable is a place in memory where a value is stored. You can assign a name to the place in memory to reference its value.

You might want to ask why we would want to use a variable instead of just using the value that it points to. That would be a good question; and there are multiple reasons. First, a variable's value can change, but the variable name never does. If we use the variable in 100 spots, then we only have to change it once, not 100 times. This could be a real time-saver when writing code. For instance, if the Webmaster's e-mail address needs to be displayed in various places in a site, storing the address in a variable and then displaying the value of that variable would mean that if the Webmaster's e-mail address changed, the value of the variable would need to be changed only in the one place where it is set, as opposed to having to change every place where the address is used.

A second reason for using variables is that you may not know what the value of the variable is going to be. One of the more common uses of this is when you are accepting input from a user, usually through an HTML form. Variables can be used to verify the user input, insert it into a database, mail it to someone, or perform whatever other processing you need to do.

Creating Variables with <cfset>
You can create variables in ColdFusion using the <cfset> tag. The <cfset> tag takes this form:

<cfset variableName = value>

As with all ColdFusion tags, it starts with the name of the tag, <cfset>. After that you specify the name of the variable that you want to create. Then comes the equal sign, followed by the value you want to give the variable.

ColdFusion has some special conventions that you must follow when chosing a variable name. If you do not follow these rules, ColdFusion will display a nasty error message when you try to execute a template. These are the rules:

  • The first character of a variable name must be a letter, a dollar sign ($), or an underscore. If backwards compatibility is a requirement you should stick with an alpha character (a letter). The underscore and dollar signs work only in ColdFusion MX or BlueDragon.
  • The remaining characters can be made up of any number of letters, numbers, dollar signs, or underscore characters. You are more than welcome to mix upper- and lower-case letters as part of a variable name.
  • Variable names cannot contain a space.
  • Variables cannot include reserved characters or words. This includes punctuation marks (other than underscore and dollar sign) such as the double quotation mark (") and names of tags or built-in functions. The full list of reserved words can be found at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/expressi.htm.
Within the scope of these few rules, you are wide open to name your variables in whatever way you please. I would always recommend that you try to choose descriptive names for your variables. The X and Y you used to name variables in algebra will not be as helpful as values like Username, FirstName, or Password; especially when you have to revisit your code six months after writing it to make some enhancements.

A variable can hold many different types of values. They can take simple values such as integers, real numbers, strings, or Booleans. An integer is a whole number, such as 12 or 205. A real number is a number with a decimal, such as 12.5 or 19.3. Strings are text values such as "This is a cfset example." Strings are always placed inside quotes, while numeric values are not. A Boolean value has one of two possible values, true or false. In CFML, the words "true" and "false" and "yes" and "no" are Boolean values. A number can also be used as a Boolean value - zero is false and all other values are true.

Complex values such as arrays, structures, or ColdFusion Components can also be assigned to variables with the <cfset> tag. We'll reserve the discussion of complex values for a future column. An expression can also be contained in the value portion of the <cfset> tag. ColdFusion will execute the expression and use the result as the value of the variable. We'll reserve an in-depth discussion of ColdFusion expressions for another article. Right now you can refer to the Macromedia documentation to learn more: http://livedocs.macromedia.com/coldfusion/6.1/ htmldocs/cfml_b14.htm#wp1160241.

Creating Some Variables
With an understanding of creating variables, here's some code that will create a few variables using the <cfset> tag:

<cfset FirstName = "Jeffry">
<cfset LastName = "Houser">
<cfset Age = 28>
<cfset State = "California">
<cfset State = "Connecticut">
<cfset State = 28>

The first line creates a variable called FirstName with a string value of Jeffry. The second variable creates a variable called LastName with a string value of Houser. The third creates a variable called Age with an integer value of 28. Then we create a variable called State and give it the value of "California". The next line changes the value of the state variable from "California" to "Connecticut".

The final line of the code segment changes the state variable's value from a string to an integer. This is an example of changing a variable's type - something that's very easy to do in ColdFusion. This is different from the way many other programming languages operate, and is part of the reason why ColdFusion is very easy to work with. You can easily change a value from an integer to a string and back just by placing another <cfset> tag.

Outputting (Displaying) Variables
Now that you've created a bunch of variables, what do you want to do with them? There are an unlimited number of things that you can do with variables, many of which I'll cover in future columns. In this column we'll just show a simple example of outputting a variable. We can do this with the <cfoutput> tag and a ColdFusion expression.

<cfoutput>
#FirstName#<br>
#LastName#<br>
#Age#<br>
#State#<br>
</cfoutput>

Before going too much further, I want to specify that this code segment must be put in the same template as the previous code segment to execute properly. This listing starts with the <cfoutput> tag. When the ColdFusion server sees the <cfoutput> tag, it knows to process all the text between the beginning <cfoutput> and the end </cfoutput>. The difference between the start and end tag is that the end tag has a slash before the tag name. This is identical to the way that HTML handles start and end tags. Not all tags have both a start and end tag. The <cfset>, for instance, has no closing tag.

You can place any sort of text that you want in the <cfoutput> tag block. The way to tell ColdFusion the difference between normal text and an expression that is to be evaluated is with the use of the pound sign, "#". Text between two separate pound signs is evaluated as an expression. Make sure that there are no spaces between the pound signs and the expression. Any text without pound signs is completely ignored by the ColdFusion server and is passed on to the browser unmodified. This text could be HTML, JavaScript, CSS, or any plain text.

The second line of the template contains a ColdFusion expression and an HTML tag. ColdFusion will look at the expression and return the value of the FirstName variable, "Jeffry". The HTML <br> tag will go straight to the browser. The same happens for the LastName, Age, and State. The code segment finishes with the end cfoutput tag. The output should look like this:

Jeffry
Houser
28
28

You'll notice that the State variable contains the most recent value it was set to, and the other values, "California" and "Connecticut", are lost.

Variable Scopes
At this point, you should have a good understanding of how to create variables within ColdFusion. There is one more important topic you'll need to understand about variables. This is the concept of variable scopes. A scope is used to define the extent of a variable's life before the server destroys it (removes it from memory), and determines how it can be used. To access a variable in a specific scope, you can specify the scope before the variable's name, and separate it from the variable name with a period, like this:

ScopeName.VariableName

Just as you could mix case sensitivity with variable names, you can also do so with variable scopes. They are not case sensitive. Here are some common variable scopes:

  • Variables: This is the local variable scope of a page, the default scope ColdFusion stores variables in, and the first place ColdFusion will look for variables whose scope has not been specified. It is available throughout the execution of a single template and all the include files that the template uses. It is not available to custom tags or ColdFusion Components called from within the template.
  • Request: The request scope is very similar to the local variable scope, except that it is available across a whole request, including inside custom tags or ColdFusion Components called from the main template.
  • Form: When you use an HTML form, its values are placed inside the form scope on the form-processing page. The life of the form scope is a single template execution. Like the request scope, it will be available to custom tags or ColdFusion components.
  • URL: The URL scope contains variables specified in the query string portion of a URL. They have a life similar to the form and request scopes.
  • Cookie: The cookie scope refers to variables that are stored by the user's Web browser. These variables are available during a single template's execution, in much the same way that form, URL, and request scopes are. However, unless you do something to erase a cookie variable from the user's browser, the value will be available on all page requests.
  • Application: The application scope is unique to a particular ColdFusion application. You can set up a ColdFusion application using the cfapplication tag. You can read more about the cfapplication tag at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-pa3.htm. The application scope is known as a persistent scope, because it exists between page requests. An application variable will exist once, no matter how many users are using your application.
  • Session: The session scope is another persistent scope. A single session exists for each user of a particular application. Just like the application scope, session usage is set up using the cfapplication tag. A different set of values in the session scope will exist for each individual user on your application.
This is a list of some of the more commonly used scopes, but it is not comprehensive. You will most likely discover more scopes during your development adventures in ColdFusion.

In our code example from the previous section, we did not specify a variable scope. When no scope is specified, the variables are placed in the local scope, which is named "variables". We could easily rewrite the previous listing to look like this:

<cfoutput>
#variables.FirstName#<br>
#variables.LastName#<br>
#variables.Age#<br>
#variables.State#<br>
</cfoutput>

This code segment works identically to the one that did not specify the variables' scope before the variable name.

Conclusion
Variables will be the basis of many of your programming projects within ColdFusion. This article should have given you a strong introduction to creating ColdFusion variables, and an overview of some of the uses they provide. In my next column, I'll take an in-depth look at ColdFusion expressions. If there's something you'd like to see in this column, feel free to drop me a line to let me know.

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.