Using a Custom Tag

an article added by: David Smith at 03222008


In: Root » Computers and technology » Programming » Using a Custom Tag

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

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 disclaimer

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.

related articles

1. 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...

2. 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...

3. Removing an Employee From the Database
The user must have the capability to remove employees from the database. The employee delete process is a simple combination of techniques that you have already learned, such as retrieving a record from the database, displaying that record in a template, and so on. The first page in this process is nearly identical to the employee get edit form. Create a file named EmployeeGetDeleteForm.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <html> <head> <ti...

4. Making direct links to the forms
Say that you want to modify or delete a company. Right now, you need to remember the company’s ID, go back to the launch pad, click Company Edit, and enter the company ID, all just to get to the edit form. Wouldn’t you rather click a company in the list and go directly to the edit form? ... <table> <tr> <td><b>ID</b></td> <td><b>Name</b></td> <td><b>Address</b></td> <td><b>City</b></t...

5. Creating your physical data model
Physical data models are extracted from their logical counterparts by mapping logical objects to physical objects supported by the target database platform. The following table shows the relationship between logical and physical objects. In many cases, your physical data model almost mirrors your logical data model because entities typically map directly to the tables that store them. Exceptions to this rule are logical data models that contain nonspecific relationships and entity subtypes. Although entity subtypes are an advanced top...

6. Understanding All Relational Result Sets
This article can help you better understand complicated SQL containing multitable joins, group-related clauses, and aggregate functions—by far the most problematic topics for most database developers. You also learn the correct way to handle database exceptions and incorporate them as actual functionality in your ColdFusion application. You learn, too, how to increase performance by caching queries in memory for fast access. You can memorize SQL clauses and Bachus-Naur forms until you’re blue in the face, ...

7. How and when to use Group by Having and Distinct
After learning how SQL works internally, you can better learn how to put the more complicated aspects of it to use. First we need to clarify the difference between GROUP BY and DISTINCT. Quite a bit of confusion exists over these two clauses, because they often produce the same query results but for very different reasons. In fact, GROUP BY and DISTINCT are not related in any way whatsoever. The GROUP BY clause produces as its intermediate work product a table of rows representing each group, and a sort of “invisible third dimen...

8. Query Caching
Query caching places the results of a database query into ColdFusion Server’s memory where it can be instantly retrieved without querying the database. Query caching is one of the most useful tools for enhancing performance in your ColdFusion applications; unfortunately, it is also one of the least used. A few caveats are involved in query caching, but all in all, it is a very straightforward technique to employ. You should consider caching only queries that fit the following criteria: The query has a significant ...

9. Views
It doesn't matter how many tables a relational join traverses, regardless of whether it contains a GROUP BY clause (or anything else for that matter), all query result sets manifest themselves as one or more rows that contain an identical collection of one or more columns. So, in a way, query results are virtual tables based on underlying physical tables of data. Now imagine if you could take a query statement and define it as a formal database object that could be accessed just as a table can. Well, you can—that is ...

10. Passing parameters by position rather than by name
Various documentation has mentioned that parameters may be passed to stored procedures in any order and that the binding that you specify by using DBVARNAME correctly maps Value attributes to their corresponding database variables, but this is not the case in practice. You should always pass parameters to stored procedures in exactly the same order as they appear in the stored procedure’s interface; otherwise, ColdFusion throws an exception. Many, but not all, database servers can return result sets from stored procedures. Fo...