|
For best results: this site requires that cookies be enabled for proper operation - see Legal Page for more info
|
|
Select Any of These |
COLD FUSIONLAST UPDATED: 08 March 2009 17:02:13 -0600 Translate this page
A HEX ON YOUR COLOR VALUES ADMIN ISSUES ALL FORM FIELD NAMES AND THEIR VALUES AVOIDING THE PLUS SIGN WHEN CONCATENATING TWO STRINGS BINARY OPERATORS--EQV BINARY OPERATORS--XOR CF Q&A #1 CF Q&A #2 CFINCLUDE, THE GREAT! CFMAIL--PART 1 OF 4 CFMAIL--PART 2 OF 4 CFMAIL--PART 3 OF 4 CFMAIL--PART 4 OF 4 CGI VARIABLES AND COLDFUSION CGI VARIABLES AND COLDFUSION, REVISITED CLIENT-SIDE VALIDATION: CFINPUT CLIENT-SIDE VALIDATION: DATES CLIENT-SIDE VALIDATION: FAST FEEDBACK CLIENT-SIDE VALIDATION: REQUIRED FIELDS COLDFUSION and MATH--FIX COLDFUSION and MATH--PIE, ER... PI COLDFUSION AND TIME COLDFUSION BASICS: USE THE # TAGS AROUND VARIABLES COLDFUSION IS SEVEN YEARS OLD COMMENTS PLEASE! CONTROL YOUR SESSION VARIABLES COOKIES FOR YOU! COOKIES HAVE A SIZE LIMIT COPY YOURSELF ON EMAILS CUSTOMIZED ERROR MESSAGES DESIGNER BEWARE! DEVELOPING YOUR OWN NOTIFICATION SYSTEM--PART 1 OF 2 DEVELOPING YOUR OWN NOTIFICATION SYSTEM--PART 2 OF 2 DIRECTORY MAPPINGS IN ADMINISTRATOR DISPLAY A PRETTY DATE ON YOUR PAGES DOMINATE YOUR SUBMIT BUTTONS DON'T USE PRIMARY KEYS AS FORM FIELDS DYNAMIC CLEAN OPERATIONS USING ONREQUESTEND.CFM EDIT TAGS IN STUDIO, THE EASY WAY ELIMINATING EXTRANEOUS WHITESPACE EMULATING A WORDS FUNCTION EXCLUDING POUND SIGNS IN HTML FORCING CUSTOM ATTRIBUTES IN CFINPUT FORM FIELD NAMING CONVENTION FORMAT THOSE NUMBERS WITH NUMBERFORMAT GET THE NAME OF THE CURRENT TEMPLATE IIF, MOD, AND ALTERNATING ROW COLORS: REVISITED IMAGES AS SUBMIT BUTTONS INCLUDING NAMES WITH EMAILS USING CFMAIL INTEGRATE NEWSFEEDS INTO YOUR SITE LOCAL INSTALL--PART 1 OF 4: SETTING UP COLDFUSION SERVER ON YOUR HOME PC LOCAL INSTALL--PART 2 OF 4: NEW NAME FOR THE LOCAL SERVER LOCAL INSTALL--PART 3 OF 4: THE BROWSE TAB AND DEVELOPMENT MAPPING LOCAL INSTALL--PART 4 OF 4: CONNECTING TO RDS VIA CF STUDIO NETSCAPE INCOMPATIBILITY WITH COLDFUSION SEARCHES ONLY ONE PACKAGE OF COOKIES FOR YOU ORDER YOUR REPORTS BY COLUMNS PARSING XML IN IE USING CFCONTENT PLEASE PASS THE QUERIES REMOVING INDENTATION IN CFMAIL CONTENTS RIGHT MARGIN INDICATOR IN STUDIO SAVE THOSE SINGLE QUOTES SECURE SERVER: USE HTTPS AND PASS VARIABLES VIA SESSION VARS SELECT BOX: FILL WITH PRIMARY KEY SERVE SOMEBODY SERVER-SIDE VALIDATION: DATE FIELDS SERVER-SIDE VALIDATION: INTEGERS SERVER-SIDE VALIDATION: REQUIRED FIELDS SET THE DATASOURCES AS APPLICATION VARIABLES SETTING APPLICATION AND SESSION VARIABLES SIMPLE SEARCHES WITH THE CONTAINS OPERATOR SPEED UP PROCESSING--USE QUALIFIERS FOR YOUR VARIABLES STICKING STRINGS TOGETHER STUDIO SHORTCUT: AUTOMATICALLY CLOSE QUOTES, POUNDS, AND MORE STUDIO SHORTCUT: JUMP TO A LINE NUMBER TABLE NAMES AND COLDFUSION THE META TAG THE POWER OF APPLICATION.CFM THE TIME BETWEEN DATES TO COMMENT OR NOT TO COMMENT TOO MUCH WHITE SPACE URL PARAMETER RULES--PART 1 OF 2 URL PARAMETER RULES--PART 2 OF 2 URL PARAMETERS 101 URL PARAMETERS--PASSED INFO USE APPLICATION VARIABLES FOR EMAIL USE MAXLENGTH TO GET THE MOST FROM FORM FIELDS USER-TOGGLED COOKIE SETTING USING CFSCRIPT TO DECLARE MULTIPLE VARIABLES USING THE MOD FUNCTION TO ALTERNATE ROW COLORS VALIDATE YOUR DATABASE CONNECTION VALIDATING DATA: SERVER-SIDE OR CLIENT-SIDE VALIDATION VALUELIST() AND RETURNING A COMMA-DELIMITED RECORDSET VARIABLE TYPES IN COLDFUSION--PART 1 OF 2 VARIABLE TYPES IN COLDFUSION--PART 2 OF 2 WATCH OUT! LOST DATA ON CFUPDATE AND CFINSERT WHEN EQUALS ARE NOT
A HEX ON YOUR COLOR VALUESHave you ever tried to include a particular color hex value in your code but ColdFusion was unable to recognize the value? Ever wondered why you could only write actual color names (for example, "red, blue")? Well, the mystery error usually occurs when you try to put a "#FFFFFF" value within a CFOUTPUT tag. ColdFusion tries to read the # as one of the output fields. To work around this problem, just place double # signs in your code. Here's an example: <td bgcolor="##FFFFFF"> This will allow you to specify colors within your CFOUTPUT tags.
ADMIN ISSUESHaving problems accessing your ColdFusion Admin page? Here are two solutions that might help: First, right-click the Admin icon on the Start menu and you will see what address has been defined for this connection. Check that address to make sure you're trying to read the right Web host. Second, make sure that the link from which you are going to the admin page is correct. For example, I recently had a problem where this URL would not work (on an NT machine): http://127.0.0.0/CFIDE/Administrator/index.cfm but the following would work: http://localhost/CFIDE/Administrator/index.cfm As you can see, there is a subtle, but crucial, difference between the two URLs.
AVOIDING THE PLUS SIGN WHEN CONCATENATING TWO STRINGSAttempting to concatenate strings is a common mistake among developers. ColdFusion, like many other languages, treats the plus sign (+) differently than the ampersand (&). Although you might think the plus sign would add two strings, in reality strings can't be mathematically "added" together. Therefore, be sure to always use the ampersand when concatenating strings and the plus sign when adding numeric data. Although this may seem obvious, you'd be surprised how many times this mistake is made. Here is an example: <CFSET NewString = "This is " & "a concatenated string.">
BINARY OPERATORS--EQVColdFusion has several binary operators inherent in its toolset. EQV, or equivalence, returns True only when both variables have the same value--either when both are true or both are false. Here's a logic chart that makes sense of this: A/B A eqv B T/F False
BINARY OPERATORS--XORColdFusion has several binary operators inherent in its toolset. XOR, or an exclusive OR, returns True only when one of two expressions are true--not when both are true. Here's a logic chart that makes sense of this: A/B A xor B T/F True
CF Q&A #1A subscriber recently asked, "How can I launch an external application from ColdFusion Studio/Homesite?" The simplest way to launch an external application is to create a custom toolbar in your ColdFusion Studio Quickbar. (Yes, the Studio toolbars are highly customizable!) Custom buttons can insert your own text, display custom dialog boxes, and even launch external applications. For example, let's suppose you'd like to be able to open the files you are working on in Notepad. Here's how to add the custom button to your toolbar: Start by right-clicking the Quickbar and selecting Customize. Then, on the Toolbars tab, select the toolbar to which you'd like to add the button. (That toolbar will then be displayed). Now click Add Custom Button and, in the Custom Toolbutton dialog box, select Launch An External Application. In the resulting window, type or browse to the filename of the app you want to open. (In this example, we use C:\Windows\Notepad.exe.) Now, to tell Studio to open the currently active document in the external program, type %CURRENT% in the Command Line text box. Also, if you'd like your button to have a pop-up hint when the cursor hovers over it, type that hint in the Button Hint box. When you're done, click OK, and then click Close. You'll now see the Notepad icon on the toolbar you chose. Click that icon to open the current document in Notepad!
CF Q&A #2A reader recently asked, "How do I get a list of tables contained in my Microsoft Access database?" Actually, you can do this with some simple SQL. The following query will return an alphabetically sorted list of tables contained in your Microsoft Access database. <cfquery datasource="myDatasource" name="GetTables">
CFINCLUDE, THE GREAT!One of my favorite functions of the CFML is the mighty CFINCLUDE tag. CFINCLUDE allows you to include the contents of another template into the one being processed. No big deal? Check this out! Let's say you've created a site using static HTML and the site consists of well over 100 pages. You've finished the project and notice that you misspelled your email address in EVERY footer of EVERY page. In this case, you would need to correct your email address ON EVERY SINGLE ONE OF THOSE PAGES. You would not be a very happy camper, now would you? Had you created the site in ColdFusion and used the CFINCLUDE tag, you would be able to correct ONE file, thereby correcting the error on every page that calls the template. Okay, so you've got your 100 pages: Now all you need to do is create a single template that contains your footer info. At the end of each page, you add a <CFINCLUDE> tag, calling your footer.cfm file: <CFINCLUDE TEMPLATE="footer.cfm> Now, every page will display the same footer information--and you can make changes that will display on every page by making them in the footer.cfm template.
CFMAIL--PART 1 OF 4The CFMAIL tag is very useful when you want to automatically send a message based on user input. (Of course, you must first make sure the Web server is configured to send email prior to using CFMAIL.) With CFMAIL you can use a database table to store email addresses and other information to put into an email message. Here's how the code might look: <CFMAIL TO="email" message text, can be CFML and HTML tags. </CFMAIL> Next time, we'll examine all those attributes.
CFMAIL--PART 2 OF 4Here's an explanation of the CFMAIL attributes: TO--Email address of addressee.
CFMAIL--PART 3 OF 4Now that you're familiar with the various CFMAIL attributes (see the previous tip), let's take a look at how you might send mail using ColdFusion. For starters, here's the code to send a simple mail message to CFINFO@email.com: <CFMAIL TO="CFINFO@email.com" This is a sample email. </CFMAIL> To make more complex messages, you simply insert the appropriate CFMAIL attributes. For example, here is an example of CFMAIL with an attachment (this code attaches file.txt to the email message): <CFMAIL TO="CFINFO@email.com" Here is the attachment. </CFMAIL>
CFMAIL--PART 4 OF 4In this series, we've been looking at ways to use CFMAIL to send email. Here, then, is a final example of CFMAIL, which includes a query. The following sample code would send an email to the recipients and let them know if their room is confirmed. If theroom is confirmed, the recipient would also see a reservation number. <CFMAIL TO="#Email# FROM="#Form.Name#" <CFIF #title# is "Mr"> Your hotel room is #Confirmed#.<br> Thank you for selecting our hotel. </CFMAIL>
CGI VARIABLES AND COLDFUSIONCGI variables, those nice nuggets of info you can poll to find information about the client's state, are read-only. You cannot change them, even with CFSET.
CGI VARIABLES AND COLDFUSION, REVISITEDNot all CGI variables are going to have values when you check them in ColdFusion. You may find that a particular variable may be at times set to an empty string value. This is because different server/browser combinations support different variables. If a particular combination doesn't support a variable, ColdFusion sets that variable's value to the empty string.
COLDFUSION and MATH--FIXFor you arithmetic buffs out there, try this function on for size. Fix() returns the integer portion of a number closest to 0 (zero). For example: FIX (4.2) yields 4 FIX (-7.9) yields -7 FIX (5.6) yields 5 FIX (-23.1) yields -23 FIX (3) yields 3
COLDFUSION and MATH--PIE, ER... PIFifteen slices of pie--nice and fattening. How about something a little lighter, like 15 digits of pi? ColdFusion's PI() function returns the "constant accurate" to a 15-digit mantissa. So, for example, if you wanted to print the value of pi, you'd use <CFOUTPUT> is equal to #PI()# </CFOUTPUT>
COLDFUSION AND TIMEDid you know that if you don't specify a value for the time portion of a date/time value, ColdFusion defaults the time to 12:00 a.m.? Maybe this helps explain why some of your date queries may not return the results you expected, eh? For example, a test such as <CFIF NOW() gte "11/25/01"> is actually comparing NOW() against 11/25/01 midnight.
COLDFUSION IS SEVEN YEARS OLDDid you know that ColdFusion was launched in 1995? Since then, it has gained major acceptance in Fortune 500 companies. While the exact count is still unknown, some reports say half of the Fortune 500 are using ColdFusion in some capacity.
COMMENTS PLEASE!Commenting your code is an important part of Web development. Not only does it help others understand your work, but when you go back to maintain and/or edit your own code, comments are a great reminder of what you did and why. ColdFusion comments are similar to HTML comments: You create an HTML comment by surrounding the comment with <!-- and -->. HTML comments contain two dashes on each side of the comment block. You create CFML comments with similar tags, but you use at least three dashes instead of two: <!--- CF comment. --->
CONTROL YOUR SESSION VARIABLESSession variables, those wonderful vars tied to each user's session, are great for keeping track of such information as username, logged-in status, and so on. Best of all, the session vars time out automatically so you don't have to clean them up to release the memory. As the ColdFusion Administrator, you set the default timeout used by session variables. Suppose, though, that you're not sure what the length of the timeout variable is or that you want a value different from the default. You can set the default session timeout variable for your application in the Application.cfm file using the SessionTimeout setting. The following line from an Application.cfm file tells ColdFusion to use session management and to set the timeout to one hour and 30 minutes. <CFAPPLICATION SESSIONMANAGEMENT="Yes" SESSIONTIMEOUT="#CreateTimeSpan(0,1,30,0)#">
COOKIES FOR YOU!Don't be afraid of cookies. They are read like any other Var. In fact, they can be set using this simple bit of code: <CFSET cookie.cName = "some value"> Here, then, is an example of the code in action: <CFSET someVar = cookie.cName> <CFOUTPUT>
COOKIES HAVE A SIZE LIMITYou've seen the big smiley-face, 16-inch cookies that are coated with icing and are oh-so-healthy for you. Perhaps you've even ingested a few yourself. Unlike the baker who can make cookies as large as he needs (or as large as her largest pan), cookies have a limit to them. A single cookie has a 4-KB limit to it, including the cookie's name, value, expiration date, and so on. While 4,096 characters is a lot of data to store in a cookie, perhaps you temporarily store URL parameters or some such data. If that's the case, keep this limit in mind--it could save you some grief tracking down what appears to be an otherwise obscure bug.
CUSTOMIZED ERROR MESSAGESThe CFERROR tag allows you to write your own error messages. If ColdFusion sees trouble and processes the CFERROR tag, instead of using the default CF error messages, you can either present the user with your own customized message or call a template that corrects the error. The following example calls a template that contains your error message, which will override the standard CF error message: <CFERROR TYPE="REQUEST" NAME="ERROR_REQUEST.CFM MAILTO="webmaster@mypage.com> And here is an example of a REQUEST ERROR TEMPLATE: <HTML> That's it! Oh yeah, the MAILTO attribute will notify the administrator of the error message.
DESIGNER BEWARE!Have you ever clicked on the Design tab in ColdFusion Studio, just to remind yourself of how pretty the front-end of your pages look? Well, don't! The Design feature, although very helpful in constructing the look and feel of your pages, can be poison to the back-end. It's known for stripping code from pages as well as altering it. I recommend you disable this feature altogether. To do so, press the F8 key to launch the Settings dialog box. Next, select the Design tab (v4.0) or Tree (v4.5). Then, click the Disable (Hide) Design Tab check box.
DEVELOPING YOUR OWN NOTIFICATION SYSTEM--PART 1 OF 2Are you curious whether the fancy page on which you spent hours working is getting any use? Well, how would you like to email yourself whenever the page is loaded? It's simple to do, using CFMAIL. Just include a short CFMAIL tag similar to the following:
</cfmail>
DEVELOPING YOUR OWN NOTIFICATION SYSTEM--PART 2 OF 2In our previous tip, we showed you how to rig a page to email you whenever it is viewed. But what if you want to notify more than just yourself? When there are several people who should be notified of a particular event on your site, you could use CFMAIL and hardcode a list of addresses in the CC option. However, if someone changes email addresses or leaves the company, you must in turn change all the instances of that individual's email address throughout your code--not a good thing. A better method to employ in this case would be to create a dummy email address on your email server, include a list of folks to whom that email address automatically forwards mail, and then use that dummy email address in your code. Using this method, you'd have to change the list of recipients only once. For example, suppose you need to send email to four people within your organization whenever a new donor signs up on your site. Create a dummy email address such as DonorNotify@charity.com that automatically forwards email to
<CFOUTPUT>
DIRECTORY MAPPINGS IN ADMINISTRATORColdFusion Administrator lets you create shortcuts, or mappings, to directories on your Web server. You can then use these mappings in your code. Open ColdFusion Administrator and click the Mappings link in the left navigation frame. ColdFusion Administrator then shows you the current mappings. (You'll notice the slash (/) is probably mapped to your root Web directory.) You can create additional mappings here as well. Suppose you want to set up things so that instead of typing a complicated directory structure reference to get to an image's repository, like this: D:\inetpub\wwwroot\theMainSite\Images you can simply enter the string /myimages/ every time you need to refer to the directory. From the Add New Mapping page, you enter /myimages/ in the Logical Path text box, then enter the desired directory string in the Directory Path text box. Don't forget to click the Add Mapping button to apply your new mapping.
DISPLAY A PRETTY DATE ON YOUR PAGESYou can use the following code to display a date in the oh-so-user-friendly format "Monday, February 7, 2000": <cfoutput>#DateFormat(Now(), "dddd, mmmm d, yyyy")#</cfoutput>
DOMINATE YOUR SUBMIT BUTTONSCan you use two submit buttons on one page? Sure! The critical aspect to using multiple submit buttons is to give each button a different name. Then, use <ONCLICK> to call a JavaScript function that checks the name of the button and changes the action attribute of the form accordingly. Example: <script language=Javascript> <input type="submit" name="submit1" value="[Caption]"
onclick="return
DYNAMIC CLEAN OPERATIONS USING ONREQUESTEND.CFMChances are you know about the Application.cfm file, appended to the top of every script. But did you know that the ColdFusion 4.01 upgrade introduces a new, similar, special file? It's called OnRequestEnd.cfm, and as you might have guessed, it's appended to the END of any script that executes in full. (If a CFABORT is encountered in the script, the OnRequestEnd.cfm is not appended.) With this functionality, you can now include dynamic cleanup operations. Perhaps you want to revert database transactions that are identified as incomplete, or reset variables--whatever it is you want to do, OnRequestEnd.cfm makes it possible.
EDIT TAGS IN STUDIO, THE EASY WAYColdFusion Studio is the development environment of choice for ColdFusion developers, because it contains tons of useful features designed to make coding more efficient. One of the lesser-known features is the Tag Editor, which allows you to add or edit any tag attribute simply by filling in its value, see which attributes are required when using a given combination, and more. To access the Tag Editor, right-click in any tag and select Edit Tag. Tag Editor also includes a button to toggle embedded tag documentation, available when editing most ColdFusion custom tags. This option is accessible as a small icon above the Cancel button. Another more basic alternative is to select the Tag Inspector (the little magnifying glass icon) in the Resource tab. This option conveniently shows the available attributes and allows you to edit each or select from a list (for attributes with predefined values).
ELIMINATING EXTRANEOUS WHITESPACEIf you've ever viewed the source of a page dynamically generated by ColdFusion, you probably saw a lot of extra blank space, otherwise known as whitespace. The reason for this is that ColdFusion, by default, outputs anything you type that's not contained within a CF tag. For example, if you type a string, save it as a CFM file, and run it, you'll see that string outputted. Likewise with a bunch of carriage returns--you'll note the carriage returns when you view the output. If you want to limit output to only what you explicitly place in CFOUTPUT tags, you can use the ENABLECFOUTPUTONLY parameter of the CFSETTING tag. Set this parameter to Yes at the top of the script, then back to No at the very bottom. Here's an example: <CFSETTING enablecfoutputonly="yes">
EMULATING A WORDS FUNCTIONAlthough ColdFusion provides many string functions, one common one that isn't offered is a "words" function, to count the number of words in a string. This can be easily emulated using this code: <cfset words = ListLen("string to count", " ")> For the above CFSET, "words" would be set to 3. Pretty nifty!
EXCLUDING POUND SIGNS IN HTMLAs you know, ColdFusion treats the pound sign (#) as a special character. In HTML, color codes in FONTS and other tags are preceded by a pound sign (for example, #ffffff). If this HTML code is encased in a CFOUTPUT tag, ColdFusion will choke with an invalid parser construct error. In these cases, you could tell ColdFusion to treat the sign as a literal pound by inserting an additional one (##), but I've found it easier to simply exclude these pound signs when writing my HTML. The browsers I've tested on don't seem to care if the pound sign precedes the color code, making life easier and minimizing chances of errors in my applications.
FORCING CUSTOM ATTRIBUTES IN CFINPUTIf you've ever used ColdFusion's CFINPUT tag in place of a standard HTML INPUT tag, you probably did so because it offers powerful features, such as client-side validation, with minimal coding. This functionality does, however, come with sacrifices: Say you want to add more attributes to the resulting INPUT, perhaps to add a custom JavaScript event or to specify a Cascading Style Sheet to apply to the control. In this case, ColdFusion will choke, informing you that you attempted to include an attribute that isn't recognized as part of the CFINPUT tag. This is often reason enough for many developers to shy away from this tag and use a standard HTML INPUT instead. Don't! Here's a workaround: Whatever you include within the quotes of a given attribute, ColdFusion accepts as that attribute's value. With this in mind, you can make use of the Chr() function to simulate a quote, without actually including it in the ColdFusion code. You therefore avoid ending that attribute, at least according to ColdFusion, and ColdFusion doesn't choke. Still doesn't make sense? This tip is better explained by looking at an example: <cfinput type="text" name="MyInput" value="MyValue#Chr(34)# Note that I only included the following string as the value of the VALUE attribute: MyValue#Chr(34)# onKeyUp=#Chr(34)#MyJavaScriptFunction(this) ColdFusion accepts this value, then proceeds to evaluate the Chr() functions, which contains the ASCII code for a quote. The resulting output is: <input type="text" name="MyInput" value="My Value" onKeyUp="MyJavaScriptFunction(this)">
FORMAT THOSE NUMBERS WITH NUMBERFORMATColdFusion's NumberFormat() function provides a variety of ways to display numbers. You can use combinations of 12 different masking characters to format your numbers. This could come in handy if you're trying to align decimals, pad with zeroes, or perhaps include a minus sign in front of negative numbers. Here's one example of NumberFormat in action:
IMAGES AS SUBMIT BUTTONSAs a ColdFusion programmer, you probably deal with a lot of Web forms and, as a result, a lot of submit buttons. If that dreary standard gray submit button is getting boring, spice up your forms by turning that button into an image. To do this, simply write your image HTML code as you normally would, but start it as an INPUT tag with a type of "image". Leave all the other image attributes in place. When placed inside form tags, an image created in this manner will replace the submit button, so clicking the image will submit the form data. Keep in mind that with images you have more flexibility, too. For example, you can add JavaScript to cause the button to change on mouseover. Pretty cool, huh? Your visitors will like it, too. Substitute this for your form's submit button: <INPUT TYPE="IMAGE" SRC="/graphics/submitbutton.gif" BORDER=0>
INCLUDING NAMES WITH EMAILS USING CFMAILThe manner in which ColdFusion accepts the inclusion of names with an associated email address can be a bit confusing--despite the fact that this standard email functionality is really useful when personalizing emails. To include a name with an email address in ColdFusion, include the name in parenthesis, as follows: <CFMAIL FROM="jon@smith.com (John Smith)" "TO="members@mylist.com
(List Members)" SUBJECT="List Mailing">
INTEGRATE NEWSFEEDS INTO YOUR SITEIf you maintain a Web site and want to offer news headlines and articles for your readers, you've got to check out this Web site: Moreover provides newsfeeds in a multitude of formats that can easily be integrated directly into your site. It even has a feed exclusively for ColdFusion developers, delivered in WDDX format. Use the CFWDDX and CFHTTP tags to populate your Web site with fresh daily news headlines from hundreds of categories. Unfamiliar with CFWDDX and CFHTTP? Stay tuned--we'll discuss the two separately in future tips.
INTRO TO CFCATCHColdFusion provides a method for trapping errors within a block of code. Using CFCatch, you tell ColdFusion to trap any errors that might occur, then based on the type of error, perform the appropriate actions that you've programmed via code. A nice feature about CFCatch is that it automatically fills a structure with the error and the error details. You can decide to show these to the user and can format them so the error displays gracefully. We'll cover CFCatch in more detail later. For now, let's suppose that CFCatch caught an error for you, and you want to display the message and the error code in a nicely formatted table. Here's a sample of the code you might put within the CFCatch block:
LOCAL INSTALL--PART 1 OF 4: SETTING UP COLDFUSION SERVER ON YOUR HOME PCWe mentioned in a prior tip that you can install ColdFusion Server on a local machine running something like Windows 98 or NT Workstation. To do so, you need to install a Web server such as Personal Web Server or another type that will run on these platforms. (We're not covering UNIX flavors here, so don't flame us, okay?) Once your personal Web server is running, you can then install ColdFusion Server from the CD. It will recognize that you're running a personal Web server and install appropriately. However, you may then wonder how to refer to your site in order to run ColdFusion Administrator. The local host is always referred to like this: http://127.0.0.1 This being the case, to run the local ColdFusion Server Administrator, you enter http://127.0.0.1/cfide/administrator
LOCAL INSTALL--PART 2 OF 4: NEW NAME FOR THE LOCAL SERVERWe've mentioned that you can refer to your local Web server installation as 127.0.0.1. But that gets old, doesn't it? You'd probably prefer a nice name you can type instead of another IP address, right? Well, it's easily done. Using Windows' Find command, perform a search for the file named Hosts. Your results may yield a file in the Windows directory named hosts.sam. Make a copy of this file and name it hosts without the extension. (Of course, if you already have a non-extensioned hosts file, don't copy it.) Now, edit the file and underneath the line 127.0.0.1 localhost enter 127.0.0.1 Mysite where Mysite is the name by which you wish to refer to your site. Now, you can enter http://mysite to get to your own local copy of your site.
LOCAL INSTALL--PART 3 OF 4: THE BROWSE TAB AND DEVELOPMENT MAPPINGColdFusion Studio allows you to see the effects of your code almost immediately via the Browse window. You access this window by clicking the Browse tab next to the Edit tab (which is the main code-editing window). To view the results of your code changes, however, you need to set up a proper development mapping, which tells Studio on what server the code you're editing resides. To do this, you'll first have to open the Development Mappings window: You can click the icon at the bottom of the screen; choose Debug, Development Mappings from the main menu; or simply press Alt-M. Next, click the Mappings tab, then click the folder icon next to the Studio Path text box to open a Select Directory window. Find the proper directory that contains your code, then click OK to return to the Mappings window. ColdFusion Studio should automatically fill out the other two text boxes. Now when you're editing a piece of code stored in the mapped directory and you click the Browse tab, you should see the results just as if you'd opened the code page in a browser.
LOCAL INSTALL--PART 4 OF 4: CONNECTING TO RDS VIA CF STUDIOTo set up ColdFusion Studio's Remote Data Services (RDS) feature with a local install, you follow the same procedure as if you were setting up RDS for a remote server. However, you must specify the server you're connecting to as 127.0.0.1. Start by selecting the Remote Files icon (it looks like a globe behind a PC) from the icons at the bottom of Studio's Filelist window. Then, right-click in the top window of that frame and choose Add RDS Server from the shortcut menu. You should now see the Configure RDS Server window. In this window, enter localhost as the description 127.0.0.1 as the Host name, and then your ColdFusion Studio username and password. Now, you can use Studio's Remote Files and Database tabs to view the information on your Web site.
MY LOGIN PAGEHere is a quick and easy way to create a username/password-protected login page: Start by developing your page so that it uses a form to pass the login name and password to a cfm page. Then, ColdFusion can compare the passed data with the data (login and password) in your database. If both username and password match, you allow the user to access the site. If not, you deny them access.
NETSCAPE INCOMPATIBILITY WITH COLDFUSION SEARCHESNot able to generate your ColdFusion search results in Netscape, but they work fine in Internet Explorer? The problem probably lies with the hidden fields at the beginning of the form--specifically, they have no specified value. IE handles this differently from Netscape, so I suggest you change these fields to include a value, thereby enabling it for both browsers: <INPUT TYPE="hidden" NAME="connect" VALUE="">
ONLY ONE PACKAGE OF COOKIES FOR YOUMmmmm . . . cookies. Chocolate chip cookies and ice cold milk make the perfect dessert, in my opinion. I can eat an entire package of cookies given enough milk. However, a browser likes only a certain number of cookies, which is why there's a limit to them. A server can set a maximum of 20 cookies. Newer cookies from the same server overwrite the older cookies, so there's a constant rotation if the 20-cookie limit is reached. Now, if you really need 20 cookies, you might rethink the way your application tracks its data. But, for those of you who really need those 20, you're probably darn glad to know that you'll continually lose the oldest to the newest.
PARSING XML IN IE USING CFCONTENTInternet Explorer 5.0 and above has an XML parser engine built in. If your ColdFusion application returns XML to the browser, you can cause its integrated engine to parse, properly format, and color-code the XML output. Just use CFCONTENT to tell the browser that you're passing XML data to it. Here is an example: <CFCONTENT TYPE="text/xml">
PLEASE PASS THE QUERIESHave you ever needed to pass a query to another page or make a single query accessible to several pages? You can, of course, do this using session variables. Suppose we performed a query called GetEmployees. To assign that query to a session variable, execute a statement like this: <cfset session.PassedQuery = GetEmployees> Then, in an action page or some other page in which you want to refer to that query, execute code similar to the following:
{output the information}
QUOTES AND DE()As you've probably discovered yourself, quotes can be a pain during processing. ColdFusion helps out by providing a function that lets you Delay Evaluation: DE(). Basically, what it does is wrap the string in double quotes with any quotes in the string escaped. Suppose you want to display to the user a string wrapped in quotation marks. You can quickly and easily do so by including in your code something similar to the following:
REMOVING INDENTATION IN CFMAIL CONTENTSWhen using CFMAIL to automatically generate and send outgoing mail from ColdFusion, bear this in mind: If your CFMAIL tag is nested within a conditional statement or other block of code, you're probably following good coding style and indenting your code. When it comes to CFMAIL, however, don't indent its contents! If you do, the resulting mail will include the indentation, which typically you don't want. The following code demonstrates both the wrong way and the correct way, respectively, and is pretty much self-explanatory: <CFIF MyVar is "yes">
RIGHT MARGIN INDICATOR IN STUDIOWhile it's not always possible, programmers should generally limit how far their code extends on one given line. Many programmers use editors that make it hard to scroll horizontally, or automatically wrap and don't scroll at all. To accommodate them (and to keep your code clean and readable), it's a good practice to limit each line to around 80 characters. ColdFusion Studio has a neat feature which, when activated, will display a thin, non-obtrusive line at a specific character position, which can serve as a reminder for when to break to the next line. To activate this feature, select Options, Settings, then click the Editor tab. Check the Visible Right Margin At Column option and specify a character position.
SAVE THOSE SINGLE QUOTESThere are times when you need to include single quotes in lists, but if you've experimented with single quotes, you've probably found that ColdFusion likes to try to interpret them, thereby wreaking havoc on your well-planned code. For example, you may need to use a list, which in turn contains items with single quotes, as part of a qualifier for a SQL query. How do you do it without bombing your code? Use PreserveSingleQuotes. This function preserves the single quotes in items such as lists when ColdFusion is performing calculations on the code. Here's an example:
<CFQUERY NAME="Recipes" DATASOURCE="Cookery">
SERVE SOMEBODYA key part of the ColdFusion puzzle is getting a Web server up and running. If you don't have a Web server, just point your browser to http://www.microsoft.com/ie/pws/ and download Microsoft Personal Web Server. It will run on most versions of Windows and serves as a great standalone platform.
SIMPLE SEARCHES WITH THE CONTAINS OPERATORColdFusion has a really handy operator called CONTAINS. It accepts a string to be searched (on the left) and the string to search for (on the right). When you use this operator properly, you can perform simple search operations, rather than using more sophisticated string manipulation. Here is an example: <CFSET myString="This is my test string."> The above example would, of course, report that the second string is contained within the first string. It's a good function to remember, because it's much quicker and easier than using string functions.
SPEED UP PROCESSING--USE QUALIFIERS FOR YOUR VARIABLESColdFusion Markup Language, like other languages, uses an internal table to keep track of its variables. Since you can have so many types of variables in ColdFusion, it makes sense to use qualifiers to tell ColdFusion exactly which type of variable you're referring to. For example, if you simply make a statement like <CFSET TempVar = cName> it's not clear exactly which cName you're referring to--the form field, the variable declared earlier, or another. ColdFusion will assume it's a local variable, which may or may not be what you want. To find cName, ColdFusion must search its tables to find the value and then assume which value you want. This takes processor time (granted, in mere milliseconds) that could be attributed to processing other requests. To eliminate this unnecessary waste, preface each of your variables with one of the following: FORM for form variables
STICKING STRINGS TOGETHERThe method of sticking strings together, also known as concatenation, in many programming languages is generally accomplished using a plus sign (+). In ColdFusion, however, you use the ampersand (&). If you use the plus sign, you'll get an error. So, to stick two vars together, you'd perform something like this: <cfset name= #Firstname# & " " & #LastName#>
STUDIO SHORTCUT: AUTOMATICALLY CLOSE QUOTES, POUNDS, AND MOREOccasionally, our tips have focused on various shortcuts in ColdFusion Studio--shortcuts that can greatly increase your speed and productivity. Here, then, is our latest timesaving tip: ColdFusion Studio, by default, closes commonly used CF and HTML tags. Did you know you can close pound signs, quotes, and comments, too? Select Options, Settings, then click the Tag Help tab and click the Settings button under Tag Completion. In the resulting window, you'll be able to dictate exactly which characters ColdFusion should complete. You can also use this dialog box to define specific tags Studio should or should not complete.
STUDIO SHORTCUT: JUMP TO A LINE NUMBEROccasionally, our tips have focused on various shortcuts in ColdFusion Studio--shortcuts that can greatly increase your speed and productivity. Here, then, is our latest timesaving tip: ColdFusion Application Server references the line number when reporting errors--which is just one reason today's shortcut is useful: When in ColdFusion Studio, you can press Ctrl-G and then enter a line number to immediately jump to that line of code. Of course, the longer your script, the more useful this feature.
TABLE NAMES AND COLDFUSIONHere's a quick tip which, as simple as it is, can save you a lot of grief: ColdFusion doesn't like spaces in table names. So don't use them. Ever.
THE META TAGThe HTML META tag can be extremely useful. It can be especially handy if a page on your site has been moved or your domain has changed and you'd like to redirect the visitor to another URL. To do this, just create a standard Web page to tell visitors that your page or site has moved and that they will be redirected. Then, in between the HTML TITLE tags, place the following code: <meta http-equiv="refresh" content="30; URL=http://www.yoursite.com/"> This will allow your redirect page to be displayed for 30 seconds before redirecting the user out to the new URL.
THE POWER OF APPLICATION.CFMIf you haven't been using an Application.cfm file in your applications, you're missing out on the enormous amount of flexibility and modularity it can offer. By definition, the Application.cfm file, if it exists, is appended to every script contained within the same directory and all subdirectories, and all code in it is executed prior to executing any scripts. With this functionality comes many possibilities: validating the user before allowing entry, preparing a database collection, appending to a log, setting global variables for use throughout your application, and much more. With the ability to define variables in the Application.cfm file, you can set common variables used globally throughout your application. Say, for example, you specify login credentials for querying a database. What if those change? You have to modify the username and password everywhere you performed a query operation in your code. Not if you specified those global variables in Application.cfm! Once defined, they can be used just like any other variables. OOPS!... In some versions of the recent tip entitled AVOIDING THE PLUS SIGN WHEN CONCATENATING TWO STRINGS, we inadvertently munged the sample code that showed the difference between (&) and (+). Here, then, is the corrected example: <CFSET NewString = "This is " & "a concatenated string."> <CFSET NewNumber = 1 + 9>
THE TIME BETWEEN DATESLooking for a quick and easy way to determine the amount of time between two dates? Check out ColdFusion's DateDiff function. This powerful little tool shows you the difference between two dates using any one of ten calculations, all in one function! Want to know the difference in years? Use
TO COMMENT OR NOT TO COMMENTDid you know that you might inadvertently provide your site's visitors with comments and clues to your coding scheme, inviting bugs at the same time? That's because HTML comments, which take the form <!-- comment text here--> don't work very well in CFML. ColdFusion will interpret and execute code within HTML comments--which means that any text meant as true comments will be user-viewable in the View Source option of the browser.
TOO MUCH WHITE SPACEWhether or not you've noticed, a server may sometimes add miles of white space to a Web page. That's because it adds a blank line for every CF tag that's processed but not shown. Try the following (at the beginning of the document): <CFSetting enableCFOutputOnly="yes"> [content, tags, etc.] <CFSetting enableCFOutputOnly="no"> But be careful! This code will display ONLY content appearing between the <CFOutput> and </CFOutput> tags. That goes for anything you might CFInclude into the page as well.
TRACKING YOUR USER'S IPIf you capture your user's IP address using the CGI variable Remote_Addr, you can display the IP using code similar to this: Your IP is #cgi.remote_addr# Of course, you can assign this variable using CFSET, or store it in a table. Treat it just like any other type of variable, in other words.
URL PARAMETER RULES--PART 1 OF 2In the past, we've covered a slew of information about URL parameters. Now, we're going to aggregate some of the rules related to these handy variables, so keep this one (and our next tip, too) handy for quick reference: * Whenever you include multiple variables in a URL parameter, you must separate the name/value pairs by an ampersand (&). For example: http://www.myserver.com/mypage.cfm?yourname="Micah"&youranswer="test" * Whenever you include URL parameters, you must include the
question mark (?) as a separator between the parameter portion and
your URL.
URL PARAMETER RULES--PART 2 OF 2In the past, we've covered a slew of information about URL parameters. Now, we're going to aggregate some of the rules related to these handy variables, so keep this one (and our previous tip, too) handy for quick reference: * If you're using ColdFusion variables in your parameters, you must
surround the variables with pound signs, just like in regular
ColdFusion code.
URL PARAMETERS 101URL parameters are great for passing information between pages--well, if you don't mind the users seeing that information. However, some characters are illegal in URL parameters. Spaces and a few other characters will break the URL parameter string if they're included in a variables value. You can ensure that your parameter strings are always valid if you wrap each value with the URLEncodedFormat function. This function translates the illegal characters into their URL-friendly (albeit cryptic) hexadecimal equivalent. (Ever seen those %20s in some URL strings?). Use it like this:
URL PARAMETERS--PASSED INFOWant to trap parameters your users might pass to your pages via URL variables? You can capture the CGI variable Query_String and pass it along to other pages, store it to another variable, or do whatever else you might want to do with a string. To display the passed parameters, try code similar to this: You passed the following to this page: <br><br>
USER-TOGGLED COOKIE SETTINGHere's a quick way to set a cookie's expiration date based on whether the user wants to be remembered. Ask the question via a check box that says Save my information for return visits and name the check box SaveMyInfo In the subsequent action page, include code similar to this:
<CFCOOKIE NAME="SaveMyInfo" VALUE="TRUE" EXPIRES="#Expires#">
USING CFSCRIPT TO DECLARE MULTIPLE VARIABLESIf you've ever had the need to declare multiple variables, you've probably gone ahead and individually declared them in CFSET tags. Did you know that you could have simply declared all the variables within one CFSCRIPT start and end tag? CFSCRIPT, by definition, allows the processing of simple routine operations, instead of CFML. Here's an example: <CFSCRIPT> Variables defined within CFSCRIPT tags can be used just like any other ColdFusion variable. If you have more than a few variables to define, this tip really comes in handy. Now you know.
USING THE MOD FUNCTION TO ALTERNATE ROW COLORSOne of the most common tasks in ColdFusion development involves querying a database, returning a recordset, and outputting the results to the browser in table format. The latter consists of looping over the query results and producing a single row dynamically populated by the query. Unfortunately, since we're only really hard-coding the HTML for a single row, all our rows will be created with the same traits (such as background color), resulting in an unorganized display of the information. Of course, it would be much cooler if we could make every other row a different color, making our information significantly more readable. Fortunately, we can! ColdFusion provides an arithmetic operator called MOD, which returns the remainder after the first number is divided by a divisor (the second number), known as a modulus. If we take a number and MOD it by 2, we'll get either a 0 or a 1, according to whether it is odd or even. Used in conjunction with the CurrentRow variable always returned by a CFQUERY operation, we can identify every other row and change the color (or any other traits, for that matter) accordingly. Here's an example: <table>
VALIDATE YOUR DATABASE CONNECTIONHaving problems connecting to a database? You can quickly verify, via the ColdFusion administrator, that your ODBC (or OLEDB) connection is working. Open the Administrator and click on ODBC or OLEDB for the data source you want to verify. Then, click the Verify option next to the data source name. ColdFusion will report back to you whether it was able to connect to the data source.
VALUELIST() AND RETURNING A COMMA-DELIMITED RECORDSETChances are you've used the QUERY attribute of the CFMAIL tag to specify a database column of email addresses. ColdFusion then loops through the data and sends a separate email to each recipient. This is useful when you're populating the email with other dynamic values, but what if the same email is going to the entire list? In this case, sending a separate email to each recipient can prove to be extremely inefficient. Instead, use the ValueList() function to convert the records returned in a given database field into a comma-delimited list, then pass it to CFMAIL's TO attribute. Or better yet, to avoid including the entire recipient list in plain view, pass it to the BCC attribute and include a fake address (or yourself) in the TO attribute. Here's an example: <CFMAIL FROM="you@yourdomain.com" "TO="members@mylist.com"
VARIABLE TYPES IN COLDFUSION--PART 1 OF 2ColdFusion has ten different types of variables. Remember that you can help speed up your applications by including the variable type in your code whenever you refer to a particular variable. Here, then, are the first five types: * Local: vars defined in your code using CFSET
VARIABLE TYPES IN COLDFUSION--PART 2 OF 2ColdFusion has ten different types of variables, five of which we listed in the previous tip. Remember that you can help speed up your applications by including the variable type in your code whenever you refer to a particular variable. Here, then, are the remaining five types: * Application: vars that are linked with a particular application
written in ColdFusion
WATCH OUT! LOST DATA ON CFUPDATE AND CFINSERTHave you ever pulled your hair out trying to figure why a form using CFUPDATE or CFINSERT fails to update one or more fields? The field is in the table, it's in the form with the proper name... yet data never gets updated! If this sounds familiar, your problem likely is that the field name in question ends in one of the words ColdFusion reserves for server validation, such as "_date", "_time", or "_range". It's surprisingly easy to create a column using these strings (such as "start_date" or "end_time".) The problem is that ColdFusion's form processing engine doesn't recognize them as valid column names but instead as validation indicators. (In the example above, it thinks that "start" is the column name and it should be validated as a "date" type field.) Sadly, the server doesn't confirm that a form element named "start" exists, so it can't figure out that you don't mean "start_date" to be a column name. It also doesn't care that this is not used as a regular form input field rather than a "hidden" field. The bottom line is that you will either have to rename the columns in the database or not use the CFINSERT and CFUPDATE tags with a form updating these columns. Warning: You should consider running an analysis to determine whether your file contains references to table columns with names that end with one of these reserved words. You may be losing data and not realizing it. The best way to do this is to look at the schemas for the tables you use. If you have ColdFusion Studio, you could also do a quick analysis of the code using extended search and replace. Just be aware that if you do find hits for these strings, it may be that they're being used legitimately for defining input validation. Therefore, be sure to carefully screen each occurrence.
WHEN EQUALS ARE NOTMost programming languages treat the equal sign (=) as an operator, meaning you can determine whether the value on the left is equal to the value on the right. This isn't the case with ColdFusion. ColdFusion uses the eq keyword for comparing one value with another to determine whether they're equal, while it reserves the equal sign (=) as an assignment operator. This is often cause for confusion among programmers with experience in other languages. This syntax is wrong: <CFIF myValue = myValue2> This syntax is correct: <CFIF myValue eq myValue2> This assignment syntax is correct: <CFSET myValue=myValue2> ColdFusion also replaces the use of a number of other standard comparison operators with its own. Here are a few of them: < (less than) with: lt
YEAR RANGES IN COLDFUSIONYou already know that ColdFusion is Y2K compliant. But can you name the proper ranges for its default year treatments? Years from 00 to 29 are lopped into the 21st century--those years with 20 in the century marker, such as 2000 or 2010. Years from 30 to 99 are stuck back in the 20th century with the 1900s (1930 to 1939, in other words).
ALL FORM FIELD NAMES AND THEIR VALUESColdFusion supplies a comma-delimited list of all field names passed by a given form in the FORM.FieldNames parameter. To list all these fields and their corresponding value, you loop this list and use the Evaluate function to return its value, like so: <CFLOOP INDEX="FieldName" LIST="#Form.FieldNames#"> <CFSET
FieldValue = With this capability, you can dynamically check for specific field names and perform actions accordingly. One project I worked on required me to take separate action on form names beginning with gm so I simply included a condition in my loop to check for this. Remember not to have a form field actually named FieldNames because this may conflict with the FORM.FieldNames functionality.
IIF, MOD, AND ALTERNATING ROW COLORS: REVISITEDIn a recent tip, we showed you how to use the MOD function to distinguish every other record returned by a query, and how to use that capability to change a table row's background color. If you recall, we used a conditional CFIF/CFELSE statement for these purposes. A more complex, but faster (and cooler) way to achieve the same result is to use ColdFusion's IIF and DE functions. In this case, you pass the MOD condition as the first parameter, followed by the return values if the condition evaluates to true or false, respectively. You then wrap the boolean return values with the DE function to prevent the evaluation of these strings as an expression. (Stay tuned for more on these functions.) Here is an example: <table>
COLDFUSION BASICS: USE THE # TAGS AROUND VARIABLESOne common mistake that newbies to ColdFusion make is to forget to include the # signs around variables. If you want to print a variable or use a variable in just about any way, you need to wrap the variables in pound signs. This tells ColdFusion to interpret the text as a variable and replace it with the value stored in memory.
SELECT BOX: FILL WITH PRIMARY KEYSelect boxes are useful for delivering lists of data to the user. It's generally a good idea to use the primary key of your query as the value of the select list items. Then, display the text with another value from that record. This way, you always know which record the user is referring to.
SECURE SERVER: USE HTTPS AND PASS VARIABLES VIA SESSION VARSSecure servers, which help prevent snoopers from getting to your valuable transaction data, are often a necessity in today's e-commerce economy. There may be times, however, when you need to pass variables between secure and nonsecure pages. To do this, you could use hidden parameters, but the better solution is to pass values using session variables. Since session variables are stored on the ColdFusion server, they add another layer of security to the whole process.
ORDER YOUR REPORTS BY COLUMNSOne nice feature of any report-type browser screen is the ability to sort columns of data. I like to create columns with a link that calls the report page--and thus the query--so that all the user needs to do is click on a column name in order to sort the data based on that column. To do this, you simply use a query that contains an Order by statement that uses a variable, like this: Select ..... The link around the column name passes the #column# variable to the page so that when the query is called the sort order is also specified.
FORM FIELD NAMING CONVENTIONYou may find your programming simpler and faster if you name your form fields the same as your database fields. ColdFusion allows you to use the same name as long as you refer to the form variable as FORM.Variable. Naming your form fields in this manner will help ensure you get the right data into the right table fields.
DON'T USE PRIMARY KEYS AS FORM FIELDSOne thing you don't want to do is use a database primary key in a form field. Primary keys should never be modified by the user: They are only for the system and programmer's use. Besides, most databases won't allow updates to a primary key once it's established. Therefore, the user has no business trying to change them. If you need to display a primary key to the user, display it as you would a regular variable.
USE MAXLENGTH TO GET THE MOST FROM FORM FIELDSFor aesthetics, you'll want to size your form fields to fit the form, but you may also want to use MaxLength to give the user as much space as she needs for data entry. MaxLength is an attribute of the <input> tag that expands your form field beyond the displayed width. This means that even though you only have space to display the first 20 characters of a field, you can still allow your user to enter as many characters as necessary. Here's an example: <input type="text" name="name" size="20" maxlength="30">
VALIDATING DATA: SERVER-SIDE OR CLIENT-SIDE VALIDATIONValidating your data--making sure it fits within the parameters you expect--can save you and your users lots of headaches by ensuring pages don't bomb because incorrect data has been entered. With ColdFusion, you have two types of data validation available to you: server-side validation and client-side validation. Server-side validation takes place just where you'd expect--on the server. When the user enters data in the form's fields and clicks the submit button, the server processes the data and validates it where you've indicated. This is the traditional method of validating data, and it works well. However, users must wait for a response from the server before they know whether they've entered incorrect data. Client-side validation takes place in the user's browser. Through scripting, you validate the data before the user's request is sent to the server. This gives the user immediate feedback, which may make your pages appear fast, clean, and efficient. This method does, however, have a drawback: The scripting for validation can be long, which adds weight to your page. As you know, the heavier the page, the longer it takes to download. You'll need to decide which method of validation is better for you: client-side, server-side, or a combination of both. In the next few tips, we'll cover methods for validating different types of fields, starting with server-side options and then moving to client-side options.
SERVER-SIDE VALIDATION: REQUIRED FIELDSServer-side validation requires that you include the name of your field in a regular <input> tag, as always. To validate the tag, however, you must include the <input> tag again as a hidden field, appended with an underscore and the type of validation. To make sure a user enters a value for a particular field, you append the "_required" attribute, as shown here: <input type="text" name="CustNumber"> <input type="hidden" name="CustNumber_required" value="You need to enter a customer number."> This second parameter forces the server to make sure the CustNumber field has a value. If it does not, an error message will display the text you've put in the value attribute.
SERVER-SIDE VALIDATION: DATE FIELDSDates are probably one of the hardest field types to format. There are many ways to enter dates: with dashes, with slashes, without the year, in the European format--you get the idea. Fortunately, you don't have to worry about the different formats if you use the _date validation tag, shown here: <input type="text" name="Started"> <input type="hidden" name="Started_date" value="The Start date specified is not a valid format.">
SERVER-SIDE VALIDATION: INTEGERSEnsuring that the user entered a whole number isn't very difficult using server-side validation. Like the rest of the validation tags, you simply follow your form field with a hidden tag, like this: <input type="text" name="Age"> <input type="hidden" name="Age_integer" value="Please specify your age in whole numbers only.">
CLIENT-SIDE VALIDATION: FAST FEEDBACKClient-side validation gives the user fast feedback regarding erroneous data he or she may have entered. This is done through the use of scripting--primarily in JavaScript. However, not all browsers support JavaScript, and not all users have JavaScript enabled in their browsers. You'll need to weigh the advantages of client-side data validation against its drawbacks, then decide if you want to implement it in your pages. Should you decide that you do want to include client-side validation, ColdFusion makes it easy for you. You don't have to write a single JavaScript line. To use client-side validation with ColdFusion, you use the <CFFORM> tag instead of the regular HTML <FORM> tag. (Naturally, you'll also use the closing </CFFORM> instead of the regular HTML </FORM> tag.) When you use <CFFORM>, you tell ColdFusion that you may be using its <CFINPUT> tag to get data from the user. <CFINPUT> will automatically generate JavaScript for you, based on the types of parameters you include. In the next few tips, we'll look at some specific ways to implement these tags for client-side validation.
CLIENT-SIDE VALIDATION: CFINPUTThe <CFINPUT> tag uses parameters very similar to the HTML <INPUT> tag. However, for validation, you include the validate parameter and include the type of validation you wish to perform. The tag takes this form: <cfinput type="text" Name="datafield" size="10" maxlength ="20" validate="type of validation" Message="your error message"> When you include <CFINPUT>, ColdFusion will generate probably no less than 50 lines of JavaScript to validate your field. If users enter incorrect data, they'll see a JavaScript window pop up with your error message, and they can then correct the mistake. This functionality adds weight to your page and may not function at all if the user's browser doesn't support JavaScript (which is increasingly rare). It's often a good idea to employ a combination of both client-side and server-side validation. That way, you can make sure that no matter what browser your users prefer, your data gets validated.
CLIENT-SIDE VALIDATION: REQUIRED FIELDSAs you may recall, server-side validation requires that you include a hidden field with the type of data for which you wish to check. For client-side validation, ColdFusion eliminates that need by letting you include a single parameter in your <CFINPUT> tag. To require a field, simply include the REQUIRED parameter with a value of yes, as shown here: <cfinput type="text" name="CustNumber" required="yes" Message="You need to enter a customer number."> If the user fails to enter a value, a message box pops up and displays your error message.
CLIENT-SIDE VALIDATION: DATESTo validate a date field in ColdFusion, you include the "date" keyword in your <CFINPUT> tag. The following code validates the data for a date in the mm/dd/yy format: <cfinput type="text" name="StartDate" validate="date" message="You need to enter a valid start date.">
GET THE NAME OF THE CURRENT TEMPLATEAs you're scripting Web applications, keep in mind that a ColdFusion template can include several other templates. Regardless of which template is currently running, it is often useful to know the name of the base ColdFusion template. Fortunately, you can add a small bit of code to your Web app's Application.cfm template to make the base template name available. To dynamically derive the template name, insert the following code at the bottom of your project's Application.cfm: <CFSET var_template_name = "#GetFileFromPath(GetTemplatePath())#"> As you can see, GetTemplate() grabs the full path of the current template. GetFileFromPath() then derives the template file name from GetTemplate().
SET THE DATASOURCES AS APPLICATION VARIABLESIn most cases, your Web application will use one or two ODBC data sources. However, you'll probably reference those datasource names hundreds of times through your app. As you can imagine, modifying the datasource name for each Query throughout your web application would be a task laden with hundreds of possible errors. Therefore, it's a good idea to set as an application variable the datasource names your app uses--and then reference the variable in your queries. This allows you to effect every query in your Web application by altering the value of one application variable. To set your datasource name or names as an application variable, turn Application and Session Management on. Then, insert the following code into the application.cfm: <cfset application.datasource = "TOPICA_PUBLIC"> Now, in your queries, insert the application.datasource into the Datasource attribute, like so: <CFQUERY NAME="SELECT_TOPICA_TITLES"
DATASOURCE="#APPLICATION.DATASOURCE#"> SELECT TITLE
USE APPLICATION VARIABLES FOR EMAILJust as it makes sense to set the datasource name for your Web project in an application variable, it also makes sense to set the email recipients of CFMAIL as application variables in the application.cfm. Setting the e-mail recipients as a variable in the application.cfm both exposes the email recipient's variable to every page in your Web project and allows you to easily change the destination of each CFMAIL. To set the email recipient as an application variable, place the following code in the Application.cfm. <cfset application.email_recipient = "daffyduck@topica.com"> Then, in the To attribute of each CFMAIL tag, insert application.email_recipient, like so: <CFMAIL to="application.email_recipient"
from="website@website.com"> Hello
SETTING APPLICATION AND SESSION VARIABLESApplication and Session variables allow you to maintain state across all of the ColdFusion templates in your Web application. Typically, you'll activate Application and Session variables in the Application.cfm template. To prevent setting and re-setting Application and Session variables each time the Application.cfm page is executed, check for the existence of the application variable. To do this, place a CFIF and an ISDEFINED around each application or session variable assignment. For example, to set the application.datasource variable only once, use the following code: <cfif not IsDefined('application.datasource') >
COPY YOURSELF ON EMAILSIf you host ColdFusion Web applications, it's generally a good idea to blind carbon copy (bcc) any CFMAIL emails to a central email box. We realize ColdFusion has the capability to log and save email contents if it experiences any problems, but often the problem will occur after ColdFusion hands the email to a mail server. Sending copies to a centralized email box gives you instant access to the email regardless of where the problem occurred. To blind carbon copy a centralized email box, insert the BCC attribute into each CFMAIL in your Web project. Here is an example: <cfmail to="#application.email_recipient#"
from="daffyduck@topica.com" subject=""
|
Just Check out some of our sponsors |
|
COPYRIGHT 1998 - 2009 All names used are Trademarks of the respective companies Send mail to
CompanyWebmaster with
questions or comments about this web site.
|