In: Categories » Computers and technology » Programming » Using a Custom Tag
Custom tags are reusable, developer-authored extensions to the ColdFusion language. The custom tag that you create in the following parts displays today’s date in a familiar format. Create a file named TodaysDate.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file.
<cfoutput>#DateFormat(Now(), “ddd, mmm d, yyyy”)#</cfoutput>
Now() returns the current date and time, and DateFormat() reformats the date. To call your custom tag, open index.cfm, add the following code to the top of the template, and save the file:
<p><cf_TodaysDate></p>
A custom tag is called by appending CF_ to the name of the tag file, without the .cfm extension. Point your browser to index.cfm and make sure that today’s date now appears at the top of the file in an easy-to-read format. Calling the custom tag runs TodaysDate.cfm. CF_TodaysDate in its current state doesn’t do much. The capability to specify the format in which the date should be presented, as follows, would be nice:
<cf_TodaysDate Format=”American”>
Format is an attribute to this custom tag. The code shows how to use the Format attribute in the custom tag. Make the changes shown in the code to your TodaysDate.cfm custom tag.
<cfswitch expression=”#Attributes.Format#”> <cfcase value=”Long”> <cfset FormatMask = “ddd, mmm d, yyyy”> </cfcase> <cfcase value=”American”> <cfset FormatMask = “mm/dd/yyyy”> </cfcase> <cfcase value=”European”> <cfset FormatMask = “dd/mm/yyyy”> </cfcase> <cfcase value=”Military”> <cfset FormatMask = “ddmmmyyyy”> </cfcase> <cfdefaultcase> <cfset FormatMask = “mm/dd/yyyy”> </cfdefaultcase> </cfswitch> <cfoutput>#DateFormat(Now(), FormatMask)#</cfoutput>
CFSWITCH evaluates the content of its Expression argument and checks it against the Value attribute of each of its CFCASE statements. As soon as a match is found between Expression and Value, the matching CFCASE block is executed. If no CFCASE tags match, the CFDEFAULTCASE is executed. Attributes.Format contains the value of the Format attribute that was passed to CF_TodaysDate (in this case, American), and FormatMask contains the date mask that the custom tag uses inside the DateFormat() function. To test the new custom tag, modify index.cfm so that the call to <cf_TodaysDate> looks as follows:
<p><cf_TodaysDate Format=”American”></p>
Run index.cfm again. Now try calling cf_TodaysDate using Format=”Military”.
You’ve written your first ColdFusion application! This is no small feat, and some of the techniques in this article are a little advanced. You’ve written an entire maintenance application for two entities in a database, created a total of 22 templates, and even made some pretty hefty modifications to your application to make it better. You should be very proud of yourself! Of course, this application is by no means complete. You have seen a few of ColdFusion’s features, but you’ve only scratched the surface. A real-world application would probably use the extra features described in the following list:
To keep things simple, you created a datasource and used a single variable Request. MainDSN to reference it. In a real application, you would not specify the username and password in ColdFusion Administrator; in Application.cfm, you would CFSET two more variables, Request.Username and Request.Password, and then specify the username and password to be used in all your CFQUERY calls.
A real application would have used structured exception handling to catch such errors as a user trying to delete a company with existing employees or adding the same employee twice.
A real application would have some type of graphical treatment and a much more well-developed navigation system.
Still, this was an impressive entry into the world of ColdFusion MX. You can only get better from this point forward! Read the rest of this article to learn the more advanced real-world principles and techniques that you need to know to create large, complex applications.
Many developers have difficulty understanding the rules of ColdFusion syntax, possibly because everyone writes ColdFusion code in a different way. This article explains the correct way to use expressions in ColdFusion. It tells you where to and where not to use pound signs and gives you the rules for using ColdFusion tags and functions. The article ends with a discussion of code comments. Expressions are everywhere in ColdFusion. Anything between pound signs is an expression in ColdFusion. Anything inside a CFSET or CFIF tag is an expression. Simply put, anything in ColdFusion that can be evaluated (i.e., “resolved into a value”) is an expression. Expressions can come in many different forms; the following four are just a small sampling:
#myVar# #Val(1 + 1)# <cfset aVar = ArrayNew(1)> <cfif aVar[1] EQ “A”></cfif>
You can have many types of expressions, but only the following four elements can make up any expression:
Variables: Variables are everywhere in ColdFusion.
Operators: Operators are symbols such as + or –, and comparisons such as GTE, LT, NOT, or MOD.
Functions: Any function can be part of an expression. Functions are always followed by a pair of enclosing parentheses.
Literals: A literal is a string or number used as part of an expression. Take, for example, the following expression:
#DateFormat(aDateVariable, “mm/dd/yyyy”)#
The mm/dd/yyyy in the preceding expression is a literal. Similarly, consider the following expression:
#Val(0)#
Here, the zero is a literal. Based on these rules, you can deconstruct some expressions. Take the following expression:
#DateFormat(aDateVariable, “mm/dd/yyyy”)#
It has three parts: a function call (DateFormat()), a variable (aDateVariable), and a string literal (mm/dd/yyyy). Now consider the following expression:
<cfset aVar = Val(anotherVar) + 1>
It has six parts: a variable (aVar), an operator (=), a function call (Val()), another variable (anotherVar), another operator (+), and a numeric literal (1). The following expression, however, is a trick on your eyes:
<cfif NOT(firstVariable GTE secondVariable)>
NOT looks as though it is a function, and firstVariable GTE secondVariable appears to be an argument to that function. This evaluation, however, is not correct. NOT is actually a ColdFusion operator, and the parentheses tell ColdFusion to evaluate firstVariable GTE secondVariable first and then to use the NOT operator on the result. The NOT operator takes a true/false expression and flips it—true becomes false and vice-versa. A better way to write this expression as is follows:
<cfif firstVariable LT secondVariable>
This version avoids any confusion on the part of the reader. Now that you’ve seen how to construct ColdFusion expressions, take a look at the operators that ColdFusion uses. Arithmetic operators work with numbers. If ColdFusion can’t convert both operands (the items on either side of the operator) to numbers, ColdFusion throws an error. Plus, minus, divide, and multiply are the four basic math operations. In division, the righthand operand cannot be zero. Use of these operators is straightforward:
1 + 1 returns 2 10 - 1 returns 9 10 / 5 returns 2 4 * 2 returns 8
Whenever the sign operators appear in front of a number, as in the following examples, they indicate the number’s sign:
+1 + 5 returns 6 (positive 1 plus 5) -1 + 7 returns 6 (negative 1 plus 7)
The modulo operator (MOD) divides the first operand by the second operand and returns the remainder. The second operand cannot be zero. Like other operators, MOD is positioned between its operands:
10 MOD 3 returns 1 (10/3 is 3 with remainder 1) 15 MOD 8 returns 7 (15/8 is 1 with remainder 7) 15 MOD 5 returns 0 (15/5 is 3 with remainder 0) 5 MOD 7 returns 5 (5/7 is 0 with remainder 5)
The integer division operator (\) divides the first operand by the second and returns the result, discarding the remainder. The second operand cannot be zero. Integer division is as straightforward as when you used it in grade school:
10 \ 3 returns 3 (10/3 is 3 with remainder 1) 15 \ 8 returns 1 (15/8 is 1 with remainder 7) 15 \ 5 returns 3 (15/5 is 3 with remainder 0) 5 \ 7 returns 0 (5/7 is 0 with remainder 5)
The exponent operator (^) returns the first operand raised to the power of the second operand:
2 ^ 3 returns 8 (2 to the third power is 8) 5 ^ 5 returns 3125 (5 to the fifth power is 3125) 8 ^ 2 returns 64 (8 squared is 64)
Comparison operators compare two values and always return a boolean result (TRUE or FALSE). You have eight comparison operators; six of them have optional notational. IS, for example, can also be written as EQ or EQUAL. Contrary to popular belief, no difference—performance, type compatibility, case sensitivity, or otherwise—exists between an operator and any of its shorthand versions. Comparison operators can take operands of any data type, but be aware that, if the data types are not the same, ColdFusion attempts to convert the operands into compatible types, possibly with unexpected results.
legal notice
Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.
Useful tools and features
related articles
In addition to being one of the easiest Web-programming languages, ColdFusion is also one of the most easily extensible languages, because it can interface with many different technologies, as shown in the following list: Java objects, which are standalone packages of code written in the Java language Custom tags written in C++ or Java, which are pieces of code to be used only with ColdFusion, but which are written in either C++ or Java Java Server Page (JSP) tag libraries, which are originally built for use w...
2. First ColdFusion Application
You learn by doing, and then we go back and explain how ColdFusion worked its magic. Before you get started, though, you must learn a few terms, set up the database, and create the Web directory that you’re going to use. These are some terms that you should know: A template is a file with a .cfm extension. ColdFusion executes these templates and produces HTML that is returned to the user’s browser. A page is what appears in your browser. It is rendered from the HTML that ColdFusion Server sends back ...
3. Building the company add action template
In this article, you create the template that puts your form data into the database. Create a file named CompanyAddAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”InsertCompany” datasource=”#Request.MainDSN#”> INSERT INTO Company( CompanyName, Address, City, State, ZipCode, Comments ) VALUES ( ‘#Trim(Form.CompanyName)#’, ‘#Trim(Form.Address)#’, ...
4. Modifying a Company in the Database
The data that CFQUERY requests from the database comes back in a result set, and the Name attribute tells ColdFusion what that result set is to be named. The SQL statement consists of three clauses: SELECT, FROM, and ORDER BY. SELECT tells the database which columns to retrieve from the database; FROM tells the database which table to retrieve those columns from; and ORDER BY tells the database how to sort the results. The result set returned from CFQUERY contains multiple rows of data, and each row has multiple columns. It would ...
5. Building the company edit action template
The code in CompanyEditAction.cfm is like the code in CompanyAddAction.cfm, but the edit action updates rather than inserts. Create a file named CompanyEditAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”UpdateCompany” datasource=”#Request.MainDSN#”> UPDATE Company SET CompanyName = ‘#Trim(Form.CompanyName)#’, Address = ‘#Trim(Form.Address)#’, City = ‘#Trim(Form.City)...
6. Adding a New Employee to the Database
The CFQUERY in CompanyDeleteAction.cfm uses a DELETE statement with two SQL clauses: DELETE and WHERE. DELETE tells the database the table from which to delete a record, and WHERE tells the database which record to delete. You can watch the company delete process in action. Point your Web browser to http://<yourserver>/CFMXBible/Ch02/CompanyGetDeleteForm.cfm and enter a CompanyID. (To get a valid ID, go to the company list and pick a number from the ID column.) Click Submit to see the chosen company’s informatio...
7. Modifying an Employee in the Database
The DateFormat() function around the DateOfBirth column in the codereturns the employee’s birth date reformatted according to a display mask. DateOfBirth normally comes back from the database in the following format: 2002-01-01 00:00:00.0 That format is not very user-friendly. Calling DateFormat() with a mask of “mm/dd/yyyy” returns the date as follows: 01/01/2002 This version is, of course, more natural and easy to read. The same is true for the employee edit process...
