Basic ColdFusion – Tutorial
Part 1: Introduction
Part 2: Assignments, basic arithmetic and displaying things on the screen
Part 3: Complex data objects: arrays, queries and structures
Part 4: ColdFusion and database
Part 5: Using form and URL variables to create forms
Part 6: “cfif” and “cfloop” tags
Part 7: Using functions in ColdFusion
Part 8: Quick look at ColdFusion components (CFCs)
Part 9: Useful hints
The aim of this tutorial is to explain to someone that never worked with ColdFusion as to what it is and how to get started quickly. There is no assumed prior knowledge of ColdFusion. However, it is assumed that you have already installed a CF (CF stands for ColdFusion) server. In the database section I also assumed that you installed a database server – for my examples I will use a SQL server and its default databases (pubs and Northwind). I assume that you know, or someone will help you with installing datasource names for these two databases.
ColdFusion is a scripting language, that since 1996 has been used by developers to create dynamic websites. A dynamic website can change depending on outside factors like data, user preferences or changes in backend database. Websites that only use HTML are static. HTML is a set of tags used to format and link pieces of text – it doesn’t change. DHTML (dynamic HTML) based website has limited ability to interact with the website visitor, however, its inability to access a database make it almost static.
ColdFusion is a programming language that is tag based and can be used on the same page as HTML (however for more advanced programming projects such practice is discouraged). All ColdFusion tags start with “cf”, for example, <cfset yourName = “Joe”> this tag sets variable “yourName” to the value of “Joe”. ColdFusion is not concerned with variable and statement case, thus <CFSET YOURname = “Joe”> is the same as <CFset yourNamE = “Joe”>.
Guide version 0.1 last updated on 11/06/2005.
I provide this guide as is, without any guarantees, explicit or implied, as to its contents. You may use the information contained herein in your computer career, however I take no responsibility for any damages you may incur as a result of following this guide. You may use this document freely and share it with anybody as long as you provide the whole document in one piece and do not charge any money for it. If you find any mistakes, please feel free to inform me about them Tom Kitta. Legal stuff aside, let us start.
2. Assignments, basic arithmetic and displaying things on the screen
In every programming language there is a way to set a variable. A variable is a space in computer (server) memory that holds a certain value. This value can be text, number or any other object (for example an array). In ColdFusion, you create a variable using the <cfset [variable name] = [variable value]> tag. For example, you can set variable “blah” to hold value of 123: <cfset blah = 123>.
Variables can store results of adding numbers, concatenating strings or any other legal operation. For example, you can do the following:
<cfset myVar = 123> <cfset anotherVar = 321> <cfset sum = myVar + anotherVar> Here is what the variable 'sum' holds sum = 444 <br/> You can output it using: <cfoutput>#sum#</cfoutput> <br/>
You can also concatenate strings together (like gluing them together). ColdFusion has automatic variable type conversion, it belongs to a family of programming languages that are not strongly typed. This means that you can have smooth transition from a number to a string depending on operation performed on them. You don’t need to specify variable type when declaring a new variable, in fact you never need to do any “casting” of variable type (i.e. explicitly setting variable type). In practice, this means that the following is a legal operation:
<cfset myStringVar = "abcdefg"> <cfset myNumberVar = 12345> <cfset concatinationVar = myStringVar & " " & myNumberVar> Here is what the variable 'concatinationVar' holds concatinationVar = "abcdefg 1234" <br/> You can see the result: <cfoutput>#concatinationVar#</cfoutput> <br/>
Please note that a string concatenated with a string (space) and a number results in a string. As you probably noticed by now the ampersand symbol (&) is used as the concatenation symbol.
I am sure that by now you have an idea, from the examples above, how one displays variable results to the screen. You output variable contents to the screen using the <cfoutput>#[some variable]#</cfoutput>. In other words, your variable needs to be surrounded by the pound symbols (#) and by the <cfoutput></cfoutput> tag pair. There has to be one pound pair per expression, but the <cfoutput></cfoutput> can surround multiple expressions. For example, lets set some variables and then display them to the screen (user’s browser window). Note, you can only display directly to the screen variables containing simple values, such as strings and numbers. There is no need to use <cfoutput> tag pair when displaying ordinary text – it is only needed when displaying ColdFusion variables (or evaluating ColdFusion expressions that result in simple types).
<cfset myFirstVar = "1st string"> <cfset mySecVar = "2nd string"> <cfset myNumber = 123> <cfset anotherNumber = 345> <cfoutput> #myFirstVar# <br/> #mySecVar# <br/> #myNumber# <br/> </cfoutput> <cfoutput<#myNumber+anotherNumber#</cfoutput> Results when above code is executed: 1st string 2nd string 123 468
Since we are talking about variables, it is worth to write few words about “scopes”. Each variable in ColdFusion belongs to a variable “scope”. A scope is basically a grouping of variable types. You may think of a scope as a grouping of variables. By default, all variables created on a template are members of a “variables” scope. The variables scope is the first scope that ColdFusion looks through when programmer doesn’t explicitly set the scope. Please note misleading scope name, yes, scope is named “variables”. For many scope types you don’t need to specify them explicitly, ColdFusion will search all scopes, starting with “variables” for variable value. You can explicitly specify scope in a <cfset> statement like this: <cfset variables.myVariable = 12345>. You just set a variable named “myVariable” in the “variables” scope to the numeric value of 12345.
The “variables” scope is the default scope. New variables which are created on ColdFusion template are created in the “variables” scope unless you explicitly define the scope in which variable is to be placed. There are many scopes in use in ColdFusion. Take a look at the table underneath for a list of most common scopes and simple explanation as to their use. Discussion of less common scopes is beyond the scope of this tutorial. For your reference, these are: server, cookie, arguments, request, client, this, flash and some tag specific scopes. Please note, that all variables in the non-persistent variables scopes, like “variables”, “form” and “url” exist only on they page they were declared on, or created by the system. On subsequent pages, these variables are not found. For more information about scopes, please take a look at scope list.
One of the more important functions used with variables is isDefined() function. It is used to check whatever a variable exist. You need to check whatever a variable exists, since using a variable that doesn’t exist will produce an error. This function returns either “true” – variable is defined, or “false” – variable is not defined. Usage example: isDefiend(“bob”) will return true if “bob” is a defined variable, false otherwise. Note that the quotes are mandatory around variables you want to test! For more help, see the documentation.
|Scope name||Need to define it
3. Complex data objects: arrays, queries and structures
Sometimes using simple variables holding just strings and numbers is not enough. At first you may think that you may get along without using structures, arrays and queries. However, just few simple real life examples will prove otherwise. If you want to use a database (anything but the most simple applications) you need to be familiar with queries. All build in ColdFusion scopes as of ColdFusion edition 6 (MX) can be accessed using structure syntax.
Structures are an abstract data type (meaning they are not simple), also known as associative arrays, that I will explain using a simple example. Say, you want to store person’s name, address, age, income and eye color on your page. You could define five separate variables, with simple data types. However, that approach has problems – it is very inflexible (think more people, more data). Instead of creating five simple variables – you should create just one, a structure. Lets call the structure “personData”. This is how the declaration would go:
<cfset personData = structNew()> <cfset personData.name = "joe"> <cfset personData.address = "101 Some Drive, Pleasant Town, 90010"> <cfset personData.age = "30"> <cfset personData.income = "50000"> <cfset personData.eyeColor = "blue">
You cannot directly display structures, only its members, thus <cfoutput>#personData</cfoutput> would produce an error – complex types cannot be displayed. However, you can display its members just fine, for example, <cfoutput>#personData.age#</cfoutput> will work – it will display 30 on the screen.
As you noticed from example above, you use the “dot” operator to define individual members of a structure. You may define as many as you like. Alternatively, you may use another syntax which uses square brackets and quotes around structure members, for example, <cfset personData.name = “joe”> can be written down as <cfset personData[“name”] = “joe”> with the square bracket notation the structure member variable case is preserved (i.e it matters for some cases).
Discussion of arrays is a continuation of the discussion about structures. I will use continuation of the previous example to place array usage into a better focus. You will now see more clearly, why structures and arrays are so much better at data representation than just simple data types.
Continuing our “personData” structure example, imagine that now you have 10 more people to store data for. As before, you could just create 10 separate variables. However, you are smarter than this – you will combine a structure storage of personal data with array storage. An array is a “list” of indexed “things”. The index in ColdFusion starts at 1 (unlike some other programming languages where it starts at 0) and goes as high as you want. Arrays can have up to three dimensions in ColdFusion, but single dimension arrays are most useful and will be discussed here. Assume, you have data in structures named “personOne”, “personTwo” and “personThree” and look at the example which will show how to place these three structures into an array. The example also show how you will access these structures later on. You may place into an array any objects you want, they can be strings (array of strings), numbers or any complex object. Arrays of structures are one of the more useful abstract data storage concepts you can learn.
<cfset myArray = arrayNew(1)> <cfset myArray = personOne> <cfset myArray = personTwo> <cfset myArray = personThree> To get the personTwo structure, you may: <br/> <cfset newPersonTwo = myArray> To print stuff stored in personTwo struct to screen: <br/> <cfoutput>#myArray.name#</cfoutput> <br/> <cfoutput>#myArray.address#</cfoutput> <br/> <cfoutput>#myArray.age#</cfoutput> <br/> <cfoutput>#myArray.income#</cfoutput> <br/> <cfoutput>#myArray.eyeColor#</cfoutput> <br/>
The third major complex data type in ColdFusion is a query. Query is made internally from the array and structure data types, however, it stands on is own as a distinct data type due to special rules that apply to it. Queries are usually returned from the database. You will learn more about how to get data from the database later on in this tutorial. Here, I will give you an example of how you can create query from scratch, without the use of a database. You will notice, that the syntax is very similar to the one used by the array of structures.
<cfset myQuery = queryNew("columnNameOne,columnNameTwo")> <cfset newRow = queryAddRow(myQuery)> <cfset newCell = querySetCell(myQuery,"columnNameOne","value one")> <cfset newCell = querySetCell(myQuery,"columnNameTwo","value two")> <cfset newRow = queryAddRow(myQuery)> <cfset newCell = querySetCell(myQuery,"columnNameOne","value three")> <cfset newCell = querySetCell(myQuery,"columnNameTwo","value four")>
Above is a query with two rows, each containing 2 columns. All <cfset> tags, with the exception of the first one, assign values to dummy variables, since there is rarely any need to keep values returned from query data setting methods. In other words, if you don’t need the return value of a function, you may just write: <cfset querySetCell(myQuery,”columnNameTwo”,”value four”)> instead of <cfset newCell = querySetCell(myQuery,”columnNameTwo”,”value four”)>.
Queries are special type of “structures of arrays” i.e. the column names are structures while each column information is stored in an array. You can access information inside a query in the same way you would access information inside a structure of arrays. To better illustrate this, I will provide an example (its rather hard concept to explain without one). The example that follows shows you how to access data in the query provided above.
<cfset firstRowFirstColumn = myQuery.columnNameOne> <cfset secondRowFirstColumn = myQuery.columnNameOne> <cfset firstRowSecondColumn = myQuery.columnNameTwo> <cfset secondRowSecondColumn = myQuery.columnNameTwo> You can output above to see that they do contain what variable names claim: <br/> <cfoutput> #firstRowFirstColumn# <br/> #secondRowFirstColumn# <br/> #firstRowSecondColumn# <br/> #secondRowSecondColumn# <br/> </cfoutput>
Few facts that are useful to know about queries:
- Query is the format in which data is returned from the database. Check documentation to learn more about queries and <cfquery> tag.
- Query contains in it besides data some special properties, for example, it contains the number of records it contains. Using above query as an example, variable “myQuery.recordcount” contains value of 2 (since our query has two rows).
- You can use most array functions on query columns, an exception are functions that effect row ordering (like delete).
- You may not only create SQL and execute it agains a database, but also against queries that are contained in ColdFusion variables. These queries of queries are possible because ColdFusion supports subset of standard SQL language. For more information, look for tutorials on use of query of query.
- You should be aware that queries are not the only way to get data out of database, you may also use something called “stored procedures”. A stored procedure is a piece of SQL that was compiled on the database server and resides there. You may access it through standard <cfquery> tag, but the recommended way uses <cfstoredproc>.
4. ColdFusion and database
In the previous section you got a taste for what a query is and how you may create one from scratch in ColdFusion. However, at least in the beginning of your career as a ColdFusion developer you will far more frequently create queries using database access than using queryNew() function. In this short section I will introduce you, very briefly, to the way you interact with a database.
For the purpose of this discussion a database is a piece of software that runs on a server and stores large amounts of data in the form of multiple data tables. Before you can access all this data you need to connect to it. You need to tell ColdFusion server where to look for all this data. This is done through ColdFusion administrator. You access the administrator through web interface using, by default, http://%5Bserver name, like http://www.tomkitta.com]/cfide/administrator/ when prompted with login page, enter your password and login. One of the menus on the left hand side will be “Data Sources”. After clicking on this link you will see database – ColdFusion manipulation screen. On this screen you can add connection(s) to you database(s) – full discussion of how you do that is beyond the scope of this short tutorial. Lets just say it is not very hard and there are plenty of resources out there that will guide you in case you run into trouble. For the rest of this section I will assume that you have at least one datasource setup. Lets name this datasource “pubs” after one of sample databases by the same name included in the default installation of Microsoft SQL Server. I assume, for the sake of examples, that datasource “pubs” points to database by the same name created during default installation of MS SQL Server.
ColdFusion has probably one of the easiest database interaction routines among all web development programming languages. Almost all interaction with the database (except advanced things like usage of stored procedures with <cfstoredproc> tag) can be accomplished with the help of <cfquery> tag. I assume, in the following example, that you have successfully setup datasource named “pubs” and a table with the name of “titles” exists in the database to which “pubs” point.
Get all data from the "titles" table (pubs datasource) <br/> <cfquery name="myFirstSelect" datasource="pubs"> SELECT * FROM titles </cfquery>
You notice that inside the <cfquery> tag braces there is special code that doesn’t look like ColdFusion. It is called “T-SQL”. The letter “T” stands for “Transact” and “SQL” is a standard query language. The T-SQL is used by MS SQL Server. Other flavors of standard SQL are used by other database engines, for example, ORACLE uses “PSQL”. You will need to learn SQL since, as mentioned before, a large part of the purpose for existence of any web development language is ability to interact with a database. Interaction means getting data from the database, changing data, inserting data and removing data. Respectively, you have special SQL statement for each of these: SELECT, UPDATE, INSERT and DELETE. Above example uses SELECT statement to get all data from the table named “titles”. I will now provide few more examples of SQL statements. This is just a quick overview of SQL, more detailed explanation of SQL (with use of particular SQL dialect) is left to another tutorial (for example, see this one).
Get All data from titles table <br/> <cfquery name="getTitles" datasource="pubs"> SELECT * FROM titles </cfquery> Get only 'title' and 'price' columns from the titles table <br/> <cfquery name="getSomeTitleData" datasource="pubs"> SELECT title,price FROM titles </cfquery> Update price for a book with ID 'BU1032' to $23.99 <br/> <cfquery name="updateTitlePrice" datasource="pubs"> UPDATE titles SET price = 23.99 WHERE (title_id = 'BU1032') </cfquery> Insert into discounts table a new entry, sample discount of $2.50 <br/> <cfquery name="addNewDiscount" datasource="pubs"> INSERT INTO discounts (discounttype, discount) VALUES ('example discount', 2.50) </cfquery> Delete from discount table the discount we inserted above <cfquery name="deleteDiscount" datasource="pubs"> DELETE FROM discounts WHERE (discount = 2.50) </cfquery>
Once you get data from the database you treat returned data as you would any other query. Note that operations other than SELECT don’t return a query back – you may omit usage of the ‘name’ parameter in <cfquery> tag. I suggest you learn all you can about SQL, as it will become the most important (after ColdFusion) language you are going to use in your career as a web developer.
5. Using form and URL variables to create forms
Forms are created in HTML using special set of form building tags. Lets build a simple form and then a simple target page.
<form name="myForm" action="targetPage.cfm" method="post"> Enter some text here <input type="text" size="50" value="Enter some text here" maxlength="150" name="someText"> <br/> Check if you like this guide <input type="radio" value="1" name="likeGuide" checked> Check if you don't <input type="radio" value="0" name="likeGuide"> <br/> <input type="submit" value="send this form"> <br/> </form>
This is how the above form looks like when displayed to the end-user:
Now, I will create the target page, the one referred to as the “targetPage.cfm” above. Note that I am going to use “post” method to send my form information to the target page. Post operation will create “form” scope variables on my target page. Almost in every case you want to use method “post” since it allows for much more data to be sent to the target page. However, “url” method is the default for historical reasons. The “url” method will create “url” scoped variables, not “form” scoped. For more information about “form” and “url” scoped variables, please refer to one of the previous sections of this tutorial.
<cfoutput>Text you typed on the form #form.someText#</cfoutput> <br/> You indicated that <cfif form.likeGuide eq 1> you like <cfelse> don't like </cfif> this guide. <br/>
As you can see, we use “form” scoped variables on the target page as we would any other variables. Now, a quick introduction to a cousin of the “form” scope – “url” scope. The variables in the “url” scope are created by ColdFusion on the page in which query string we have some defined values. For example, lets assume that we just called a page with the following in the address tab: http://www.tomkitta.com/somepage.cfm?name=tom&job=programmer On the “somepage.cfm” two “url” scoped variables would be created, “url.name” and “url.job” (they are both created at the same time, their order in the query string doesn’t matter). The first variable will have the value of “tom”, the second will have the value of “programmer”. The “url” variables are a quick way to transfer variables and their values from page to page. Please note that for both “url” and “form” scopes you don’t need to specify “form” or “url” strings in front of variables that are in the “url” and “form” scopes. ColdFusion will search all scopes that don’t need to be explicitly specified by the user for your variables and their values. For flexibility reasons (for example, you want to be able to accept both “form” scope variables as well as “url” scoped variables) you may omit “url.” and “form.” scope specifying strings. The following are equivalent: <cfset test = form.myFormVariable> and <cfset test = myFormVariable>. However, for most applications it is a good practice to specify which scope you are in for clarity. Also, ColdFusion first searches the “variables” scope, then other scopes – thus the process of searching for “form” and “url” variable values if no scope is explicitly stated takes time.
6. “cfif” and “cfloop” tags
One of the most important concepts in functional programming language group are the concepts of “if statement” and “loop statement”. Both of these are very fundamental and their syntax should be one of the first things programmers learn in new language. The “if statement” is a form of a question. If something is true then do this, if something is not true, do something else if defined, else proceed without doing anything. Lets look at the following examples:
<cfset x = 5> <cfif x eq 5> x is equal to 5 <br/> </cfif> <cfif x eq 4> This will not print <br/> </cfif> <cfif x gt 10> This will not print <br/> <cfelse> x is less than or equal to 10 <br/> </cfif> <cfif x gt 5> This line will not print since x is not greater than 5 <br/> <cfelseif x eq 5> This line will print since x is 5 <br/> <cfelse> This case will not execute, since above case will <br/> </cfif>
Please note the usage of new tags, <cfelse> and <cfelseif>. These two tags are helpers inside the <cfif> block of code. The first one is placed as the last condition inside the if block – it executes only if all cases above fail. The second one is used to expand on the first if condition – provide alternative if statements in a long chain – trying to catch specific user input. Very long sequences of <cfelseif> tags can be replaced by <cfcase> statements, which some claim are easier to read (explanation is beyond the scope of this tutorial). The most important thing to remember about the if statement is what it evaluates – it checks for truth. For example, as above, it checks whatever it is True that x is equal to 5. If it is true, then what follows is executed, if not, then case is skipped. If you use boolean variables, that have value of either true or false, you can just type <cfif myBoolean> do something </cfif>. I will provide here now a short list of most common comparison elements used.
Comparison operators are not case sensitive when comparing strings. You may also use logic operators in ColdFusion when evaluating truth value, you may use “and”, “or” and “not”.
Now its time for introduction of the “loop statement”. We start with a simple counter loop, where we count from 1 to 10. The purpose of loops is to repeat certain action for specific number of times. There are few other flavours of loop:
- conditional – loop execute till some condition specified stays true.
- query – loop over a query. You can use cfoutput to print out query sequentially, but cfoutput is limited, it cannot be nested (unless you use group by).
- list – loops over every element in a list. List is a string that is delimited (divided) by certain character. Most common character used is a comma. For example, the following is a list of three elements delimited by a comma: “1,2,3”.
- Collection – loops over elements in a structure.
Counting from 1 to 10, by 1 (step is 1); Printing loop counter <br/> <cfloop index="x" from="1" to="10" step="1"> <cfoutput>#x#</cfoutput> <br/> </cfloop> Conditional loop, executes infinite loop in this case since x is always 5 <br/> <cfset x = 5> <cfloop condition="x eq 5"> X is still 5 <br/> </cfloop> Query loop loops over all rows in input query <br/> <cfset myQuery = queryNew("columnOne")> <cfset queryAddRow(myQuery)> <cfset querySetCell(myQuery,"columnOne","value one in column one")> <cfloop query="myQuery"> <cfoutput>#myQuery.columnOne#</cfoutput> <br/> </cfloop> List loop executes a loop over all elements contained in a list <br/> <cfset myList = "listElementOne, listElementTwo"> <cfloop index="x" list="#myList#" delimiters=","> <cfoutput>#x#</cfoutput> <br/> </cfloop> Collection loop executes a loop over all elements in input collection <br/> <cfset myStruct = structNew()> <cfset myStruct.itemOne = "item one"> <cfloop collection="myStruct" item="x"> <cfoutput>#x#</cfoutput> <br/> </cfloop>
7. Using functions in ColdFusion
Functions are blocks of code that have a name and optional input/ output parameters. They are used to simplify web development and in re-use of code. There are two types of functions, functions that are written by you and functions that are defined in ColdFusion (build in functions). One of the most useful functions is isDefined(). It is used to check whatever a variable is defined. It returns true, if it is, false otherwise. There are many more functions build into ColdFusion. For a complete list of build in functions, take a look at the manual to find out about other functions. Good knowledge of functions is essential to you success as a web developer, together with knowledge of almost all build in tags. Note that we already used some functions in previous examples, without stating that we are using functions. After a short example illustrating the use of build in functions, I will explain how to create your own functions.
<cfset x = 5> <cfif isDefined("x")> X is defined (this will execute since x is defined above) <br/> </cfif> <cfif isDefined("y")> Y is defined <br/> <cfelse> Y is NOT defined (this will execute since Y is not defined) <br/> </cfif> You can use the len() function to check the length of strings: <br/> <cfif len(x) eq 1> Since x as a string has length of 1 this will print <br/> </cfif> Here we create a two dimensional array with arrayNew() function <br/> <cfset myArray = arrayNew(2)>
I will now explain how to create functions using tags (you can also create functions in ColdFusion script). Function is declared with the usage of tag <cffunction>. What is inside this tag definition is part of function body and will be executed when the function is called. Functions in ColdFusion can return only one value (i.e. a single string or a structure). If you need to return multiple values – just build them into a single structure. Your functions don’t need to return a vlaue – it is said that their return value is of type “void”. Your functions may also produce output to the screen – they can be used as display functions. Lets look at few examples of function definition with explanation as to what each part of the definition and body does.
<cffunction name="additionSample" access="public" returnType="numeric" hint="Adding two inputs."> <cfargument name="firstNumber" type="numeric" required="true"> <cfargument name="secondNumber" type="numeric" required="true"> <cfset var resultOfAddition = arguments.firstNumber + arguments.secondNumber> <cfreturn resultOfAddition> </cffunction>
In above function declaration, we see that all of function body is surrounded by cffunction tags. Briefly, you always need to define function name – all other parameters to the <cffunction> tag are optional. However, it is a good idea to include more information than the bare minimum about your new function. This extra information will help you or someone using your code later on. For more information about <cffunction>, see ColdFusion documentation. If you want to pass something to your function (arguments can be set as optional) you need to specify them with another tag, <cfargument>. This tag is used to specify information about the values that you are going to accept into your function from the outside (place where your function is used). Only the name is required attribute for this tag, however, as with its parent tag, <cffunction>, it is a good idea to include more information about the values you are going to accept. For more information about this tag I am going to send you to ColdFusion manual.
Inside above function you see that I have used “var” before the name of the variable. The keyword “var” used in front of the variable name you are declaring using the <cfset> tag forces ColdFusion to create variables that are local to the function. This means that these variables will only be accessed from within this particular function’s body. They are private to this function. It is a good programming practice to define variables only in scopes they are going to be used – there is no point of making every variable global. You will understand why it is so important when you write your first large program and realize that usage of variables in the most global scopes (like session or application) is only good for variables that actually need to be accessible from so many places in your application. Just think of what a mess it would be if you had hundreds of variables accessible from everywhere in your application. How would you ever keep track of all of them?
When you are ready to return a value from your function, you use <cfreturn> tag. It is vary basic tag that executes only once in a function (it terminates function execution) in order to present function output to the calling page/ process. If you are returning something from your function then you need to use this tag. However, if you are not returning anything from your function than you cannot use this tag (i.e. your function’s output type is set to “void”). You may have multiple <cfreturn> tags in your function code, however, only one will be executed (i.e. multiple <cfreturn> tags inside nested <cfif> tags – for example).
Function that output to the screen: <br/> <cffunction name="helloWorld" access="public" output="yes" returnType="void" hint="Prining hello world on the screen."> Hello World <br/> </cffunction> To access above function (i.e. run it): <br/> <cfset helloWorld()> OR <br/> <cfoutput>#helloWorld()#</cfoutput>
As you can see in above example, there are two common ways of calling your functions, you can either use <cfset> tag or <cfoutput> tag. There are other ways of calling functions, but they are less used, for now the above two will suffice. If you were to call additionSample() function from the previous example, you would need to add two parameters (both numeric). For example, to find out how much is 2 + 2, you could either <cfset twoPlusTwo = additionSample(2,2)> or <cfoutput>#additionSample(2,2)#</cfoutput>.
8. Quick look at ColdFusion components (CFCs)
You can combine functions together and form ColdFusion components, also known as CFC. Think about components as objects – they are ColdFusion answer to the basic requirements of object oriented design. The whole discussion of object oriented programming is well beyond the scope of this tutorial. All I will do here is tell you how to create and access CFCs.
CFCs were introduced in version 6 of ColdFusion. They are stored in files with extension of “.cfc”. For example, component names car will be stored in file named “car.cfc”. You only store one component per file. Each component’s definition (code) is surrounded by <cfcomponent> tags. Inside CFC you have multiple function definition. Some functions are “public” – for use outside the component, some are for use in the component only – they are “private”. All functions contained in a CFC should have a similar purpose. For example, they are responsible for database access. The following is an example of CFC definition with some functions in it. Note that all code that is present outside a function but inside <cfcomponent> tags is executed at the time of CFC initialization.
<cfcomponent name="sampleCFC" hint="just a sample component"> <cfset componentName = "Sample"> <cfset this.color = "blue"> <cffunction name="additionSample" access="public" returnType="numeric" hint="Adding two inputs."> <cfargument name="firstNumber" type="numeric" required="true"> <cfargument name="secondNumber" type="numeric" required="true"> <cfset var resultOfAddition = arguments.firstNumber + arguments.secondNumber> <cfreturn resultOfAddition> </cffunction> <cffunction name="getComponentName" access="private" output="no" returnType="string" hint="Get name."> <cfreturn componentName> </cffunction> </cfcomponent>
You will notice that we have used another scope above, “this”. This special scope refers to the “properties” that exist inside components. These properties can be set from outside of a component – they are not private. On the other hand, variables defined without the use of “this” scope are private to the component they were defined in. Now I will show you how you use your new component inside your ColdFusion template (you may also initiate components inside other components).
<cfobject name="myCFC" component="simpleCFC"> Now lets use function inside our CFC initialized above: <br/> <cfset aPlusB = myCFC.additionSample(5,10)> The value stored inside aPlusB is 15 <br/>
One of the easiest methods of initializing CFCs using tags is <cfobject> tag. The “name” parameter of this tag is a variable you are going to use to access all methods (functions that are members of objects are called methods) contained within your CFC. The variable you use stores component definition. You may think of it as a special scope used only for that particular component. For more information about components, once again, you need to look into CF manual and also here. There is another method of initialization of not whole CFCs but of methods in them. You may use <cfinvoke> tag to invoke just one method inside a CFC. Once method is invoked CFC is created just for the time needed for method invocation to complete. This method of using CFC is useful when you only need to use one method from a CFC. For more information, please take a look at the help files.
9. Useful hints
Here I present a list of useful things you should know about ColdFusion that don’t fit into any of tutorial topics above. The list contains all sorts of things that will make you a advanced CF developer in shortest possible time.
- You can find a lot of pre-written ColdFusion functions on the web. Why write something from scratch when you can use someone else’s work (provided for free)? A good place to start is CF library project You may also checkout ColdFusion exchange provided by Macromedia on their website.
- If you are in trouble, stuck on some problem related to ColdFusion, newsgroups are one of the best places to look for help. One of the oldest newsgroups related to ColdFusion is located on House of Fusion website. You may also checkout Macromedia newsgroups.
- I know this one is rather obvious, however, I put it here anyways, just in case: “Use your favorite search engine to seek solutions to your programming problems”. I use Google before I seek help from my co-workers/ friends and newsgroups. There is nothing more embarrassing than someone pointing you to a website they found with Google in 2min.
- In the beginning of your programming career in ColdFusion it might be of rather great help to read other people’s code. You may download some free code from different places, most notably form Macromedia exchange. You can just look at the code other people created and see how they code.
- Don’t forget that any code can be well understand by the compiler (ColdFusion server) but only well written code can be understood by other people (or you when you look over your own code few weeks after it was written).
- Use inline comments to comment your code – make sure your comments have a meaning, i.e. comment only where needed harder points of your code. There is no need to comment things that are obvious, for example, there is little point to place a comment “adding 2 to x” besides x + 2.
- Indent your code – make sure that each block of code has the same indentation.
- Avoid using global scoped variables.
- Re-use your code with functions and components – avoid as much as possible “cut and paste” programming style.
- There are two usefull tags that you should know of – <cfdump> and <cftrace>. Both of these tags are used to help you in debigging of your code. The first tag is used to display in browser’s window the contents of the structure you pass to it. For example, you can “dump” to the screen a whole query, named “myQuery” like this: <cfdump var=”#myQuery#”>. Note that the pound signs are mandatory since <cfdump> is expression based tag. As for <cftrace>, it is used to display one line of debug code – just like using <cfoutput> tag, but with more control – more geared towards debugging. For example, to display a variable (simple type, like a string) in the area of CF debug – you can type <cftrace text=”My variable is #myVar#” inline=”false”>.
I hope you enjoyed my short introduction to ColdFusion. It is (in my opinion) the easiest to learn web development language. Through it is easy to learn it can be used for applications that all other web development languages are used for. If CF is too slow at some task, or unable to do them you can always extend it. ColdFusion is a front end to a more powerful Java language, which comes with all the bells and whistles modern programming languages have to offer.
If you found some mistakes in this guide, would like to contribute some of your own work, or have some problems with the examples presented above, feel free to contact the author. You can use contact information contained on my website.