What is CF Script

an article added by: Johanna Schmidt at 04032008


In: Categories » » Programming » What is CF Script

One of the great things about ColdFusion is its easy-to-use, tagbased syntax. Having the capability to intersperse CFML and HTML tags without needing to open and close script blocks or needing to remember what syntax you’re currently working in is a wonderful thing. At times, however, using a scriptable syntax would be nice—for example, if you’re doing heavy data processing on a page. As nice as CFML’s tag-based syntax is, number crunching is best expressed in script. CFSCRIPT is a server-side scripting language that works with CFML to give you the best of both worlds: an elegant, tag-based syntax whenever you need it and a flexible scripting syntax if you don’t. User-defined functions are discussed later. We do not include them in this article because of ColdFusion MX’s capability to define UDFs by using either CFSCRIPT or CFML syntax. This article describes the basics of CFSCRIPT. Essentially, CFSCRIPT is an instruction to the ColdFusion processing engine to treat a block of code as scripting-based syntax rather than as tag-based syntax. Why mess with a perfectly good thing (CFML) by adding another complication (scripting)? Because the latter is easier to code and faster to process. Consider the following snippet, for example, which loops from 1 to 10, adding each index to a running total:

<cfset TheSum = 0>
   <cfloop from=”1” to=”10” index=”i”>
   <cfset TheSum = TheSum + i>
   </cfloop>

Following is the same code expressed in CFSCRIPT’s scripting syntax:

<cfscript>
   TheSum = 0;
   for(i = 1; i LTE 10; i = i + 1) {
TheSum = TheSum + 1;
   }
 </cfscript>

CFSCRIPT doesn’t support the ++ syntax for incrementing a variable that may be familiar to you if you have experience with Java, JavaScript, or C++. Look familiar? If you’re having JavaScript déjà vu, that’s normal, because CFSCRIPT is almost identical to JavaScript. CFSCRIPT blocks mostly instantiate variables and perform calculations, but they can produce output, too. Consider, for example, the following extension of the preceding code snippet:

<cfset TheSum = 0>
   <cfloop from=”1” to=”10” index=”i”>
   <cfset TheSum = TheSum + i>
   </cfloop>
   <cfoutput>#TheSum#</cfoutput>

Normally, anything that isn’t part of a CFML tag is output to the page. CFSCRIPT, however, uses a function named WriteOutput() for page output, as the following example shows:

<cfscript>
   TheSum = 0;
   for(i = 1; i LTE 10; i = i + 1) {
   TheSum = TheSum + 1;
   }
   WriteOutput(TheSum);
 </cfscript>

Think of WriteOutput() as the server-side equivalent of JavaScript’s client-side document.write() method. The difference between WriteOutput() and document.write() shows the different mindset of CFSCRIPT as compared to CFML. Rather than the text just “being there,” as it is in CFML, CFSCRIPT must be directed to output the text. Notice the use of semicolons, which terminate CFSCRIPT statements. CFSCRIPT is less forgiving than JavaScript with respect to semicolon termination; forget one, and ColdFusion throws an error. Another thing that you need to get used to in CFSCRIPT is the use of curly braces. Curly braces surround blocks of CFSCRIPT code similar to the way that opening and closing tags surround blocks of CFML code, but their use is actually more critical. A simple if construct in CFSCRIPT looks as follows:

<cfscript>
   if(this EQ that)
   doThis();
   else
   doThat();
 </cfscript>

The preceding snippet runs error free, but suppose that you need to add another statement after doThis(), as in the following example:

<cfscript>
if(this EQ that)
   doThis();
   doSomeOtherThingToo();
   else
   doThat();
 </cfscript>

ColdFusion throws an error, because it sees an else clause without a corresponding if clause. This happens because the doSomeOtherThingToo() statement is considered the continuation of statements after the if statement finishes executing the doThis() statement. For CFSCRIPT to execute both statements when the if tests TRUE, you must enclose them within curly braces as follows:

<cfscript>
   if(this EQ that) {
   doThis();
   doSomeOtherThingToo();
   } else
   doThat();
 </cfscript>

In fact, a best practice is to always include the curly braces, regardless of whether you need them or not, as in the following example:

<cfscript>
   if(this EQ that) {
   doThis();
   doSomeOtherThingToo();
   } else {
   doThat();
   }
 </cfscript>

Why? Because you never know when you’re going to add another statement to an existing if test. We can’t tell you how many times that we threw errors in the early days by adding a second statement to an existing, unenclosed if construct, simply because we didn’t pay attention to the enclosure mechanism. If you always enclose, you never throw errors. The same holds true for any language that requires such enclosure. All CFSCRIPT code is contained between CFSCRIPT tags, as shown in the following example:

... Regular CFML code goes here ...
   <cfscript>
   ... CFSCRIPT code goes here
   </cfscript>
   ... Regular CFML code goes here ...

Notice that the content of a CFSCRIPT block must be a complete statement. You cannot, for example, do the following:

<cfscript>
   if(myVar GT yourVar) {
</cfscript>
   My text goes here.
   <cfscript>
   }
 </cfscript>

That type of construction is valid in some other scripting languages, but not in CFSCRIPT. CFSCRIPT operations must be self-contained in a single code block, as follows:

<cfscript>
   if(myVar GT yourVar) {
   WriteOutput(“My text goes here.”);
   }
 </cfscript>

You can have several CFSCRIPT blocks in a single ColdFusion template, but each CFSCRIPT block must be a self-standing block of executable code. The simplest operation in CFSCRIPT is setting a variable, as follows:

<cfscript>
   myVar = 1;
 </cfscript>

Setting a variable in CFSCRIPT requires no CFSET tag, and the statement ends with a semicolon. You can now use myVar just as you would any other ColdFusion variable. Notice that you can share any variable between CFSCRIPT and regular CFML, as follows:

<cfset myVar = 1>
   <cfscript>
   myVar = myVar + 1;
   yourVar = 3;
   </cfscript>
   <cfoutput>#yourVar + myVar#</cfoutput>

You are not limited to setting and reading variables in the Variables scope, either. Any variable that you can set by using tag-based CFML can also be set by using CFSCRIPT’s scripting syntax. The if construct in CFSCRIPT works exactly the same as its CFML counterpart, CFIF. ColdFusion evaluates a condition and executes a dependant statement based on whether the condition is true or false. Compare the following CFML and CFSCRIPT if constructs:

CFML:

<cfif myVar GT yourVar>
... execute if true ...
 </cfif>
 CFSCRIPT:
if(myVar GT yourVar) {
   ... execute if true ...
   }

CFSCRIPT also has an equivalent to CFELSE, as the following example shows:

if(myVar GT yourVar) {
   ... execute if true ...
   }
   else {
   ... execute if false ...
   }

You also find an equivalent to CFELSEIF in CFSCRIPT, as follows:

if(myVar GT yourVar) {
   ... execute if true ...
   }
   else if (myVar EQ yourVar) {
   ... execute if true ...
   }
   else {
   ... execute if all conditions false ...
   }

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

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

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

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

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

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

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

6. 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, a...

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

8. 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, ...

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

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