Using the IsDefined() Function

Team-Fly    

ColdFusion® MX: From Static to Dynamic in 10 Steps
By Barry Moore
Table of Contents
Step 5.  Using Forms with ColdFusion MX


As you progress with your ColdFusion coding, you will find that it is very handy to be able to check for the existence of a variable and then perform one action if it does exist and another if it does not. As we have already seen in Step 4, "Controlling Program Flow," we can use IF statements to take care of the conditional processing. We just need a way to check for the existence of the variable.

The IsDefined() function fits the bill just perfectly. It determines whether or not a specified variable exists (is defined). If the specified variable does exist, the function returns a value of TRUE; if it does not exist, the function (not surprisingly) returns a value of FALSE. The function only takes one parameter, and that is the name of the variable for which we want to check.

Going back to our problem of the FORM.MailList variable being present with some form submissions but not with others, we could use the IsDefined() function to check for its existence. For example, we could use the following code to check for the variable. If it exists (is defined), we will output its value; if not, we won't do anything.

 <CFIF IsDefined("FORM.MailList") IS TRUE>        <B>Mailing List: </B>#FORM.MailList#<BR>  </CFIF>

NOTE

Make sure you use quotation marks around the name of the variable for which you are checking. If you do not, the IF statement will check for the contents of the variable rather than for the variable itself.

Also note that developers (lazy bunch that they are) have a shorthand method of coding when checking for a value of IS TRUE. You just leave off the IS TRUE bit; it is assumed. So, the opening <CFIF> statement could also read <CFIF IsDefined("FORM.MailList")>.


If you want to perform an action only if the variable is not defined, you can use the logical NOT operator to reverse the question. For example, with the following code, we can ask the user why he does not want to be on our mailing list.

 <CFIF NOT IsDefined("FORM.MailList") >        What? Are you too good for our mailing list. Huh? <BR>  </CFIF>

    Team-Fly    
    Top
     



    ColdFusion MX. From Static to Dynamic in 10 Steps
    ColdFusion MX: From Static to Dynamic in 10 Steps
    ISBN: 0735712964
    EAN: 2147483647
    Year: 2002
    Pages: 140
    Authors: Barry Moore

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net