Installing and Using ColdFusion MX

Installing and Using ColdFusion MX is intended for anyone who needs to install and configure ColdFusion MX 7.

This book contains the following chapters:

  • Introduction
  • Preparing to Install ColdFusion MX 7
  • Installing the Server Configuration
  • Installing the Multiserver Configuration
  • Installing the J2EE Configuration
  • Configuring Your System
  • Troubleshooting


Introduction

Installing and Using ColdFusion MX is intended for anyone who needs to install and configure Macromedia ColdFusion MX 7.

About ColdFusion MX 7 documentation

The ColdFusion MX 7 documentation is designed to provide support for the complete spectrum of participants.

Documentation set

The ColdFusion MX 7 documentation set includes the following titles:

Book | Description
Installing and Using ColdFusion MX | Describes system installation and basic configuration for Windows, Solaris, and Linux. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_installing.
Configuring and Administering ColdFusion MX | Part I describes how to manage the ColdFusion environment, including connecting to your data sources and configuring security for your applications. Part II describes Verity search tools and utilities that you can use for configuring the Verity Search Server engine, as well as creating, managing, and troubleshooting Verity collections. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_configadmin.
ColdFusion MX Developer’s Guide | Describes how to develop your dynamic web applications, including retrieving and updating your data, using structures, and forms. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_dev.
Getting Started Building ColdFusion MX Applications | Contains an overview of ColdFusion features and application development procedures. Includes a tutorial that guides you through the process of developing an example ColdFusion application. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_gs.
CFML Reference | Provides descriptions, syntax, usage, and code examples for all ColdFusion tags, functions, and variables. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs__cfml_reference.
CFML Quick Reference | Provides a brief guide that shows the syntax of ColdFusion tags, functions, and variables.

Viewing online documentation

All ColdFusion MX 7 documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com. In addition, you can view the documentation in LiveDocs, which lets you add comments to pages and view the latest comments added by Macromedia, by going to www.macromedia.com/go/livedocs_cfmx7docs.


Preparing to Install ColdFusion MX 7

This chapter describes Macromedia ColdFusion MX 7 product editions, system requirements, and other high-level considerations. Before installing ColdFusion MX 7, you should review the information in this chapter and determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.

Contents

About the ColdFusion MX 7 installation

ColdFusion MX 7 product editions

System requirements

Installation considerations

Gathering information necessary to install ColdFusion MX 7
Next


About the ColdFusion MX 7 installation

ColdFusion MX 7 provides a powerful and flexible installation and upgrade process. The ColdFusion MX 7 installation process includes the following phases:

  1. Plan the installation. You determine your installation, configuration, and upgrade options.
  2. Run the installer. You run the ColdFusion MX 7 installer.
  3. (J2EE configuration only) Deploy ColdFusion MX 7. You deploy and configure ColdFusion MX 7 on your J2EE application server.

The ColdFusion MX 7 installation process supports the following scenarios:

New installation Install ColdFusion MX 7 on a computer with no previous ColdFusion installation.

Upgrade installation You can upgrade from ColdFusion 4.5, ColdFusion 5, ColdFusion MX, and ColdFusion MX 6.1. When upgrading from ColdFusion 4.5, or 5, the installer migrates previous settings to ColdFusion MX 7. When upgrading from ColdFusion MX or ColdFusion MX 6.1, the installer preserves the existing settings and installs in a new directory, automatically assigning ports that do not conflict with the existing installation.

You can install ColdFusion MX 7 in any of the following configurations:

Server configuration Lets you install one instance of ColdFusion MX 7 with an embedded J2EE server. This configuration most closely resembles the ColdFusion MX base release and other releases prior to ColdFusion MX, such as ColdFusion 5 and ColdFusion 4.5. This was formerly known as the stand-alone configuration. For information on installing the server configuration, see Installing the Server Configuration.

Multiserver configuration (Enterprise Edition only) Installs JRun and automatically deploys ColdFusion MX 7 in a separate JRun server instance. This configuration supports server instance creation and ColdFusion deployment in the ColdFusion MX Administrator and lets you manage ColdFusion MX 7 deployments on multiple JRun servers. For information on installing the multiserver configuration, see Installing the Multiserver Configuration.

J2EE configuration (Enterprise Edition only) Lets you deploy ColdFusion MX 7 as a Java application running on a Java 2 Enterprise Edition (J2EE) application server, either using the bundled license of JRun or using a third-party J2EE server, such as IBM WebSphere or BEA WebLogic. When you use the J2EE configuration, you can deploy ColdFusion MX 7 multiple times on a single computer. For information on installing the J2EE configuration, see Installing the J2EE Configuration.

The remainder of this chapter describes product editions and system requirements. After you understand the editions and ensure that your environment meets the system requirements, continue with the instructions in Installing the Server Configuration Installing the Multiserver Configuration, or Installing the J2EE Configuration, as appropriate.


ColdFusion MX 7 product editions

The following table describes each edition of ColdFusion MX 7:

Edition

Description

Licensing

Developer

For Windows and Linux.

Supports requests from the local host and two remote IP addresses. Includes every feature in the Enterprise Edition, with the following exceptions:.

  • Banded reports, output from the cfdocument tag, and charts are watermarked.
  • Verity update is supported on a single-server configuration only.
  • There is a 10K Verity document search limit.
  • EAR/WAR deployment is not supported.
  • If you install ColdFusion MX 7 in Trial mode, it reverts to Developer Edition after 30 days.

Free for a single computer used for development and evaluation purposes only. Applications on Development Edition server are viewable from up to five client machines. Not licensed for deployment.

Standard

For Windows and Linux.

Features full ColdFusion Markup Language (CFML) support, including:

  • Custom tags and ColdFusion Components.
  • Full support for server-side ActionScript and Macromedia Flash Remoting.
  • Extensibility and integration with Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML), and with Component Object Model (COM), Enterprise Java Beans (EJBs), and Common Object Request Broker Architecture (CORBA).
  • Rich forms.
  • A built-in charting and graphing engine, including enhancements in ColdFusion MX 7.
  • Database connectivity using ODBC with a desktop database, such as Microsoft Access, and using a Type 4 driver for SQL Server or MySQL.
  • Database and LDAP directory authentication, and resource security.
  • A 125K Verity document search limit.
  • ColdFusion MX 7 reporting

Licensed per server (up to eight processors per server).

Enterprise

For Windows, Linux, and Solaris.

Includes every feature in the Standard Edition, and also provides the following:

  • Database connectivity using Type 4 drivers for Oracle, DB2, Sybase, and Informix
  • External Event Gateway support, including XMPP/Jabber IM Gateway, Lotus Sametime IM Gateway, Asynchronous CFML Gateway, SMS/Mobile Cell Gateway, and local SMS development toolkit
  • The ability to import and execute Java Server Page (JSP) servlets and JSP Tag Library imports
  • Server sandbox security
  • A 250K Verity document search
  • Advanced server management capabilities, including server log analysis, configurable probes and alarms, and automated archive and deployment options
  • J2EE support, in particular, Servlet, Java Server Pages (JSP), and Enterprise JavaBeans (EJB)
  • Support for deployment on third-party J2EE application servers
  • Multiserver configuration and J2EE configuration support running multiple instances of ColdFusion MX 7 on a single computer
  • Backup mail servers and multithreaded e-mail delivery
  • HTTP-based load-balancing and failover using the Cluster Manager
  • Complete JRun 4 included
  • EAR/WAR package creation, and EAR/WAR deployment
  • Archive and deployment services

Licensed per CPU. Initial license is for two CPUs; licenses available in two-CPU increments.

Note: If you have a previous licensed version of ColdFusion installed, and you want to evaluate the Report Builder, you must install a trial or developer edition of ColdFusion MX 7.


System requirements

The ColdFusion MX 7 system requirements are available on the Macromedia web site. To view the system requirements, including a list of supported J2EE application servers, go to www.macromedia.com/go/sysreqscf.

To use third-party JDBC type 4 drivers, see Connecting to an external JDBC Type 4 data source. The installation instructions also describe how to provide ODBC database support on Windows.


Installation considerations

This section describes the following topics for installing or upgrading to ColdFusion MX 7:

  • Installation considerations for all platforms
  • Installation considerations for Windows
  • Installation considerations for UNIX

Note: To use VisiBroker for CORBA connections in ColdFusion MX 7, see Enabling CORBA support.

Installation considerations for all platforms

The following are installation considerations for all platforms:

  • Macromedia supports installing ColdFusion MX 7 side-by-side with ColdFusion MX 6.1 and ColdFusion MX. Macromedia supports upgrading to ColdFusion MX 7 from ColdFusion 5 and ColdFusion 4.5. If you are upgrading, you must back up your existing ColdFusion applications first.
  • If you have previously installed a Beta version of ColdFusion MX 7, you must uninstall it before you install the release version.
  • Macromedia recommends using the built-in (internal port-based) web server for development, but not in a production environment.
  • If you have ColdFusion 4.5 or 5 installed on your computer, ColdFusion MX 7 installs in coexist mode automatically. You can migrate ColdFusion 4.5 or ColdFusion 5 resources (such as data sources and Verity collections) to ColdFusion MX 7.
  • Previous versions of ColdFusion MX, including ColdFusion MX 6.1, can coexist with ColdFusion MX 7; however, you cannot install ColdFusion MX 7 in the directory where ColdFusion MX 6.1 resides.

    You can switch to use a different web server for ColdFusion MX 7 after the installation, by following the instructions for your platform and the web server in Configuring web servers.

  • During installation of the server configuration, if you select the built-in web server, your web root directory is C:/CFusionMX7/wwwroot by default. This web server runs on the 8500 port. To display a page, append 8500 to the end of the host name or IP address; for example,
    http://localhost:8500/MyApp.cfm. (If the page still does not appear, ensure that the document is located in the ColdFusion MX 7 web root directory; for example, C:/CFusionMX7/wwwroot\MyApp.cfm. For more information, see Using the built-in web server.
  • To interact with ColdFusion pages and components from a Macromedia Flash SWF file, use the Flash Remoting service in ColdFusion MX 7. To develop applications that use Flash Remoting, you must install the Flash Remoting components in the Flash MX authoring environment. The Flash MX authoring environment or Macromedia Flex is required to build applications that connect to and interact with the Flash Remoting service in ColdFusion MX 7.
  • By default, Macromedia Flash Remoting cannot access web services through ColdFusion MX 7.

To enable Flash Remoting to access web services through ColdFusion MX 7:

  1. Open the cf_root/WEB-INF/gateway-config.xml file in a text editor.
  2. Locate the following line.
    <!--<adapter>coldfusion.flash.adapter.CFWSAdapter</adapter>-->
  3. Remove the comments, so that the line appears as follows.
    <adapter>coldfusion.flash.adapter.CFWSAdapter</adapter>
  4. Save the file.
  5. Restart ColdFusion MX 7.

    For more information on Flash Remoting, see ColdFusion MX Developer’s Guide.

    • ColdFusion MX 7 is built in Java and when installing the server configuration, the ColdFusion MX 7 installer automatically installs the JRE that is appropriate for your platform. When installing the J2EE configuration, ColdFusion MX 7 uses the same JRE as your J2EE application server.
    • In an optimal production environment, each ColdFusion MX 7 application is hosted on a dedicated server; database, mail, and other servers are not on the same computer.

Installation considerations for Windows

The following installation considerations are for Windows systems only:

  • Do not configure the server running ColdFusion MX 7 as a Primary Domain Controller (PDC) or Backup Domain Controller (BDC). Macromedia follows the Microsoft network model, in which the first level is the PDC or BDC. These systems only manage the network or domain and are not designed to run application servers. ColdFusion MX 7 should reside on the second level of Microsoft Windows 2000 stand-alone systems. Stand-alone servers can participate in a network or domain.
  • Windows 2000 Professional handles only ten TCP/IP connections concurrently. Therefore, Macromedia does not recommend using this operating system in a production environment; use Windows 2000 Server instead.

Installation considerations for UNIX

The following are installation considerations for UNIX systems only:

  • For troubleshooting purposes, the installer creates the following log file during an installation or upgrade on UNIX: cf_root/Macromedia_ColdFusion_MX7_install.log. If you contact Macromedia Technical Support for installation support, you must send them this file.
  • If you are deploying the J2EE configuration on a platform other than Linux or Solaris, use the coldfusion-70-other.jar installer. This Java-only installer does not include features that require platform-specific binary files, such as Verity and C++ CFX support.
  • Macromedia does not recommend using Apple Mac OS X 10.3 in a production environment


Gathering information necessary to install ColdFusion MX 7

Although the ColdFusion MX 7 installer provides an intuitive interface, it helps to plan your answers to the questions asked by the installer. Use the following table to help plan for installing ColdFusion MX 7. You should first determine the type of installation, and then answer the questions that pertain to that type of installation.

Question | Answer | Installation types
Platform-specific installer name? | ___________________________________ | All
What is the serial number for ColdFusion MX 7? | ___________________________________ | All
What is the type of installation? | Server configuration Multiserver configuration J2EE configuration | All
EAR file or WAR files? | EAR | WAR | J2EE configuration
Install which subcomponents? | ColdFusion MX 7 ODBC Services ColdFusion MX 7 Search Services Getting Started Experience, Tutorials, & Documentation Note: Do not install the Getting Started Experience if you are installing in a production environment. | All
JRun installation directory? | ___________________________________ | Multiserver configuration
Installation directory for EAR or WAR file? | ___________________________________ | J2EE configuration
Context root for ColdFusion (EAR file only, default=cfmx)? | ___________________________________ | J2EE configuration
Java Servlet API version? | 2.3 or greater | 2.2 or lower | J2EE configuration
ColdFusion MX 7 installation directory? | ___________________________________ | Server configuration
Configure web server or use built-in web server? | Configure web server for ColdFusion MX 7 | Enable ColdFusion MX built-in web server (coexist) | Server (existing ColdFusion web server configuration) Multiserver configuration
Choose web server to configure. | IIS | Apache | SunONE| Other | Server configuration Multiserver configuration
(Apache and SunONE) Configuration directory? | ___________________________________ | Server configuration (new installation) Server configuration (existing ColdFusion 4.5/5) Multiserver configuration
(Apache) Path to server binary? | ___________________________________ | Server configuration (new installation) Server configuration (existing ColdFusion 4.5/5) Multiserver configuration
ColdFusion MX Administrator password? | ___________________________________ | All
Do you want to enable RDS? | Yes | No Note: RDS allows the server to interact with remotely connected developers. Macromedia recommends that you disable RDS for production servers. Disabling RDS also disables the directory browsing applets in the ColdFusion MX Administrator. | All
RDS password? | ___________________________________ | All
Previous


Installing the Server Configuration

This chapter describes how to install and uninstall ColdFusion MX 7 in the server configuration. The ColdFusion MX 7 server configuration contains an embedded copy of JRun and is most similar to previous ColdFusion versions.

Note: In this chapter, cf_root refers to your installation directory. By default, this directory is C:\CFusionMX7 in Windows, and /opt/coldfusionmx7 on UNIX.

Contents

Installing ColdFusion MX 7 using the server configuration

Installing the ColdFusion Report Builder

Installing the Verity search server separately

ColdFusion MX 7 server configuration directory structure

Using the built-in web server

Uninstalling ColdFusion MX 7
Next


Installing ColdFusion MX 7 using the server configuration

This section provides installation instructions for the ColdFusion MX 7 server configuration on Windows, Linux, and UNIX.

Before you run the installer, you should determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.

This section describes the following topics:

  • Installing ColdFusion MX 7 server configuration on Windows
  • Installing the ColdFusion MX 7 server configuration on UNIX


Installing ColdFusion MX 7 server configuration on Windows

This section explains how to install ColdFusion MX 7 on Windows.

Note: The Windows installer requires a computer that supports at least 256 colors.

To install ColdFusion MX 7 in Windows:

  1. Read the online version of the Release Notes for any late-breaking information or updates. For more information, see www.macromedia.com/go/proddoc_releasenotes.
  2. Ensure that your operating system meets the system requirements described in System requirements.
  3. Review Installation considerations for Windows and Installation considerations for all platforms.
  4. Determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.
  5. Close any applications that are currently running on your computer.
  6. If you plan to configure an external web server, ensure that the web server is running.
  7. If you are installing on a computer on which ColdFusion 4.5 or 5 already exists, shut down all ColdFusion services. For information about stopping ColdFusion services, see Managing ColdFusion MX 7 services in Windows.
  8. Insert the CD or download the setup file from the Macromedia website.
  9. If the installation wizard does not start automatically when you insert the CD, locate the setup.exe file on the CD and double-click it. If you are installing from a network or a downloaded file, locate the ColdFusion MX 7 installation executable file (coldfusion-70-win.exe) and double-click it.

    The installation wizard starts.

  10. Follow the instructions in the wizard, and let it run to completion.
  11. Open the ColdFusion MX Administrator to configure the server.
  12. After the server configuration is complete, click OK to run the Getting Started Experience.

    If you are new to ColdFusion, you can use the Getting Started Experience to learn about the basics of creating a ColdFusion application. If you are already familiar with ColdFusion, you can view code snippets that highlight the new features in ColdFusion MX 7.

  13. To install the ColdFusion MX 7 Extensions for Dreamweaver, double-click the cfmx7dreamweaverextensions.mxp file, which is located in the cf_root/wwwroot/CFIDE/installers directory.

    Note: If you configured ColdFusion MX to run with an external web server, this file is in the webroot/CFIDE/installers directory.

  14. To install ColdFusion MX 7 Report Builder, double-click the CFReportBuilderInstaller.exe file, which is in the cf_root/wwwroot/CFIDE/installers directory.
  15. Configure and manage your system, as described in Configuring Your System.
  16. To learn about ColdFusion MX 7, read the documentation, which is accessible through the Documentation link at the top of the ColdFusion MX Administrator.


Migrating Windows settings manually

If you are upgrading from ColdFusion 4.5 or 5, you can optionally migrate settings later, manually.

To migrate settings manually:

  1. Close the ColdFusion MX Administrator, if it is not already closed.
  2. Open the cf_root\lib\adminconfig.xml (server configuration) file in a text editor.
  3. Change the value for runmigrationwizard and runmxmigrationwizard to true, as necessary, so the appropriate lines of the file appear as follows:
    <runmigrationwizard>true</runmigrationwizard>

    or

    <runmxmigrationwizard>true</runmxmigrationwizard>
  4. Change the value for migratecf5 or migratecf6 to true, as necessary, so the appropriate lines of the file appear as follows:
    <migratecf5>true</migratecf5>

    or

    <migratecf6>true</migratecf6>
  5. Save the file.
  6. Restart the ColdFusion MX Administrator from the Windows Start menu.

    You are prompted again to migrate your settings.

    Caution: If you migrate your ColdFusion 5 settings later, you might overwrite new ColdFusion MX 7 settings.


Installing the ColdFusion MX 7 server configuration on UNIX

This section explains how to install ColdFusion MX 7 on UNIX.

By default, ColdFusion MX 7 installs into the /opt/coldfusionmx7 directory. To install it into a different directory, you must create that directory before you run the installation.

Note: The default user is nobody for the UNIX installer running ColdFusion MX 7.

To install the ColdFusion MX 7 server configuration on UNIX:

  1. Read the online version of the Release Notes for any late-breaking information or updates. For more information, see www.macromedia.com/go/proddoc_releasenotes.
  2. Ensure that your operating system meets the system requirements as described on the Macromedia web site at www.macromedia.com/go/sysreqscf.
  3. Review Installation considerations for UNIX and Installation considerations for UNIX.
  4. Determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.
  5. If you plan to configure an external web server, ensure that the web server is running.
  6. If you are installing on a computer on which ColdFusion 4.5 or 5 already exists, shut down the ColdFusion servers. For information about stopping ColdFusion services, see Managing the ColdFusion MX 7 process on UNIX.
  7. Log in as root.
  8. Copy the installation file that is appropriate for your platform and locale from the CD or Macromedia website, and save it to a directory on your local disk.

    The following are the installation files for supported server configuration platforms:

    • coldfusion-70-lin.bin
    • coldfusion-70-sol.bin
  9. Using the cd command, go to the directory that contains the installation file.
  10. Start the installation with the following command:
    ./<filename>

    The installation program starts.

    Note: To run the UNIX installer in GUI mode, type ./<filename> -i gui.

  11. Follow the prompts, and let the installation program run to completion.

    Caution: For security reasons, it is crucial that you do not use root for the runtime user.

  12. Start ColdFusion MX 7 with the following command:
    /cf_root/bin/coldfusion start

    If you specified the use of an external web server when you ran the installer, ColdFusion MX 7 automatically runs the cf_root/bin/cfmx-connectors.sh script when it starts the first time. This shell script runs the Web Server Configuration Tool using the settings you specified during the installation. If there are problems running this script, review the configuration and bin directory specifications, modify as necessary, and rerun the script. You can also configure your web server using the scripts in cf_root/bin/connectors, as appropriate.

    To stop ColdFusion MX 7, use the following command:

    /cf_root/bin/coldfusion stop

    For more information on managing processes, see Managing the ColdFusion MX 7 process on UNIX.

  13. Open ColdFusion MX Administrator to run the configuration wizard.
  14. Configure and manage your system, as described in Configuring Your System.
  15. To learn about ColdFusion MX 7, read the documentation, which is accessible through the Documentation link at the top of the ColdFusion MX Administrator.


Migrating UNIX settings manually

If you are upgrading from ColdFusion 4.5 or 5, you can optionally migrate settings later. To migrate later:

To migrate settings manually:

  1. Close the ColdFusion MX Administrator, if it is not already closed.
  2. Open the cf_root/lib/adminconfig.xml file in a text editor.
  3. Change the value of runmigrationwizard and runmxmigrationwizard to true, as necessary, so that the appropriate lines of the file appear as follows:
    <runmigrationwizard>true</runmigrationwizard>
<runmxmigrationwizard>true</runmxmigrationwizard>
  4. Save the file.
  5. Restart the ColdFusion MX Administrator.

    You are prompted again to migrate your settings.

    Caution: If you migrate your ColdFusion 5 settings later, you might overwrite new ColdFusion MX 7 settings.


Installing the ColdFusion Report Builder

ColdFusion MX 7 reporting consists of server-side runtime processing and the ColdFusion Report Builder. The server-side processing is available on any platform, however, the ColdFusion Report Builder runs on Windows only.

To install the ColdFusion Report Builder:

  1. Access the ColdFusion Report Builder installer from one of the following locations:
    • The ColdFusion MX 7 installation Go to the webroot/CFIDE/installers directory.
    • The ColdFusion MX 7 CD Use the CD Browser to select the ColdFusion MX reporting option.
    • The Macromedia web site Go to www.macromedia.com/go/cfmx7_reporting/.
  2. Double-click the CFReportBuilderInstaller.exe file.
  3. Follow the instructions in the installation.


Installing the Verity search server separately

By default, the installer installs the Verity search server on the same computer as ColdFusion MX 7. To enable searches using Verity, if you want to install the Verity search server on a different computer from the one where you install ColdFusion MX 7, you must install the Verity search server separately. For more information, see Installing the Verity search server separately.


ColdFusion MX 7 server configuration directory structure

The following table describes the directories under the cf_root directory when you install the server configuration of ColdFusion MX 7:

Directory | Description
bin | Programs for starting, stopping, and viewing information for ColdFusion MX 7, and to run Crystal Reports (Windows only).
cache | Repository for temporary files from ColdFusion MX 7.
cfx | Sample C++ and Java CFX files with their supporting files. You can also store your CFX files in this directory (although you can put them in any location that is defined in your classpath).
charting | Files for the ColdFusion MX 7 graphing and charting engine.
CustomTags | Repository for your custom tags.
db | In Windows, the files for sample Microsoft Access databases and ODBC services. On UNIX, the files for the sample PointBase databases.
gateway | (Enterprise Edition only) Files for ColdFusion MX 7 event gateways.
jintegra | JIntegra programs, libraries, and other supporting files (for example, to integrate Java and COM code; manage access to ActiveX controls (OCXs) that are hosted in a graphical user interface (GUI) container; and register the JVM and type libraries).
lib | JAR, XML, property, and other files that are the foundation of ColdFusion MX 7, for functionality such as queries, charting, mail, security, Verity searches, and system probes.
logs | Repository for ColdFusion MX 7 log files. JRE-specific log files are in the runtime/logs directory.
Mail | Repository for spooled mail and mail that cannot be delivered.
META-INF | XML metadata for the ColdFusion MX Administrator.
registry | (UNIX only) Flat file to store registry settings
runtime | Programs and supporting files for the ColdFusion MX 7 runtime. In Windows, the files for the bundled JRE are in runtime\jre.
runtime/jre | Files for the Java Runtime Environment (JRE) that is bundled with ColdFusion MX 7.
temp_zip | The zipped version of the sample applications.
uninstall | Files to uninstall ColdFusion MX 7.
verity | Verity collections. (The Verity program files are in the lib directory.)
wwwroot | Default web root directory for the built-in web server. When running on other web servers, this directory contains only the WEB-INF directory; do not remove this directory.


Using the built-in web server

ColdFusion MX 7 has its own web server that you can use to develop ColdFusion MX 7 applications, without depending on an external web server, such as Internet Information Server (IIS), Apache, or SunONE. Macromedia does not recommend using the built-in web server in a production environment. However, it is more than suitable for development, allowing you to create virtual directories and set the default document (for example, default.cfm or index.cfm).

During the ColdFusion MX 7 installation, you must choose a web server. If you select the built-in web server, your web root directory is located in the cf_root/wwwroot directory. By default, the web server runs on port 8500. This means that to display a page in your application, you must append :8500 to the host name or IP address in the URL; for example,
http://localhost:8500/YourApp1/index.cfm. (If the page still does not appear, make sure that the document is located in the built-in web server’s web root directory; for example, C:\CFusionMX7\wwwroot\YourApp1\index.cfm.)

Note: If you install the Server configuration of ColdFusion MX 7 with the built-in server and port 8500 is in use, for example by ColdFusion MX or ColdFusion MX 6.1, the installer starts with port 8501 and looks at up to 100 ports to find one that is not being used by an application that is running. ColdFusion MX 7 uses that port and displays a message to indicate which port it selected.

If you select an external web server, the built-in web server is deactivated.

This section describes the following topics:

  • Switching the port for the built-in web server
  • Switching from another web server


Switching the port for the built-in web server

You can change the port on which the built-in web server runs.

To change the port for the built-in web server:

  1. Back up the jrun.xml file.

    This file is in the cf_root\runtime\servers\default\SERVER-INF directory in Windows, and in the cf_root/runtime/servers/default/SERVER-INF directory on UNIX.

  2. Open the original jrun.xml file for editing.
  3. Change the port number specified in the WebService port attribute (near the bottom of the file):
    <service class="jrun.servlet.http.WebService" name="WebService">
    <attribute name="port">8500</attribute>
    <attribute name="interface">*</attribute>
    <attribute name="deactivated">false</attribute>
    ...
</service>

    Note: Make sure that the deactivated attribute is set to false.

  4. Save the file.
  5. Restart ColdFusion MX 7.


Switching from another web server

You can switch from an external web server to the built-in ColdFusion MX 7 web server without reinstalling, even if you did not select it during installation.

To switch from an external web server to the built-in web server:

  1. Back up the jrun.xml file.

    This file is in the cf_root\runtime\servers\default\SERVER-INF directory in Windows, and in the cf_root/runtime/servers/default/SERVER-INF directory on UNIX.

  2. Open the original jrun.xml file for editing.
  3. Locate the WebService service and set the deactivated attribute to false:
    <service class="jrun.servlet.http.WebService" name="WebService">
    <attribute name="port">8500</attribute>
    <attribute name="interface">*</attribute>
    <attribute name="deactivated">false</attribute>
    ...
</service>
  4. Locate the ProxyService service and set the deactivated attribute to true:
    <service class="jrun.servlet.jrpp.JRunProxyService" name="ProxyService">
  <attribute name="activeHandlerThreads">8</attribute>
  <attribute name="minHandlerThreads">1</attribute>
  <attribute name="maxHandlerThreads">1000</attribute>
  <attribute name="mapCheck">0</attribute>
  <attribute name="threadWaitTimeout">20</attribute>
  <attribute name="backlog">500</attribute>
  <attribute name="deactivated">true</attribute>
...
  5. Save the file.
  6. Copy the CFM pages in your web root directory (including the CFIDE and cfdocs directories) to the ColdFusion MX 7 cf_root/wwwroot directory, and use appropriate URL references (for example, http://localhost:8500/YourApp1/index.cfm). If you switch from the built-in web server to an external web server, you must copy the contents of the cf_root/wwwroot directory to your web server root. If you are using Macromedia Dreamweaver, be sure to reconfigure any sites that you move from one server to another.
  7. Restart ColdFusion MX 7.

To switch to another web server, follow the instructions for the appropriate web server on your platform in Configuring web servers.

Note: The installation wizard does not allow you to configure both an external web server and the built-in web server and in most cases, you do not enable both the built-in web server and an external web server. If you do, you must create web server directory mappings so that both web servers use the same web root.


Uninstalling ColdFusion MX 7

The steps for uninstalling ColdFusion MX 7 depend on your operating system.

This section describes the following topics:

  • Uninstalling ColdFusion MX 7 from Windows systems
  • Uninstalling ColdFusion MX 7 from UNIX systems

Uninstalling ColdFusion MX 7 from Windows systems

Uninstalling ColdFusion MX 7 deletes all program files and related components from your computer.

To uninstall ColdFusion MX 7 from Windows:

  1. Select Start > Settings > Control Panel > Add/Remove Programs > Macromedia ColdFusion MX7.
  2. Click Change/Remove.
  3. When the program completes, remove any remaining files and directories in the cf_root directory.
  4. In some cases, the uninstall program may require you to restart the computer.

ColdFusion MX 7 is deleted from your server.

Uninstalling ColdFusion MX 7 from UNIX systems

Uninstalling ColdFusion MX 7 deletes all program files and related components from your computer.

To uninstall ColdFusion MX 7 from UNIX:

  1. Log in as root.
  2. Enter the following command to go to the cf_root/uninstall directory:
    cd cf_root/uninstall
  3. Enter the following command:
    ./uninstall.sh
  4. When the program completes, remove any remaining files and directories in the cf_root directory.

ColdFusion MX 7 is deleted from your server.
Previous


Installing the Multiserver Configuration

This chapter describes how to install Macromedia ColdFusion MX 7 in the multiserver configuration.

Contents

About multiserver configuration

Installing ColdFusion MX 7 using the multiserver configuration

Installing the Verity search server separately

Uninstalling ColdFusion MX 7
Next


About multiserver configuration

When you install ColdFusion MX 7 using the multiserver configuration, the installation wizard automatically deploys and configures ColdFusion MX 7 on its own JRun server. This configuration supports server instance creation in the ColdFusion MX Administrator and lets you manage ColdFusion MX 7 deployments on multiple JRun servers.

If you already have JRun 4 installed and you want to use the server instance creation feature of ColdFusion MX 7, you must uninstall it before you install the multiserver configuration of ColdFusion MX 7.

When you use the multiserver configuration, you can use the ColdFusion MX Administrator to define multiple server instances on a single computer, each running ColdFusion MX 7. Running multiple instances of ColdFusion MX 7 has the following advantages:

Application isolation You deploy an independent application to each server instance. Each server instance has separate settings, and because each server instance runs in its own instance of the JVM, problems encountered by one application have no effect on other applications.

Load balancing and failover You deploy the same application to each server instance and add the instances to a cluster. The web server connector optimizes performance and stability by automatically balancing load and by switching requests to another server instance when a server instance stops running.

For more information on configuring ColdFusion MX 7 on multiple server instances, including detailed information for configuring multiple server instances when running on JRun 4, see Configuring and Administering ColdFusion MX.

For more information about J2EE servers, see J2EE application servers.


Installing ColdFusion MX 7 using the multiserver configuration

This section provides installation instructions for the ColdFusion MX 7 multiserver configuration. You must install ColdFusion MX 7 using the multiserver configuration on a computer that has no previous versions of JRun.

During the multiserver installation procedure, the installation wizard performs the following actions:

  • Installs JRun 4.
  • Creates a JRun server named cfusion (in addition to the admin and samples JRun servers).
  • (Windows) Creates and starts Windows services for the admin and cfusion JRun servers.
  • Configures the jrun_root/bin/jvm.config file, as appropriate for the platform.
  • (Optional) Configures the JRun cfusion server for use with an external web server. In Windows, the installation wizard runs the Web Server Configuration Tool. On UNIX, the installation wizard creates a shell script that you can run to execute the Web Server Configuration Tool with the settings specified in the installation wizard.

    Note: The default JRun web server port for the cfusion server is 8300. However, if you install the multiserver configuration of ColdFusion MX 7 with the built-in server and port 8300 is in use, the installer starts with port 8301 and looks at up to 100 ports to find one that is not being used by an application that is running. ColdFusion MX 7 uses that port and displays a message to indicate which port it selected.

This section describes the following topics:

  • Installing the multiserver configuration in Windows
  • Installing the multiserver configuration on UNIX


Installing the multiserver configuration in Windows

This section explains how to install the multiserver configuration of ColdFusion MX 7 in a Windows platform.

Note: The Windows installer requires a computer that supports at least 256 colors.

To install the multiserver configuration in Windows:

  1. Read the online version of the Release Notes for any late-breaking information or updates. For more information, see www.macromedia.com/go/proddoc_releasenotes.
  2. Ensure that your operating system meets the system requirements described in System requirements.
  3. Review the Installation considerations for Windows and Installation considerations for all platforms.
  4. Determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.
  5. Close any applications that are currently running on your computer.
  6. If you plan to configure an external web server, make sure that the web server is running.
  7. Insert the CD or download the setup file from the Macromedia website.
  8. If the installation wizard does not start automatically when you insert the CD, locate the setup.exe file on the CD and double-click it. If you are installing from a network or a downloaded file, locate the ColdFusion MX 7 installation executable file (coldfusion-70-win.exe) and double-click it.

    The installation wizard starts.

  9. Follow the instructions in the installation wizard and let it run to completion. (Ensure that you select Multiserver configuration.)

    Note: The installation wizard disables the multiserver configuration option if JRun 4 is already installed on the computer.

  10. Open the ColdFusion MX Administrator to configure the server.
  11. After the server configuration is complete, click OK to run the Getting Started Experience.

    If you are new to ColdFusion, you can use the Getting Started Experience to learn about the basics of creating a ColdFusion application. If you are already familiar with ColdFusion, you can view code snippets that highlight the new features in ColdFusion MX 7.

  12. Configure and manage your system, as described in Configuring Your System.
  13. To install the ColdFusion MX 7 Extensions for Dreamweaver, double-click the cfmx7dreamweaverextensions.mxp file, which is located in the cf_webapp_root/wwwroot/CFIDE/installers directory.
  14. To install ColdFusion MX 7 Report Builder, double-click the CFReportBuilderInstaller.exe file, which is in the cf_webapp_root/CFIDE/installers directory. For more information, see Installing the ColdFusion Report Builder.
  15. Code and test ColdFusion MX 7 CFM pages.

    If you configured an external web server, store CFM pages under your web root directory. If you are using the built-in web server, store CFM pages under the web application root (jrun_root/servers/cfusion/cfusion-ear/cfusion-war) and access these pages using a URL of the form http://hostname:8300/context-root/filename.cfm, as follows:

    • hostname The machine name, IP address, or localhost.
    • contextroot The context root for the ColdFusion MX 7 web application. For more information, see Context root.
    • filename The directory path and file to display. The path is relative to the cfusion-war directory.

    For example, to display a CFM file located at C:/JRun4/servers/cfusion/cfusion-ear/cfusion-war/eisapp/index.cfm using the built-in JRun web server and a context root of cfmx, you specify the URL as http://localhost:8300/cfmx/eisapp/index.cfm.


Installing the multiserver configuration on UNIX

This section explains how to install the ColdFusion MX 7 multiserver configuration on UNIX.

To install the multiserver configuration on UNIX:

  1. Read the online version of the Release Notes for any late-breaking information or updates. For more information, see www.macromedia.com/go/proddoc_releasenotes.
  2. Ensure that your operating system meets the system requirements described on the Macromedia web site at www.macromedia.com/go/sysreqscf.
  3. Review the Installation considerations for UNIX and Installation considerations for all platforms.
  4. Determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.
  5. Log in as root.
  6. Copy the installation file that is appropriate for your platform and locale from the CD or Macromedia website, and save it to a directory on your local disk.

    The following are the installation files for supported server configuration platforms:

    • coldfusion-70-lin.bin
    • coldfusion-70-sol.bin
  7. Using the cd command, go to the directory that contains the installation file.
  8. Start the installation with the following command:
    ./<filename> -i console

    The installation program starts.

    Note: To run the UNIX installer in GUI mode, type ./<filename> -i gui.

  9. Follow the instructions in the installation wizard. Ensure that you select Multiserver configuration.

    Note: For security reasons, it is crucial that you do not use root for the runtime user.

  10. When the installation completes successfully, start the JRun cfusion server:
    jrun_root/bin/jrun -start cfusion
  11. If you specified external web server settings when you ran the installation wizard, run the jrun_root/bin/cfmx-connectors.sh shell script. The script runs the Web Server Configuration Tool, which configures the web server for use with ColdFusion MX 7. The web server should also be running.

    If there are problems running this script, review the configuration and bin directory specifications, modify as necessary, and rerun the script. You can also configure your web server using the scripts in jrun_root/bin/connectors, or through java -jar jrun_root/lib/wsconfig.jar, as appropriate.

    Note: This step is important, because if you specified the use of an external web server when you ran the installation wizard, the CFIDE and cfdocs directories are placed under that web server’s root directory, and you must successfully configure the web server before you open the ColdFusion MX Administrator.

  12. Open ColdFusion MX Administrator to run the configuration wizard.
  13. Configure and manage your system, as described in Configuring Your System.
  14. Code and test ColdFusion MX 7 CFM pages.

    If you configured an external web server, store CFM pages under your web root directory. If you are using the built-in web server, store CFM pages under the web application root (jrun_root/servers/cfusion/cfusion-ear/cfusion-war) and access these pages using a URL of the form http://hostname:8300/context-root/filename.cfm, as follows:

    • hostname The machine name, IP address, or localhost.
    • contextroot The context root for the ColdFusion MX 7 web application. For more information, see Context root.
    • filename The directory path and file to display. The path is relative to the cfusion-war directory.

    For example, to display a CFM file located at /opt/jrun4/servers/cfusion/cfusion-ear/cfusion-war/eisapp/index.cfm using the built-in JRun web server and a context root of cfmx, you specify the URL as http://localhost:8300/cfmx/eisapp/index.cfm.


Configuration

In addition to enabling sandbox security in the ColdFusion MX Administrator, the application server must be running a security manager (java.lang.SecurityManager) and you must define the following JVM arguments:

-Djava.security.manager
  -Djava.security.policy="cf_webapp_root/WEB-INF/cfusion/lib/coldfusion.policy"
  -Djava.security.auth.policy="cf_webapp_root/WEB-INF/cfusion/lib/neo_jaas.policy"

You configure these settings by using a text editor to modify the jrun_root/bin/jvm.config file. or through the Settings panel of the JRun Management Console (JMC).


Uninstalling ColdFusion MX 7

The steps for uninstalling ColdFusion MX 7 depend on your operating system.

This section describes the following topics:

  • Uninstalling ColdFusion MX 7 from Windows systems
  • Uninstalling ColdFusion MX 7 from UNIX systems

Uninstalling ColdFusion MX 7 from Windows systems

Uninstalling ColdFusion MX 7 deletes all program files and related components from your computer.

To uninstall ColdFusion MX 7 from Windows:

  1. Select Start > Settings > Control Panel > Add/Remove Programs > Macromedia ColdFusion MX 7 with JRun 4.
  2. Click Change/Remove.
  3. When the program completes, remove any remaining files and directories in the cf_webapp_root directory.
  4. In some cases, the uninstall program may require you to restart the computer.

ColdFusion MX 7 is deleted from your server.

Uninstalling ColdFusion MX 7 from UNIX systems

Uninstalling ColdFusion MX 7 deletes all program files and related components from your computer.

To uninstall ColdFusion MX 7 from UNIX:

  1. Log in as root.
  2. Enter the following command to go to the cf_webapp_root/uninstall directory:
    cd cf_webapp_root/uninstall
  3. Enter the following command:
    ./uninstall.sh
  4. When the program completes, remove any remaining files and directories in the cf_webapp_root directory.

ColdFusion MX 7 is deleted from your server.
Previous


Installing the J2EE Configuration

This chapter describes how to install, deploy, and undeploy Macromedia ColdFusion MX 7 Enterprise Edition in the J2EE configuration. It includes overview information, specific instructions for installing Macromedia JRun 4 (which automatically deploys and configures ColdFusion MX 7), and general instructions for use with all J2EE application servers.

Contents

J2EE application servers

Preparing to install using the J2EE configuration

Installing an EAR file or WAR files

Installing the Verity search server separately

ColdFusion MX 7 J2EE deployment and configuration

Undeploying ColdFusion MX 7
Next


J2EE application servers

One of the main advantages of ColdFusion MX 7 is that it can be installed as an integrated server (the server configuration) or deployed as a Java application on a standards-based J2EE application server (multiserver configuration and J2EE configuration). In addition to greater flexibility, this allows your ColdFusion applications to leverage features of the J2EE architecture, such as support for multiple application instances and multiple-instance clustering.

You can deploy ColdFusion MX 7 in the J2EE configuration using a J2EE application server, such as JRun 4 or IBM WebSphere. When you use the J2EE EAR/WAR configuration, you can use an existing J2EE application server; the installation wizard creates a web application archive (WAR) or enterprise application archive (EAR) file, which you then deploy using the tools provided by your chosen application server.

This section describes the following topics:

  • Choosing EAR or WAR deployment
  • Context root
  • Multiple instances
  • Platforms

Choosing EAR or WAR deployment

In the J2EE environment, you deploy applications in one of the following formats:

Web application archive file Contains the ColdFusion MX 7 application. A web application archive (also called a WAR) uses a directory structure that contains a WEB-INF/web.xml deployment descriptor, which defines the servlets and context parameters it uses. J2EE application servers can deploy web applications in this directory structures as-is or in compressed WAR files that contain these directory structures. However, ColdFusion MX 7 must run from an expanded directory structure:

cfusion (cfusion.war)
  WEB-INF
    web.xml
  CFIDE
  cfdocs
CFIDE (rds.war)
  WEB-INF
    web.xml

The cfusion.war file contains the ColdFusion MX 7 web application. The rds.war file is a web application that redirects requests from /CFIDE to /context-root/CFIDE. It forwards requests to the ColdFusion MX Administrator when ColdFusion MX 7 uses a context root other than a forward slash (/).

Enterprise application archive file Contains the ColdFusion MX 7 and RDS redirector web applications. An enterprise application archive (also called an EAR) uses a directory structure that contains a META-INF/application.xml deployment descriptor, which defines the web applications that it contains. J2EE application servers can deploy enterprise applications in these directory structures as-is or in compressed EAR files that contain these directory structures. However, ColdFusion MX 7 must run from an expanded directory structure:

cfusion-ear
  META-INF
    application.xml
  cfusion-war
    WEB-INF
      web.xml
    CFIDE
    cfdocs
  rds.war
    WEB-INF
      web.xml

If your J2EE application server supports enterprise applications, you should install and deploy the EAR file. For more information, see Installing an EAR file or WAR files.

Context root

Because the J2EE environment supports multiple, isolated web applications running in a server instance, J2EE web applications running in a server are each rooted at a unique base URL, called a context root (or context path). The J2EE application server uses this initial portion of the URL (that is, the portion immediately following http://hostname) to determine which web application services an incoming request.

For example, if you are running ColdFusion MX 7 with a context root of cfmx, you display the ColdFusion MX Administrator using the URL http://localhost/cfmx/CFIDE/administrator/index.cfm.

Most J2EE application servers allow one application in each server instance to use a forward slash (/) for the context root. Setting the context root to / for the ColdFusion MX 7 application is especially useful when serving CFM pages from the web server, because it supports the functionality most similar to previous ColdFusion versions. In addition, the RDS web application is not required if you use a context root of /.

When you deploy the ColdFusion MX 7 EAR file, it uses the context root that you specified when you ran the installation wizard, which copied your specification to the context-root element of the META-INF/application.xml file. When you deploy ColdFusion MX 7 as a WAR file, you use application-server-specific functionality to define the context root.

Note: Each web application running in a server instance must have a unique context root. The JRun default web application uses / for a context root, so if you want to use / for the ColdFusion MX 7 context root when you deploy on JRun, you must either delete the default-war application or change the default-war context root by editing the default-ear/META-INF/application.xml file.

Multiple instances

When you use the J2EE configuration, you can define multiple server instances on a single computer, each running ColdFusion MX 7. Running multiple instances of ColdFusion MX 7 has the following advantages:

Application isolation You deploy an independent application to each server instance. Each server instance has separate settings, and because each server instance runs in its own instance of the JVM, problems encountered by one application have no effect on other applications.

Load balancing and failover You deploy the same application to each server instance and add the instances to a cluster. The web server connector optimizes performance and stability by automatically balancing load and by switching requests to another server instance when a server instance stops running.

For more information on configuring ColdFusion MX 7 on multiple server instances, including detailed information for configuring multiple server instances when running on JRun 4, see Configuring and Administering ColdFusion MX. The multiserver configuration provides the instance manager to make configuring ColdFusion MX 7 on multiple servers easier; however, you can also configure ColdFusion MX 7 on multiple servers manually by deploying EAR files and WAR files on multiple server instances.


Platforms

Full ColdFusion MX 7 functionality is available on Windows, Linux, and Solaris. Additionally, you can install and deploy the all-Java ColdFusion MX 7 J2EE configuration on other platforms, although without the functionality provided by platform-specific binary files (C++ CFXs).


Preparing to install using the J2EE configuration

This section provides installation instructions for the ColdFusion MX 7 J2EE configuration. When you install the J2EE configuration, you have the following options:

New installation -- multiserver configuration Use this option to install a copy of Macromedia JRun 4 with ColdFusion MX 7 deployed and configured as an enterprise application in a JRun server. For installation details, see Installing ColdFusion MX 7 using the multiserver configuration. Macromedia recommends this configuration option if JRun or another J2EE application server is not already installed on the computer and you plan to use JRun 4 instead of another J2EE application server.

New installation -- create an EAR or WAR file Use this option if you already have a J2EE application server running on the computer. The installation wizard creates an EAR file or two WAR files, which you deploy using J2EE application-server-specific tools or utilities. For installation details, see Installing an EAR file or WAR files.


Installing an EAR file or WAR files

If your computer is already running a J2EE application server, the installation wizard creates an EAR file or WAR files, which you deploy using application-server-specific tools.

The ColdFusion MX 7 J2EE configuration must run from an expanded directory structure. Different J2EE application servers have different functionality with regard to deployment and an expanded directory structure, as follows:

Deploy compressed archive to working directory On some J2EE application servers (such as IBM WebSphere), the deployment process expands the EAR/WAR file into a working directory and, from that point forward, the expanded directory is considered to be the application. For these application servers, you deploy the compressed EAR/WAR file and work in the resulting directory structure.

Deploy expanded archive as working directory On other application servers (such as JRun 4 and BEA WebLogic), the deployment process expands the EAR/WAR file into a temporary directory and (conceptually), the compressed EAR/WAR file is still considered to be the application. For these application servers, you must expand the EAR/WAR file manually, and then deploy the expanded directory structure, which becomes your working directory.

The following sections provide installation procedures for Windows and UNIX systems. For more about deployment and configuration, see ColdFusion MX 7 J2EE deployment and configuration.

This section describes the following topics:

  • Installing an EAR file or WAR files in Windows
  • Installing an EAR file or WAR files on UNIX
  • Updating from ColdFusion MX or ColdFusion MX 6.1 for J2EE


Installing an EAR file or WAR files in Windows

This section explains how to install the ColdFusion MX 7 J2EE configuration in Windows. If you are updating an existing deployment of ColdFusion MX or ColdFusion MX 6.1 for J2EE, see Updating from ColdFusion MX or ColdFusion MX 6.1 for J2EE before you continue.

Note: The Windows installer requires a computer that supports at least 256 colors.

To install ColdFusion MX 7 in Windows (J2EE configuration):

  1. Read the online version of the Release Notes for any late-breaking information or updates. For more information, see www.macromedia.com/go/proddoc_releasenotes.
  2. Ensure that your operating system meets the system requirements described in System requirements.
  3. Review the Installation considerations for Windowsand Installation considerations for all platforms.
  4. Determine and record environment information, as described in Preparing to install using the J2EE configuration.
  5. Determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7
  6. Close any applications that are currently running on your computer.
  7. Insert the CD or download the setup file from the Macromedia website.
  8. If the installation wizard does not start automatically when you insert the CD, locate the setup.exe file on the CD and double-click it. If you are installing from a network or a downloaded file, locate the ColdFusion MX 7 installation executable file (coldfusion-70-win.exe) and double-click it.

    The installation wizard starts.

  9. Follow the instructions in the wizard, and let it run to completion.
  10. Deploy ColdFusion MX 7 and configure Java settings, as required by your application server. For more information, see ColdFusion MX 7 J2EE deployment and configuration.
  11. Open ColdFusion MX Administrator to run the configuration wizard.
  12. To install the ColdFusion MX 7 Extensions for Dreamweaver, double-click the cfmx7dreamweaverextensions.mxp file, which is located in the cf_webapp_root/wwwroot/CFIDE/installers directory.
  13. To install ColdFusion MX 7 Report Builder, double-click the CFReportBuilderInstaller.exe file, which is in the cf_webapp_root/CFIDE/installers directory. For more information, see Installing the ColdFusion Report Builder.
  14. Configure and manage your system, as described in Configuring Your System.
  15. Code and test ColdFusion CFM pages.

    Store CFM pages under the web application root (either cfusion-ear\cfusion-war or cfusion-war) and access these pages using a URL of the form http://hostname:portnumber/context-root/filename.cfm, as follows:

    • hostname The machine name, IP address, or localhost.
    • portnumber The port number used by your application server’s web server.
    • contextroot The context root for the ColdFusion MX 7 web application. For more information, see Context root.
    • filename The directory path and file to display. The path is relative to the cfusion-war directory.

    For example, to display a CFM file located at C:\JRun4\servers\myserver\cfusion-ear\cfusion-war\eisapp\index.cfm using the built-in JRun web server and a context root of cfmx, you specify the URL as http://localhost:8100/cfmx/eisapp/index.cfm.


Installing an EAR file or WAR files on UNIX

This section explains how to install the ColdFusion MX 7 J2EE configuration on UNIX. If you are updating an existing deployment of ColdFusion MX or ColdFusion MX 6.1 for J2EE, see Updating from ColdFusion MX or ColdFusion MX 6.1 for J2EE before you continue.

By default, the ColdFusion MX 7 J2EE installation places files in the /opt/cfmx7 directory. To install into a different directory, you must create that directory before you run the installation.

To install ColdFusion MX 7 on UNIX (J2EE configuration):

  1. Read the online version of the Release Notes for any late-breaking information or updates. For more information, see www.macromedia.com/go/proddoc_releasenotes.
  2. Ensure that your operating system meets the system requirements described on the Macromedia web site at www.macromedia.com/go/sysreqscf.
  3. Review the Installation considerations for UNIX and Installation considerations for all platforms.
  4. Determine and record environment information, as described in Preparing to install using the J2EE configuration.
  5. Determine the answers to the questions in the section Gathering information necessary to install ColdFusion MX 7.
  6. Log in as root.
  7. Copy the installation file that is appropriate for your platform and locale from the CD or Macromedia website, and save it to a directory on your local disk.

    The following are the installation files for supported J2EE configuration platforms:

    • coldfusion-70-lin.bin
    • coldfusion-70-sol.bin
    • coldfusion-70-other.jar
  8. Using the cd command, go to the directory with the installation file.
  9. Start the installation with the following command:
    ./<filename> -i console

    The installation program starts.

    To use the coldfusion-70-other.jar file to install on a UNIX platform other than Solaris or Linux, enter the following command (for more information, see Installation considerations for UNIX):

    java_home/bin/java -jar coldfusion-70-other.jar -i console

    Note: To run the UNIX installer in GUI mode, type ./<filename> -i gui.

  10. Follow the prompts, and let the installation program run to completion.

    Caution: For security reasons, it is crucial that you do not use root for the runtime user.

  11. Deploy ColdFusion MX 7 and configure Java settings, as required by your application server. For more information, see ColdFusion MX 7 J2EE deployment and configuration.

    Note: If you deployed the rds.war file, and an error message indicates that RDS is not installed or not enabled, edit the rds.properties file to match the ColdFusion context root, restart the application server, and re-open the ColdFusion MX Administrator.

  12. Open the ColdFusion MX Administrator to run the Configuration Wizard.
  13. Configure and manage your system, as described in Configuring Your System.
  14. Code and test ColdFusion MX 7 CFM pages.

    Store CFM pages under the web application root (either cfusion-ear/cfusion-war or cfusion-war) and access these pages using a URL of the form http://hostname:portnumber/context-root/filename.cfm, as follows:

    • hostname The machine name, IP address, or localhost.
    • portnumber The port number used by your application server’s web server.
    • contextroot The context root for the ColdFusion MX 7 web application. For more information, see Context root.
    • filename The directory path and file to display. The path is relative to the cfusion-war directory.

    For example, to display a CFM file located at /opt/jrun4/servers/myserver/cfusion-ear/cfusion-war/eisapp/index.cfm using the built-in JRun web server and a context root of cfmx, you specify the URL as http://localhost:8100/cfmx/eisapp/index.cfm.


Updating from ColdFusion MX or ColdFusion MX 6.1 for J2EE

If you previously deployed ColdFusion MX for J2EE or the ColdFusion MX 6.1 J2EE configuration on your application server, you must also perform the following steps as part of the installation procedure:

  1. As appropriate for your application server, either stop the ColdFusion application and RDS application (if it is running), or stop the application server before you start the installation wizard.
  2. (Windows only) If you installed the SequelLink ODBC Agent, stop the ColdFusion MX or ColdFusion MX 6.1 ODBC services before you start the installation wizard.
  3. Copy application files to a backup directory.
  4. Save settings by copying the ColdFusion MX 6.1files cf_webapp_root/WEB-INF/cfusion/lib/neo-*.xml to a backup directory
  5. Before you deploy ColdFusion MX 7, undeploy the existing ColdFusion MX or ColdFusion MX 6.1 application using your application-server-specific undeploy functionality.
  6. Create a directory named cf6settings in the cf_webapp_root/WEB-INF/cfusion/lib directory.
  7. Copy the backed up ColdFusion MX 6.1files settings files to the ColdFusion MX 7 cfusion/lib/cf6settings directory.
  8. Edit the ColdFusion MX 7 cfusion/lib/adminconfig.xml file by setting the value of the runmigrationwizard and the migratef6 switch to true.
  9. Restart the ColdFusion MX 7 application.
  10. Browse to ColdFusion MX Administrator to run the migration wizard.

Note: Migration from ColdFusion 4.5 or 5 to the ColdFusion MX J2EE configuration is not supported.


Installing the Verity search server separately

To enable searches using Verity, you must install the Verity search server separately if either of the following is true:

  • You are running ColdFusion in a J2EE configuration with a WAR or EAR file.
  • You want to install the Verity search server on a different machine from the one where you install ColdFusion MX 7.

You should start by planning the answers to questions asked by the Installer:

  • "Where would you like to install?" _______________________________

    Macromedia recommends that you specify a location that is not a subdirectory of the application server directories.

  • The IP address of the ColdFusion Server that this machine will accept requests from__________________

The IP address is necessary only if you are installing Verity search server on a different computer from the one where you installed ColdFusion MX 7. If you do not specify an IP address, the Installer uses the default 127.0.0.1, which is localhost.

To install the Verity search server separately:

  1. Download your platform-specific installer from the Macromedia website at www.macromedia.com/go/verity or copy it from the ColdFusion MX CD, as follows:
    • Windows - coldfusion-search.win.exe
    • Linux - coldfusion-search-lin.bin
    • Solaris - coldfusion-search-sol.bin
  2. Close any applications that are currently running on your computer.
  3. Run the platform-specific installer using the appropriate command.

    Note: Only console installations are available for UNIX systems.

  4. (UNIX only) If you chose not to start the Verity search server automatically, start, stop, and restart Verity by running verity_root/bin/cfmxsearch -start | -stop | -restart.


ColdFusion MX 7 J2EE deployment and configuration

The J2EE specification allows application servers to handle compressed and expanded deployments in a server-dependent manner; each application server has its own deployment and configuration mechanism, as the following table shows:

Application server | Deployment mechanism | Expanded or compressed deployment
JRun 4 | Auto deploy to server root | Expanded
IBM WebSphere | IBM WebSphere Administrative Console | Compressed
BEA WebLogic | WebLogic Administration Console | Expanded

For basic deployment information, see your J2EE application server documentation. ColdFusion MX 7 deployment instructions differ for each J2EE application server. For up-to-date information on deploying ColdFusion MX 7 on a variety of J2EE application servers, see www.macromedia.com/go/cfmx7_j2eecert.

For more information, see Deployment and Configuration.

This section describes the following topics:

  • Deployment
  • Configuration
  • ColdFusion MX 7 J2EE deployment and configuration


Deployment

The instructions at www.macromedia.com/go/cfmx7_j2eecert provide detailed, application-server-specific ColdFusion MX 7 deployment instructions. Depending on your application server, the instructions describe deployment of an EAR file or WAR files in either a compressed archive or an expanded directory structure. When you deploy ColdFusion MX 7 on an existing version of JRun 4, you must expand the EAR file or WAR files manually before deployment.

The following procedures describe EAR and WAR deployment on an existing version of JRun 4.

Tip: The instructions for expanding the cfusion.ear file also apply when deploying ColdFusion MX 7 on BEA WebLogic.

Expanding and deploying an EAR file on JRun 4

Before you deploy ColdFusion MX 7 as an enterprise application on an existing JRun server, you must expand the EAR and the WAR files that it contains.

Note: If you are already using an application with an empty context root, you must use a context root other than / for the cfusion-ear file. If you specified / when you installed ColdFusion MX 7, you can change it by opening the cfusion-ear/META-INF/application.xml file in a text editor and modifying the context-root element. After you deploy the cfusion-ear file, you access ColdFusion pages by specifying http://hostname:portnumber/contextroot/pagename.cfm.

To deploy ColdFusion MX 7 as an enterprise application on JRun 4:

  1. Run the installation wizard for your platform, as described in Installing an EAR file or WAR files. Select the EAR option. When you get to the deployment step, return to these instructions.

    If you are updating an existing deployment of ColdFusion MX or ColdFusion MX 6.1 for J2EE, you must undeploy ColdFusion MX or ColdFusion MX 6.1 for J2EE before you deploy ColdFusion MX 7, as described in Updating from ColdFusion MX or ColdFusion MX 6.1 for J2EE.

  2. Expand the EAR file by performing the following steps:
    1. Open a console window, navigate to the directory that contains the EAR file, and make a new directory named cfusion-ear:
          md cfusion-ear (mkdir cfusion-ear on UNIX)
    2. Change to the cfusion-ear directory and expand the cfusion.ear file with the jar command:
          cd cfusion-ear
    java_home/bin/jar -xvf ../cfusion.ear

      This expands the cfusion.ear file into cfusion.war and rds.war (rds.war is not included if you specified a context root of / when you ran the installation wizard).
    3. In cfusion-ear, make a new directory named cfusion-war.
          md cfusion-war (mkdir cfusion-war on UNIX)
    4. Change to the cfusion-war directory and expand the cfusion.war file with the jar command:
          cd cfusion-war
    java_root/bin/jar -xvf ../cfusion.war

      This expands the cfusion.war file.
    5. (If rds.war exists) Go up one level to cfusion-ear, make a new directory named rds-war.
          cd ..
    md rds-war (mkdir rds-war on UNIX)
    6. (If rds.war exists) Change to the rds-war directory and expand rds.war with the jar command:
          cd rds-war
    java_root/bin/jar -xvf ../rds.war

      This expands rds.war.
    7. Go up one level to the cfusion-ear file, and delete the cfusion.war and rds.war files:
          cd ..
    del cfusion.war (rm cfusion.war on UNIX)
    del rds.war (rm rds.war on UNIX)
    8. Open the cfusion-ear/META-INF/application.xml file in a text editor.
    9. Change the web-uri element from cfusion.war to cfusion-war (or the name of the directory that contains the expanded cfusion.war file). Change the web-uri element for rds.war to rds-war. A directory name in the web-uri element cannot contain a dot.
    10. Save the application.xml file.
  3. Deploy ColdFusion MX 7 by copying the cfusion-ear directory structure to the jrun_root/servers/servername directory. If auto deploy is enabled, JRun 4 either deploys the application immediately (if the JRun server is running), or when you start the JRun server.
  4. Review the server log (jrun_root/logs/servername-event.log) to ensure that ColdFusion MX 7 deployed successfully.

Expanding and deploying WAR files on JRun 4

When you deploy ColdFusion MX 7 as a web application on an existing JRun server, you expand the cfusion.war file, deploy it, and optionally modify the context root. For complete information on deploying ColdFusion MX 7 on JRun 4 as a WAR file, see www.macromedia.com/go/cfmx7_j2eecert.


Configuration

After you deploy the ColdFusion MX 7 application, you define JVM arguments. Each J2EE application server has a different method for defining JVM arguments. Depending on your server, you can update variables in a batch file or shell script, define arguments in an administrative interface, modify the java.library.path JVM argument directly, or modify the system path directly. You define two types of JVM arguments:

  • Platform-specific items for the java.library.path argument
  • Java arguments for the java.args argument

Note: When running JRun 4, you configure these settings through the Settings panel of the JRun Management Console (JMC) or by using a text editor to modify the jrun_root/bin/jvm.config file.

After you deploy the ColdFusion MX 7 J2EE configuration, you can run basic ColdFusion pages and start the ColdFusion MX Administrator. However, certain types of ColdFusion MX 7 functionality are performed through platform-specific binary files (that is, compiled C++ files, not Java bytecode), which are provided for Windows, Solaris, and Linux. In addition, some of these features require server-specific environment settings. The following list includes platform-specific functionality and the steps you must perform to enable their use:

COM (Windows only) Add the following jIntegra binary directories to the JVM’s native library path (java.library.path):

WEB-INF/cfusion/jintegra/bin
WEB-INF/cfusion/jintegra/bin/international

Note: If your J2EE server runs on an operating system other than Windows, Solaris, or Linux, you can still run ColdFusion MX 7, but the functionality that is provided through platform-specific binary files is unavailable. For a complete list of supported platforms, see System requirements.

Depending on your operating system, you might have to add the following to the java.args JVM argument:

COM (Windows only) Add the following arguments:

-DJINTEGRA_NATIVE_MODE -DJINTEGRA_PREFETCH_ENUMS

CORBA (optional) Copy the vbjorb.jar file to the WEB-INF/cfusion/lib directory and define the following argument:

-Xbootclasspath/a:"cf_webapp_root/WEB-INF/cfusion/lib/vbjorb.jar"

Charting (UNIX only) Define the following argument:

-Djava.awt.graphicsenv=com.gp.java2d.ExGraphicsEnvironment"

For JDK 1.4.1 and later versions, specify com.gp.java2d.ExHeadlessGraphicsEnvironment instead of com.gp.java2d.ExGraphicsEnvironment.

Security In addition to enabling sandbox security in the ColdFusion MX Administrator, the application server must be running a security manager (java.lang.SecurityManager) and you must define the following JVM arguments:

-Djava.security.manager
  -Djava.security.policy="cf_webapp_root/WEB-INF/cfusion/lib/coldfusion.policy"
  -Djava.security.auth.policy="cf_webapp_root/WEB-INF/cfusion/lib/neo_jaas.policy"

Additional setup To use cfregistry on Windows, to use the cfreport tag for Crystal Reports, and to use any C++ CFX custom tags, you must add cfusion/lib to the Java library path. Add the following directory to the JVM’s native library path (java.library.path):

WEB-INF/cfusion/lib

Additionally, certain application servers require that you disable server-specific policy-file permissions in order to enable the ColdFusion security manager. For more information, see the application-server-specific instructions at www.macromedia.com/go/cfmx7_j2eecert.

If the version of the tools.jar file in your application server’s JRE is different from the version of the tools.jar file in the WEB-INF/cfusion/lib directory, you should rename or delete the WEB-INF/cfusion/lib/tools.jar file to ensure that your application server’s tools.jar file is used.


ColdFusion MX 7 J2EE configuration directory structure

The following table describes the directories under the cf_webapp_root web application directory when you use the J2EE configuration:

Directory | Description
cfdocs | Documentation for ColdFusion MX 7.
CFIDE | Files for the ColdFusion MX Administrator.
WEB-INF/cfclasses | Compiled ColdFusion templates in your ColdFusion MX applications.
WEB-INF/cfc-skeletons | Support for ColdFusion components that are exported as web services.
WEB-INF/cfform | Files that support Flash forms.
WEB-INF/cftags | Templates for ColdFusion MX.
WEB-INF/gateway | Files that support event gateways.
WEB-INF/cfusion/bin | Executable files used by ColdFusion MX.
WEB-INF/cfusion/cfx | CFX tag include file and examples.
WEB-INF/cfusion/charting | Files for the ColdFusion MX graphing and charting engine.
WEB-INF/cfusion/Custom Tags | Repository for your custom tags.
WEB-INF/cfusion/db | Sample databases: in Windows, the files for sample Microsoft Access databases and ODBC services; on UNIX, the files for the sample PointBase databases. Also includes software for installing ODBC support and other database system-specific files.
WEB-INF/cfusion/jintegra | JIntegra programs, libraries, and other supporting files (for example, to integrate Java and COM code; manage access to ActiveX controls (OCXs) that are hosted in a graphical user interface (GUI) container; and register the JVM and type libraries).
WEB-INF/cfusion/lib and WEB-INF/lib | JAR, XML, property, and other files that are the foundation of ColdFusion MX, including functionality such as queries, charting, mail, security, Verity searches, and system probes.
WEB-INF/cfusion/logs | ColdFusion MX log files.
WEB-INF/cfusion/Mail | Files, including spool files, used by ColdFusion MX for mail.
WEB-INF/cfusion/registry | Used only in UNIX, by the cfregistry tag.
WEB-INF/cfusion/stubs | Compiled code for web services.
WEB-INF/cfusion/verity | Verity collections.


Undeploying ColdFusion MX 7

To undeploy ColdFusion MX 7 in the J2EE configuration, you use application-server specific undeploy tools and methods.

To undeploy ColdFusion MX 7 in the J2EE configuration:

  1. Remove all ColdFusion MX 7 specifications from the java.args and java.library.path JVM arguments used by your application server.
  2. (Windows only) If you installed ODBC support, remove the ODBC Windows services by navigating to the cf_webapp_root\WEB_INF\cfusion\db\SequeLink Setup directory and executing the RemoveSequeLink.bat file.
  3. If necessary, copy and save CFM pages from the ColdFusion MX 7 web application root.
  4. Undeploy the ColdFusion MX 7 web application, using application-server-specific undeploy functionality. In JRun 4, you undeploy by deleting the jrun_root/server/servername/cfusion-ear directory.
  5. If necessary, restart the application server.
Previous


Configuring Your System

This chapter describes how to manage ColdFusion MX 7 services and processes, how to configure web servers manually, and how to change user accounts and configure databases for ColdFusion MX 7.

Note: In this chapter, cf_root refers to your installation directory in the server configuration. By default, this directory is C:\CFusionMX7 in Windows, and /opt/coldfusionmx7 on UNIX. Jrun_root refers your installation directory in the multiserver configuration. By default, this directory is C:\JRun4 in Windows and /opt/jrun4 on UNIX.

Contents

Overview of configuration tasks

Managing ColdFusion MX 7

Configuring web servers

Installing Verity Locales

Enabling CORBA support

Disabling Remote Development Services

Disabling JSP functionality (server configuration only)

Changing the ColdFusion MX 7 user account in Windows

Connecting to an external JDBC Type 4 data source
Next


Overview of configuration tasks

The following table describes when to do the configuration tasks that are documented in this chapter:

Configuration task | When to do it
Managing ColdFusion MX 7 | You must stop and restart ColdFusion MX 7 after you enable or disable security in the ColdFusion MX Administrator or change any of the Java and JVM settings, in order for your changes to take effect. You can do this at any time after you install ColdFusion MX 7.
Configuring web servers | When moving to a production server or when the built-in web server no longer meets your needs.
Enabling CORBA support | You must do this only if you must make CORBA invocations from ColdFusion MX 7. You can do this after you install ColdFusion MX 7 and before you make a CORBA call from ColdFusion MX 7.
Disabling Remote Development Services | For security reasons, disable RDS when you move an application to the production environment.
Disabling JSP functionality (server configuration only) | When running ColdFusion MX 7 Enterprise Edition in a hosted environment, you might want to disable JSP processing.
Changing the ColdFusion MX 7 user account in Windows | You must do this only if you discover that the account under which ColdFusion MX 7 is running has inappropriate access rights; for example, to interact with remote data sources, other application pages, or COM objects. You can do this after you install ColdFusion MX 7 and before you deploy your application.
Connecting to an external JDBC Type 4 data source | You must do this only if you use a Type 4 database driver that is not included in ColdFusion MX 7. You can do this after you install ColdFusion MX 7 and before you set up the data source in the ColdFusion MX Administrator.

For information about additional configuration tasks, see Configuring and Administering ColdFusion MX.


Managing ColdFusion MX 7

The ColdFusion MX 7 installation creates a few services in Windows and a single process on UNIX. The following sections describe how to manage the services:

  • Managing ColdFusion MX 7 services in Windows
  • Managing the ColdFusion MX 7 process on UNIX


Managing ColdFusion MX 7 services in Windows

This section describes the ColdFusion MX 7 services and explains how to manage them.

Overview of services

The ColdFusion MX 7 server configuration installation creates the following service in Windows 2000, Windows XP, and Windows 2003:

Service | Purpose
ColdFusion MX 7 Application Server | The main ColdFusion service. ColdFusion pages cannot be processed if this service is not running.

The multiserver configuration installation creates the following services in Windows 2000, Windows XP, and Windows 2003:

Service | Purpose
Macromedia JRun Admin Server | Runs the admin JRun server, used by the JRun Management Console (JMC).
Macromedia JRun CFusion Server | Runs the JRun cfusion server. Contains ColdFusion MX 7 deployed as an enterprise application.

All Windows configurations install the following services for ODBC support:

Service | Purpose
ColdFusion MX 7 ODBC Agent | The service used to configure data sources for the ColdFusion MX ODBC Server.
ColdFusion MX 7 ODBC Server | The middle-tier service for ODBC connections that use the DataDirect drivers for Microsoft Access and ODBC Socket.

All Windows configurations install the following services for Verity support:

Service | Purpose
ColdFusion MX 7 Search Service | Provides support for the ColdFusion MX 7 search tags.. You cannot use the ColdFusion MX 7 search tags if this process is not running..

Note: If you have ColdFusion MX 6.1 installed, any services named ColdFusion MX refer to ColdFusion MX 6.1 services; ColdFusion MX 7 services are named ColdFusion MX 7.

Starting and stopping services

This section describes how to start and stop Windows services.

Note: In the ColdFusion MX Administrator, if you enable or disable security or change any option in the Java and JVM Settings page, you must stop and restart ColdFusion MX 7 for your changes to take effect. This applies to the server configuration only; in the multiserver and J2EE configurations, you use application-server-specific methods to update Java settings.

To start or stop a ColdFusion service:

  1. Open the Services dialog box:
    • In Windows 2000, Windows XP, or Windows 2003, select Start > Settings > Control Panel > Administrative Tools > Services.
    • For other Windows platforms, see the Windows online Help.

    If a service is running, its status appears as Started in the Status column. If it is not running, no status appears for the service.

  2. Right-click a service, and select Stop, Start, or Restart.

    The Services window refreshes.

To set ColdFusion MX 7 to start automatically or manually:

  1. Open the Services dialog box:
    • In Windows 2000, Windows XP, or Windows 2003, select Start > Settings > Control Panel > Administrative Tools > Services.
    • For other Windows platforms, see the Windows online Help.
  2. In Windows 2000, Windows XP, or Windows 2003, right-click the service that you want to configure, and select Properties.
  3. In the Properties dialog box, click the General tab.
  4. Select one of the following options in the Startup Type frame or drop-down list box:
    • Automatic Starts the service automatically when you start the computer.
    • Manual Requires a user or dependent service to manually start the service.
  5. Click OK.


Managing the ColdFusion MX 7 process on UNIX

This section describes the ColdFusion MX 7 process and explains how to manage it.

Note: This discussion applies to the ColdFusion MX 7 server configuration only. With the multiserver or J2EE configuration, you start and stop ColdFusion MX 7 by starting the application server.

Overview of the ColdFusion MX 7 process

The ColdFusion MX 7 installation creates a single process on UNIX called cfusion. To check whether it is running, use the following command:

ps -eaf | grep cfusion

If it is running, your computer returns something similar to the following line:

nobody 4528 1 10 12:44 pts/0 00:00:07 /opt/coldfusionmx/bin/cfusion -start default

Managing the process

The ColdFusion MX 7 process starts automatically when you start your computer and shuts down automatically when you shut down your computer.

In the ColdFusion MX Administrator, if you enable or disable security or change any option in the Java and JVM Settings page, you must stop and restart the ColdFusion MX 7 process for your changes to take effect. This applies to the server configuration only; in the multiserver and J2EE configurations, you use application-server-specific methods to update Java settings.

To manage the ColdFusion MX 7 process on UNIX:

  1. Log in as root, if you have not already done so.
  2. Enter the following command:
    cd cf_root/bin
  3. Enter the appropriate command for what you need to do, as the following table describes:

    Task

    Command to enter

    Start ColdFusion MX 7

    coldfusion start

    Stop ColdFusion MX 7

    coldfusion stop

    Restart ColdFusion MX 7

    coldfusion restart

    View performance information for ColdFusion MX 7

    coldfusion status

    Run Web Server Configuration Tool

    coldfusion wsconfig


Configuring web servers

This section describes how to configure a web server to serve ColdFusion pages, for Windows and UNIX. Do this if you did not configure a web server automatically during installation, to change your web server, or to configure a web server for a cluster.

You configure an external web server connection using the Web Server Configuration Tool, which you can run either through a graphical user interface (GUI) or the command line. The Windows discussions describe GUI mode, and the UNIX instructions describe command-line mode; however, you can use GUI mode on UNIX if you have access to a graphical environment.

Tip: ColdFusion MX 7 provides batch files and shell scripts in the cf_root/bin/connectors directory to help you get started with command-line usage.

For more information on the Web Server Configuration Tool, including information on multihoming and distributed usage, see Configuring and Administering ColdFusion MX.

Note: If you cannot verify your configuration, repeat the procedure. If the problem persists, contact Macromedia Technical Support for assistance, or manually create the element that you cannot verify in the configuration (for example, manually add an entry to the Apache httpd.conf file, as described in this section).

Configuring web servers in Windows

This section explains how to configure the following web servers in Windows:

  • Configuring IIS in Windows
  • Configuring SunONE Web Server or iPlanet web server in Windows
  • Configuring Apache web server in Windows

Configuring IIS in Windows

This section describes how to configure IIS for ColdFusion MX in Windows, and how to verify your configuration. You configure IIS using the Web Server Configuration Tool in either GUI or command-line mode. This discussion describes how to use GUI mode.

Tip: (Server configuration only) To use the command line, open the batch files located in cf_root\bin\connectors.

For more information, see the Web Server Management chapter in Configuring and Administering ColdFusion MX.

To configure IIS for ColdFusion MX 7 in Windows:

  1. Start the Web Server Configuration Tool by selecting Start > Programs > Macromedia > ColdFusion MX 7 > Web Server Configuration Tool.
  2. Click Add.
  3. In the Server drop-down list box, select the host name and the server or cluster name that you want to configure. In the ColdFusion MX 7 server configuration, the server name is always coldfusion. Clustering support is not available on the server configuration.

    Note: The server or cluster does not have to reside on the web server computer.

  4. In the Web Server Properties area, select IIS and specify the website. For IIS, you typically specify All.
  5. Select the Configure web server for ColdFusion MX applications option.

    Caution: Omitting the previous step causes your web server to serve ColdFusion MX 7 source code.

  6. Click OK.
  7. Copy the CFIDE and cfdocs directories from cf_root/wwwroot to your web server root directory. In addition, copy your application’s CFM pages from cf_root/wwwroot to your web server root directory. In the multiserver configuration, these files are under the jrun_root/servers/cfusion/cfusion-ear/cfusion-war directory.

To verify your IIS configuration:

  1. Verify that the following file was created: cf_root/runtime/lib/wsconfig/jrun.dll (server configuration) or jrun_root/lib/wsconfig/jrun.dll (multiserver configuration). On IIS6, this file is named jrun_iis6.dll.
  2. For each of your IIS websites, verify that application mappings for .cfm, .cfml, .cfc, .cfswf, .cfr, .jsp, and .jws were added, as follows:
    1. In IIS, right-click an IIS website and select Properties.
    2. In the Properties dialog box, on the Home Directory tab, click Configuration.
    3. In the Application Configuration dialog box, click the App Mappings tab.

      You should see mappings for .cfm, .cfml, .cfc, .cfswf, .cfr, .jsp, and .jws in the Extension column.

  3. Verify that each of your IIS websites has a virtual directory called JRunScripts.

    The following figure shows a sample JRunScripts virtual directory:

    The IIS virtual directory for ColdFusion MX, called JRunScripts

  4. Verify that the JRunScripts directory in each of your IIS websites points to the correct location, as follows:
    1. Right-click the JRunScripts directory and select Properties.
    2. In the Properties dialog box, on the Virtual Directories tab, verify that the Local Path text box contains the following path:

      path/wsconfig/number (typically 1)

Configuring SunONE Web Server or iPlanet web server in Windows

This section describes how to configure SunONE Web Server 6 or iPlanet web server 6.x for ColdFusion MX 7 in Windows, and how to verify your configuration. You configure SunONE or iPlanet using the Web Server Configuration Tool in either GUI or command-line mode. This discussion describes how to use GUI mode.

Tip: (Server configuration only) To use the command line, open the batch files located in cf_root/bin/connectors.

For more information, see the Web Server Management chapter of Configuring and Administering ColdFusion MX.

To configure SunONE or iPlanet for ColdFusion MX 7 in Windows:

  1. Start the Web Server Configuration Tool by selecting Start > Programs > Macromedia > ColdFusion MX 7 > Web Server Configuration Tool.
  2. Click Add.
  3. In the Server drop-down list box, select the host name and the server or cluster name to configure. For the ColdFusion MX 7 server configuration, this is always coldfusion. Clustering support is not available on the server configuration.

    Note: The server or cluster does not have to reside on the web server computer.

  4. In the Web Server Properties area, select SunONE Web Server (iPlanet) or Netscape Enterprise Server (NES), and specify the path to the directory that contains the obj.conf file.
  5. Select the Configure web server for ColdFusion MX applications option.

    Caution: Omitting the previous step causes your web server to serve ColdFusion MX 7 source code.

  6. Click OK.
  7. Copy the CFIDE and cfdocs directories from cf_root/wwwroot to your web server root directory. In addition, copy your application’s CFM pages from cf_root/wwwroot to your web server root directory. In the multiserver configuration, these files are under the jrun_root/servers/cfusion/cfusion-ear/cfusion-war directory.

To verify your SunONE or iPlanet configuration:

  1. Verify that the following file was created: cf_root/runtime\lib\wsconfig\number\jrun_nsapi35.dll (server configuration) or jrun_root/lib/wsconfig/number/jrun_nsapi35.dll (multiserver configuration).
  2. Open the SunONE configuration file, obj.conf, in the web server directory (for example, in C:\iPlanet\Servers\https-yourserver\config\obj.conf).
  3. Verify that the following line was added to the file:
    NameTrans fn="jrunfilter"
  4. Verify that #JRun prefixes the following NameTrans line in the file:
    #JRun NameTrans fn="pfx2dir" from="/servlet"
    dir="$docroot/servlet" name="ServletByExt"
  5. Verify that the following object element is at the end of the file:
    <Object name="jrun">
PathCheck fn="jrunfilter"
Service fn="jrunservice"
</Object>

Configuring Apache web server in Windows

This section describes how to configure the Apache web server for ColdFusion MX 7 in Windows, and how to verify your configuration. You configure Apache using the Web Server Configuration Tool in either GUI or command-line mode. This discussion describes how to use GUI mode.

Tip: (Server configuration only) To use the command line, open the batch files located in cf_root\bin\connectors.

For more information, see the Web Server Management chapter in Configuring and Administering ColdFusion MX.

To configure Apache for ColdFusion MX 7 in Windows:

  1. Start the Web Server Configuration Tool by selecting Start > Programs > Macromedia > ColdFusion MX 7 > Web Server Configuration Tool.
  2. Click Add.
  3. In the Server drop-down list box, select the host name and the server or cluster name to configure. For the ColdFusion MX 7 server configuration, this is always coldfusion. Clustering support is not available on the server configuration.

    Note: The server or cluster does not have to reside on the web server computer.

  4. In the Web Server Properties area, select Apache and specify the path to the directory that contains the httpd.conf file.
  5. Select the Configure web server for ColdFusion MX applications option.

    Caution: Omitting the previous step causes your web server to serve ColdFusion MX 7 source code.

  6. Click OK.
  7. Copy the CFIDE and cfdocs directories from cf_root/wwwroot to your web server root directory. In addition, copy your application’s CFM pages from cf_root/wwwroot to your web server root directory. In the multiserver configuration, these files are under the jrun_root/servers/cfusion/cfusion-ear/cfusion-war directory.

To verify your Apache configuration:

  1. Verify that one of the following files was created:
    • cf_root\runtime\lib\wsconfig\number\mod_jrun.so (Apache 1.3.2.7)
    • cf_root\runtime\lib\wsconfig\number\mod_jrun20.so (Apache 2.x)

    In the multiserver configuration, this file is located under jrun_root/lib/wsconfig.

  2. Open the Apache configuration file, httpd.conf, in your Apache conf directory. In Windows, the default is C:\Program Files\Apache Group\Apache\conf\httpd.conf.

    Verify that the following code is appended to this file:

    # JRun Settings
LoadModule jrun_module "c:/CFusionMX7/runtime/lib/wsconfig/1/mod_jrun.so"
<IfModule mod_jrun.c>
  JRunConfig Verbose false
  JRunConfig Apialloc false
  JRunConfig Ssl false
  JRunConfig IgnoreSuffixmap false
  JRunConfig Serverstore "c:/CFusionMX7/runtime/lib/wsconfig/1/jrunserver.store"
  JRunConfig Bootstrap 127.0.0.1:51000
  #JRunConfig Errorurl <optionally redirect to this URL on errors>
  JRunConfig jrun-handler .jsp .jws .cfm .cfml .cfc .cfswf .cfr
</IfModule>


Configuring web servers on UNIX

This section explains how to configure the following web servers on UNIX:

  • Configuring Apache web server on UNIX
  • Configuring SunONE or iPlanet web server on UNIX

Configuring Apache web server on UNIX

This section describes how to configure the Apache web server for ColdFusion MX 7 on UNIX, and how to verify your configuration.

Note: When running the Web Server Configuration Tool on the multiserver configuration, wsconfig.jar is located in jrun_root/lib. On the server configuration only, you can also use the scripts in cf_root/bin/connectors, modifying them, as appropriate for your environment.

To configure the Apache web server for ColdFusion MX 7 on UNIX:

  1. Enter the following command on a single line:
    wsconfig -server servername -ws Apache -dir <apache config directory> -coldfusion -v

    Note: You must enter the previous command as a single (long) line.

    The wsconfig file is in cf_root/runtime/bin (server configuration) or jrun_root/bin (multiserver configuration)

    The following is a sample command:

    /opt/cfusionmx7/runtime/bin/wsconfig -server coldfusion -ws Apache -dir /etc/httpd/conf  -coldfusion -v

    Note: For unique configurations (such as the preconfigured Apache web servers from Redhat or Sun), add the -bin and -script parameters, as described in Configuring and Administering ColdFusion MX.

  2. Copy the CFIDE and cfdocs directories from cf_root/wwwroot to your web server root directory. In addition, copy your application’s pages from cf_root/wwwroot to your web server root directory. In the multiserver configuration, these files are under the jrun_root/servers/cfusion/cfusion-ear/cfusion-war directory.

To verify your Apache configuration:

  1. Verify that one of the following files was created:
    • cf_root/runtime/lib/wsconfig/number/mod_jrun.so (Apache 1.3.x)
    • cf_root/runtime/lib/wsconfig/number/mod_jrun20.so (Apache 2.x)

    In the multiserver configuration, this file is located under jrun_root/lib/wsconfig.

  2. Open the Apache configuration file, httpd.conf, in your Apache conf directory. By default it is /etc/httpd/conf/httpd.conf.

    Verify that the following code is added to this file:

    # JRun Settings
LoadModule jrun_module "/opt/CFusionMX7/runtime/lib/wsconfig/1/mod_jrun.so"
<IfModule mod_jrun.c>
  JRunConfig Verbose false
  JRunConfig Apialloc false
  JRunConfig Ssl false
  JRunConfig Serverstore "/opt/CFusionMX7/runtime/lib/wsconfig/1/
    jrunserver.store"
  JRunConfig Bootstrap 127.0.0.1:51000
  #JRunConfig Errorurl <URL for errors>
  JRunConfig jrun-handler .jsp .jws .cfm .cfml .cfc
</IfModule>

Configuring SunONE or iPlanet web server on UNIX

This section describes how to configure SunONE Web Server or iPlanet web server (4.x or 6.x) for ColdFusion MX 7 on UNIX, and how to verify your configuration.

Note: When running the Web Server Configuration Tool on the multiserver configuration, wsconfig.jar is located in jrun_root/lib. On the server configuration only, you can also use the scripts in cf_root/bin/connectors, modifying them, as appropriate for your environment.

To configure Netscape or iPlanet for ColdFusion MX 7 on UNIX:

  1. Enter the following command on a single line:
    wsconfig -server servername -ws sunone | iplanet | nes -dir path_to_config  -coldfusion -v

    Note: You must enter the previous command as a single (long) line. Specify sunone, iplanet or nes.

    The following is a sample command:

    /opt/cfusionmx7/runtime/bin/wsconfig -server coldfusion -ws sunone -dir path_to_config -coldfusion -v
  2. Copy the CFIDE and cfdocs directories from cf_root/wwwroot to your web server root directory. In addition, copy your application’s CFM pages from cf_root/wwwroot to your web server root directory. In the multiserver configuration, these files are under the jrun_root/servers/cfusion/cfusion-ear/cfusion-war directory.

To verify your Netscape or iPlanet configuration:

  1. Verify that the following file was created:
    cf_root/runtime/lib/wsconfig/1/jrun_nsapi35.dll

    In the multiserver configuration, this file is located under jrun_root/lib/wsconfig.

  2. Open the Netscape configuration file, obj.conf, in the web server directory (for example, in /usr/netscape/server4/https-surf/config/obj.conf).
  3. Verify that the following line is in the file:
    NameTrans fn="jrunfilter"
  4. Verify that #JRun prefixes the following NameTrans line in the file:
    #JRun NameTrans fn="pfx2dir" from="/servlet"
    dir="e:/netscape/servers/docs/servlet"
  5. Verify that the following object element is at the end of the file:
    <Object name="jrun">
PathCheck fn="jrunfilter"
Service fn="jrunservice"
</Object>


Installing Verity Locales

ColdFusion MX 7 lets you do Verity searches for languages other than English. For more information on Verity, see Configuring and Administering ColdFusion MX.

This section describes how to install a Verity Locales package from the Macromedia website, and how to switch to a different Verity Locales package.

To install Verity Locales:

  1. In your browser, go to the following location on the Macromedia website: www.macromedia.com/go/verity

    Enter your ColdFusion MX 7 license key.

  2. Download the appropriate Verity Locales package, and save it to your cf_root directory.
    • verity_asian_locales.zip - includes Japanese, Korean, Chinese (Simplified), and Chinese (Traditional)
    • verity_ee_me_locales.zip - includes Arabic, Bulgarian, Czech, Greek, Hebrew, Hungarian, Polish, Russian, and Turkish
    • verity_weuropean_locales.zip - includes Danish, Dutch, Finnish, French, German, Italian, Norwegian (Bokmal), Norwegian (Nynorsk), Portuguese, Spanish, and Swedish
    • verity_multilanguage_locale.zip
  3. Extract the ZIP file in your cf_root directory.

    During extraction, the search files are automatically placed in the appropriate directories.

  4. To use a different Verity Locales package (for example, English), repeat this procedure for the new Verity Locales package.


Enabling CORBA support

ColdFusion MX 7 supports third-party Object Request Brokers (ORBs) through its integration with Borland Visibroker. However, you must acquire the Common Object Request Broker Architecture (CORBA) software separately from Borland.

This section describes the following topics:

  • System requirements
  • Installing Visibroker for CORBA connections

System requirements

You must have all of the following components installed on your computer before you can make CORBA invocations from ColdFusion MX 7:

  • Borland Visibroker 4.5.1 for Java
  • Java Runtime Environment (JRE) 1.2 for the Visibroker Interface Repository
  • JRE 1.3 or later for ColdFusion MX 7

Installing Visibroker for CORBA connections

To install Visibroker for CORBA connections:

  1. Install Visibroker on the CORBA server side.

    For more information, see the Borland Visibroker documentation.

  2. Add the vbjorb.jar file to the ColdFusion MX 7 classpath, as follows:
    1. In the ColdFusion MX Administrator, select Server Settings > Java and JVM. When using the J2EE configuration, you add the vbjorb.jar file to the J2EE application server classpath, using the server-specific method.
    2. On the Java and JVM Settings page, in the Class Path text box, enter the path to your vbjorb.jar file (for example, C:\Inprise\vbroker\lib\vbjorb.jar). If you are using JVM version 1.4 or later, you must add -Xbootclasspath/a:"C:/Inprise/vbroker/lib/vbjorb.jar", to the JVM Args text box.

      You only need the JAR file on the computer that is running ColdFusion MX 7; you do not need the full Visibroker installation.

    3. Click Submit Changes.
  3. Configure a Visibroker connector in ColdFusion MX 7, as follows:
    1. In the ColdFusion MX Administrator, select Extensions > CORBA Connectors.
    2. In the CORBA Connectors page, click Register CORBA Connector.
    3. In the CORBA Connector page, enter information for the connector.

      The following is an example of a correctly configured connector:

    Field

    Value

    ORB Name

    visibroker

    ORB Class Name

    coldfusion.runtime.corba.VisibrokerConnector

    Classpath

    (none)

    ORB Property File

    C:\CFusionMX7\lib\vbjorb.properties

    The ORB Property File points to a Java properties file that contains the correct ORB settings for Visibroker.

    The contents of the vbjorb.properties file look like the following:

    org.omg.CORBA.ORBClass=com.inprise.vbroker.orb.ORB org.omg.CORBA.ORBSingletonClass=com.inprise.vbroker.orb.ORB SVCnameroot=namingroot
    1. When you finish editing the page, click Submit.

      The CORBA Connectors page appears.

    2. Select the radio button to the left of your new CORBA connector and click Select ORB Connector.

      This sets the new connector to be the default.

  4. Prepare your CORBA server side, as follows:
    1. Start your Visibroker osagent service or process, if it is not already running, by entering the following command:
          osagent

      Note: If you must connect to an osagent in another subnetwork, include the following lines in the vbjorb.properties file:

    vbroker.agent.addr=<IP address of machine running OSAGENT>
    vbroker.agent.port=<port>
    2. Start the Interface Repository and load it with the IDL file that you plan to use, by entering an irep command, as in the following example:
          irep myir MyIDLFile.idl
    3. (Optional) Start the Naming Service by entering a command like the following:
          nameserv namingroot

      Note: The name of the Naming Service (namingroot in the previous example) must match the value for SVCnameroot in the vbjorb.properties file.
    4. Start Visibroker on your CORBA server.

      For more information, see the Borland Visibroker documentation.

  5. Restart ColdFusion MX 7 for your changes to take effect.

    For more information, see Managing ColdFusion MX 7.

You can now make CORBA invocations from ColdFusion MX 7. For more information about integrating CORBA objects into ColdFusion MX 7, see ColdFusion MX Developer’s Guide.


Disabling Remote Development Services

If you use Macromedia Dreamweaver MX or Macromedia HomeSite+ to develop your applications, you can access a remote ColdFusion MX 7 server using HTTP. However, you must configure Remote Development Services (RDS) in your integrated development environment (IDE), and RDS must be enabled in ColdFusion MX 7. Using RDS, IDE users can securely access remote files and data sources, build SQL queries from these data sources, and debug CFML code.

Note: The ColdFusion Report Builder uses RDS for the Query Builder and for charting support.

However, for security reasons, Macromedia recommends that you disable RDS on a production server. To disable it, you must disable the RDSServlet mapping.

To disable the RDSServlet mapping:

  1. Back up the web.xml file.

    This file is in the cf_root\wwwroot\WEB-INF directory in Windows and in the cf_root/wwwroot/WEB-INF directory on UNIX. In the multiserver and J2EE configurations, this file is under cf_webapp_root/WEB-INF.

  2. Open the original web.xml file for editing.
  3. Comment out the RDSServlet mapping, as the following example shows:
    <!--
<servlet-mapping id="macromedia_mapping_9">
    <servlet-name>RDSServlet</servlet-name>
    <url-pattern>/CFIDE/main/ide.cfm</url-pattern>
</servlet-mapping>
-->
  4. Save the file.
  5. Restart ColdFusion MX 7.

    RDS is disabled on the ColdFusion MX 7 server.

For more information, see Starting and stopping services for Windows, or Managing the process for UNIX.


Disabling JSP functionality (server configuration only)

ColdFusion MX 7 Enterprise Edition provides support for JavaServer Pages (JSP) technology through the underlying J2EE application server on which it runs. Because JSP code runs outside of the realm of the ColdFusion MX 7 security framework and, therefore, is not subject to ColdFusion MX 7 sandbox security, you do not typically deploy JSPs in a shared, hosted environment where more than one customer shares a single server.

To disable JSP functionality:

  1. Open cf_root/runtime/servers/default/SERVER-INF/default-web.xml in a text editor.
  2. Find the servlet-mapping entry for JspLicenseServlet.
  3. Comment out this entry, as the following example shows:
    ...
<!--
    <servlet id="macromedia_servlet_8789">
        <servlet-name>RDSServlet</servlet-name>
        <display-name>RDS Servlet</display-name>
        <servlet-class>coldfusion.bootstrap.BootstrapServlet</servlet-class>
        <init-param id="InitParam_103401311065856789">
            <param-name>servlet.class</param-name>
            <param-value>coldfusion.rds.RdsFrontEndServlet</param-value>
        </init-param>
    </servlet>
-->
...
  4. Save and close the file.
  5. Restart ColdFusion MX 7.


Changing the ColdFusion MX 7 user account in Windows

The ColdFusion services, by default, run under the highly privileged system accounts. For an extra level of security, Macromedia recommends that you create a Windows user under which you run the services and only give privileges needed to run the web application (for example, folder permissions for the web root.)

To change the ColdFusion MX 7 user account:

  1. Open the Services Control Panel. (For example, select Start > Settings > Control Panel > Administrative Tools > Services.)
  2. Right-click ColdFusion MX 7 Application Server, and select Properties.

    The ColdFusion MX 7 Application Server Properties (Local Computer) dialog box appears.

  3. On the Log On tab, select This account, and enter the account information.
  4. Click OK.
  5. In the Services control panel, right-click ColdFusion MX 7 Application Server, and select Restart.

    Caution: Do not rename your Windows Administrator account. This causes problems with security policies and profiles.


Connecting to an external JDBC Type 4 data source

To use a JDBC driver that is not included with ColdFusion MX 7 (such as SQLAnywhere or PostgreSQL) you must configure it and add a data source for it.

To connect to an external JDBC data source:

  1. Copy the database driver .jar file to one of the following directories:
    • (server configuration only) cf_root/lib
    • (multiserver or J2EE configuration) cf_webapp_root/WEB-INF/cfusion/lib
  2. Restart ColdFusion MX 7.

    For more information, see Managing ColdFusion MX 7.

    Note: In Windows, ensure that you restart all of the ColdFusion MX 7 services; these are listed in Overview of services.

  3. In the ColdFusion MX Administrator, add the other JDBC Type 4 data source, selecting Other from the Driver drop-down list box.

    For more information, see the chapter on data source management in Configuring and Administering ColdFusion MX.

You can now connect to an external JDBC Type 4 data source.
Previous


Troubleshooting

This chapter contains solutions to common installation problems.

Contents

Common installation problems

Data source problems

Migration problems

J2EE configuration problems

Post-install problems

Uninstall problems
Next


Common installation problems

Spaces in the TEMP or TMP environment variables (Windows only)

Problem: A space in the path of the TMP or TEMP environment variables in Windows causes the installer to abort after extracting from the archive.

Solution: Change the TEMP or TMP environment variable so it does not include spaces.

Incomplete download

Problem: InstallAnywhere displays a message to choose another install location. No matter what location you choose, the install doesn’t succeed.

Solution: Make sure that you downloaded the complete installation file; if not, download the file again.

Problem: When you try to download the ColdFusion MX 7 installation file on an Apple Macintosh, the download stops before it is complete, but the browser indicates that the download is complete.

Solution: If you are using Safari:

  1. Start the download.
  2. Open the download window (Option-Command-L).
  3. When the download looks like it has stalled, click the Stop (X) button.
  4. Click the Resume button.

    Safari continues the download from where it stalled.

  5. Repeat Steps 3 and 4 as necessary

Web Server connectors not installed

Problem: If you install ColdFusion MX 7 on Apache 2.0.50, the configuration file is not updated automatically.

Solution: You must install the Web Server connectors manually, as described in Configuring web servers.

Server error

Problem: When trying to access any CFM page either from the server itself, or remotely, the following error appears:

Server Error
The server encountered an internal error and was unable to complete your request.
JRun Connector Protocol Error.

Solution: Run the Web Server Configuration Tool to unconfigure and reconfigure your web server connectors, as described in Configuring web servers.

Cannot start ColdFusion MX 7 Server

Problem: After installing Windows SP2 firewall, you cannot start ColdFusion services.

Solution: After installing Windows XP Service Pack 2, the Windows Firewall is enabled by default. This prevents ColdFusion MX 6.1 from functioning correctly. For more information see the Tech Note at www.macromedia.com/support/coldfusion/ts/documents/windowsspxp2.htm.

Cannot access Flash content locally

Problem: You cannot access any Flash content locally after installing ColdFusion MX 7 on IIS.

Solution: Look at the installation log to see if it contains the following error:

ANT Script Error:
Status: ERROR
Additional Notes: ERROR - Error adding connector to webserver: Internet Information Server (IIS)
CommandLine:
ErrorString: file:C:/Temp/0971.tmp/savedURL.1:31:
java.io.FileNotFoundException: C:\blackstone\ConnectorInstall0.txt.bat
(Access is denied)

If so, shut down IIS, and then run the Web Server Configuration Tool by selecting Start > Programs > Macromedia > Coldfusion MX 7 > Web Server Configuration Tool.

Errors displaying Flash forms

Problem: When you try to browse a ColdFusion page that contains a Flash form, the following errors appear:

2 Errors found.
Error /CFIDE/gettingstarted/community/webroot/index.cfm:-1
macromedia.css.LocatorParser
Error /CFIDE/gettingstarted/community/webroot/inde.mxml:381
The class 'mx.rpc.RemoteClassRelayResponder' could not be loaded.

Solution: If you are using an external web server, such as Apache or IIS, rerun the Web Server Configuration Tool; also, try using the built-in server, using port 8500. For more information, see Configuring web servers.

Cannot run Macromedia Flex

Problem: After installing ColdFusion MX 7, you cannot run Macromedia Flex on it.

Solution: You must install the J2EE configuration of ColdFusion MX 7 to run Macromedia Flex on ColdFusion MX 7.

Browsing a ColdFusion page displays a download window

Problem: In prior versions of ColdFusion, you used IIS to map the file extension .cfm to ICSF.dll. In ColdFusion MX 7, you have not mapped the .cfm file extension to any .dll file. As a result, ColdFusion pages do not execute running under Windows 2000 and IIS 5.0, but display a download window instead.

Solution: Run the Web Server Configuration Tool by selecting Start > Programs > Macromedia > Coldfusion MX 7 > Web Server Configuration Tool. For more information, see Configuring web servers.

ColdFusion MX Administrator displays as an encrypted page

Problem: After you install ColdFusion MX 7, you install Windows XP SP2. When you start ColdFusion MX Administrator, the Administrator displays as an encrypted page.

Solution: The Windows XP SP2 update may have undone the IIS mapping for ColdFusion MX 7. Run the batch scripts to uninstall, and then reinstall the IIS connectors. For more information, see Configuring web servers.

ColdFusion MX 7 doesn’t start

Problem: ColdFusion MX 7 doesn’t start when you have McAfee Privacy Service installed on system.

Solution: You must remove McAfee Privacy Service.


Data source problems

Unable to add a Microsoft Access data source

Problem: When you try to add a Microsoft Access data source, the following error appears:

Unable to update the ColdFusion MX 7 ODBC Server.
Timeout period expired without completion of C:\blackstone\db\slserver54\admin\swcla.exe

Solution: Install and start up the ODBC service, or use the Microsoft Access with Unicode driver.

Unable to use a data source created with UnixODBC

Problem: You cannot use a data source created with UnixODBC in ColdFusion MX 7.

Solution: You can use a driver such as the InterClient JDBC driver for InterBase available from Borland (www.borland.com/interbase/). Follow the documentation for setting up a data source using a third-party JDBC driver, Connecting to an external JDBC Type 4 data source, in conjunction with the InterClient documentation.


Migration problems

Data sources not recognized

Problem: When you migrate from a previous version of ColdFusion to ColdFusion MX 7, your application does not recognize data sources.

Solution: Redefine the data sources.

CFCs not recognized in Dreamweaver

Problem: When you migrate from a previous version of ColdFusion to ColdFusion MX 7, the CFCs do not appear in the Components panel of Dreamweaver.

Solution: Check the mappings and update them as necessary.

Installation fails

Problem: On UNIX and Linux systems, when you try to install ColdFusion MX 7 on systems where the /tmp partition is mounted noexec, the installation fails.

Solution: This is because the install attempts to use the /tmp directory for unpacking and running the installer runtime. To avoid this issue, set the IATEMPDIR environment variable to a directory on the system that has execute permissions before running the installer.

Installation fails

Problem: When you try to install ColdFusion MX 7, the installation fails and generate the error:

"java.lang.OutOfMemoryError Invocation of this Java Application has caused an InvocationTargetException. This application will now exit. (LAX)"

Solution: You must clean up the directory to which the installer is trying to extract the JRE, for example, /home/tmp.


J2EE configuration problems

Problem: When you install JRun 4, then install the ColdFusion MX 7 WAR, and attempt to open the ColdFusion MX Administrator, the following error appears:

500 The Security service is not available.
The security service is not available.

Solution: Look at the log files in cfusion/logs to see if a message indicates that you need the Java Crypto Extensions (JCE) on a 1.3 JVM. (The 1.4 JVM has this preconfigured.) Run JRun 4 Updater, making sure that you specify the correct directory.

Problem: There is inconsistent behavior when you try to launch JRun using /opt/jrun4/bin/jrun.

Solution: Launch JRun using the following:

/yourJAVA_HOME/bin/java -jar /opt/jrun4/lib/jrun.jar -start cfusion

ColdFusion MX Administrator fields not editable

Problem: When you run the pure Java installation kit (coldfusion-70-other.jar) on Mac OS X in GUI mode, the password and confirm password fields on the Administrator Password panel are not editable.

Solution: To be able to enter a password, click Next, and then click OK when the message that you cannot have a blank password appears. You can then enter a password.


Post-install problems

CLOB and data corruption

Problem: You are using the Japanese version of ColdFusion MX 7 and Oracle 8/9 with NLS_Characterset JA16SJJS, and encounter CLOB corruption and data corruption.

Solution: Set codepageoverride=MS932 in the JDBC URL.

Unsupported keysize or algorithm parameters

Problem: You are running ColdFusion MX 7 on WebSphere 5.1 on IBM JVM 1.4.1 and encounter an "Unsupported keysize or algorithm parameters" exception.

Solution: You must install unlimited jurisdiction policy files, as follows:

  1. Download and install Unrestricted JCE Policy files for IBM SDK 1.4 from https://www6.software.ibm.com/dl/jcesdk/jcesdk-p.
  2. Unzip the file.
  3. Copy files unzipped from this link to the jre/lib/security directory.
  4. Restart WebSphere.

Virtual mapping resource path of /* does not work

Problem: You add a virtual mapping resource path of /* which does not work.

Solution: Do not map any directories to wildcard resource paths that contain WEB-INF as a virtual mapping. In ColdFusion MX 6.1, the fact that this worked was a side-effect of the particular way the classloader was configured. For ColdFusion MX 7, the classloader is consistent across all editions; the ColdFusion classloader is no longer blended with the application server's classloader. This change was made to ensure that ColdFusion MX 7 works consistently in standalone server as well as deployed as an EAR/WAR to any certified J2EE application server.


Uninstall problems

COM disabled

Problem: You have a previous version of ColdFusion on the system. When you uninstall ColdFusion MX 7, COM is disabled.

Solution: You must re-register the typeviewer.dll file associated with the previous version of ColdFusion.
Previous


Getting Started Building ColdFusion MX Applications

Getting Started Building ColdFusion MX 7 Applications is intended for anyone who needs to begin programming in the ColdFusion MX 7 development environment. This book includes a tutorial, which uses supporting files that are installed if you chose to install example applications. If you did not install the ColdFusion MX 7 example applications, you can download the tutorial files from the ColdFusion Support center on the Macromedia website.

This book contains the following chapters:

  • Introduction
  • Introducing ColdFusion MX
  • CFML Basics
  • Database Fundamentals
  • Lesson 1: Preparing to Build the Sample Application
  • Lesson 2: Configuring Your Development Environment
  • Lesson 3: Retrieving Data
  • Lesson 4: Building Dynamic Queries
  • Lesson 5: Creating a Trip Detail Page
  • Lesson 6: Creating a Main Application Page
  • Lesson 7: Validating Data to Enforce Business Rules
  • Lesson 8: Implementing Browsing and Searching
  • Lesson 9: Enabling Database Maintenance
  • Lesson 10: Restricting Access to ColdFusion Applications


Introduction

Getting Started Building ColdFusion MX Applications is intended for anyone who needs to begin programming in the Macromedia ColdFusion MX 7 development environment. This manual includes a tutorial, which uses supporting files that are installed if you chose to install sample applications. If you did not install the ColdFusion MX sample applications, you can download the tutorial files from the ColdFusion Support center on the Macromedia website.

About Macromedia ColdFusion MX 7 documentation

The ColdFusion MX 7 documentation is designed to provide support for the complete spectrum of participants.

Documentation set

The ColdFusion MX 7 documentation set includes the following titles:

Book | Description
Installing and Using ColdFusion MX | Describes system installation and basic configuration for Microsoft Windows, Solaris, and Linux. To see this manual, go to http://www.macromedia.com/go/livedocs_cfmx7docs_installing.
Configuring and Administering ColdFusion MX | Part I describes how to manage the ColdFusion environment, including connecting to your data sources and configuring security for your applications. Part II describes Verity search tools and utilities that you can use for configuring the Verity K2 Server search engine, as well as creating, managing, and troubleshooting Verity collections. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_configadmin.
ColdFusion MX Developer’s Guide | Describes how to develop your dynamic web applications, including retrieving and updating your data, and using structures and forms. This manual includes two volumes. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_dev.
Getting Started Building ColdFusion MX Applications | Contains an overview of ColdFusion features and application development procedures. This manual includes a tutorial that guides you through the process of developing a sample ColdFusion application. To see this manual online, go to www.macromedia.com/go/livedocs_cfmx7docs_gs.
CFML Reference | Provides descriptions, syntax, usage, and code examples for all ColdFusion tags, functions, and variables. This manual includes two volumes. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs__cfml_reference.
CFML Quick Reference | Shows the syntax of ColdFusion tags, functions, and variables in a brief guide.

Viewing online documentation

All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com. In addition, you can view the documentation in LiveDocs, which lets you add comments to pages and view the latest comments added by Macromedia, by going to www.macromedia.com/go/livedocs_cfmx7docs.


Introducing ColdFusion MX

This chapter introduces the core technologies that are the foundation for Macromedia ColdFusion MX. In addition, it introduces the basic concepts about ColdFusion MX, how it works, and the various components that comprise it.

Contents

About ColdFusion MX

How ColdFusion processes pages

Building applications with CFML
Next


About ColdFusion MX

ColdFusion MX is a powerful web application server that lets you create robust sites and applications without a long learning curve. ColdFusion MX does not require coding in traditional programming languages (for example, C, C++, Java, XML), although it supports these traditional programming languages.

ColdFusion MX consists of the following core components:

  • ColdFusion application server
  • ColdFusion Markup Language (CFML)
  • ColdFusion MX Administrator

The following sections describe these core components in more detail. In addition, the Getting Started Experience, which you can view by opening the Macromedia ColdFusion MX Administrator and clicking Getting Started, provides introductory information about ColdFusion and code snippets that highlight the new features of ColdFusion MX 7.


The ColdFusion application server

The ColdFusion application server is itself a web application that typically resides on the same computer as your web server software. It is the program that parses (reads and interprets) and processes supplied instructions. These instructions are passed to ColdFusion through ColdFusion pages, which use a .cfm or .cfc filename extension. A ColdFusion page looks like an HTML page, but contains special tags that instruct the ColdFusion server to perform specific operations.


The ColdFusion Markup Language

ColdFusion Markup Language (CFML) is a tag-based language similar to HTML that uses special tags and functions. With CFML, you can enhance your standard HTML files with database commands, conditional operators, and high-level formatting functions, and rapidly produce easy-to-maintain web applications.

CFML looks similar to HTML: it includes start and end tags, and each tag is enclosed in angle brackets. All ending tags are preceded with a forward slash (/) and all tag names are preceded with cf.


The ColdFusion MX Administrator

You use the ColdFusion MX Administrator to configure and maintain the ColdFusion application server. It is a web-based application that you can access using any web browser, from any computer with an Internet connection.

You can manage the following configuration options with the ColdFusion MX Administrator:

  • ColdFusion data sources
  • Debugging output
  • Server settings
  • Application security

For further details about the ColdFusion MX Administrator, see Installing and Using ColdFusion MX or Configuring and Administering ColdFusion MX.


How ColdFusion processes pages

The following steps explain how the ColdFusion server processes a ColdFusion page:

  1. The ColdFusion server looks at the content of the page and searches for the following ColdFusion instructions:
    • Tag names that begin with cf.
    • Variables and functions that are always surrounded by number signs (#).
  2. If the ColdFusion server finds any HTML or plain text in the page, the ColdFusion server returns it to the web server unchanged.
  3. The ColdFusion server processes all the ColdFusion instructions found, and returns any remaining results to the web server. The web server then sends the entire output to the browser.


Building applications with CFML

You build ColdFusion applications as a series of pages that use CFML. Developers can extend this language by creating their own custom tags or user-defined functions (UDF), or by integrating COM, C++, and Java components, such as Java Server Page (JSP) tag libraries.

Interacting with data sources

ColdFusion applications can interact with any database that supports a JDBC technology-based driver. A JDBC technology-based driver uses an Application Programming Interface (API) to execute SQL statements to databases on most platforms. However, ColdFusion is not limited to JDBC data sources. You can also interact with existing Open Database Connectivity (ODBC) data sources by using ODBC Socket, a driver that interacts with an existing ODBC driver.

Interacting with mobile devices

ColdFusion MX 7 lets you create applications that can respond to events and messages from diverse sources, including instant messaging, mobile phone Short Message Service (SMS) text messages, Internet socket requests, and system events. For information, see Using Event Gateways in ColdFusion MX Developer’s Guide.

Development tools

You can code your ColdFusion application with NotePad or any HTML editor; however, Macromedia recommends that you build your applications using Macromedia Dreamweaver MX. Dreamweaver MX offers features and wizards that enhance ColdFusion development. For more information about Dreamweaver MX, see Lesson 2: Configuring Your Development Environment.
Previous


CFML Basics

This chapter introduces the basic elements of CFML, including how to create Macromedia ColdFusion pages, and use variables, functions, conditional processing, and form processing.

Contents

Working with ColdFusion pages

About CFML elements

Working with CFML expressions

About conditional processing

Processing form data

Commenting your code
Next


Working with ColdFusion pages

ColdFusion pages are plain text files that you use to create web applications. You can create your ColdFusion applications by writing all the code manually or by using wizards (provided with some editors) to generate the majority of the code for you.

You can use the following editors to create your ColdFusion pages:

  • Macromedia Dreamweaver MX
  • Macromedia HomeSite+
  • Macromedia ColdFusion Studio
  • Any HTML editor
  • Windows Notepad
  • Vi or Emacs (UNIX systems)

The best choice for creating ColdFusion pages is Macromedia Dreamweaver MX. Dreamweaver MX includes many CFML features for building applications, such as rapid visual development, robust CFML editing, and integrated debugging. Dreamweaver MX also includes a copy of HomeSite+ for users who are familiar with developing their application code using ColdFusion Studio or HomeSite 5. HomeSite+ combines all the features of ColdFusion Studio and HomeSite 5, along with support for the latest ColdFusion MX tags. For more information, see Lesson 2: Configuring Your Development Environment.

Note: This manual describes how to create ColdFusion applications by writing your code manually. It does not address how to create ColdFusion pages by generating code with wizards. For information about using wizards to generate CFML code, see the product documentation for Dreamweaver MX and HomeSite+.


Creating a ColdFusion page

Creating a ColdFusion page involves using tags and functions. The best way to understand this process is to create a ColdFusion page.

In the following procedure, you will create a simple ColdFusion page by using HTML tags, one ColdFusion tag, and two ColdFusion functions. The following table briefly explains the ColdFusion tags and functions:

Element

Description

Now()

A function supported in CFML that you can use to retrieve information from your system.

You will use the Now() function in the following procedure to return the current date that is retrieved from your system.

DateFormat()

A function that instructs ColdFusion to format the date returned by the Now() function.

cfoutput

A ColdFusion tag that you use to return dynamic data (data retrieved from a database) to a web page.

You will use the cfoutput tag in the following procedure to display the current date retrieved from your system.

Note: ColdFusion tags and functions are considered primary elements of CFML. You will learn more about these elements and others later in this manual.

To create a ColdFusion page:

  1. Open your editor and create a blank file.
  2. Enter the following code on the page:
    <html>
<head>
<title>A ColdFusion Page</title>
</head>
<body>
<strong>Hello world, this is a ColdFusion page.</strong>
<br>
<cfoutput> Today’s date is #DateFormat(Now())# </cfoutput>
</body>
</html>


Saving your ColdFusion page

In order for the ColdFusion server to process the page, you must save the ColdFusion page on a computer where the ColdFusion MX is installed. If you are creating your pages on a local server (on which ColdFusion is running), you can save the pages locally; if you are using a remote server, you must save your pages on that server.

If you are using the ColdFusion MX J2EE configuration, you typically save ColdFusion pages under the ColdFusion web application root. For example, in the default directory structure when you use the J2EE configuration with JRun, you save pages under jrun_root/servers/cfusion/cfusion-ear/cfusion-war. When you use JRun, you can also run the Web Server Configuration Tool and save pages under your web root directory.

Tip: ColdFusion MX on Macintosh OS X uses the J2EE configuration.

To save the code that you typed to create a ColdFusion page:

  1. Create a directory called test under the web_root or web_application_root directory.
  2. In the test directory, save the file as cfpage.cfm.


Browsing your code

To ensure that the code you wrote is working as expected, you must view the ColdFusion page in a browser. The following procedure describes how to view the ColdFusion page that you created earlier.

To view the ColdFusion page:

  1. Open a web browser and go to the following URL:

    http://localhost/test/cfpage.cfm

    Note: If you are using the built-in web server, specify the port to use in the URL as follows:
    http://localhost:8500/test/cfpage.cfm.

    The address localhost is only valid when you view pages locally. The URL for a remote site would include the server name or IP address of the server where ColdFusion is installed; for example, http://<serveripaddress>/test/cfpage.cfm.

    If you are using the ColdFusion MX J2EE configuration, you may also need to include a context root in the URL; for example, http://<server>/<context-root>/<page>.cfm. For example, if you deploy an EAR file and use the default context root of cfmx, you specify http://localhost/cfmx/test/cfpage.cfm.

    The following figure shows the cfpage.cfm page in the browser:

    This image shows the results of step one in a browser window:Hello world, this is a ColdFusion page.Today’s date is 17-Feb-02

  2. Do the following tasks:
    1. View the source code that was returned to the browser. In most browsers, you can view the source by right-clicking on the page, and then selecting View Source.
    2. Compare the browser source code with the source code that appears in your editor. Notice that the CFML tags were processed on the page but did not appear in the source that was returned to your browser.

      As described in Introducing ColdFusion MX, ColdFusion processes all the instructions (CFML tags and functions) it receives on a page, and then returns the results of the instructions that your browser can interpret and display.


About CFML elements

CFML consists of two primary language elements: tags and functions. Tags let you perform operations such as accessing a database. Functions can return data and do other operations like retrieving the system date. Almost everything that you want to accomplish with ColdFusion involves using tags and functions.

You use another important element known as a variable. Variables are an important part of most programming languages and are equally important with CFML. Variables let you store information in memory and enable you to pass data.

The following sections describe how to use these three elements.


Tags

You can think of tags as commands that you use to instruct the ColdFusion server to perform operations. These operations might include selecting data from a database, reading a file that resides on the server, or showing the results of processing.

Tag syntax

As discussed in Introducing ColdFusion MX, ColdFusion tags are similar to HTML tags. ColdFusion tags are enclosed in angle brackets and often have a start and end tag. The start tag encloses the tag name in brackets, like this:

<tagname>

Most often the end tag encloses the tag name in brackets and includes a forward slash (/), like this:

</tagname>

The information processed by ColdFusion is placed between the start and end tag, like this:

<tagname>
    info to be processed ...
</tagname>

ColdFusion tags, for the most part, share these common characteristics:

  • All start with cf.
  • Include a start and end tag.
  • Use attributes (like HTML tags), and most attributes have values.

Some ColdFusion tags, such as cfset, omit the ending tag. This type of tag uses one set of angle brackets and places all the required information between the left (<) and right (>) angle brackets, like this:

<cfset name="bob">

For a complete list of tags and their syntax, see CFML Reference.

Tag attributes

Tag attributes instruct ColdFusion about the details of an operation. For example, to update a database table, ColdFusion requires specific information about the database, such as the database name and the table name. The code required to write this type of statement might look like this:

<cfupdate datasource="mydb" tablename="mytable">

where datasource and tablename are attributes of the cfupdate tag and "mydb" and "mytable" are attribute values.

For a complete list of tags and their attributes, see CFML Reference.


Functions

Typically, a function acts on data. It can generate a value or a set of values, usually from some input. You can perform the following operations (actions) with functions:

  • Manipulate data and time values
  • Examine a value or variable
  • Display and format information
  • Manipulate string data
  • Retrieve system information and resources
  • Perform mathematical operations

Functions and number signs

You use number signs (#) with functions to display the results of a function on the page. Number signs tell the ColdFusion server to evaluate the content between the number signs and display the value, for example:

<cfoutput>
    Hello world, <br>
    Today’s date is #DateFormat(Now(), "mm/dd/yyyy")#
</cfoutput>

The following figure shows the output of this example:

This image shows that the results of the output are:Hello world,Today’s date is 02/27/2002

If you did not include the number signs around the DateFormat(Now(), "mm/dd/yyyy") function, ColdFusion would not evaluate the function and the previous example would display your source code, as follows:

This image shows the results if pound signs were not included around function:Hello world,Today’s date is DateFormate(Now), "mm/dd/yy")

For more information about how to use number signs with functions, see ColdFusion MX Developer’s Guide.

Functions and parentheses

All functions have parentheses, regardless of whether the function acts on data. Consider the following function:

#Now()#

If you put anything inside the parentheses of the Now() function, an error would occur. The Now() function returns an unformatted date and time. However, you can format the results of this function with other functions, such as the DateFormat() or TimeFormat() functions.

Using functions on values

Usually, a function performs an operation on a value, and the value can include the value of a variable. For example, to format the value of a variable that contains a value in dollars, the code to write this statement might look like this:

#DollarFormat(price)#

The DollarFormat function returns a value as a string and formats that value with two decimal places, a thousands separator, and a dollar sign. The number signs (#) around the function instruct ColdFusion to evaluate the content between the number signs and display the value.

Nesting functions

Functions can generate data, as well as act on data. Consider the following example:

#DateFormat(Now(), "mm/dd/yyyy")#

In this example, the Now() function generates the date, and then the DateFormat function formats the date.


Variables

Variables let you store data in memory on the server. Variables always have a name and a value. You can assign a value to a variable, or you can instruct ColdFusion to assign variable values based on data that it retrieves from a data source, such as a database table.


Naming variables

You must use the following rules for naming ColdFusion variables:

  • Names are case-insensitive (uppercase, lowercase, or mixed case).
  • Names can contain only letters, numbers, and underscore characters.
  • Each name must begin with a letter.
  • Special characters (such as double-quotation marks ("), reserved names (such as functions and tags), and spaces are not allowed.


Ways to use variables

You can use variables for the following purposes:

  • Store data collected from a form.
  • Store results of a calculation (such as the number of database records returned).
  • Use as input to a function.


Creating variables with the cfset tag

ColdFusion lets you create variables as you need them. You create the variable (name and value) using the cfset tag. This tag has the following syntax:

<cfset variable_name = value>

In the following examples, the variables are assigned a string literal value. All string literal values are surrounded by double-quotation marks.

<cfset my_first_name = "Kaleigh">
<cfset my_last_name = "Smith">

In the next example, ColdFusion uses the values of the my_first_name and my_last_name variables to set the value for the my_full_name variable in the last line of code. The ampersand (&) string operator joins the variables, and the space surrounded by double-quotation marks (" ") adds a space between the variables.

<cfset my_first_name = "Kaleigh">
<cfset my_last_name = "Smith">
<cfset my_full_name = variables.my_first_name & " " & variables.my_last_name>

Tip: String values assigned to a variable must be enclosed in single-quotation marks (') or double-quotation marks ("). Numeric or Boolean values assigned to a variable do not require single- or double-quotation marks.

So far, all the variable examples have shown local variables. Local variables are variables that you can use only on the current ColdFusion page. The previous example used a variables prefix to reference an existing variable on the page. Using a prefix when referencing a variable is important because ColdFusion supports many types of variables. Use the following syntax to reference a local variable:

variables.variablename

Because ColdFusion lets you use the same name with variables of more than one type, ColdFusion relies on scope referencing. In scope referencing, you preface the variable’s name with the scope when you refer to that variable.

Other variables and their scope

Each type of variable that ColdFusion supports has it own scope, or where it can be referenced, and its own way of referencing that variable type. The following table identifies some of the more common types of variables and their prefixes:

Scope | Prefix | Description
Variables (local variable) | Variables | Variables created using a cfset or cfparam tag. Most often you define the variable on the current page or on a page that you include using the cfinclude tag.
Form | Form | Data entered in tags in an HTML form or ColdFusion form and processed on the action page.
URL | URL | Variables passed to a page as URL string parameters.
Query | QueryName | Variables that have names based on the column names that you select in the database table. The values are created when you execute the query that selects data from the database.

You will use these other types of variables in Part II of this manual. For additional information about variables, see CFML Reference.


Displaying variable output

Output is what remains after the ColdFusion server processes the CFML tags on a page. Usually the output has two parts:

  • Information that the user sees (for example, a confirmation message)
  • Information that is stored by the server as a result of processing (for example, user input collected from a form)

One of the tags that ColdFusion provides to display output is the cfoutput tag. The cfoutput tag instructs ColdFusion to process all the code between the cfoutput start and end tags. The syntax for the cfoutput tag looks like this:

<cfoutput>
    {normal html, text, and ColdFusion processing instructions}
</cfoutput>

To return the value of a variable, you must always surround the variable name with number signs (#) and place the variable name between the cfoutput start and end tags. For example, the following code creates a variable and instructs the ColdFusion server to return the value of the variable:

<cfset my_first_name = "Kaleigh">
<cfset my_last_name = "Smith">
<cfset my_full_name = variables.my_first_name & " " & variables.my_last_name>
<cfoutput>
    #variables.my_full_name#
</cfoutput>

The following text is the output:

Kaleigh Smith


Working with CFML expressions

Expressions are an important part of the ColdFusion language. Expressions are a collection of different elements, ColdFusion variables, functions, and operators. You can think of them as strings of text that consist of one or more of the following elements:

  • Literal text (string), numbers, dates, and other values
  • Variables
  • Functions
  • Operators (& for joining statements, + for addition, and so on)

This chapter includes many examples of expressions; for example:

  • #variables.my_full_name#
  • DateFormat(Now())
  • my_first_name= "Kaleigh"

When you build expressions in ColdFusion, you can include simple and complex elements; how you represent these elements determines how ColdFusion processes your application.


Building expressions

In ColdFusion, you build expressions as you need them. The expressions can include simple elements, such as the expressions shown previously, or they can include complex elements, such as arithmetic functions, strings, and decision operators. (You build some complex expressions in Part II of this manual.)

As mentioned, it is important that elements are identified properly in your expression so that ColdFusion processes them as expected, and you avoid unnecessary errors. When you write expressions, consider the following coding practices:

  • Use of consistent character case
  • When to use number signs (#)
  • When quotation marks are needed


Specifying a consistent character case

Because the ColdFusion server is case-insensitive, you can write expressions using all uppercase, all lowercase, or mixed case. However, for code readability and consistency, you should use the same character case in all your programs. If you write your programs using the same case rules, you might prevent errors from occurring when you combine CFML on a page with case-sensitive languages, such as JavaScript.


Specifying number signs to denote functions or variables

In ColdFusion, you specify number signs (#) to denote functions and variables within a string of text. You use number signs to show the results of the function or variable on the page. Number signs instruct the ColdFusion server to evaluate the function (or variable) between the number signs and display the value. The value of the function (or variable) appears in the browser as a result.

The following are some common ways to use number signs:

  • In the following example, you include the number signs to return the value to a page:
    <cfoutput> Hello #variables.my_first_name# </cfoutput>

    If you omit the number signs, the text, not the value, appears on the page.

  • In the following example, you do not include the number signs because you are using the cfset tag to assign one variable’s value to another value:
    <cfset my_full_name = variables.my_first_name & " " & variables.my_last_name>
  • To display a number sign on a page, you must designate the number sign as a literal character. You do this by using two number signs (##); for example:
    <cfoutput>
    ##1: Your name.
</cfoutput>

    The result is the following output:

    #1. Your name.

For more information and examples on using number signs in expressions, see ColdFusion MX Developer’s Guide.


Specifying quotation marks around values

When you assign literal values to variables, you must surround the literal value with single- or double-quotation marks. ColdFusion interprets the content between the quotation marks as a literal value and assigns that value to the variable; for example:

<cfset my_first_name = "Kaleigh">
<cfset my_last_name = "Smith">
<cfset my_age = 5>

ColdFusion instantiates the variable my_first_name to the string literal Kaleigh. Further, Smith is assigned to the variable my_last_name and 5 is assigned to age.

When referencing a variable by its name, you do not surround the name with quotation marks. In the following example, when you concatenate literal text and variables using the & operator, you don’t surround the variable references with quotation marks:

<cfset the_string = "My name is " & variables.my_first_name &
" and my age is " & variables.my_age>

My name is is literal text, and you, therefore, surround it with quotation marks. The variable references variables.my_first_name and variables.my_age are not surrounded by quotation marks. ColdFusion uses the values of the referenced variables (Kaleigh and 5, respectively) when assigning the value to the variable the_string.

To display quotation marks on a page as literal characters, you must use two consecutive quotation marks; for example:

<cfset mystring = "We all shouted ""Happy Birthday"" when he entered the room.">
<cfoutput>
    #mystring#
</cfoutput>

The result is the following output:

We all shouted "Happy Birthday" when he entered the room.


Specifying operators in expressions

In ColdFusion, you use operators to test conditions; for example, you use the IS operator to test for equality. When you use operators in expressions, you must only use supported logical operators that ColdFusion can interpret properly. For example, if you use the greater than operator (>) or the less than operator (<), ColdFusion interprets them as the start or end of a tag rather than as an operator.

The following table lists the unsupported logical operators and their equivalent ColdFusion operators:

Unsupported logical operator | Equivalent ColdFusion decision operator | Description
= | IS, EQUAL, EQ | Tests for equality.
< | LT, LESS THAN | Tests for less than.
<= | LTE, LE, LESS THAN OR EQUAL TO | Tests for less than or equal to.
> | GT GREATER THAN | Tests for greater than.
>= | GTE, GREATER THAN OR EQUAL TO | Tests for greater than or equal to.
< > | IS NOT, NEQ, NOT EQUAL | Tests for nonequality.
 | CONTAINS | Tests whether a value is contained within a second value.
 | DOES NOT CONTAIN | Tests whether a value is not contained within a second value.

Arithmetic operators

The following table lists the arithmetic operators that ColdFusion supports:

Operators | Description
+, -, *, / | The basic arithmetic operators: addition, subtraction, multiplication, and division. In the case of division, the right operand cannot be zero.
+, - | Unary arithmetic operators for setting the sign of a number as either positive or negative (+ or -).
Mod | Returns the remainder (modulus) after a number is divided by a divisor. The result has the same sign as the divisor. The right operand cannot be zero. For example, 11 MOD 4 is 3.
\ | Divides two integer values. Use the \ (backslash character) to separate the integers. The right operand cannot be zero. For example, 9 \ 4 is 2.
^ | Returns the result of a number raised to a power (exponent). Use the ^ (caret) to separate the number from the power. The left operand cannot be zero. For example, 2 ^ 3 is 8.

String operator

The following table describes the one ColdFusion string operator that is a concatenation operator:

Operator | Description
& | Concatenates strings.


About conditional processing

So far, all the coding examples shown in this chapter are considered linear coding examples. Linear code is when ColdFusion executes code starting with the first line on the page, and processes every line in order. Although you will use linear code in your applications, you will often write code that performs various actions based on conditions, such as the following:

  • Determine whether a user entered a value in a form field.
  • Display results based on user input.
  • Display messages based on the time of day.

You use conditional processing to customize the behavior of your application. Conditional processing facilitates decision making and lets you control how the code on a page is processed.

In ColdFusion, you implement conditional processing with flow control tags. These tags are similar to other programming language control elements, such as if, then, and else. When using these tags, you can facilitate decision making in your code. The most fundamental tags used to control code execution are the cfif, cfelse, and cfelseif tags. Because you will see and use these tags in Part II of this manual, the following sections provide a basic introduction on how to use these tags. For more information about other conditional processing tags, including tags for looping, see ColdFusion MX Developer’s Guide.

Using the cfif tag to evaluate True or False conditions

To create statements that let you evaluate conditions and perform an action based on the result, you use the cfif tag to create a cfif statement. The basic syntax is as follows:

<cfif expression>
    HTML and CFML tags executed if expression is True.
</cfif>

In this example, ColdFusion only executes the code inside the cfif statement if the expression evaluates to True. To perform actions if the expression is False, you can use the cfelse tag. For example, if the following cfif expression evaluates to False, the code between the cfelse tag and the ending cfif tag is processed:

<cfif expression>
    HTML and CFML tags executed if expression is True.
<cfelse>
    HTML and CFML tags executed if expression is False.
</cfif>

Using the cfelseif tag to evaluate multiple expressions

To evaluate multiple expressions in a cfif statement, you can use cfelseif and cfelse tags in your statement; for example:

<cfif expression 1>
    HTML and CFML tags executed if expression 1 is True.
<cfelseif expression 2>
    HTML and CFML tags executed if expression 2 is True.
<cfelse>
    HTML and CFML tags executed for expression(s) that is False.
</cfif>

The following example shows you how you can evaluate multiple expressions using these tags. This example uses a form in which users can enter their state to determine their state tax:

<cfoutput>
<cfif form.state IS "MA">
    #form.state# State Tax: 8.5%
<cfelseif form.state IS "VA">
    #form.state# State Tax: 8.2%
<cfelse>
    #form.state# State Tax Unknown
</cfif>
</cfoutput>

The output of this cfif statement is based on the value entered by the user. If the user enters MA in the state form field, the state tax results returned is 8.5%. If the user enters VA in the state form field, the state tax results returned is 8.2%. If the user enters any other state in the state form field, State Tax Unknown is returned.


Processing form data

Virtually all web applications that gather and write information to a database use a form to accomplish that task. Forms let you collect information from a user (using an order form, registration form, and so on) and write that information to a database. Like HTML, there are two independent steps for creating a form in ColdFusion:

  1. Creating the layout for the form itself.
  2. Writing the code to process the submitted information.

Every form that you create in ColdFusion consist of two parts: the form page and the action page. These two pages work together to process user input. The form page contains the user interface elements, such as input fields and radio buttons. The action page handles the processing of the form page data.

When a user submits a form, the form values are stored in form variables and sent to the action page for processing. The following figure shows the relationship between the form page and action page:

This image shows the relationship between the form page and action page.

In order for the form page to find its corresponding action page, the action statement in the form tag must be correct. The form tag includes the information that tells the server where to send the data that it collects. It also tells the server how to send it. To process these instructions to the server, the form tag uses the following syntax:

<form action="actionpagename.cfm" method="Post">
    HTML and CFML form tags
</form>

The first attribute (action) in the form tag lets you specify where to send the data. The page that you specify where to send the data is the name of the action page. The second attribute in the form tag is method. The only method that ColdFusion supports is post. All ColdFusion forms must set the method attribute to post.

In Part II of this manual, you use ColdFusion form tags to create forms and write collected values to a database.


Commenting your code

As in other programming languages, it is important to include comments in your code. You should comment your code for the following reasons:

  • Commented code is easier to debug than code that is not commented.
  • If you describe the code on the page, it is easier to make modifications.
  • Commented code tends to be better organized.

Comment tag

The ColdFusion comment tag is similar to the HTML comment tag, except that it has three dashes instead of two:

<!--- This is a CFML comment --->

ColdFuions comments can wrap to more than one line. ColdFusion comments are not returned to the browser because the ColdFusion server processes and omits the comments from the page. The user will never be able to read your comments.
Previous


Database Fundamentals

This chapter provides a quick overview of relational database concepts and terms. It describes what a database is and how it is organized. It also discusses the Structured Query Language (SQL) that you use to interact with databases.

Contents

About database basics

About SQL

Using SQL with ColdFusion
Next


About database basics

Even though you do not need a thorough understanding of database management systems to create ColdFusion applications, you must understand some basic concepts and techniques about databases. The information in this chapter will help you get started using ColdFusion.


What is a relational database?

A relational database is a structured collection of information that is related to a particular subject or purpose, such as an inventory database or a human resources database. You use databases to manage information. Information, such as product name, cost, and on-hand inventory, is stored in a database. Within the database, you organize the data into storage containers called tables. Tables are made up of columns and rows. Columns represent individual fields in a table. Rows represent records of data in a table. You can think of database tables as grids, as in the following example:

This image defines the structure of a database table, and shows the location of fields and records.

Each field in the table contains one piece of information. In an employee table, for example, one column contains the employee name, another contains the employee phone number, and the other columns each store one piece of information, such as the address, city, state, zip, and salary information. Each record represents one set of related information. For example, an employee table might store information about one employee per row. The number of rows in a table represents the total number of table records.


About relational tables

In a database, you can organize data in multiple tables. For example, if you manage a database for the Human Resources department, you might have one table that lists all the information about employees and another table that lists all the departments:

This image shows the relationship between department and employee tables.

You have multiple departments for employees, but you would not store the information about the departments in every employee row for the following reasons:

  • The department information is the same for each employee in a given department; however, repeating the department information for each employee is redundant. Storing redundant data takes up more disk space.
  • If the department information changes, you can update one occurrence. All references to that department are updated automatically.

Storing multiple occurrences of the same data is rarely a good thing. Good relational database design separates application entities into their own tables. Key values from one table are often stored in a related table rather than repeating the information. The key value is used to join the data between the tables to return the complete set of data required.


About SQL

SQL (Structured Query Language) is a language that lets you communicate with databases. For example, you can use SQL to retrieve data from a database, add data to a database, delete or update records in a database, change columns in multiple rows, add columns to tables, and add and delete tables.

Unlike other computer languages, SQL is made up of a small number of language elements that let you interact efficiently with a database. Some of the more frequently used elements include the following SQL commands:

Command | Use
SELECT | Retrieve (query) information in a database.
INSERT | Add records to a database.
UPDATE | Update information in a database.
DELETE | Delete information in a database.

Understanding basic SQL SELECT statements

One of the most widely used SQL statements is the SELECT statement. The SQL SELECT statement retrieves columns of data from a database. The tabular result is stored in a result table (called the record set).

You use the following SELECT statement to retrieve information from a table:

SELECT column_name(s) FROM table_name

Consider a table named Clients that contains the following rows:

LastName | FirstName | Address | City
Brown | Marie | 12 State St | Boston
Adams | Russell | 521 Beacon St | Boston
Carter | Joan | 1 Broadway | New York

To select the columns named LastName and FirstName, use the following SELECT statement:

SELECT LastName, FirstName FROM Clients

The result of this SQL statement contains the following data:

LastName | FirstName
Brown | Marie
Adams | Russell
Carter | Joan

Using the SQL WHERE clause to limit the rows returned

To conditionally select data from a table, you can add a WHERE clause to the SELECT statement, which results in the following syntax:

SELECT column_name FROM table_name WHERE column condition value

With the WHERE clause, you can use any of the following operators:

Operator | Description
= | Equal
<> | Not equal
> | Greater than
< | Less than
>= | Greater than or equal
<= | Less than or equal
BETWEEN | Between an inclusive range
AND | Joins one or more conditions
OR | Joins one or more conditions
LIKE | Specifies a search for a pattern in a column. You can use a percent sign (%) to define wildcards (missing letters in the pattern) before and after the pattern.

For example, to select the columns named LastName and FirstName for Clients whose City is Boston, use the following SELECT statement:

SELECT LastName, FirstName FROM Clients Where City = 'Boston'

The result of the preceding SQL statement contains the following data:

LastName | FirstName
Brown | Marie
Adams | Russell

You can compose a WHERE clause with one or more conditions; these are called subclauses. You join subclauses using the operators AND and OR. The AND operator displays a row if all conditions that are listed are True. The OR operator displays a row if any of the conditions listed are True. The following statement shows an example of a WHERE clause with multiple subclauses:

SELECT LastName, FirstName FROM Clients Where City = 'Boston' AND FirstName = 'Marie'

The result of the preceding SQL statement contains the following data:

LastName | FirstName
Brown | Marie

Note: The preceding SQL SELECT examples use single-quotation marks around the value. SQL uses single-quotation marks around text values. Most database systems also accept double-quotation marks. Do not enclose numeric values in quotation marks.

Sorting the results

You use the ORDER BY clause to sort the result rows. The following SQL statement returns an alphabetic list of people sorted by last name, and then first name, from the Clients table:

SELECT * FROM Clients Order By LastName, FirstName

The default is to return the results in ascending order (top to bottom). If you include the DESC keyword in the ORDER BY clause, the rows are returned in descending order (bottom to top).

The following statement returns a reverse alphabetic list of the Clients table:

SELECT * FROM Clients Order By LastName, FirstName DESC

Note: The SQL SELECT statement is quite powerful. There are several other options for retrieving data from a SQL database using the SELECT statement, which are not described in this manual. For more information, consult a SQL reference.


Using SQL with ColdFusion

ColdFusion communicates with your data source through a database interface called Java Database Connectivity (JDBC). JDBC is a standard application programming interface (API) for accessing information from different database systems and different storage formats.


About data sources

A data source is a complete database configuration that uses a JDBC driver to communicate with a specific database. In ColdFusion, you must configure a data source for each database file that you want to use. After you configure a data source, the ColdFusion server is then capable of communicating with that data source through the JDBC driver.

You configure data sources in ColdFusion by using the ColdFusion MX Administrator. For information about how to configure the sample data source file that is supplied for use with Part II of this manual, see Lesson 2: Configuring Your Development Environment. For more information about configuring a data source in ColdFusion, see Installing and Using ColdFusion MX or ColdFusion MX Developer’s Guide.


Writing SQL and CFML statements to interact with a data source

After ColdFusion makes a connection to the data source, you can interact with that database by using SQL and ColdFusion.

To interact with an established data source, you must include SQL statements in your CFML statements; for example:

<cfquery name="queryname" datasource="namedbfile">
    SELECT FirstName, LastName, DepartmentID
    From Employee
</cfquery>

In this example, the first attribute of the cfquery tag is the name of the query. The second attribute of the cfquery tag defines the name of the data source. The SELECT statement defines the fields (columns) to be retrieved from a table named Employee.


CFML tags that interact with a database

The following table lists the CFML tags that you can use to interact with a database:

Tag | Description
cfquery | To retrieve (query) information in a database.
cfinsert | To add records to a database.
cfupdate | To update information in a database.

Part II of this manual introduces these tags when you use them to interact with the sample database. For more information about interacting with a database, see ColdFusion MX Developer’s Guide or CFML Reference.
Previous


Lesson 1: Preparing to Build the Sample Application

This tutorial guides you through the process of building a simple Macromedia ColdFusion web application. By the end of the tutorial, you will be familiar with how to use Macromedia ColdFusion MX 7 to query and update a database, validate data, generate a report, and require user authentication.

The application that you will build in this tutorial is for a fictitious travel company called Compass Travel. Compass Travel markets a wide range of adventure trips to the public through its website. Trip coordinators at Compass Travel are responsible for maintaining the trip information. The sample tutorial application assists the trip coordinators in maintaining trip information in the Compass Travel database.

ColdFusion development is the emphasis of the tutorial; therefore, you will not need to design or build the Compass Travel database. It is important, however, for you to be familiar with the layout of the database. Additionally, you must understand the functional requirements that will help determine the application design. This lesson provides an overview of these application design steps, while the remainder of this manual guides you through the lessons on constructing the sample application.
Next


Application development steps

Most software applications contain three major functions:

  • A user interface to capture data
  • Logic to validate the captured data
  • A database to store the validated data

The steps to develop these major functions vary from project to project. In this tutorial, you will review or participate in the following application development steps to build the Compass Travel Trip Maintenance application:

Step | Description
1 | Determine the application functional requirements.
2 | Determine the data requirements by identifying the information required for the Trip Maintenance application.
3 | Design the database for your application by exploring the database tables that will store the trip information.
4 | Develop the ColdFusion application pages.

The following sections explore an overview of each of these application development steps.


Exercise 1: Determining the application functional requirements

Before you can build the sample application, you must understand the functional requirements that influence its design. The design of the sample application centers around the daily tasks performed by Compass Travel’s trip coordinators. The following table describes these tasks:

Trip coordinator task | Description
Produce current trip listing | To help Compass Travel agents take trip reservations on the telephone and in person, the trip coordinator maintains a list of current trip offerings.
Provide trip information | On an ad hoc basis, Compass Travel management asks the trip coordinator to develop lists of trips that meet specific criteria.
Maintain trip information | The trip coordinator is responsible for keeping all trip information up to date. To do this, the coordinator needs to locate a trip to edit it or delete it. Additionally, the coordinator must be able to add a new trip.
Ensure the quality of trip information | The trip coordinator is responsible for periodically browsing the current trip offerings to ensure that all the information is accurate. Additionally, when adding a new trip or editing an existing one, the trip coordinator must ensure that the data adheres to the Compass Travel business rules.

You can derive several functional requirements for the new application from the preceding table. For example, the sample application must provide the ability to do the following:

  • Generate trip listings.
  • Find trips based on user-supplied criteria.
  • Browse trips.
  • Add a new trip.
  • Delete an existing trip.
  • Edit an existing trip.
  • Validate new or updated trips against Compass business rules.

In the lessons that follow, you will build ColdFusion pages to address each of these functional requirements. The basis for every requirement is the idea of a trip. Before you can build code to address any of these requirements, you must understand which attributes of a trip are important to Compass Travel. For this you must determine the data requirements for the application. Understanding the data requirements is essential to building the proper database to hold the application data.


Exercise 2: Determining the data requirements

Prior to creating the application pages to capture trip information, you must determine what type of data is required about each trip. For the example in this tutorial, the Compass Travel trip coordinator must maintain the following information about each trip:

  • Trip name
  • Type of event (surfing, mountain climbing, kayaking, and so on)
  • Trip description
  • Trip location
  • Departure date
  • Return date
  • Price
  • Base cost
  • Assigned trip leader
  • Total number of people who can attend the trip
  • An indicator of whether a deposit is required
  • Trip photograph

By collecting the preceding information about each trip, the Compass Travel website can market its trips online to the general public. Customers who are booking a trip need to know the trip name, when the trip begins and ends, the price, and a description. Additionally, the trip coordinator must identify the filename for a photograph of each trip. The Compass Travel website displays the photograph to further entice prospective customers into booking the trip. Finally, Compass Travel considers it important to store the base cost for each trip to help determine trip profitability. The cost must be captured, but it is for Compass Travel internal use only and is not shown on the public website.


Exercise 3: Designing the database for your application

After you identify the information to collect, you must consider where to store the data. Prior to creating the data collection form and instructing ColdFusion where to store the form data, you must have a database ready to accept the data.

If you had to create the Compass Travel database, you would create a table named trips to store the information that you plan to collect about each trip. The table would look something like the following table:

This image shows the trips database table.

Recognizing the data types

Each field in the Trips table has a data type attribute that describes the type of data that can be stored in the column. For instance, the tripName column can contain text data, while the price column can only contain numeric data. It is important to know what type of data is valid for each column so that your data collection forms can validate against incorrect values entered by the user.

Looking closer, you might wonder why the eventType column is a number and not a text data type column. Recall that data requirements analysis identified the need for a type of event (surfing, mountain climbing, kayaking, and so on). The purpose of this column is to classify trips into various categories based on the trip activity. It is essential that the application classify the trips consistently. Therefore, it is important to offer a list of event types for the user to select, rather than to accept free text input.

To present a list of event types for user selection, the event types are stored in a separate table, the eventtypes table. This table is already populated and contains the following rows:

The list of event types for user selection are stored in the Eventtypes table.

Establishing a relationship between the two tables

When the user selects an event type from the list obtained from reading the eventtypes table, the correct event type must be saved to the trips table with all the other trip-related data. The application could store the eventType (for example, mountain climbing) itself into the eventType column in the trips table. But if the name Mountain Climbing were later shortened to Climbing in the eventtypes table, new mountain climbing trips would be classified differently than ones saved before the change. For this reason and to save space in the database, the key to the eventtypes row (eventTypeID) is stored in the trips table instead.

The two tables are said to have a relationship. This relationship works by matching data in key fields. In this case, the matching fields consist of a primary key (eventTypeID) from the eventtypes table, which provides a unique identifier for each record, and a foreign key (eventType) in the trips table. The foreign key contains the same value as the primary key, pointing to a unique event type. The following figure shows this relationship:

This image shows the relationship between the eventtypes table and the trips table.


Exercise 4: Developing the sample application

Using the application functional requirements and the database that is provided for this tutorial, you are ready to use ColdFusion to develop the Trip Maintenance application. The remaining lessons in the tutorial step you through the process of constructing this application. When you are done, the main page for the Trip Maintenance application will appear as follows:

This image shows a picture of the main application page.

The main application page is where users will come to view information about trips and to navigate to other ColdFusion pages to add, edit, or search for new trips.

The following lessons explain how to do these tasks:

  • Configure your development environment (Lesson 2: Configuring Your Development Environment).
  • Retrieve data from a database (Lesson 3: Retrieving Data).
  • Build dynamic queries (Lesson 4: Building Dynamic Queries).
  • Build the trip detail page (Lesson 5: Creating a Trip Detail Page).
  • Build the main application page (Lesson 6: Creating a Main Application Page).
  • Write code to enforce Compass Travel business rules (Lesson 7: Validating Data to Enforce Business Rules).
  • Implement browsing and searching (Lesson 8: Implementing Browsing and Searching).
  • Enable database maintenance (Lesson 9: Enabling Database Maintenance).
  • Restrict access to the Compass Travel application by requiring user authentication (Lesson 10: Restricting Access to ColdFusion Applications).


How to proceed

Each lesson in the tutorial is designed to let you proceed at your own pace. At any time, you can stop and later return to that place in a lesson so that you can complete all the sections in the lesson.

Each lesson guides you through a scenario to enhance the Compass Travel Trip Maintenance application. Sections within a lesson present basic programming concepts that you need to understand before completing the section exercises.

Depending on your programming experience, you can read the entire lesson and then proceed to the hands-on exercises, or you can skip some information in the lesson and proceed directly to the exercises. For each exercise, there is a completed version of each file created or modified in that lesson. The completed solution files are in the directory cf_root/cfdocs/getting_started/solutions. Appended to each filename is the lesson and exercise number. For example, the version of the file tripdetail.cfm that you would have after performing the steps in Lesson 5, Exercise 4 is named tripdetail_lesson5_ex4.cfm. To use the solution file and continue with Lesson 5, Exercise 5, copy the tripdetail_lesson5_ex4.cfm file to the cf_root/cfdocs/my_app directory, and overwrite the tripdetail.cfm file if it already exists in the my_app directory.


Working directories

The following table describes the working directories for this tutorial:

Directory | Description
my_app | You save all your source code in this directory.
solutions | You can find solutions to all the exercises in this directory.
db | You use this directory as the working directory for the Compass Travel database.
photos | You use this directory to access existing trip photographs.
images | You use this directory to access application image files.

Locating the working directories

The working directories for this tutorial are under your web root directory. For example, the directory path on your computer might look like the following:

  • (On Windows) web_root\cfdocs\getting_started
  • (On UNIX) web_root/cfdocs/getting_started

Note: When using the J2EE configuration, the cfdocs directory is under the ColdFusion web application root. For more information, see Saving your ColdFusion page.

You can view ColdFusion application pages on your local computer by opening a web browser and entering one of the following URLs:

Configuration | URL
For local third-party web server configuration | http://localhost/cfdocs/getting_started/my_app/<pagename>.cfm
For built-in ColdFusion web server configuration | http://localhost:8500/cfdocs/getting_started/my_app/<pagename>.cfm

For more information about the tutorial file structure and the location of the getting_started subdirectories, see Exercise 1: Verifying the tutorial file structure.


Requirements

To use this tutorial, you must have the following components installed:

ColdFusion MX 7 For information on how to install ColdFusion MX 7, see Installing and Using ColdFusion MX.

Database Management System A database management system can be installed on the same computer as ColdFusion MX or on a separate computer. For the purpose of this tutorial, a Microsoft Access database file for Microsoft Windows users and a PointBase database file for UNIX users have been provided. For information about how to configure the Compass Travel data source, see Lesson 2: Configuring Your Development Environment. For additional information about configuring a data source, see Installing and Using ColdFusion MX.

Web browser You can use Microsoft Internet Explorer (4.0 or later) or Netscape Navigator (6.0 or later).

Text editor or IDE (Interactive Development Environment) In order to use the Macromedia Dreamweaver Extensions described in this tutorial, you must use Dreamweaver MX 2004. However, you can use Macromedia HomeSite+, ColdFusion Studio, any text editor, or IDE, and copy and paste the code that the Dreamweaver Extensions create. In the exercises in this tutorial, the term editor means Dreamweaver MX 2004, HomeSite+, ColdFusion Studio, or any text editor or IDE of your choice.

Previous


Lesson 2: Configuring Your Development Environment

In this lesson, you set up your development environment for the tutorial. This lesson describes the tutorial file structure, and how to configure the database connection and debugging options. Additionally, it provides an overview of using Macromedia Dreamweaver MX for Macromedia ColdFusion development.

This lesson explains how to do the following tasks:

Exercise 1: Verifying the tutorial file structure

Exercise 2: Setting up your development environment

Exercise 3: Configuring a database connection

Exercise 4: Configuring debugging options
Next


Exercise 1: Verifying the tutorial file structure

Before you begin the tutorial, verify that the configuration of the computer where ColdFusion MX 7 is installed matches the file structure described in the following sections.

The files required to complete the Compass Travel tutorial are installed under the web server root directory. The location of this directory varies, depending on whether you chose to configure a local third-party web server (such as IIS) or the ColdFusion stand-alone web server during installation, as follows:

  • When you use a third-party web server (such as IIS or Apache), the files are installed in: web_root/cfdocs/getting_started.
  • When you use the ColdFusion built-in web server, the files are installed in: cf_root\webroot\cfdocs\getting_started.

The following is the getting_started directory structure:

getting_started
   -db
   -my_app
      -images
   -new_user_database
   -photos
   -solutions

Note: When you use the J2EE configuration, the cfdocs directory is under the ColdFusion web application root. For more information, see Saving your ColdFusion page.

ColdFusion MX installs two copies of the sample CompassTravel database file. The working copy is located in the db directory; a backup copy of the file is in the new_user_database directory.

To ensure that you are working with the original database file, verify that the file in the db directory has the same date as the backup file in the new_user_database directory. If the date of the file in the db directory is later than the backup file, replace the file in the db directory with a copy of the backup database.

Caution: Do not write to the database file in the new_user_database directory. The backup file lets multiple users perform the tutorial.

In each of the database subdirectories, the tutorial provides one sample database file for Microsoft Windows users and one sample database file for UNIX users. Windows users use a Microsoft Access file, and UNIX users use a PointBase file.

Note: The sample PointBase file consists of two files: compasstravel.dbn and compasstavel$1.wal. ColdFusion MX uses both of these files to work with the content in the sample PointBase database.

Save all the files that you create for the tutorial application in the my_app directory. This directory contains one subdirectory for images. The image subdirectory contains the required image files for the tutorial application.

The photos directory contains the required photo files for the tutorial application. The solutions directory provides sample application files that you can use when building the tutorial application.


Exercise 2: Setting up your development environment

If you are running ColdFusion in a Windows environment, Macromedia recommends that you use Macromedia Dreamweaver MX for ColdFusion development; however, if you are running ColdFusion in a UNIX environment, you should use the text editor that you prefer. Although Dreamweaver MX offers features that help you create ColdFusion applications quickly and easily, you can still follow the steps of the tutorial by entering or copying the code examples into your editor.

Note: To use the Dreamweaver Extensions included with ColdFusion MX 7, you must use Macromedia Dreamweaver MX 2004 version 7.0.1.

About Macromedia Dreamweaver MX

Macromedia Dreamweaver MX is the preferred development environment for building ColdFusion MX 7 applications. It supports the latest ColdFusion MX 7 features, and it combines superior code editing features with the visual design features of Dreamweaver. You can build ColdFusion MX 7 applications by writing the code manually or generating the code by using one of the code-generating tools provided with Dreamweaver MX. In addition, ColdFusion MX 7 provides extensions to Dreamweaver that let you perform some administrative tasks without leaving the Dreamweaver environment and generate code for some of the most common tasks you encounter when creating a ColdFusion application.

With Dreamweaver MX, you can author and test your application code from a local or remote client. You can save your code directly to the server computer where ColdFusion is installed. The following sections provide an overview of Dreamweaver MX, and information on how to configure Dreamweaver MX for ColdFusion development.


Features for ColdFusion developers

Dreamweaver MX provides a wide variety of code editing features for ColdFusion developers, including the following:

  • Extensions that generate code for common ColdFusion application tasks.
  • Extensions that let you perform administrative tasks without leaving the Dreamweaver environment.
  • Rich tag editors for quickly setting attributes and values for every CFML tag.
  • Code hints for writing CFML tag attributes.
  • A code validator for validating code readiness against other ColdFusion versions.
  • A tag chooser with integrated reference material for inserting ColdFusion tags.
  • A snippets panel for reusing code.
  • An integrated debugging display for quickly pinpointing problem areas in the code.
  • A remote ColdFusion server connection for browsing remote data sources and files.
  • ColdFusion MX documentation included in the Dreamweaver MX online Help.

To use Dreamweaver MX to build the sample ColdFusion application in this tutorial, see the following sections for information about configuring Dreamweaver for ColdFusion development.

Configuring Dreamweaver MX for ColdFusion development

Before you use Dreamweaver MX to create the sample application in this tutorial, you must configure Dreamweaver to use the ColdFusion MX 7 Extensions for Dreamweaver, which are included with ColdFusion MX 7. You must also define the connection to the sample database file. The Extensions simplify the process of configuring database connections.

To configure Dreamweaver MX to create the sample application:

  1. Install the ColdFusion MX 7 Extensions for Dreamweaver by double-clicking the cfmx7dreamweaverextensions.mxp file, which is located in the cf_root/wwwroot/CFIDE/installers directory.
  2. Create a site that contains the tutorial files.
  3. Specify ColdFusion as the application document type.
  4. Specify ColdFusion as the site application server technology. For information about how to perform these steps, see the Dreamweaver MX online Help or Using Dreamweaver MX.
  5. Specify the RDS login information for the site.

    Tip: If you are a new Dreamweaver MX user, you can perform the Dreamweaver MX tutorial before using Dreamweaver MX to build the sample application. The tutorial in this book does not describe how to use Dreamweaver. The purpose of this tutorial is to teach you how to build ColdFusion applications using ColdFusion Markup Language (CFML).


Exercise 3: Configuring a database connection

One of the most commonly used and most powerful features of ColdFusion is the ability to connect to and manipulate data from a wide variety of databases. Like most ColdFusion developers, you will probably use this capability often. To be able to connect to a database, you must create a a data source in ColdFusion. A data source contains the information that ColdFusion needs to be able to recognize and communicate with a database.

ColdFusion MX 7 includes a Dreamweaver extension that lets you create a data source without having to leave the Dreamweaver environment. If you are not using Dreamweaver, you use the ColdFusion Administrator to create data sources; seeConfiguring a data source in the Administrator for more information.

Using Dreamweaver to configure a data source

To create a ColdFusion data source without leaving the Dreamweaver environment, you need the following information:

  • The type of connection to use
  • The name to call the data source
  • The location of the database file(s)

To configure a database connection in Dreamweaver:

  1. Ensure that the site that contains the tutorial files is the current site.
  2. Select Create New > ColdFusion.
  3. On the Databases tab, click the + button.
  4. Select Microsoft Access Connection.
  5. In the CF Data Source Name text box, enter CompassTravel.
  6. Specify the Database File as c:\CFusionMX7\wwwroot\cfdocs\getting_started\db\CompassTravel.mdb.
  7. Select the Use Default Username check box.
  8. When prompted for the password for this site, enter the ColdFusion Administrator password you specified when you installed ColdFusion MX 7.
  9. Click OK.
  10. Continue with Exercise 4: Configuring debugging options.

Configuring a data source in the Administrator

You can use the ColdFusion MX 7 Administrator to configure a data source. If you are running ColdFusion in a UNIX environment, you must use the ColdFusion MX 7 Administrator to connect to the PointBase database in the data source.

To access the ColdFusion MX 7 Administrator:

  • Open a browser and go to one of the following URLs:
    • External web server users: http://localhost/CFIDE/administrator
    • Built-in web server users: http://localhost:8500/CFIDE/administrator
    • J2EE server users: http://localhost:portnumber/CFIDE/administrator. If you installed ColdFusion Enterprise Edition with JRun, the default HTTP port is 8300.

Note: If you are accessing the ColdFusion MX Administrator from a remote client, you must replace localhost with the host name or IP address of the computer where ColdFusion MX is installed.

The following sections describe how to establish a connection to the sample tutorial database file and how to enable optional debugging settings.

Configuring the connection to the sample database file

The following procedures describe how to configure a connection to the sample database file (CompassTravel) using the ColdFusion MX Administrator. Prior to building the sample application, you must configure the Compass Travel database connection.

Perform one of the following procedures. The Microsoft Access procedure is for Windows users. The PointBase procedure is for UNIX and Macintosh OS X users.

To define the connection to the sample Microsoft Access database:

  1. In the ColdFusion MX Administrator, select Data & Services > Data Sources.
  2. In the Data Source Name box, enter CompassTravel.
  3. In the Driver list, select Microsoft Access with Unicode.
  4. Click Add.
  5. Click Browse Server and navigate to the cf_root/cfdocs/getting_started/db/CompassTravel.mdb file.
  6. Click Apply.
  7. Click Show Advanced Settings and ensure that the settings for CLOB and BLOB are enabled (checked).
  8. Click Submit to complete the data source configuration.

    The ColdFusion MX Administrator verifies the data source connection and the name CompassTravel appears in the Connected Data Sources table.

  9. Ensure that OK appears in the Status column for CompassTravel.

    If the connection to the CompassTravel data source fails, do the following:

    1. Verify that the name of the data source file does not contain a space. If it does contain a space, delete the data source from the Connected Data Source dialog box. To do this, click the Delete action button associated with the CompassTravel data source name, and then repeat the steps in this procedure to reconfigure this data source.
    2. Verify that the path specified for the Compass Travel database file is correct.

To define the sample PointBase database file:

  1. In the ColdFusion MX Administrator, select Data & Services > Data Sources.

    The Add New Data Source dialog box appears.

  2. Specify the following:

    Field

    Action

    Data Source name text box

    Specify the name CompassTravel.

    Note: Ensure that the name of the data source file does not contain any spaces. If the name contains a space, the data source connection fails.

    Driver drop-down selection box

    Select Other.
  3. Click Add to configure the data source name and driver.

    The Data Source dialog box appears.

  4. Specify the following:

    Field

    Action

    JDBC URL

    Enter the following JDBC URL for the Compass Travel PointBase files:

    jdbc:pointbase:compasstravel,database.home=/<home location>/wwwroot/cfdocs/getting_started/db

    The following is the default home location for stand-alone ColdFusion web server configurations:

    /opt/coldfusionmx7/wwwroot/cfdocs/getting_started/db

    Driver Class

    Enter the following driver class:

    com.pointbase.jdbc.jdbcUniversalDriver

    Driver Name

    Specify PointBase.

    Username

    Specify PBPUBLIC.

    Password

    Specify PBPUBLIC.

    Description

    Enter the following:

    Database file for Compass Travel tutorial
  5. Click Show Advanced Settings to make the following settings:

    Field

    Action

    Maintain Connection

    Disabled (clear)

    CLOB

    Enabled (checked)

    BLOB

    Enabled (checked)
  6. Click Submit to complete the data source configuration.

    The name CompassTravel appears in the Connected Data Sources dialog box.

  7. Click Verify All Connections to ensure that ColdFusion can access this file.

    OK appears in the Status column for successful connections.

    If the connection to the compass travel data source fails, do the following:

    1. Verify that the name of the data source file does not contain a space. If it does contain a space, delete the data source from the Connected Data Source dialog box. To do this, click the Delete action button associated with the CompassTravel data source name, and then repeat the steps in this procedure to reconfigure this data source.
    2. Verify that the JDBC URL is correct.


Exercise 4: Configuring debugging options

ColdFusion provides debugging information to make it easier to fix problems in your application. You can view debugging information for individual ColdFusion pages while editing them in Dreamweaver, or enable debugging throughout your application by using the ColdFusion MX 7 Administrator to set debugging options.

Viewing debugging information within Dreamweaver

Instead of enabling debugging for an application, you can view debugging information for any ColdFusion page in Dreamweaver.

To view debugging information for a ColdFusion page in Dreamweaver:

  1. Open the page to debug in Dreamweaver.
  2. On the Documents tab, click the Server Debug icon.
  3. If an Exceptions category appears in the Results panel, click the + button to expand the category.
  4. Fix the error and save the file, and click Browse.
  5. To leave debug mode, switch to either Code view or Design view.

Enabling debugging in the ColdFusion MX Administrator

The ColdFusion MX Administrator provides a variety of debugging settings that let you enable debugging information on a server-wide basis. If you are working on a development system, you can have these options turned on all the time. However, if you are working on a production system, you most likely will not want to have these options turned on, because the debugging information can appear on the bottom of an application page or in a dockable tree in your browser.

The location of the debugging information or the type of debugging data shown varies, depending on the options that you enable on the Debugging page in the ColdFusion MX Administrator. In the following example, the debugging output includes general information about the ColdFusion server, the execution time of the application, and variable information:

The following figure shows an example of how debugging information can appear when appended to the bottom of a page in a browser:

This image shows a picture of debugging information appended to the bottom of a form page.

If you are using a development server to build the sample application in this tutorial, you can enable some of these settings to help debug any unexpected problems.

Use the following steps to enable debugging options in the ColdFusion MX Administrator.

To enable debugging options:

  1. In the ColdFusion MX Administrator, select Debugging & Logging > Debugging Settings.

    A list of debugging options appears on the Debugging Settings page.

  2. Select the Enable Debugging check box.

    The debugging service is enabled for all options already selected on the page.

  3. On the Debugging Settings page, view the description of each option that is enabled. If you do not want to append debugging information for a specific option, clear the check box.

    For the purpose of this tutorial, enable the following debugging options:

    Option

    Description

    Database Activity

    Identifies database activity related to SQL query events.

    Exception Information

    Identifies ColdFusion exceptions raised in the debugging output.

    Tracing Information

    Lets you trace event information reported in the debugging output.

    Form, URL and Session Variables

    Displays variable information in the debugging output.
  4. Click Submit Changes when you are done.


Sending debugging information to remote clients

If you are using a remote client to perform the tutorial in this book, you must specify your IP address to receive debugging information. If you are working on a local client (the computer where ColdFusion is installed), you do not need to do this.

To receive debugging information when using a remote client:

  1. In the ColdFusion MX Administrator, select Debugging & Logging > Debugging IP Addresses.

    The Debugging IP Address page appears.

  2. In the IP Address text box, enter the IP address of your remote client.
  3. Click Add.


Summary

In this lesson, you set up your development environment, configured data sources, and set up debugging options.

In the next lesson

In the next lesson, you learn to retrieve data from a database, display the results of querying a database, and use ColdFusion components to write structured, reusable code.
Previous


Lesson 3: Retrieving Data

In this lesson, you begin the construction of a Macromedia ColdFusion web application for the fictitious company, Compass Travel. The exercises in this lesson introduce you to the process of retrieving data from the Compass Travel relational database.

This lesson contains the following exercises:

Exercise 1: About the trip list

Exercise 2: Retrieving the information for the trip list

Exercise 3: Displaying the query result using the cfoutput tag

Exercise 4: Writing structured, reusable code

Exercise 5: Creating additional queries
Next


Exercise 1: About the trip list

As you recall from Lesson 1: Preparing to Build the Sample Application, one of the requirements for the Trip Maintenance application is the ability to generate trip listings. To help Compass Travel agents take trip reservations by telephone and in person, the trip coordinator maintains a list of current trip offerings. Years ago, the coordinator would type the list and fax it to the various Compass Travel offices in an effort to keep everyone informed. When Compass Travel built an intranet that was accessible by all offices, the trip coordinator added the following HTML web page to the site:

This image shows a picture of the Trip List page.

Each time the Trip List HTML page is rendered in a browser, it displays the same web page. Since the page always shows an identical trip list, it is considered a static web page. You should only use static web pages when you are creating a page that is not likely to change often.

Using the static web page approach, the Trip Coordinator needs to modify all the web pages that reference trip lists when trips are added, deleted, or trip names are changed. This manual process of updating each web page can lead to inaccurate or untimely information. Luckily, Compass Travel has built a database that contains a list of trips, so you can build a more accurate and timely solution for the trip coordinator.

In this lesson, you will create a dynamic Trip List page to present an up-to-date list of trips on the Compass Travel website. The primary users of this component are the Compass Travel coordinators and agents, not the general public.

To display the information on the page, you do the following:

  1. Retrieve the data that you want to display.
  2. Display the data on the page.


Exercise 2: Retrieving the information for the trip list

Relational database management systems process SQL instructions sent to them from various applications. ColdFusion sends SQL statements to database managers to manipulate data. ColdFusion needs a way to know to which database manager to send a specific SQL string for evaluation. In CFML, the cfquery tag serves this purpose. You will use the SQL SELECT statement and the cfquery tag to create a dynamic version of the Trip List page described earlier in this lesson. In this example, you use the cfquery tag to return all the trip names found in the tripName column in the Compass Travel Trips table. To use the SQL SELECT statement to dynamically retrieve this information, you must execute the SQL SELECT statement between the cfquery start and end tags.

To retrieve the trip list:

  1. If you are working in Dreamweaver, ensure that the site that you created in Lesson 1 is the current site. For more information, see Configuring Dreamweaver MX for ColdFusion development.
  2. Open a new file and save it as triplisting.cfm in the my_app directory.

    Note: If you are working in Dreamweaver, ensure that you select ColdFusion Templates in the Save As Type list.

  3. Enter the following code, or do the steps listed in the Let Dreamweaver do it section.
    <cfquery name="TripList" datasource="CompassTravel">
    SELECT trips.tripName FROM trips
</cfquery>
  4. Save the file.

Let Dreamweaver do it

Dreamweaver lets you create a query without having to enter the code.

To create a query in Dreamweaver:

  1. Click the Bindings tab in the application panel.
  2. Click the + button.
  3. Select Recordset (Query).
  4. In the Name text box, enter TripList.
  5. From the Data source list, select CompassTravel.
  6. From the Tables list, select trips.
  7. Next to Columns, click Selected.
  8. Select tripName.
  9. Click OK.
  10. Save the file.

Your ColdFusion application page retrieves the information for the trip list. Next, you need to display the information.

Reviewing the code

The following table describes the code used to build the query:

Code

Explanation

<cfquery name="TripList" datasource="CompassTravel">

ColdFusion query named TripList. Submits any SQL statement between the cfquery start and end tags to the data source specified in the datasource attribute.

SELECT trips.tripName FROM trips

SQL SELECT statement to retrieve all tripName(s) from the trips table.


Exercise 3: Displaying the query result using the cfoutput tag

In CFML Basics, you learned that the ColdFusion cfoutput tag is an easy mechanism to display literal text and the contents of variables. Additionally, the cfoutput tag significantly simplifies displaying the results of queries. When used to display the results from a query, the cfoutput tag automatically loops through the record set for you. You simply specify the name of the query in the query attribute of the cfoutput tag:

<cfoutput query="TripResult">

All the code between the cfoutput start and end tags is the output code block. The output code block executes repeatedly, once for each row in the record set. However, if the query returns no rows, ColdFusion skips the code contained in the output code block.

<cfoutput query = "xxx">
    ...output code block...
</cfoutput>

Displaying the column contents from the SQL statement

In CFML you surround variables with number signs (#) to display their contents using the cfoutput tag. You also use this approach with column names specified in the SELECT statement of a cfquery. For example, when you want to display the trip names from the SQL query, you use #tripName# within the output code block:

<cfoutput query="TripResult">
    #tripname#
</cfoutput>

For additional information about using SQL with cfquery and cfoutput, see ColdFusion MX Developer’s Guide.

To display the query results:

  1. Modify the triplisting.cfm file by adding the highlighted code so that it appears as follows:
    <cfquery name="TripList" datasource="compasstravel">
        SELECT trips.tripName FROM trips
</cfquery>
<html>
    <head>
        <title>Trip Listing</title>
    </head>
    <body>
        <h1>Trip List</h1>
        <cfoutput query="TripList">#tripName#<br></cfoutput>
    </body>
</html>
  2. Save the file as triplisting.cfm in the my_app directory.
  3. View the triplisting.cfm page in a browser. The page lists all the trip names retrieved from the Compass Travel database.

Reviewing the code

The following table describes the code used to display the query result set:

Code

Explanation

<cfoutput query="TripResult"> #tripName#<br</cfoutput>

Output code block. Displays the value of the tripName column for each row in the result set from the "TripResult" query.


Exercise 4: Writing structured, reusable code

Generally, it is good coding practice to separate business logic from the display. The ColdFusion page that you just created contains both business logic (the database query) and presentation (the output code block). To separate them, you put the query in a ColdFusion component (CFC). Doing so separates business logic from presentation; it also makes it easy to reuse the query anywhere in your application. For more information, see Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide.

To move the query to a CFC:

  1. Create the CFC file.
  2. Copy the query to the CFC.
  3. Call the method that contains the query.

Creating the CFC file

ColdFusion components (CFCs) are special files saved with the filename extension .cfc. They can contain data and functions. Within CFCs, functions are referred to as methods. Actions that you want ColdFusion to perform, such as querying a database, are contained in component methods. One CFC can contain many methods. Each method in a CFC can return only one variable. The following is the general syntax of a CFC:

<cfcomponent>
    <cffunction name="firstMethod">
         <!--- CFML code for this method goes here. --->
    </cffunction>
    <cffunction name="secondMethod">
         <!--- CFML code for this method goes here. --->
    </cffunction>
</cfcomponent>

To create the CFC file:

  1. Create a directory named components as a subdirectory of the my_app directory.
  2. Open a new blank file.

    Note: If you are using Dreamweaver, select Dynamic page in the Category list, and select ColdFusion Component in the Dynamic Page list.

  3. Enter the following code, or do the steps listed in the Let Dreamweaver do it section.
    <cfcomponent displayName="Get Trips" hint="Get trip information">
    <cffunction name="basicList" displayName="List all trips"
    hint="List trips in same order as in table" access="public"
    returnType="query" output="false">

        <cfreturn>
    </cffunction>
</cfcomponent>
  4. Save the file as gettrips.cfc in the components directory.

Let Dreamweaver do it

Dreamweaver lets you create a ColdFusion component without having to enter the code.

To create a CFC in Dreamweaver:

  1. Click the Components tab.
  2. Click the + button.
  3. In the Display name text box, enter Get Trips.
  4. In the Hint text box, enter Get trip information.
  5. In the Name text box, enter gettrips.
  6. Click the Browse button, and make the components directory the current directory.
  7. In the Section list, click Functions.
  8. Click the + button.
  9. In the Name text box, enter basicList.
  10. In the Display name text box, enter List all trips.
  11. In the Hint text box, enter List trips in same order as in the table.
  12. Select query as the Return type.
  13. Click OK.
  14. Save the file as gettrips.cfc in the components directory.

Copying the query to the CFC

To copy the query to the CFC, you copy the CFML to the CFC, between the opening and closing cffunction tags.

To copy the query to the CFC:

  1. Highlight the following code on the triplisting.cfm page:
    <cfquery name="TripList" datasource="CompassTravel">
    SELECT trips.tripName FROM trips
</cfquery>
  2. Cut the highlighted code and copy it to the gettrips.cfc page so that it appears as follows:
    <cfcomponent displayName="Get Trips" hint="Get trip information">
    <cffunction name="basicList"
        displayName="List all trips" hint="List trips in same order as in table"
        access="public" returnType="query" output="false">
        <cfquery name="TripList" datasource="CompassTravel">
            SELECT trips.tripName FROM trips
        </cfquery>
        <cfreturn>
    </cffunction>
</cfcomponent>
  3. Modify the code by adding the following text so that the method returns the results of the query to the triplisting.cfm page:
    <cfreturn TripList>
  4. Save the gettrips.cfc file.

Calling the query method

To perform the query that is now in a method in a ColdFusion component, you have to call (invoke) the method. To do so, you can use the cfinvoke tag. Within the cfinvoke tag, you specify the name of the ColdFusion component, the method to call, and the query to return to the calling page. The name of the component includes the package, "cfdocs.getting_started.my_app.components." The package looks very similar to the path, except that it contains periods instead of slashes. Like a path, it specifies the location of the component.

To invoke the method:

  1. Go to the top of the triplisting.cfm file.
  2. Enter the following code, or do the steps listed in the Let Dreamweaver do it section.
    <cfinvoke
 component="cfdocs.getting_started.my_app.components.gettrips"
 method="basicList"
 returnvariable="TripList">
</cfinvoke>
  3. Save the file.
  4. View the triplisting.cfm page in a browser and notice that the page lists the trip names, just as it did previously.

Let Dreamweaver do it

Dreamweaver lets you invoke a method in a CFC without having to write the code.

To invoke the method using Dreamweaver:

  1. Click the Components tab in the Application panel.
  2. Click the + button next to cfdocs.getting_started.my_app.components.
  3. Click the + button next to gettrips.
  4. Select query basicList() and drag it to the top of the triplisting.cfm file.
  5. Change the value of the returnvariable to be the name of the query, TripList, as follows:
    returnvariable="TripList"
  6. Return to Step 3 in the To invoke the method: procedure.


Exercise 5: Creating additional queries

In this exercise, you will improve the Trip List page to make it easier for the Compass Travel agents to locate trips. You must make the following improvements:

  • Sort the trip names in alphabetical order.
  • Display the departure date, return date, and price for each trip.
  • Develop a Budget Trip List report that identifies trips that are priced $1500 or less.

You could modify the existing query; however, you may need to use that query in the future. Instead, you can create an additional method in the gettrips.cfc component with a query that meets the preceding requirements. You can then call the new methods with the enhanced query from the triplisting.cfm page. Display the triplisting.cfm page in the browser after each step to ensure that the corresponding requirement was met.

To modify the application, you must:

  • Create the query that meets the requirements.
  • Invoke the method that contains the query.
  • Display the results.

Creating the query

To continue writing structured, reusable code, you create the query in a method in the existing CFC.

To create a method with enhanced query results:

  1. Open the gettrips.cfc file.
  2. Enter the following code just before the closing cfcomponent tag, or do the steps in the Let Dreamweaver do it section.
    <cffunction name="getBudgetTrips" displayName="Budget trip list"
    hint="List trips under $1500 alphabetically"
    access="public"
    returnType="query"
    output="false">
    <cfquery name="budgetTrips" datasource="CompassTravel">
        SELECT tripName, departureDate, returnDate, price
        FROM trips
        WHERE price <= 1500
        ORDER BY tripName
    </cfquery>
    <cfreturn budgetTrips>
    </cffunction>
  3. Save the file.

Let Dreamweaver do it

You can use the Dreamweaver Extensions to create a CFC query and invoke the method that contains the query from the triplisting.cfm page.

To create the enhanced CFC query in Dreamweaver:

  1. Open the gettrips.cfc file and position the pointer before the closing cfcomponent tag.
  2. Click the Bindings tab.
  3. Click the + button.
  4. Select Recordset (Query).
  5. In the Name text box, enter budgetTrips.
  6. Click the New Function button.
  7. In the New function name text box, enter getBudgetTrips.
  8. Click OK.
  9. In the Data Source list, select CompassTravel.
  10. In the Table list, select trips.
  11. Click the Selected button.
  12. Select tripName, departureDate, returnDate, and price from the list of columns.
  13. In the Filter section, select price, select < from the list of operators, select Entered value, and enter 1500 in the text box.
  14. In the Sort section, select tripName, and select Ascending.
  15. Click OK.
  16. Save the file.

Invoking the new method

To use the new query, you invoke the method that contains the query.

To invoke the new method with the enhanced query:

  1. Open the triplisting.cfm file.
  2. Modify the following code, or do the steps listed in the Let Dreamweaver do it section.
    <cfinvoke
 component="cfdocs.getting_started.my_app.components.gettrips"
 method="getBudgetTrips"
 returnvariable="budgetTrips">
</cfinvoke>
  3. Save the file.

Let Dreamweaver do it

You can use the Dreamweaver Extensions to create the CFC query and invoke the method that contains the query from the triplisting.cfm page.

To invoke the enhanced CFC query in Dreamweaver:

  1. Delete the cfinvoke code block.
  2. Click the Components tab.
  3. Click the + button next to cfdocs.getting_started.my_app.components, and click the + button next to gettrips.
  4. Select query getBudgetTrips and drag it to the top of the file.
  5. Change the value of the returnvariable to be the name of the query, budgetTrips, as follows:
    returnvariable="budgetTrips"
  6. Save the file.

Displaying the results

To display the results of the new query, you refer to the new query in the cfoutput block and include all the columns that you want to display.

To display the results of the enhanced query

  1. Change the output block in the triplisting.cfm file to output all three selected fields from the enhanced query, as follows:
    <cfoutput query="budgetTrips">
    #tripName#
    departs: #departureDate#
    returns: #returnDate#
    price: #price#<BR>
</cfoutput>
  2. Change the heading tag in the triplisting.cfm file from <h1>Trip List</h1> to <h1>Budget Trip List</h1>.
  3. Save both the triplisting.cfm file and the gettrips.cfc file.
  4. View the triplisting.cfm page in a browser and verify that all the new requirements were met. The revised TripListing.cfm page looks like this:

    This image shows a picture of the revised unformatted Budget Trip List page.

    The dates and prices in the preceding listing are not formatted. In Lesson 6: Creating a Main Application Page, you will enhance the look of this page.


Summary

This lesson described how to access a relational database using ColdFusion. You used the SQL SELECT statement and the cfquery and cfoutput tags to display trip lists. You also learned to use ColdFusion components to write structured, reusable code.


In the next lesson

In the next lesson, you will build the search form to let users select which information to retrieve. To build the query based on what the user enters in the search form, you will use dynamic SQL. You will then display the results of the search on an action page.
Previous


Lesson 4: Building Dynamic Queries

In this lesson, you develop a search form to allow users to select the information to retrieve, and then display, the search results.

This lesson contains the following exercises:

Exercise 1: Creating the trip search form

Exercise 2: Building a query that uses dynamic SQL

Exercise 3: Constructing the initial Trip Search Results page

Exercise 4: Testing the Trip Search Results page

Exercise 5: Enabling the departure and price criteria on the Trip Search form

Exercise 6: Testing the revised Trip Search Results page
Next


Exercise 1: Creating the trip search form

As you recall from Lesson 1: Preparing to Build the Sample Application, two of the requirements for the Trip Maintenance application are the ability to generate trip listings and a trip query facility. You will create a search interface that meets both of these requirements in this exercise.


About the trip search form

The dynamic listings that you developed in Lesson 3: Retrieving Data meet many of Compass Travel’s requirements for locating trips. However, what if the number of trips were in the thousands or tens of thousands? Locating the right trip for a customer might be difficult and certainly time consuming. Moreover, it is very hard, if not impossible, to anticipate all the ways that a user might want to search for trips.

A better solution is to provide an interface for the user to specify the search criteria. The purpose of the Trip search form is to enable Compass Travel employees to search and view brief details about existing trips on their website. The completed form should appear as follows:

This image shows a picture of the trip search form.


Designing the search criteria page

When designing the search criteria page, it is a good idea to develop a list of possible queries that the user might issue when searching for the records. Most Compass Travel customers are primarily concerned with trip locations, departure dates, and price; the following is a list of the types of queries that the agents are likely to require at Compass Travel:

  • List the trips located in Hawaii.
  • Identify the trips with a price greater than $3,000.
  • Show the trips departing after 11/11/2005 that are priced less than $2,000.

There are a number of considerations to take into account when you design a search page to capture the user’s search criteria. The following are two of the most important considerations:

  • For which database columns will the user be allowed to specify a search condition?
  • Should the user be allowed to identify which database columns to include in the record set?

In this exercise, the Compass Travel trip coordinator searches the trips based on tripLocation, departureDate, and price. Because these columns are the only ones that users can query, they are the only ones contained in the WHERE clause of the generated SQL statement. In addition, the coordinator has no control over which columns are returned in the record set. The query always returns the same columns to identify a trip:

  • tripName
  • tripLocation
  • departureDate
  • returnDate
  • price
  • tripID

In later exercises, you will reference these columns when you build the SQL SELECT statement for the cfquery in the search action page.


Understanding search query operators

Now that you have decided which columns can be queried (tripLocation, departureDate, and price), you can build a simple form that lets the user enter values for each of these fields. If the user enters a value (for example, Boston) for the tripLocation field and leaves the other two fields blank, the search results page constructs the following SQL statement:

SELECT tripName, tripLocation, departureDate,
    returnDate, price, tripID
FROM trips
WHERE tripLocation = 'Boston'

When you design the Search Criteria page, you must decide which operators to support for each of the columns you can query. The operators that you use depend on the data type of the SQL column.

For example, suppose the user wants a list of all the trips where the trip location begins with a "B." SQL is well-suited for this type of query. Typical SQL string operators are equals, starts with, contains, and ends with.

However, price is a numeric data type. The user can specify any of the following:

  • Price is 5000
  • Price less than 600
  • Price greater than 1500

Although many more operators are permissible, for simplification, you can use the following operators for the Compass Travel columns that you can query:

Column to query | Query operators
tripLocation | is, begins with
departureDate | is, before, after
price | is, greater than, less than

Creating the Trip Search page

A simple design for a search criteria page presents an operator list and data entry field for each of the columns that you can query. To create the search criteria page, you create an HTML form.

To create the search page:

  1. Create a blank file.

    Note: If you are using Dreamweaver, select Dynamic page in the Category list and ColdFusion in the Dynamic Page list.

  2. Enter, or copy and paste, the following code in the blank file:
    <html>
<head>
<title>Trip Maintenance - Search Form</title>
</head>
<body>
<img src="images/tripsearch.gif">
<!--- Search form --->
<form action="tripsearchresult.cfm" method="post">

<table>
    <!--- Field: tripLocation --->
    <tr>
        <td>	Trip Location
        </td>
        <td>
            <select name="tripLocationOperator">
                <option value="EQUALS">is
                <option value="BEGINS_WITH">begins with
            </select>
        </td>
        <td>
            <input type="text" name="tripLocationValue">
        </td>
    </tr>
    <!--- Field: departureDate --->
    <tr>
        <td>	Departure Date
        </td>
        <td>
            <select name="departureOperator">
                <option value="EQUALS">is
                <option value="BEFORE">before
                <option value="AFTER">after
            </select>
        </td>
        <td>
            <input type="text" name="departureValue">
            </td>
    </tr>
    <!--- Field: price --->
    <tr>
        <td>Price
        </td>
        <td>
            <select name="priceOperator">
                <option value="EQUALS">is
                <option value="GREATER">greater than
                <option value="SMALLER">smaller than
            </select>
        </td>
        <td>
            <input type="text" name="priceValue">
        </td>
    </tr>
</table>
<p>
<input type="submit" value="Search">
</form>
</body>
</html>
  3. Save the file as tripsearchform.cfm in the my_app directory.

Reviewing the code

The following table describes the search criteria code and its function:

Code

Explanation

<form action="tripsearchresult.cfm" method="post">

Identifies tripsearchresult.cfm as the search action page. Results of user entry are passed to the search action page.

<select name="tripLocationOperator">
<option value="EQUALS">is
<option value="BEGINS_WITH">begins with
</select>

Builds a drop-down list offering the query operators for tripLocation. There must one operator list box for each queryable column.

<input type="text" name="tripLocationValue">

Captures a value to test. There is one text control for each queryable column.


Exercise 2: Building a query that uses dynamic SQL

Dynamic SQL is a term that refers to SQL code that your program generates using variables before the SQL is executed. You can use dynamic SQL to accomplish tasks such as adding WHERE clauses to a search based on the fields that the user filled out on a search criteria page.

Based on the columns that you can query in this tutorial, the SQL query to display the search results would look like this:

SELECT tripName,  tripLocation, departureDate, returnDate, price, tripID
FROM trips

The purpose of the Trip Search form is to supply the data needed to build the WHERE clause to finish this SQL SELECT statement and constrain the query according to the user’s input.

When the user enters the search criteria on the Trip Search form and clicks the Search button, the form fields are posted to the Trip Search Results page. The posted field values compose the WHERE clause in the SQL SELECT statement. The following example lists the WHERE clauses that you can generate depending on the criteria set on the search page:

WHERE tripLocation = 'Aruba'
WHERE tripLocation Like 'C%'
WHERE tripLocation = 'China'
    AND departureDate > 1/1/2001
    AND price < 1500

In this example, the SQL AND operator joins the search condition clauses. To simplify the trip search example, you will use the SQL AND operator to combine all the search condition clauses. A more sophisticated search criteria page might present the user a choice of using AND or OR to connect one search criterion with the others.

The action page invokes a method that builds the WHERE clause so that the SQL SELECT statement retrieves the information that the user requests. Then, the action page displays an HTML table with the results of the user query using the cfoutput block.

Building the WHERE Clause with the cfif and cfset tags

The WHERE clause in a SQL SELECT statement is a string. You use the CFML cfset and cfif tags to conditionally build the WHERE clause depending on values passed to the search action page. The cfset statement creates a variable or changes the value of an existing variable. For example, to create a variable named color and initialize its value to red, you use the following statement:

<cfset color = "red">

The cfif tag instructs the program to branch to different parts of the code depending on whether a test evaluates to True or False. For example, to have some code execute if the color variable is equal to red, and other code execute if it is not, you use the following pseudocode:

<cfif color EQ "red">
... statements for color red
<cfelse>
... statements for other than red
</cfif>

Building a SQL WHERE clause in code is largely an exercise in string concatenation. The & operator combines two strings in ColdFusion. For example, the following code snippet:

<cfset FirstName = "Wilson">
<cfset LastName = "Gato">
<cfset FullName = FirstName & " " & LastName>
<cfoutput>My name is #FullName#.</cfoutput>

results in the following text:

My name is Wilson Gato.

For each search criterion on the Trip Search form, the code within the Trip Search Results page must do the following:

  • Verify that the user entered data in the search criterion’s value field. To do so, you use the cfif tag; for example, <cfif Form.tripLocationValue GT "">.
  • If data was entered, construct a WHERE subclause by concatenating the following:
    • The SQL keyword AND
    • The corresponding SQL column name (in the Trip Search example, tripLocation) for the search criterion
    • The SQL operator equivalent of the search query operator
    • The test value entered by the user

The following code shows the creation of the WHERE subclause:

<cfif Form.tripLocationOperator EQ "EQUALS">
    <cfset WhereClause = WhereClause & " AND tripLocation = '" &
        form.tripLocationValue & "'" >
<cfelse>
    <cfset WhereClause = WhereClause & " AND tripLocation like '" &
        form.tripLocationValue & "%'" >
</cfif>

When you test for a string column within the WHERE clause of the SQL SELECT statement, you must enclose the test value in quotation marks.

When you use a variable to construct a WHERE clause, you must preserve the quotation marks so that the database server does not return an error. To preserve the quotation marks, you must use the ColdFusion PreserveSingleQuotes function. The PreserveSingleQuotes function prevents ColdFusion from automatically escaping single-quotation marks contained in the variable string passed to the function.

Note: The cfqueryparam tag also escapes single-quotation marks. For more information, see CFML Reference.


Creating the CFC query

The following code shows how to construct the tripLocation SQL WHERE subclause. Specifically, it uses a dynamic SQL SELECT statement built from parameters from the Trip Search page to display the search results. To continue the good coding practice of separating business logic and presentation, you put the code to build the query using dynamic SQL in a function in the CFC that you have been working with.

To add the new query to the CFC:

  1. Open the file gettrips.cfc file and position the pointer before the closing cfcomponent tag.
  2. Enter the following code, or do the steps in the Let Dreamweaver do it section:
    <cffunction name="getTripsFromForm" access="public" returntype="query">
    <cfquery name="TripResult" datasource="CompassTravel">
        SELECT tripID, tripName, tripLocation, departureDate,
            returnDate, price FROM trips
    </cfquery>
    <cfreturn TripResult>
</cffunction>
  3. Add the logic for creating the WHERE clause dynamically by entering the highlighted code.
    <cffunction name="getTripsFromForm" access="public" returntype="query">
    <!--- Create WHERE clause from data entered via search form --->
    <cfset WhereClause = " 0=0 ">
    <!--- Build subclause for trip location --->
    <cfif Form.tripLocationValue GT "">
        <cfif Form.tripLocationOperator EQ "EQUALS">
            <cfset WhereClause = WhereClause & " and tripLocation = '" &
    form.tripLocationValue & "'" >
        <cfelse>
            <cfset WhereClause = WhereClause & " and tripLocation like '" & form.tripLocationValue & "%'" >
        </cfif>
    </cfif>
    <cfquery name="TripResult" datasource="CompassTravel">
        SELECT tripID, tripName, tripLocation, departureDate,
            returnDate, price FROM trips
    </cfquery>
    <cfreturn TripResult>
</cffunction>
  4. Add the highlighted code to the cfquery block to use the dynamically built WHERE clause in the query:
        <cfquery name="TripResult" datasource="CompassTravel">
        SELECT tripID, tripName, tripLocation, departureDate,
            returnDate, price FROM trips
            WHERE #PreserveSingleQuotes(WhereClause)#
    </cfquery>
  5. Save the file.

Let Dreamweaver do it

You can use the Dreamweaver Extensions to create the CFC query.

To construct the query with Dreamweaver:

  1. Click the Bindings tab.
  2. Click the + button.
  3. Select Record set (Query).
  4. In the Name text box, enter TripResult.
  5. Click the New Function button.
  6. In the New function name text box, enter getTripsFromForm and click OK.
  7. From the Data source list, select CompassTravel.
  8. From the Tables list, select trips.
  9. Click the Selected radio button.
  10. Select tripName, tripLocation, departureDate, returnDate, price, and tripID.
  11. Click OK.
  12. Return to Step 3 in the To add the new query to the CFC: section.


Exercise 3: Constructing the initial Trip Search Results page

After the user enters the search criteria and submits the form, the results are posted to the Trip Search Results page, as the following figure shows:

This image shows a picture of the trip search results form.

The logic contained in the search results page, also known as the action page, invokes the CFC method that builds the SQL SELECT statement contained in a cfquery tag by using ColdFusion string manipulation. The action page displays the result using the cfoutput tag.

To create the Trip Search Results page:

  1. Create a blank document and save it as tripsearchresult.cfm in the my_app directory.

    Note: If you are using Dreamweaver, select Dynamic page in the Category list, and ColdFusion in the Dynamic Page list.

  2. Enter the following code, or do the steps in the Let Dreamweaver do it section.
    <cfinvoke
    component="cfdocs.getting_started.my_app.components.gettrips"
    method="getTripsFromForm"
    returnvariable="TripResult">
</cfinvoke>
  3. Enter or copy and paste the following code after the closing cfinvoke tag:
    <html>
<head>
<title>Trip Maintenance - Search Results</title>
</head>
<body>
    <img src="images/tripsearchresults.gif">
    <table border="0" cellpadding="3" cellspacing="0">
        <tr bgcolor="Gray">
            <td>	Trip Name
            </td>
            <td>	Location
            </td>
            <td>	Departure Date
            </td>
            <td>	Return Date
            </td>
            <td>	Price
            </td>
        </tr>
        <cfoutput query="TripResult">
            <tr>
                <td>	#tripName#
                </td>
                <td>	#tripLocation#
                </td>
                <td>	#departureDate#
                </td>
                <td>	#returnDate#
                </td>
                <td>	#price#
                </td>
            </tr>
        </cfoutput>
</table>
</body>
</html>
  4. Save the file.

Let Dreamweaver do it

As you have in previous exercises, you can let Dreamweaver generate the code to invoke the method.

To invoke the method using Dreamweaver:

  1. Click the Components tab.
  2. Click the + button next to cfdocs.getting_started.my_app.components.
  3. Click the + button next to gettrips.
  4. Select query getTripsFromForm() and drag it to the top of the triplisting.cfm file.
  5. Change the value of returnvariable to be the name of the query, TripResult, as follows:
    returnvariable="TripResult"
  6. Return to Step 3 in the To create the Trip Search Results page: section.

Reviewing the code

The following table describes the code used to build the tripLocation WHERE subclause:

Code

Explanation

<cfset WhereClause = " 0=0 ">

The cfset tag initializes the WhereClause variable to hold the WHERE clause to be constructed. The initial value is set to " 0=0 " so that the WHERE clause has at least one subclause in case the user enters no search criteria.

<cfif Form.tripLocationValue GT "">

The cfif tag tests to see if the user entered anything in the Value input field for tripLocation criterion.

SELECT tripName,  tripLocation,
departureDate, returnDate, price, tripID
FROM trips
WHERE #PreserveSingleQuotes(WhereClause)#

SQL query to execute. The PreserveSingleQuotes function ensures that quotation marks are passed to the database server as intended.

The preceding code only builds the tripLocation subclause. In the following exercise, you will add code for the other two columns that you can query, departureDate and price.


Exercise 4: Testing the Trip Search Results page

In this exercise, you will test the tripsearchresults.cfm page. First, you will test the Trip Search Results page by entering criteria on the Trip Search form and inspecting the results. Next, you will finish the code to construct the complete WHERE clause for all three columns that you can query from the Trip Search form.

To test the Trip Search Results page:

  1. View the tripsearchform.cfm page from the my_app directory in your browser and do the following:
    1. In the Trip Location drop-down list, select the Begins With option, and enter the value C in the text box.
    2. Click Search.

      The Trip Results page displays several entries, as follows:

      This image shows a picture of the trip search results.

    3. Notice in the Trip Results page that only one trip has a trip location of China.
    4. Click the Back button in your browser to return to the Trip Search page.
  2. In the Trip Location drop-down list of the Trip Search page, select the Is option, enter the value China, and then click Search.

    The Trip Search Results page displays only one entry for the trip to China in the HTML table.

  3. Verify that the other criteria (departure date and price) are not taken into consideration yet as follows:
    1. Click the Back button in the browser to return to the Trip Search page.
    2. In the Departure Date drop-down list box, select Before, enter 1/1/1900 as the date, and select Smaller Than 0 for the price.

      Either of these conditions would produce a results page with no rows.

    3. Click the Search button.

      The Trip Search Results page should be identical to the one in Step 2, because the code to build the WHERE clause in the Trip Search Results page does not include departure date and price.


Exercise 5: Enabling the departure and price criteria on the Trip Search form

In this exercise, you will modify the Trip Search Results page to add the criteria needed for the departure and price query.

To enable the departure and price criteria:

  1. Open the gettrips.cfc file.
  2. In the getTripsFromForm method, position the pointer before the cfquery code block.
  3. To build the departureDate WHERE subclause, enter or copy and paste the code in the following table immediately before the cfquery code block:

    For this database

    Enter this code

    (Windows users) Microsoft Access database file

    <!--- Build subclause for departureDate --->
<cfif Form.departureValue GT "">
<cfif Form.departureOperator EQ "EQUALS">
<cfset WhereClause = WhereClause & " and departureDate = " & CreateODBCDate(Form.departureValue)>
<cfelseif Form.departureOperator EQ "AFTER">
<cfset WhereClause = WhereClause & " and departureDate  > " & CreateODBCDate(Form.departureValue)>
<cfelseif Form.departureOperator EQ "BEFORE">
<cfset WhereClause = WhereClause & " and departureDate  <  " & CreateODBCDate(Form.departureValue)>
</cfif>
</cfif>

    (UNIX users) PointBase database file

    <!--- Build subclause for departureDate --->
<cfif Form.departureValue GT "">
<cfif Form.departureOperator EQ "EQUALS">
<cfset WhereClause = WhereClause & " and departureDate = Date '"  &  Form.departureValue  &  "'">
<cfelseif Form.departureOperator EQ "AFTER">
<cfset WhereClause = WhereClause & " and departureDate > Date '"  & Form.departureValue  &  "'">
<cfelseif Form.departureOperator EQ "BEFORE">
<cfset WhereClause = WhereClause & " and departureDate < Date '"  &  Form.departureValue  &  "'">
</cfif>
</cfif>
  4. To build the price WHERE subclause, enter the following code after the code you entered in the previous step.
    <!--- Build subclause for price--->
<cfif Form.priceValue GT "">
    <cfif Form.priceOperator EQ "EQUALS">
        <cfset WhereClause = WhereClause & " and price = " & form.priceValue>
    <cfelseif Form.priceOperator EQ "GREATER">
        <cfset WhereClause = WhereClause & " and price > " & form.priceValue>
    <cfelseif Form.priceOperator EQ "SMALLER">
        <cfset WhereClause = WhereClause & " and price < " & form.priceValue>
    </cfif>
</cfif>
  5. Save the file.


Exercise 6: Testing the revised Trip Search Results page

In this exercise, you will verify that the price and departureDate are now considered in the query.

To test the revised Trip Search Results page:

  1. Open the tripsearchform.cfm page in the my_app directory in your browser.
  2. In the Departure Date drop-down list box, select Before, enter 1/1/1900 as the date (specify 1900-1-1 on UNIX).
  3. Select Smaller Than, and enter 0 for the price.
  4. Click the Search button.

    Because the departure date is considered in the query, there are no rows returned.

    Note: If you planned to use many more fields as search criteria, the approach used to add departure date and price criteria to the Trip Search form is not the most elegant solution. A generic routine to handle WHERE clause string construction based on specific data types could reduce the code and be a more extensible solution than the one presented here. However, this more extensible approach is beyond the scope of this tutorial.


Summary

This lesson described how to build a search tool that dynamically builds a WHERE clause of the SQL SELECT statement using cfif and cfset tags. To ensure that the SQL statement remains intact, you used the PreserveSingleQuotes CFML function.


In the next lesson

In the next lesson, you will build the Trip Detail page, which will display detailed information about the currently selected trip.

Previous


Lesson 5: Creating a Trip Detail Page

In this lesson you will enhance the Compass Travel Trip Maintenance application. This lesson contains the following exercises:

Exercise 1: Creating a Trip Detail page

Exercise 2: Avoiding the potential security risk when using dynamic SQL

Exercise 3: Linking the Trip Search Results page with the Trip Detail page

Exercise 4: Enhancing the look of the Trip Search Results and Trip Detail pages

ColdFusion tags and functions introduced in this lesson

The following table describes the ColdFusion tags and functions that you use in this lesson to enhance the sample ColdFusion application:

Element

Type

Description

DollarFormat

Function

Returns a number as a String formatted with two decimal places, a thousands separator, and a dollar sign. If the specified number is negative, parentheses are used.

DateFormat

Function

Returns a formatted date-time value. If no mask is specified, the DateFormat function returns the date value in the dd/mmm/yy format. The DateFormat function supports dates that have the U.S. date format.

IsDefined

Function

Evaluates a String value to determine whether it represents an existing variable. Returns True if the variable is found, False if not found.

URLEncodedFormat

Function

Converts a text string into a String that you can safely use in a URL.

Next


Exercise 1: Creating a Trip Detail page

By design, the Trip Search Results page displays a subset of the information about a trip. To get additional information about any of the trips, the user should be able to click any row to display the detailed trip data.

In this exercise, you build a Trip Detail page to provide all the information about a particular trip that is stored in the Compass Travel trips database. The following figure shows an example of the Trip Detail page that you build:

This image shows a picture of the Trip Detail page.

After you complete the Trip Maintenance application in this tutorial, you will use this Trip Detail page in several ways:

  • You can call the Trip Detail page directly by typing in the address of the page with an ID. For example, to view trip information for Rio Cahabon Rafting with tripID 24, you open a browser and enter the following URL:
    http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24
  • You can navigate to the Trip Detail page by creating a hyperlink from the trip name on the Trip Search Results page. This will offer the user drill-down capability when searching for trips. You will link the Trip Search Results page and the Trip Detail page in one of the exercises in this lesson.
  • You can use browse buttons on the Trip Detail page to navigate the Trips table row-by-row. You will implement this navigational feature in Lesson 6: Creating a Main Application Page.


Building the Trip Detail page

To build the Trip Detail page, you do the following:

  • Create a CFC that queries the database.
  • Create the Trip Detail page, which invokes the CFC query and displays the results of the query.

To build the CFC query:

  1. Create a blank ColdFusion page.
  2. Save the file as tripdetail.cfm in the my_app directory.
  3. Perform the following steps, or do the steps in the Let Dreamweaver do it section.
    1. Enter the following code:
      <cfinvoke
  component="cfdocs.getting_started.my_app.components.displaytripdetail"
  method="getTripDetails"
  returnvariable="tripDetails">
</cfinvoke>
    2. Save the file.
    3. Create a file named displaytripdetail.cfc in the my_app/components directory.
    4. Enter the following code:
      <cfcomponent>
  <cffunction name="getTripDetails" access="public" returntype="query">
    <cfset var tripDetails = "" >
    <cfquery name="tripDetails" datasource="CompassTravel" maxrows=1>
        SELECT * FROM trips
            <cfif IsDefined("URL.ID")>
            WHERE tripID = #URL.ID#
            </cfif>
    </cfquery>
    <cfreturn tripDetails>
  </cffunction>
</cfcomponent>
    5. Save the file.

Let Dreamweaver do it

You can use the Dreamweaver Extensions to build the CFC query.

To create the CFC query in Dreamweaver:

  1. Open a new file in the my_app directory in Dreamweaver.
  2. Save the file as tripdetail.cfm.
  3. Click the Bindings tab.
  4. Click the + button.
  5. Select Recordset (Query).
  6. In the Name text box, enter tripDetails.
  7. In the Data sources list, select CompassTravel.
  8. Click the CFC Query button.
  9. In the Name text box, enter tripDetails.
  10. Click the Create New Component button.
  11. In the Name text box, enter displaytripdetail.
  12. In the Component Location text box, enter /components/.
  13. In the Recordset name text box, enter tripDetails.
  14. In the Function text box, enter getTripDetails.
  15. In the Data source list, select CompassTravel.
  16. In the Table list, select trips.
  17. Click OK.
  18. When asked whether to include dependent files, click Yes.
  19. Click OK.
  20. In the displaytripdetail.cfc file, modify the cfquery code block by adding the highlighted text:
    <cfquery name="tripDetails" datasource="CompassTravel" maxrows=1>
        SELECT * FROM trips
            <cfif IsDefined("URL.ID")>
            WHERE tripID = #URL.ID#
            </cfif>
    </cfquery>
  21. Save the file.

To display the results of the query on the Trip Detail page:

  1. Open the tripdetail.cfm file.
  2. Enter or copy and paste the following cfoutput code after the cfinvoke code block:
    <cfoutput query="TripDetails">
    <img src="images/tripmaintenance.gif">
<table>
    <tr>
        <td valign="top">	Trip Name:
        </td>
        <td>	#tripName#
        </td>
    </tr>
    <tr>
        <td valign="top">	Description:
        </td>
        <td>	#tripDescription#
        </td>
    </tr>
    <tr>
        <td valign="top">	Location:
        </td>
        <td>	#tripLocation#
        </td>
    </tr>
    <tr>
        <td valign="top">	Departure Date:
        </td>
        <td>	#departureDate#
        </td>
    </tr>
    <tr>
        <td valign="top">	Return Date:
        </td>
        <td>	#returnDate#
        </td>
    </tr>
    <tr>
        <td valign="top">	Price:
        </td>
        <td>	#price#
        </td>
        </tr>
    <tr>
        <td valign="top">	Base Cost:
        </td>
        <td>	#baseCost#
        </td>
    </tr>
    <tr>
        <td valign="top">	Trip Leader:
        </td>
        <td>	#tripLeader#
        </td>
    </tr>
    <tr>
        <td valign="top">	Number People:
        </td>
        <td>	#numberPeople#
        </td>
    </tr>
    <tr>
        <td valign="top">	Deposit Required:
        </td>
        <td>	#depositRequired#
        </td>
    </tr>
    <tr>
        <td valign="top">	Photo File:
        </td>
        <td>	#photo#
        </td>
    </tr>
</table>
</cfoutput>
  3. To provide a title that appears in the browser window, insert the following HTML code before the <cfoutput query = "TripQuery"> line:
    <html><head>
    <title> Trip Maintenance - View Record </title>
</head>
<body>
  4. Add the following code at the end of the file:
    </body>
</html>
  5. Save the file.

To view the Trip Detail page:

  1. Open a browser.
  2. Enter one of the following URLs, which use the tripID of 24, which specifies the Rio Cahabon Rafting trip:
    http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24

    Note: If you are using the built-in ColdFusion server, enter localhost:8500 instead of localhost.

    The following figure shows the expected result:

    This image shows a picture of Trip Maintenance page.

Reviewing the code

The following table describes the ColdFusion code that you use to build the Trip Detail page:

Code

Explanation

<cfcomponent>
  <cffunction name="getTripDetails" access="public" returntype="query">
...
<cfreturn tripDetails>
  </cffunction>
</cfcomponent>

The cfcomponent tag creates a CFC. The cffunction tag creates a method named getTripDetails in the CFC; the method returns the results of the query to the calling page.

<cfquery name="TripQuery"
dataSource="CompassTravel" maxRows=1>

The cfquery tag includes a maxRows attribute. This attribute limits the number of result rows brought back from the database. In the Trip Detail page, you want to show only a single row at a time; therefore, the maxRows attribute is set to 1.

<cfif IsDefined("URL.ID")>
    WHERE tripID = #URL.ID#
</cfif>

The URL.ID specifies a parameter that you can include in the URL that requests this page. If the ID parameter is passed within the URL, it is used in the SQL query to identify the tripID to SELECT. You can use the CFML IsDefined function to determine if a parameter is passed within the URL. You can also use IsDefined to determine if the user has entered data in form fields prior to the form post action.

As you did in this exercise, you can build comprehensive database query applications using CFML and dynamic SQL. To further test the new Trip Detail page that you created, you will link it to the search facility that you built in Lesson 4: Building Dynamic Queries. However, before you link that search facility, you must understand a potential security risk using dynamic SQL. The following exercise describes this risk and how to avoid it.


Exercise 2: Avoiding the potential security risk when using dynamic SQL

To reduce round trips between the client and the database server, many SQL database servers permit the client to submit multiple SQL statements in a single request, separated by a semicolon (;). For these database managements systems, the following SQL request is valid:

DELETE from trips where tripLocation = 'China'; SELECT tripName from trips

This request might be an efficient way to list the trips that remain after the database management system removes the China trip. Problems arise when the SQL statement is built dynamically.

In the Trip Maintenance application, when the client program or user passes an ID in the URL that calls the Trip Detail page, the page displays the relevant trip information. The following code builds the correct WHERE clause that supports this behavior:

<cfif IsDefined("URL.ID")>
    WHERE tripID = #URL.ID#
</cfif>

If a user called the Trip Detail page using the following statement:

http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24;DROP+trips

the SQL database management system executes the proper SQL SELECT statement, and then immediately erases the Trips table from the database.

Protecting your application

To ensure that your application is protected from such an attack, you can exploit the fact that the ID must be a numeric value. The CFML Val function returns the numeric value at the beginning of a string expression. You can use the Val function as follows:

<cfif IsDefined("URL.ID")>
    WHERE tripID = #Val(URL.ID)#
</cfif>

If nonnumeric data is passed within the URL ID field, the Val function returns 0, and the trip with ID 0 appears (if one exists). If the user enters the previously cited URL
(http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=24;DROP+trips), the application ignores the non-numeric values and displays the trip information of trip ID 24.

Warning: The exercises in this tutorial ignore the dynamic SQL risk from attack. To eliminate this risk, you should use ColdFusion functions (such as Val) to perform type checking on all URL parameters. For queries, you can also use the cfqueryparam tag, which is explained in CFML Reference.


Exercise 3: Linking the Trip Search Results page with the Trip Detail page

In this exercise, you will modify the Trip Search Results page to let the user view the details of any trip. To do this, you will convert each trip name entry in the results page to a link, which will display the trip’s detailed information in the detail page.

Use the following steps to link the Trip Search Results page (tripsearchresult.cfm) to the Trip Detail page (tripdetail.cfm).

To create links between the Trip Search Results page and the Trip Detail page:

  1. Open the tripsearchresult.cfm file from the my_app directory.
  2. Replace #tripName# in the cfoutput block with the following code:
    <a href="tripdetail.cfm?ID=#URLEncodedFormat(tripID)#">#tripName# </a>

    Note: The URLEncodedFormat is a ColdFusion function that returns a URL-encoded string. Spaces are replaced with %20, and nonalphanumeric characters with equivalent hexadecimal escape sequences. The function lets you pass arbitrary strings within a URL, because ColdFusion automatically decodes URL parameters that are passed to the page.

  3. Save the file.

To test the revised page:

  1. View the tripsearchform.cfm page from the my_app directory in your browser.
  2. In the Trip Location drop-down list, select Begins With, and enter the value C.
  3. Click Search.

    The Trip Search Results page displays a hyperlink for each trip name, as the following figure shows:

    This image shows a picture of the Trip Search Results page.

  4. To view the Trip Detail page for a trip, click the trip name.

You might notice that the dates and prices in both the Trip Detail and Trip Search Results pages are unformatted. You will improve the appearance of the application in Exercise 4: Enhancing the look of the Trip Search Results and Trip Detail pages.


Exercise 4: Enhancing the look of the Trip Search Results and Trip Detail pages

The Trip Maintenance application now provides a useful drill-down mechanism for locating trips. Although this application is functionally sound, its appearance could be improved, including formatting dates and dollar amounts, and making long lists easier to read.

Formatting dates and dollar amounts

ColdFusion provides several functions to improve application appearance. These include the DateFormat and DollarFormat functions that format dates and currency variables.

To format the dates and dollar amounts:

  1. To format the Trip Detail page dollar and date fields, open the tripdetail.cfm file in the my_app directory in your editor and make the following changes:

    Existing code

    Replacement code

    #departureDate#

    #DateFormat(departureDate, "mm/dd/yyyy")#

    #returnDate#

    #DateFormat(returnDate, "mm/dd/yyyy")#

    #price#

    #DollarFormat(price)#

    #baseCost#

    #DollarFormat(baseCost)#
  2. Save the file.
  3. To format the currency and date fields on the Trips Search Results page, open the tripsearchresult.cfm file in your editor and make the changes for departureDate, returnDate, and price indicated in the table.
  4. Save the file.

To view the application’s new appearance:

  1. View the tripsearchform.cfm page in the my_app directory in your browser.
  2. In the Trip Location drop-down list, select Begins With and enter the value C.
  3. Click Search.

    The Trip Search Results page appears:

    This image shows a picture of debugging information appended to the bottom of a form page.

  4. In the Trip Search Results page, click the link for Riding the Rockies.

    The properly formatted Trip Detail page appears:

    This image shows a picture of the Trip Detail page.


Summary

In this lesson, you transformed the search facility that you built in Lesson 4: Building Dynamic Queries into a drill-down facility for trip queries. You built a Trip Detail page to show more information about a particular trip. You also formatted the Trip Search Results and Trip Detail pages using the CFML DateFormat and DollarFormat functions. You linked the Trip Search Results page with the Trip Detail page.


In the next lesson

In the next lesson, you will add navigation and maintenance buttons on the main Trip Maintenance application page.
Previous


Lesson 6: Creating a Main Application Page

In this lesson you will enhance the Compass Travel Trip Maintenance application. So far, you created a very useful drill-down query facility. Compass Travel trip coordinators can produce lists required by management and easily locate and display information about any trip. There are several requirements that were identified in Lesson 1: Preparing to Build the Sample Application that you have not yet addressed:

  • The ability to browse through the Trips table.
  • The ability to add, delete, and edit trip information.

You will modify the Trip Detail page to accomplish this additional functionality. The Trip Detail page shows information about a single trip. You will convert the Trip Detail page into the main application page by adding the following functionality:

  • Navigation buttons to browse the database
  • Database maintenance buttons to edit, delete, and add new trips, as well as a button to search

This lesson contains the following exercises:

Exercise 1: Creating the main application page from the Trip Detail page

Exercise 2: Adding database maintenance buttons
Next


Exercise 1: Creating the main application page from the Trip Detail page

In this exercise, you convert the Trip Detail page into the main Trip Maintenance application page. The main application page includes additional buttons for navigating to other ColdFusion pages and browsing the trip database records.

This image shows a picture of the Trip Maintenance page with callouts showing maintenance buttons, trip detail, and navigation buttons.


Adding navigation buttons to browse the database

The drill-down search function developed in Lesson 5: Creating a Trip Detail Page is very useful when the user knows some search criteria to enter. Flipping back and forth between the results page and the detail page to navigate through a record set can be tedious. Moreover, on occasion the trip coordinator might want to browse the Trips database just to check for anomalies or to become familiar with its contents. In these cases, the trip coordinator does not know the criteria to search for in advance.

The following figure shows the navigation buttons. The label below each button does not appear in the application; it describes which row to display relative to the currently displayed row.

This image shows a picture of the Trip Detail page navigation buttons.

To add navigation buttons to the Trip Detail page:

  1. Open the tripdetail.cfm file in the my_app directory.
  2. Insert the following code between the </table> and </cfoutput> tags:
    <form action="navigationaction.cfm" method="post">
    <input type="hidden" name="RecordID" value="#tripID#">
    <!--- graphical navigation buttons --->
    <input type="image" name="btnFirst" src="images/first.gif">
    <input type="image" name="btnPrev" src="images/prev.gif">
    <input type="image" name="btnNext" src="images/next.gif">
    <input type="image" name="btnLast" src="images/last.gif">
</form>

    Note: The current trip record ID (tripID) is in a hidden field in the form code. This field provides the action page with current record ID that it must have in order to build the query to access the appropriate record in the Trips database table.

  3. Save the file.

To test the updated application:

  1. View the updated tripdetail.cfm page in a browser.

    The Trip Search Results page appears:

    This image shows a picture of the Trip Search Results page.

  2. Test the buttons by clicking any navigation button.

    An error occurs because the navigation action page (navigationaction.cfm) does not exist. The navigation action page processes the navigation button requests. You will build the navigation action page in Lesson 7: Validating Data to Enforce Business Rules.

Reviewing the code

The following table describes the navigation code for the Trip Detail page:

Code

Explanation

<form action="navigationaction.cfm" method="post">

Form tag that identifies the navigationaction.cfm file to handle record navigation.

<INPUT type="hidden" name="RecordID" value="#tripID#">

Hidden RecordID field with the value of the current tripID.

<input type="image" name="btnFirst" src="images/first.gif">
<input type="image" name="btnPrev" src="images/prev.gif">
<input type="image" name="btnNext" src="images/next.gif">
<input type="image" name="btnLast" src="images/last.gif">

Navigation buttons that are image type HTML input tags.


Exercise 2: Adding database maintenance buttons

The search and sequential navigation capabilities are features for locating Compass Travel trips. After locating a trip, the trip coordinator must be able to modify or delete it. Additionally, when viewing the detail for a trip, the trip coordinator must be allowed to add a new trip or use the search facility. To enable trip coordinators to do this, you add the following buttons to the Trip Detail page:

This image shows a picture of the maintenance buttons.

As described in Exercise 1: Creating the main application page from the Trip Detail page, it is important to pass the current record ID (tripID) to the action page to build the proper SQL statement to process the navigation button requests. It is also important to pass the current record ID to the Maintenance Action page. Therefore, you use an HTML input tag to hide the current recordID and post it to the maintenanceaction.cfm page.

To add maintenance buttons:

  1. Open the tripdetail.cfm file from the my_app subdirectory.
  2. Enter the following code immediately after the <cfoutput query="TripQuery"> tag:
    <form action="maintenanceaction.cfm" method="post">
    <input type="hidden" name="RecordID" value="#tripID#">
    <input type="submit" name="btnAdd" value="   Add    ">
    <input type="submit" name="btnEdit" value="  Edit  ">
    <input type="submit" name="btnDelete" value="Delete">
    <input type="submit" name="btnSearch" value="Search">
</form>

    Note: The current trip record ID (tripID) is in a hidden field in the form code. This field provides the action page with current record ID that it must have in order to build the query to access the appropriate record in the Trips database table.

  3. Save the file.

To test the updated application:

  1. Open your browser.
  2. Enter the following URL to view the updated tripdetail.cfm page
    http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=8

    Note: If you are using the built-in ColdFusion server, enter localhost:8500 instead of localhost.

    The page appears as follows:

    This image shows a picture of the Trip Maintenance page with maintenance buttons.

  3. Click Search or Delete to test the database maintenance buttons.

    An error occurs because the Maintenance Action page does not exist. The Maintenance Action page is required to process the maintenance button requests. You will develop this page in Lesson 7: Validating Data to Enforce Business Rules.


Summary

In this lesson, you added trip maintenance and navigation buttons, which converted the Trip Detail page into the main Trip Maintenance application page.


In the next lesson

In Lesson 7: Validating Data to Enforce Business Rules, you will build the action pages required to implement the navigation and maintenance buttons on the main Trip Maintenance application page.
Previous


Lesson 7: Validating Data to Enforce Business Rules

In this lesson, you will create a page for the trip coordinator to add new trip offerings and update existing trips. In addition, you will add logic to validate that data entered so that it complies with Compass Travel business rules.

This lesson contains the following exercises:

Exercise 1: Using an HTML form to collect data

Exercise 2: Creating a simple action page

Exercise 3: About data validation

Exercise 4: Providing server-side validation

Exercise 5: Validating data on the client using ColdFusion form tags

Exercise 6: Dynamically populating the list of event types

Exercise 7: Validating the existence of the trip photo file

ColdFusion tags and functions introduced in this lesson

The following table describes the ColdFusion tags and functions that you use in this lesson to enhance the ColdFusion application:

Element

Type

Description

cfform

Tag

Builds a form with CFML custom control tags that provide more functionality than standard HTML form input elements.

cfinput

Tag

Use inside the cfform tag to place radio buttons, check boxes, or text boxes. Provides input validation for the specified control type.

cfselect

Tag

Use inside the cfform tag. Lets you construct a drop-down list form control. You can populate the drop-down list from a query, or use the HTML option tag. You also use option elements to populate lists. The syntax for the option tag is the same as for its HTML counterpart.

FileExists

Function

Returns True if the file specified in the argument exists, False if it doesn’t exist.
Next


Exercise 1: Using an HTML form to collect data

In this exercise, you develop the Trip Edit page, which provides a data entry form that is used to add new trips and edit existing trips. You validate the data entered against Compass Travel business rules. The fields required to capture trip information are the same as those on the Trip Detail page that you used to display trip information in Lesson 6: Creating a Main Application Page. The following figure shows the Trip Edit page:

Image shows picture Trip edit data collection page.

The page appears when the user clicks the Add or Edit button on the main Trip Maintenance application page (tripdetail.cfm).

To create the Trip Edit data collection form:

  1. Create a blank file.
  2. Enter or copy and paste the following code into the file:
    <html>
<head><title>Compass Travel Trip Maintenance</title></head>
<body>
    <form action="tripeditaction.cfm" method="post">
        <!--- Field: Trip Maintenance Image --->
    <IMG src="images/tripmaintenance.gif">
    <P>
    <table>
        <!--- Field: tripName --->
        <TR>
            <TD valign="top"> Trip Name </TD>
            <TD><INPUT type="text" name=tripName size="50"></TD>
        </TR>
            <!--- Field: eventType --->
        <tr>
            <td valign="top">Type of Event</td>
            <td><select size="1" name="eventType">
                <option value="1" selected>Surfing</option>
                <option value="2">Mountain Climbing</option>
                <option value="3">Mountain Biking</option>
                </select>
            </td>
        </tr>
        <!--- Field: tripDescription --->
        <TR>
            <TD valign="top"> Trip Description </TD>
            <TD>
                <textarea cols="50" rows="5" name="tripDescription"></textarea>
            </TD>
        </TR>
        <!--- Field: tripLocation --->
        <TR>
            <TD valign="top">Trip Location</TD>
            <TD><INPUT name=tripLocation size=50></TD>
        </TR>
        <!--- Field: departureDate --->
        <TR>
            <TD valign="top"> Departure Date</TD>
            <TD><INPUT name=departureDate size=10></TD>
        </TR>
        <!--- Field: returnDate --->
        <TR>
            <TD valign="top"> Return Date</TD>
            <TD><INPUT name=returnDate size=10></TD>
        </TR>
        <!--- Field: numberPeople --->
        <TR>
            <TD valign="top">Number of People</TD>
            <TD><INPUT size=6 name=numberPeople></TD>
        </TR>
        <!--- Field: Price --->
        <TR>
            <TD valign="top">Price</TD>
            <TD><INPUT size=10 name=price></TD>
        </TR>
        <!--- Field: baseCost --->
        <TR>
            <TD valign="top"> Base Cost </TD>
            <TD><INPUT size=10 name=baseCost></TD>
        </TR>
        <!--- Field: depositRequired --->
        <TR>
            <TD valign="top"> Deposit Required </TD>
            <TD><input type="checkbox" name="depositRequired" value="Yes"></TD>
        </TR>
        <!--- Field: tripLeader --->
        <TR>
            <TD valign="top">Trip Leader</TD>
            <TD><INPUT maxLength=50 size=50 name=tripLeader></TD>
        </TR>
        <!--- Field: photo --->
        <TR>
            <TD valign="top">Photo File Name</TD>
            <TD><INPUT maxLength=50 size=50 name=photo></TD>
        </TR>
    </table>
    <p>
    <input type="submit" value="Save">
    <input type="submit" value="Cancel" name="btnCancel">
    </p>
    </form>
</body>
</html>
  3. Save the file as tripedit.cfm in the my_app directory.

Reviewing the code

The following table explains the use of some of the HTML tags in the Trip Edit page. For more information on HTML, consult any HTML primer.

Tag

Description

Form

You create a data entry form by using the form tag. The form tag takes two tag attributes; for example:

<form action="tripeditaction.cfm" Method= "Post">

Here, the action attribute specifies the name of the ColdFusion file that the web server will navigate to in response to the form’s submission. The method attribute specifies how data is returned to the web server. Submit all ColdFusion forms using the Post method attribute.

Table

You can format a data entry form and display its controls neatly, by using the table tag, table; table row tag, tr; and the table data tag, td.

Form Controls

The form requires controls to collect and submit user input. There are a variety of types of form controls that you can use. For this lesson, you will use the following controls:

  • <input> Accepts text answers, such as Trip Name and Trip Price.
  • <input type=checkbox> Asks yes or no questions, such as Deposit Required?
  • <select>,<option> Provides user with a list of possible answers, such as the event type (Mountain Biking, Surfing, and so on).
  • <textarea> Gathers user input on multiple lines, such as for the Trip Description.
  • <input type=submit> Posts the information collected to the server.

To test the Trip Edit page:

  1. View the tripedit.cfm page in a browser.
  2. Enter a trip name in the Trip Name field.
  3. Click Save.

    An error occurs.

If you view the form source (tripedit.cfm) in an editor, you can see that the <form> tag has an action attribute. This attribute indicates the page that receives the form values posted by the tripedit.cfm page. Because you have not yet created the tripeditaction.cfm page, ColdFusion MX sends an error.

At this point, this form does not store any information in the database and does not enforce any business rules of Compass Travel. In the next exercise, you develop the action page to enforce the business rules.


Exercise 2: Creating a simple action page

In this exercise, you develop an action page that you will eventually use to insert or update trip data passed from the Trip Edit page into the trips table of the Compass Travel database.

To build the Trip Edit action page:

  1. Create a blank file.
  2. Enter or copy and paste the following code into the file:
    <html>
    <head>
        <title>Trip Maintenance Confirmation</title>
    </head>
    <body>
            <h1>Trip Added</h1>
            <!--- Database insert logic goes here. --->
            <cfoutput>
                You have added #Form.TripName# to the trips database.
            </cfoutput>
    </body>
</html>
  3. Save the page as tripeditaction.cfm in the my_app directory.

To test the trip edit page:

  1. Open the tripedit.cfm page in the my_app directory in a browser.
  2. In the Trip Name field, enter 12345.
  3. Click Save.

    The message "You have added 12345 to the trips database." appears. The tripeditaction.cfm page does not actually update the database yet; it simply displays a message saying that you added the trip to the database. Before you add the code to allow updates to the database, you must add the logic to validate the data entered in the form.

Reviewing the code

The following table describes the code that you use to verify whether a file exists:

Code

Explanation

    <h1>Trip Added</h1>
    <!--- Database insert logic goes here. --->
    <cfoutput>You have added #Form.TripName# to the trips database.
    </cfoutput>

Displays the heading "Trip Added." Displays the message "You have added TripName to the trips database," where TripName is the trip name you entered in the form’s Trip Name field.


Exercise 3: About data validation

To ensure that the data entered in the trip edit form is valid, Compass Travel has identified a set of business rules for capturing and editing trip information. A fundamental concern is ensuring that the captured data is suitable for the column definitions in the Trips table. This type of validation on a single field is often referred to as a single-field edit.

Compass Travel has other operating policies that involve evaluating the values from more than one field. These validations, referred to as cross-field edits, are usually more difficult to program. To ensure that new trips are uniformly captured, Compass Travel has published cross-field validations and single-field edits in its Compass Travel business rules.

The following table lists the Compass Travel business rules for capturing and editing trip information. This table identifies which rules require single-field or cross-field editing.

Compass Travel new trip policy |  | Edit type
1 | All trips must be named. | Single-field
2 | All trips must be accompanied by a full description. | Single-field
3 | Each trip must be categorized by event type. Only valid event types (1-surfing, 2-mountain climbing, and so on) are permissible. | Single-field
4 | Trip locations are required. | Single-field
5 | The maximum number of people permitted on the trip must be specified. | Single-field
6 | The trip departure and return dates must be specified for each trip. All trip dates must be valid future dates. Departure date must precede return date. | Single-field Cross-field
7 | The trip’s price and base cost are required. Both values are positive numeric values. The trip price must have at least a 20% markup over base cost. | Cross-field
8 | Any trip priced over $750 requires a deposit. | Cross-field
9 | A trip leader must be identified. | Single-field
10 | A photo must accompany all new trips. The photo image file must reside in the images directory of the Compass Travel website. | Single-field

ColdFusion provides numerous ways to validate data. For more information, see Validating Data in ColdFusion MX Developer’s Guide. In this lesson, you use special tags to simplify the process of enforcing business rules. Using ColdFusion, it is possible to enforce business rules in several places. For example, you can enforce some validation edits on the client. You can enforce other validation edits on the server after the data entry form is submitted. You will explore these options in the following exercises.


Exercise 4: Providing server-side validation

In this exercise, you will learn about the following tasks:

  • Creating a local variable to indicate whether data entered in the form conforms to the Compass Travel business rules
  • Ensuring that a value was entered
  • Evaluating check box and radio button variables
  • Adding validation for all Compass Travel business rules


Creating a local variable

The purpose of the tripeditaction.cfm action page is to update the Compass Travel database, so it is important to make certain that any values entered conform to all the business rules before modifying the database. Failure of any one of the rules prevents modification of the database.

One approach to ensuring that the action page considers each business rule is to create a local variable with a cfset tag within the action page that tests whether any of the business rules failed.

The cfset tag lets you manipulate the value of a variable. For example, the following pseudocode initializes a variable to a specific value and checks the value using the cfif statement:

<cfset isOk = "Yes">
if rule 1 fails then
<cfset isOK = "No"
...
if Rule n fails then
<cfset isOk = "No">
...
<cfif isOk = "Yes">
    update the database
</cfif>

In this example, the cfset tag initializes the local variable isOk to Yes. If any rule fails, the variable isOK is set to No. The code then tests if isOk equals Yes, before executing the SQL insert logic.

To create the local variable:

  1. Open the tripeditaction.cfm file in an editor.
  2. Add the following code at the top of the file:
    <cfset isOk = "Yes">
  3. Modify the file by adding the following highlighted code:
    <cfif isOk EQ "Yes">
    <h1>Trip Added</h1>
    <!--- Database insert logic goes here. --->
    <cfoutput>
        You have added #Form.TripName# to the trips database.
    </cfoutput>
</cfif>
  4. Save the file.

Because you did not yet add any logic to test whether any values entered in the form are valid, the page works precisely as before, displaying a message that indicates the database was updated, without actually performing the update.

For more information about using the cfset and cfif tags, see ColdFusion MX Developer’s Guide or CFML Reference.


Ensuring that a value was entered

The first approach that you take to enforce Compass Travel business rules is to enhance the action page to validate the data collected on the data entry form. The action page receives a form variable for every field on the form that contains a value. You use the cfif tag to test the values of these fields to ensure that they adhere to Compass Travel business rules.

You can use the cfif tag to create conditions that evaluate to either True or False. To use the cfif tag to test whether a trip name was entered (business rule 1) on the Trip Edit form, you add the following cfif statement:

<cfif Form.tripName EQ "">
    <cfoutput> Trip Name cannot be blank. </cfoutput>
</cfif>

In this example, the cfif statement tests to see if the value of the form variable tripName is blank. If the trip name condition evaluates to True, ColdFusion sends the message "Trip name cannot be blank" to the browser.

Note: The keyword EQ is an operator that tests for equality. For more information about the cfif tag and its operators, see ColdFusion MX Developer’s Guide.

To ensure that a Trip Name was entered:

  1. Open the tripeditaction.cfm file.
  2. Enter the following code after the line <cfset isOk = "Yes">.
    <!--- Trip Name is required. --->
<cfif Form.tripName EQ "">
    <CFSET IsOk = "No">
    <cfoutput>Trip name cannot be blank.<br></cfoutput>
</cfif>
  3. Save the file.

To test the data validation:

  1. Open the tripedit.cfm page in a browser.
  2. Verify that there is no value in the Trip Name field.
  3. Click Save.

    The error message "Trip name cannot be blank" appears.

Evaluating check box and radio button variables

Business rule 8 in the Compass Travel new trip policy requires you to test the value of the depositRequired check box form variable. Check box and radio button variables are only passed to the action page when the user selects these options on the form. An error occurs if the action page tries to use a variable that was not passed.

To ensure that an error does not occur, you use the IsDefined function in a cfif statement to determine whether the user selected the Deposit Required check box on the form.

The cfif statement and the IsDefined function evaluate the value of the form variable depositRequired to determine if a value exists. The statement not IsDefined returns True if the specified variable is not found, and the cfset statement sets the form variable to No. A value of No indicates that a deposit is not required; a value of Yes indicates that a deposit is required.

To set the value of the Deposit Required check box:

  1. Open the tripeditaction.cfm file.
  2. Enter the following code after the first cfif code block.
    <cfif not IsDefined("Form.depositRequired")>
    <cfset form.depositRequired = "No">
</cfif>
  3. Save the file.

Adding validation for all Compass Travel business rules

You add validation for all the form variables.

To validate all the data passed:

  1. Open the tripeditaction.cfm file in the my_app directory.
  2. Enter the validation code blocks in the following table after the cfif code blocks that you already entered.
  3. Save the file.

The following table lists the Compass Travel business rules and shows the corresponding code that ensures that the data entered in the form follows the business rules.

Note: You have already entered validation code for business rule 1. Validation code for business rule 10 is described in more detail later in this lesson.

Rule

Description

Validation code

2

All trips must be accompanied by a full description.

<!--- Trip description is required. --->
<cfif Form.tripDescription EQ "">
    <cfset IsOk = "No">
    <cfoutput>
        Trip description cannot be blank.
    </cfoutput>
</cfif>

3

Each trip must be categorized by event type. Only valid event types (1-surfing, 2-mountain climbing, and so on) are permissible.

Because event type 1 (surfing) is selected by default, there is always a value for event type.

4

Trip locations are required.

<!--- Trip location is required. --->
<cfif Form.tripLocation EQ "">
    <cfset IsOk = "No">
    <cfoutput>
        Trip location cannot be blank.
    </cfoutput>
</cfif>

5

The maximum number of people permitted on the trip must be specified.

<!--- Number of people is required and must be numeric. --->
<cfif Form.numberPeople EQ "" or
    IsNumeric(Form.numberPeople) EQ False>
    <cfset IsOk = "No">
    <cfoutput>
        The number of people must be a number and
        cannot be blank.
    </cfoutput>
</cfif>

6

The trip departure and return dates must be specified for each trip.

All trip dates must be valid future dates. Departure date must precede return date.

<cfif form.departureDate GT form.returnDate>
    <cfset isOk = "No">
    <cfoutput>
        Departure date cannot precede return date.
        Please re-enter.
    </cfoutput>
</cfif>

7

The trip’s price and base cost are required. Both values are positive numeric values. The trip price must have at least a 20% markup over base cost.

<!--- Base Cost is required and must be numeric. --->
<cfif Form.baseCost EQ "" or
    IsNumeric(Form.baseCost) EQ False>
    <cfset IsOk = "No">
    <cfoutput>
        Base Cost must be a number and cannot be
        blank.
    </cfoutput>
    <cfelse>
    <!--- Price must be 20% greater than Base Cost. --->
    <cfif Form.basecost * 1.2 GT  #Form.price#>
        <cfset IsOk = "No">
        <cfoutput>
            Price must be marked up at least 20%
            above cost.
        </cfoutput>
    </cfif>
</cfif>

8

Any trip priced over $750 requires a deposit.

<!--- Price is required and must be numeric. --->
<cfif Form.price EQ "" or
    IsNumeric(Form.baseCost) EQ False>
    <cfset IsOk = "No">
    <cfoutput>
        Price must be a number and cannot be blank.
    </cfoutput>
    <cfelse>
    <!--- A deposit is required when the price is > $750. --->
        <cfif Form.price GT 750 AND
            Form.depositRequired EQ "No">
            <cfset IsOk = "No">
            <cfoutput>
                Deposit is required for
                trips priced over $750.
            </cfoutput>
    </cfif>
</cfif>

9

A trip leader must be identified.

<!--- Trip Leader is required. --->
<cfif Form.tripLeader EQ "">
    <cfset IsOk = "No">
    <cfoutput>
        A trip leader must be specified.
    </cfoutput>
</cfif>

10

A photo must accompany all new trips.

<!--- Photo filename is required. --->
<cfif Form.photo EQ "">
    <cfset IsOk = "No">
    <cfoutput>
        Photo filename must be specified.</cfoutput>
</cfif>

Note: The code for business rules 7 and 8 uses ColdFusion cfif and cfelse conditional processing tags. The code inside the cfif tags only executes when the condition evaluates to True. To perform other actions when the condition evaluates to False, the cfelse tag is used. For more information about using conditional processing tags, see ColdFusion MX Developer’s Guide.

To test the validation code:

  1. View the tripedit.cfm page in the browser.
  2. In the form, enter 500 in both the Price and Base Cost fields.
  3. Click the Save button.

    The trip price error message displays: "Price must be marked up at least 20% above cost."

  4. Click the browser Back button to return to the tripedit.cfm page.
  5. To avoid the error, enter 800 in the Price field, and click Save.
  6. Test various combinations to ensure that all the Compass Travel business rules are enforced by filling out the fields on the form and clicking Save.

    Testing recommendations:

    • Leave out required fields, such as trip name or location.
    • Enter a nonnumeric value in Number of People, such as one.
    • Leave the entire form blank and click Save. The following messages appear:

      Trip name cannot be blank. A trip leader must be specified. Photo filename must be specified. The number of people must be a number and cannot be blank. Trip location cannot be blank. Base cost must be a number and cannot be blank. Price must be a number and cannot be blank.


Exercise 5: Validating data on the client using ColdFusion form tags

In this exercise, you will compare server-side and client-side validation. You then modify the testedit.cfm page to use client-side scripting.

Comparing server-side and client-side validation

Validating data on the server-side has two drawbacks. First, the action page is used for validation, so the form page is not in the browser context when the error is trapped. The user, therefore, will not get immediate feedback from the page where the data was entered. Second, because data capture occurs on the client and validation occurs on the server, the number of round-trips to the server is increased. This can cause increased traffic on the network and the server. If the data is validated on the client, only valid data is posted to the server and traffic is reduced.

An alternative approach to server-side editing is to use client-side scripting. Client-side scripting lets you validate the form data entered on the client prior to posting it to the server. CFML provides alternative versions of standard HTML form tags, which provide the advantages of client-side data validation. These data input tags include cfinput text, cfinput radio, cfinput checkbox, cfselect, and others. For more information, see Validating Data in ColdFusion MX Developer’s Guide.

ColdFusion form tags include the following attributes:

Attribute | Description
validate | The data type that the field tag validates against. Values include: integer, date, time, telephone, zipcode.
message | The error message that appears if validation fails.
range | The range of permissible values for this tag.
required | An indicator of whether data is required for the corresponding tag.

To use the improved form tags, you must replace the HTML form tag with the cfform tag. The following code snippets show the use of the improved ColdFusion form tags. The first code snippet shows how the duration field is validated on the server. The second code snippet shows how ColdFusion form tags simplify field validation on the client.

Server-side validation approach (no cfform tag)

The following code is on the server (tripeditaction.cfm page):

<!--- Number of people is required and must be numeric. --->
<cfif Form.numberPeople EQ "" or IsNumeric(Form.numberPeople) EQ False>
    <CFSET IsOk = "No">
    <cfoutput>The number of people must be a number and cannot be blank.
    </cfoutput>
</cfif>

Code

Explanation

<cfif Form.numberPeople EQ "" or
IsNumeric(Form.numberPeople) EQ False>

The cfif tag evaluates the value of the form variable numberPeople to determine if the user entered a value. The IsNumeric function checks whether the value entered on the form was a numeric value.

Client-side validation approach using a cfform tag

The following code is on the client (tripedit.cfm page):

<cfinput name="duration" message="Duration must be a number and cannot be blank."
validate="integer" required="Yes" size="3" maxlength="3">

Code

Explanation

<cfinput name="duration"
message="Duration must be a number and cannot be blank." validate="integer"
required="Yes" size="3" maxlength="3">

Use the cfinput tag to create the duration input entry field within a cfform tag. The validate attribute defines the field as an integer. The required attribute indicates that the field must have an entry. If the data is not entered or data entered is not an integer, the message attribute specifies that the message, "Duration must be...." appears.

Modifying the Trip Edit page to use ColdFusion form tags

In this exercise, you use the ColdFusion form tags to move the validation of many business rules from the server to the client. To do this, you change the HTML form tags in the tripedit.cfm page to ColdFusion form tags that validate these fields on the client side. Next, you remove the unneeded server-side single-field validation code from the tripeditaction.cfm page. Finally, you test the form to ensure that the client-side validation is working correctly.

To use the ColdFusion form tags on the Trip Edit page:

  1. Open the tripedit.cfm file in the my_app directory in your editor.
  2. Locate and change the <form> and </form> tags to <cfform> and </cfform> tags, respectively.
  3. Change the <input> tags to <cfinput> tags, <select> tags to <cfselect> tags, and <textarea> tags to <cftextarea> tags.

    Note: The input type for the submit button must remain a standard input rather than cfinput.

  4. For each ColdFusion form tag (cfinput and cfselect), assign the following appropriate values:

    Attribute value

    Description

    required

    Use this attribute for fields that must be filled out or selected.

    validate

    Use this attribute for fields that require a specific data type for validation. Values include: integer, date, time, telephone, and zip code.

    message

    Use this attribute for fields that require an error message to appear if validation fails. The message reflects the text that describes the business rule.

    The following table contains the revised code blocks:

    Rule

    Description

    Validation code

    1

    All trips must be named.

    <cfinput name= "tripName"
    maxlength = "50" size = "50"
    required = "Yes"
    message = "Trip name must not be blank">

    2

    All trips must be accompanied by a full description.

    <cftextarea name="tripDescription"
    required="Yes"
    message="Trip description must not be blank.">
</cftextarea>

    3

    Each trip must be categorized by event type. Only valid event types (1-surfing, 2-mountain climbing, and so on) are permissible.

    <cfselect size="1" name="eventType"
    required="Yes"
    message="Type of event must be selected.">
        <option value="1" selected>Surfing</option>
        <option value="2">Mountain Climbing</option>
        <option value="3">Mountain Biking</option>
</cfselect>

    4

    Trip locations are required.

    <cfinput size="50" name="tripLocation"
    required="Yes"
    message="Trip location must not be blank.">

    5

    The maximum number of people permitted on the trip must be specified.

    <cfinput name="numberPeople"
    size="6"
    required="Yes"
    validate="integer"
    message="The number of people field must be
    a number and cannot be blank.">

    6

    The trip departure and return dates must be specified for each trip.

    All trip dates must be valid future dates. Departure date must precede return date.

    <cfinput name="departureDate"
    size="10"
    required="Yes"
    validate="date"
    message="Departure date must be a valid date.">

<cfinput name="returnDate"
    size="10"
    required="Yes"
    validate="date"
    message="Return date must be a valid date.">

    7

    The trip’s price and base cost are required. Both values are positive numeric values. The trip price must have at least a 20% markup over base cost.

    <cfinput name="price"
    size="10"
    required="Yes"
    validate="integer"
    message="Price is required and must be numeric.">

<cfinput name="baseCost"
    size="10"
    required="Yes"
    validate="integer"
    message="Base cost is required and must be numeric.">

    8

    Any trip priced over $750 requires a deposit.

    <cfinput name="depositRequired"
    type="checkbox"
    value="Yes" >

    9

    A trip leader must be identified.

    <cfinput name="tripLeader"
    maxlength="50" size="50"
    required="Yes"
    message="A trip leader must be specified.">

    10

    A photo must accompany all new trips.

    <cfinput name="photo"
    maxlength="50" size="50"
    required="Yes"
    message="Valid photo file name must be specified.">

    Tip: For additional help, review the completed code in the ttripedit_lesson7_ex5.cfm file within the solutions directory. For more details about using ColdFusion form tags and their attributes, see ColdFusion MX Developer’s Guide.

    Note: The client-side validation code that you added to the tripedit.cfm page does not validate the cross-field rules.

  5. Open the tripeditaction.cfm file in the my_app directory and delete the code for the following single-field validation rules:
    • Trip name is required.
    • Trip description is required.
    • Trip leader is required.
    • Photo filename is required.
    • Number of people is required and must be numeric.
    • Trip location is required.
    • Base cost is required and must be numeric.
    • Price is required and must be numeric.
  6. Save the file.

    The modified tripeditaction.cfm page appears as follows:

    <cfset isOk = "Yes">
<cfif not isdefined("Form.depositRequired")>
   <cfset form.depositRequired = "No">
</cfif>
<cfif Form.price GT 750 AND Form.depositRequired EQ "No">
    <cfset IsOk = "No">
    <cfoutput>Deposit is required for trips priced over $750.</cfoutput>
</cfif>
<cfif Form.basecost * 1.2 GT #Form.price#>
    <cfset IsOk = "No">
    <cfoutput>Price must be marked up at least 20% above cost.</cfoutput>
</cfif>
<cfif form.departureDate GT form.returnDate>
    <cfset isOk = "No">
    <cfoutput>Return date cannot precede departure date. Please re-enter.</cfoutput>
</cfif><html>
<head>
<title>Trip Maintenance Confirmation</title>
</head>

<body>

<cfif isOk EQ "Yes">
    <h1>Trip Added</h1>
    <cfoutput>You have added #Form.TripName# to the trips database.
    </cfoutput>
</cfif>
</body>
</html>

To test the modified code:

  1. View the tripedit.cfm page in a browser.
  2. Test the client- and server-side field validations by filling out the fields on the form and clicking Save.

    Testing recommendations:

    • Omit required fields such as trip name or location.
    • Make the departure date an invalid date, such as 12/32/2002.
    • Enter a nonnumeric value in Number of People, such as one.


Exercise 6: Dynamically populating the list of event types

Currently, the event types in the tripedit.cfm file are hard-coded. In the preceding exercises, each option tag in the event type contained a value attribute and option text, such as Surfing. These values come from the eventtypes table; they do not have to be hard-coded. The event type in the Trips table is an identifier that is used as a foreign key to the eventtypes table, which holds the actual event names. The eventtypes table column eventTypeID is used for the value attribute and the eventType for the literal value that appears in the select box. To retrieve the data from this table, you must include the following cfquery:

<cfquery name="GetEvents" datasource="CompassTravel">
    SELECT eventType, eventTypeID
    FROM eventtypes
</cfquery>

To exploit the query in the HTML option tags, you can replace the HTML select tag with a cfselect tag.

The cfselect tag is an improved version of the HTML select tag. Like other ColdFusion form tags, the cfselect tag provides the required and message attributes that validate the data entered. Using the cfselect tag and the preceding cfquery, you can implement the eventType field data entry as follows.

To display a list of event types from the eventtypes table and add validation:

  1. View the tripedit.cfm page in a browser. Select the event types drop-down list. Notice that only three event types appear in the list.
  2. Open the tripedit.cfm file in the my_app directory.
  3. Add the following code before the <html> tag:
    <cfquery name="GetEvents" datasource="CompassTravel">
    SELECT eventType, eventTypeID
    FROM eventtypes
</cfquery>

    Note: In previous exercises, you learned to write structured reusable code by placing queries in ColdFusion components. Although this practice is advisable when creating ColdFusion applications, you put the query in the tripedit.cfm file for simplicity.

  4. Replace the following eventtypes code lines:
    <cfselect size="1" name="eventType" required="Yes"
    message="Type of event must be selected.">
    <option value="1" selected>Surfing</option>
    <option value="2">Mountain Climbing</option>
    <option value="3">Mountain Biking</option>
</cfselect>

    with these lines:

    <cfselect size="1" name="eventType" required="Yes"
    message="Type of event must be selected.">
    <cfoutput query="GetEvents">
        <option value="#GetEvents.eventTypeID#">
            #GetEvents.eventType#
        </option>
    </cfoutput>
</cfselect>
  5. Save the file.

To test the modified code:

  1. View the tripedit.cfm page in a browser.
  2. Select the event types drop-down list. Notice that all seven event types appear in the list.


Exercise 7: Validating the existence of the trip photo file

At this point, you have a more efficient application. The client is handling much of the validation of the Compass Travel new trip business rules. Except for the trip photo file, the server receives only valid data.

The trip photo file business rule does not fit nicely into this design, however. This business rule has two parts:

  • A photo filename must accompany all new trips.
  • The photo image file must reside in the images directory of the Compass Travel website.

You used the required attribute for the photo cfinput tag to ensure that a filename is entered. Now you must ensure that the file exists in the right directory so that the application can display it to the user.

Because browser clients are prohibited from doing standard file input and output (I/O) on the web server, the Trip Maintenance application uses server-side validation to ensure the existence of the photo file. You add the business rule for the photo file to the tripeditaction.cfm page.

To verify that a file exists, ColdFusion provides a FileExists function. This function has the following syntax:

FileExists(absolute_path)

This function returns Yes if the file specified in the argument does exist; otherwise, it returns No.

Note: The trip photo images are stored in the following path relative to your web root directory: \cfdocs\getting_ started\photos. Therefore, if your web root is C:\inetpub\wwwroot, the photos are stored in the C:\inetpub\wwwroot\cfdocs\getting_ started\photos directory.

For more information about the FileExists function, see CFML Reference.

To verify that the photo filename exists:

  1. Open the tripeditaction.cfm file in the my_app directory.
  2. Add logic to check that the user entered a valid photo filename by copying the following code immediately following the first <cfset isOk = "Yes"> statement:
        <!-- Check to see if photo file exists. --->
    <cfset PhotoLocation = "C:\Inetpub\wwwroot\CFDOCS\getting_started\Photos\">
    <cfset PhotoLocation = PhotoLocation  & FORM.photo>
    <cfif not FileExists(PhotoLocation)>
       <cfset isOk = "No">
       <cfoutput>Trip Photo does not exist</cfoutput>
    </cfif>
  3. Verify that the code you just copied is pointing to the correct PhotoLocation path. The path is specified in the <cfset PhotoLocation = "C:..."> tag.

    For example, depending on your web server configuration, the PhotoLocation path might be:

    • For MS Windows systems:
          <cfset PhotoLocation =
    "C:\CFusionMX7\wwwroot\cfdocs\getting_started\photos\">

      or

    <cfset PhotoLocation =
    "C:\Inetpub\wwwroot\cfdocs\getting_started\photos\">
    • For Linux or Solaris systems:
          <cfset PhotoLocation =
    "/opt/cfusionmx7/wwwroot/cfdocs/getting_started/photos/">

      or

    <cfset PhotoLocation =
    "/<webserverdocroot>/cfdocs/getting_started/photos/">
  4. Save the file.

To test the modified code:

  1. View the tripedit.cfm page in your browser.
  2. Perform tests by doing the following:
    1. In the Trip Edit page, enter valid information in all the required fields except the Photo Filename field.
    2. In the Photo Filename field, enter nowhere.jpg, and click Save.

      The following error message appears: Trip photo does not exist.

    3. To avoid the error, replace the invalid photo filename in the Trip Edit page with somewhere.jpg and click Save.

      The following message appears: Trip added.

Reviewing the code

The following table describes the code used to verify whether the photo file exists:

Code

Explanation

<cfset PhotoLocation =
"C:\CFusionMX7\wwwroot\cfdocs\
getting_started\photos\">

The cfset tag sets the value of the PhotoLocation path to the appropriate directory.

Note: The code snippet shows one value for Windows systems.

<cfset PhotoLocation = PhotoLocation  & FORM.photo>

The ColdFusion & operator in the cfset tag combines the directory name with the name of the photo file entered in the form.

<cfif not FileExists(PhotoLocation)>
    <cfset isOk = "No">
    <cfoutput>
    Trip Photo does not exist.
    </cfoutput>
</cfif>

FileExists checks to see if the file indicated by the fileLocation variable exists at the specified disk location. If it doesn’t, an error message appears.


Summary

As described in this lesson, ColdFusion offers a number of alternatives to validating data. If you are familiar with standard page validation code, ColdFusion supports these development approaches. However, ColdFusion form tags simplify data validation. In this lesson, you also dynamically populated a list.


In the next lesson

Now that you are sure that your application can save valid data, in the next lesson, you will write code to add trips to the database. Additionally, you will add logic to update existing trip data in the Trips table.
Previous


Lesson 8: Implementing Browsing and Searching

In this lesson, you will further enhance the Compass Travel Macromedia ColdFusion application by providing code to implement the navigation and searching functions.

This lesson contains the following exercises:

Exercise 1: Enabling users to browse trip details

Exercise 2: Determining actions based on which button a user clicks

Exercise 3: Enabling searching from the Trip Detail page

ColdFusion tags and functions introduced in this lesson

The following table identifies the ColdFusion tag and structure that you use in this lesson to enhance the Trip Maintenance application:

Element

Type

Description

cflocation

Tag

Tag opens a ColdFusion page or HTML file.

URL

Structure

Structure to hold the variables within a URL.
Next


Exercise 1: Enabling users to browse trip details

In Lesson 6: Creating a Main Application Page, you added buttons to the Trip Detail page to browse records in the database. In this exercise, you build the action pages that implement the actions for these buttons.

To enable browsing, you build the Navigation Action page. This page determines which trip record appears on the Trip Detail page after the user clicks one of the navigation buttons. There is no HTML output displayed from this action page. Instead, this page uses dynamic SQL to identify the tripID that must appear on the Trip Detail page. In this dynamic SQL statement, the proper tripID is passed as a parameter to the URL, and then redirects the tripID to the Trip Detail page.

Using dynamic SQL to browse the Trips table

The tripID uniquely identifies a trip in the Trips table. In Lesson 6: Creating a Main Application Page, you displayed the Trip Detail page for a trip by passing the ID as a parameter of the URL. For example, you would use the following URL to display the detail information for a trip with the ID of 20:

http://localhost/cfdocs/getting_started/my_app/tripdetail.cfm?ID=20

The main objective of the Navigation Action page (navigationaction.cfm) is to navigate to the Trip Detail page using a URL that includes the correct tripID based on the navigation button clicked. Because trips are added and later deleted, trips might not be ordered sequentially by ID. There can be missing IDs where trips were deleted. For example, if the current tripID is 10 and the user clicks the Next navigation button, the tripID of the next trip might not be 11; it could be 14.

To retrieve the proper tripID, you must query the database to find out what the next (or previous, first, or last) ID is, based on the current tripID. The navigation action page uses dynamic SQL to build a query to find the appropriate ID to use.

In Lesson 4: Building Dynamic Queries, you used ColdFusion string manipulation to construct the proper SQL SELECT WHERE clause. In this lesson, you use a similar approach to build the WHERE clause for navigation. Additionally, you use the proper ORDER BY clause to select the correct trip row from the trips table.

For example, if the current tripID equals 6, the following table identifies the proper SQL statement based on the navigation button that the user clicked:

Navigation button | SQL statement to navigate to correct trip ID | SQL statement description
First Row | SELECT tripID FROM trips ORDER BY tripID | Returns the list of all tripIDs in ascending (1,2,3...) order.
Previous Row | SELECT tripID FROM trips WHERE tripID < 6 ORDER BY tripID DESC | Returns the list of all tripIDs less than 6 in descending (5,4,3...) order.
Next Row | SELECT tripID FROM trips WHERE tripID > 6 ORDER BY tripID | Returns the list of all tripIDs greater than 6 in ascending (7,8,9...) order.
Last Row | SELECT tripID FROM trips ORDER BY tripID DESC | Returns the list of all tripIDs in descending (99,98,97...) order.

To properly build the SQL SELECT statement for previous and next row navigation, you must know the current tripID. This is the reason for using the hidden input tag RecordID on the Trip Detail page. You can use the form variable #Form.RecordID# in the Navigation Action page for building the proper test in the WHERE clause of the SQL SELECT statement.

Limiting the number of result rows

Each of the SQL statements in the preceding table returns a result set of trips rows. The result set can range from zero to any number of rows. The Navigation Action page must limit the result set count to 1, because only the initial row in the result set appears on the Trip Detail page.

ColdFusion provides the maxRows attribute for the cfquery tag for this purpose. This attribute limits the number of result rows returned from the database. To show only a single row at a time in the Trip Detail page, set maxRows to 1.

To build the Navigation Action page:

  1. Create a blank file.
  2. Enter the following code in the blank file:
    <!---			NAVIGATION BUTTONS 			--->
    <cfquery name="TripQuery" datasource="CompassTravel" maxrows="1">
        SELECT tripID FROM trips
        <cfif IsDefined("Form.btnPrev.X")>
            WHERE tripID < #Form.RecordID#
            ORDER BY tripID DESC
        <cfelseif IsDefined("Form.btnNext.X")>
            WHERE tripID > #Form.RecordID#
            ORDER BY tripID
        <cfelseif IsDefined("Form.btnFirst.X")>
            ORDER BY tripID
        <cfelseif IsDefined("Form.btnLast.X")>
            WHERE tripID > #Form.RecordID#
            ORDER BY tripID DESC
        </cfif>
    </cfquery>
    <cfif TripQuery.RecordCount is 1>
        <cflocation url="tripdetail.cfm?ID=#TripQuery.tripID#">
    <cfelse>
        <cflocation url="tripdetail.cfm?ID=#Form.RecordID#">
    </cfif>
  3. Save the file as navigationaction.cfm in the my_app directory.

Note: In previous lessons, you adhered to good coding practices by putting queries in ColdFusion components. To optimize performance, and because the Navigation Action page contains only a query, the page is a ColdFusion page rather than a CFC. For more information about code reuse, see Creating ColdFusion Elements in ColdFusion MX Developer’s Guide.

Reviewing the code

The following table describes the code used to process the navigation button requests:

Code

Explanation

<cfquery
    name="TripQuery"
    dataSource="CompassTravel"
    maxRows=1>

The cfquery tag identifies that a query named TripQuery is executed against the CompassTravel data source. The number of rows returned cannot exceed 1 (maxRows=1).

SELECT tripID FROM trips

The SQL SELECT statement will always start with "SELECT tripID FROM trips."

<cfif IsDefined("Form.btnPrev.X")>
    WHERE tripID < #Form.RecordID#
    ORDER BY tripID DESC

<cfelseif IsDefined("Form.btnNext.X")>
    WHERE tripID > #Form.RecordID#
    ORDER BY tripID

<cfelseif IsDefined("Form.btnFirst.X")>
    ORDER BY tripID

<cfelseif IsDefined("Form.btnLast.X")>
    WHERE tripID > #Form.RecordID#
    ORDER BY tripID DESC

</cfif>

</cfquery>

The cfif tag checks whether the user pressed a navigation button on the browse page. The X property is checked because the buttons on the detail page use image type HTML input tags. The X property is a mouse offset that gets sent when the user clicks a graphic button.

The WHERE and ORDER BY clauses vary depending on the navigation button that the user clicks.

<cfif TripQuery.RecordCount is 1>
<cflocation url="tripdetail.cfm?RecordID=#TripQuery.tripID#">
<cfelse>
<cflocation url="tripdetail.cfm?RecordID=#Form.RecordID#">
</cfif>

The cfif tag checks to see whether the query returned a row to display. If it did, that tripID is used to form a URL to navigate to using the cflocation tag. If the query returned no rows, it navigates back to the detail page with the current record ID, which passed in the hidden form variable RecordID.

To test the navigation:

  1. View the tripdetail.cfm page from the my_app directory in a browser.
  2. Click the Next Row button.

    The Trip Detail page shows information about the second trip.

  3. Click the Previous Row button.

    The Trip Detail page shows information about the first trip.

  4. Click the Last Row button.

    The Trip Detail page shows information about the last trip.

  5. Click the First Row button.

    The Trip Detail page shows information about the first trip.


Exercise 2: Determining actions based on which button a user clicks

In Lesson 6: Creating a Main Application Page, you added buttons to the Trip Detail page to let users search and modify the trips database; however, because you had not yet written the code to implement these capabilities, ColdFusion displayed an error when you clicked the buttons. Clicking these button sends the user to the maintenanceaction.cfm page. In this exercise, you will create the Maintenance Action page (maintenanceaction.cfm).

ColdFusion creates a variable only for the button that the user clicked. You use the IsDefined function to test for the existence of the variable, which determines which action the application takes.

To create the Maintenance Action page:

  1. Create a blank file.
  2. Enter the following code in the blank file:
    <cfif IsDefined("Form.btnSearch")>
    <!--- Code to execute if the user clicked Search. --->
<cfelseif IsDefined("Form.btnDelete")>
    <!--- Code to execute if the user clicked Delete. --->
<cfelseif IsDefined("Form.btnEdit")>
    <!--- Code to execute if the user clicked Edit. --->
<cfelseif IsDefined("Form.btnAdd")>
    <!--- Code to execute if the user clicked Add. --->
</cfif>
  3. Save the file as maintenanceaction.cfm in the my_app directory.


Exercise 3: Enabling searching from the Trip Detail page

You already created a search capability when you created the tripsearchform.cfm page in Lesson 4: Building Dynamic Queries. When the user clicks the Search button, you want to navigate to the tripsearchform.cfm page. You use the cflocation tag to do so.

To enable searching from the Trip Detail page:

  1. Open the maintenanceaction.cfm file in the my_app directory in your editor.
  2. Add the highlighted code in the file.
    <cfif IsDefined("Form.btnSearch")>
    <!--- Code to execute if the user clicked Search. --->
    <cflocation url="tripsearchform.cfm">
<cfelseif IsDefined("Form.btnDelete")>
    <!--- Code to execute if the user clicked Delete. --->
<cfelseif IsDefined("Form.btnEdit")>
    <!--- Code to execute if the user clicked Edit. --->
<cfelseif IsDefined("Form.btnAdd")>
    <!--- Code to execute if the user clicked Add. --->
</cfif>
  3. Save the file.

Reviewing the code

The following table describes the code that executes when the user clicks the Search button:

Code

Explanation

<cfif IsDefined("Form.btnSearch")>
    <cflocation url="tripsearchform.cfm">

If the Form.btnSearch variable exists because the user clicked the Search button, go to the page tripsearchform.cfm.


Summary

In this lesson, you added the capability of browsing trips sequentially to the Trip Detail page. You also limited the result set of the dynamic query using the MaxRows attribute of the cfquery tag.

By implementing the Maintenance Action page, you enabled users to take action on the current trip. You used the ColdFusion cflocation tag to link the search page to the Trip Detail page.


In the next lesson

You have implemented the navigation buttons and the Search button on the Trip Detail page. In Lesson 9: Enabling Database Maintenance, you will implement the Delete, Add and Edit buttons.
Previous


Lesson 9: Enabling Database Maintenance

In this lesson, you will enable maintenance of the trips database. The exercises will guide you through the steps of adding the database update logic to delete trips, add new trip offerings, and update existing trips in the Compass Travel database.

This lesson contains the following exercises:

Exercise 1: Deleting the current trip record shown on the Trip Detail page

Exercise 2: Adding trips with SQL INSERT statements

Exercise 3: Adding data using the cfinsert tag

Exercise 4: Updating a SQL row using the cfupdate tag

Exercise 5: Linking the Trip Edit page to the main page

Exercise 6: Inserting values in the edit form

ColdFusion tags introduced in this lesson

The following table identifies the ColdFusion tags that you use in this lesson to enhance the ColdFusion application:

Element

Type

Description

cfinsert

Tag

Inserts records in a JDBC data source.

cfupdate

Tag

Updates records in a JDBC data source.
Next


Exercise 1: Deleting the current trip record shown on the Trip Detail page

In Lesson 8: Implementing Browsing and Searching, you created the tripeditaction.cfm page to contain server side edits for the trip edit data entry form. In this lesson, you complete the tripeditaction.cfm page.

Before you can write the code to delete a trip, you must understand the underlying SQL statement to delete rows from the trips table.

The SQL DELETE statement removes existing rows in a relational table. The DELETE statement has the following format:

DELETE FROM table_name WHERE column_name = some_value

For example, the database table named Clients contains holds information about people, in the following rows:

LastName | FirstName | Address | City
Jones | Tom | 50 Main St | New York
Adamson | Anita | 521 Beacon St | Boston
Green | Peter | 1 Broadway | New York

To delete everyone from New York from the table, use the following statement:

DELETE FROM Clients WHERE City = 'New York'

After the database management system processes the preceding statement, the table contains the following row only:

LastName | FirstName | Address | City
Adamson | Anita | 521 Beacon St | Boston

To ensure that the Trip Maintenance application deletes only the proper trip, you must use the unique tripID key when issuing the SQL DELETE statement. The RecordID field holds the tripID. Using the hidden RecordID input tag from the Trip Detail page, the following SQL statement deletes a row from the Trips table:

DELETE FROM trips WHERE tripID = #Form.RecordID#

To enable users to delete trips:

  1. Open the maintenanceaction.cfm file in the my_app directory in your editor.
  2. Add the highlighted code in the file.
    <cfif IsDefined("Form.btnSearch")>
    <!--- Code to execute if the user clicked Search. --->
    <cflocation url="tripsearchform.cfm">
<cfelseif IsDefined("Form.btnDelete")>
    <!--- Code to execute if the user clicked Delete. --->
    <cfquery name="DeleteRecord" datasource="CompassTravel">
        DELETE FROM trips WHERE tripID = #Form.RecordID#
    </cfquery>
<cflocation url="tripdetail.cfm">
<cfelseif IsDefined("Form.btnEdit")>
    <!--- Code to execute if the user clicked Edit. --->
<cfelseif IsDefined("Form.btnAdd")>
    <!--- Code to execute if the user clicked Add. --->
</cfif>
  3. Save the page.

To test the delete capability:

  1. View the tripdetail.cfm page in a browser.

    The current trip is Nepal. Notice that the destination for the Nepal Summit Challenge trip is Imji Himal, Nepal.

  2. Click Search.

    The Trip Search page appears.

  3. In the Trip Search page, select Begins With in the selection box for Trip Location.
  4. Enter Imji in the Trip Location field.
  5. Click Search.
  6. Verify that only one trip is found whose location begins with Imji.
  7. To return to the Trip Detail page for this trip, click Nepal Summit Challenge
  8. In the Trip Detail page, click Delete.
  9. Click Search.
  10. Select Beings With in the selection box for Trip Location.
  11. Enter Imji in the Trip Location field.
  12. Click Search.

    There should be no records, because you deleted the trip.


Exercise 2: Adding trips with SQL INSERT statements

In Lesson 8: Implementing Browsing and Searching, you built a Trip Edit page to collect the data. Now you can modify the Trip Edit action page to insert the data into the database. There are two approaches to inserting data into a SQL database:

  • Build a SQL INSERT statement and execute it using the cfquery tag.
  • Use the ColdFusion cfinsert tag. This approach eliminates the need for you to learn SQL syntax.

In this exercise, you use a SQL INSERT statement.

In previous lessons, you used the SQL SELECT statement to retrieve data and the SQL DELETE statement to delete data from the Trips table in the Compass Travel database. To add new trips to the database using SQL, you must understand the syntax of the SQL INSERT statement.

The SQL INSERT statement inserts new rows into a relational table. The SQL INSERT statement has the following format:

INSERT INTO table_name
VALUES (value1, value2,....)

For example, the database table named Clients contains information about people in the following rows:

LastName | FirstName | Address | City
Tom | Jones | 12 State St | Boston
Peter | Green | 1 Broadway | New York

To add a record to the table, use the following statement:

INSERT INTO Clients
VALUES ('Smith', 'Kaleigh', '14 Greenway', 'Windham')

After the database management system processes the preceding statement, the table contains the following rows:

LastName | FirstName | Address | City
Tom | Jones | 12 State St | Boston
Peter | Green | 1 Broadway | New York
Smith | Kaleigh | 14 Greenway | Windham

Notice that the values inserted in the table were surrounded by single-quotation marks in the statement. In SQL, you must surround any text or date values with single-quotation marks; however, you don’t use single-quotation marks with numeric values.

Alternatively, you can specify the columns for which you want to insert data. This approach lets you insert data into some columns while omitting others. For this approach, you use the following syntax:

INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)

For example, to add Kaleigh Smith of Windham, with an unknown address, you use the named column approach:

INSERT INTO Clients (LastName, FirstName, City)
VALUES ('Smith', 'Kaleigh', 'Windham')

You use the cfquery tag to execute SQL from ColdFusion. The cfquery tag passes SQL statements to your data source. As described in Lesson 2: Configuring Your Development Environment, a data source stores information about how to connect to an indicated data provider, such as a relational database management system. The data source that you established in that chapter stored information on how to access the Compass Travel database. The data source name was "CompassTravel."

To add data using a SQL INSERT statement and a cfquery tag:

  1. Open the tripeditaction.cfm file in the my_app directory.
  2. Locate the <cfif isOk EQ "Yes"> tag near the end of the file. After the <H1>Trip Added
    </H1>     line, add the following code in the following table to insert the data from the Form variables into the trips table:

    For

    Code

    Windows users, using MS Access

    <!--- Insert the new trip record into the Compass
    Travel database. --->
<cfquery name="AddTrip" datasource="compasstravel">
    INSERT INTO Trips (tripName, eventType, tripDescription,
        tripLocation,departureDate, returnDate, price, tripLeader,
        photo, baseCost, numberPeople, depositRequired)
    VALUES ('#Form.tripName#', #Form.eventType#,
        '#Form.tripDescription#',
        '#Form.tripLocation#','#Form.departureDate#',
        '#Form.returnDate#',
        #Form.price#, '#Form.tripLeader#', '#Form.photo#',
        #Form.baseCost#, #Form.numberPeople#, '#Form.depositRequired#')
</cfquery>

    UNIX users, using PointBase

    <!--- Insert the new trip record into the
    Compass Travel database. --->
<!--- Use local variables to convert dates to JDBC format
    (yyyy-mm-dd) from input format (mm/dd/yyyy). --->
<cfset JDBCdepartureDate = #Right(Form.departureDate,4)#
    & "-" & #Left(Form.departureDate,2)# & "-"
    & #Mid(Form.departureDate,4,2)#>
<cfset JDBCreturnDate = #Right(Form.returnDate,4)# & "-"
    & #Left(Form.returnDate,2)# & "-"
    & #Mid(Form.returnDate,4,2)#>
<cfquery name="AddTrip" datasource="CompassTravel">
    INSERT INTO Trips (tripName, eventType,
    tripDescription, tripLocation,
        departureDate, returnDate, price, tripLeader, photo,
        baseCost, numberPeople,	depositRequired)
  VALUES ('#Form.tripName#', #Form.eventType#, '#Form.tripDescription#',
        '#Form.tripLocation#', Date'#JDBCdepartureDate#',
        Date'#JDBCreturnDate#',
        #Form.price#,'#Form.tripLeader#', '#Form.photo#',
        #Form.baseCost#, #Form.numberPeople#, '#Form.depositRequired#')
</cfquery>
  3. Save the file.

To test the modified code:

  1. Open the tripedit.cfm page in your browser.
  2. In the tripedit.cfm page, enter in the fields the values in the following table, and then click Save.

    Field

    Value

    Trip Name

    NH White Mountains

    Event Type

    Mountain Climbing

    Trip Description

    Climb the 5 highest peaks in the New Hampshire White Mountains.

    Trip Location

    Northeastern New Hampshire

    Departs

    05/01/2005

    Returns

    05/10/2005

    Number of People

    15

    Price

    1200

    Base Cost

    600

    Deposit Required

    Yes

    Trip Leader

    Tom Finn

    Photo File Name

    whitemountains.jpg

    After the new trip is written to the database, the following message appears: You have added NH White Mountains to the trips database.

  3. To verify that the trip was saved, open the tripsearchform.cfm page in the my_app directory in your browser.
  4. In the Trip Search page, in the Trip Location drop-down list, select the Begins With option, and enter the value Nor in the text box.
  5. Click Search.

    The TripResults page appears.

  6. Click NH White Mountains to display the details of the trip you just added. Verify that all the fields were saved correctly.
  7. Click the Delete button to delete this record so that you can reuse some of the steps of this exercise in Exercise 3: Adding data using the cfinsert tag.

Reviewing the code

The following table describes the SQL INSERT and cfquery code that ColdFusion uses to add data:

Code

Explanation

<cfquery name="AddTrip"
datasource="CompassTravel">

Using the datasource attribute, the cfquery tag connects to the CompassTravel data source and returns a result set identified by the name attribute.

INSERT INTO Trips (TripName,
EventType, tripDescription,
tripLocation, departureDate,
returnDate, price, tripLeader,photo,
baseCost, numberPeople,
depositRequired)
  VALUES ( '#Form.TripName#',
#Form.EventType#,
'#Form.tripDescription#',
'#Form.tripLocation#',
'#Form.departureDate#',
'#Form.returnDate#', #Form.price#,
'#Form.tripLeader#', '#Form.photo#',
#Form.baseCost#, Form.numberPeople#,
'#Form.depositRequired#)

The SQL INSERT statement identifies the data to insert into the Trips table. The table column names are cited in a comma-separated list surrounded by parentheses (TripName, EventType....) after the table name Trips.

The VALUES keyword indicates the list of values that are inserted into the columns in the same order as the columns are specified earlier in the statement.

The values refer to form variables that are passed from the data entry form to the action page. The variables are surrounded by number signs; for example, #Form.baseCost#. Also, if the column data type is a String data type, the values are surrounded by single-quotation marks; for example: '#Form.TripName#'.

For more information about adding data to a database using SQL and the cfquery tag, see ColdFusion MX Developer’s Guide. For more information about SQL, consult any SQL primer.


Exercise 3: Adding data using the cfinsert tag

For developers who prefer not to have to remember SQL syntax to add information to SQL databases, ColdFusion simplifies the coding for inserting SQL rows through the use of the cfinsert tag. As you might expect, the cfinsert tag has datasource and tablename attributes to specify where the data is inserted. The tag also has a formfields attribute to identify which fields to insert. The formfields attribute specifies a comma-separated list of form fields to insert. If this attribute is not specified, all the fields in the form are included in the operation. The following example uses the cfinsert tag with these attributes:

<cfinsert datasource="CompassTravel" tablename="Trips"
    formfields="tripName, eventType, tripDescription, tripLocation,
    departureDate, returnDate, price, tripLeader, photo, baseCost,
    numberPeople, depositRequired">

The cfinsert tag used in the preceding code snippet uses the following attributes:

Attribute | Description
datasource | The data source name associated with the database where the data is inserted.
tablename | The name of the SQL table within the database where the data is inserted.
formfields | A comma-separated list of form fields to insert.

To add data using cfinsert:

  1. Open the tripeditaction.cfm file from the my_app directory in your editor.
  2. Remove the entire AddTrip cfquery code block that you added in Exercise 2: Adding trips with SQL INSERT statements:
        <cfquery name="AddTrip" datasource="compasstravel">
        INSERT INTO Trips (tripName, eventType, tripDescription,
            tripLocation,departureDate, returnDate, price, tripLeader,
            photo, baseCost, numberPeople, depositRequired)
        VALUES ('#Form.tripName#', #Form.eventType#,
            '#Form.tripDescription#',
            '#Form.tripLocation#','#Form.departureDate#',
            '#Form.returnDate#',
            #Form.price#, '#Form.tripLeader#', '#Form.photo#',
            #Form.baseCost#, #Form.numberPeople#, '#Form.depositRequired#')
    </cfquery>
  3. Add the following cfinsert tag to insert data into the trips table in the same location as the code that you just deleted:
    <cfinsert datasource="CompassTravel" tablename="trips">
  4. Save the file.

To test the modified code:

  1. Open the tripedit.cfm page in your browser.
  2. In the tripedit.cfm page, enter in the fields the values in the following table, and then click Save:

    Field

    Value

    Trip Name

    NH White Mountains

    Event Type

    Mountain Climbing

    Trip Description

    Climb the 5 highest peaks in the New Hampshire White Mountains.

    Trip Location

    Northeastern New Hampshire

    Departs

    05/01/2005

    Returns

    05/10/2005

    Number of People

    15

    Price

    1200

    Base Cost

    600

    Deposit Required

    Yes

    Trip Leader

    Tom Finn

    Photo File Name

    whitemountains.jpg

    After the new trip is written to the database, the following message appears: You have added NH White Mountains to the trips database.

  3. To verify that the trip was saved, open the tripsearchform.cfm page in the my_app directory in your browser.
  4. In the Trip Search page, in the Trip Location drop-down list, select the Begins With option, and enter the value Nor in the text box.
  5. Click Search.

    The TripResults page appears.

  6. Click NH White Mountains to display the details of the trip you just added. Verify that all the fields were saved correctly.

For more information about adding data to a database using the cfinsert tag, see ColdFusion MX Developer’s Guide.


Exercise 4: Updating a SQL row using the cfupdate tag

To update an existing SQL row, ColdFusion offers a simple approach through the use of the cfupdate tag. Like the cfinsert tag, the cfupdate tag has datasource and tablename attributes to specify where the data is to be inserted. The tag also has a formfields attribute to identify which fields are to insert. The formfields attribute specifies a comma-separated list of form fields to insert. If this attribute is not specified, all the fields in the form are included in the operation.

All the fields of the tripedit.cfm page have corresponding columns in the Trips table, so you can omit the FormFields attribute for both the cfinsert and cfupdate tags. If the tripID form field is passed from the Trip Edit page, the cfupdate tag is used; otherwise the cfinsert tag is executed. The following example uses the cfupdate and cfinsert tags without the formfields attribute:

<cfif not isdefined("form.tripID")>
    <cfinsert datasource="CompassTravel" tablename="Trips">
        <cflocation url="tripdetail.cfm">
    <cfelse>
    <cfupdate datasource="CompassTravel" tablename="Trips">
        <cflocation url="tripdetail.cfm?ID=#Form.tripID#">
</cfif>

Reviewing the code

The following tables describes the cfinsert and cfupdate code:

Code

Explanation

<cfif not isdefined("form.tripID")>
    <cfinsert datasource="CompassTravel"
    tablename="Trips">
        <cflocation url="tripdetail.cfm">
<cfelse>
<cfupdate datasource="CompassTravel"
    tablename="Trips">
<cflocation url="tripdetail.cfm?ID=#Form.tripID#">
</cfif>

The IsDefined function determines whether the hidden field tripID was passed to the action page from the tripedit.cfm page. If there is a current trip, the IsDefined function returns True. When there is no current trip, the cfif statement is True. When the cfif statement is True, the cfinsert tag executes and the main page appears with the updated trip. If the cfif statement evaluates to False, the cfinsert statement executes and the first trip appears in the main page.

To update the database using a cfupdate tag:

  1. Open the tripeditaction.cfm file in the my_app directory in your editor.
  2. Add the following code before the </body> tag at the end of the file:
    <!--- Update the database --->
    <cfif isOk EQ "Yes">
       <cfif isdefined("form.tripID")>
           <cfupdate datasource="CompassTravel" tablename="trips">
           <cflocation url="tripdetail.cfm?ID=#Form.tripID#">
       <cfelse>
           <cfinsert datasource="CompassTravel" tablename="TRIPS">
           <cflocation url="tripdetail.cfm">
       </cfif>
    <cfoutput>You have added #Form.TripName# to the trips database.
    </cfoutput>
    </cfif>
  3. Save the file.

For more information about adding data to a database using the cfupdate tag, see ColdFusion MX Developer’s Guide.


Exercise 5: Linking the Trip Edit page to the main page

As discussed in Lesson 7: Validating Data to Enforce Business Rules, the action page for the maintenance buttons on the main page is maintenanceaction.cfm. You previously added code for the Search and Delete buttons. In this exercise, you add code for the Add and Edit buttons.

To link the Add and Edit buttons on the Trip Detail page:

  1. Open the maintenanceaction.cfm file in the my_app directory in your editor.
  2. Locate the </cfif> tag at the end of the file.
  3. Insert the highlighted code:
        <cfelseif IsDefined("Form.btnEdit")>
    <!--- Code to execute if the user clicked Edit. --->
        <cflocation url="tripedit.cfm?ID=#Form.RecordID#">
    <cfelseif IsDefined("Form.btnAdd")>
    <!--- Code to execute if the user clicked Add. --->
        <cflocation url="tripedit.cfm">
  4. Save the file.


Exercise 6: Inserting values in the edit form

Notice that when the user clicks the Add button, the maintenanceaction.cfm page navigates to the tripedit.cfm page without passing any arguments. Conversely, when the user clicks the Edit button, the Trip Edit page passes the current record ID. The Trip Edit page must handle both cases. When a RecordID is passed on the URL, the tripedit.cfm page must query the database and fill the form with the data for the corresponding trip.

To insert values in the edit form:

  1. Open the tripedit.cfm file in your editor.
  2. Enter or copy and paste the following code after the cfquery block that appears at the top of the file:
    <cfif IsDefined("URL.ID")>
    <cfquery name="TripQuery" datasource="CompassTravel" maxrows="1">
        SELECT tripName, eventType, tripDescription, tripLocation,
        departureDate, returnDate, price, tripLeader, photo, baseCost,
        numberPeople, depositRequired, tripID
        FROM trips
    <cfif IsDefined("URL.ID")>
        WHERE tripID = #url.ID#
    </cfif>
    </cfquery>
<!--- Set the local variables --->
    <cfset tripName = '#TripQuery.tripName#'>
    <cfset eventType = '#TripQuery.eventType#'>
    <cfset tripDescription = '#TripQuery.tripDescription#'>
    <cfset tripLocation = '#TripQuery.tripLocation#'>
    <cfset departureDate = DateFormat(#TripQuery.departureDate#,
        "mm/dd/yyyy")>
    <cfset returnDate = DateFormat(#TripQuery.returnDate#,"mm/dd/yyyy")>
    <cfset price = #TripQuery.price#>
    <cfset tripLeader = '#TripQuery.tripLeader#'>
    <cfset photo = '#TripQuery.photo#'>
    <cfset baseCost = #TripQuery.baseCost#>
    <cfset numberPeople = #TripQuery.numberPeople#>
    <cfif isDefined("TripQuery.depositRequired")>
        <cfset depositRequired = 'Yes'>
        <cfelse>
        <cfset depositRequired = 'No'>
    </cfif>
<cfelse>
    <cfset tripName = ''>
    <cfset tripDescription = ''>
    <cfset eventTypeIdentifier = #GetEvents.eventType#>
    <cfset tripLocation = ''>
    <cfset departureDate = ''>
    <cfset returnDate = ''>
    <cfset price = ''>
    <cfset tripLeader = ''>
    <cfset photo = ''>
    <cfset baseCost = ''>
    <cfset numberPeople = ''>
    <cfset depositRequired = 'Yes'>
</cfif>
  3. To make the appropriate values appear in the form, insert the code that is highlighted in the following table:

    Note: If the user clicks the Add button, the values from the currently displayed trip detail appear in the form; otherwise, all values, except those in the event type field, are blank.

  4. Save the file.

    Code

    Explanation

    <TD><cfinput name= "tripName"
    maxlength = "50"
    size = "50"
    required = "Yes"
    value="tripName"
    message = "Trip name must not be blank">
</TD>

    Set the value of the Trip Name to be blank if the ID is undefined; otherwise, set the value equal to the Trip Name that appeared on the Trip Detail page.

    <TD><cftextarea name="tripDescription"
    required="Yes"
    message="Trip description must not be blank.">
    value="#tripDescription#"
    </cftextarea>
</TD>

    Set the value of the Trip Description to be blank if the ID is undefined; otherwise, set the value equal to the Trip Description that appeared on the Trip Detail page.

    <td><cfselect size="1" name="eventType" required="Yes"
    message="Type of event must be selected.">
    <cfoutput query="GetEvents">
        <option value= "#GetEvents.eventTypeID#">#GetEvents.eventType#
    </option>
    </cfoutput>
</cfselect>
</td>

    Set the value of the Event Type to be the list of events.

    <TD><cfinput size="50" name="tripLocation"
    required="Yes"
    value="#tripLocation#"
    message="Trip location must not be blank.">
</TD>

    Set the value of the Trip Location to be blank if the ID is undefined; otherwise, set the value equal to the Trip Location that appeared on the Trip Detail page.

    <TD><cfinput name="departureDate"
    size="10"
    required="Yes"
    validate="date"
    value="#departureDate#"
    message="Departure date must be a valid date.">
</TD>

    Set the value of the Departure Date to be blank if the ID is undefined; otherwise, set the value equal to the Departure Date that appeared on the Trip Detail page.

    <TD><cfinput name="returnDate"
    size="10"
    required="Yes"
    validate="date"
    value="#returnDate#"
    message="Return date must be a valid date.">
</TD>

    Set the value of the Return Date to be blank if the ID is undefined; otherwise, set the value equal to the Return Date that appeared on the Trip Detail page.

    <TD><cfinput name="numberPeople"
    size="6"
    required="Yes"
    validate="integer"
    value="#numberPeople#"
    message="The number of people field must be a number and cannot be blank.">
</TD>

    Set the value of the Number of People to be blank if the ID is undefined; otherwise, set the value equal to the Number of People that appeared on the Trip Detail page.

    <TD><cfinput name="price"
    size="10"
    required="Yes"
    validate="integer"
    value="#price#"
    message="Price is required and must be numeric.">
</TD>

    Set the value of the Price to be blank if the ID is undefined; otherwise, set the value equal to the Price that appeared on the Trip Detail page.

    <TD><cfinput name="baseCost"
    size="10"
    required="Yes"
    validate="integer"
    value="#baseCost#"
    message="Base cost is required and must be numeric.">
</TD>

    Set the value of the Base Cost to be blank if the ID is undefined; otherwise, set the value equal to the Base Cost that appeared on the Trip Detail page.

    <TD><cfinput name="depositRequired"
    type="checkbox"
    value="#depositRequired#" >
</TD>

    Set the value of the Deposit Required to be "Yes" if the ID is undefined; otherwise, set the value equal to the Deposit Required that appeared on the Trip Detail page.

    <TD><cfinput name="tripLeader"
    maxlength="50" size="50"
    required="Yes"
    value="#tripLeader#"
    message="A trip leader must be specified."></TD>

    Set the value of the Trip Leader to be blank if the ID is undefined; otherwise, set the value equal to the Trip Leader that appeared on the Trip Detail page.

    <TD><cfinput name="photo"
    maxlength="50" size="50"
    required="Yes"
    value="#photo#"
    message="Valid photo file name must be specified.">
</TD>

    Set the value of the Photo to be blank if the ID is undefined; otherwise, set the value equal to the Photo that appeared on the Trip Detail page.

Reviewing the code

The following table describes the code that ColdFusion uses to properly initialize the Trip Edit form:

Code

Explanation

<cfif IsDefined("URL.ID")>
<cfquery name="TripQuery" datasource="CompassTravel"
maxrows="1">
    SELECT tripName, eventType, tripDescription,
tripLocation, departureDate, returnDate, price,
tripLeader, photo, baseCost, numberPeople,
depositRequired, tripID
    FROM trips
    <cfif IsDefined("URL.ID")>
        WHERE tripID = #ID#
    </cfif>
</cfquery>
        <!--- Set the local variables --->
<cfset tripName = '#TripQuery.tripName#'>
<cfset eventType = #TripQuery.eventType#>
        <cfset tripDescription = TripQuery.tripDescription#'>
<cfset tripLocation = '#TripQuery.tripLocation#'>
<cfset departureDate = DateFormat(#TripQuery.departureDate#,"mm/dd/yyyy")>
<cfset returnDate = DateFormat(#TripQuery.returnDate#,"mm/dd/yyyy")>
...
<cfelse>
<cfset tripName = ''>
<cfset eventType = ''>

...

</cfif>

The ColdFusion function IsDefined determines whether an ID argument was passed as part of the invoking URL.

When an ID is passed, it is used in the WHERE clause of the SQL SELECT statement to retrieve the information about the current trip. The application then instantiates local variables from the results of the SQL query. The

ColdFusion DateFormat function formats the date fields.

If the user clicks the Add button to add a new trip, there is no ID passed as a URL argument. In this case, the local variables are instantiated to blank.

To test the modified code:

  1. Open the tripdetail.cfm page in your browser.
  2. Do the following tasks:
    1. Click the Edit button.
    2. Double the price of the current trip.
    3. Click Save.

Summary

In this lesson you used the SQL DELETE statement, and the cfinsert and cfupdate tags to delete, add, and update data to a table.

Previous


Lesson 10: Restricting Access to ColdFusion Applications

This chapter provides information on using the Login Wizard to restrict access to a new or existing Macromedia ColdFusion application. You will learn about the Login Wizard, and then add user authentication to the Compass Travel application.

This lesson contains the following exercises:

Exercise 1: About the Login Wizard.

Exercise 2: Requiring users to log in to the Compass Travel application.
Next


Exercise 1: About the Login Wizard

ColdFusion MX 7 provides Macromedia Dreamweaver MX Extensions to assist you in creating a ColdFusion MX application that requires login, or user, authentication. The user authentication interface that you create using the Login Wizard can perform simple authentication, authentication against a Microsoft Windows NT domain, or authentication against a Lightweight Directory Access Protocol (LDAP) server.

In Dreamweaver MX, you open the Login Wizard, which guides you through the user authentication interface creation process. The wizard then creates or modifies the files necessary to add user authentication to your ColdFusion MX application.

Installing the Login Wizard

The Login Wizard is installed with ColdFusion MX 7 when you install the Dreamweaver Extensions. If you did not install the Dreamweaver Extensions when you installed ColdFusion MX 7, you can install them separately.

To install the Dreamweaver Extensions:

  1. Ensure that you have installed Dreamweaver 7.0.1 or later.
  2. Make coldfusion/CFIDE/installers the current directory.
  3. Double-click the CFMX7DreamWeaverExtensions.mxp file.
  4. Follow the prompts in the installer.

Preparing to run the Login Wizard

Before using the Login Wizard, you should determine the following information:

  • Which of the authentication types you want to use to restrict access to your application. The types include the following:
    • LDAP, which grants access to users who have an entry in a known LDAP server.
    • NT, which grants access to users who belong to the specified Windows domain.
    • Simple authentication, which grants access to users who enter the user name and password that you specify in the Login Wizard.
  • Whether you want the login page to appear as either of the following:
    • Basic authentication, which uses the browser login pop-up window to prompt the user for login credentials.
    • ColdFusion Login page, which uses a web page to prompt the user for login credentials.

If the application for which you want to restrict access is deployed on a remote server, you should synchronize the files that constitute the application with those that reside on your local server. You should then use the Login Wizard to modify the files on your local server, and perform testing before redeploying the application on the remote server. You can move the application files to the remote server either by using the Login Wizard, which uses Dreamweaver, or by using Dreamweaver directly.

Creating an application that includes user authentication

If you are creating an application, you can use the Login Wizard to create the files necessary for user authentication before creating any other application files. The following table lists the files that the Login Wizard creates for each type of authentication and type of login page:

File | Description
Application.cfc | This file is invoked every time any file in or under this directory is called. You can modify this file as appropriate for your application; however, you should not alter the following line of code: <cfinclude template="mm_wizard_application_include.cfm">
index.cfm | You can replace this file with your own index.cfm file.
mm_wizard_application_include.cfm | This file contains the logic to determine if the user is a valid user. If not, the application automatically redirects the user to a login form. This file is an included call from Application.cfc.
mm_wizard_authenticate.cfc | This file contains the method required to perform user authentication. It creates a <cfloginuser>, which is the ColdFusion MX 7 version of an authenticated user.
mm_wizard_login.cfm | The ColdFusion Login page.
readme.txt | Describes the files that the Login Wizard creates.

Adding user authentication to an existing application

You can use the Login Wizard to add user authentication to an existing application. The Login Wizard modifies the existing Application.cfc. If your application uses an Application.cfm file instead of an Application.cfc file, ColdFusion MX ignores the Application.cfm file when the Login Wizard creates the Application.cfc file in the same directory as the existing Application.cfm file.

If your application already contains a file named index.cfm, the Login Wizard creates the file mm_wizard_index.cfm. You can use your existing index.cfm file without modifying it.

Starting the Login Wizard

After you install the Login Wizard, you can open it from Dreamweaver.

To start the Login Wizard:

  1. Start Dreamweaver.
  2. Ensure that the active site is the one for which you want to restrict access.

    Note: The currently active site must be a local site. The Remote Info Access and the Test Server Access must be RDS

  3. In Dreamweaver, select Commands > CF Login Wizard.
  4. Click Begin the Wizard.
  5. Do one of the following:
    • If the site for which you want to restrict access is the currently active site in Dreamweaver, select the Secure Your Active Site option.
    • To restrict access to a different site, select the Secure a Specific Directory option, click Browse, and then select the application for which you want to restrict access.
  6. Click Next.
  7. Depending on the type of authentication you want to use, continue with the instructions in the appropriate section:
    • Creating a login using simple authentication
    • Creating a login using LDAP authentication
    • Creating a login using Windows NT authentication


Creating a login using simple authentication

When you create a Login using simple authentication, you specify one username and password that all users enter to gain access to your application.

To create a login using simple authentication:

  1. Start the Login Wizard. (See Starting the Login Wizard.)
  2. Select Simple as the type of authentication.
  3. Select one of the following:

    Basic Authentication to use the browser dialog box to prompt the user for credentials

    ColdFusion Login page to prompt the user in a web page

  4. Click Next.
  5. Enter the user name and password that you want users to enter to have access to your application.
  6. Click Next.

    Note: You can specify only one user name and password combination for each application.

    The Login Wizard creates the files necessary to restrict access to your application. The Wizard then displays a list of the files.

  7. To deploy the modified application to your production server, select the check box.
  8. Click Done.


Creating a login using LDAP authentication

If the users of your application have entries in a known LDAP server, you can create a login using LDAP authentication.

To create a login using LDAP authentication:

  1. Start the Login Wizard. (See Starting the Login Wizard.)
  2. Select LDAP as the type of authentication.
  3. Select one of the following:

    Basic Authentication to use the browser dialog box to prompt the user for credentials

    ColdFusion Login page to prompt the user in a web page

  4. Enter the required information in each text box.
  5. Click Verify LDAP Server to verify connection to the LDAP server.
  6. Click Next.
  7. Select the check box to have the Login Wizard synchronize the files on the remote server.
  8. Click Done.


Creating a login using Windows NT authentication

  1. Start the Login Wizard. (See Starting the Login Wizard.)
  2. Select NT as the type of authentication.
  3. Select one of the following:

    Basic Authentication to use the browser dialog box to prompt the user for credentials

    ColdFusion Login page to prompt the user in a web page

  4. Enter the name of the domain for whose members you want to grant access to your application.

    Note: The Login Wizard does not perform validation of the domain name and works only on Windows.

  5. Click Next.
  6. Select the check box to have the Login Wizard synchronize the files on the remote server.
  7. Click Done.


Exercise 2: Requiring users to log in to the Compass Travel application

To ensure that only employees of Compass Travel can access the application you have built, you use the Login Wizard to provide user authentication. You specify only one username and password that all employees of Compass Travel will use to gain access to the application.

Note: To perform the steps in this exercise, you must be running Windows. In addition, the site that contains the Compass Travel application must be a site managed by Dreamweaver.

To add user authentication to the Compass Travel application:

  1. Start Dreamweaver.
  2. Verify that the Compass Travel site is the current site.
  3. In Dreamweaver, select Commands > CF Login Wizard.
  4. Click Begin the Wizard.
  5. Select the Secure Your Active Site option.
  6. Click Next.
  7. Select Simple as the type of authentication.
  8. Select Basic Authentication.
  9. Enter CompassStaff as the user name.
  10. Enter Columbus92 as the password.

    The Login Wizard creates the files necessary to restrict access to your application. The Wizard then displays a list of the files.

  11. Click Done.

To test the authentication:

  1. Open the tripdetail.cfm page in the my_app directory in your browser.
  2. When prompted, enter CompassStaff as the user name.
  3. Enter Columbus92 as the password.


Summary

In this lesson, you learned how to use the Login Wizard to provide user authentication for a site, and added user authentication to the Compass Travel application.

You have completed the Compass Travel application. As you create your own ColdFusion MX applications, see ColdFusion MX Developer’s Guide and CFML Reference.
Previous


CFML Reference

CFML Reference is your primary ColdFusion Markup Language (CFML) reference. Use this book to learn about CFML tags and functions, ColdFusion expressions, and using JavaScript objects for WDDX in Macromedia ColdFusion MX 7. It also provides detailed references for Java and C++ CFX interfaces.

This book contains the following chapters:

  • Introduction
  • Reserved Words and Variables
  • ColdFusion Tags
  • ColdFusion Functions
  • ColdFusion MX Flash Form Style Reference
  • Application.CFC Reference
  • ColdFusion MX Event Gateway Reference
  • ColdFusion C++ CFX Reference
  • ColdFusion Java CFX Reference


Introduction

CFML Reference is your primary ColdFusion Markup Language (CFML) reference. Use this manual to learn about CFML tags and functions, ColdFusion expressions, and using JavaScript objects for WDDX in Macromedia ColdFusion MX 7. It also provides detailed references for Java and C++ CFX interfaces.

About Macromedia ColdFusion MX documentation

The ColdFusion MX documentation is designed to provide support for the complete spectrum of participants.

Documentation set

The ColdFusion documentation set includes the following titles:

Manual | Description
Installing and Using ColdFusion MX | Describes system installation and basic configuration for Windows, Solaris, Linux, and HP-UX.
Configuring and Administering ColdFusion MX | Part I describes how to manage the ColdFusion environment, including connecting to your data sources and configuring security for your applications. Part II describes Verity search tools and utilities that you can use for configuring the Verity K2 Server search engine, as well as creating, managing, and troubleshooting Verity collections.
ColdFusion MX Developer’s Guide | Describes how to develop your dynamic web applications, including retrieving and updating your data, and using structures and forms.
Getting Started Building ColdFusion MX Applications | Contains an overview of ColdFusion features and application development procedures. Includes a tutorial that guides you through the process of developing an example ColdFusion application.
CFML Reference | Provides descriptions, syntax, usage, and code examples for all ColdFusion tags, functions, and variables.
CFML Quick Reference | A brief guide that shows the syntax of ColdFusion tags, functions, and variables.

Viewing online documentation

All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com.


Reserved Words and Variables

This chapter provides information on Macromedia ColdFusion reserved words, and lists scope variables.

Contents

Reserved words

Scope-specific built-in variables

ColdFusion tag-specific variables

CGI environment variables
Next


Reserved words

The following list indicates words you must not use for ColdFusion variables, user-defined function names, or custom tag names. While some of these words can be used safely in some situations, you can prevent errors by avoiding them entirely.

  • Any name starting with cf. However, when you call a CFML custom tag directly, you prefix the custom tag page name with cf_.
  • Built-in function names, such as Now or Hash
  • Scope names, such as Form or Session
  • Operators, such as NE or IS
  • The names of any built-in data structures, such as Error or File
  • The names of any built-in variables, such as RecordCount or CGI variable names
  • CFScript language element names such as for, default, or continue

Remember that ColdFusion is not case-sensitive. For example, all of the following are reserved words: IS, Is, iS, and is.

This section describes the following topics:

  • Reserved words in forms
  • Reserved words in queries
  • Variable scope
  • Caller scope
  • Client variables
  • Server variables
  • Application and session variables


Reserved words in forms

You must also not create form field names ending in any of the following, except to specify a form field validation rule using a hidden form field name.

  • _integer
  • _float
  • _range
  • _date
  • _time
  • _eurodate


Reserved words in queries

The following table lists SQL keywords that are reserved in ColdFusion queries of queries. This list includes all reserved words in the SQL standard, and should be avoided in variables used in all queries. Do not use these keywords as variable names in any queries.

Note: Many database management systems have additional reserved words that you cannot use as variable names in queries to their databases. For a detailed list, see your DBMS documentation.

ABSOLUTE | ACTION | ADD | ALL | ALLOCATE
ALTER | AND | ANY | ARE | AS
ASC | ASSERTION | AT | AUTHORIZATION | AVG
BEGIN | BETWEEN | BIT | BIT_LENGTH | BOTH
BY | CASCADE | CASCADED | CASE | CAST
CATALOG | CHAR | CHARACTER | CHARACTER_ LENGTH | CHAR_LENGTH
CHECK | CLOSE | COALESCE | COLLATE | COLLATION
COLUMN | COMMIT | CONNECT | CONNECTION | CONSTRAINT
CONSTRAINTS | CONTINUE | CONVERT | CORRESPONDING | COUNT
CREATE | CROSS | CURRENT | CURRENT_DATE | CURRENT_TIME
CURRENT_ TIMESTAMP | CURRENT_ USER | CURSOR | DATE | DAY
DEALLOCATE | DEC | DECIMAL | DECLARE | DEFAULT
DEFERRABLE | DEFERRED | DELETE | DESC | DESCRIBE
DESCRIPTOR | DIAGNOSTICS | DISCONNECT | DISTINCT | DOMAIN
DOUBLE | DROP | ELSE | END | END-EXEC
ESCAPE | EXCEPT | EXCEPTION | EXEC | EXECUTE
EXISTS | EXTERNAL | EXTRACT | FALSE | FETCH
FIRST | FLOAT | FOR | FOREIGN | FOUND
FROM | FULL | GET | GLOBAL | GO
GOTO | GRANT | GROUP | HAVING | HOUR
IDENTITY | IMMEDIATE | IN | INDICATOR | INITIALLY
INNER | INPUT | INSENSITIVE | INSERT | INT
INTEGER | INTERSECT | INTERVAL | INTO | IS
ISOLATION | JOIN | KEY | LANGUAGE | LAST
LEADING | LEFT | LEVEL | LIKE | LOCAL
LOWER | MATCH | MAX | MIN | MINUTE
MODULE | MONTH | NAMES | NATIONAL | NATURAL
NCHAR | NEXT | NO | NOT | NULL
NULLIF | NUMERIC | OCTET_LENGTH | OF | ON
ONLY | OPEN | OPTION | OR | ORDER
OUTER | OUTPUT | OVERLAPS | PAD | PARTIAL
POSITION | PRECISION | PREPARE | PRESERVE | PRIMARY
PRIOR | PRIVILEGES | PROCEDURE | PUBLIC | READ
REAL | REFERENCES | RELATIVE | RESTRICT | REVOKE
RIGHT | ROLLBACK | ROWS | SCHEMA | SCROLL
SECOND | SECTION | SELECT | SESSION | SESSION_USER
SET | SIZE | SMALLINT | SOME | SPACE
SQL | SQLCODE | SQLERROR | SQLSTATE | SUBSTRING
SUM | SYSTEM_USER | TABLE | TEMPORARY | THEN
TIME | TIMESTAMP | TIMEZONE_ HOUR | TIMEZONE_ MINUTE | TO
TRAILING | TRANSACTION | TRANSLATE | TRANSLATION | TRIM
TRUE | UNION | UNIQUE | UNKNOWN | UPDATE
UPPER | USAGE | USER | USING | VALUE
VALUES | VARCHAR | VARYING | VIEW | WHEN
WHENEVER | WHERE | WITH | WORK | WRITE
YEAR | ZONE |  |  |


Scope-specific built-in variables

ColdFusion returns variables, such as those returned in a cfdirectory or cfftp operation. A variable is usually referenced by scoping it according to its type: naming it according to the code context in which it is available; for example, Session.varname, or Application.varname. For more information on ColdFusion scopes, see Using ColdFusion Variables in ColdFusion MX Developer’s Guide

You use the cflock tag to limit the scope of CFML constructs that modify shared data structures, files, and CFXs, to ensure that modifications occur sequentially. For more information, see cflock, and Using Persistent Data and Locking in ColdFusion MX Developer’s Guide.

This section describes the following topics:

  • Variable scope
  • Caller scope
  • Client variables
  • Server variables
  • Application and session variables

Variable scope

ColdFusion supports the Variables scope. Unscoped variables created with the cfset tag acquire the Variables scope by default. For example, the variable created by the statement <CFSET linguist = Chomsky> can be referenced as #Variables.linguist#

Caller scope

History

ColdFusion MX: The Caller scope is accessible as a structure. (In earlier releases, it was not.)

Client variables

The following client variables are reserved:

Client.CFID
Client.CFToken
Client.HitCount
Client.LastVisit
Client.TimeCreated
Client.URLToken

Server variables

Use the Server prefix to reference server variables, as follows:

Server.ColdFusion.ProductName
Server.ColdFusion.ProductVersion
Server.ColdFusion.ProductLevel
Server.ColdFusion.SerialNumber
Server.ColdFusion.SupportedLocales
Server.ColdFusion.AppServer
Server.ColdFusion.Expiration
Server.ColdFusion.RootDir
Server.OS.Name
Server.OS.AdditionalInformation
Server.OS.Version
Server.OS.BuildNumber

Application and session variables

To enable application and session variables, use the cfapplication tag or Application.cfc. Reference them as follows:

Application.myvariable
Session.myvariable

To ensure that modifications to shared data occur in the intended sequence, use the cflock tag. For more information, see cflock.

The predefined application and session variables are as follows:

Application.ApplicationName
Session.CFID
Session.CFToken
Session.URLToken


Custom tag variables

A ColdFusion custom tag returns the following variables:

ThisTag.ExecutionMode
ThisTag.HasEndTag
ThisTag.GeneratedContent
ThisTag.AssocAttribs[index]

A custom tag can set a Caller variable to provide information to the caller. The Caller variable is set as follows:

<cfset Caller.variable_name = "value">

The calling page can access the variable with the cfoutput tag, as follows:

<cfoutput>#variable_name#</cfoutput>

This section describes the following topics:

  • Request variable
  • Form variable

Request variable

Request variables store data about the processing of one page request. Request variables store data in a structure that can be passed to nested tags, such as custom tags, and processed once.

To provide information to nested tags, set a Request variable, as follows:

<CFSET Request.field_name1 = "value">
<CFSET Request.field_name2 = "value">
<CFSET Request.field_name3 = "value">
...

Each nested tag can access the variable with the cfoutput tag, as follows:

<CFOUTPUT>#Request.field_name1#</CFOUTPUT>

Form variable

ColdFusion supports the Form variable FieldNames. FieldNames returns the names of the fields on a form. You use it on the action page associated with a form, as follows:

Form.FieldNames


ColdFusion tag-specific variables

Some ColdFusion tags return data as variables. For example, the cffile tag returns file size information in the FileSize variable, referenced as CFFILE.FileSize.

The following tags return data that can be referenced in variables:

cfcatch
cfdirectory
cferror
cffile
cfftp
cfhttp
cfindex
cfldap
cfpop
cfquery
cfregistry
cfsearch
cfstoredproc

This section describes the following topics:

  • ColdFusion query variables
  • CFCATCH variables
  • CFDIRECTORY variables
  • CFERROR variables
  • CFFILE ACTION=Upload variables
  • CFFTP error variables
  • CFFTP ReturnValue variable
  • CFFTP query object columns CFHTTP variables
  • CFLDAP variables
  • CFPOP variables
  • CFQUERY and CFSTOREDPROC variables
  • CFREGISTRY variables
  • CFSEARCH variables

ColdFusion query variables

A ColdFusion tag that returns a query object supports the following variables, where queryname is the value of the name attribute:

queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList

CFCATCH variables

Within a cfcatch block, the active exception properties can be accessed as the following variables:

CFCATCH.Type
CFCATCH.Message
CFCATCH.Detail
CFCATCH.ErrNumber
CFCATCH.NativeErrorCode
CFCATCH.SQLState
CFCATCH.LockName
CFCATCH.LockOperation
CFCATCH.MissingFileName
CFCATCH.TagContext
CFCATCH.ErrorCode
CFCATCH.ExtendedInfo

Within a cfcatch block, database exception properties can be accessed as the following variables:

CFCATCH.QueryError
CFCATCH.SQL
CFCATCH.Where
CFCATCH.Datasource

Within a cfcatch block, undefined variable exception properties can be accessed as the following variable:

CFCATCH.Name

Within a cfcatch block, syntax and parsing exception properties can be accessed as the following variables:

CFCATCH.TokenText
CFCATCH.Snippet
CFCATCH.Column
CFCATCH.KnownColumn
CFCATCH.Line
CFCATCH.KnownLine

CFDIRECTORY variables

The cfdirectory tag, with action=list, returns a query object as follows, where queryname is the name attribute value:

queryname.Name
queryname.Size
queryname.Type
queryname.DateLastModified
queryname.Attributes
queryname.Mode

CFERROR variables

When cferror generates an error page, the following error variables are available if type="request" or "exception".

Error.Diagnostics
Error.MailTo
Error.DateTime
Error.Browser
Error.GeneratedContent
Error.RemoteAddress
Error.HTTPReferer
Error.Template
Error.QueryString

The following error variables are available if type="validation".

Error.ValidationHeader
Error.InvalidFields
Error.ValidationFooter

Any cfcatch variable that applies to exception type can be accessed within the Error scope, as follows:

Error.Type
Error.Message
Error.Detail
Error.ErrNumber
Error.NativeErrorCode
Error.SQLState
Error.LockName
Error.LockOperation
Error.MissingFileName
Error.TagContext
Error.ErrorCode
Error.ExtendedInfo

Note: You can substitute the prefix CFERROR for Error, if type = "Exception"; for example, CFERROR.Diagnostics, CFERROR.Mailto, or CFERROR.DateTime.

CFFILE ACTION=Upload variables

File variables are read-only. Use the CFFILE prefix to reference file variables; for example, CFFILE.ClientDirectory. The File prefix is deprecated in favor of the CFFILE prefix.

CFFILE.AttemptedServerFile
CFFILE.ClientDirectory
CFFILE.ClientFile
CFFILE.ClientFileExt
CFFILE.ClientFileName
CFFILE.ContentSubType
CFFILE.ContentType
CFFILE.DateLastAccessed
CFFILE.FileExisted
CFFILE.FileSize
CFFILE.FileWasAppended
CFFILE.FileWasOverwritten
CFFILE.FileWasRenamed
CFFILE.FileWasSaved
CFFILE.OldFileSize
CFFILE.ServerDirectory
CFFILE.ServerFile
CFFILE.ServerFileExt
CFFILE.ServerFileName
CFFILE.TimeCreated
CFFILE.TimeLastModified

CFFTP error variables

When you use the cfftp stoponerror attribute, these variables are populated:

CFFTP.Succeeded
CFFTP.ErrorCode
CFFTP.ErrorText

CFFTP ReturnValue variable

Some cfftp file and directory operations provide a return value, in the variable CFFTP.ReturnValue. Its value is determined by the results of the action attribute. When you specify any of the following actions, cfftp returns a value:

GetCurrentDir
GetCurrentURL
ExistsDir
ExistsFile
Exists

CFFTP query object columns

When you use the cfftp tag with the listdir action, cfftp returns a query object, where queryname is the name attribute value, and row is the row number of each file or directory entry:

queryname.Name[row]
queryname.Path[row]
queryname.URL[row]
queryname.Length[row]
queryname.LastModified[row]
queryname.Attributes
queryname.IsDirectory
queryname.Mode

CFHTTP variables

A cfhttp get operation can return text and binary files. Files are downloaded and the contents stored in a variable or file, depending on the MIME type, as follows:

CFHTTP.FileContent
CFHTTP.MimeType
CFHTTP.Header
CFHTTP.ResponseHeader[http_hd_key]
CFHTTP.StatusCode

CFLDAP variables

The cfldap action=query tag returns information about the LDAP query, as follows:

queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList

CFPOP variables

The cfpop tag returns the following result columns, depending on the action attribute value and the use of other attributes, such as attachmentpath, where queryname is the name attribute value:

queryname.Date
queryname.From
queryname.Body
queryname.Header
queryname.MessageNumber
queryname.ReplyTo
queryname.Subject
queryname.CC
queryname.To
queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList
queryname.Attachments
queryname.AttachmentFiles

CFQUERY and CFSTOREDPROC variables

The cfquery tag returns information about the query in this variable:

CFQUERY.ExecutionTime

The cfquery tag uses the query name to scope the following data about the query:

queryname.CurrentRow
queryname.RecordCount
queryname.ColumnList

The cfstoredproc tag returns the following variables:

CFSTOREDPROC.ExecutionTime
CFSTOREDPROC.StatusCode

CFREGISTRY variables

The cfregistry tag returns a query record set that you can reference after executing the GetAll action, as follows, where queryname is the name attribute value:

queryname.Entry
queryname.Type
queryname.Value

CFSEARCH variables

A cfsearch operation returns the following variables, where searchname is the name attribute value:

searchname.URL
searchname.Key
searchname.Title
searchname.Score
searchname.Custom1 and Custom2
searchname.Summary
searchname.RecordCount
searchname.CurrentRow
searchname.RecordsSearched
searchname.ColumnList


Standard CGI variables

The CGI variables that are available for your use vary with the web server and configuration. Some of the following variables may not be available.

This section lists the following CGI 1.1 variables that some web servers create when a CGI script is called:

  • Request
  • Server
  • Client

Request

CGI.AUTH_TYPE
CGI.CONTENT_LENGTH
CGI.CONTENT_TYPE
CGI.METHOD
CGI.PATH_INFO
CGI.PATH_TRANSLATED
CGI.QUERY_STRING
CGI.REMOTE_ADDR
CGI.REMOTE_HOST
CGI.REMOTE_USER
CGI.REQUEST_METHOD
CGI.SCRIPT_NAME

Server

CGI.GATEWAY_INTERFACE
CGI.SERVER_NAME
CGI.SERVER_PORT
CGI.SERVER_PROTOCOL
CGI.SERVER_SOFTWARE

Client

CGI.CERT_ISSUER
CGI.CERT_SUBJECT
CGI.CLIENT_CERT_ENCODED
CGI.HTTP_ACCEPT
CGI.HTTP_IF_MODIFIED_SINCE
CGI.HTTP_USER_AGENT

The CERT_ISSUER, CERT_SUBJECT, CLIENT_CERT_ENCODED variables are available only when you use client certificates.


CGI environment variables

When a browser makes a request to a server, the web server and the browser create environment variables. In ColdFusion, these variables are referred to as CGI environment variables. They take the CGI prefix regardless of whether the server uses a server API or CGI to communicate with the ColdFusion server.

Environment variables contain data about the transaction between the browser and the server, such as the IP Address, browser type, and authenticated username. You can reference CGI environment variables for a given page request anywhere in the page. CGI variables are read-only.

Note: The environment variables available to applications depend on the browser and server software.

This section describes the following topics:

  • Testing for CGI variables
  • CGI server variables
  • CGI client variables
  • CGI client certificate variables

Testing for CGI variables

Because some browsers do not support some CGI variables, ColdFusion always returns True when it tests for the existence of a CGI variable, regardless of whether the browser supports the variable. To determine if the CGI variable is available, test for an empty string, as shown in the following example:

<cfif CGI.varname IS NOT "">
    CGI variable exists
<cfelse>
    CGI variable does not exist
</cfif>

CGI server variables

The following table describes common CGI environment variables that the server creates (some of these are not available with some servers):

CGI server variable | Description
SERVER_SOFTWARE | Name and version of the information server software answering the request (and running the gateway). Format: name/version.
SERVER_NAME | Server's hostname, DNS alias, or IP address as it appears in self-referencing URLs.
GATEWAY_INTERFACE | CGI specification revision with which this server complies. Format: CGI/revision.
SERVER_PROTOCOL | Name and revision of the information protocol this request came in with. Format: protocol/revision.
SERVER_PORT | Port number to which the request was sent.
REQUEST_METHOD | Method with which the request was made. For HTTP, this is Get, Head, Post, and so on.
PATH_INFO | Extra path information, as given by the client. Scripts can be accessed by their virtual pathname, followed by extra information at the end of this path. The extra information is sent as PATH_INFO.
PATH_TRANSLATED | Translated version of PATH_INFO after any virtual-to-physical mapping.
SCRIPT_NAME | Virtual path to the script that is executing; used for self-referencing URLs.
QUERY_STRING | Query information that follows the ? in the URL that referenced this script.
REMOTE_HOST | Hostname making the request. If the server does not have this information, it sets REMOTE_ADDR and does not set REMOTE_HOST.
REMOTE_ADDR | IP address of the remote host making the request.
AUTH_TYPE | If the server supports user authentication, and the script is protected, the protocol-specific authentication method used to validate the user.
REMOTE_USER AUTH_USER | If the server supports user authentication, and the script is protected, the username the user has authenticated as. (Also available as AUTH_USER.)
REMOTE_IDENT | If the HTTP server supports RFC 931 identification, this variable is set to the remote username retrieved from the server. Use this variable for logging only.
CONTENT_TYPE | For queries that have attached information, such as HTTP POST and PUT, this is the content type of the data.
CONTENT_LENGTH | Length of the content as given by the client.

CGI client variables

The following table describes common CGI environment variables the browser creates and passes in the request header:

CGI client variable | Description
HTTP_REFERER | The referring document that linked to or submitted form data.
HTTP_USER_AGENT | The browser that the client is currently using to send the request. Format: software/version library/version.
HTTP_IF_MODIFIED_SINCE | The last time the page was modified. The browser determines whether to set this variable, usually in response to the server having sent the LAST_MODIFIED HTTP header. It can be used to take advantage of browser-side caching.

CGI client certificate variables

ColdFusion makes available the following client certificate data. These variables are available when running Microsoft IIS 4.0 or Netscape Enterprise under SSL if your web server is configured to accept client certificates.

CGI client certificate variable

Description

CERT_SUBJECT

Client-specific information provided by the web server. This data typically includes the client's name, e-mail address, and so on; for example:

O = "VeriSign, Inc.", OU = VeriSign Trust Network, OU = "www.verisign.com/repository/RPA Incorp. by Ref.,LIAB.LTD(c)98", OU = Persona Not Validated, OU = Digital ID Class 1 - Microsoft, CN = Matthew Lund, E = mlund@macromedia.com

CERT_ISSUER

Information about the authority that provided the client certificate; for example:

O = "VeriSign, Inc.", OU = VeriSign Trust Network, OU = "www.verisign.com/repository/RPA Incorp. By Ref.,LIAB.LTD(c)98", CN = VeriSign Class 1 CA Individual Subscriber-Persona Not Validated

CLIENT_CERT_ENCODED

The entire client certificate binary, base-64 encoded. This data is typically of interest to developers, so they can integrate with other software that uses client certificates.

Previous


ColdFusion Tags

ColdFusion Markup Language (CFML) includes a set of tags that you use in Macromedia ColdFusion MX 7 pages to interact with data sources, manipulate data, and display output. CFML tag syntax is similar to HTML element syntax.

This chapter contains categorized and alphabetical lists of the tags followed by the detailed tag descriptions.

Contents

Tag summary

Tags by function

Tag changes since ColdFusion 5

Tag descriptions

Tag summary

The following table briefly describes CFML tags:

CFML tag | Category | Description
cfabort | Flow-control tags | Stops the processing of a ColdFusion page at the tag location
cfapplet | Forms tags | Embeds Java applets in a cfform tag
cfapplication | Application framework tags | Defines an application name; activates client variables; specifies client variable storage mechanism
cfargument | Extensibility tags | Creates a parameter definition within a component definition; defines a function argument
cfassociate | Application framework tags | Enables subtag data to be saved with a base tag
cfbreak | Flow-control tags | Breaks out of a CFML looping construct
cfcache | Page processing tags | Caches ColdFusion pages
cfcalendar | Forms tags | Provides a calendar from which to select a date
cfcase | Flow-control tags | Used with the cfswitch and cfdefaultcase tags
cfcatch | Exception handling tags, Flow-control tags | Catches exceptions in ColdFusion pages
cfchart | Data output tags | Generates and displays a chart
cfchartdata | Data output tags | Defines chart data points
cfchartseries | Data output tags | Defines style in which chart data displays
cfcol | Data output tags | Defines table column header, properties
cfcollection | Extensibility tags | Administers Verity collections
cfcomponent | Extensibility tags | Creates and defines a component object
cfcontent | Data output tags, Page processing tags | Defines content type and filename of a file to be downloaded by current page
cfcookie | Variable manipulation tags | Defines and sets cookie variables, including expiration and security options
cfdefaultcase | Flow-control tags | Receives control if there is no matching cfcase tag value
cfdirectory | File management tags | Performs typical directory-handling tasks from within a ColdFusion application
cfdocument | Data output tags | Creates PDF or FlashPaper output from a text block containing CFML and HTML
cfdocumentitem | Data output tags | Specifies action items, such as header, footer, and page break, for a PDF or FlashPaper document
cfdocumentsection | Data output tags | Divides a PDF or FlashPaper document into sections
cfdump | Debugging tags, Variable manipulation tags | Outputs variables for debugging
cfelse | Flow-control tags | Creates IF-THEN-ELSE constructs
cfelseif | Flow-control tags | Creates IF-THEN-ELSE constructs
cferror | Exception handling tags, Application framework tags | Displays custom HTML error pages when errors occur
cfexecute | Flow-control tags, Extensibility tags | Executes developer-specified process on server computer
cfexit | Flow-control tags | Aborts processing of executing CFML tag
cffile | File management tags | Performs typical file-handling tasks from within ColdFusion application
cfflush | Data output tags, Page processing tags | Flushes currently available data to client
cfform | Forms tags | Builds input form; performs client-side input validation
cfformgroup | Forms tags | Groups form control into a containing object
cfformitem | Forms tags | Adds text and dividing rules to Flash forms
cfftp | Forms tags, Extensibility tags, Internet Protocol tags | Permits FTP file operations
cffunction | Extensibility tags | Defines function that you build in CFML
cfgrid | Forms tags | Displays tabular grid control, in cfform tag
cfgridcolumn | Forms tags | Used in cfform; defines columns in a cfgrid
cfgridrow | Forms tags | Defines a grid row; used with cfgrid
cfgridupdate | Forms tags | Directly updates ODBC data source from edited grid data
cfheader | Data output tags, Page processing tags | Generates HTTP headers
cfhtmlhead | Page processing tags | Writes text and HTML to HEAD section of page
cfhttp | Internet Protocol tags | Performs GET and POST to upload file or post form, cookie, query, or CGI variable directly to server
cfhttpparam | Internet Protocol tags | Specifies parameters required for a cfhttp POST operation; used with cfhttp
cfif | Flow-control tags | Creates IF-THEN-ELSE constructs
cfimport | Application framework tags | Imports JSP tag libraries into a CFML page
cfinclude | Flow-control tags | Embeds references to ColdFusion pages
cfindex | Extensibility tags | Creates Verity search indexes
cfinput | Forms tags | Creates an input element (radio button, check box, text entry box); used in cfform
cfinsert | Database manipulation tags | Inserts records in a data source
cfinvoke | Extensibility tags | Invokes component methods from a ColdFusion page or component
cfinvokeargument | Extensibility tags | Passes a parameter to a component method or a web service
cfldap | Internet Protocol tags | Provides access to LDAP directory servers
cflocation | Flow-control tags | Controls execution of a page
cflock | Application framework tags | Ensures data integrity and synchronizes execution of CFML code
cflog | Data output tags, Other tags | Writes a message to a log file
cflogin | Security tags | Defines a container for user login and authentication code
cfloginuser | Security tags | Identifies an authenticated user to ColdFusion
cflogout | Security tags | Logs the current user out
cfloop | Flow-control tags | Repeats a set of instructions based on conditions
cfmail | Internet Protocol tags | Assembles and posts an e-mail message
cfmailparam | Internet Protocol tags | Attaches a file or adds a header to an e-mail message
cfmailpart | Internet Protocol tags | Contains one part of a multi-part mail message
cfmodule | Application framework tags | Invokes a custom tag for use in a ColdFusion page
cfNTauthenticate | Security tags | Authenticates user information against an NT domain
cfobject | Extensibility tags | Creates COM, component, CORBA, Java, and web service objects
cfobjectcache | Database manipulation tags | Flushes the query cache
cfoutput | Data output tags | Displays the output of a database query or other operation
cfparam | Variable manipulation tags | Defines a parameter and its default value
cfpop | Internet Protocol tags | Gets and deletes messages from POP mail server
cfprocessingdirective | Data output tags | Suppresses white space and other output
cfprocparam | Database manipulation tags | Holds parameter information for stored procedure
cfprocresult | Database manipulation tags | Result set name that ColdFusion tags use to access result set of a stored procedure
cfproperty | Extensibility tags | Defines components
cfquery | Database manipulation tags | Passes SQL statements to a database
cfqueryparam | Database manipulation tags | Checks data type of a query parameter
cfregistry | Other tags, Variable manipulation tags | Reads, writes, and deletes keys and values in a Windows system registry
cfreport | Exception handling tags | Embeds a ColdFusion Report Builder or Crystal Reports report
cfreportparam | Exception handling tags | Passes an input parameter to a ColdFusion Report Builder report
cfrethrow | Exception handling tags | Rethrows currently active exception
cfreturn | Extensibility tags | Returns results from a component method
cfsavecontent | Variable manipulation tags | Saves generated content inside tag body in a variable
cfschedule | Variable manipulation tags | Schedules page execution; optionally, produces static pages
cfscript | Application framework tags | Encloses a set of cfscript statements
cfsearch | Extensibility tags | Executes searches against data indexed in Verity collections, using cfindex
cfselect | Forms tags | Creates a drop-down list box form element; used in cfform tag
cfset | Variable manipulation tags | Defines a variable
cfsetting | Other tags, Variable manipulation tags | Defines and controls ColdFusion settings
cfsilent | Data output tags, Page processing tags | Suppresses CFML output within tag scope
cfslider | Forms tags | Creates slider control; used in cfform
cfstoredproc | Database manipulation tags | Holds database connection information; identifies a stored procedure to execute
cfswitch | Flow-control tags | Evaluates passed expression; passes control to matching cfcase tag
cftable | Data output tags | Builds a table in a ColdFusion page
cftextarea | Forms tags | Puts a multiline text box in a form
cfthrow | Exception handling tags, Flow-control tags | Throws a developer-specified exception
cftimer | Debugging tags | Displays execution time for a block of code
cftrace | Debugging tags | Displays and logs application debugging data
cftransaction | Database manipulation tags | Groups cfquery operations into one transaction; performs rollback processing
cftree | Forms tags | Creates tree control element; used in cfform
cftreeitem | Forms tags | Populates a tree control element in a form; used with cftree
cftry | Exception handling tags, Flow-control tags | Catches exceptions in ColdFusion pages
cfupdate | Database manipulation tags | Updates rows in a database data source
cfwddx | Extensibility tags | Serializes and de-serializes CFML data structures to XML-based WDDX format
cfxml | Extensibility tags | Creates an XML document object
Next


Tags by function

The following tables list Tags by their function or purpose.

Application framework tags

Database manipulation tags

Data output tags

Debugging tags

Exception handling tags

Extensibility tags

File management tags

Flow-control tags

Forms tags

Internet Protocol tags

Page processing tags

Security tags

Variable manipulation tags

Other tags


Application framework tags

cfapplication | cfimport | cfscript
cfassociate | cflock |
cferror | cfmodule |


Database manipulation tags

cfinsert | cfprocresult | cfstoredproc
cfobjectcache | cfquery | cftransaction
cfprocparam | cfqueryparam | cfupdate


Data output tags

cfchart | cfdocumentitem | cfoutput
cfchartdata | cfdocumentsection | cfprocessingdirective
cfchartseries | cfflush | cfreport
cfcol | cfheader | cfreportparam
cfcontent | cflog | cfsilent
cfdocument | cfoutput | cftable


Debugging tags

cfdump

cftimer

cftrace


Exception handling tags

cfcatch | cfrethrow | cftry
cferror | cfthrow |


Extensibility tags

cfchart | cffunction | cfreportparam
cfchartdata | cfindex | cfreturn
cfchartseries | cfinvoke | cfsearch
cfcollection | cfinvokeargument | cfwddx
cfcomponent | cfobject | cfxml
cfexecute | cfproperty |
cfftp | cfreport |


File management tags

cfdirectory

cffile

cfftp


Flow-control tags

cfabort | cfexecute | cfrethrow
cfbreak | cfexit | cfswitch
cfcase | cfif | cfthrow
cfdefaultcase | cfinclude | cftry
cfelse | cflocation |
cfelseif | cfloop |


Forms tags

cfapplet | cfgrid | cfselect
cfcalendar | cfgridcolumn | cfslider
cfform | cfgridrow | cftextarea
cfformgroup | cfgridupdate | cftree
cfformitem | cfinput | cftreeitem


Internet Protocol tags

cfftp | cfldap | cfmailpart
cfhttp | cfmail | cfpop
cfhttpparam | cfmailparam |


Page processing tags

cfcache | cfheader | cfprocessingdirective
cfcontent | cfhtmlhead | cfsetting
cfflush | cfinclude | cfsilent


Security tags

cflogin | cflogout
cfloginuser | cfNTauthenticate


Variable manipulation tags

cfcookie | cfregistry | cfset
cfdump | cfsavecontent | cfsetting
cfparam | cfschedule |


Other tags

cflog

cfregistry


Tag changes since ColdFusion 5

The following tables list Tags, attributes, and values that have changed since ColdFusion 5.0 and indicate the specific release in which the change was made.

New tags, attributes, and values

Deprecated tags, attributes, and values

Obsolete tags, attributes, and values


New tags, attributes, and values

This table lists tags, attributes, and attribute values that have been added since the ColdFusion MX release:

Tag | Attribute or value | Added in this ColdFusion release
cfapplication | scriptProtect | ColdFusion MX 7
 | loginStorage | ColdFusion MX 6.1
cfargument | xml value of type attribute | ColdFusion MX 7
 | All | ColdFusion MX
cfcache | cachedirectory, timespan attributes | ColdFusion MX
cfcalendar | All | ColdFusion MX 7
cfchart | style , title attributes | ColdFusion MX 7
 | xAxisType, yAxisType attributes | ColdFusion MX 6.1
 | All | ColdFusion MX
cfchartdata | All | ColdFusion MX
cfchartseries | datalabelstyle attribute | ColdFusion MX 7
 | column value of type attribute
 | All | ColdFusion MX
cfcollection | categories attribute | ColdFusion MX 7
 | New values of the language attribute
 | list and categoryList values of action attribute
 | name attribute | ColdFusion MX
cfcomponent | style, namespace, serviceportname, porttypename, wsdlfile, and bindingname attributes | ColdFusion MX 7
 | Extended functionality for the hint and displayname attributes when publishing document-literal style web services
 | All | ColdFusion MX
cfcontent | variable attribute | ColdFusion MX 7
cfdirectory | recurse attribute for list and delete actions | ColdFusion MX 7
cfdocument | All | ColdFusion MX 7
cfdocumentitem | All | ColdFusion MX 7
cfdocumentsection | All | ColdFusion MX 7
cfexecute | variable attribute | ColdFusion MX 6.1
cffile | result attribute for upload action | ColdFusion MX 7
 | fixnewline attribute for action="append" and action="write"
cfform | name and action attributes are optional | ColdFusion MX 7
 | accessible, format, height, width , method, onError, preloader, scriptsrc, skin, style, timeout, wMode attributes
 | onReset event
cfformgroup | All | ColdFusion MX 7
cfformitem | All | ColdFusion MX 7
cfftp | result attribute | ColdFusion MX 7
cffunction | description attributes | ColdFusion MX 7
 | All | ColdFusion MX
cfgrid | format attribute and support for Flash and XML output enabled, onChange, style, tooltip, visible attributes (Flash format only) | ColdFusion MX 7
cfgridcolumn | mask attribute | ColdFusion MX 7
 | currency value of type attribute | ColdFusion MX 7
cfhttp | result attribute | ColdFusion MX 7
 | HEAD, PUT, DELETE, OPTIONS, and TRACE values of method attribute | ColdFusion MX 6.1
 | multipart, getasbinary, proxyUser, proxyPassword attributes
 | charset,firstrowasheaders attributes | ColdFusion MX
cfhttpparam | header and body values of type attribute | ColdFusion MX 6.1
 | encoded, mimeType attributes
cfimport | All | ColdFusion MX
cfindex | custom3, custom4, category, and categorytree attributes for update and refresh actions | ColdFusion MX 7
 | status attribute for Update, Refresh, Delete, Purge actions
 | New values of the language attribute
cfinput | height and width attributes (all except checkbox and radiobutton) | ColdFusion MX 7
 | bind attribute (text and password)
 | label attribute (all but radiobutton, image, reset, and submit)
 | mask attribute (text only)
 | validateAt attribute (all but radiobutton, image, reset, and submit)
 | datefield, button, file, hidden, image, reset, and submit values of type attribute
 | daynames and monthnames attributes (type="datefield" only)
 | boolean, email, guid, maxlength noblanks, range, submitOnce, URL, USdate, and uuid values of the validate attribute
 | tooltip, visible, and enabled attributes (Flash forms only)
 | src attribute (image only)
cfinvoke | servicePort attribute for web services | ColdFusion MX 7
 | All | ColdFusion MX
cfinvokeargument | omit attribute | ColdFusion MX 7
 | All | ColdFusion MX
cfldap | returnAsBinary attribute | ColdFusion MX 7
cflogin | All | ColdFusion MX
cfloginuser | All | ColdFusion MX
cflogout | All | ColdFusion MX
cfmail | spoolEnable attribute | ColdFusion MX
 | charset, failto, replyTo, userName, password, wrapText attributes | ColdFusion MX 6.1
cfmailparam | contentID, dispositionattributes | ColdFusion MX 7
 | type attribute | ColdFusion MX 6.1
cfmailpart | All | ColdFusion MX 6.1
cfNTauthenticate | All | ColdFusion MX 7
cfobject | All | ColdFusion MX
cfobjectcache | All | ColdFusion MX
cfparam | min, max, pattern attributes | ColdFusion MX 7
 | creditcard, email, eurodate, float, integer, range, regex, regular_expression, ssn, social_security_number, time, URL, USdate, XML, zipcode attributes of the type attribute
cfprocessingdirective | pageEncoding attribute | ColdFusion MX
cfproperty | All | ColdFusion MX
cfquery | result attribute | ColdFusion MX 7
cfreturn | All | ColdFusion MX
cfreport | template, format, name, filename, query, overwrite attributes | ColdFusion MX 7
cfreportparam | All | ColdFusion MX 7
cfsearch | category, categoryTree, status, suggestions, contextPassages, contextBytes, contextHighlightBegin, contextHighlightEnd, previousCriteria attributes | ColdFusion MX 7
 | natural, internet, and internet_basic values of type attribute
cfselect | selected attribute can take a list | ColdFusion MX 7
 | enabled, group, height, label, onKeyUp, onKeyDown, onMouseUp, onMouseDown, onChange, onClick, queryPosition, tooltip, visible, and width attributes
cfsetting | requestTimeOut attribute | ColdFusion MX
cfstoredproc | result attribute | ColdFusion MX 7
cftextarea | All | ColdFusion MX 7
cfthrow | object attribute | ColdFusion MX
cftimer | All | ColdFusion MX 7
cftree | format, onChange, style attributes | ColdFusion MX 7
cftrace | All | ColdFusion MX
cfxml | All | ColdFusion MX


Deprecated tags, attributes, and values

The following tags, attributes, and attribute values are deprecated. Do not use them in ColdFusion applications. They might not work, and might cause an error, in releases later than ColdFusion MX.

Tag

Attribute or value

Deprecated as of this ColdFusion release

cfcache

cachedirectory, timeout attributes

ColdFusion MX

cfcollection

map and repair options of the action attribute

ColdFusion MX 7

cferror

monitor option of the exception attribute

ColdFusion MX

cffile

system value for attributes attribute

ColdFusion MX

temporary value for attributes attribute

ColdFusion MX

cfform

passthrough attribute

ColdFusion MX 7

enableCAB attribute

ColdFusion MX

cfftp

agentname attribute

ColdFusion MX

cfgraph

All

ColdFusion MX

cfgraphdata

All

ColdFusion MX

cfgridupdate

connectString, dbName, dbServer, dbType, provider, providerDSN attributes

ColdFusion MX

cfinput

passthrough attribute

ColdFusion MX 7

cfinsert

connectString, dbName, dbServer, dbType, provider, providerDSN attributes

ColdFusion MX

cfldap

filterFile attribute

ColdFusion MX

cflog

date, thread, time attributes

ColdFusion MX

cfquery

connectString, dbName, dbServer, provider, providerDSN, sql attributes

ColdFusion MX

The following dbType attribute values:

dynamic, ODBC, Oracle73, Oracle80, Sybase11, OLEDB, DB2

ColdFusion MX

(The value query is valid.)

cfregistry

All, on UNIX only

ColdFusion MX

cfsearch

external, language attributes

ColdFusion MX

cfselect

passthrough attribute

ColdFusion MX 7

cfservlet

All

ColdFusion MX

cfservletparam

All

ColdFusion MX

cfslider

img, imgStyle, grooveColor, refreshLabel, tickmarkimages, tickmarklabels, tickmarkmajor, tickmarkminor attributes

ColdFusion MX

cfstoredproc

connectString, dbName, dbServer, dbtype, provider, providerDSN attributes

ColdFusion MX

cftextinput

All

ColdFusion MX 7

cfupdate

connectString, dbName, dbServer, dbtype, provider, providerDSN attributes

ColdFusion MX


Obsolete tags, attributes, and values

The following tags, attributes, and attribute values are obsolete. Do not use them in ColdFusion applications. They do not work, and might cause an error, in releases later than ColdFusion 5.

Tag

Attribute or value

Obsolete as of this ColdFusion release

cfauthenticate

All

ColdFusion MX

cfchart

rotated attribute

ColdFusion MX 7

cffile

attributes attribute value archive

ColdFusion MX

cfimpersonate

All

ColdFusion MX

cfindex

action attribute value optimize

ColdFusion MX

external attribute

cfinternaladminsecurity

All

ColdFusion MX

This tag did not appear in CFML Reference.

cfldap

fileterConfig attribute

ColdFusion MX

cfnewinternaladminsecurity

All

ColdFusion MX

This tag did not appear in CFML Reference.

cfsetting

catchExceptionsByPattern attribute

ColdFusion MX

Previous


cfabort

Description

Stops the processing of a ColdFusion page at the tag location. ColdFusion returns everything that was processed before the tag. The tag is often used with conditional logic to stop processing a page when a condition occurs.

Category

Flow-control tags

Syntax

<cfabort
    showError = "error_message">

See also

cfbreak, cfexecute, cfexit, cfif, cflocation, cfloop, cfswitch, cfthrow, cftry; cfabort and cfexit in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
showError | Optional |  | Error to display, in a standard ColdFusion error page, when tag executes.

Usage

When you use the cfabort and cferror tags together, the cfabort tag halts processing immediately; the cferror tag redirects output to a specified page.

If this tag does not contain a showError attribute value, processing stops when the tag is reached and ColdFusion returns the page contents up to the line that contains the cfabort tag.

When you use this tag with the showError attribute, but do not define an error page using cferror, page processing stops when the cfabort tag is reached. The message in showError displays to the client.

When you use this tag with the showError attribute and an error page using cferror, ColdFusion redirects output to the error page specified in the cferror tag.

Example

This example shows the use of cfabort to stop processing. In the second example, where cfabort is used, the result never displays.

<h3>Example A: Let the instruction complete itself</h3>
<!--- first, set a variable --->
<cfset myVariable = 3>
<!--- now, perform a loop that increments this value --->
<cfloop from = "1" to = "4" index = "Counter">
    <cfset myVariable = myVariable + 1>
</cfloop>

<cfoutput>
<p>	The value of myVariable after incrementing through the loop #Counter# times is:
#myVariable#
</cfoutput>

<h3>Example B: Use cfabort to halt the instructions with showmessage attribute and cferror</h3>
<!--- Reset the variable and show the use of cfabort. --->
<cfset myVariable = 3>
<!--- now, perform a loop that increments this value --->
<cfloop from = "1" to = "4" index = "Counter">
<!--- on the second time through the loop, cfabort --->
    <cfif Counter is 2>
    <!--- Take out the cferror line to see cfabort error processed by CF error page --->
        <cferror type="request" template="request_err.cfm">
        <cfabort showerror="CFABORT has been called for no good reason">
<!--- Processing is stopped, and subsequent operations are not carried out.--->
    <cfelse>
        <cfset myVariable = myVariable + 1>
    </cfif>
</cfloop>

<cfoutput>
<p> The value of myVariable after incrementing through the loop#counter# times is: #myVariable#
</cfoutput>
Next


cfapplet

Description

This tag references a registered custom Java applet. To register a Java applet, in the ColdFusion Administrator, click Extensions > Java Applets.

Using this tag within a cfform tag is optional. If you use it within cfform, and the method attribute is defined in the Administrator, the return value is incorporated into the form.

Category

Forms tags

Syntax

<cfapplet
    appletSource = "applet_name"
    name = "form_variable_name"
    height = "height_in_pixels"
    width = "width_in_pixels"
    vSpace = "space_above_and_below_in_pixels"
    hSpace = "space_on_each_side_in_pixels"
    align = "alignment_option"
    notSupported = "message_to_display_for_nonJava_browser"
    param_1 = "applet_parameter_name"
    param_2 = "applet_parameter_name"
    param_n = "applet_parameter_name">

See also

cfform , cfformgroup , cfformitem , cfgrid , cfinput , cfobject , cfselect , cfservlet , cfslider , cftextarea , cftree

History

ColdFusion MX:

  • Removed the requirement that you use this tag within a cfform tag.
  • Changed the behavior when this tag is used within a cfform tag; if the method attribute is defined in the Administrator, the return value of the applet’s method is incorporated into the form.

Attributes

Attribute

Req/Opt

Default

Description

appletSource

Required

Name of registered applet

name

Required

Form variable name for applet

height

Optional

Height of applet, in pixel

width

Optional

Width of applet, in pixels

vSpace

Optional

Space above and below applet, in pixels

hSpace

Optional

Space on left and right of applet, in pixels

align

Optional

Alignment:

  • Left
  • Right
  • Bottom
  • Top
  • TextTop
  • Middle
  • AbsMiddle
  • Baseline
  • AbsBottom

notSupported

Optional

See Description

Text to display if a page that contains a Java applet-based cfform control is opened by a browser that does not support Java or has Java support disabled. For example:

notSupported = "<b>Browser must support Java to view

ColdFusion Java Applets</b>"

Default:

<b>Browser must support Java to<br> view ColdFusion Java Applets!</b>

param_n

Optional

Registered parameter for applet. Specify only to override values for applet in ColdFusion Administrator.

Usage

You can specify the applet method attribute only in the Administrator, Java Applets view. For other attributes, you can accept the default values in the Administrator view, or specify values in this tag and override the defaults.

If Java applet components are stored in a JAR file, enter the filename in the ColdFusion Administrator, Java Applets window, Archive text box. For more information, see Embedding Java applets in Building Dynamic Forms with cfform Tags in ColdFusion MX Developer’s Guide

Example

<p>cfapplet lets you reference custom Java applets that have been
    registered using the ColdFusion Administrator.
<p>To register a Java applet, open the ColdFusion Administrator and
    click "Applets" link under "extensions" section.
<p>This example applet copies text that you type into a form. Type
    some text, and then click "copy" to see the copied text.

<cfform action = "index.cfm">
    <cfapplet appletsource = "copytext" name = "copytext">
</cfform>


cfapplication

Description

Defines the scope of a ColdFusion application; enables and disables storage of Client variables; specifies the Client variable storage mechanism; enables Session variables; and sets Application variable timeouts.

Category

Application framework tags

Syntax

<cfapplication
    name = "application_name"
    loginStorage = "cookie" or "session"
    clientManagement = "yes" or "no"
    clientStorage = "datasource_name" or "Registry" or "Cookie"
    setClientCookies = "yes" or "no"
    sessionManagement = "yes" or "no"
    sessionTimeout = #CreateTimeSpan(days, hours, minutes, seconds)#
    applicationTimeout = #CreateTimeSpan(days, hours, minutes, seconds)#
    setDomainCookies = "yes" or "no"
    scriptProtect = "none", "all", or list>

See also

cfassociate, cferror, cflock, cfmodule; Application.CFC Reference; Designing and Optimizing a ColdFusion Application and Integrating J2EE and Java Elements in CFML Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added scriptProtect attribute

ColdFusion MX 6.1: Added loginStorage attribute

ColdFusion MX:

  • Changed how persistent scopes are available: Server, Session, and Application scope variables are stored in memory as structures. In earlier releases, only Session and Application scope variables were stored this way. You cannot access the UDF function scope as a structure.
  • Changed the algorithm for setting the CFTOKEN variable value: if the registry key UUIDToken is a non-zero value, ColdFusion uses a number constructed from the UUID plus a random number. Otherwise, ColdFusion sets the CFTOKEN variable default value using a positive random integer. (In earlier releases, ColdFusion always used a number constructed from the UUID plus a random number.)

Attributes

Attribute

Req/Opt

Default

Description

name

See Description

Name of application. Up to 64 characters.

For Application and Session variables: Required.

For Client variables: Optional

loginStorage

Optional

cookie
  • cookie: store login information in the Cookie scope.
  • session: store login information in the Session scope.

clientManagement

Optional

no
  • yes: enables client variables.
  • no

clientStorage

Optional

registry

How client variables are stored:

  • datasource_name: in ODBC or native data source. You must create storage repository in the Administrator.
  • registry: in the system registry.
  • cookie: on client computer in a cookie. Scalable. If client disables cookies in the browser, client variables do not work.

setClientCookies

Optional

yes
  • yes: enables client cookies.
  • no: ColdFusion does not automatically send CFID and CFTOKEN cookies to client browser; you must manually code CFID and CFTOKEN on the URL for every page that uses Session or Client variables.

sessionManagement

Optional

no
  • yes: enables session variables.
  • no

sessionTimeout

Optional

Specified in Variables page of ColdFusion Administrator

Lifespan of session variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas.

applicationTimeout

Optional

Specified in Variables page of ColdFusion Administrator

Lifespan of application variables. CreateTimeSpan function and values in days, hours, minutes, and seconds, separated by commas.

setDomainCookies

Optional

no
  • yes: uses domain cookies for CFID and CFTOKEN cookies and for all Client variables when using cookies for client variable storage. Required for applications running on clusters.
  • no: uses host-specific cookies for CFID, CFTOKEN, and all client variable cookies.

scriptProtect

Optional

Determined by ColdFusion MX Administrator Enable Global Script Protection setting

Specifies whether to protect variables from cross-site scripting attacks

  • none: do not protect variables
  • all: protect Form, URL, CGI, and Cookie variables
  • comma-delimited list of ColdFusion scopes: Protect variables in the specified scopes.

For more information, see Usage.

Usage

This tag is typically used in the Application.cfm file, to set defaults for a ColdFusion application.

Note: You can also set the application defaults in the Application.cfc file. For more information, see Application variables.

This tag enables application variables, unless they are disabled in the ColdFusion Administrator. The Administrator setting also overrides the sessionManagement attribute. For more information, see Configuring and Administering ColdFusion MX.

If ColdFusion is running on a cluster, you must specify clientStorage = "cookie" or a data source name; you cannot specify "registry".

ColdFusion generates an error if the application name is longer than 64 characters.

The CFTOKEN variable is 8 bytes in length. Its range is 10000000 --99999999.

Note: If you specify ClientStorage=cookie, any Client scope variables set following a cfflush tag are not saved in the Client browser.

Protecting variables from cross-site scripting attacks

The ScriptProtect attribute lets you protect one or more variable scopes from cross-site scripting attacks, where a client attempts to get your application to send malicious code back to a user’s browser. In these attacks, user input (for example, from form fields or from URL variables) sets a CF variable which is destined for user output. The submitted data includes malicious code, such as JavaScript or an applet or object reference, which then executes on the user’s system.

Note: The ColdFusion MX Administrator Settings page Enable Global Script Protection option determines the default script protection setting. You can use the scriptProtect attribute to override the Administrator setting. You can also use the Application.cfc initialization code to set the protection value.

The ColdFusion MX cross-site scripting protection operation is done when ColdFusion MX processes the application settings at the beginning of a request. Thus, it can process the URL, and Cookie, CGI, and Form variables in a user’s request. By default, it replaces occurrences of the following tag names with the text InvalidTag: object, embed, script, applet, and meta. It allows these names in plain text, replaces the words if they are used as tag names.

You can specify any or all ColdFusion scopes for protection, but only the Form, URL, CGI, and Cookie scopes have variables that are often provided by unknown sources. Also, protecting a scope requires additional processing. For these reasons, the all attribute value applies protection to only the four scopes.

The script protection mechanism applies a regular expression that is defined in the cf_root/lib/neo-security.xml file in the server configuration, or the cf_root/WEB-INF/cfusion/lib/neo-security.xml file in the J2EE configuration to the variable value. You can customize the patterns that ColdFusion replaces by modifying the regular expression in the CrossSiteScriptPatterns variable.

Locking server, application, and session variables

When you set or update variables in the server, application, and session scopes, use the cflock tag with the scope attribute set to the following value:

  • For server variables, specify "server"
  • For application variables, specify "application"
  • For session variables, specify "session"

In some cases, you should also lock code that reads variables in these scopes. For information about locking scopes, see cflock.

Example

<!--- This example shows how to use cflock to prevent race conditions during data updates to variables in Application, Server, and Session scopes. --->
<h3>cfapplication Example</h3>
<p>cfapplication defines scoping for a ColdFusion application and enables or disables application and/or session variable storage. This tag is placed in a special file called Application.cfm that automatically runs before any other CF page in a directory (or subdirectory) where the Application.cfm file appears.</p>

<cfapplication name = "ETurtle"
sessionTimeout = #CreateTimeSpan(0, 0, 0, 60)#
sessionManagement = "Yes">

<!--- Initialize session and application variables used by E-Turtleneck. --->
<cfparam name="application.number" default="1">
<cfparam name="session.color" default= "">
<cfparam name="session.size" default="">

<cfif IsDefined("session.numPurchased") AND IsNumeric(trim(session.cartTotal))>
<!--- Use the application scope for the application variable to prevent race condition. This variable keeps track of total number of turtlenecks sold. --->
    <cflock scope = "Application" timeout = "30" type = "Exclusive">
    <cfset application.number = application.number + session.numPurchased>
    </cflock>
</cfif>

<cfoutput>
E-Turtleneck is proud to say that we have sold #application.number# turtlenecks to date.
</cfoutput>
<!--- End of Application.cfm --->


cfargument

Description

Creates a parameter definition within a component definition. Defines a function argument. Used within a cffunction tag.

Category

Extensibility tags

Syntax

<cfargument
    name="string"
    type="data type"
    required="yes" or "no"
    default="default value"
    displayname="descriptive name"
    hint="extended description"	>

See also

cfcomponent , cffunction , cfinvoke , cfinvokeargument , cfobject , cfproperty , cfreturn

Attributes

Attribute

Req/Opt

Default

Description

name

Required

String; an argument name.

type

Optional

any

String; a type name; data type of the argument.

  • any
  • array
  • binary
  • boolean
  • date
  • guid: the argument must be a UUID or GUID of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where each x is a character representing a hexadecimal number (0-9A-F).
  • numeric
  • query
  • string
  • struct
  • uuid: the argument must be a ColdFusion UUID of the form xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx where each x is a character representing a hexadecimal number (0-9A-F).
  • variableName: a string formatted according to ColdFusion variable naming conventions.
  • xml: XML objects and XML strings
  • a component name: if the type attribute value is not one of the preceding items, ColdFusion treats it as the name of a ColdFusion component. When the function executes, it generates an error if the argument that is passed in is not a CFC with the specified name.

required

Optional

no

Note: All arguments are required when invoked as a web service, irrespective of how they are defined.

Specifies whether the parameter is required to execute the component method. The parameter is not required if you specify a default attribute.

  • true or "yes"
  • false or "no"

default

Optional

If no argument is passed, specifies a default argument value.

displayname

Optional

name attribute value

Meaningful only for CFC method parameters. A value to be displayed when using introspection to show information about the CFC.

hint

Optional

Meaningful only for CFC method parameters. Text to be displayed when using introspection to show information about the CFC. The hint attribute value follows the displayname attribute value in the parameter description line. This attribute can be useful for describing the purpose of the parameter.

Usage

This tag must be in a cffunction tag, before any other tags in the cffunction tag body.

Arguments that are passed when a method is invoked can be accessed from the method body in the following ways:

  • With shorthand syntax: #myargument#
    (This example accesses the argument myargument.)
  • Using the arguments scope as an array: #arguments[1]#
    (This example accesses the first defined argument in the cffunction.)
  • Using the arguments scope as a struct: #arguments.myargument#
    (This example accesses the argument myargument in the array.)

Example

<!--- This example defines a function that takes a course number parameter and returns the course description. --->
<cffunction name="getDescription">
    <!--- Identify argument --->
    <cfargument name="Course_Number" type="numeric" required="true">
    <!--- Use the argument to get a course description from the database --->
    <cfquery name="Description" datasource="cfdocexamples">
        SELECT Descript
        FROM Courses
        WHERE Number = '#Course_Number#'
    </cfquery>
    <!--- Specify the variable that the function returns --->
    <cfreturn Description.Descript>
</cffunction>


cfassociate

Description

Allows subtag data to be saved with a base tag. Applies only to custom tags.

Category

Application framework tags

Syntax

<cfassociate
    baseTag = "base_tag_name"
    dataCollection = "collection_name">

See also

cfapplication , cferror , cflock , cfmodule; High-level data exchange in Creating and Using Custom CFML Tags in ColdFusion MX Developer’s Guide.

Attributes

Attribute | Req/Opt | Default | Description
baseTag | Required |  | Base tag name.
dataCollection | Optional | AssocAttribs | Structure in which base tag stores subtag data.

Usage

Call this tag within a subtag, to save subtag data in the base tag.

When ColdFusion passes subtag attributes back to the base tag, it saves them in a structure whose default name is AssocAttribs. To segregate subtag attributes (in a base tag that can have multiple subtags), specify a structure name, in the dataCollection attribute. The structure is appended to an array whose name is thistag.collectionName.

Within the custom tag code, the attributes passed to the tag by using the attributeCollection attribute are saved as independent values, with no indication that they are grouped into a structure by the custom tag’s caller. Therefore, in the called tag, if you assign a value to a specific attribute, it replaces the value passed in the attributeCollection attribute that you used when calling the subtag.

Example

<!--- Find the context. --->
<cfif thisTag.executionMode is "start">
 <!--- Associate attributes. --->
 <cfassociate baseTag = "CF_TAGBASE">

 <!--- Define defaults for attributes. --->
 <cfparam name = "attributes.happy" default = "yes">
 <cfparam name = "attributes.sad" default = "no">
...


cfauthenticate

Description

This tag is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide.

History

ColdFusion MX: this tag is obsolete. It does not work in ColdFusion MX and later releases.


cfbreak

Description

Used within a cfloop or cfswitch tag. Breaks out of a loop or switch block.

Category

Flow-control tags

Syntax

<cfbreak>

See also

cfabort, cfexecute, cfif, cflocation, cfloop, cfswitch, cfthrow, cftry; cfloop and cfbreak in Elements of CFML in ColdFusion MX Developer’s Guide

Example

<!--- This shows the use of cfbreak to exit a loop when a condition is met.--->
<!--- Select courses; use cfloop to find a condition; then break the loop. --->
<!--- Check that number is numeric. --->
<cfif IsDefined("form.course_number")>
    <cfif Not IsNumeric(form.course_number)>
        <cfabort>
    </cfif>
</cfif>
<cfquery name="GetCourses" datasource="cfdocexamples">
    SELECT *
    FROM Courses
    ORDER by course_number
</cfquery>

<p> This example uses CFLOOP to cycle through a query to find a value.
(In our example, a list of values corresponding to courses in the Snippets
datasource). When the conditions of the query are met, CFBREAK stops the loop.
<p> Please enter a Course Number, and hit the "submit" button:
<form action="cfbreak.cfm" method="POST">
    <select name="courseNum">
        <cfoutput query="GetCourses">
            <option value="#course_number#">#course_number#
        </cfoutput>
    </select>
    <input type="Submit" name="" value="Search on my Number">
</form>
<!--- If the courseNum variable is not defined,
        don't loop through the query.--->
<cfif IsDefined ("form.courseNum") IS "True">
<!--- Loop through query until value found, then use CFBREAK to exit query.--->
    <cfloop query="GetCourses">
        <cfif GetCourses.course_number IS form.courseNum>
            <cfoutput>
                <h4>Your Desired Course was found:</h4>
                <pre>#course_number# #descript#</pre>
            </cfoutput>
            <cfbreak>
        <cfelse>
            <br> Searching...
        </cfif>
    </cfloop>
</cfif>


cfcache

Description

Stores a copy of a page on the server and/or client computer, to improve page rendering performance. To do this, the tag creates temporary files that contain the static HTML returned from a ColdFusion page.

Use this tag if it is not necessary to get dynamic content each time a user accesses a page.

You can use this tag for simple URLs and for URLs that contain URL parameters.

Category

Page processing tags

Syntax

<cfcache
    action = "action"
    directory = "directory_name"
    timespan = "value"
    expireURL = "wildcarded_URL_reference"
    username = "username"
    password = "password"
    port = "port_number"
    protocol = "protocol">

See also

cfflush , cfheader , cfhtmlhead , cfsetting , cfsilent

History

ColdFusion MX:

  • Deprecated the cachedirectory and timeout attributes. They might not work, and might cause an error, in later releases.
  • Added the timespan attribute.
  • Changed how pages are cached: the default action attribute value, cache, caches a page on the server and the client. (In earlier releases, this option cached a page only on the server.)
  • Changed the source of the protocol and port values: the default protocol and port values are now taken from the current page URL. (In earlier releases, they were "http" and "80", respectively.)
  • Changed how session state is handled when caching a page: this tag can cache pages that depend on session state, including pages that are secured with a ColdFusion login. (In earlier releases, the session state was cleared when caching the page, causing authentication to be lost.)
  • Changed how files are cached: this tag uses a hash() of the URL for the filename to cache a file. (In earlier releases, ColdFusion used the cfcache.map file.)

Attributes

Attribute

Req/Opt

Default

Description

action

Optional

cache
  • cache: server-side and client-side caching.
  • flush: refresh cached page(s).
  • clientcache: browser-side caching only. To cache a personalized page, use this option.
  • servercache: server-side caching only. Not recommended.
  • optimal: same as "cache".

directory

Optional

cf_root/cache

Absolute path of cache directory.

timespan

Optional

Page is flushed only when cfcache action = "flush" is executed

The interval until the page is flushed from the cache.

  • A decimal number of days. For example:
    • - ".25", for one-fourth day (6 hours)
    • - "1", for one day
    • - "1.5", for one and one half days
  • A return value from the CreateTimeSpan function; for example, "#CreateTimeSpan(0, 6, 0, 0)#".

expireURL

Optional

Flush all cached pages

Used with action = "flush". A URL reference. ColdFusion matches it against the mappings in the specified cache directory. Can include wildcards. For example: "*/view.cfm?id=*".

username

Optional

A username. Provide this if the page requires authentication at the web server level.

password

Optional

A password. Provide this if the page requires authentication at the web server level.

port

Optional

The current page port

Port number of the web server from which the URL is requested. In the internal call from cfcache to cfhttp, ColdFusion resolves each URL variable in the page; this ensures that links in the page remain functional.

protocol

Optional

The current page protocol

Protocol that is used to create URL from cache.

  • http://
  • https://

Usage

Use this tag in pages whose content is not updated frequently. Taking this action can greatly improve the performance of your application.

The output of a cached page is stored in a file on the client browser and/or the ColdFusion server. Instead of regenerating and downloading the output of the page each time it is requested, ColdFusion uses the cached output. ColdFusion regenerates and downloads the page only when the cache is flushed, as specified by the timespan attribute, or by invoking cfcache action=flush.

To enable a simple form of caching, put a cfcache tag, specifying the timespan attribute, at the top of a page. Each time the specified time span passes, ColdFusion flushes (deletes) the copy of the page from the cache and caches a new copy for users to access.

You can specify client-side caching or a combination of client-side and server-side caching (the default), using the action attribute. The advantage of client-side caching is that it requires no ColdFusion resources; the browser stores pages in its own cache, improving performance. The advantage of combination caching is that it optimizes server performance; if the browser does not have a cache of the page, the server can get data from its own cache. (Macromedia recommends that you do not use server-side only caching. Macromedia recommends that you use combination caching.)

If a page contains personalized content, use the action = "clientcache" option to avoid the possibility of caching a personalized copy of a page for other users.

Debug settings have no effect on cfcache unless the application page enables debugging. When generating a cached file, cfcache uses cfsetting showDebugOutput = "no".

The cfcache tag evaluates each unique URL, including URL parameters, as a distinct page, for caching purposes. For example, the output of http://server/view.cfm?id=1 and the output of http://server/view.cfm?id=2 are cached separately.

The cfcache tag uses the cfhttp tag to get the contents of a page to cache. If there is an HTTP error accessing the page, the contents are not cached. If a ColdFusion error occurs, the error is cached.

For more information, see Caching ColdFusion pages that change infrequently in Optimizing ColdFusion applications in ColdFusion MX Developer’s Guide.

Example

<!--- This example produces as many cached files as there are
URL parameter permutations. You can see that the page is cached when the
timestamp doesn't change.--->

<cfcache
timespan="#createTimeSpan(0,0,10,0)#">
<body>

<h3>This is a test of some simple output</h3>

<cfoutput>
This page was generated at #now()#<br>
</cfoutput>

<cfparam name = "URL.x" default = "no URL parm passed" >
<cfoutput>The value of URL.x = # URL.x #</cfoutput>


cfcalendar

Description

Puts an interactive Macromedia Flash format calendar in an HTML or Flash form. Not supported in XML format forms. The calendar lets a user select a date for submission as a form variable.

Category

Forms tags

Syntax

<cfcalendar
name = "name of calendar"
height = "height"
width = "width"
selectedDate = "date"
startRange = "first disabled date"
endRange = "last disabled date"
disabled = "true", "false", or no attribute value
mask = "character pattern"
dayNames = "days-of-the-week labels"
monthNames = "month labels"
visible = "Yes" or "No"
enabled = "Yes" or "No"
tooltip = "Tip text"
onChange = "actionscript to invoke">

See also

cfform, cfgrid, cfinput, cfselect, cfslider, cftextarea, cftree; About Flash form styles in Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

History

ColdFusion MX 7: Added tag.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

The name of the calendar.

height

Optional

Determined by Flash

The vertical dimension of the calendar specified in pixels.

width

Optional

Determined by Flash

The horizontal dimension of the calendar specified in pixels.

selectedDate

Optional

None (Flash shows the current month)

The date that is initially selected. It is highlighted in a color determined by the form skin. Must be in mm/dd/yyyy or dd/mm/yyyy format, depending on the current locale. (Use the setlocale tag to set the locale, if necessary.)

startRange

Optional

The start of a range of dates that are disabled. Users cannot select dates from this date through the date specified by the endRange attribute.

endRange

Optional

The end of a range of dates that are disabled. Users cannot select dates from the date specified by the startRange attribute through this date.

disabled

Optional

not disabled

Disables all user input, making the control read-only. To disable input, specify disabled without an attribute or disabled="Yes" (or any ColdFusion positive boolean value, such as True). To enable input, omit the attribute or specify disabled="No" (or any ColdFusion negative boolean value, such as False).

mask

Optional

MM/DD/YYYY

A pattern that specifies the format of the submitted date. Mask characters are:

  • D = day; can use 0–2 mask characters
  • M = month; can use 0–4 mask characters
  • Y = year; can use 0, 2, or 4 characters
  • E = day in week; can use 0–4 characters
  • Any other character = put the character in the specified location

For more information on masking, see Masking input data in the cfinput reference page.

firstDayOfWeek

Optional

0

Integer in the range 0-6 specifying the first day of the week in the calendar: 0 indicates Sunday; 6 indicates Saturday.

dayNames

Optional

S, M, T, W, Th, F, S

A comma-delimited list that sets the names of the weekdays displayed in the calendar. Sunday is the first day and the rest of the weekday names follow in the normal order.

monthNames

Optional

January, February, March, April, May, June, July, August, September, October, November, December

A comma-delimited list of the month names that are displayed at the top of the calendar.

style

Optional

Flash ActionScript style or styles to apply to the calendar. For more information, see Setting styles and skins in Flash forms in ColdFusion MX Developer’s Guide.

enabled

Optional

Yes

Flash only: Boolean value specifying whether the control is enabled. A disabled control appears in light gray. This is the inverse of the disabled attribute.

visible

Optional

Yes

Flash only: Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank.

tooltip

Optional

Flash only: Text to display when the mouse pointer hovers over the control.

onChange

Optional

ActionScript that runs when the user selects a date.

Usage

The cfcalendar tag displays a calendar month, showing the month, the year, a grid of the days of the month, and headings for the days of the week. The calendar contains forward and back arrow buttons to let you change the month and year that are displayed.

If you include a value for the selectedDate attribute, that date is highlighted in green and determines the month and year that display initially. Changing the month and year display does not change the selected date. A user can change the selected date by clicking a different date on the calendar. The onChange attribute can specify an ActionScript event handler function that runs when the user selects a date.

The current date is highlighted in reverse (that is, a white number on a black background). If the selected date is in a different month or year, however, the current date does not appear unless you move to it by clicking the forward or back arrows.

The mask attribute lets you specify the format of the selected date that is returned to the application.

You can use the keyboard to access and select dates from a cfcalendar control:

  • Use the Up, Down, Left, and Right Arrow keys to change the selected date.
  • Use the Home and End keys to reach the first and last enabled date in a month, respectively.
  • Use the Page Up and Page Down keys to reach the previous and next month, respectively.

Note: The cfcalendar tag is not supported in XML format forms.

Example

This example produces a 200-pixel by 150-pixel calendar with a Flash haloBlue skin. It displays abbreviated month names and two-character days of the week. It initially displays today’s date as determined by the selectedDate attribute. When you click the Save button, the form submits back to the current page, which displays the submitted information.

The example also has three dateField controls that let the user change the initial selected date that displays on the calendar and a blocked-out date range. The initial blocked-out date is a four-day period immediately preceding today’s date.

Note: This example must be modified to work in locales that do not use mm/dd/yyyy date formats. To do so, use the LSDateFormat function in place of the DateFormat function and a mask that is appropriate for your locale, such as dd/mm/yyyy.

<!--- Set initial selected and blocked-out dates.--->
<cfparam name="Form.startdate" default="#dateformat(now()-5, 'mm/dd/yyyy')#">
<cfparam name="Form.enddate" default="#dateformat(now()-1, 'mm/dd/yyyy')#">
<cfparam name="Form.selectdate" default="#dateformat(now(), 'mm/dd/yyyy')#">

<!--- If the form has been submitted, display the selected date. --->
<cfif isDefined("Form.submitit")>
    <cfoutput><b>You selected #Form.selectedDate#</b><br><br></cfoutput>
</cfif>

<b>Please select a date on the calendar and click Save.</b><br>
<br>
<cfform name="form1" format="Flash" skin="haloBlue" width="375" height="350" >
    <cfcalendar name="selectedDate"
        selectedDate="#Form.selectdate#"
        startRange="#Form.startdate#"
        endRange="#Form.enddate#"
        mask="mmm dd, yyyy"
        dayNames="SU,MO,TU,WE,TH,FR,SA"
        monthNames="JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC"
        style="rollOverColor:##FF0000"
        width="200" height="150" >
    <cfinput type="dateField" name="startdate" label="Block out starts"
        width="100" value="#Form.startdate#">
    <cfinput type="dateField" name="enddate" label="Block out ends" width="100"
        value="#Form.enddate#">
    <cfinput type="dateField" name="selectdate" label="Initial date" width="100"
        value="#Form.selectdate#" >
    <cfinput type="Submit" name="submitit" value="Save" width="100">
</cfform>


cfcase

Description

Used only inside the cfswitch tag body. Contains code to execute when the expression specified in the cfswitch tag has one or more specific values.

Category

Flow-control tags

Syntax

<cfcase
    value = "value or delimited set of values"
    delimiters = "delimiter characters">

See also

cfdefaultcase, cfswitch; cfswitch, cfcase, and cfdefaultcase in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
value | Required |  | The value or values that the expression attribute of the cfswitch tag must match. To specify multiple matching values, separate the values with the delimiter character. The value or values must be simple constants or constant expressions, not variables.
delimiter | Optional | , (comma) | Specifies the delimiter character or characters that separate multiple values to match. If you specify multiple delimiter characters, you can use any of them to separate the values to be matched.

Usage

The contents of the cfcase tag body executes only if the expression attribute of the cfswitch tag evaluates to a value specified by the value attribute. The contents of the cfcase tag body can include HTML and text, and CFML tags, functions, variables, and expressions. You do not have to explicitly break out of the cfcase tag, as you do in some languages.

One cfcase tag can match multiple expression values. To do this, separate the matching values with the delimiter character, which is the comma by default. For example the following line matches "red", "blue", or "green":

<cfcase value="red,blue,green">

You can use the delimiter attribute to specify one or more delimiters to use in place of the comma. For example, the following line matches "cargo, live", "cargo, liquid", and "cargo, solid":

<cfcase value="cargo, live;cargo, liquid-cargo, solid" delimiters=";-">

Example

The following example displays a grade based on a 1-10 score. Several of the cfcase tags match more than one score. For simplicity, the example sets the score to 7.

<cfset score="7">
<cfswitch expression="#score#">
    <cfcase value="10">
        <cfset grade="A">
    </cfcase>
    <cfcase value="9;8" delimiters=";">
        <cfset grade="B">
    </cfcase>
    <cfcase value="7;6" delimiters=";">
        <cfset grade="C">
    </cfcase>
    <cfcase value="5;4;" delimiters=";">
        <cfset grade="D">
    </cfcase>
    <cfdefaultcase>
        <cfset grade="F">
    </cfdefaultcase>
</cfswitch>
<cfoutput>
    Your grade is #grade#
</cfoutput>


cfcatch

Description

Used inside a cftry tag. Together, they catch and process exceptions in ColdFusion pages. Exceptions are events that disrupt the normal flow of instructions in a ColdFusion page, such as failed database operations, missing include files, and developer-specified events.

Category

Exception handling tags

Syntax

<cfcatch type = "exceptiontype">
    Exception processing code here
</cfcatch>

See also

cftry, cferror, cfrethrow, cfthrow , onError; Handling Errors in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed SQLSTATE value behavior: the SQLSTATE return value in a cfcatch tag depends on the database driver type:
    • Type 1 (JDBC-ODBC bridge): the value is the same as in ColdFusion 5
    • Type 4 (100% Java, no native methods): the value might be different

    If your application depends on SQLSTATE values for flow control, the application might produce unexpected behavior with ColdFusion MX.

  • Changed the behavior of this tag when type="any": it is not necessary, when you include a cfcatch tag with type="any", to do so in the last cfcatch tag in the block, to ensure that all other tests are executed before it. ColdFusion finds the best-match cfcatch block.
  • Changed the behavior of the cfscript tag: it includes try and catch statements that are equivalent to the cftry and cfcatch tags.
  • Changed object modification: you cannot modify the object returned by cfcatch.
  • Changed thrown exceptions: the cfcollection, cfindex, and cfsearch tags can throw the SEARCHENGINE exception. In earlier releases, an error in processing these tags threw only an UNKNOWN exception.

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

Any
  • application: catches application exceptions
  • database: catches database exceptions
  • template: catches ColdFusion page exceptions
  • security: catches security exceptions
  • object: catches object exceptions
  • missingInclude: catches missing include file exceptions
  • expression: catches expression exceptions
  • lock: catches lock exceptions
  • custom_type: catches the specified custom exception type that is defined in a cfthrow tag
  • searchengine: catches Verity search engine exceptions
  • any: catches all exception types

Usage

You must code at least one cfcatch tag within a cftry block. Put cfcatch tags at the end of a cftry block. ColdFusion MX tests cfcatch tags in the order in which they appear. This tag requires an end tag.

If type="any", ColdFusion MX catches exceptions from any CFML tag, data source, or external object. To get the exception type use code such as the following:

    #cfcatch.type#

Applications can use the cfthrow tag to throw developer-defined exceptions. Catch these exceptions with any of these type options:

  • "custom_type"
  • "Application"
  • "Any"

The custom_type type is a developer-defined type specified in a cfthrow tag. If you define a custom type as a series of strings concatenated by periods (for example, "MyApp.BusinessRuleException.InvalidAccount"), ColdFusion MX can catch the custom type by its character pattern. ColdFusion MX searches for a cfcatch tag in the cftry block with a matching exception type, starting with the most specific (the entire string), and ending with the least specific.

For example, you could define a type as follows:

<cfthrow type = "MyApp.BusinessRuleException.InvalidAccount">

If you have the following cfcatch tag, it will handle the exception:

<cfcatch type = "MyApp.BusinessRuleException.InvalidAccount">

Otherwise, if you have the following cfcatch tag, it will handle the exception:

<cfcatch type = "MyApp.BusinessRuleException">

Finally, if you have the following cfcatch tag, it will handle the exception:

<cfcatch type = "MyApp">

You can code cfcatch tags in any order to catch a custom exception type.

If you specify type = "Application", the cfcatch tag catches only custom exceptions that have the Application type in the cfthrow tag that defines them.

The cfinclude, cfmodule, and cferror tags throw an exception of type = "template".

An exception that is thrown within a cfcatch block cannot be handled by the cftry block that immediately encloses the cfcatch tag. However, you can rethrow the currently active exception with the cfrethrow tag.

The cfcatch variables provide the following exception information:

cfcatch variable

Content

cfcatch.type

Type: Exception type, as specified in cfcatch.

cfcatch.message

Message: Exception's diagnostic message, if provided; otherwise, an empty string; in the cfcatch.message variable.

cfcatch.detail

Detailed message from the CFML interpreter or specified in a cfthrow tag. When the exception is generated by ColdFusion (and not cfthrow), the message can contain HTML formatting and can help determine which tag threw the exception.

cfcatch.tagcontext

An array of tag context structures, each representing one level of the active tag context at the time of the exception.

cfcatch.NativeErrorCode

Applies to type = "database". Native error code associated with exception. Database drivers typically provide error codes to diagnose failing database operations. Default: -1.

cfcatch.SQLState

Applies to type = "database". SQLState associated with exception. Database drivers typically provide error codes to help diagnose failing database operations. Default: -1.

cfcatch.Sql

Applies to type = "database". The SQL statement sent to the data source.

cfcatch.queryError

Applies to type ="database". The error message as reported by the database driver.

cfcatch.where

Applies to type = "database". If the query uses the cfqueryparam tag, query parameter name-value pairs.

cfcatch.ErrNumber

Applies to type = "expression". Internal expression error number.

cfcatch.MissingFileName

Applies to type = "missingInclude". Name of file that could not be included.

cfcatch.LockName

Applies to type = "lock". Name of affected lock (if the lock is unnamed, the value is "anonymous").

cfcatch.LockOperation

Applies to type = "lock". Operation that failed (Timeout, Create Mutex, or Unknown).

cfcatch.ErrorCode

Applies to type = "custom". String error code.

cfcatch.ExtendedInfo

Applies to type = "application" and "custom". Custom error message; information that the default exception handler does not display.

Advanced Exception types

You can specify the following advanced exception types in the type attribute:

ColdFusion advanced exception type

COM.Allaire.ColdFusion.CFEXECUTE.OutputError

COM.Allaire.ColdFusion.CFEXECUTE.Timeout

COM.Allaire.ColdFusion.FileException

COM.Allaire.ColdFusion.HTTPAccepted

COM.Allaire.ColdFusion.HTTPAuthFailure

COM.Allaire.ColdFusion.HTTPBadGateway

COM.Allaire.ColdFusion.HTTPBadRequest

COM.Allaire.ColdFusion.HTTPCFHTTPRequestEntityTooLarge

COM.Allaire.ColdFusion.HTTPCGIValueNotPassed

COM.Allaire.ColdFusion.HTTPConflict

COM.Allaire.ColdFusion.HTTPContentLengthRequired

COM.Allaire.ColdFusion.HTTPContinue

COM.Allaire.ColdFusion.HTTPCookieValueNotPassed

COM.Allaire.ColdFusion.HTTPCreated

COM.Allaire.ColdFusion.HTTPFailure

COM.Allaire.ColdFusion.HTTPFileInvalidPath

COM.Allaire.ColdFusion.HTTPFileNotFound

COM.Allaire.ColdFusion.HTTPFileNotPassed

COM.Allaire.ColdFusion.HTTPFileNotRenderable

COM.Allaire.ColdFusion.HTTPForbidden

COM.Allaire.ColdFusion.HTTPGatewayTimeout

COM.Allaire.ColdFusion.HTTPGone

COM.Allaire.ColdFusion.HTTPMethodNotAllowed

COM.Allaire.ColdFusion.HTTPMovedPermanently

COM.Allaire.ColdFusion.HTTPMovedTemporarily

COM.Allaire.ColdFusion.HTTPMultipleChoices

COM.Allaire.ColdFusion.HTTPNoContent

COM.Allaire.ColdFusion.HTTPNonAuthoritativeInfo

COM.Allaire.ColdFusion.HTTPNotAcceptable

COM.Allaire.ColdFusion.HTTPNotFound

COM.Allaire.ColdFusion.HTTPNotImplemented

COM.Allaire.ColdFusion.HTTPNotModified

COM.Allaire.ColdFusion.HTTPPartialContent

COM.Allaire.ColdFusion.HTTPPaymentRequired

COM.Allaire.ColdFusion.HTTPPreconditionFailed

COM.Allaire.ColdFusion.HTTPProxyAuthenticationRequired

COM.Allaire.ColdFusion.HTTPRequestURITooLarge

COM.Allaire.ColdFusion.HTTPResetContent

COM.Allaire.ColdFusion.HTTPSeeOther

COM.Allaire.ColdFusion.HTTPServerError

COM.Allaire.ColdFusion.HTTPServiceUnavailable

COM.Allaire.ColdFusion.HTTPSwitchingProtocols

COM.Allaire.ColdFusion.HTTPUnsupportedMediaType

COM.Allaire.ColdFusion.HTTPUrlValueNotPassed

COM.Allaire.ColdFusion.HTTPUseProxy

COM.Allaire.ColdFusion.HTTPVersionNotSupported

COM.Allaire.ColdFusion.POPAuthFailure

COM.Allaire.ColdFusion.POPConnectionFailure

COM.Allaire.ColdFusion.POPDeleteError

COM.Allaire.ColdFusion.Request.Timeout

COM.Allaire.ColdFusion.SERVLETJRunError

COMCOM.Allaire.ColdFusion.HTTPConnectionTimeout

Example

<!--- cfcatch example, using TagContext to display the tag stack. --->
<h3>cftry Example</h3>
<!--- Open a cftry block. --->
<cftry>
    <!--- Note misspelled tablename "employees" as "employeeas". --->
    <cfquery name = "TestQuery" dataSource = "cfdocexamples">
        SELECT *
        FROM EMPLOYEEAS
    </cfquery>
    <!--- Other processing goes here. --->
    <!--- Specify the type of error for which we search. --->
    <cfcatch type = "Database">
        <!--- the message to display. --->
        <h3>You've Thrown a Database <b>Error</b></h3>
        <cfoutput>
            <!--- The diagnostic message from ColdFusion MX. --->
            <p>#cfcatch.message#</p>
            <p>Caught an exception, type = #CFCATCH.TYPE# </p>
            <p>The contents of the tag stack are:</p>
            <cfdump var="#cfcatch.tagcontext#">
        </cfoutput>
    </cfcatch>
</cftry>


cfchart

Description

Generates and displays a chart.

Category

Data output tags, Extensibility tags; Controlling chart appearance in Creating Charts and Graphs in ColdFusion MX Developer’s Guide

Syntax

Syntax 1
<!--- This syntax uses an XML file or string to specify the chart style. --->
<cfchart
        style = "XML string or filename">
</cfchart>
Syntax 2
<!--- This syntax uses the attributes of the cfchart tag to specify the chart style. --->
<cfchart
        backgroundColor = "Hex value or Web color"
        chartHeight = "integer number of pixels"
        chartWidth = "integer number of pixels"
        dataBackgroundColor = "Hex value or Web color"
        font = "font name"
        fontBold = "yes" or "no"
        fontItalic = "yes" or "no"
        fontSize = "integer font size"
        foregroundColor = "Hex value or Web color"
        format = "flash" or "jpg" or "png"
        gridlines = "integer number of lines"
        labelFormat = "number, currency, percent, date"
        markerSize = "integer number of pixels"
        name = "String">
        pieSliceStyle = "solid, sliced"
        scaleFrom = "integer minimum value"
        scaleTo = "integer maximum value"
        seriesPlacement = "default, cluster, stacked, percent"
        show3D = "yes" or "no"
        showBorder = "yes" or "no"
        showLegend = "yes" or "no"
        showMarkers = "yes" or "no"
        showXGridlines = "yes" or "no"
        showYGridlines = "yes" or "no"
        sortXAxis = "yes" or "no"
        tipBGColor = "hex value or web color"
        tipStyle = "MouseDown, MouseOver, none"
        title = "title of chart"
        url = "onClick destination page"
        xAxisTitle = "title text"
        xAxisType = "scale or category"
        xOffset = "number between -1 and 1"
        yAxisTitle = "title text"
        yAxisType = "scale or category"
        yOffset = "number between -1 and 1"
        </cfchart>

See also

cfchartdata, cfchartseries

History

ColdFusion MX 7:

  • Added style and title attributes.
  • Added support for eight-digit hexadecimal values to specify RGB color and transparency.
  • Removed the rotated attribute.
  • Renamed the column chart type to be horizontalbar chart type.

ColdFusion MX 6.1:

  • Added the xAxisType and yAxisType attributes.
  • Changed interpolation behavior: the tag now interpolates data points on line charts with multiple series.

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

backgroundColor

Optional

Color of the area between the data background and the chart border, around labels and around the legend.

Hexadecimal value or supported named color; see the name list in Usage. For a hexadecimal value, use the form "##xxxxxx" or "##xxxxxxxx", where x = 0-9 or A-F; use two number signs or none.

chartHeight

Optional

240

Chart height; integer number of pixels.

chartWidth

Optional

320

Chart width; integer number of pixels.

dataBackgroundColor

Optional

white

Color of area around chart data.

Hexadecimal value or supported named color; see the name list in Usage.

For a hexadecimal value, use the form "##xxxxxx" or "##xxxxxxxx", where x = 0-9 or A-F; use two number signs or none.

font

Optional

arial

Name of text font:

  • arial
  • times
  • courier
  • arialunicodeMS. This option is required, if you are using a double-byte character set on UNIX, or using a double-byte character set in Windows with a file type of Flash.

fontBold

Optional

no

Whether to make the text bold:

  • yes
  • no

fontItalic

Optional

no

Whether to make the text italicized:

  • yes
  • no

fontSize

Optional

11

Font size; integer.

foregroundColor

Optional

black

Color of text, grid lines, and labels.

Hexadecimal value or supported named color; see name list in Usage.

For a hexadecimal value, use the form "##xxxxxx" or "##xxxxxxxx", where x = 0-9 or A-F; use two number signs or none.

format

Optional

flash

File format in which to save the graph:

  • flash
  • jpg
  • png

gridlines

Optional

10, including top and bottom

Number of grid lines to display on the value axis, including axis; positive integer.

labelFormat

Optional

number

Format for y-axis labels:

  • number
  • currency
  • percent
  • date

markerSize

Optional

(Automatic)

Size of data point marker in pixels; integer.

name

Optional

Page variable name; string. Generates the the graph as binary data and assigns it to the specified variable. Suppresses chart display. You can use the name value in the cffile tag to write the chart to a file.

pieSliceStyle

Optional

sliced

Applies to the cfchartseries type attribute value pie.

  • solid: displays pie as if unsliced.
  • sliced: displays pie as if sliced.

rotated

Optional

no

Whether to rotate the chart 90 degrees:

  • yes
  • no

scaleFrom

Optional

Determined by data

Y-axis minimum value; integer.

scaleTo

Optional

Determined by data

Y-axis maximum value; integer.

seriesPlacement

Optional

default

Relative positions of series in charts that have more than one data series.

  • default: ColdFusion determines relative positions, based on graph types
  • cluster
  • stacked
  • percent

show3D

Optional

yes

Whether to display the chart with three-dimensional appearance:

  • yes
  • no

showBorder

Optional

no

Whether to display a border around the chart:

  • yes
  • no

showLegend

Optional

yes

Whether to display the legend if the chart contains more than one data series:

  • yes
  • no

showMarkers

Optional

yes

Whether to display markers at data points in line, curve, and scatter graphs:

  • yes
  • no

showXGridlines

Optional

no

Whether to display x-axis gridlines:

  • yes
  • no

showYGridlines

Optional

yes

Whether to display y-axis gridlines:

  • yes
  • no

sortXAxis

Optional

no

Whether to display column labels in alphabetic order along the x-axis:

  • yes:
  • no

Ignored if the xAxisType attribute is scale.

style

Optional

XML file or string to use to specify the style of the chart.

title

Optional

Title of the chart.

tipbgcolor

Optional

white

Background color of tips. Applies only to Flash format graph files.

Hexadecimal value or supported named color; see the name list in the Usage section.

For a hexadecimal value, use the form "##xxxxxx", where x = 0-9 or A-F; use two number signs or none.

tipStyle

Optional

mouseOver

Determines the action that opens a pop-up window to display information about the current chart element.

  • mouseDown: display if the user positions the cursor at the element and clicks the mouse. Applies only to Flash format graph files. (For other formats, this option functions the same as mouseOver.)
  • mouseOver: displays if the user positions the cursor at the element
  • none: suppresses display

url

Optional

URL to open if the user clicks item in a data series; the onClick destination page.

You can specify variables within the URL string; ColdFusion passes current values of the variables.

  • $VALUE$: the value of the selected row. If none, the value is an empty string.
  • $ITEMLABEL$: the label of the selected item. If none, the value is an empty string.
  • $SERIESLABEL$: the label of the selected series. If none, the value is an empty string.

For example:

"somepage.cfm?item=$ITEMLABEL$&series=$SERIESLABEL$&value=$VALUE$

  • "javascript:...": executes a client-side script
    •

xAxisTitle

Optional

Title that appears on the x-axis; text.

xAxisType

Optional

category

Whether the x-axis indicates data or is numeric:

  • category: The axis indicates the data category. Data is sorted according to the sortXAxis attribute.
  • scale: The axis is numeric. All cfchartdata item attribute values must be numeric. The x-axis is automatically sorted numerically.

xOffset

Optional

0.1

Number of units by which to display the chart as angled, horizontally. Applies if show3D="yes". The number can be between -1 and 1, where "-1" specifies 90 degrees left and "1" specifies 90 degrees right.

yAxisTitle

Optional

Title of the y-axis; text.

yAxisType

Optional

category

Currently has no effect, as the y-axis is always used for data values.

yOffset

Optional

0.1

Number of units by which to display the chart as angled, vertically. Applies if show3D="yes". The number can be between -1 and 1, where "-1" specifies 90 degrees left and "1" specifies 90 degrees right.

Usage

The cfchart tag defines a container in which a graph displays: its height, width, background color, labels, and so on. The cfchartseries tag defines the chart style in which data displays: bar, line, pie, and so on. The cfchartdata tag defines a data point.

Data is passed to the cfchartseries tag in the following ways:

  • As a query
  • As data points, using the cfchartdata tag

For the font attribute value ArialUnicodeMS, the following rules apply:

  • In Windows, to permit Flash charts (type = "flash") to render a double-byte character set, you must select this value.
  • On UNIX, for all type values, to render a double-byte character set, you must select this value.
  • If this value is selected, the fontBold and fontItalic attributes have no effect.

The following table lists W3C HTML 4 named color value or hexadecimal values that the color attribute accepts:

Color name | RGB value
Aqua | ##00FFFF
Black | #000000
Blue | ##0000FF
Fuchsia | ##FF00FF
Gray | ##808080
Green | ##008000
Lime | ##00FF00
Maroon | ##800000
Navy | ##000080
Olive | ##808000
Purple | ##800080
Red | ##FF0000
Silver | ##C0C0C0
Teal | ##008080
White | ##FFFFFF
Yellow | ##FFFF00

For all other color values, you must enter the hexadecimal value. You can enter a six-digit value, which specifies the RGB value, or an eight-digit value, which specifies the RGB value and the transparency. The first two digits of an eight-digit hexadecimal value specify the degree of transparency, with FF indicating opaque and 00 indicating transparent. Values between 00 and FF are allowed.

For more color names that are supported by popular browsers, go to www.w3.org/TR/css3-color

You can specify whether charts are cached in memory, the number of charts to cache, and the number of chart requests that ColdFusion can process concurrently. To set these options in the ColdFusion Administrator, select Server Settings > Charting.

Example

<!---The following example analyzes the salary data in the cfdocexamples
database and generates a bar chart showing average salary by department. The
body of the cfchartseries tag includes one cfchartdata tag to include data that
is not available from the query. --->

<!--- Get the raw data from the database. --->
<cfquery name="GetSalaries" datasource="cfdocexamples">
SELECT Departmt.Dept_Name,
Employee.Dept_ID,
Employee.Salary
FROM Departmt, Employee
WHERE Departmt.Dept_ID = Employee.Dept_ID
</cfquery>

<!--- Use a query of queries to generate a new query with --->
<!--- statistical data for each department. --->
<!--- AVG and SUM calculate statistics. --->
<!--- GROUP BY generates results for each department. --->
<cfquery dbtype = "query" name = "DataTable">
SELECT
Dept_Name,
AVG(Salary) AS avgSal,
SUM(Salary) AS sumSal
FROM GetSalaries
GROUP BY Dept_Name
</cfquery>

<!--- Reformat the generated numbers to show only thousands. --->
<cfloop index = "i" from = "1" to = "#DataTable.RecordCount#">
<cfset DataTable.sumSal[i] = Round(DataTable.sumSal[i]/1000)*1000>
<cfset DataTable.avgSal[i] = Round(DataTable.avgSal[i]/1000)*1000>
</cfloop>

<h1>Employee Salary Analysis</h1>
<!--- Bar graph, from Query of Queries --->
<cfchart format="flash"
xaxistitle="Department"
yaxistitle="Salary Average">

<cfchartseries type="bar"
query="DataTable"
itemcolumn="Dept_Name"
valuecolumn="avgSal">

<cfchartdata item="Facilities" value="35000">

</cfchartseries>
</cfchart>


cfchartdata

Description

Used with the cfchart and cfchartseries tags. This tag defines chart data points. Its data is submitted to the cfchartseries tag.

Category

Data output tags, Extensibility tags

Syntax

<cfchartdata
    item = "text"
    value = "number">

See also

cfchart, cfchartseries; Creating Charts and Graphs in ColdFusion MX Developer’s Guide

ColdFusion MX: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
item | Required |  | Data point name; string.
value | Required |  | Data point value; number or expression.

Example

<!--- The following example analyzes the salary data in the cfdocexamples
database and generates a bar chart showing average salary by department. The
body of the cfchartseries tag loops over a cfchartdata tag to include data
available from the query. --->

<!--- Get the raw data from the database. --->
<cfquery name="GetSalaries" datasource="cfdocexamples">
SELECT Departmt.Dept_Name,
Employee.Dept_ID,
Employee.Salary
FROM Departmt, Employee
WHERE Departmt.Dept_ID = Employee.Dept_ID
</cfquery>

<!--- Use a query of queries to generate a new query with --->
<!--- statistical data for each department. --->
<!--- AVG and SUM calculate statistics. --->
<!--- GROUP BY generates results for each department. --->
<cfquery dbtype = "query" name = "DataTable">
SELECT
Dept_Name,
AVG(Salary) AS avgSal,
SUM(Salary) AS sumSal
FROM GetSalaries
GROUP BY Dept_Name
</cfquery>

<!--- Reformat the generated numbers to show only thousands. --->
<cfloop index = "i" from = "1" to = "#DataTable.RecordCount#">
<cfset DataTable.sumSal[i] = Round(DataTable.sumSal[i]/1000)*1000>
<cfset DataTable.avgSal[i] = Round(DataTable.avgSal[i]/1000)*1000>
</cfloop>

<h1>Employee Salary Analysis</h1>
<!--- Bar graph, from Query of Queries. --->
<cfchart format="flash"
xaxistitle="Department"
yaxistitle="Salary Average">

<cfchartseries type="bar"
itemcolumn="Dept_Name"
valuecolumn="avgSal">

<cfloop query="DataTable">
<cfchartdata item="#DataTable.Dept_Name#" value="#DataTable.avgSal#">
</cfloop>

</cfchartseries>
</cfchart>


cfchartseries

Description

Used with the cfchart tag. This tag defines the chart style in which the data displays: bar, line, pie, and so on.

Category

Data output tags, Extensibility tags

Syntax

<cfchartseries
    colorlist = "list">
    itemColumn="queryColumn"
    markerStyle="style"
    paintStyle="plain, raise, shade, light"
    query="queryName"
    seriesColor="Hex value or Web color"
    seriesLabel="Label Text"
    type="type"
    valueColumn="queryColumn"
    dataLabelStyle="style"
</cfchartseries>

See also

cfchart, cfchartdata; Creating Charts and Graphs in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the dataLabelStyle attribute and the horizontalbar chart type.

ColdFusion MX 6.1: Changed interpolation behavior: the tag now interpolates data points on line charts with multiple series.

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

colorlist

Optional

Sets colors for each data point. Applies if the cfchartseries type attribute is pie, pyramid, area, horizontalbar, cone, cylinder, or step.

Comma-delimited list of hexadecimal values or supported, named web colors; see the name list and information about six- and eight-digit hexadecimal values in the cfchart Usage section.

For a hexadecimal value, use the form "##xxxxxx" or "##xxxxxxxx", where x = 0-9 or A-F; use two number signs or none.

itemColumn

Required if query attribute is specified

Name of a column in the query specified in the query attribute; contains the item label for a data point to graph.

markerStyle

Optional

rectangle

Sets the icon that marks a data point for two-dimensional line, curve, and scatter graphs:

  • rectangle
  • triangle
  • diamond
  • circle
  • letter
  • mcross
  • snow
  • rcross

paintStyle

Optional

plain

Sets the paint display style of the data series:

  • plain: solid color.
  • raise: the appearance of a button.
  • shade: gradient fill, darker at the edges.
  • light: a lighter shade of color; gradient fill.

query

Optional

Name of the ColdFusion query from which to get data to graph.

seriesColor

Optional

Color of the main element (such as the bars) of a chart. For a pie chart, the color of the first slice.

Hexadecimal value or supported named color; see the name list and information about six- and eight-digit hexadecimal values in the Usage section for the cfchart tag.

For a hexadecimal value, use the form "##xxxxxx" or "##xxxxxxxx", where x = 0-9 or A-F; use two number signs or none.

seriesLabel

Optional

Text of the data series label

type

Required

Sets the chart display style:

  • bar
  • line
  • pyramid
  • area
  • horizontalbar
  • cone
  • curve
  • cylinder
  • step
  • scatter
  • pie

valueColumn

Required if query attribute is specified

Name of a column in the query specified in the query attribute; contains data values to graph.

dataLabelStyle

Optional

None

Specifies the way in which the color is applied to the item in the series:

  • none: nothing is printed.
  • value: the value of the datapoint.
  • rowLabel: the row's label.
  • columnLabel: the column's label.
  • pattern: combination of column label, value, and aggregate information, such as columnLabel value for the percentage of total graph; for example, Sales 55,000 20% of 277,000.

Usage

For a pie chart, ColdFusion sets pie slice colors as follows:

  • If the seriesColor attribute is omitted, ColdFusion automatically determines the colors of the slices.
  • If the seriesColor attribute is specified, ColdFusion automatically determines the colors of the slices after the first one, starting with the specified color for the first slice.

Example

<!--- The following example analyzes the salary data in the cfdocexamples
database and generates a bar chart showing average salary by department. --->

<!--- Get the raw data from the database. --->
<cfquery name="GetSalaries" datasource="cfdocexamples">
SELECT Departmt.Dept_Name,
Employee.Dept_ID,
Employee.Salary
FROM Departmt, Employee
WHERE Departmt.Dept_ID = Employee.Dept_ID
</cfquery>

<!--- Use a query of queries to generate a new query with --->
<!--- statistical data for each department. --->
<!--- AVG and SUM calculate statistics. --->
<!--- GROUP BY generates results for each department. --->
<cfquery dbtype = "query" name = "DataTable">
SELECT
Dept_Name,
AVG(Salary) AS avgSal,
SUM(Salary) AS sumSal
FROM GetSalaries
GROUP BY Dept_Name
</cfquery>

<!--- Reformat the generated numbers to show only thousands. --->
<cfloop index = "i" from = "1" to = "#DataTable.RecordCount#">
<cfset DataTable.sumSal[i] = Round(DataTable.sumSal[i]/1000)*1000>
<cfset DataTable.avgSal[i] = Round(DataTable.avgSal[i]/1000)*1000>
</cfloop>

<h1>Employee Salary Analysis</h1>
<!--- Bar graph, from Query of Queries --->
<cfchart format="flash"
xaxistitle="Department"
yaxistitle="Salary Average">

<cfchartseries type="bar"
query="DataTable"
itemcolumn="Dept_Name"
valuecolumn="avgSal" />
</cfchart>


cfcol

Description

Defines table column header, width, alignment, and text. Used within a cftable tag.

Category

Data output tags

Syntax

<cfcol
    header = "column_header_text"
    width = "number_indicating_width_of_column"
    align = "left" or "right" or "center"
    text = "column_text">

See also

cfcontent, cfoutput, cftable; Performing file operations with cfftp in Interacting with Remote Servers in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added the ability to construct dynamic cfcol statements.

Attribute

Req/Opt

Default

Description

header

Required

Column header text. To use this attribute, you must also use the cftable colHeaders attribute.

width

Optional

20

Column width. If the length of data displayed exceeds this value, data is truncated to fit. To avoid this, use an HTML table tag.

If the surrounding cftable tag includes the htmltable attribute, width specifies the percent of the table width and it does not truncate text; otherwise, width specifies the number of characters.

align

Optional

left

Column alignment:

  • left
  • right
  • center

text

Required

Double-quotation mark-delimited text; determines what to display. Rules: same as for cfoutput sections. You can embed hyperlinks, image references, and input controls.

Usage

At least one cfcol tag is required within the cftable tag. You must put cfcol and cftable tags adjacent in a page. The only tag that you can nest within the cftable tag is the cfcol tag. You cannot nest cftable tags.

To display the cfcol header text, you must specify the cfcol header and the cftable colHeader attribute. If you specify either attribute without the other, the header does not display. No error is thrown.

Example

<!--- This example shows the use of cfcol and cftable to align
information returned from a query. --->
<!--- query selects information from cfdocexamples data source. --->
<cfquery name = "GetEmployees" dataSource = "cfdocexamples">
    SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
    FROM Employees
</cfquery>
<html>
<body>
<h3>cfcol Example</h3>
<!--- Uses the HTMLTable attribute to display cftable as an HTML
table, rather than PRE formatted information --->
<cftable
    query = "GetEmployees"
    startRow = "1" colSpacing = "3"
    HTMLTable colheaders>
<!--- Each cfcol tag sets the width of a column in the table,
the header information, and the text/CFML for the cell. --->
    <cfcol header = "<b>ID</b>"
        align = "Left"
        width = 2
        text  = "#Emp_ID#">
    <cfcol header = "<b>Name/Email</b>"
        align = "Left"
        width = 15
        text  = "<a href = ’mailto:#Email#’>#FirstName# #LastName#</A>">
    <cfcol header = "<b>Phone Number</b>"
        align = "Center"
        width = 15
        text  = "#Phone#">
</cftable>


cfcollection

Description

Creates and administers Verity search engine collections.

Category

Extensibility tags

Syntax

<cfcollection
    action = "action"
    collection = "collection_name"
    path = "path_to_verity_collection"
    language = "language"
    name = "queryname"
categories = "yes" or "no">

See also

cfexecute , cfindex , cfobject , cfreport , cfsearch , cfwddx

History

ColdFusion MX 7:

  • Removed reference to external collections.
  • Deprecated the map and repair options of the action attribute. They might not work, and might cause an error, in later releases.
  • Added categories attribute and categorylist action.
  • Added CATEGORIES, SIZE, DOCCOUNT, and LASTMODIFIED to list of variables returned by the list action.
  • Marked as obsolete the MAPPED, ONLINE, and REGISTERED variables returned by the list action.

ColdFusion MX:

  • Changed the requirements for the action attribute: it is now required.
  • Added the action attribute list value. It is the default.
  • Changed the requirements for the action attribute value map: it is not necessary to specify the action attribute value map. (ColdFusion detects collections and creates maps collections as required.)
  • Changed acceptable collection naming: this tag accepts collection names that include spaces.
  • Changed Verity operations behavior: ColdFusion supports Verity operations on Acrobat PDF files.
  • Changed thrown exceptions: this tag can throw the SEARCHENGINE exception.

Attributes

Attribute

Req/Opt

Default

Description

action

Required; see Usage

list
  • categorylist: retrieves categories from the collection and indicates how many documents are in each one. Returns a structure of structures in which the category representing each substructure is associated with a number of documents. For a category in a category tree, the number of documents is the number at or below that level in the tree.
  • create: registers the collection with ColdFusion.
    • If the collection is present: creates a map to it.
    • If the collection is not present: creates it.
  • delete: unregisters a collection and deletes its directories.
  • list: returns a query result set, named from the name attribute value, of the attributes of the collections that are registered by ColdFusion.
  • map: creates a map to a collection. If the action is create and the collection already exists, Coldfusion also creates a map to the collection.
  • optimize: optimizes the structure and contents of the collection for searching; recovers space. Causes collection to be taken offline, preventing searches and indexing.
  • repair: deprecated. Does nothing.

collection

See Usage

  • A collection name. The name can include spaces.

path

See Usage

Absolute path to a Verity collection.

To map an existing collection, specify a fully qualified path to the collection (not including the collection name); for example, "C:\MyCollections\".

language

See Usage

English

Although English is the default language, Englishx, a more advanced English locale, is also provided. For a list of options, see Usage.

Requires the appropriate (European or Asian) Verity Locales language pack.

name

See Usage

Name for the query results returned by the list and categorylist actions.

categories

See Usage

no

Used only for creating a collection:

  • yes: this collection includes support for categories.
  • no: this collection does not support categories.

Usage

With this tag you can create, register, and administer a Verity collection that was created by ColdFusion or by a Verity application.

The following table shows the dependence relationships among this tag’s attribute values:

This attribute is required, optional, or unnecessary (blank):

For this action attribute value:

list

create

map

optimize

repair

delete

categorylist

collection

Required

Required

Required

Required

Required

Required

path

Required

Required

language

Optional

Optional

name

Required

Required

categories

The following examples illustrate the structures returned by the categorylist action:

CATEGORIES
blue | 10
green | 3
magenta | 3
purple | 2
CATEGORYTREES
a/ | 10
a/b | 10
a/b/c | 10
a/b/c/subdir | 3

The list action returns the following information in a result set that contains one row per collection:

Column

Contents

CATEGORIES
  • yes: the collection has category support enabled.
  • no: the collection does not have category support enabled.

CHARSET

The character set of the collection.

CREATED

The date and time that the collection was created.

DOCCOUNT

The number of documents in this collection.

EXTERNAL
  • yes: the collection is external.
  • no: the collection is not external.
  • Not Found: the collection is registered but is not available in the defined path .

LANGUAGE

The locale setting of the collection.

This information is not available for K2Server collections.

LASTMODIFIED

The date and time that the collection was last changed.

MAPPED

Obsolete

NAME

The name of the collection.

ONLINE

Obsolete

PATH

Absolute path to the collection.

REGISTERED

Obsolete

SIZE

The size of the collection, expressed in kilobytes.

The ColdFusion MX Administrator Verity > Collections page displays the information that is returned when you use the list attribute.

If the Verity Server is not running when the list action is executed, the tag throws an error.

To determine whether a collection exists, use code, such as the following, to execute a query of queries:

<cfcollection action="list" name="myCollections" >
<cfquery name="qoq" dbtype="query">
select * from myCollections
where myCollections.name = 'myCollectionName'
</cfquery>
<cfif qoq.recordcount GT 0>
    <!--- Collection exists --->
    <cfdump var = #qoq#>
</cfif>

To get a result set with values for all the collections that are registered with the Verity server, use code such as the following:

<cfcollection action="list" name="myCollections">
<cfoutput query="myCollections">
    #name#<br>
</cfoutput>

To add content to a collection, use cfindex. To search a collection, use cfsearch .

The language attribute of this tag supports the following options:

Asian Language Pack
Japanese | Korean | Chinese | Traditional Chinese
Multilanguage Language Pack
Unicode |  |  |
Western European Language Pack
Bokmal | Finnish | Italian | Spanish
Danish | French | Nynorsk | Swedish
Dutch | German | Portuguese |
Eastern European/Middle Eastern Language Pack
Arabic | Greek | Polish | Turkish
Bulgarian | Hebrew | Russian |
Czech | Hungarian | Russian2 |

The default location of Verity collections is as follows:

  • Server configuration:
    • Windows: C:\CFusionMX7\verity\collections
    • UNIX system: /opt/coldfusionmx7/verity/collections
  • J2EE configuration: webapp_root/WEB-INF/cfusion/verity/collections

Example

<!-------------------------------------------------------------------------
(coll_actn.cfm)
Check for server platform and use its default Verity Collection directory.
If you did not install ColdFusion MX in the default directory, or if you use
the J2EE configuration, or if your webroot is not C:\CFusionMX7\wwwroot, you
might need to change the path in this example. For example, for JRun4 the path
might be C:\JRun4\Verity\Collections\
--------------------------------------------------------------------------->
<cfif Find("Windows", Server.OS.Name)>
    <cfset collPath = "C:\JRun4\Verity\Collections\">
<cfelse>
    <cfset collpath = "/opt/coldfusionmx7/verity/collections/">
</cfif>

<!--------------------------------------------------------------------------
Process form input and do the requested cfcollection operation.
--------------------------------------------------------------------------->

<cfif IsDefined("form.CollectionName") AND IsDefined("form.CollectionAction")>
    <cfif form.CollectionName is not "">
        <cfswitch expression="#FORM.CollectionAction#">
          <cfcase value="Create">
            <cfcollection action="CREATE" collection="#FORM.CollectionName#"
                    path="#collPath#" categories="yes">
            <h3>Collection created.<br>
            Use CFINDEX to populate it.</h3>
          </cfcase>
          <cfcase value="Repair">
            <cfcollection action="REPAIR" collection="#FORM.CollectionName#">
            <h3>Collection repaired.</h3>
          </cfcase>
          <cfcase value="Optimize">
            <cfcollection action="OPTIMIZE" collection="#FORM.CollectionName#">
            <h3>Collection optimized.</h3>
          </cfcase>
          <cfcase value="Delete">
            <cfcollection action="DELETE" collection="#FORM.CollectionName#">
           <h3>Collection deleted.</h3>
          </cfcase>
        </cfswitch>
    <cfelse>
    <h3>Please enter a name for your collection</h3>
    </cfif>
</cfif>

<!--------------------------------------------------------------------
(coll_form.cfm)
Form to specify the collection name and action
    coll_form.cfm
--------------------------------------------------------------------->

<form action="coll_actn.cfm" method="POST" >
<select name="CollectionAction">
    <option value="Create">Create this collection
    <option value="Optimize">Optimize this collection
    <option value="Repair">Repair this collection
    <option value="Delete">Delete this collection
</select>

<p><strong>Collection on which to act</strong><br>
Use the default value or enter your own Collection name<br>
<input type="Text" name="CollectionName" value="My_coll"></p>

<input type="Submit" name="" value="alter or create my collection">
</form>


cfcomponent

Description

Creates and defines a component object; encloses functionality that you build in CFML and enclose within cffunction tags. This tag contains one or more cffunction tags that define methods. Code within the body of this tag, other than cffunction tags, is executed when the component is instantiated.

A component file has the extension CFC and is stored in any directory of an application.

A component method is invoked in the following ways:

  • Within the cfinvoke tag in a ColdFusion page
  • Within a URL that calls a CFC file and passes a method name as a URL parameter
  • Within the cfscript tag
  • As a web service
  • From Flash code

Category

Extensibility tags

Syntax

<cfcomponent
    extends ="anotherComponent"
    output = "yes" or "no"
    style = "rpc" or "document"
    namespace = "default service namespace"
    serviceportname = "port element name"
    porttypename = "porttype element name"
    bindingname = "binding element name"
    wsdlfile = "path to hard-coded wsdl file"
    displayname = "text string">
    hint = "text string">
    variable declarations
    <cffunction ...>
        ...
    </cffunction>

    <cffunction ...>
        ...
    </cffunction>
</cfcomponent>

See also

cfargument , cffunction , cfinvoke , cfinvokeargument , cfobject , cfproperty , cfreturn , Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added support for publishing document-literal style web services.
  • Added the style, namespace, serviceportname, porttypename, wsdlfile, and bindingname attributes.
  • Extended functionality for the hint and displayname attributes when publishing document-literal style web services.

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

extends

Optional

Name of parent component from which to inherit methods and properties.

output

Optional

Component body displayable text is processed as standard CFML

Specifies whether constructor code in the component can generate HTML output; does not affect output in the body of cffunction tags in the component.

  • yes: Constructor code is processed as if it were within a cfoutput tag. Variable names surrounded by number signs (#) are automatically replaced with their values.
  • no: Constructor code is processed as if it were within a cfsilent tag.
  • If you do not specify this attribute, constructor code is processed as standard CFML. Any variables must be in cfoutput tags.

style

Optional

rpc

Specifies whether a CFC used for web services uses RPC-encoded style or document-literal style:

  • rpc: RPC-encoded style
  • document: document-literal style

namespace

Optional

classname

Specifies the namespace used in the WSDL when using the CFC as a document-literal style web service. If you don’t specify this attribute, ColdFusion MX derives the value from the CFC class name.

This attribute applies only when style="document".

serviceportname

Optional

Specifies the name attribute of the port element in the WSDL. If you don’t specify this attribute, ColdFusion MX derives the value from the CFC class name.

This attribute applies only when style="document".

porttypename

Optional

Specifies the name attribute of the porttype element in the WSDL. If you don’t specify this attribute, ColdFusion MX derives the value from the CFC class name.

This attribute applies only when style="document".

bindingname

Optional

Specifies the binding attribute of the port element in the WSDL. If you don’t specify this attribute, ColdFusion MX derives the value from the CFC class name.

This attribute applies only when style="document".

wsdlfile

Optional

A properly formatted WSDL file to be used instead of WSDL generated by ColdFusion MX.

This attribute applies only when style="document".

displayname

Optional

A string to be displayed when using introspection to show information about the CFC. The information appears on the heading, following the component name.

If the style attribute is set to document, ColdFusion MX uses the displayname attribute as the name attribute of the service element in the WSDL.

hint

Optional

Text to be displayed when using introspection to show information about the CFC. The hint attribute value appears below the component name heading. This attribute can be useful for describing the purpose of the parameter.

If the style attribute is set to document, ColdFusion MX uses the hint attribute as the content of the documentation element of the service in the WSDL.

Usage

If you specify the extends attribute, the data and methods of the parent component are available to CFC methods as if they were parts of the current component. If the managerCFC component extends the employeeCFC component, and the employeeCFC component has a getEmployeeName method, you can call this method using the managerCFC, as follows:

<cfinvoke component="managerCFC" method="getEmployeeName" returnVariable="managerName" EmployeeID=#EmpID#>

This tag requires an end tag.

If you specify style="document", ColdFusion MX publishes the CFC as a document-literal style web service. For more information, see Publishing document-literal style web services in Using Web Services in ColdFusion MX Developer’s Guide.

Example

<cfcomponent>
    <cffunction name="getEmp">
         <cfquery name="empQuery" datasource="cfdocexamples" >
             SELECT FIRSTNAME, LASTNAME, EMAIL
             FROM tblEmployees
         </cfquery>
         <cfreturn empQuery>
    </cffunction>

    <cffunction name="getDept">
        <cfquery name="deptQuery" datasource="cfdocexamples" >
             SELECT *
             FROM tblDepartments
         </cfquery>
         <cfreturn deptQuery>
    </cffunction>
</cfcomponent>


cfcontent

Description

Does either or both of the following:

  • Sets the MIME content encoding header for the current page; if the encoding information includes a character encoding, sets the character encoding of generated output.
  • Sends the contents of a file, or of a variable that contains binary data, as the page output.

To restrict this tag, use the Sandbox Security feature of the ColdFusion MX Administrator. For more information, see the Administrator online Help.

Category

Data output tags

Syntax

<cfcontent
    type = "file_type"
    deleteFile = "yes" or "no"
    file = "filename"
    variable = "variablename"
    reset = "yes" or "no">

See also

cfcol , cfheader , cfhttp , cfoutput , cftable

History

ColdFusion MX 7: Added the variable attribute.

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

The MIME content type of the page, optionally followed by a semicolon and the character encoding. By default, ColdFusion sends pages as text/html content type in the UTF-8 character encoding.

The content type determines how the browser or client interprets the page contents.

The following are some of the content type values you can use:

  • text/html
  • text/plain
  • application/x-shockwave-flash
  • application/msword
  • image/jpeg

The following list includes commonly used character encoding values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For example:

type = "text/html"

type = "text/html; charset=ISO-8859-1"

deleteFile

Optional

no

Applies only if you specify a file with the file attribute.

  • yes: deletes the file on the server after sending its contents to the client.
  • no: leaves the file on the server.

file

Optional

Name of file whose contents will be the page output. The file name must start with a drive letter and a colon, or a forward or backward slash. When using ColdFusion in a distributed configuration, the file attribute must refer to a path on the system on which the web server runs. When you use this attribute, any other output on the current CFML page is ignored; only the contents of the file are sent to the client.

variable

Optional

Name of a ColdFusion MX binary variable whose contents can be displayed by the browser, such as the contents of a chart generated by the cfchart tag or a PDF or Excel file retrieved by a cffile action="readBinary" tag. When you use this attribute, any other output on the current CFML page is ignored; only the contents of the file are sent to the client.

reset

Optional

yes

If you specify a file or variable attribute, this attribute has no effect; otherwise, it does the following:

  • yes: discards output that precedes call to cfcontent
  • no: preserves output that precedes call to cfcontent. In this case, all output is sent with the specified type.

Usage

To set the character encoding (character set) of generated output, including the page HTML, use code such as the following:

<cfcontent type="text/html; charset=ISO-8859-1">

When ColdFusion processes an HTTP request, it determines the character encoding to use for the data it returns in the HTTP response. By default, ColdFusion returns character data using the Unicode UTF-8 format, regardless of the value of an HTML meta tag in the page. You can use the cfcontent tag to override the default character encoding of the response. For example, to tell ColdFusion MX to return the page using Japanese EUC character encoding, use the type attribute, as follows:

<cfcontent type="text/html; charset=EUC-JP">

If you call the cfcontent tag from a custom tag, and you do not want the tag to discard the current page when it is called from another application or custom tag, set reset = "no".

If a file delete operation is unsuccessful, ColdFusion throws an error.

Do not use this tag after the cfflush tag on a page, it will have no effect or ColdFusion will throw an error.

The following tag can force most browsers to display a dialog box that asks users whether they want to save the contents of the file specified by the cfcontent tag using the filename specified by the filename value. If the user selects to open the file, most browsers open the file in the related application, not the browser window.

<cfheader name="Content-Disposition" value="attachment; filename=filename.ext">

Some file types, such as PDF documents, do not use executable code and can display directly in most browsers. To request the browser to display the file directly, use a cfheader tag similar to the following:

<cfheader name="Content-Disposition" value="inline; filename=name.ext">

You can use any value for the filename part of the filename attribute, but the ext part must be the standard Windows extension for the file type.

For file types that might contain executable code, such as Microsoft Excel documents, most browsers always ask before opening the document. For these file types, the inline content disposition specification requests the browser to display the file directly if the user selects to open the file.

For more information on character encodings, see the following web pages:

  • www.w3.org/International/O-charset.html provides general information on character encodings and the web, and has several useful links.
  • www.iana.org/assignments/character-sets is a complete list of character sets names used on the Internet, maintained by the Internet Assigned Numbers Authority.
  • java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html lists the character encodings that Java, and therefore ColdFusion, can interpret. This list uses Java internal names, not the IANA character encoding names that you use in the SetEncoding charset parameter and other ColdFusion attributes and parameters. ColdFusion MX 6.0 Updater 3 uses JDK 1.3. CFMX 6.1 uses JDK 1.4.2; for encoding support, see http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html.

For a complete list of media types used on the Internet, see www.iana.org/assignments/media-types/.

Example

<!--- CFCONTENT Example 1
This example shows the use of cfcontent to return the contents of the CF
Documentation page dynamically to the browser. You might need to change the
path and/or drive letter depending on how ColdFusion is installed on your
system. Notice that the graphics do not display and the hyperlinks do not work,
because the html page uses relative filename references.
The root of the reference is the ColdFusion page, not the location of the
html page. --->

<cfcontent type = "text/html"
file = "C:\CFusionMX7\wwwroot\cfdocs\dochome.htm"
deleteFile = "no">

<!--- CFCONTENT EXAMPLE 2
This example shows how the Reset attribute changes text output. Notice how the
first text section ("This example shows how the Reset attribute changes output
for text reset = "Yes":123) does NOT print out to the screen. --->

<p>This example shows how the Reset attribute changes output for text.</p>
<p>reset = "Yes": 123 <BR> <cfcontent type = "text/html" reset = "Yes">456</p>
<p>This example shows how the Reset attribute changes output for text.</p>
<p>reset = "No": 123 <BR> <cfcontent type = "text/html" reset = "No">456</p>
<!--- CFCONTENT EXAMPLE 3
This example triggers a download of an Excel file. The user will be prompted
with an option to save the file or open it in the browser. --->

<cfheader name="Content-Disposition" value="inline; filename=acmesales03.xls">
<cfcontent type="application/vnd.ms-excel" file="c:\temp\acmesales03.xls">

<!--- CFCONTENT EXAMPLE 4
This example triggers a download of a Word document then deletes the original
from the "temp" directory. The user will be prompted
with an option to save the file or open it in the browser. --->

<cfheader name="Content-Disposition" value="inline; filename=temp.doc">
<cfcontent type="application/msword" file="c:\temp\Cable.doc" deletefile="yes">

<!--- CFCONTENT EXAMPLE 5
This example causes the browser to treat the HTML table as Excel data.
Excel interprets the table format.
Because Excel can include executable code, the browser prompts the user whether
to save the file or open it in a browser. --->

<cfheader name="Content-Disposition" value="inline; filename=acmesalesQ1.xls">
<cfcontent type="application/vnd.msexcel">

<table border="2">
<tr><td>Month</td><td>Quantity</td><td>$ Sales</td></tr>
<tr><td>January</td><td>80</td><td >$245</td></tr>
<tr><td>February</td><td>100</td><td>$699</td></tr>
<tr><td>March</td><td>230</td><td >$2036</td></tr>
<tr><td>Total</td><td>=Sum(B2..B4)</td><td>=Sum(C2..C4)</td></tr>
</table>


cfcookie

Description

Defines web browser cookie variables, including expiration and security options.

Category

Forms tags, Variable manipulation tags

Syntax

<cfcookie
    name = "cookie_name"
    value = "text"
    expires = "period"
    secure = "yes" or "no"
    path = "url"
    domain = ".domain">

See also

cfdump , cfparam , cfregistry , cfsavecontent , cfschedule , cfset

History

ColdFusion MX 6.1:

  • Changed the expires attribute: it now accepts a date time object.
  • Cookie names can include all ASCII characters except commas, semicolons, or whitespace characters.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

Name of cookie variable. ColdFusion converts cookie names to all-uppercase. Cookie names set using this tag can include any printable ASCII characters except commas, semicolons or white space characters.

value

Optional

Value to assign to cookie variable. Must be a string or variable that can be stored as a string.

expires

Optional

Expiration of cookie variable.

  • The default: the cookie expires when the user closes the browser, that is, the cookie is "session only".
  • A date or date/time object (for example, 10/09/97)
  • A number of days (for example, 10, or 100)
  • now: deletes cookie from client cookie.txt file (but does not delete the corresponding variable the Cookie scope of the active page).
  • never: The cookie expires in 30 years from the time it was created (effectively never in web years).

secure

Optional

If browser does not support Secure Sockets Layer (SSL) security, the cookie is not sent. To use the cookie, the page must be accessed using the https protocol.

  • yes: Variable must be transmitted securely.
  • no

path

Optional

URL, within a domain, to which the cookie applies; typically a directory. Only pages in this path can use the cookie. By default, all pages on the server that set the cookie can access the cookie.

path = "/services/login"

To specify multiple URLs, use multiple cfcookie tags.

If you specify path, you must also specify domain.

domain

Required if path attribute is specified.
Optional otherwise

Domain in which cookie is valid and to which cookie content can be sent from the user’s system. By default, the cookie is only available to the server that set it. Use this attribute to make the cookie available to other servers.

Must start with a period. If the value is a subdomain, the valid domain is all domain names that end with this string. This attribute sets the available subdomains on the site upon which the cookie can be used.

For a domain value that ends in a country code, the specification must contain at least three periods; for example, ".mongo.state.us". For top-level domains, two periods are required; for example, ".mgm.com".

You cannot use an IP address as a domain.

Usage

If this tag specifies that a cookie is to be saved beyond the current browser session, the client browser writes or updates the cookie in its local cookies file. Until the browser is closed, the cookie resides in browser memory. If the expires attribute is not specified, the cookie is not written to the browser cookies file.

If you use this tag after the cfflush tag on a page, ColdFusion does not send the cookie to the browser; however, the value you set is available to ColdFusion in the Cookie scope during the browser session.

Note: You can also create a cookie that expires when the current browser session expires by using the cfset tag or a CFScript assignment statement to set a variable in the Cookie scope, as in <cfset Cookie.mycookie="sugar">. To get a cookie’s value, refer to the cookie name in the Cookie scope, as in <cfif Cookie.mycookie is "oatmeal">.

You can use dots in cookie names, as the following examples show:

<cfcookie name="person.name" value="wilson, john">
<cfset cookie.person.lastname="Santiago">

To access cookies, including cookies that you set and all cookies that are sent by the client, use the Cookie scope. For example, to display the value of the person.name cookie set in the preceding code, use the following line:

<cfoutput>#cookie.person.name#</cfoutput>

Example

<!--- This example shows how to set/delete a cfcookie variable. --->
<!--- Select users who have entered comments into a sample database. --->
<cfquery name = "GetAolUser" dataSource = "cfdocexamples">
    SELECT EMail, FromUser, Subject, Posted
    FROM Comments
</cfquery>
<html>
<body>
<h3>cfcookie Example</h3>
<!--- If the URL variable delcookie exists, set cookie expiration date
to NOW --->
<cfif IsDefined("url.delcookie") is True>
    <cfcookie name = "TimeVisited"
    value = "#Now()#"
    expires = "NOW">
<cfelse>
<!--- Otherwise, loop through list of visitors; stop when you match
the string aol.com in a visitor’s e-mail address. --->
<cfloop query = "GetAolUser">
    <cfif FindNoCase("aol.com", Email, 1) is not 0>
        <cfcookie name = "LastAOLVisitor"
        value = "#Email#"
        expires = "NOW" >
    </cfif>
</cfloop>
<!--- If the timeVisited cookie is not set, set a value. --->
    <cfif IsDefined("Cookie.TimeVisited") is False>
        <cfcookie name = "TimeVisited"
        value = "#Now()#"
        expires = "10">
    </cfif>
</cfif>
<!--- Show the most recent cookie set. --->
<cfif IsDefined("Cookie.LastAOLVisitor") is "True">
    <p>The last AOL visitor to view this site was
    <cfoutput>#Cookie.LastAOLVisitor#</cfoutput>, on
    <cfoutput>#DateFormat(COOKIE.TimeVisited)#</cfoutput>
<!--- Use this link to reset the cookies. --->
<p><a href = "cfcookie.cfm?delcookie = yes">Hide my tracks</A>
<cfelse>
    <p>No AOL Visitors have viewed the site lately.
</cfif>


cfdefaultcase

Description

Used only inside the cfswitch tag body. Contains code to execute when the expression specified in the cfswitch tag does not match a of the value specified by a cfcase tag.

Category

Flow-control tags

Syntax

<cfdefaultcase>

See also

cfcase, cfswitch; cfswitch, cfcase, and cfdefaultcase in Elements of CFML in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed placement requirements: this tag does not have to follow all cfcase tags in the cfswitch tag body.

Usage

The contents of the cfdefaultcase tag body is executes if the expression attribute of the cfswitch tag does not match any of the values specified by the cfcase tags in the cfswitch tag body. The contents of the cfdefaultcase tag body can include HTML and text, and CFML tags, functions, variables, and expressions.

You can specify only one cfdefaultcase tag within a cfswitch tag. You can put the cfdefaultcase tag at any position within a cfswitch statement; it is not required to be the last item, but it is good programming practice to put it last.

Example

<!--- The following example displays a grade based on a 1-10 score.
        Several of the cfcase tags match more than one score.
        For simplicity, the example sets the score to 7. --->
<cfset score="7">
<cfswitch expression="#score#">
    <cfcase value="10">
        <cfset grade="A">
    </cfcase>
    <cfcase value="9;8" delimiters=";">
        <cfset grade="B">
    </cfcase>
    <cfcase value="7;6" delimiters=";">
        <cfset grade="C">
    </cfcase>
    <cfcase value="5;4;" delimiters=";">
        <cfset grade="D">
    </cfcase>
    <cfdefaultcase>
        <cfset grade="F">
    </cfdefaultcase>
</cfswitch>
<cfoutput>
    Your grade is #grade#
</cfoutput>


cfdirectory

Description

Manages interactions with directories.

Category

File management tags

Syntax

<cfdirectory
    action = "directory action"
    directory = "directory name"
    name = "query name"
    filter = "list filter"
    mode = "permission"
    sort = "sort specification"
    newDirectory = "new directory name"
    recurse = "yes" or "no">

See also

cffile

History

ColdFusion MX 7: Added the recurse attribute (named recursive in Alpha 1) and directory result-set column.

ColdFusion MX:

  • Changed behavior for action = "list":
    • On Windows, cfdirectory action = "list" no longer returns the directory entries "." (dot) or ".." (dot dot), which represent "the current directory" and "the parent directory."
    • On Windows, cfdirectory action = "list" no longer returns the values of the Archive and System attributes.
    • On UNIX and Linux, cfdirectory action = "list" does not return any information in the mode column.

Attributes

Attribute

Req/Opt

Default

Description

action

Optional

List
  • list: returns a query record set of the files in the specified directory. The directory entries "." (dot) and ".." (dot dot), which represent the current directory and the parent directory, are not returned.
  • create
  • delete
  • rename

directory

Required

Absolute pathname of directory against which to perform action.

You can use an IP address, as in the following example:

<cfdirectory directory="//12.3.123.123/c_drive/" name="dirQuery" action="LIST">

name

Required if action = "list"

Name for output record set.

filter

Optional if action = "list"

File extension filter applied to returned names; for example, *.cfm. One filter can be applied.

mode

Optional

Used with action = "create". Permissions. Applies only to UNIX and Linux. Octal values of chmod command. Assigned to owner, group, and other, respectively. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

sort

Optional; used if action = "list"

ASC

Query column(s) by which to sort directory listing. Delimited list of columns from query output.

To qualify a column, use:

  • asc: ascending (a to z) sort order.
  • desc: descending (z to a) sort order.

For example:

sort = "directory ASC, size DESC, datelastmodified"

newDirectory

Required if action = "rename"

New name for directory.

recurse

Optional

no

Whether ColdFusion performs the action on subdirectories:

  • yes
  • no

Valid for action="list" and action="delete".

Usage

If you put ColdFusion applications on a server that is used by multiple customers, you must consider the security of files and directories that could be uploaded or otherwise manipulated with this tag by unauthorized users. For more information about securing ColdFusion tags, see Configuring and Administering ColdFusion MX.

If action = "list", cfdirectory returns the following result columns, which you can reference in a cfoutput tag:

  • name Directory entry name. The entries "." and ".." are not returned.
  • directory Directory containing the entry.
  • size Directory entry size.
  • type File type: File, for a file; Dir, for a directory.
  • dateLastModified The date that an entry was last modified.
  • attributes File attributes, if applicable.
  • mode Empty column; retained for backward compatibility with ColdFusion 5 applications on UNIX.

You can use the following result columns in standard CFML expressions, preceding the result column name with the query name:

#mydirectory.name#
#mydirectory.directory#
#mydirectory.size#
#mydirectory.type#
#mydirectory.dateLastModified#
#mydirectory.attributes#
#mydirectory.mode#

Note: If the cfdirectory tag does not appear to work, for example, if a list operation returns an empty result set, make sure that you have correct permissions to access the directory. For example, if you run ColdFusion as a service on Windows, it operates by default as System, and cannot access directories on a remote system or mapped drive; to resolve this issue, do not run ColdFusion using the local system account.

The filter attribute specifies a pattern of one or more characters. All names that match that pattern are included in the list. On Windows systems, pattern matching ignores text case, on UNIX and Linux, pattern matches are case-sensitive.

The following two characters have special meaning in the pattern and are called metacharacters:

  • * matches any zero or more characters
  • ? matches any single character

The following table shows examples of patterns and file names that they match:

Pattern | Matches
foo.* | Any file called foo with any extension; for example, foo.html, foo.cfm, and foo.xml.
*.html | All files with the suffix .html, but not files with the suffix .htm.
?? | All files with two-character names.

Example

<!--- EXAMPLE 1: Creating and Renaming
Check that the directory exists to avoid getting a
ColdFusion error message. --->
<cfset newDirectory = "otherNewDir">
<cfset currentDirectory = GetDirectoryFromPath(GetTemplatePath()) & "newDir">
<!--- Check to see if the Directory exists. --->
<cfif DirectoryExists(currentDirectory)>
<!--- If TRUE then rename the directory. --->
    <cfdirectory action = "rename" directory = "#currentDirectory#" newDirectory = "#newDirectory#" >
    <cfoutput>
    <p>The directory existed and the name has been changed to: #newDirectory#</p>
    </cfoutput>
<cfelse>
    <!--- If FALSE, create the directory. --->
    <cfdirectory action = "create" directory = "#currentDirectory#" >
    <cfoutput><p>Your directory has been created.</p></cfoutput>
</cfif>

<!--- EXAMPLE 2: Deleting a directory
Check that the directory exists and that files are not in the directory
to avoid getting ColdFusion error messages. --->

<cfset currentDirectory = GetDirectoryFromPath(GetTemplatePath()) & "otherNewDir">
<!--- Check to see if the Directory exists. --->
<cfif DirectoryExists(currentDirectory)>
    <!--- If TRUE, check to see if there are files in the directory before deleting. --->
    <cfdirectory action="list" directory="#currentDirectory#"
    name="myDirectory">
    <cfif myDirectory.recordcount gt 0>
    <!--- If TRUE, delete the files from the directory. --->
        <cfoutput>
        <p>Files exist in this directory. Either delete the files or code
            something to do so.</P>
        </cfoutput>
    <cfelse>
    <!--- Directory is empty - just delete the directory. --->
        <cfdirectory action = "delete" directory = "#currentDirectory#">
        <cfoutput>
        <p>The directory existed and has been deleted.</P>
        </cfoutput>
    </cfif>
<cfelse>
    <!--- If FALSE, post message or do some other function. --->
    <cfoutput><p>The directory did NOT exist.</p></cfoutput>
</cfif>
<!---EXAMPLE 3: List directories
The following example creates both an array of directory names and a query that
contains entries for the directories only. --->

<cfdirectory directory="C:/temp" name="dirQuery" action="LIST">

<!--- Get an array of directory names. --->
<cfset dirsArray=arraynew(1)>
<cfset i=1>
<cfloop query="dirQuery">
<cfif dirQuery.type IS "dir">
    <cfset dirsArray[i]=dirQuery.name>
    <cfset i = i + 1>
</cfif>
</cfloop>
<cfdump var="#dirsArray#">
<br>
<!--- Get all directory information in a query of queries.--->
<cfquery dbtype="query" name="dirsOnly">
SELECT * FROM dirQuery
WHERE TYPE='Dir'
</cfquery>
<cfdump var="#dirsOnly#">


cfdocument

Description

Creates PDF or FlashPaper output from a text block containing CFML and HTML.

Category

Data output tags

Syntax

<cfdocument
    format = "PDF" or "FlashPaper"
    filename = "filename"
    overwrite = "yes" or "no"
    name = "output variable name"
    pagetype = "page type"
    pageheight = "page height in inches"
    pagewidth = "page width in inches"
    orientation = "portrait/landscape"
    margintop = "number"
    marginbottom = "number"
    marginleft = "number"
    marginright = "number"
    unit = "in" or "cm"
    encryption = "128-bit" or "40-bit" or "none"
    ownerpassword = "password"
    userpassword = "password"
    permissions = "permission list"
    fontembed = "yes" or "no"
    backgroundvisible = "yes" or "no"
    scale = "percentage less than 100">

    HTML and CFML code
</cfdocument>

See also

cfreport , cfdocumentitem, cfdocumentsection

History

ColdFusion MX 7: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

format

Required

Specifies the report format:

  • PDF
  • FlashPaper

filename

Optional

Specifies the name of a file to contain the PDF or FlashPaper output.

If you omit the filename attribute, ColdFusion MX streams output to the browser.

overwrite

Optional

no

Specifies whether ColdFusion MX overwrites an existing file. Used in conjunction with the filename attribute

name

Optional

Specifies the name of an existing variable into which the tag stores the PDF or FlashPaper output.

pagetype

Optional

A4

Specifies the page size into which ColdFusion generates the report:

  • legal: 8.5 inches x 14 inches.
  • letter: 8.5 inches x 11 inches.
  • A4: 8.27 inches x 11.69 inches.
  • A5: 5.81 inches x 8.25 inches.
  • B5: 9.81 inches x 13.88 inches.
  • Custom: custom height and width. If you specify custom, you must also specify the pageheight and pagewidth attributes, can optionally specify margin attributes, and can optionally specify whether the units are inches or centimeters.

pageheight

Optional

Specifies the page height in inches (default) or centimeters. This attribute is only valid if pagetype=custom. To specify page height in centimeters, include the unit=cm attribute.

pagewidth

Optional

Specifies the page width in inches (default) or centimeters. This attribute is only valid if pagetype=custom. To specify page width in centimeters, include the unit=cm attribute.

orientation

Optional

portrait

Specifies the page orientation:

  • portrait
  • landscape

margintop

Optional

Specifies the top margin in inches (default) or centimeters. To specify the top margin in centimeters, include the unit=cm attribute.

marginbottom

Optional

Specifies the bottom margin in inches (default) or centimeters. To specify the bottom margin in centimeters, include the unit=cm attribute.

marginleft

Optional

Specifies the left margin in inches (default) or centimeters. To specify the left margin in centimeters, include the unit=cm attribute.

marginright

Optional

Specifies the right margin in inches (default) or centimeters. To specify the right margin in centimeters, include the unit=cm attribute.

unit

Optional

in

Specifies the default unit for the pageheight, pagewidth, and margin attributes:

  • in: inches.
  • cm: centimeters.

encryption

Optional

None

(format="PDF" only) Specifies whether the output is encrypted:

  • 128-bit
  • 40-bit
  • none

ownerpassword

Optional

(format="PDF" only) Specifies an owner password.

userpassword

Optional

(format="PDF" only) Specifies a user password.

permissions

Optional

(format="PDF" only) Specifies one or more of the following permissions:

  • AllowPrinting
  • AllowModifyContents
  • AllowCopy
  • AllowModifyAnnotations
  • AllowFillIn
  • AllowScreenReaders
  • AllowAssembly
  • AllowDegradedPrinting

Separate multiple permissions with a comma.

fontembed

Optional

yes

Specifies whether ColdFusion embeds fonts in the output:

  • yes: embed fonts.
  • no: do not embed fonts.

Selective: embed all fonts except Java fonts and core fonts. For more information, see Usage.

backgroundvisible

Optional

no

Specifies whether the background prints when the user prints the document:

  • yes: include the background when printing.
  • no: do not include the background when printing.

scale

Optional

Calculated by ColdFusion

Specifies a scale factor as a percentage. Use this option to reduce the size of the HTML output so that it fits on that paper. Specify a number less than 100.

Usage

Use the cfdocument tag to render HTML and CFML output into PDF or FlashPaper format. ColdFusion MX does not return HTML and CFML outside of the
<cfdocument> </cfdocument> pair.

The cfdocument tag can render HTML that supports the following standards:

  • HTML 4.01
  • XML 1.0
  • DOM Level 1 and 2
  • CSS1 and CSS2

The cfdocument tag does not support the Internet Explorer-specific HTML generated by Microsoft Word.

The PDF or FlashPaper document returned by the cfdocument tag overwrites any previous HTML in the input stream and ignores any HTML after the </cfdocument> tag.

You cannot embed a cfreport tag in a cfdocument tag.

When you use the cfdocument tag, ColdFusion MX creates a new scope named cfdocument. This scope contains the following variables:

  • currentpagenumber
  • totalpagecount

Note: The cfdocument scope variables are reserved for page number rendering. Do not use them in ColdFusion expressions. For example, the following code does not work:

<cfif cfdocument.currentpagenumber gt 1>
    <cfoutput>#cfdocument.currentpagenumber-1#</cfoutput>
</cfif>

Example

<cfdocument format="flashpaper">
<p>This is a document rendered by the cfdocument tag.</p>

<table width="50%" border="2" cellspacing="2" cellpadding="2">
  <tr>
    <td><strong>Name</strong></td>
    <td><strong>Role</strong></td>
  </tr>
  <tr>
    <td>Bill</td>
    <td>Lead</td>
  </tr>
  <tr>
    <td>Susan</td>
    <td>Principal Writer</td>
  </tr>
  <tr>
    <td>Adelaide</td>
    <td>Part Time Senior Writer</td>
  </tr>
  <tr>
    <td>Thomas</td>
    <td>Full Time for 6 months</td>
  </tr>
  <tr>
    <td>Michael</td>
    <td>Full Time for 4 months</td>
  </tr>
</table>
</cfdocument>


cfdocumentitem

Description

Specifies action items for a PDF or FlashPaper document created by the cfdocument tag. Actions include the following:

  • Page break
  • Header
  • Footer

Category

Data output tags

Syntax

<cfdocument ...>
Syntax 1
<cfdocumentitem type = "pagebreak"/>

Syntax 2
    <cfdocumentitem
        type = "header" or "footer">
header/footer text
</cfdocumentitem>

</cfdocument>

See also

cfreport , cfdocument, cfdocumentsection

History

ColdFusion MX 7: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

type

Required

Specifies the action:

  • pagebreak: start a new page at the location of the tag.
  • header: use the text between the <cfdocumentitem> and </cfdocumentitem> tags as the running header.
  • footer: use the text between the <cfdocumentitem> and </cfdocumentitem> tags as the running footer.

Usage

Use the cfdocumentitem tag to control the formatting of a PDF or FlashPaper report. This tag must be wrapped inside a <cfdocument> </cfdocument> pair.

Write code for one cfdocumentitem tag for each pagebreak, running header, or running footer.

You can use the cfdocument scope variable, cfdocument.currentpagenumber, to display the current page number in a header or footer. You can also use cfdocument.totalpagecount to display the total number of pages. For example:

...
<cfdocumentItem type= "footer>
   #cfdocument.currentpagenumber# of #cfdocument.totalpagecount#
</cfdocumentitem>

You can use cfdocumentitem tags with or without the cfdocumentsection tag, as follows:

Without cfdocumentsection The cfdocumentitem attribute applies to the entire document, as follows:

  • If the tag is at the top of the document, it applies to the entire document.
  • If the tag is in the middle of the document, it applies to the rest of the document.
  • If the tag is at the end of the document, it has no affect.

With cfdocumentsection tags The cfdocumentitem attribute applies only to the section and overrides previously specified header and footer specifications.

Example

<cfquery datasource="cfdocexamples" name="parksQuery">
SELECT parkname, suptmgr from parks
</cfquery>

<cfdocument format="PDF">
  <cfdocumentitem type="header">National Parks Report</cfdocumentitem>
  <!--- Use a footer with current page of totalpages format --->
  <cfdocumentitem type="footer">
    <cfoutput>Page #cfdocument.currentpagenumber# of #cfdocument.totalpagecount#</cfoutput>
 </cfdocumentitem>

<h1>Park list</h1>
<table width="95%" border="2" cellspacing="2" cellpadding="2" >
  <tr >
    <th>Park</th>
    <th>Manager</th>
  </tr>
 <cfoutput query="parksQuery">
   <tr>
    <td><font size="-1">#parkname#</font></td>
    <td><font size="-1">#suptmgr#</font></td>
   </tr>
 </cfoutput>
</table>
</cfdocument>


cfdocumentsection

Description

Divides a PDF or FlashPaper document into sections. By using this tag in conjunction with a cfdocumentitem tag, each section can have unique headers, footers, and page numbers.

Category

Data output tags

Syntax

<cfdocument ...>

    <cfdocumentsection
        margintop = "number"
        marginbottom = "number"
        marginleft = "number"
        marginright = "number">

    HTML, CFML, and cfdocumentitem tags
</cfdocumentsection>

</cfdocument>

See also

cfreport, cfdocument, cfdocumentitem

History

ColdFusion MX 7: Added this tag and the margintop, marginbottom, marginleft, marginright attributes.

Attributes

Attribute | Req/Opt | Default | Description
margintop | Optional |  | Specifies the top margin in inches (default) or centimeters. To specify the top margin in centimeters, include the unit="cm" attribute in the parent cfdocument tag.
marginbottom | Optional |  | Specifies the bottom margin in inches (default) or centimeters. To specify the bottom margin in centimeters, include the unit="cm" attribute in the parent cfdocument tag.
marginleft | Optional |  | Specifies the left margin in inches (default) or centimeters. To specify the left margin in centimeters, include the unit="cm" attribute in the parent cfdocument tag.
marginright | Optional |  | Specifies the right margin in inches (default) or centimeters. To specify the right margin in centimeters, include the unit="cm" attribute in the parent cfdocument tag.

Usage

Use the cfdocumentsection tag to divide a report into sections. Within each cfdocumentsection tag, you can use one or more cfdocumentitem tags to specify unique headers and footers for each section.

When using cfdocumentsection, ColdFusion MX ignores HTML and CFML not enclosed within cfdocumentsection tags.

The margin attributes override margins specified in previous sections or in the parent cfdocument tag. If you specify margin attributes, the units are controlled by the unit attribute of the parent cfdocument tag; the unit attribute has a default value of inches.

Example

<cfquery datasource="cfdocexamples" name="empSalary">
SELECT Emp_ID, firstname, lastname, e.dept_id, salary, d.dept_name
FROM employee e, departmt d
WHERE e.dept_id = d.dept_id
ORDER BY d.dept_name
</cfquery>

<cfdocument format="PDF">
  <cfoutput query="empSalary" group="dept_id">
    <cfdocumentsection>
    <cfdocumentitem type="header">
        <font size="-3"><i>Salary Report</i></font>
    </cfdocumentitem>
    <cfdocumentitem type="footer">
        <font size="-3">Page #cfdocument.currentpagenumber#</font>
    </cfdocumentitem>
    <h2>#dept_name#</h2>
     <table width="95%" border="2" cellspacing="2" cellpadding="2" >
      <tr>
         <th>Employee</th>
         <th>Salary</th>
      </tr>
      <cfset deptTotal = 0 >
      <!--- inner cfoutput --->
      <cfoutput>
        <tr>
          <td><font size="-1">
            #empSalary.lastname#, #empSalary.firstname#</font>
          </td>
          <td align="right"><font size="-1">
            #DollarFormat(empSalary.salary)#</font>
          </td>
         </tr>
         <cfset deptTotal = deptTotal + empSalary.salary>
      </cfoutput>
        <tr>
          <td align="right"><font size="-1">Total</font></td>
          <td align="right"><font size="-1">#DollarFormat(deptTotal)#</font></td>
        </tr>
        <cfset deptTotal = 0>
       </table>
      </cfdocumentsection>
    </cfoutput>
</cfdocument>


cfdump

Description

Use the cfdump tag to get the elements, variables, and values of most kinds of ColdFusion objects. Useful for debugging. You can display the contents of simple and complex variables, objects, components, user-defined functions, and other elements.

Category

Debugging tags, Variable manipulation tags

Syntax

<cfdump
    var = "#variable#"
    expand = "yes" or "no"
    label = "text"
    top = "number of rows or levels">

See also

cfcookie , cfparam , cfsavecontent , cfschedule , cfset , cftimer , cfwddx

History

  • ColdFusion MX 7: Added the top attribute.
  • ColdFusion MX 6.1: Added the ability to dump COM objects; it displays the methods and Get and Put properties typeinfo information for the object.

Attributes

Attribute

Req/Opt

Default

Description

var

Required

Variable to display. Enclose a variable name in number signs.

These kinds of variables yield meaningful cfdump displays:

  • array
  • CFC
  • COM object
  • Java object
  • simple
  • query
  • structure
  • UDF
  • wddx
  • xml

expand

Optional

yes
  • yes: in Internet Explorer and Mozilla, expands views.
  • no: contracts expanded views.

label

Optional

A string; header for the dump output.

top

Optional

9999

The number of rows to display. For a structure, this is the number of nested levels to display.

Usage

The expand/contract display capability is useful when working with large structures, such as XML document objects, structures, and arrays.

To display a construct, use code such as the following, in which myDoc is a variable of type XmlDocument:

<cfif IsXmlDoc(mydoc) is "yes">
    <cfdump var="#mydoc#">
</cfif>

The tag output is color-coded according to data type.

If a table cell is empty, this tag displays "[empty string]".

Example

<!--- This example shows how to use this tag to display the CGI scope as a structure: --->

<cfdump var="#cgi#">


cfelse

Description

Used as the last control block in a cfif tag block to handle any case not identified by the cfif tag or a cfelseif tag.

Category

Flow-control tags

Syntax

<cfif expression>
        HTML and CFML tags
    <cfelseif expression>
        HTML and CFML tags
    <cfelse>
        HTML and CFML tags
</cfif>

See also

cfif , cfelseif , cfabort , cfbreak , cfexecute , cfexit , cflocation , cfloop , cfswitch , cfthrow , cftry

Usage

If the values of the expressions in the containing cfif tag and all cfelseif tags are false, ColdFusion processes the code between this tag and the cfif end tag. This tag must be inside a cfif tag block. It does not require an end tag.

For more information and an example, see cfif.


cfelseif

Description

Used as a control block in a cfif tag block to handle any case not identified by the cfif tag or a cfelseif tag.

Category

Flow-control tags

Syntax

<cfif expression>
        HTML and CFML tags
    <cfelseif expression>
        HTML and CFML tags
    <cfelse>
        HTML and CFML tags
</cfif>

See also

cfif , cfelse , cfabort , cfbreak , cfexecute , cfexit , cflocation , cfloop , cfswitch , cfthrow , cftry

Usage

If the value of the expression in this tag is true, and the values of the expressions in the containing cfif tag and preceding cfelseif tags are false, ColdFusion processes the code between this tag and a following cfelseif or cfelse tag, or the cfif end tag and then skips to the code following the cfif end tag. Otherwise, ColdFusion skips the code.

This tag must be inside a cfif tag block. It does not require an end tag.

For more information and an example, see cfif.


cferror

Description

Displays a custom HTML page when an error occurs. This lets you maintain a consistent look and feel among an application’s functional and error pages.

Category

Exception handling tags, Extensibility tags, Application framework tags

Syntax

<cferror
    type = "a type"
    template = "template_path"
    mailTo = "email_address"
    exception = "exception_type">

See also

cfrethrow , cfthrow , cftry , Handling Errors in ColdFusion MX Developer’s Guide.

History

ColdFusion MX: Deprecated the monitor option of the exception attribute. It might not work, and might cause an error, in later releases.

Attributes

Attribute

Req/Opt

Default

Description

type

Required

Type of error that the custom error page handles. The type also determines how ColdFusion handles the error page. For more information, see Specifying a custom error page in Specifying a custom error page in ColdFusion MX Developer’s Guide.

  • exception: an exception of the type specified by the exception attribute.
  • validation: errors recognized by server-side type validation.
  • request: any encountered error.

template

Required

Relative path to the custom error page. (A ColdFusion page was formerly called a template.)

mailTo

Optional

An e-mail address. This attribute is available on the error page as the variable error.mailto. ColdFusion does not automatically send anything to this address.

exception

Optional

Any

Type of exception that the tag handles:

  • application: application exceptions.
  • database: database exceptions.
  • template: ColdFusion page exceptions.
  • security: security exceptions.
  • object: object exceptions.
  • missingInclude: missing include file exceptions.
  • expression: expression exceptions.
  • lock: lock exceptions.
  • custom_type: developer-defined exceptions, defined in the cfthrow tag.
  • any: all exception types.

For more information on exception types, see cftry.

Usage

Use this tag to provide custom error messages for pages in an application. This lets you maintain a consistent look and feel within the application, even when errors occur.

You generally embed this tag in your Application CFC or Application.cfm file to specify error-handling responsibilities for an entire application. You must put it in one of these files if you specify type="validation"; ColdFusion ignores it on any other page.

The cftry and cfcatch tags provide a more interactive way to handle ColdFusion errors within a ColdFusion page than the cferror tag, but the cferror tag is a good safeguard against general errors.

To ensure that error pages display successfully, avoid using the cfencode utility to encode pages that include the cferror tag.

Page types

The following table describes the types of errors you can specify and code you can use on the pages that handle these error type:

Page type

Description

Use

Exception

Dynamically invoked by the CFML language processor when it detects an unhandled exception condition.

Uses the full range of CFML tags. Error variables must be in cfoutput tags.

Can handle specific exception types or display general information for exceptions.

Request

Includes the error variables described in the Error Variables section.

Cannot include CFML tags, but you can display values of the error variables by enclosing them in number signs (#), as in #error.MailTo#.

Use as a backup error handler to other error handling methods, including exception type.

Validation

Handles data input validation errors that occur when submitting a form that uses hidden form-field validation or onSubmit validation.

Cannot include CFML tags, but you can display values of the error variables by enclosing them in number signs (#), as in #Error.InvalidFields#.

You must specify the validation error handler in the Application.cfc or Application.cfm file.

Handles hidden form-field or onSubmit format validation errors only.

Error variables

The exception-handling page specified in the cferror tag template attribute contains one or more error variables. ColdFusion substitutes the value of the error variable when an error displays.

The following table lists error variables:

Page type | Error variable | Description
Validation only | error.validationHeader | Validation message header text.
 | error.invalidFields | Unordered list of validation errors.
 | error.validationFooter | Validation message footer text.
Request and Exception | error.diagnostics | Detailed error diagnostics from ColdFusion MX.
 | error.mailTo | E-mail address (same as value in cferror.MailTo).
 | error.dateTime | Date and time when error occurred.
 | error.browser | Browser that was running when error occurred.
 | error.remoteAddress | IP address of remote client.
 | error.HTTPReferer | Page from which client accessed link to page where error occurred.
 | error.template | Page executing when error occurred.
 | error.generatedContent | The content generated by the page up to the point where the error occurred.
 | error.queryString | URL query string of client's request.
Exception only | error.message | Error message associated with the exception.
 | error.rootCause | The root cause of the exception. This structure contains the information that is returned by a cfcatch tag. For example, for a database exception, the SQL statement that caused the error is in the error.RootCause.Sql variable. For Java exceptions, this variable contains the Java servlet exception reported by the JVM as the cause of the "root cause" of the exception.
 | error.tagContext | Array of structures containing information for each tag in the tag stack. The tag stack consists of each tag that is currently open.
 | error.type | Exception type.

Note: If type = "exception", you can substitute the prefix cferror for Error; for example, cferror.diagnostics, cferror.mailTo, or cferror.dateTime.

Example

<h3>cferror Example</h3>

<!--- Example of cferror call within a page.
         NOTE: If you use cferror type="VALIDATION" you MUST put it in
         Application.cfc or Application.cfm --->
<cferror type = "REQUEST"
template = "request_err.cfm"
mailTo = "admin@mywebsite.com">
<!--- This query calls a non-existent datasource, triggering an error to be handled. --->
<cfquery name="testQuery" datasource="doesNotExist">
select * from nothing
</cfquery>

<!--- Example of the page (request_err.cfm) to handle this error. --->
<html>
<head>
<title>We're sorry -- An Error Occurred</title>
</head>
<body>
<h2>We're sorry -- An Error Occurred</h2>
<p>
If you continue to have this problem, please contact #error.mailTo#
with the following information:</p>
<p>
<ul>
<li><b>Your Location:</b> #error.remoteAddress#
<li><b>Your Browser:</b> #error.browser#
<li><b>Date and Time the Error Occurred:</b> #error.dateTime#
<li><b>Page You Came From:</b> #error.HTTPReferer#
<li><b>Message Content</b>:
<p>#error.diagnostics#</p>
</ul>


cfexecute

Description

Executes a ColdFusion developer-specified process on a server computer.

Category

Extensibility tags, Flow-control tags

Syntax

<cfexecute
    name = "application name"
    arguments = "command line arguments"
    outputFile = "output filename"
    variable = "variable name"
    timeout = "timeout interval">
    ...
</cfexecute>

See also

cfcollection , cfindex , cfobject , cfreport , cfsearch , cfwddx

History

ColdFusion MX 6.1:

  • Added the variable attribute.
  • Changed file path behavior for the outputFile attribute: if you do not specify an absolute file path in the outputFile attribute, the path is relative to the ColdFusion temporary directory.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

Absolute path of the application to execute.

On Windows, you must specify an extension; for example, C:\myapp.exe.

arguments

Optional

Command-line variables passed to application. If specified as string, it is processed as follows:

  • Windows: passed to process control subsystem for parsing.
  • UNIX: tokenized into an array of arguments. The default token separator is a space; you can delimit arguments that have embedded spaces with double-quotation marks.

If passed as array, it is processed as follows:

  • Windows: Elements are concatenated into a string of tokens, separated by spaces. Passed to process control subsystem for parsing.
  • UNIX: Elements are copied into an array of exec() arguments.

outputFile

Optional

File to which to direct program output. If no outputfile or variable attribute is specified, output is displayed on the page from which it was called.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

variable

Optional

Variable in which to put program output. If no outputfile or variable attribute is specified, output is displayed on page from which it was called.

timeout

Optional

0

Length of time, in seconds, that ColdFusion waits for output from the spawned program.

  • 0: equivalent to nonblocking mode.
  • A very high value: equivalent to blocking mode.

If the value is 0:

  • ColdFusion starts a process and returns immediately. ColdFusion may return control to the calling page before any program output displays. To ensure that program output displays, set the value to 2 or higher.
  • If the outputFile attribute is not specified, any program output is discarded

Usage

Do not put other ColdFusion tags or functions between the start and end tags of cfexecute. You cannot nest cfexecute tags.

Exceptions

Throws the following exceptions:

  • If the application name is not found: java.io.IOException
  • If the effective user of the ColdFusion executing thread does not have permissions to execute the process: a security exception

The time out values must be between zero and the longest time out value supported by the operating system.

Example

<h3>cfexecute</h3>
<p>This example executes the Windows NT version of the netstat network
monitoring program, and places its output in a file.

<cfexecute name = "C:\WinNT\System32\netstat.exe"
    arguments = "-e"
    outputFile = "C:\Temp\output.txt"
    timeout = "1">
</cfexecute>


cfexit

Description

This tag aborts processing of the currently executing CFML custom tag, exits the page within the currently executing CFML custom tag, or re-executes a section of code within the currently executing CFML custom tag.

Category

Debugging tags, Flow-control tags

Syntax

<cfexit
    method = "method">

See also

cfabort, cfbreak, cfexecute, cfif, cflocation, cfloop, cfswitch, cfthrow, cftry; cfabort and cfexit in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

method

Optional

exitTag
  • exitTag: aborts processing of currently executing tag.
  • exitTemplate: exits page of currently executing tag.
  • loop: re-executes body of currently executing tag.

Usage

If this tag is encountered outside the context of a custom tag, for example in the base page or an included page, it executes in the same way as cfabort. The cfexit tag can help simplify error checking and validation logic in custom tags.

The cfexit tag function depends on its location and execution mode:

Method value | Location of cfexit call | Behavior
exitTag | Base page | Terminate processing
 | Execution mode = Start | Continue after end tag
 | Execution mode = End | Continue after end tag
exitTemplate | Base page | Terminate processing
 | Execution mode = Start | Continue from first child in body
 | Execution mode = End | Continue after end tag
loop | Base page | Error
 | Execution mode = Start | Error
 | Execution mode = End | Continue from first child in body

Example

<h3>cfexit Example</h3>
<p>cfexit can be used to abort the processing of the currently executing
CFML custom tag. Execution resumes following the invocation of
the custom tag in the page that called the tag.
<h3>Usage of cfexit</h3>
<p>cfexit is used primarily to perform a conditional stop of processing
inside a custom tag. cfexit returns control to the page that
called that custom tag, or in the case of a tag called by another
tag, to the calling tag.

<!--- cfexit can be used within a CFML custom tag, as follows: --->
<!--- Place this code (uncomment the appropriate sections) within the
customtags directory. --->

<!--- MyCustomTag.cfm --->
<!--- This simple custom tag checks for the existence.
of myValue1 and myValue2. If they are both defined,
the tag adds them and returns the result to the calling
page in the variable "result". If either or both of the
expected attribute variables is not present, an error message
is generated, and cfexit returns control to the
calling page. --->

<!--- <cfif NOT IsDefined("attributes.myValue2")>
            <cfset caller.result = "Value2 is not defined">
            <cfexit method = "exitTag">
     <cfelseif NOT IsDefined("attributes.myValue1")>
            <cfset caller.result = "Value1 is not defined">
            <cfexit method = "exitTag">
     <cfelse>
             <cfset value1 = attributes.myValue1>
             <cfset value2 = attributes.myValue2>
            <cfset caller.result = value1 + value2>
     </cfif> --->
<!--- End MyCustomTag.cfm --->

<!--- Place this code within your page --->

<!--- <p>The call to the custom tag, and then the result:
<CF_myCustomTag
        myvalue2 = 4>
<cfoutput>#result#</cfoutput> --->
<p>If cfexit is used outside a custom tag, it functions like a cfabort.
For example, the text after this message is not processed:
<cfexit>
<p>This text is not executed because of the cfexit tag above it.


cffile

Description

Manages interactions with server files.

The following sections describe the actions of the cffile tag:

  • cffile action = "append"
  • cffile action = "copy"
  • cffile action = "delete"
  • cffile action = "move"
  • cffile action = "read"
  • cffile action = "readBinary"
  • cffile action = "rename"
  • cffile action = "upload"
  • cffile action = "write"

Note: To execute, this tag must be enabled in the ColdFusion Administrator. For more information, see Configuring and Administering ColdFusion MX.

If your ColdFusion applications run on a server used by multiple customers, consider the security of the files that could be uploaded or manipulated by cffile. For more information, see Configuring and Administering ColdFusion MX.

Category

File management tags

Syntax

The tag syntax depends on the action attribute value. See the following sections.

  • cffile action = "append"
  • cffile action = "copy"
  • cffile action = "delete"
  • cffile action = "move"
  • cffile action = "read"
  • cffile action = "readBinary"
  • cffile action = "rename"
  • cffile action = "upload"
  • cffile action = "write"

See also

cfdirectory

History

ColdFusion MX 7: Added the result attribute, which allows you to specify an alternate variable in which to receive result parameters. Used for action = "upload" action.

ColdFusion MX 6.1:

  • Changed file path requirements: if you do not specify an absolute file path, the path is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.
  • Changed behavior for action="read": if the file starts with a byte order mark (BOM) ColdFusion uses it to determine the character encoding.
  • Changed behavior for action="upload" nameConflict="MakeUnique" ColdFusion now makes filenames unique by appending a incrementing number, 1 for the first file, 2 for the second and so on, to the name. In ColdFusion MX filenames were made unique by appending an additional "1" for each file, as in 1, 11, 111, and so on.

ColdFusion MX:

  • Changed use of slashes in paths: you can use forward (/) or backward (\) slashes in paths on both UNIX and Windows systems.
  • Changed file hierarchy requirements: ColdFusion does not require that you put files and directories that you manipulate with this tag below the root of the web server document directory.
  • Changed directory path requirements for the destination attribute: a directory path that you specify in the destination attribute does not require a trailing slash.
  • Deprecated the system value of the attributes attribute.
  • Deprecated the temporary value of the attributes attribute. In ColdFusion MX, it is a synonym for normal. It might not work in later releases.
  • Changed the action attribute options read, write, append and move: they support a new attribute, charset.
  • The archive value of the attributes attribute is obsolete and has no effect.

Example

<!--- This shows how to write, read, update, and delete a file using CFFILE.
This is a view-only example. --->
<!---
<cfif IsDefined("form.formsubmit") is "Yes">
    <!--- The form has been submitted, now do the action. --->
    <cfif form.action is "new">
        <!--- make a new file --->
        <cffile 			action="Write"
            file="#GetTempDirectory()#foobar.txt"
            output="#form.the_text#">
    </cfif>
    <cfif form.action is "read">
        <!--- read existing file --->
        <cffile 			action="Read"
                file="#GetTempDirectory()#foobar.txt"
                variable="readText">
    </cfif>

    <cfif form.action is "add">
        <!--- update existing file --->
        <cffile 			action="Append"
            file="#GetTempDirectory()#foobar.txt"
            output="#form.the_text#">
    </cfif>

    <cfif form.action is "delete">
        <!--- delete existing file --->
        <cffile 		action="Delete"
            file="#GetTempDirectory()#foobar.txt">
    </cfif>
</cfif>
<!--- Set some variables. --->
<cfparam 	name="fileExists" 	default="no">
<cfparam name="readText" default="">
<!--- First, check whether canned file exists. --->
<cfif FileExists("#GetTempDirectory()#foobar.txt") is "Yes">
    <cfset fileExists="yes">
</cfif>
<!--- Now, make the form that runs the example. --->
<form action="index.cfm" method="POST">
<h4>Type in some text to include in your file:</h4> <p>
<cfif fileExists is "yes">
    <p>A file exists (foobar.txt, in <cfoutput>#GetTempDirectory()#</cfoutput>).
    You may add to it, read from it, or delete it. </p>
</cfif>
<!--- If reading from a form, let that information display in textarea. --->
<textarea name="the_text" cols="40" rows="5">
    <cfif readText is not "">
        <cfoutput>#readText#</cfoutput>
    </cfif></textarea>
<!--- Select from the actions depending on whether the file exists. --->
<select name="action">
<cfif fileExists is "no">
    <option value="new">Make new file
</cfif>
<cfif fileExists is "yes">
    <option value="add">Add to existing file
    <option value="delete">Delete file
    <option value="read">Read existing file
</cfif>
</select>
<input type="Hidden" name="formsubmit" value="yes">
<input type="Submit" name="" value="make my changes">
</form> --->


cffile action = "append"

Description

Appends text to a text file on the server.

Syntax

<cffile
    action = "append"
    file = "full_path_name"
    output = "string"
    addNewLine = "yes" or "no"
    attributes = "file_attributes_list"
    mode = "mode"
    charset = "charset_option" >

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

file

Required

Pathname of the file to which to append content of output attribute.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

mode

Optional

Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other, respectively. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

output

Required

String to append to the file.

addNewLine

Optional

yes
  • yes: appends newline character to text written to file.
  • no

attributes

Optional

Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file’s attributes are maintained.

Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten.

  • readOnly
  • hidden
  • normal

charset

Optional

JVM default file character set

The character encoding in which the file contents is encoded. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information character encodings, see
www.w3.org/International/O-charset.html.

fixnewline

Optional

No
  • Yes: changes embedded line-ending characters in string variables to operating-system specific line endings
  • No: (default) do not change embedded line-ending characters in string variables.

See cffile action = "write" for an example that uses this attribute.

Example

<!--The first example creates the file \temp\foo on a windows system and sets attributes to normal. --->
<cffile action = "write" file = "\temp\foo" attributes = normal output = "some text">
<!--- The second example appends to the file. --->
<cffile action = "append" file = "\temp\foo" attributes = normal output = "Is this a test?">


cffile action = "copy"

Description

Copies a file from one directory to another on the server.

Syntax

<cffile
    action = "copy"
    source = "full_path_name"
    destination = "full_path_name"
    mode = "mode"
    attributes = "file_attributes_list">

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

source

Required

Pathname of the file to copy.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

destination

Required

Pathname of a directory or file on web server where the file will be copied. If you specify a filename without a directory path, ColdFusion copies it relative to the source directory.

mode

Optional

Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other, respectively. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

attributes

Optional

Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file's attributes are maintained.

Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten.

  • readOnly
  • hidden
  • normal

Example

This example copies the keymemo.doc file to the c:\files\backup\ directory:

<cffile action = "copy"
source = "c:\files\upload\keymemo.doc"
destination = "c:\files\backup\">


cffile action = "delete"

Description

Deletes a file on the server.

Syntax

<cffile
    action = "delete"
    file = "full_path_name">

See also

cfdirectory

Attributes

Attribute | Req/Opt | Default | Description
action | Required |  | Type of file manipulation that the tag performs.
file | Required |  | Pathname of the file to delete. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

Example

The following example deletes the specified file:

<cffile action = "delete"
    file = "c:\files\upload\#Variables.DeleteFileName#">


cffile action = "move"

Description

Moves a file from one location to another on the server.

Syntax

<cffile
    action = "move"
    source = "full_path_name"
    destination = "full_path_name"
    mode = "mode"
    attributes = "file_attributes_list"
    charset = "charset_option">

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

source

Required

Pathname of the file to move.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

destination

Required

Pathname of the destination directory or file. If not an absolute path, it is relative to the source directory.

mode

Optional

Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other, respectively. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

attributes

Optional

Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file's attributes are maintained.

Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten.

  • readOnly
  • hidden
  • normal

charset

Optional

JVM default file character set

The character encoding in which the file contents is encoded. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information character encodings, see
www.w3.org/International/O-charset.html.

Example

The following example moves the keymemo.doc file from the c:\files\upload\ directory to the c:\files\memo\ directory in Windows:

<cffile
    action = "move"
    source = "c:\files\upload\keymemo.doc"
    destination = "c:\files\memo\">

In this example, the destination directory is "memo."


cffile action = "read"

Description

Reads a text file on the server. The file is read into a dynamic, local variable that you can use in the page. For example:

  • Read a text file; insert the file’s contents into a database
  • Read a text file; use the find and replace function to modify the file’s contents

Note: This action reads the file into a variable in the local Variables scope. It is not intended for use with large files, such as logs, because this can bring down the server.

Syntax

<cffile
    action = "read"
    file = "full_path_name"
    variable = "var_name"
    charset = "charset_option" >

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

file

Required

Pathname of the file to read.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

variable

Required

Name of variable to contain contents of text file.

charset

Optional

Character encoding identified by the file’s byte order mark, if any; otherwise, JVM default file character set.

The character encoding in which the file contents is encoded. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

If the file starts with a byte order mark and you set this attribute to a conflicting character encoding, ColdFusion generates an error.

For more information character encodings, see
www.w3.org/International/O-charset.html.

Usage

The following example creates a variable named Message for the contents of the file message.txt:

<cffile 			action = "read"
file = "c:\web\message.txt"
variable = "Message">

The variable Message can be used in the page. For example, you could display the contents of the message.txt file in the final web page as follows:

<cfoutput>#Message#</cfoutput>

ColdFusion supports functions for manipulating the contents of text files. You can also use the variable that is created by a cffile action = "read" operation in the ArrayToList and ListToArray functions.

Note: If you use this tag to read a file that is encoded using the Windows Cp1252 (windows-1252) encoding of the Latin-1 character set on a system whose default character encoding is Cp1252, and the files has characters encoded in the Hex 8x or 9x range, you must specify charset="windows-1252" attribute, even though this is the default encoding. Otherwise, some characters in the Hex8x and 9x ranges that do not map correctly and display incorrectly.


cffile action = "readBinary"

Description

Reads a binary file (such as an executable or image file) on the server, into a binary object parameter that you can use in the page. To send it through a web protocol (such as HTTP or SMTP) or store it in a database, first convert it to Base64 using the ToBase64 function.

Note: This action reads the file into a variable in the local Variables scope. It is not intended for use with large files, such as logs, because they can bring down the server.

Syntax

<cffile
    action = "readBinary"
    file = "full_path_name"
    variable = "var_name">

See also

cfdirectory

Attributes

Attribute | Req/Opt | Default | Description
action | Required |  | Type of file manipulation that the tag performs.
file | Required |  | Pathname of a binary fine to read. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.
variable | Required |  | Name of variable to contain contents of binary file.

Usage

You convert the binary file to Base64 to transfer it to another site.

Example

The following example reads the binary file somewhere.jpg, writes it to a different folder as somewhereB.jpg, and then displays the new file:

<cffile action = "readBinary" file = "C:\inetpub\wwwroot\cfdocs\getting_started\photos\somewhere.jpg" variable = "aBinaryObj">
<!--- Output binary object to JPEG format for viewing. --->
<cffile action="write" file = "c:\files\updates\somewhereB.jpg" output = "#toBinary(aBinaryObj)#">
<!--- HTML to view image. --->
<img src="C:\files\updates\somewhereB.jpg">


cffile action = "rename"

Description

Renames or moves a file on the server.

Syntax

<cffile
    action = "rename"
    source = "full_path_name"
    destination = "path_name"
    mode = "mode"
    attributes = "file_attributes_list">

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

source

Required

Pathname of file to rename.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

destination

Required

Destination file or directory. If not an absolute path, it is relative to the source directory.

mode

Optional

Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

attributes

Optional

Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file's attributes are maintained.

Each value must be specified explicitly. For example, if attributes = "readOnly", all other attributes are overwritten.

  • hidden
  • normal
  • readOnly

Usage

The rename action renames or move a file. The destination attribute must be a pathname, not just a new name for the file. If the destination is a directory, the file is moved and not renamed.

Example

Windows Example:

<!--- Source Document is read-only but when renamed it becomes normal (not hidden or read-only). --->
<cffile action = "rename" source = "c:\files\memo\readonlymemo.doc" destination = "c:\files\memo\normalmemo.doc" attributes="normal">

Unix Example:

<cffile action = "rename" source = "#myWR#/memo/sample.txt" destination = "#myWR#/memo/other_sample.txt" mode="666">


cffile action = "upload"

Description

Copies a file to a directory on the server.

Syntax

<cffile
    action = "upload"
    fileField = "formfield"
    destination = "full_path_name"
    nameConflict = "behavior"
    accept = "mime_type/file_type"
    mode = "permission"
    attributes = "file_attribute_or_list">
    result = "result_name"

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

fileField

Required

Name of form field used to select the file.

Do not use number signs (#) to specify the field name.

destination

Required

Pathname of directory in which to upload the file. If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

nameConflict

Optional

Error

Action to take if filename is the same as that of a file in the directory.

  • Error: file is not saved. ColdFusion stops processing the page and returns an error.
  • Skip: file is not saved. This option permits custom behavior based on file properties.
  • Overwrite: replaces file.
  • MakeUnique: forms a unique filename for the upload; name is stored in the file object variable serverFile.

accept

Optional

Limits the MIME types to accept. Comma-delimited list. For example, to permit JPEG and Microsoft Word file uploads:

accept = "image/jpg, application/msword"

The browser uses file extension to determine file type.

mode

Optional

Applies only to UNIX and Linux. Permissions. Octal values of chmod command. Assigned to owner, group, and other, respectively. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

attributes

Optional

Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file's attributes are maintained.

Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten.

  • readOnly
  • hidden
  • normal (if you use this option with other attributes, it is overridden by them)

result

Optional

Allows you to specify a name for the variable in which cffile returns the result (or status) parameters. If you do not specify a value for this attribute, cffile uses the prefix ‘cffile’. For more information, see the Usage section.

Usage

After a file upload is completed, you can get status information using file upload parameters. To refer to parameters, use either the cffile prefix or, if you specified an alternate name in the result attribute, the name you specified there. For example, if you did not specify a name in the result attribute, access the fileExisted parameter as #cffile.fileExisted#. If you set the result attribute to myResult, however, access fileExisted as #myResult.fileExisted#.

Status parameters can be used anywhere that other ColdFusion parameters can be used.

Tip: The result attribute allows functions or CFCs that get called from multiple pages at the same time to avoid overwriting the results of one call with another.

Note: The file prefix is deprecated, in favor of the cffile prefix. Do not use the file prefix in new applications.

Tip: If your page is uploading a file that was selected on a form or was otherwise sent to your page via a multipart/form-data HTTP message, you can determine the approximate size of the file by checking the value of the CGI.content_length variable. This variable includes the file length plus the length of any other request content.

The following file upload status parameters are available after an upload:

Parameter | Description
attemptedServerFile | Initial name ColdFusion used when attempting to save a file
clientDirectory | Directory location of the file uploaded from the client’s system
clientFile | Name of the file uploaded from the client’s system
clientFileExt | Extension of the uploaded file on the client system (without a period)
clientFileName | Name of the uploaded file on the client system (without an extension)
contentSubType | MIME content subtype of the saved file
contentType | MIME content type of the saved file
dateLastAccessed | Date and time the uploaded file was last accessed
fileExisted | Whether the file already existed with the same path (yes or no)
fileSize | Size of the uploaded file
fileWasAppended | Whether ColdFusion appended uploaded file to a file (yes or no)
fileWasOverwritten | Whether ColdFusion overwrote a file (yes or no)
fileWasRenamed | Whether uploaded file renamed to avoid a name conflict (yes or no)
fileWasSaved | Whether ColdFusion saves a file (yes or no)
oldFileSize | Size of a file that was overwritten in the file upload operation
serverDirectory | Directory of the file saved on the server
serverFile | Filename of the file saved on the server
serverFileExt | Extension of the uploaded file on the server (without a period)
serverFileName | Name of the uploaded file on the server (without an extension)
timeCreated | Time the uploaded file was created
timeLastModified | Date and time of the last modification to the uploaded file

Note: File status parameters are read-only. They are set to the results of the most recent cffile operation. If two cffile tags execute, the results of the second overwrite the first, unless you have specified a different result variable in the result attribute.

Example

The following example creates a unique filename, if there is a name conflict when the file is uploaded on Windows:

<!--- Windows Example --->
<!--- Check to see if the Form variable exists. --->
<cfif isDefined("Form.FileContents") >
    <!--- If TRUE, upload the file. --->
    <cffile action = "upload"
        fileField = "FileContents"
        destination = "c:\files\upload\"
        accept = "text/html"
        nameConflict = "MakeUnique">
<cfelse>
    <!--- If FALSE, show the Form. --->
    <form method="post" action=<cfoutput>#cgi.script_name#</cfoutput>
        name="uploadForm" enctype="multipart/form-data">
        <input name="FileContents" type="file">
        <br>
        <input name="submit" type="submit" value="Upload File">
    </form>
</cfif>


cffile action = "write"

Description

Writes a text file on the server, based on dynamic content. You can create static HTML files from the content, or log actions in a text file.

Syntax

<cffile
    action = "write"
    file = "full_path_name"
    output = "content"
    mode = "permission"
    addNewLine = "yes" or "no"
    attributes = "file_attributes_list"
    charset = "charset_option" >

See also

cfdirectory

History

See the History section of the main cffile tag page.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Type of file manipulation that the tag performs.

file

Required

Pathname of the file to write.

If not an absolute path (starting a with a drive letter and a colon, or a forward or backward slash), it is relative to the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

output

Required

Content of the file to be created.

mode

Optional

Applies only to UNIX and Linux. Permissions. Octal values of UNIX chmod command. Assigned to owner, group, and other, respectively. For example:

  • 644: assigns read/write permission to owner; read permission to group and other.
  • 777: assigns read/write/execute permission to all.

addNewLine

Optional

yes
  • yes: appends newline character to text written to file.
  • no

attributes

Optional

Applies to Windows. A comma-delimited list of attributes to set on the file.

If omitted, the file's attributes are maintained.

Each value must be specified explicitly. For example, if you specify attributes = "readOnly", all other attributes are overwritten.

  • readOnly
  • hidden
  • normal

charset

Optional

JVM default file character set.

The character encoding in which the file contents is encoded. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information character encodings, see www.w3.org/International/O-charset.html.

fixnewline

Optional

No
  • Yes: changes embedded line-ending characters in string variables to operating-system specific line endings.
  • No: (default) do not change embedded line-ending characters in string variables.

Example

This example creates a file with information a user entered in an HTML insert form:

<cffile action = "write"
    file = "c:\files\updates\#Form.UpdateTitle#.txt"
    output = "Created By: #Form.FullName#
    Date: #Form.Date#
    #Form.Content#">

If the user submitted a form with the following:

UpdateTitle = "FieldWork"
FullName = "World B. Frueh"
Date = "10/30/01"
Content = "We had a wonderful time in Cambridgeport."

ColdFusion would create a file named FieldWork.txt in the c:\files\updates\ directory and the file would contain the following text:

Created By: World B. Frueh
Date: 10/30/01
We had a wonderful time in Cambridgeport.

This example shows the use of the mode attribute for UNIX. It creates the file /tmp/foo with permissions rw-r--r-- (owner = read/write, group = read, other = read):

<cffile action = "write"
    file = "/tmp/foo"
mode = 644>

This example appends to the file and sets permissions to read/write (rw) for all:

<cffile action = "append"
    destination = "/home/tomj/testing.txt"
mode = 666
output = "Is this a test?">

This example uploads a file and gives it the permissions owner/group/other = read/write/execute):

cffile action = "upload"
    fileField = "fieldname"
destination = "/tmp/program.exe"
mode = 777>

This example uses the fixnewline attribute to changes embedded line-ending characters in xmlString, which is derived from xmlData, to operating-system specific line endings.

<cfxml variable="xmlData">
    <docroot>
        <payload type="string">This is some plain text</payload>
    </docroot>
</cfxml>
<cfset xmlString = toString(xmlData)>

<cfset key = createUUID()>
<cfset encString=encrypt(xmlString, key)>
<cffile action="write" addnewline="yes" file="C:\CFusionMX7\wwwroot\test\store.dat" output="#encString#" fixnewline="yes">
<cffile action="read" file="C:\CFusionMX7\wwwroot\test\store.dat" variable="retrievedString">
<cfset decString=decrypt(retrievedString, key)>
<cfdump var="#decString#">
<cfset newXML = xmlParse(decString)>
<cfdump var="#newXML#">


cfflush

Description

Flushes currently available data to the client.

Category

Data output tags, Page processing tags

Syntax

<cfflush
    interval = "integer number of bytes">

See also

cfcache , cfheader , cfinclude , cfsetting , cfsilent

Attributes

Attribute | Req/Opt | Default | Description
interval | Optional |  | Integer. Flushes output each time this number of bytes becomes available. HTML headers, and data that is already available when the tag is executed, are omitted from the count.

Usage

The first occurrence of this tag on a page sends back the HTML headers and any other available HTML. Subsequent cfflush tags on the page send only the output that was generated after the previous flush.

When you flush data, ensure that enough information is available, as some browsers might not respond if you flush only a small amount. Similarly, set the interval attribute for a few hundred bytes or more, but not thousands of bytes.

Use the interval attribute only when a large amount of output will be sent to the client, such as in a cfloop or a cfoutput of a large query. Using this form globally (such as in the Application.cfm file) might cause unexpected errors when CFML tags that modify HTML headers are executed.

Caution: Because the cfflush tag sends data to the browser when it executes, it has several limitations, including the following: Using any of the following tags or functions on a page anywhere after the cfflush tag can cause errors or unexpected results: cfcontent, cfcookie, cfform, cfheader, cfhtmlhead, cflocation, and SetLocale. (These tags and functions normally modify the HTML header, but cannot do so after a cfflush tag, because the cfflush sends the header.) Using the cfset tag to set a cookie anywhere on a page that has a cfflush tag does not set the cookie in the browser. Using the cfflush tag within the body of several tags, including cfsavecontent, cfquery, and custom tags, cause errors. If you save Client variables as cookies, any client variables that you set after a cfflush tag are not saved in the browser.

Note: Normally, the cferror tag discards the current output buffer and replaces it with the contents of the error page. The cfflush tag discards the current buffer. As a result, the Error.GeneratedContent variable resulting from a cferror tag after a cfflush contains any contents of the output buffer that has not been flushed. This content is not sent to the client. The content of the error page displays to the client after the bytes that have been sent.

Example

The following example uses cfloop tags and the rand random number generating function to delay data display. It simulates a page that is slow to generate data.

<h1>Your Magic numbers</h1>
<p>It will take us a little while to calculate your ten magic numbers. It takes a lot of work to find numbers that truly fit your personality. So relax for a minute or so while we do the hard work for you.</p>
<H2>We are sure you will agree it was worth the short wait!</H2>
<cfflush>

<cfflush interval=10>
<!--- Delay Loop to make it seem harder. --->
<cfloop index="randomindex" from="1" to="200000" step="1">
    <cfset random=rand()>
</cfloop>

<!--- Now slowly output 10 random numbers. --->
<cfloop index="Myindex" from="1" to="10" step="1">
    <cfloop index="randomindex" from="1" to="100000" step="1">
        <cfset random=rand()>
    </cfloop>
    <cfoutput>
        Magic number #Myindex# is:&nbsp;&nbsp;#RandRange(
100000, 999999)#<br><br>
    </cfoutput>
</cfloop>


cfform

Description

Builds a form with CFML custom control tags; these provide more functionality than standard HTML form input elements. You can include the resulting form on the client page as HTML or Flash content, and generate the form using XML and XSLT.

Category

Forms tags

Syntax

<cfform
    name = "name"
    action = "form_action"
    method = "POST" or "GET"
    format = "HTML" or "Flash" or "XML"
    skin = "Flash or XSL skin"
    style = "style specification"
    preserveData = "yes" or "no"
    onSubmit = "javascript"
    scriptSrc = "path"
    codeBase = "URL"
    archive = "URL"
The following attributes are supported in Flash and XML only
width = "pixels or percent"
height = "pixels or percent"
The following attributes are supported in Flash only
onError = "ActionScript code"
wMode = "window" or "transparent" or "opaque"
accessible = "yes" or "no"
preloader = "yes" or "no"
timeout = "seconds"
The following attributes are supported in HTML and XML only
class = "form class"
enctype = "Internet media type"
id = "HTML id"
onload = "load event script"
onreset = "reset event script"
target = "target window or frame">
...
</cfform>

See also

cfapplet, cfcalendar, cfformgroup, cfformitem, cfgrid, cfinput, cfselect, cfslider, cftextarea, cftree; Requesting and Presenting Information in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added ability to set the default value of the scriptSrc attribute in the ColdFusion MX Administrator.
  • Deprecated the passthrough attribute. The tag now supports all HTML form tag attributes directly.
  • Added the method attribute and support for the GET method.
  • Added support for Flash and XML output, including the format, height, width, preloader, timeout, wMode, accessible, and skin attributes.
  • Added cfformgroup, cfformitem, and cftextarea child tags.

ColdFusion MX:

  • Deprecated the enableCAB attribute. It might not work, and might cause an error, in later releases.
  • Changed the name and action attributes to optional.
  • Changed integer validation to require an integer value. In previous releases it would convert a floating point value to an integer.

Attributes

The following table lists attributes that ColdFusion uses directly. For HTML format forms, this tag also supports the standard HTML form tag attributes that are not on this list, and passes them directly to the browser. ColdFusion also includes all supported HTML attributes in the XML.

Attribute

Applies
to

Req/Opt

Default

Description

name

HTML, Flash, XML

Opt

CFForm_n

A name for the form.

In HTML format, if you omit this attribute and specify an id attribute, ColdFusion does not include a name attribute in the HTML sent to the browser; this behavior lets you use the cfform tag to create XHTML-compliant forms. If you omit the name attribute and the id attribute, ColdFusion generates a name of the form CFForm_n where n is a number that assigned serially to the forms on a page.

action

HTML, Flash, XML

Opt

See Description

Name of ColdFusion page to execute when the form is submitted for processing.

If you omit this attribute, the form posts to the page identified by the CGI.SCRIPT_NAME variable, the requested page that resulted in displaying the form.

method

HTML, Flash, XML

Opt

post

The method the browser uses to send the form data to the server:

  • post: sends the data using the HTTP post method, This method sends the data in a separate message to the server.
  • get: sends the data using the HTTP get method, which puts the form field contents in the URL query string.

format

HTML, Flash, XML

Opt

HTML
  • HTML: generates an HTML form and send it to the client. cfgrid and cftree child controls can be in Flash or applet format.
  • Flash: generates a Flash form and send it to the client. All controls are in Flash format.
  • XML: generates XForms-compliant XML and save the results in a variable specified by the name attribute. By default, ColdFusion also applies an XSL skin and displays the result. For more information, see the skin attribute.

skin

Flash,
XML

Opt

Flash: haloGreen

XML:

default.xsl

Flash: Use a Macromedia halo color to stylize the output. The skin determines the color used for highlighted and selected elements.

  • haloSilver
  • haloBlue
  • haloGreen
  • haloOrange

XML: Specfies whether to apply an XSL skin and display the resulting HTML to the client. Can be any of the following:

  • ColdFusion MX skin name: applies the specified skin.
  • XSL file name: applies the skin located in the specified path.
  • "none": does not apply an XSL skin. Your CFML page must process the XML that ColdFusion saves in the variable specified by the name attribute and display any results.
  • (omitted) or "default": uses the ColdFusion MX default skin.

You can specify the following ColdFusion MX skins (located in the cf_webroot\CFIDE\scripts\xsl directory):

  • basic
  • basiccss
  • beige
  • blue
  • bluegray
  • lightgray
  • red
  • silver

A filename can be any of the following:

  • absolute URL
  • URL relative to the web root
  • absolute file path
  • name of a file in the scripts folder or a subdirectory of the cf_webroot\CFIDE\scripts directory. In this case, do not specify the .xsl suffix.

style

HTML, Flash, XML

Opt

Styles to apply to the form. In HTML or XML format, ColdFusion passes the style attribute to the browser or XML.

In Flash format, must be a style specification in CSS format. For detailed information on specifying Flash styles, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

preserveData

HTML
XML

Opt

no

When the cfform action attribute posts back to the page that contains the form, this determines whether to override the control values with the submitted values.

  • false: uses values specified in the control tag attributes.
  • true: uses corresponding submitted values.

Applies to these controls:

  • cfinput, cfslider, cftextinput: overrides the value attribute value.
  • cfselect controls that are populated from queries: Overrides the selected attribute. See cfselect.
  • cftree controls: overrides the cftreeitem expand attribute. If true, expands previously-selected elements. The cftree completePath attribute must be set to yes.
  • cfgrid controls: has no effect. (This avoids confusion as to whether data has been resubmitted to the database by the control.)

onLoad

HTML
XML

Opt

JavaScript to execute when the form loads.

onReset

HTML
XML

Opt

JavaScript to execute when the user clicks a reset button.

onSubmit

HTML

Flash

XML

Opt

JavaScript or ActionScript function to execute to preprocess data before form is submitted. See ColdFusion MX Developer’s Guide. If any child tags specify onSubmit field validation, ColdFusion does the validation before executing this JavaScript.

scriptSrc

HTML, Flash
XML

Opt

See Description

Specifies the URL, relative to the web root, of the directory that contains the cfform.js file with the client-side JavaScript used by this tag and its child tags. For XML format forms, this directory is also the default directory for XSLT skins.

This attribute is useful if the file is not in the default location. This attribute may be required in some hosting environments and configurations that block access to the /CFIDE directory.

The default location is set in the ColdFusion MX Administrator; by default, it is /CFIDE/scripts/cfform.js.

If the Administrator has an empty default value, ColdFusion looks for the script in the directory that contains the ColdFusion page.

codeBase

applets in HTML and XML

Opt

See Description

URL of downloadable JRE plug-in for Internet Explorer; used for cfgrid, cfslider, and cftree Java applet controls.

Default: /CFIDE/classes/cf-j2re-win.cab

archive

applets in HTML and

XML

Opt

See Description

URL of downloadable Java classes for cfgrid, cfslider, and cftree applet controls.

Default: /CFIDE/classes/cfapplets.jar

height

Flash

XML

Opt

100%

The height of the form. Use a number to specify pixels, In Flash, you can use a percentage value, such as "height=60%" to specify a percentage of the available width. The displayed height might be less than the specified size.

width

Flash

XML

Opt

100%

The width of the form. Use a number to specify pixels, In Flash, you can use a percentage value, such as "width=60%" to specify a percentage of the available width..

onError

Flash

Opt

Applies only for onSubmit or onBlur validation; has no effect for onServer validation.

An ActionScript expression or expressions to execute if the user submits a form with one or more validation errors.

wMode

Flash

Opt

Window

Specifies how the Flash form appears relative to other displayable content that occupies the same space on an HTML page.

  • window: the Flash form is the topmost layer on the page and obscures anything that would share the space, such as drop-down dynamic HTML lists.
  • transparent: the Flash form honors the z-index of dhtml so you can float items above it. If the Flash form is above any item, transparent regions in the form show the content that is below it.
  • opaque: the Flash form honors the z-index of dhtml so you can float items above it. If the Flash form is above any item, it blocks any content that is below it.

accessible

Flash

Opt

No

Specifies whether to include support screen readers in the Flash form. Screen reader support adds approximately 80KB to the SWF file sent to the client.

preloader

Flash

Opt

true

Specifies whether to display a progress bar when loading the Flash form.

timeout

Flash

Opt

0

Integer number of seconds for which to keep the form data in the Flash cache on the server. A value of 0 prevents the data from being cached. For more information, see Caching data in Flash forms in ColdFusion MX Developer’s Guide.

Note: Attributes that are not marked as supported in XML are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML as html namespace attributes to the form tag.

Usage

This tag requires an end tag.

You can use the following ColdFusion form control tags within the cfform tag:

  • cfapplet Used in HTML and XML format only; embeds a registered Java applet.
  • cfformgroup Used in Flash and XML format only; groups and arranges child controls.
  • cfformitem Used in Flash and XML format only; adds horizontal rules, vertical rules, and text to the form.
  • cfgrid Creates a grid control to display tabular data.
  • cfinput Creates and an input element.
  • cfselect Creates a drop-down list box.
  • cfslider Used in HTML and XML format only; creates a slider control.
  • cftextarea Creates a multi-line text input box.
  • cftree Creates a tree control.

In HTML format, all tags, and in Flash format the cftree and cfgrid tags, require JavaScript support on the browser. The cfapplet tag and applet format cfgrid, cfslider, and cftree tags require the client to download a Java applet.

If you specify Flash format in the cfform tag, ColdFusion ignores any HTML in the form body. You must use ColdFusion tags, such as cfinput, for all form controls. You can include individual Flash format cfgrid and cftree controls in an HTML format cfform tag.

In Flash format, if your forms do not request sensitive data (such as credit card numbers), consider setting the timeout attribute. This can prevent users from getting "The form data has expired, Please reload this page in your browser" errors if they use the browser back button to return to the form. For more information, see Caching data in Flash forms in Caching data in Flash formsin ColdFusion MX Developer’s Guide.

Note: In Flash format, if you do not specify height and width attributes, Flash reserves browser space equal to the area of the browser window. If any other output follows the form, users must scroll to see it. Therefore, if you follow a Flash form with additional output, specify the height and width values.

If attribute value text must include quotation marks, escape them by doubling them.

Using the onError attribute in Flash forms

If you use onSubmit or onBlur validation, the onError attribute lets you specify ActionScript code to execute if the user tries to submit a Flash form with validation errors, as follows:

  • If you specify one or more valid Flash expressions, Flash executes the expressions.
  • If you omit the attribute, Flash displays a dialog box with all applicable error messages.
  • If you specify onError="" (an empty string) Flash does not display any message, but does not submit the form.

Your ActionScript can use the errors variable to determine the fields and errors. The errors object has the following fields:

Field | Contents
name | The name attribute of the control’s CFML tag.
field | The internal name used by Flash for the field. name (for example, _level0.field1)
value | The value in the field.
message | The message attribute of the control’s CFML tag.

The following example shows cfform tags with an onError attribute that selects the tab in an accordion or tabnavigator that contains a lastName field with an invalid entry:

<cfform name="form1" format="flash" width="800" height="500"
        onError="if (errors['lastName'] != undefined
            ){tabA.selectedIndex=0; _root.lastName.setFocus();}">

<Incorporating HTML form tags and attributes

In HTML format, the cfform tag lets you incorporate the following standard HTML elements. They are not available in Flash format:

  • Standard HTML form tag attributes and values. The attributes and values are included in the form tag that cfform outputs in the page. For example, you can use form tag attributes like target or onMouseOver with cfform.
  • HTML tags that can ordinarily be put within the HTML form tag. For example, you can use the HTML input tag to create a submit button in a cfform, without the other features of cfinput:
    <cfform>
    <input type = "Submit" value = " update... ">
</cfform>

Examples

<h3>cfform Example</h3>
<!--- If Form.oncethrough exists, the form has been submitted. --->
<cfif IsDefined("Form.oncethrough")>
    <cfif IsDefined("Form.testVal1")>
        <h3>Results of Radio Button Test</h3>
        <cfif Form.testVal1>Your radio button answer was yes
        <cfelse>Your radio button answer was no
        </cfif>
    </cfif>
    <h3>Results of Checkbox Test</h3>
    <cfif IsDefined("Form.chkTest2")>
        Your checkbox answer was yes
    <cfelse>
        Your checkbox answer was no
    </cfif>
    <cfif IsDefined("Form.textSample") AND Form.textSample is not "">
        <h3>Results of Credit Card Input</h3>
        Your credit card number, <cfoutput>#Form.textSample#</cfoutput>,
        was valid under the MOD 10 algorithm.
    </cfif>
    <cfif IsDefined("Form.sampleSlider")>
        <cfoutput>
            <h3>You gave this page a rating of #Form.sampleSlider#</h3>
        </cfoutput>
    </cfif>
    <hr noshade="True">
</cfif>

<!--- Begin by calling the cfform tag. --->
<cfform name="cfformexample">
    <h4>This example displays radio button input type for cfinput.</h4>
    Yes <cfinput type = "Radio" name = "TestVal1" value = "Yes" checked>
    No <cfinput type = "Radio" name = "TestVal1" value = "No">
    <h4>This example displays checkbox input type for cfinput.</h4>
    <cfinput type = "Checkbox" name = "ChkTest2" value = "Yes">
    <h4>This shows client-side validation for cfinput text boxes.</h4>
    (<i>This item is optional</i>)<br>
    Please enter a credit card number:
    <cfinput type = "Text" name = "TextSample"
        message = "Please enter a Credit Card Number"
        validate = "creditcard" required = "No">
    <h4>This example shows the use of the cfslider tag.</h4>
    Rate your approval of this example from 1 to 10 by sliding control.<br>
    1 <cfslider name = "sampleSlider" width="100"
            label = "Page Value: " range = "1,10"
            message = "Please enter a value from 1 to 10"> 10
    <p><cfinput type = "submit" name = "submit" value = "show me the result">
    <cfinput type = "hidden" name = "oncethrough" value = "Yes"></p>
</cfform>

A Simple XML form

The following example shows a simple XML-format form. It uses the default.xsl transform that is supplied with ColdFusion to generate the HTML output for display:

<cfform name="testXForm" format="XML" skin="basic">
  <!--- Use cfformgroup to put the first and last names on a single line. --->
  <cfformgroup type="horizontal">
      <cfinput type="text" name="firstname" label="First Name:" value="Robert">
      <cfinput type="text" name="lastname" label="Last Name:" value="Smith">
  </cfformgroup>
  <cfinput type="password" name="password" label="Password:" value="">
  <cfinput type="hidden" name="hidden" label="hidden:" value="">
  <cfselect name="state" style="width:200" label="State">
    <option>California</option>
    <option selected>Utah</option>
    <option>Iowa</option>
    <option selected>New York</option>
   </cfselect>
   <cftextarea name="description" label="Description:" rows="5" cols="40">this is sample text.</cftextarea>
</cfform>


cfformgroup

Description

Creates a container control for multiple form controls. Used in the cfform tag body of Macromedia Flash and XML forms. Ignored in HTML forms.

Category

Forms tags

Syntax

<cfformgroup
    type = "group type"
    label = "label"
    style = "style specification"
    selectedIndex = "page number">
    width = "pixels"
    height = "pixels"
    enabled = "Yes" or "No"
    visible = "Yes" or "No"
    OnChange = "ActionScript expression"
    toolTip = "Tip text"
...ColdFusion forms controls
</cfformgroup>
or
<cfformgroup
    type = "repeater"
    query = "query object"
startrow = "row number"
maxrows = "integer">
...ColdFusion forms controls
</cfformgroup>

See also

cfapplet , cfcalendar , cfform , cfformitem , cfgrid , cfinput , cfselect , cfslider , cftextarea , cftree, Using the cfformgroup tag to structure forms in Creating Forms in Macromedia Flash and Using cfformgroup tags in Creating Skinnable XML Forms in ColdFusion MX Developer’s Guide.

History

ColdFusion MX 7: Added this tag.

Attributes

The following table lists the attributes and their behavior in Flash forms. For XML, if not otherwise noted, the attribute is passed to the XML but is not interpreted by the basic XSL style sheet provided with ColdFusion MX.

Note: Attributes that are not marked as supported in XML are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML

Attribute

Req/Opt;

Formats

Default

Description

type

Required;

Flash and XML

XML: Can be any XForms group type defined in the XSLT. The XSL skins provided with ColdFusion MX support the following types:

  • horizontal: align child tags horizontally within a form and put this tag’s label attribute to the left of the children.
  • vertical: align child tags vertically within a form and put this tag’s label attribute to the left of the children.
  • fieldset: corresponds to the HTML fieldset tag, which groups its children, typically by drawing a box around them and replacing part of the top line with legend text. To specify the legend, use the label attribute. To specify the box dimensions, use the style attribute with height and width values. You must explicitly use cfformgroup type="vertical" inside this formgroup to align its child tags vertically.

Flash: Must be one of the following:

  • repeater: dynamically creates an instance of the cfformgroup’s child tag or tags for each row of a query object, without requiring ColdFusion to recompile the Flash SWF file when the number of rows changes.
  • horizontal: aligns child tags horizontally within a form and put this tag’s label attribute to the left of the children. Use this tag to arrange individual controls horizontally.
  • vertical: aligns child tags vertically within a form and puts this tag’s label attribute to the left of the children. Use this tag to arrange individual controls vertically.
  • hbox: aligns children horizontally. Use this type to arrange groups of form controls horizontally. Do not use this attribute to align individual controls horizontally, because the child controls do not align properly; use the horizontal type instead.
  • vbox: aligns children vertically. Use this type to arrange groups of controls vertically. Do not use this attribute to align individual controls vertically, as the child controls will not align properly; use the vertical type instead.

  • hdividedbox: aligns children horizontally. Each child is in a box with a border, and there are dividers between the boxes that users can move to change the relative sizes of the children. Use a tag with this attribute to arrange groups of form controls horizontally. You cannot use this attribute to align individual controls horizontally.
  • vdividedbox: aligns children vertically. Each child is in a box with a border, and there are dividers between the boxes that users can move to change the relative sizes of the children. Use this type to group form controls, for example as a unit in an hbox form group. Do not use this attribute to align individual tags vertically.
  • panel: a container consisting of a title bar containing the label attribute text, a border, and a content area with vertically arranged children.
  • tile: places the children in a rectangular grid.
  • accordion: places each child in a pleat of an expanding and contracting accordion. Define each pleat using a cfformgroup type="page" tag.
  • tabnavigator: places the children in a tabbed dialog box. Define each tab using a cfformgroup type="page" tag.
  • page: places the children tags, aligned vertically, in a single tab of a parent tabnavigator or pleat of an accordion container.

query

Required for type= repeater, ignored otherwise;

Flash

The query to use with the repeater. Flash creates an instance of each of the cfformgroup tag’s child tags for each row in the query. You can use the bind attribute in the child tags to use data from the query row for the instance.

startrow

Optional;

Flash

0

Used only for the repeater type; ignored otherwise.

Specifies the row number of the first row of the query to use in the Flash form repeater. This attribute is zero-based: the first row is row 0, not row 1 (as in most ColdFusion tags).

maxrows

Optional;

Flash

Used only for the repeater type; ignored otherwise.

Specifies the maximum number of query rows to use in the Flash form repeater. If the query has more rows than the sum of the startrow attribute and this value, the repeater does not use the remaining rows.

label

Optional;

Flash and XML

Label to apply to the form group.

In Flash, does the following:

  • For a page or panel form group, determines the label to put on the corresponding accordion pleat, the tabnavigator tab, or the panel title bar. For a Flash horizontal or vertical form group, specifies the label to put to the left of the group.
  • Ignored in Flash for repeater, hbox, hdividedbox, vbox, vdividedbox, tile, accordion, and tabnavigator types.

style

Optional;

Flash and XML

Flash: A Flash style specification in CSS format. For detailed information on specifying Flash styles, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

XML: An inline CSS style specification.

selectedIndex

Optional;

Flash only

Used only for accordion and tabnavigator types; ignored otherwise. Specifies the page control to display as open, where 0 (not 1) specifies the first page control defined in the group.

width

Optional;

Flash and XML

Width of the group container, in pixels. If you omit this attribute, Flash automatically sizes the container width. Ignored for Flash repeater type.

height

Optional;

Flash

Height of the group container, in pixels. If you omit this attribute, Flash automatically sizes the container height. Ignored for Flash repeater type.

enabled

Optional;

Flash

Yes

Boolean value specifying whether the controls in the form group are enabled. Disabled controls appear in light gray.

visible

Optional;

Flash

Yes

Boolean value specifying whether the controls in the form group are visible. If the controls are invisible, the space that would be occupied by visible controls is blank.

onChange

Optional;

Flash

Tabnavigator and accordion types only: ActionScript expression or expressions to execute when a new tab or accordion page is selected.

Note: The onChange event occurs when the form first appears.

tooltip

Optional;

Flash

Text to display when the mouse pointer hovers in the form group area. If a control in the form group also specifies a tooltip, Flash displays the control’s tooltip when the mouse pointer hovers over the control.

Usage

This tag requires an end tag. This tag is ignored if the cfform type is HTML; any tag body’s contents are interpreted as if the surrounding cfformgroup does not exist.

In Flash format forms, this tag organizes the contents of the form. It groups and arranges child tags. The body of this tag can contain the following tags; all other tags and text are ignored:

  • cfformgroup
  • cfformitem
  • cfcalendar
  • cfgrid
  • cfinput
  • cfselect
  • cftextarea
  • cftree

For more information on using this tag in Flash forms, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

In XML format, ColdFusion passes the tag and its attributes to the XML; it is the responsibility of the skin XSLT to handle the XML. The ColdFusion basic skin supports the horizontal, vertical, and dualselectlist styles only. For more information on using this tag in XML forms, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

Example

For a simple example of an XML form that uses a single cfformgroup tag, see cfform .

The following example shows how to use the cfformgroup tag to arrange elements on a Flash form. It creates an hdividedbox container that has a vbox container on each side. The left box has heading text and two radio buttons. The right box has heading text and three check boxes.

<h3>Simple cfformgroup Example</h3>
<cfform name="myform" height="450" width="500" format="Flash" >
    <cfformgroup type="hdividedbox" >
        <cfformgroup type="VBox">
            <cfformitem type="text" height="20">
                Pets:
            </cfformitem>
            <cfinput type="Radio" name="pets" label="Dogs" value="Dogs"
                checked>
            <cfinput type="Radio" name="pets" label="Cats" value="Cats">
        </cfformgroup>

        <cfformgroup type="VBox">
            <cfformitem type="text" height="20">
                Fruits:
            </cfformitem>
            <cfinput type = "Checkbox" name="chk1" Label="Apples"
                value="Apples">
            <cfinput type="Checkbox" name="chk2" Label="Bananas"
                value="Bananas">
            <cfinput type="Checkbox" name="chk3" Label="Pears"
                value="Pears">
        </cfformgroup>
    </cfformgroup>
</cfform>

The following more complex example shows more fully how you can use cfformgroup tags to arrange controls in a Flash form. It also shows many of the text formatting features that you can use in a text cfformgroup body. When you submit the form, the page dumps the contents of the Forms scope, to show you the submitted data.

<h2>cfformgroup Example</h2>
<cfif IsDefined("form.oncethrough")>
    <h3>The form submitted the following information to ColdFusion MX:</h3>
    <cfdump var="#form#"><br><br><br>
</cfif>

<h3>A Flash form using cfformgroup tags</h3>
<cfform name="myform" height="450" width="500" format="Flash">

<!--- The following formgroup shows how you can present formatted text. --->
    <cfformitem type="html">
        <b><font color="#FF0000" size="+4" face="serif">
        This form has two tabs, asking for the following:</font></b><br>
        <li>contact information</li>
        <li><i>preferences</i></li>
        <b>Try entering information on both tabs</b><br>
        Submit the form and see what ColdFusion gets in the Forms scope.</b><br>
        <a href="http://www.macromedia.com/" target="_blank">
        <font color="#0000FF"><u>
        This link displays the Macromedia home page in a new browser window
        </u></font></a><br>
        &nbsp;<br>
    </cfformitem>

<!--- Use a tabnavigator with two tabs for user input. --->
    <cfformgroup type="tabnavigator" height="220">
        <cfformgroup type="page" label="Contact Information">
            <!--- Align the first and last name fields horizontally --->
            <cfformgroup type="horizontal" label="Your Name">
                <cfinput type="text" required="Yes" name="firstName" label="First"
                    value="" width="100"/>
                <cfinput type="text" required="Yes" name="lastName" label="Last"
                    value="" width="100"/>
            </cfformgroup>
            <cfformitem type="html"><textformat indent="95"><font size="-2">
                Flash fills the email field in automatically.
                You can replace any of the text.
                </font></textformat>
            </cfformitem>
            <!--- The bind attribute gets the field contents from the firstname
                    and lastName fields as they get filled in. --->
            <cfinput type="text" name="email" label="email"
                bind="{firstName.text}.{lastName.text}@mm.com">

            <cfinput type="text" name="phone" validate="telephone" required="Yes"
                label="Phone Number">
        </cfformgroup>

        <cfformgroup type="page" label="Preferences">
            <cfformitem type="text" height="30">
                <b>Tell us your preferences</b>
            </cfformitem>
            <!--- Put the pet selectors to the left of the fruit selectors. --->
            <cfformgroup type="hbox">
            <!--- Group the pet selector box contents, aligned vertically. --->
                <cfformgroup type="vbox">
                    <cfformitem type="text" height="20">
                        Pets:
                    </cfformitem>
                    <cfformgroup type="vertical">
                        <cfinput type="Radio" name="pets" label="Dogs" value="Dogs"
                            checked>
                        <cfinput type="Radio" name="pets" label="Cats" value="Cats">
                    </cfformgroup>
                </cfformgroup>
            <!--- Group the fruit selector box contents, aligned vertically. --->
                <cfformgroup type="vbox">
                    <cfformitem type="text" height="20">
                        Fruits:
                    </cfformitem>
                    <cfformgroup type="tile" width="200" label="Tile box">
                        <--- Flash requires unique names for all controls --->
                        <cfinput type = "Checkbox" name="chk1" Label="Apples"
                            value="Apples">
                        <cfinput type="Checkbox" name="chk2" Label="Bananas"
                            value="Bananas">
                        <cfinput type="Checkbox" name="chk3" Label="Pears"
                            value="Pears">
                        <cfinput type="Checkbox" name="chk4" Label="Oranges"
                            value="Oranges">
                        <cfinput type="Checkbox" name="chk5" Label="Grapes"
                            value="Grapes">
                        <cfinput type="Checkbox" name="chk6" Label="Cumquats"
                            value="Cumquats">
                    </cfformgroup>
                </cfformgroup>
            </cfformgroup>
        </cfformgroup>
    </cfformgroup>

    <cfformgroup type="horizontal">
        <cfinput type = "submit" name="submit" width="100" value = "Show Results">
        <cfinput type = "reset" name="reset" width="100" value = "Reset Fields">
        <cfinput type = "hidden" name="oncethrough" value = "Yes">
    </cfformgroup>
</cfform>


cfformitem

Description

Inserts a horizontal line, a vertical line, a spacer, or text in a Flash form. Used in the cfform or cfformgroup tag body for Flash and XML forms. Ignored in HTML forms.

Category

Forms tags

Syntax

<cfformitem
    type = "hrule, vrule, or spacer"
    style = "style specification"
    width = "pixels"
    height = "pixels"
    visible = "Yes" or "No"/>

or

<cfformitem
    type= "html or text"
    style = "style specification"
    width = "pixels"
    height = "pixels"
    visible = "Yes" or "No"
    enabled = "Yes" or "No"
    tooltip = "Tip text"
    bind = "bind expression">
...text
</cfformitem>

See also

cfapplet , cfform , cfformgroup , cfgrid , cfinput , cfselect , cfslider , cftextarea , cftree, Adding text, images, rules, and space with the cfformitem tag in Adding text, images, rules, and space with the cfformitem tag in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added tag

Attributes

The following table lists the attributes and their behavior in Flash forms. For XML format, if not otherwise noted, the attribute is passed to the XML but is not interpreted by the basic XSL style sheet provided with ColdFusion MX.

Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML in all controls except text and html types.

Attribute

Req/Opt;

Formats

Default

Description

type

Required;

Flash and XML

Flash:

  • html: place the text in the body of this tag on the form. For Flash forms, you can use the following text formatting tags, most of which correspond to HTML tags, in the text: a, b, br, font, i, img, li, p, textformat, and u. For details on using these formatting tags, see the Flash documentation. The style attribute has no effect on the format of the text in type.
  • text: place the text in the body of this tag on the form verbatim, without interpreting any markup. You can control the overall appearance of the text by using the style attribute.
  • spacer: places an invisible spacer of the specified height and width on the form. Used to place space between form controls. This tag must not have any children.
  • hrule: places a horizontal rule on the form. This tag must not have any children.
  • vrule: places a vertical rule on the form. This tag must not have any children.

XML:

  • html: puts the CFML tag’s body text in a CDATA section in an XML xf:output element.
  • text: XML-formats (escapes characters such as <) the CFML tag’s body text and puts it in a CDATA section in an XML xf:output element.
  • hrule: puts an hr tag in the output. Use the style attribute to specify all rule characteristics, including height and width. This tag must not have any children.
  • Any other string: generates an XML xf:group element with the type name as the appearance attribute. The CFML tag body is put in a CDATA section in a cf:attribute name="body" element. The XSL transforms provided with ColdFusion MX ignore these elements.

style

Optional;

Flash and XML

Flash:

Must be a style specification in CSS format.

Ignored if the type attribute is html or text.

For detailed information on specifying Flash styles, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide. Not used with the spacer type.

XML:

ColdFusion passes the style attribute to the XML. ColdFusion skins include the style attribute in the generated HTML.

width

Optional;

Flash

Width of the item, in pixels. If you omit this attribute, Flash automatically sizes the width. In ColdFusion XSL skins, use the style attribute, instead.

height

Optional;

Flash

Height of the item, in pixels. If you omit this attribute, Flash automatically sizes the width. In ColdFusion XSL skins, use the style attribute, instead.

enabled

Optional;

Flash

Yes

Boolean value specifying whether the control is enabled. Disabled text appear in light gray. Has no effect on spacers and rules.

visible

Optional;

Flash

Yes

Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank. Has no effect on spacers.

tooltip

Optional;

Flash

Text to display when the mouse pointer hovers over the control. Has no effect on spacers.

bind

Optional;

Flash

A Flash bind expression that populates the field with information from other form fields. If you use this attribute, ColdFusion MX ignores any text that you specify in the body of the cftextitem tag. This attribute can be useful if the cfformitem tag is in a cfformgroup type="repeater" tag. See Usage. For details, see Flash form data binding in the cfinput tag description.

Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML in all controls except text and html types.

Usage

This tag requires an end tag or a slash before the closing end character of the opening tag, as the following example shows:

<cfformitem type="hrule" />

For more information on using this tag in Flash forms, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

Example

The following example shows a simple Flash form using horizontal rules and text:

<h3>cfformitem Example</h3>
<cfform name="myform" height="450" width="500" format="Flash" >
    <cfformitem type="hrule" />
    <cfformitem type="text">
        This simple form has two hrule cfformitem tags around the cfformitem tag
        that contains this text.
    </cfformitem>
    <cfformitem type="hrule" />
</cfform>

For a more complex form, see cfformgroup .


cfftp

Description

Lets users implement File Transfer Protocol (FTP) operations.

Category

File management tags, Internet Protocol tags

Syntax

The tag syntax depends on the action attribute value. See the following sections:

  • cfftp: Opening and closing FTP server connections
  • cfftp: Connection: File and directory operations
  • cfftp action = "listDir"

See also

cfhttp, cfldap, cfmail, cfpop; Performing file operations with cfftp in Interacting with Remote Servers in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the result attribute for file and directory operations.

ColdFusion MX: Deprecated the agentname attribute. It might not work, and might cause an error, in later releases.

Usage

Use this tag to move files between a ColdFusion server and an FTP server.

This tag does not move files between a ColdFusion server and a client browser. You do this as follows:

  • To transfer files from a client to a ColdFusion server: cffile action = "upload"
  • To transfer files from a ColdFusion server to a client: the cfcontent tag

Security settings

ColdFusion MX security settings can prevent the cfftp tag from executing. If you run ColdFusion applications on a server that is used by multiple customers, consider the security of the files that the customer can move. For more information, see the "Administering Security" section of Configuring and Administering ColdFusion MX.


cfftp: Opening and closing FTP server connections

Description

To establish a connection with an FTP server, you use the open action with a connection attribute.

Syntax

<cfftp
    action = "action"
    username = "name"
    password = "password"
    server = "server"
    timeout = "timeout in seconds"
    port = "port"
    connection = "name"
    proxyServer = "proxy server"
    retryCount = "number"
    stopOnError = "yes" or "no"
    passive = "yes" or "no">

See also

cfhttp , cfldap , cfmail , cfpop

Attributes

Attribute

Req/Opt

Default

Description

action

Required

FTP operation to perform.

  • open: creates an FTP connection
  • close: terminates an FTP connection

username

Required if action = "open"

User name to pass in the FTP operation.

password

Required if action = "open"

Password to log in the user.

server

Required if action = "open"

FTP server to which to connect; for example, ftp.myserver.com

timeout

Optional

30

Value in seconds for the timeout of all operations, including individual data request operations.

port

Optional

21

Remote port to which to connect.

connection

Optional, but always used with open or close

Name of the FTP connection. If you specify the username, password, and server attributes, and if no connection exists for them, ColdFusion creates one. Calls to cfftp with the same connection name reuse the connection.

proxyServer

Optional

String. Name of proxy server (or servers) to use, if proxy access is specified.

retryCount

Optional

1

Number of retries until failure is reported.

stopOnError

Optional

no
  • yes: halts processing, displays an appropriate error.
  • no: populates these variables:
    • cfftp.succeeded – yes or no.
    • cfftp.errorCode – Error number. See the IETF Network
      Working Group RFC 959: File Transfer Protocol (FTP)
      www.ietf.org/rfc/rfc0959.txt.
    • cfftp.errorText – Message text.

For conditional operations, use cfftp.errorCode. Do not use cfftp.errorText for this purpose.

passive

Optional

no
  • yes: enables passive mode.
  • no

Usage

When you establish a connection with cfftp action="open" and specify a name in the connection attribute, ColdFusion caches the connection so that you can reuse it to perform additional FTP operations. When you use a cached connection for subsequent FTP operations, you do not have to specify the username, password, or server connection attributes. The FTP operations that use the same connection name automatically use the information stored in the cached connection. Using a cached connection helps save connection time and improves file transfer performance.

You do not need to open a connection for single, simple, FTP operations, such as GetFile or PutFile.

To keep a connection open throughout a session or longer, put the connection name in the Session or Application scope; for example, specify connection="Session.FTPConnection". However, if you do this, you must specify the full variable name in all FTP operations, and you must use the close action when you are finished. Keeping a connection open prevents others from using the FTP server; so close a connection as soon as possible. If you do not assign the connection name to Session or Application variable, the connection remains open for the current page only, and you do not have to close it manually.

Changes to a cached connection, such as changing retryCount or timeout values, might require reestablishing the connection.

Example

<p>cfftp lets users implement File Transfer Protocol operations.
By default, cfftp caches an open connection to an FTP server.
<p>cfftp operations are usually of two types:
<ul>
    <li>Establishing a connection
    <li>Performing file and directory operations
</ul>
<p>This example opens and verifies a connection, lists the files in a
directory, and closes the connection.
<p>Open a connection
<cfftp action = "open"
    username = "anonymous"
    connection = "My_query"
    password = "youremail@email.com"
    server = "ftp.tucows.com"
    stopOnError = "Yes">
<p>Did it succeed? <cfoutput>#cfftp.succeeded#</cfoutput>
<p>List the files in a directory:
<cfftp action = "LISTDIR"
    stopOnError = "Yes"
    name = "ListFiles"
    directory = "/"
    connection = "my_query">
<cfoutput query = "ListFiles">
    #name#<br>
</cfoutput>

<p>Close the connection:
<cfftp action = "close"
connection = "My_query"
stopOnError = "Yes">
<p>Did it succeed? <cfoutput>#cfftp.succeeded#</cfoutput>


cfftp: Connection: File and directory operations

Description

Use this form of the cfftp tag to perform file and directory operations with cfftp.

Syntax

<cfftp
    action = "action"
    username = "name"
    password = "password"
    name = "query_name"
    server = "server"
    ASCIIExtensionList = "extensions"
    transferMode = "mode"
    failIfExists = "yes" or "no"
    directory = "directory name"
    localFile = "filename"
    remoteFile = "filename"
    item = "directory or file"
    existing = "file or directory name"
    new = "file or directory name"
    proxyServer = "proxy server"
    passive = "yes" or "no">
result = "result_name"

See also

cfhttp , cfldap , cfmail , cfpop

Attributes

Attribute

Req/Opt

Default

Description

action

Required if connection is not cached

FTP operation to perform:

  • changedir
  • createDir
  • listDir
  • removeDir
  • getFile
  • putFile
  • rename
  • remove
  • getCurrentDir
  • getCurrentURL
  • existsDir
  • existsFile
  • exists

username

Required if connection is not cached

User name to pass in the FTP operation.

password

Required if action = "open"

Password to log in the user.

name

Required if action = "listDir"

Query name of directory listing.

server

Required if FTP connection is not cached

FTP server to which to connect; for example, ftp.myserver.com.

ASCIIExtensionList

Optional

txt;htm;html;cfm;cfml;
shtm;shtml;
css;asp;asa

Delimited list of file extensions that force ASCII transfer mode, if transferMode = "auto".

transferMode

Optional

Auto
  • ASCII FTP transfer mode
  • Binary FTP transfer mode
  • Auto FTP transfer mode

failIfExists

Optional

yes
  • yes: if a local file with same name exists, the getFile action will fail.
  • no

directory

Required if action = "changedir", "createDir", "listDir", or "existsDir"

Directory on which to perform an operation.

localFile

Required if action = "getFile" or "putFile"

Name of the file on the local file system.

remoteFile

Required if action = "getFile", "putFile", or "existsFile"

Name of the file on the FTP server file system.

item

Required if action = "exists" or "remove"

Object of these actions: file or directory.

existing

Required if action = "rename"

Current name of the file or directory on the remote server.

new

Required if action = "rename"

New name of file or directory on the remote server.

proxyServer

Optional

String. Name of the proxy server (s) to use, if proxy access is specified.

passive

Optional

no
  • yes: enables passive mode.
  • no

result

Optional

Specifies a name for the structure in which cfftp stores the returnValue variable. If set, this value replaces cfftp as the prefix to use when accessing returnVariable. See the Usage section for more information

Usage

If you use connection caching to an active FTP connection, you do not have to respecify the username, password, or server connection attributes.

Changing a cached connection, such as changing retryCount or timeout values, might require reestablishing the connection.

If action = "listDir", the attributes column returns directory or normal. Other platform-specific values, such as hidden and system, are no longer supported.

If action = "listDir", a mode column is returned. The column contains an octal string representation of UNIX permissions; for example, "777."

The cfftp.returnValue variable provides the return value for these actions:

  • getCurrentDir
  • getCurrentURL
  • existsDir
  • existsFile
  • exists

For more information, see ColdFusion MX Developer’s Guide.

Caution: Object (file and directory) names are case-sensitive.

Action (cfftp.ReturnValue variable)

The results of an action determine the value of the returnValue variable, as the following table shows:

cfftp action | Value of cfftp.returnValue
getCurrentDir | String. Current directory.
getCurrentURL | String. Current URL.
existsDir | yes or no.
existsFile | yes or no.
exists | yes or no.

To access the returnValue variable, you must prefix it with either cfftp or the value specified by the result attribute, if it is set. The result attribute provides a way for cfftp calls from multiple pages, possibly at the same time, to avoid overwriting the results of one with another. If you set the result attribute to myResult, for example, you would access the returnVariable variable as myResult.returnVariable. Otherwise, you would access it as cfftp.returnVariable.

Example

The following example opens a connection and gets a file listing showing file or directory name, path, URL, length, and modification date:

<p>Open a connection
<cfftp connection = "myConnection"
    username = "myUserName"
    password = "myUserName@allaire.com"
    server = "ftp.allaire.com"
    action = "open"
    stopOnError = "Yes">

<p>Did it succeed? <cfoutput>#cfftp.succeeded#</cfoutput>
<cfftp connection = "myConnection"
    action = "LISTDIR"
    stopOnError = "Yes"
    name = "ListDirs"
    directory = "/">

<p>FTP Directory Listing:<br>
<cftable query = "ListDirs" HTMLTable = "Yes" colHeaders = "Yes">
    <cfcol header = "<b>Name</b>" text = "#name#">
    <cfcol header = "<b>Path</b>" text = "#path#">
    <cfcol header = "<b>URL</b>" text = "#url#">
    <cfcol header = "<b>Length</b>" text = "#length#">
    <cfcol header = "<b>LastModified</b>"
     text = "#DateFormat(lastmodified)#">
    <cfcol header = "<b>IsDirectory</b>" text = "#isdirectory#">
</cftable>

<p>Move Image File to Remote Server:<br></p>
<!--- The image will be put into the root directory of the FTP server unless
otherwise noted.
i.e. remoteFile = "somewhere_put.jpg" vs remoteFile = "/support/somewhere_put.jpg"
--->
<cfftp
connection = "myConnection"
action = "putFile"
name = "uploadFile"
transferMode = "binary"
localFile = "C:\files\upload\somewhere.jpg"
remoteFile = "somewhere_put.jpg"
>
<p>Did it succeed? <cfoutput>#cfftp.succeeded#</cfoutput>

<p>Close the connection:
<cfftp connection = "myConnection"
    action = "close"
    stopOnError = "Yes">
<p>Did it succeed? <cfoutput>#cfftp.succeeded#</cfoutput>


cfftp action = "listDir"

Description

To access the columns in a query object, use this tag with action = "listDir".

Usage

When you use this action, you must specify a value for the name attribute. This value holds the results of the listDir action in a query object. The query object consists of columns that you can reference, in the form queryname.columname[row], where queryname is the name of the query, specified in the name attribute; and columnname is a column returned in the query object. The value row is the row number of each file/directory entry returned by the listDir operation. A separate row is created for each entry:

cfftp query object column | Description
Name | Filename of the current element.
Path | File path (without drive designation) of the current element.
URL | Complete URL for the current element (file or directory).
Length | File size of the current element.
LastModified | Unformatted date/time value of the current element.
Attributes | String. Attributes of the current element: normal or Directory.
IsDirectory | Boolean. Whether object is a file or directory.
Mode | Applies only to UNIX and Linux. Permissions. Octal string.

Note: Previously supported query column values that pertain to system-specific information are not supported; for example, hidden and system.


cffunction

Description

Defines a function that you can call in CFML. Required to define ColdFusion component methods.

History

ColdFusion MX 7: Added the XML value to the returntype attribute.

ColdFusion MX: Added this tag.

Category

Extensibility tags

Syntax

<cffunction
    name = "methodName"
    returnType = "dataType"
    roles = "securityRoles"
    access = "methodAccess"
description = "function description"
output = "yes" or "no"
    displayName = "name"
    Hint = "hint text">

See also

cfargument , cfcomponent , cfinvoke , cfinvokeargument , cfobject , cfproperty , cfreturn

Attributes

Attribute

Req/Opt

Default

Description

name

Required

A string; a component method that is used within the cfcomponent tag.

returnType

Required for a web service; Optional, otherwise.

any

String; a type name; data type of the function return value:

  • any
  • array
  • binary
  • boolean
  • date
  • guid – The argument must be a UUID or GUID of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where each x is a character representing a hexadecimal number (0-9A-F).
  • numeric
  • query
  • string
  • struct
  • uuid: the argument must be a ColdFusion UUID of the form xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx where each x is a character representing a hexadecimal number (0-9A-F).
  • variableName: a string formatted according to ColdFusion variable naming conventions.
  • void: does not return a value
  • xml: allows web service functions to return CFML XML objects and XML strings.
  • a component name: if the type attribute value is not one of the preceding items, ColdFusion treats it as the name of a ColdFusion component. When the function executes, it generates an error if the argument that is passed in is not a CFC with the specified name.

roles

Optional

"" (empty)

A comma-delimited list of ColdFusion security roles that can invoke the method. Only users who are logged in with the specified roles can execute the function. If this attribute is omitted, all users can invoke the method.

access

Optional

public

The client security context from which the method can be invoked:

  • private: available only to the component that declares the method and any components that extend the component in which it is defined.
  • package: available only to the component that declares the method, components that extend the component, or any other components in the package.
  • public: available to a locally executing page or component method.
  • remote: available to a locally or remotely executing page or component method, or a remote client through a URL, Flash, or a web service. To publish the function as a web service, this option is required.

description

Optional

Supplies a short text description of the function.

output

Optional

Function body is processed as standard CFML

Specifies under which conditions the function can generate HTML output.

  • yes: the entire function body is processed as if it were within a cfoutput tag. Variables names surrounded by number signs (#) are automatically replaced with their values.
  • no: the function is processed as if it were within a cfsilent tag

If you do not specify this attribute, the function body is processed as standard CFML. Any variables must be in cfoutput tags.

displayname

Optional

Meaningful only for CFC method parameters. A value to be displayed in parentheses following the function name when using introspection to show information about the CFC.

hint

Optional

Meaningful only for CFC method parameters. Text to be displayed when using introspection to show information about the CFC. The hint attribute value follows the syntax line in the function description.

Usage

The cffunction tag can define a function that you call in the same manner as a ColdFusion built-in function.

To define a ColdFusion component (CFC) method, you must use a cffunction tag.

The following example shows cffunction tag attributes for a simple CFC method that returns a ColdFusion Query object.

<cffunction
    name="getEmployees"
    access="remote"
    returnType="query"
    hint="This query returns all records in the employee database. It can
drill-down or narrow the search, based on optional input parameters.">

For information on using the cffunction tag for ColdFusion components, see Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide.

If you specify a roles attribute, the function executes only if a user is logged in and belongs to one of the specified roles.

If you specify variableName for the returnType attribute, the function must return a string that is in ColdFusion variable name format; that is, the function must return a string that starts with a letter, underscore, or Unicode currency symbol, and consist of letters, numbers, and underscores (_), periods, and Unicode currency symbols, only. ColdFusion does not check whether the value corresponds to an existing ColdFusion variable.

Example

<cfcomponent>
    <cffunction name="getEmp">
         <cfquery
                name="empQuery" datasource="ExampleApps" >
                SELECT FIRSTNAME, LASTNAME, EMAIL
                FROM tblEmployees
         </cfquery>
         <cfreturn empQuery>
    </cffunction>
    <cffunction name="getDept">
        <cfquery
name="deptQuery" datasource="ExampleApps" >
             SELECT *
             FROM tblDepartments
         </cfquery>
         <cfreturn deptQuery>
    </cffunction>
</cfcomponent>


cfgraph

Description

This tag is deprecated. Use the cfchart, cfchartdata, and cfchartseries tags instead.

Displays data graphically.

History

ColdFusion MX: Deprecated this tag. It works differently than it did in ColdFusion 5, and it might not work in later releases.

The incompatibilities between the ColdFusion MX implementation and earlier implementations of this tag are as follows:

cfgraph tag attribute

ColdFusion MX functionality

Title

Ignored.

Titlefont

Ignored.

Barspacing

Ignored.

Bordercolor

Color used for border, gridlines, and text displays.

Colorlist

List of colors to use for each data point for bar, pyramid, area, horizontalbar, cone, cylinder, step, and pie charts.

Valuelabelfont

Sets value label text font. If the Valuelabelfont, Itemlabelfont, and Legendfont values differ, ColdFusion uses the last value that you specify in the tag.

Arial is not supported; it is mapped to Dialog.

Itemlabelfont

Sets item label text font. If the Valuelabelfont, Itemlabelfont, and Legendfont values differ, ColdFusion uses the last value that you specify in the tag.

Arial is not supported; it is mapped to Dialog.

Legendfont

Sets legend text font. If the Valuelabelfont, Itemlabelfont, and Legendfont values differ, ColdFusion uses the last value that you specify in the tag

Arial is not supported; it is mapped to Dialog.

ShowLegend
  • above, below, left, right: these options cause the legend to display, but have no effect on its location.
  • none: prevents display of a legend.

Valuelabelsize

Sets value label text size. If the Valuelabelsize and Itemlabelsize values differ, ColdFusion uses the last value that you specify in the tag.

Itemlabelsize

Sets item label text size.

Itemlabelorientation

Ignored. ColdFusion calculates best orientation based on label and graph size.

Borderwidth
  • a nonzero number: default-width border, regardless of number value.
  • 0: no border.

Depth
  • 0: displays graph with two-dimensional appearance.
  • any other value: displays graph with threedimensional appearance.

Linewidth

Ignored.

Showvaluelabel
  • yes: displays values on mouse-click.
  • no: suppresses value displays.
  • rollover: displays values on mouse-over.

Valuelocation

Ignored.

url

URL of page to open if any item in the graph is clicked.

The following variables may be used within the URL; they are substituted with real values before the URL is accessed:

  • "$value$": selected row/column value or an empty string.
  • "$itemlabel$": selected item (column) value or an empty string.
  • "$serieslabel$": selected series (row) value or an empty string.
  • "javascript:...": executes client side scripts.

Urlcolumn

Ignored.

Type="HorizontalBar"

The (0,0) coordinate is located at the lower-left.

ScaleFrom

If the smallest value in the data is less than scaleFrom or the largest value in the data is greater than scaleTo, the respective data value is used as the minimum or maximum on the Y scale. Therefore, regardless of the scaleFrom or scaleTo value, all data values display.


cfgraphdata

Description

This tag is deprecated. Use the cfchart, cfchartdata, and cfchartseries tags instead.

Displays a data point in a graph. Used within the cfgraph tag.

History

ColdFusion MX: Deprecated this tag. It works differently than in ColdFusion 5 and might not work in later releases.


cfgrid

Description

Used within the cfform tag. Puts a grid control (a table of data) in a ColdFusion form. To specify grid columns and row data, use the cfgridcolumn and cfgridrow tags, or use the query attribute, with or without cfgridcolumn tags.

Category

Forms tags

Syntax

<cfgrid
    name = "name"
    format = "applet" or "Flash" or "xml"
    height = "integer"
    width = "integer"
    query = "query_name"
    selectMode = "mode"
    insert = "yes" or "no"
    delete = "yes" or "no"
    font = "column_font"
    fontSize = "size"
    italic = "yes" or "no"
    bold = "yes" or "no"
    textColor = "web color"
    gridLines = "yes" or "no"
    rowHeight = "pixels"
    colHeaders = "yes" or "no"
    colHeaderFont = "font_name"
    colHeaderFontSize = "size"
    colHeaderItalic = "yes" or "no"
    colHeaderBold = "yes" or "no"
    colHeaderTextColor = "web color"
    bgColor = "web color"
    maxRows = "number"
    The following works in Flash format only
    style= "style specification"
    enabled = "Yes" or "No"
    visible = "Yes" or "No"
    toolTip = "Tip text"
onChange = "ActionScript"
    The following work in applet and XML format only
autoWidth = "yes" or "no"
    vSpace = "integer"
    hSpace = "integer"
    align = "value"
    sort = "yes" or "no"
    href = "URL"
    hrefKey = "column_name"
    target = "URL_target"
    appendKey = "yes" or "no"
    highlightHref = "yes" or "no"
    onValidate = "javascript_function"
    onError = "text"
    gridDataAlign = "position"
    rowHeaders = "yes" or "no"
    rowHeaderAlign = "position"
    rowHeaderFont = "font_name"
    rowHeaderFontSize = "size"
    rowHeaderItalic = "yes" or "no"
    rowHeaderBold = "yes" or "no"
    rowHeaderTextColor = "web color"
    colHeaderAlign = "position"
    selectColor = "web color"
    notSupported = "text"
    pictureBar = "yes" or "no"
    insertButton = "text"
    deleteButton = "text"
    sortAscendingButton = "text"
    sortDescendingButton = "text">
zero or more cfgridcolumn and cfgridrow tags
</cfgrid>

See also

cfapplet , cfcalendar , cfgridcolumn , cfgridrow , cfgridupdate , cfform , cfformgroup , cfformitem , cfgrid , cfinput , cfselect , cfslider , cftextarea , cftree

History

ColdFusion MX 7:

  • Added the format attribute and support for Flash and XML output.
  • Added enabled, onChange, style, tooltip, and visible attributes (Flash format only).

ColdFusion MX: Changed the rowHeaderWidth attribute: ColdFusion does not use the rowHeaderWidth attribute. You can omit it.

Attributes

Note: In XML format, ColdFusion MX passes all attributes to the XML. The supplied XSLT skins do not handle or display XML format grids, but do display applet and Flash format grids.

Attribute

Req/Opt;

Formats

Default

Description

name

Required; All

Name of the grid control.

format

Optional; All

applet
  • applet: generates a Java applet.
  • Flash: generates a Flash grid control.
  • xml: generates an XML representation of the grid.
    In XML format forms, includes the generated XML in the form.
    In HTML format forms, puts the XML in a string variable with the name specified by the name attribute.

height

Optional; All

300 (applet only)

Height of the control, in pixels.

If you omit the attribute in Flash format, the grid sizes automatically..

width

Optional; All

300 (applet only)

Width of the control, in pixels.

If you omit the attribute in Flash format, the grid sizes automatically.

query

Optional; All

Name of the query associated with the control.

selectMode

Optional; All

Applet format: Browse;

Flash format: Row

Selection mode for items in the control.

  • Edit: user can edit grid data. Selecting a cell opens the editor for the cell type.
  • Row: user selections automatically extend to the row that contains selected cell.

The following are used in applet format only; Flash interprets these as Row:

  • Single: user selections are limited to selected cell.
  • Column: user selections automatically extend to column that contains selected cell.
  • Browse: user can only browse grid data.

font

Optional; All

Font of text.

fontSize

Optional; All

Size of text, in points.

italic

Optional; All

no
  • yes: displays text in italics.
  • no

bold

Optional; All

no
  • yes: displays text in bold.
  • no

textColor

Optional; All

Black

Color of text. Can be a hexadecimal value or a named color.

For a hexadecimal value, use the form "##xxxxxx", where x = 0-9 or A-F; use two number signs or none.

For a list of the supported named colors, see cfchart.

selectColor

Optional; All

Background color for a selected item.

  • Options: same as for textColor attribute

gridLines

Optional; All

yes
  • yes: enables row and column rules.
  • no

rowHeight

Optional; All

Minimum row height, in pixels. Used with cfgridcolumn type = "Image"; defines space for graphics to display in row.

colHeaders

Optional; All

yes
  • yes: displays column headers.
  • no

colHeaderFont

Optional; All

Font of column header.

colHeaderFontSize

Optional; All

Size of column header text, in points.

colHeaderItalic

Optional; All

no
  • yes: displays column headers in italics.
  • no

colHeaderBold

Optional; All

no
  • yes: displays column headers in bold.
  • no

colHeaderTextColor

Optional; All

Color of column headers.

  • Options: same as for textColor attribute.

bgColor

Optional; All

Background color of the control.

  • Options: for applet format, same as for textColor attribute; for Flash format, must be a hexadecimal value.
  • Flash format only: to specify background colors for alternating rows, separate the two colors with a comma.

maxRows

Optional; All

Maximum number of rows to display in the grid.

style

Optional;

Flash

Must be a style specification in CSS format. Ignored for type="text".

enabled

Optional;

Flash

Yes

Flash format only: Boolean value specifying whether the control is enabled. A disabled control appears in light gray.

visible

Optional;

Flash

Yes

Flash format only: Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank.

tooltip

Optional;

Flash

Flash format only: text to display when the mouse pointer hovers over the control.

onChange

Optional;

Flash

ActionScript to run when the control changes due to user action in the control.

autoWidth

Optional;

applet

no
  • yes: sets column widths so that all columns display within the grid width. Widths are equal or the proportions are determined by the relative cfgridcolumn width attribute values. Horizontal scroll bars are not available.
  • no: sets columns to equal widths or the values specified in the cfgridcolumn width attributes.

vSpace

Optional;

applet

Vertical space above and below the control, in pixels.

hSpace

Optional;

applet

Horizontal space to the left and right of the control, in pixels.

align

Optional;

applet

Alignment of the grid cell contents:

  • Top
  • Left
  • Bottom
  • Baseline
  • Texttop
  • Absbottom
  • Middle
  • Absmiddle
  • Right

insert

Optional;

applet

no
  • yes: users can insert row data in the grid; takes effect only if selectmode="edit".
  • no

delete

Optional;

applet

no
  • yes: users can delete row data from the grid; takes effect only if selectmode="edit".
  • no

sort

Optional;

applet

no

Adds sort buttons to perform simple text sorts on a user-selected column:

  • yes: put sort buttons on the grid control.
  • no

Independent of this setting, users can sort columns by clicking the column head. If selectMode="browse", the table cannot be sorted.

href

Optional;

applet

URL or name of a query column that contains URLs to hyperlink each grid cell with.

target

Optional;

applet

The target frame or window in which to display the href URL; for example, "_blank".

appendKey

Optional;

applet

yes
  • yes: when used with href, appends "CFGRIDKEY=" and information about the selected items. For details see Using the href attribute.
  • no

hrefKey

Optional;

applet

A query column to use for the value appended to the href URL of each cell, if appendKey="True". If you use cfgridcolumn tags, the column must be specified in one of these tags.

highlightHref

Optional;

applet

yes
  • yes: highlights links associated with an href attribute value.
  • no

onValidate

Optional;

applet

A JavaScript function to validate user input. The form object, input object, and input object value are passed to the function, which must return True if validation succeeds; False otherwise.

onError

Optional;

applet

A JavaScript function to execute if validation fails.

gridDataAlign

Optional;

applet

Left
  • Left: left-aligns data within the column.
  • Right: right-aligns data within the column.
  • Center: centers data within the column.

rowHeaders

Optional;

applet

yes
  • yes: displays a column of numeric row labels.
  • no

rowHeaderAlign

Optional;

applet

Left
  • Left: left-aligns the row header text.
  • Right: right-aligns the row header text.
  • Center: centers the row header text.

rowHeaderFont

Optional;

applet

Font for the row labels.

rowHeaderFontSize

Optional;

applet

Text size of the row labels, in points.

rowHeaderItalic

Optional;

applet

no
  • yes: displays row label text in italics.
  • no

rowHeaderBold

Optional;

applet

no
  • yes: displays row label text in bold.
  • no

rowHeaderTextColor

Optional;

applet

Black

Text color of grid control row headers.

  • Options: same as for the textColor attribute.

colHeaderAlign

Optional;

applet

Left
  • Left: left-aligns the column header text.
  • Right: right-aligns the column header text.
  • Center: centers the column header text.

notSupported

Optional;

applet

(See Description)

Text to display if the browser does not support Java or has Java support disabled.

Default: "<b> Browser must support Java to view ColdFusion Java Applets</b>"

pictureBar

Optional;

applet

no
  • yes: puts images (and no text) on the Insert, Delete, and Sort buttons.
  • no: puts text (and no images) on the Insert, Delete, and Sort buttons.

insertButton

Optional;

applet

Insert

Insert button text; takes effect only if selectmode="edit".

deleteButton

Optional;

applet

Delete

Delete button text; takes effect only if selectmode="edit".

sortAscendingButton

Optional;

applet

A -> Z

Sort button text.

sortDescendingButton

Optional;

applet

Z -> A

Sort button text.

Usage

This tag must be in a cfform tag block.

An applet format grid requires the client to download a Java applet. Also, if the client does not have an up-to-date Java plugin installed, the system might also have to download an updated Java plugin to display the an applet format grid. A Flash format grid generates a Flash control, and can be embedded in an HTML format cfform tag. For this tag to work properly in either Flash or applet format, the browser must also be JavaScript-enabled.

Note: If you specify Flash format for this tag in an HTML format form, and you do not specify height and width attributes, Flash takes up more than the remaining visible area on the screen. If any other output follows the grid, including any form controls, users must scroll to see it. Therefore, if you follow a Flash grid in an HTML form with additional output, specify height and width values.

You can populate a cfgrid with data from a cfquery. If you do not specify any cfgridcolumn tags in the cfgrid body, ColdFusion generates a grid with the following:

  • A column for each column in the query.
  • A default header for each column, created by replacing hyphen or underscore characters in the table column name with spaces. The first character, and any character after a space, are changed to uppercase; all other characters are lowercase.

This tag requires an end tag.

Note: Clicking the submit button while editing a grid cell occasionally causes the cell changes to be lost. To ensure that changes are submitted properly, Macromedia recommends that after user updates data in a cell, they click another cell before submitting the form.

How data is returned from cfgrid

This tag returns data by setting form variables in the data submitted to the form's action page, as an HTML form control does. Because the data can vary, depending on the tag’s SelectMode attribute value, the form variables that are returned also vary depending on this value.

In general, the data returned falls into one of these categories:

  • Simple data, returned from simple select operations
  • Complex data, returned from insert, update and delete operations

Simple selection data (SelectMode = Single, Column, or Row)

The data that form variables return to the cfform's action page contains information about which cells the user selected. In general, ColdFusion makes this data available in the action page, as ColdFusion variables in the Form scope, with the naming convention form.#GridName#.#ColumnName#

Each SelectMode returns these form variable(s):

  • SelectMode="single"
    form.#GridName#.#ColumnName# = "SelectedCellValue"
  • SelectMode="column"
    form.#GridName#.#ColumnName# = "ValueOfCellRow1,
ValueOfCellRow2, ValueOfCellRowN"
  • SelectMode="row"
    form.#GridName#.#Column1Name# = "ValueOfCellInSelectedRow"
form.#GridName#.#Column2Name# = "ValueOfCellInSelectedRow"
form.#GridName#.#ColumnNName# = "ValueOfCellInSelectedRow"

Complex update data (SelectMode = Edit)

The grid returns a large amount of data, to inform the action page of inserts, updates or deletes that the user made to the grid. In most cases, you can use the cfgridupdate tag to automatically gather the data from the form variables; the tag collects data, writes SQL calls, and updates the data source.

If you cannot use cfgridupdate (if, for example, you must distribute the returned data to more than one data source), you must write code to read form variables. In this mode, ColdFusion creates the following array variables in the Form scope for each cfgrid:

form.#GridName#.#ColumnName#
form.#GridName#.original.#ColumnName#
form.#GridName#.RowStatus.Action

Each table row that contains an update, insert, or deletion has a parallel entry in each of these arrays. To view all the information for all the changes, you can traverse the arrays, as in this example. To make it work with a cfgrid on a submitted cfform, set the GridName variable to the name of the grid and the ColNameList to a list of the grid columns.

<cfloop index="ColName" list="#ColNameList#">
    <cfif IsDefined("form.#GridName#.#ColName#")>
        <cfoutput><br>form.#GridName#.#ColName#:<br></cfoutput>

        <cfset Array_New = form.[#GridName#][#ColName#]>
        <cfset Array_Orig = form[#GridName#][’original’][#ColName#]>
        <cfset Array_Action = form[#GridName#]RowStatus.Action>

        <cfif NOT IsArray(Array_New)>
            <b>The form variable is not an array!</b><br>
        <cfelse>
            <cfset size = ArrayLen(Array_New)>
            <cfoutput>
            Result Array Size is #size#.<br>
            Contents:<br>
            </cfoutput>

            <cfif size IS 0>
                <b>The array is empty.</b><br>
            <cfelse>
                <table BORDER="yes">
                    <tr>
                        <th>Loop Index</TH>
                        <th>Action</TH>
                        <th>Old Value</TH>
                        <th>New Value</TH>
                    </tr>
                    <cfloop index="LoopCount" from="1" to=#size#>
                        <cfset Val_Orig	= Array_Orig[#LoopCount#]>
                        <cfset Val_New 	= Array_New[#LoopCount#]>
                    <cfset Val_Action	= Array_Action[#LoopCount#]>
                    <cfoutput>
                    <tr>
                        <td>#LoopCount#</td>
                        <td>#Val_Action#</td>
                        <td>#Val_Orig#</td>
                        <td>#Val_New#</td>
                    </tr>
                    </cfoutput>
                    </cfloop>
                </table>
            </cfif>
        </cfif>

    <cfelse>
        <cfoutput>form.#GridName#.#ColName#: NotSet!</cfoutput><br>
    </cfif>
</cfloop>

Using the href attribute

When specifying a URL with grid items using the href attribute, the selectMode attribute value determines whether the appended key value is limited to one grid item or extends to a grid column or row. When a user clicks a linked grid item, a cfgridkey variable is appended to the URL, in this form:

http://myserver.com?cfgridkey=selection

If the appendKey attribute is set to no, no grid values are appended to the URL.

The value of selection is determined by the value of the selectMode and attribute:

  • If you specify a hrefKey attribute, selection is the field value of the column specified by the attribute. Otherwise, it is one of the following:
  • If selectMode="Single", selection is the value of the column clicked.
  • If selectMode="Row", selection is a comma-delimited list of column values in the clicked row, beginning with the value of the first cell in the row.
  • If selectMode="Column", selection is a comma-delimited list of row values in the clicked column, beginning with the value of the first cell in the column.

Example

The following example creates a Flash form that displays a set of available courses from the CourseList table in the cfdocexamples database. For more complex examples that use the cfgrid tag, see cfgridcolumn, cfgridrow, and cfgridupdate.

<!--- Query the database to fill up the grid. --->
<cfquery name = "GetCourses" dataSource = "cfdocexamples">
SELECT Course_ID, Dept_ID, CorNumber,
CorName, CorLevel
FROM CourseList
ORDER by Dept_ID ASC, CorNumber ASC
</cfquery>

<h3>cfgrid Example</h3>
<I>Currently available courses</i>
<!--- cfgrid must be inside a cfform tag. --->
<cfform>
    <cfgrid name = "FirstGrid" format="Flash"
        height="320" width="580"
        font="Tahoma" fontsize="12"
        query = "GetCourses">
    </cfgrid>
</cfform>


cfgridcolumn

Description

Used with the cfgrid tag in a cfform. Formats a columns and optionally populates the column from a query. The font and alignment attributes used in cfgridcolumn override global font or alignment settings defined in cfgrid.

Category

Forms tags

Syntax

<cfgridcolumn
    name = "column_name"
    header = "header"
    width = "column_width"
    type = "type"
    display = "yes" or "no"
    select = "yes" or "no"
    font = "column_font"
    fontSize = "size"
    italic = "yes" or "no"
    bold = "yes" or "no"
    textColor = "web color" or "expression"
    bgColor = "web color" or "expression"
    dataAlign = "position"
The following attribute applies to Flash format only
    mask= "format mask"
The following attribute applies to applet format only
    href = "URL"
    hrefKey = "column_name"
    target = "URL_target"
    headerFont = "font_name"
    headerFontSize = "size"
    headerItalic = "yes" or "no"
    headerBold = "yes" or "no"
    headerTextColor = "web color"
    headerAlign = "position"
    numberFormat = "format"
    values = "Comma-separated strings and/or numeric range"
    valuesDisplay = "Comma-separated strings and/or numeric range"
    valuesDelimiter = "delimiter character">

See also

cfgrid , cfgridrow , cfgridupdate , cfform , cfapplet , cfinput , cfselect , cfslider , cftextarea , cftree

History

ColdFusion MX 7: Added the mask attribute, and the currency type attribute value.

ColdFusion MX: Changed behavior if select="no": a user cannot select and edit the cell data, regardless of the cfgrid selectmode attribute value. When clicked, the cell border (and, depending on the selectColor value, the cell background) changes color, but the cell data cannot be edited.

Attributes

Note: In XML format, ColdFusion MX passes all attributes to the XML. The supplied XSLT skins do not handle or display XML format grids, but do display applet and Flash format grids.

Attribute

Req/Opt;

Formats

Default

Description

name

Required;

All

Name of the grid column element. If the grid uses a query, this attribute must be the name of the query column that populates the grid column.

header

Optional;

All

yes

Column header text. Used only if the cfgrid colHeaders attribute is True (the default).

width

Optional;

All

Column head width

Column width, in pixels.

type

Optional;

All

You can specify the following values in all formats:

  • image: grid displays the image specified by the URL in the column. If you use a relative URL, the image must be in the CFIDE\classes directory or a subdirectory. If image is larger than column cell, it is clipped to fit. Flash images must be JPEG files. Applet images can be JPEG or GIF files.
  • boolean: column displays as check box; if cell is editable, user can change the check mark.
  • numeric: user can sort grid data numerically.
  • string_noCase: user can sort grid data as case-insensitive text.

You can specify the following attribute in applet format; it does not work in Flash grids.

  • image: you can use the following built-in ColdFusion image names, in addition to paths to image files, in the column values:

- cd

- computer

- document

- element

- folder

- floppy

- fixed

- remote

You can specify the following attribute in Flash format; it does not work in applet grids:

  • currency: formats the column data as currency, aligning it around the decimal point. If users sort the grid using this column, it will sort correctly for the currency, Use the mask attribute to specify a currency symbol, which defaults to the dollar sign ($).

display

Optional;

All

yes
  • yes
  • no: hides the column.

select

Optional;

All

yes

Determines selection behavior if the cfgrid selectmode attribute value is column, edit, or single; ignored for row or browse values.

  • yes: users can select the column or select or edit cells in the column, as specified by the selectmode attribute.
  • no: users cannot select the column or select or edit cells in the column.

font

Optional;

All

As specified by cfgrid

Font of data in column.

fontSize

Optional;

All

As specified by cfgrid

Size of text in column.

italic

Optional;

All

As specified by cfgrid
  • yes: displays grid control text in italics.
  • no

bold

Optional;

All

As specified by cfgrid
  • yes: displays grid control text in bold.
  • no

textColor

Optional;

All

Color of grid element text in column as a hexadecimal number or text name.

To enter a hexadecimal value, use the form "##xxxxxx", where x = 0-9 or A-F; use two number signs or none.

  • Any color, in hexadecimal format
  • Black
  • Red
  • Blue
  • Magenta
  • Cyan
  • Orange
  • Darkgray
  • Pink
  • Gray
  • White
  • Lightgray
  • Yellow

bgColor

Optional;

All

Color of background of grid column.

  • Options: same as for the textColor attribute.

dataAlign

Optional;

All

as specified by cfgrid

Column data alignment:

  • Left
  • Right
  • Center

mask

optional;
Flash

A mask pattern that controls the character pattern that the form displays or allows users to input and sends to ColdFusion.

For columns with the currency type attribute, the mask specifies the currency symbol. ColdFusion MX automatically inserts the character before the numeric value.

For columns with text or numeric values, mask specifies the format to display or allow users to input, as follows:

  • A = [A-Za-z]
  • X = [A-Za-z0-9]
  • 9 = [0-9]
  • ? = Any character
  • All other characters = ColdFusion inserts the literal character.

If the column values are dates or timestamps, ColdFusion uses the mask pattern to format the selected date.

For details of the date/time mask format, see date/time formats in mask attribute.

href

Optional;

Applet

URL or query column name that contains a URL to hyperlink each grid column with.

hrefKey

Optional;

Applet

The query column to use for the value appended to the href URL of each column, instead of the column’s value.

target

Optional;

Applet

Frame in which to open link specified in href.

headerFont

Optional;

Applet

as specified by cfgrid

Column header font.

headerFontSize

Optional;

Applet

as specified by cfgrid

Column header text size, in pixels.

headerItalic

Optional;

Applet

as specified by cfgrid
  • yes: displays column header in italics.
  • no

headerBold

Optional;

Applet

as specified by cfgrid
  • yes: displays header in bold.
  • no

headerTextColor

Optional;

Applet

Color of grid control column header text.

  • Options: same as for the textColor attribute.

headerAlign

Optional;

Applet

as specified by cfgrid

Column header text alignment:

  • Left
  • Right
  • Center

numberFormat

Optional;

Applet

Format for displaying numeric data in the grid. See numberFormat mask characters.

values

Optional;

Applet

Formats cells in column as drop-down list boxes; specify items in drop-down list. For example:

values = "arthur, scott, charles, 1-20, mabel"

valuesDisplay

Optional;

Applet

Maps elements in the values attribute to string to display in the drop-down list. Delimited strings and/or numeric range(s).

valuesDelimiter

Optional;

Applet

, [comma]

Delimiter in values and valuesDisplay attributes.

numberFormat mask characters

In applet format only, you can use the following numberFormat attribute mask characters to format output in U.S. numeric and currency styles. For more information on using these mask characters, see NumberFormat. (The cfgridcolumn tag does not support international number formatting.)

Character | Meaning
_ | (Underscore) Digit placeholder.
9 | Digit placeholder.
. | (Period) Location of mandatory decimal point.
0 | Located to left or right of mandatory decimal point; pads with zeros.
( ) | Puts parentheses around mask if number is less than 0.
+ | Puts plus sign before positive numbers, minus sign before negative numbers.
- | Puts space before positive numbers, minus sign before negative numbers.
, | (Comma) Separates every third decimal-place with a comma.
L,C | Left-justify or center-justify number within width of mask column. First character of mask must be L or C. Default: right-justified.
$ | Puts dollar sign before formatted number. Must be the first character of mask.
^ | (Caret) Separates left from right formatting.

date/time formats in mask attribute

By default, Flash displays date/time values in grid columns using a format that shows values such as Oct 29 2004 11:03:21. Use the mask attribute to display the date or time in a different format, as described in the following table:

Pattern letter

Description

Y

Year. If the number of pattern letters is two, the year is truncated to two digits; otherwise, it appears as four digits. The year can be zero-padded, as the third example shows in the following set of examples:

Examples:

YY = 03

YYYY = 2003

YYYYY = 02003

M

Month in year. The format depends on the following criteria:

  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.
  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.
  • If the number of pattern letters is three, the format is interpreted as short text.
  • If the number of pattern letters is four, the format is interpreted as full text.

Examples:

M = 7

MM= 07

MMM=Jul

MMMM= July

D

Day in month.

Examples:

D=4

DD=04

DD=10

E

Day in week. The format depends on the following criteria:

  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.
  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.
  • If the number of pattern letters is three, the format is interpreted as short text.
  • If the number of pattern letters is four, the format is interpreted as full text.

Examples:

E = 1

EE = 01

EEE = Mon

EEEE = Monday

A

AM/PM indicator.

J

Hour in day (0-23).

H

Hour in day (1-24).

K

Hour in am/pm (0-11).

L

Hour in am/pm (1-12).

N

Minute in hour.

Examples:

N = 3

NN = 03

S

Second in minute.

Other text

You can add other text into the pattern string to further format the string. You can use punctuation, numbers, and all lowercase letters. You should avoid uppercase letters because they may be interpreted as pattern letters.

Example:

EEEE, MMM. D, YYYY at H:NN A = Tuesday, Sept. 8, 2003 at 1:26 PM

Example

The following example lets you update certain fields of the CourseList table in the cfdocexamples database. It uses cfgridcolumn tags to structure the table.

<!--- If the gridEntered field exists, the form has been submitted.
        Update the database. --->
<cfif IsDefined("form.gridEntered")>
    <cfgridupdate grid = "FirstGrid" dataSource = "cfdocexamples"
    tableName = "CourseList" keyOnly = "Yes">
</cfif>

<!--- Query the database to fill up the grid. --->
<cfquery name = "GetCourses" dataSource = "cfdocexamples">
 SELECT Course_ID, Dept_ID, CorNumber,
     CorName, CorLevel, CorDesc
FROM CourseList
ORDER by Dept_ID ASC, CorNumber ASC
</cfquery>

<html>
<head>
<title>cfgrid Example</title>
</head>
<body>
<h3>cfgrid Example</h3>
<I>You can update the Name, Level, and Description information for courses.</i>
<!--- The cfform tag must surround a cfgrid control. --->
<cfform action = "#CGI.SCRIPT_NAME#">
    <cfgrid name = "FirstGrid" width = "500"
            query = "GetCourses" colheaderbold="Yes"
            font = "Tahoma" rowHeaders = "No"
            selectColor = "Red" selectMode = "Edit" >
        <!--- cfgridcolumn tags arrange the table and control the display. --->
        <!--- Hide the primary key, required for update --->
        <cfgridcolumn name = "Course_ID" display = "No">
        <!--- select="No" does not seem to have any effect !!! --->
        <cfgridcolumn name = "Dept_ID" header = "Department" Select="No"
            width="75" textcolor="blue" bold="Yes">
        <cfgridcolumn name = "CorNumber" header = "Course ##" Select="No"
            width="65">
        <cfgridcolumn name = "CorName" header = "Name" width="125">
        <cfgridcolumn name = "CorLevel" header = "Level" width="85">
        <cfgridcolumn name = "CorDesc" header = "Description" width="125">
    </cfgrid>
    <br>
    <cfinput type="submit" name="gridEntered">
</cfform>
</body>
</html>


cfgridrow

Description

Lets you define a cfgrid control that does not use a query as source for row data. If a query attribute is specified in the cfgrid tag, the cfgridrow tags are ignored.

Category

Forms tags

Syntax

<cfgridrow
    data = "col1, col2, ...">

See also

cfgrid , cfgridcolumn , cfgridupdate , cfform , cfinput , cfselect , cfslider , cftextarea , cftree

Attributes

Attribute | Req/Opt | Default | Description
data | Required |  | Comma-delimited list of column values. If a value contains a comma, it must be escaped with another comma.

Example

The following example shows how you use the cfgridrow tag can populate a cfgrid tag from list data:

<!--- Set two lists, each with the data for a grid column. --->
<cfset cities = "Rome,Athens,Canberra,Brasilia,Paris">
<cfset countries = "Italy,Greece,Australia,Brazil,France">

<cfform name = "cities">
    <cfgrid name="GeoGrid" autowidth = "yes" vspace = "4"
            height = "120" font="tahoma" rowheaders="no">
        <cfgridcolumn name="City" header="City">
        <cfgridcolumn name="Country" header="Country">
        <!--- Loop through the lists using cfgridrow to poplulate the grid. --->
        <cfloop index="i" from="1" to="#ListLen(cities)#">
            <cfgridrow data ="#ListGetAt(cities, i)#,#ListGetAt(countries, i)#">
        </cfloop>
    </cfgrid><br><br>
</cfform>


cfgridupdate

Description

Used within a cfgrid tag. Updates data sources directly from edited grid data. This tag provides a direct interface with your data source.

This tag applies delete row actions first, then insert row actions, then update row actions. If it encounters an error, it stops processing rows.

Category

Forms tags

Syntax

<cfgridupdate
    grid = "gridname"
    dataSource = "data source name"
    tableName = "table name"
    username = "data source username"
    password = "data source password"
    tableOwner = "table owner"
    tableQualifier = "qualifier"
    keyOnly = "yes" or "no">

See also

cfgrid , cfgridcolumn , cfgridrow , cfform , cfapplet , cfinput , cfselect , cfslider , cftextinput , cftree

History

ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider, and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5.

Attributes

Attribute

Req/Opt

Default

Description

grid

Required

Name of the cfgrid form element that is the source for the update action.

dataSource

Required

Name of the data source for the update action.

tableName

Required

Name of the table to update.

For ORACLE drivers, entry must be upper-case.

For Sybase driver, entry is case-sensitive; must be same case as used when table was created.

username

Optional

Overrides username value specified in ODBC setup.

password

Optional

Overrides password value specified in ODBC setup.

tableOwner

Optional

Table owner, if supported.

tableQualifier

Optional

Table qualifier, if supported. Purpose:

  • SQL Server and Oracle driver: name of database that contains the table.
  • Intersolv dBASE driver: directory of DBF files.

keyOnly

no

Applies to the update action:

  • yes: the WHERE criteria are limited to the key values.
  • no: the WHERE criteria include key values and the original values of changed fields.

Example

The following example lets you update a database by using a cfgrid tag to add and delete entire records or to update the data in individual cells. The cfgridupdate tag processes the data from the submitted form and updates the database.

<!--- If the gridEntered form field exists, the form was submitted.
        Perform gridupdate. --->
<cfif IsDefined("form.gridEntered") is True>
    <cfgridupdate grid = "FirstGrid" dataSource = "cfdocexamples" Keyonly="true"
        tableName = "CourseList">
 </cfif>

<!--- Query the database to fill up the grid. --->
<cfquery name = "GetCourses" dataSource = "cfdocexamples">
SELECT Course_ID, Dept_ID, CorNumber,
     CorName, CorLevel, CorDesc
FROM CourseList
ORDER by Dept_ID ASC, CorNumber ASC
</cfquery>

<h3>cfgrid Example</h3>
<I>Try adding a course to the database, and then deleting it.</i>
<cfform>
<cfgrid name = "FirstGrid" width = "450"
    query = "GetCourses" insert = "Yes" delete = "Yes"
    font = "Tahoma" rowHeaders = "No"
    colHeaderBold = "Yes"
    selectMode = "EDIT"
    insertButton = "Insert a Row" deleteButton = "Delete selected row" >
</cfgrid><br>
<cfinput type="submit" name="gridEntered">
</cfform>...


cfheader

Description

Generates custom HTTP response headers to return to the client.

Category

Data output tags, Page processing tags

Syntax

<cfheader
    name = "header_name"
    value = "header_value"
    charset="charset">
or
<cfheader
    statusCode = "status_code"
    statusText = "status_text">

See also

cfcache , cfflush , cfhtmlhead , cfinclude , cfsetting , cfsilent , cfcontent

History

ColdFusion MX 6.1: Changed behavior for the name attribute: cfheader name="Content-Disposition" uses the default file character encoding to encode this header’s value, so the name of a file can include characters in the character encoding used in the file.

Attributes

Attribute

Req/Opt

Default

Description

name

Required if statusCode not specified

Header name.

value

Optional

HTTP header value.

charset

Optional

UTF-8

The character encoding in which to encode the header value. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information about character encodings, see
www.w3.org/International/O-charset.html.

statusCode

Required if name not specified

Number. HTTP status code.

statusText

Optional

Explains the status code.

Usage

If you use this tag after the cfflush tag on a page, an error is thrown.

Example

<h3>cfheader Example</h3>

<p>cfheader generates custom HTTP response headers to return to the client.
<p>This example forces browser client to purge its cache of requested file.
<cfheader name="Expires" value="#GetHttpTimeString(Now())#">


cfhtmlhead

Description

Writes text to the head section of a generated HTML page.

Category

Page processing tags

Syntax

<cfhtmlhead
    text = "text">

See also

cfcache , cfflush , cfheader , cfheader , cfinclude , cfsetting , cfsilent

Attributes

Attribute | Req/Opt | Default | Description
text | Required |  | Text to add to the <head> area of an HTML page.

Usage

Use this tag for embedding JavaScript code, or putting other HTML tags, such as meta, link, title, or base in an HTML page header.

If you use this tag after the cfflush tag on a page, an error is thrown.

Example

<!--- This example displays the information provided by the Macromedia
Designer & Developer Center XML feed,
http://www.macromedia.com/devnet/resources/macromedia_resources.rdf
See http://www.macromedia.com/desdev/articles/xml_resource_feed.html
for more information on this feed. --->

<!--- Set the URL address. --->
<cfset urlAddress="http://www.macromedia.com/devnet/resources/macromedia_resources.rdf">

<!--- Use the CFHTTP tag to get the file content represented by urladdress
Note that />, not an end tag. terminates this tag. --->
<cfhttp url="#urladdress#" method="GET" resolveurl="Yes" throwOnError="Yes"/>

<!--- Parse the XML and output a list of resources. --->
<cfset xmlDoc = XmlParse(CFHTTP.FileContent)>

<!--- Get the array of resource elements, the xmlChildren of the xmlroot. --->
<cfset resources=xmlDoc.xmlroot.item>
<cfset numresources=ArrayLen(xmlDoc.xmlRoot.xmlChildren)-1>
<cfloop index="i" from="1" to="#numresources#">
<cfset item=resources[i]>
<cfoutput>
<strong><a href=#item.link.xmltext#>#item.title.xmltext#</strong></a><br>
<strong>Author</strong>&nbsp;&nbsp;#item.creator.xmltext#<br>
<strong>Description</strong> #item.description.xmlText#<br>
<strong>Applies to these products</strong><br>
<cfloop index="i" from="1" to="#arrayLen(item.subject)#" step="1">
#item.subject[i].xmltext#<br>
</cfloop>
<br>
</cfoutput>
</cfloop>


cfhttp

Description

Generates an HTTP request and handles the response from the server.

Category

Internet Protocol tags

Syntax

<cfhttp
    url = "server_URL"
    port = "port_number"
    method = "method_name"
    proxyServer = "hostname"
    proxyPort = "port_number"
    proxyUser = "username"
    proxyPassword = "password"
    username = "username"
    password = "password"
    userAgent = "user_agent"
    charset = "character encoding"
    resolveURL = "yes" or "no"
    throwOnError = "yes" or no"
    redirect = "yes" or "no"
    timeout = "timeout_period"
    getasbinary = "yes or no"
    multipart = "yes or no"
    path = "path"
    file = "filename"
    name = "queryname"
    columns = "query_columns"
    firstrowasheaders = "yes" or "no"
    delimiter = "character"
    textQualifier = "character"
    result = "result_name"
    cfhttpparam tags [optional for some methods]
</cfhttp>

See also

cfhttpparam , GetHttpRequestData , cfftp , cfldap , cfmail , cfpop , SetEncoding

History

ColdFusion MX 7: Added the result attribute, which allows you to specify an alternate variable in which to receive a result.

ColdFusion MX 6.1:

  • Added support for the following methods: HEAD, PUT, DELETE, OPTIONS, TRACE.
  • Added multipart, getAsBinary, proxyUser, and proxyPassword attributes.
  • Changed httpparam behavior: all operations can have httpparam tags.
  • Added the cfhttp.errorDetail return variable.
  • Modified response body content types considered to be text.
  • Changed behavior for multiple headers: multiple headers of the same type are returned in an array.
  • Added support for HTTPS proxy tunneling.
  • Fixed bugs in code and documentation.

ColdFusion MX:

  • Added the charset and firstrowasheaders attributes.
  • Changed Secure Sockets Layer (SSL) support: ColdFusion uses the Sun JSSE library, which supports 128-bit encryption, to support SSL.

Attributes

The following attributes control the HTTP transaction and can be used for all HTTP methods:

Attribute

Req/Opt

Default

Description

url

Req

Uses the http protocol

Address of the resource on the server which will handle the request. The URL must include the hostname or IP address.

If you do not specify the transaction protocol (http:// or https://), ColdFusion defaults to http.

If you specify a port number in this attribute, it overrides any port attribute value.

The cfhttpparam tag URL attribute appends query string attribute-value pairs to the URL.

port

Opt

80 for http

443 for https

Port number on the server to which to send the request. A port value in the url attribute overrides this value.

method

Opt

GET
  • GET: requests information from the server. Any data that the server requires to identify the requested information must be in the URL or in cfhttp type="URL" tags.
  • POST: sends information to the server for processing. Requires one or more cfhttpparam tags. Often used for submitting form-like data.
  • PUT: requests the server to store the message body at the specified URL. Use this method to send files to the server.
  • DELETE: requests the server to delete the specified URL.
  • HEAD: identical to the GET method, but the server does not send a message body in the response. Use this method for testing hypertext links for validity and accessibility, determining the type or modification time of a document, or determining the type of server.
  • TRACE: requests that the server echo the received HTTP headers back to the sender in the response body. Trace requests cannot have bodies. This method enables the ColdFusion application to see what is being received at the server, and use that data for testing or diagnostic information.
  • OPTIONS: a request for information about the communication options available for the server or the specified URL. This method enables the ColdFusion application to determine the options and requirements associated with a URL, or the capabilities of a server, without requesting any additional activity by the server.

proxyServer

Opt

Host name or IP address of a proxy server to which to send the request.

proxyPort

Opt

80

Port number to use on the proxy server.

proxyUser

Opt

User name to provide to the proxy server.

proxyPassword

Opt

Password to provide to the proxy server.

username

Opt

Use to pass a user name to the target URL for Basic Authentication. Combined with password to form a base64 encoded string that is passed in the Authenticate header. Does not provide support for Integrated Windows, NTLM, or Kerebos authentication.

password

Opt

Use to pass a password to the target URL for Basic Authentication. Combined with username to form a base64 encoded string that is passed in the Authenticate header. Does not provide support for Integrated Windows, NTLM, or Kerebos authentication.

userAgent

Opt

Cold
Fusion

Text to put in the user agent request header. Used to identify the request client software. Can make the ColdFusion application appear to be a browser.

charset

Opt

For request: UTF-8

For response: charset specified by response Content- Type header, or UTF-8 if response does not specify charset.

The character encoding of the request, including the URL query string and form or file data, and the response. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information character encodings, see
www.w3.org/International/O-charset.html.

resolveURL

Opt

no
  • no: does not resolve URLs in the response body. As a result, any relative URL links in the response body do not work.
  • yes: resolves URLs in the response body to absolute URLs, including the port number, so that links in a retrieved page remain functional. Applies to these HTML tags:
    • - img src
    • - a href
    • - form action
    • - applet code
    • - script src
    • - embed src
    • - embed pluginspace
    • - body background
    • - frame src
    • - bgsound src
    • - object data
    • - object classid
    • - object codebase
    • - object usemap

Does not resolve URLs if the file and path attributes are used.

throwOnError

Opt

no
  • yes: if the server returns an error response code, throws an exception that can be caught using the cftry and cfcatch or ColdFusion error pages.
  • no: does not throw an exception if an error response is returned. In this case, your application can use the cfhttp.StatusCode variable to determine if there was an error and its cause.

redirect

Opt

yes

If the response header includes a Location field AND ColdFusion receives a 300-series (redirection) status code, specifies whether to redirect execution to the URL specified in the field:

  • yes: redirects execution to the specified page.
  • no: stops execution and returns the response information in the cfhttp variable, or throws an error if the throwOnError attribute is True.

The cfhttp.responseHeader.Location variable contains the redirection path. ColdFusion follows a maximum of four redirects on a request. If there are more, ColdFusion functions as if redirect ="no".

Note: The cflocation tag generates an HTTP 302 response with the url attribute as the Location header value.

timeout

Opt

Value, in seconds, that is the maximum time the request can take. If the timeout passes without a response, ColdFusion considers the request to have failed.

If the client specifies a timeout in the URL search parameter (for example, ?RequestTime=120) ColdFusion uses the lesser of the URL timeout and the timeout attribute value; this ensures that the request times out before, or at the same time as, the page.

If the URL does not specify a timeout, ColdFusion uses the lesser of the Administrator timeout and the timeout attribute value.

If the timeout is not set in any of these, ColdFusion waits indefinitely for the cfhttp request to process.

getAsBinary

Opt

no
  • no: if ColdFusion does not recognize the response body type as text, converts it to a ColdFusion object.
  • Auto: if ColdFusion does not recognize the response body type as text, converts it to ColdFusion Binary type data.
  • yes: always converts the response body content into ColdFusion Binary type data, even if ColdFusion recognizes the response body type as text.

ColdFusion recognizes the response body as text if:

  • the header does not specify a content type.
  • the content type starts with "text".
  • the content type starts with "message".
  • the content type is "application/octet-stream".

If ColdFusion does not recognize the body as text and converts it to an object, but the body consists of text, the cfoutput tag can display it. The cfoutput tag cannot display Binary type data. (To convert binary data to text, use the ToString function.)

The following attribute is used with the PUT method to determine how to send data specified with httpparam type="formField":

Attribute

Req/Opt

Default

Description

multipart

Optional

no

(Sends as multipart only if request includes File type data.)

Tells ColdFusion to send all data specified by cfhttpparam type="formField" tags as multipart form data, with a Content-Type of multipart/form-data. By default, ColdFusion sends cfhttp requests that contain only formField data with a Content Type of application/x-www-form-urlencoded. (If the request also includes File type data, ColdFusion uses the multipart/form-data content type for all parts.)

If yes, ColdFusion also sends the request’s charset in each Content-Type description. All form field data must be encoded in this character encoding, and ColdFusion does not URLEncode the data. (The field name must be in ISO-88591-1 or ASCII.) Some http parsers, including the one used by previous versions of ColdFusion, ignore the multipart form field character encoding description.

The following attribute allows you to specify the name of the variable in which you would like the results of the operation returned. The name you specify replaces cfhttp as the prefix by which you access the returned variables. For example, if you set the result attribute to myResult, you would access FileContent as #myResult.FileContent#.

The result attribute allows functions or CFCs that are called from multiple pages at the same time to avoid overwriting the results of one call with another. For information about the variables returned by a cfhttp get operation, see Variables returned by a cfhttp get operation in the Usage section.

Attribute | Req/Opt | Default | Description
result | Optional |  | Specifies the name of the variable in which you want the result returned.

The following attributes tell ColdFusion to put the HTTP response body in a file. You can put the response body in a file for GET, POST, PUT, DELETE, OPTIONS, and TRACE methods, but it is generally not useful with the DELETE or OPTIONS method.

Attribute | Req/Opt | Default | Description
path | Required if file is specified. |  | Tells ColdFusion to save the HTTP response body in a file. Contains the absolute path to the directory in which to store the file.
file | Required if path is specified and not a GET method | See Description | Name of the file in which to store the response body. For a GET operation, the default is the file requested in the URL, if there is one. For example, if the URL in a GET method is http:www.myco.com/test.htm, the default file is test.htm. Do not specify the path to the directory in this attribute; use the path attribute.

The following attributes tell ColdFusion to convert the HTTP response body into a ColdFusion query object. They can be used with the GET and POST methods only.

Attribute

Req/Opt

Default

Description

name

Opt

Tells ColdFusion to create a query object with the given name from the returned HTTP response body.

columns

Opt

First row of response contains column names.

The column names for the query, separated by commas, with no spaces. Column names must start with a letter. The remaining characters can be letters, numbers, or underscore characters (_).

If there are no column name headers in the response, specify this attribute to identify the column names.

If you specify this attribute, and the firstrowasHeader attribute is True (the default), the column names specified by this attribute replace the first line of the response. You can use this behavior to replace the column names retrieved by the request with your own names.

If a duplicate column heading is encountered in either this attribute or in the column names from the response, ColdFusion appends an underscore to the name to make it unique.

If the number of columns specified by this attribute does not equal the number of columns in the HTTP response body, ColdFusion generates an error.

firstrowas
headers

Opt

yes

Determines how ColdFusion processes the first row of the query record set:

  • yes: processes the first row as column heads. If you specify a columns attribute, ColdFusion ignores the first row of the file.
  • no: processes the first row as data. If you do not specify a columns attribute, ColdFusion generates column names by appending numbers to the word "column"; for example, "column_1".

delimiter

Opt

, [comma]

A character that separates query columns. The response body must use this character to separate the query columns.

textQualifier

Opt

" [double-quotation mark]

A character that, optionally, specifies the start and end of a text column. This character must surround any text fields in the response body that contain the delimiter character as part of the field value.

To include this character in column text, escape it by using two characters in place of one. For example, if the qualifier is a double-quotation mark, escape it as "".

Usage

The cfhttp tag is a general-purpose tool for creating HTTP requests and handling the returned results. It enables you to generate most standard HTTP request types. You use embedded cfhttpparam tags to specify request headers and body content.

When ColdFusion receives a response to a cfhttp request, it can put the response body (if any) in a file or the cfhttp.FileContent string variable. If the body text is structured as a result set, ColdFusion can put the body text in query object. You can also access the values of all returned headers and specify how to handle error status and redirections, and specify a timeout to prevent requests from hanging.

The HTTP protocol is the backbone of the World Wide Web and is used for every web transaction. Because the cfhttp tag can generate most types of requests, it provides significant flexibility. Possible uses include:

  • Interacting with dynamic web sites and services that are not available as web services. (Use the the cfinvoke tag to access SOAP web services.)
  • Getting the contents of an HTML page or other file such as an image on a web server for use in your CFML page or storage in a file.
  • Sending a secure request to a server by specifying the https protocol in the url attribute.
  • Using the POST method to send a multipart/form-data style post to any URL that can handle such data and return results, including CGI executables or even other ColdFusion pages.
  • Using the PUT method to upload files to a server that does not accept FTP requests.

This tag can, and for PUT and POST requests must, have a body that contains cfhttpparam tags. If this tag has cfhttpparam tags, it must have a </cfhttp> end tag.

To use HTTPS with the cfhttp tag, you might need to manually import the certificate for each web server into the keystore for the JRE that ColdFusion uses. This procedure should not be necessary if the certificate is signed (issued) by an authority that the JSSE (Java Secure Sockets Extension) recognizes (for example, Verisign); that is, if the signing authority is in the cacerts already. However, you might need to use the procedure if you are issuing SSL (secure sockets layer) certificates yourself.

To manually import a certificate:

  1. Go to a page on the SSL server in question.
  2. Double-click the lock icon.
  3. Click the Details tab.
  4. Click Copy To File.
  5. Select the base64 option and save the file.
  6. Copy the CER file into C:\CFusionMX7\runtime\jre\lib\security (or whichever JRE ColdFusion is using).
  7. Run the following command in the same directory (keytool.exe is located in C:\CFusionMX7\runtime\jre\bin):
    keytool -import -keystore cacerts -alias giveUniqueName -file filename.cer

Variables returned by a cfhttp get operation

The cfhttp tag returns the following variables. If you set the result attribute, the name you assign replaces cfhttp as the prefix. For additional information, see the result attribute.

Name

Description

cfhttp.charSet

Response character character set (character encoding) specified by the response Content-Type header.

cfhttp.errorDetail

If the connection to the HTTP server fails, contains details about the failure. For instance: "Unknown host: my.co.com"; otherwise, the empty string. Macromedia recommends that you check this variable for an error condition before checking other variables.

cfhttp.fileContent

Response body; for example, the contents of a html page retrieved by a GET operation. Empty if you save the response in a file.

cfhttp.header

Raw response header containing all header information in a single string. Contains the same information as the cfhttp.responseHeader variable.

cfhttp.mimeType

MIME type specified by the response Content-Type header; for example, text/html.

cfhttp.responseHeader

The response headers formatted into a structure. Each element key is the header name, such as Content-Type or Status_Code. If there is more than one instance of a header type, the type values are put in an array.

One common technique is to dynamically access the cfhttp.responseHeader structure as a dynamic array; for example, #cfhttp.resonseHeader[fieldVariable]#.

cfhttp.statusCode

The HTTP status_code header value followed by the HTTP Explanation header value; for example, "200 OK".

cfhttp.text

Boolean; True if the response body content type is text. ColdFusion recognizes the response body as text if:

  • the header does not specify a content type.
  • the content type starts with "text".
  • the content type starts with "message".
  • the content type is "application/octet-stream".

Building a query from a delimited text file

The cfhttp tag can create a ColdFusion query object form the response body. To do so, the response body must consist of lines of text, with each line having fields that are delimited by a character that identifies the column breaks. The default delimiter is a comma (,). The response data can also use a text qualifier; the default is a double-quotation mark ("). If you surround a string field in the text qualifier, the field can contain the delimiter character. To include the text qualifier in field text, escape it by using a double character. The following line shows a two-line request body that is converted into a query. It has three comma-delimited fields:

Field1,Field2,Field3
"A comma, in text","A quote: ""Oh My!""",Plain text

Run the following code to show how ColdFusion treats this data:

<cfhttp method="Get"
    url="127.0.0.1:8500/tests/escapetest.txt"
    name="onerow">
<cfdump var="#onerow#"><br>

Column names can be specified in three ways:

  • By default, ColdFusion uses the first row of the response as the column names.
  • If you specify a comma-delimited columns attribute, ColdFusion uses the names specified in the attribute as the column names. Set firstRowAsHeaders="no" if the first row of the response contains data. Otherwise, ColdFusion ignores the first row.
  • If you do not specify a columns attribute and set firstrowasheaders="no", ColdFusion generates column names of the form Column_1, Column2, etc.

The cfhttp tag checks to ensure that column names in the data returned by the tag start with a letter and contain only letters, numbers, and underscore characters (_).

ColdFusion checks for invalid column names. Column names must start with a letter. The remaining characters can be letters, numbers, or underscores (_). If a column name is not valid, ColdFusion generates an error.

Notes

  • For the ColdFusion MX Administrator timeout and the URL timeout to take effect, you must enable the timeout in the ColdFusion MX Administrator, Server Settings page. For more information, see Configuring and Administering ColdFusion MX.
  • The cfhttp tag supports Basic Authentication for all operations.
  • The cfhttp tag uses SSL to negotiate secure transactions.
  • If you put the HTTP response body in a file, ColdFusion does not put it in the CFHTTP.FileContent variable or generate a query object. If you do not put the response body in a file, ColdFusion puts it in the CFHTTP.FileContent variable; if you specify a name attribute ColdFusion generates a query object.
  • The cfhttp tag does not support NTLM or Digest Authentication.

Example

<!--- This example displays the information provided by the Macromedia
Designer & Developer Center XML feed,
http://www.macromedia.com/desdev/resources/macromedia_resources.xml
See http://www.macromedia.com/desdev/articles/xml_resource_feed.html
for more information on this feed. --->

<!--- Set the URL address. --->
<cfset urlAddress="http://www.macromedia.com/desdev/resources/macromedia_resources.xml">

<!--- Use the CFHTTP tag to get the file content represented by urladdress.
        Note that />, not an end tag, terminates this tag. --->
<cfhttp url="#urladdress#" method="GET" resolveurl="Yes" throwOnError="Yes"/>

<!--- Parse the XML and output a list of resources. --->
<cfset xmlDoc = XmlParse(CFHTTP.FileContent)>
<!--- Get the array of resource elements, the xmlChildren of the xmlroot. --->
<cfset resources=xmlDoc.xmlroot.xmlChildren>
<cfset numresources=ArrayLen(resources)>

<cfloop index="i" from="1" to="#numresources#">
    <cfset item=resources[i]>
    <cfoutput>
        <strong><a href=#item.url.xmltext#>#item.title.xmltext#</strong></a><br>
        <strong>Author</strong>&nbsp;&nbsp;#item.author.xmltext#<br>
        <strong>Applies to these products</strong><br>
        <cfloop index="i" from="4" to="#arraylen(item.xmlChildren)#">
            #item.xmlChildren[i].xmlAttributes.Name#<br>
        </cfloop>
        <br>
    </cfoutput>
</cfloop>


cfhttpparam

Description

Allowed inside cfhttp tag bodies only. Required for cfhttp POST operations. Optional for all others. Specifies parameters to build an HTTP request.

Category

Internet Protocol tags

Syntax

<cfhttpparam
    type = "transaction type"
    name = "data name"
    value = "data value"
    file = "filename"
    encoded = "yes" or "no"
    mimeType = "MIME type designator">

See also

cfhttp , GetHttpRequestData , cfftp , cfldap , cfmail , cfmailparam , cfpop

History

ColdFusion MX 6.1:

  • Added the header and body types.
  • Added the encoded and mimeType attributes.
  • Changed HTTP method behavior: all HTTP methods can have httpparam tags.
  • Changed the name attribute requirements: it is not required for all types.

Attributes

Attribute

Req/Opt

Default

Description

type

Required

Information type:

  • header: specifies an HTTP header. ColdFusion does not URL encode the header.
  • CGI: specifies an HTTP header. ColdFusion URL encodes the header by default.
  • body: specifies the body of the HTTP request. ColdFusion does not automatically set a content-type header or URL encode the body contents. To specify the content-type, use a separate cfhttp tag with type=header.
  • XML: identifies the request as having a content-type of text/xml. Specifies that the value attribute contains the body of the HTTP request. Used to send XML to the destination URL. ColdFusion does not URL encode the XML data.
  • file: tells ColdFusion to send the contents of the specified file. ColdFusion does not URL encode the file contents.
  • URL: specifies a URL query string name-value pair to append to the cfhttp url attribute. ColdFusion URL encodes the query string.
  • formField: specifies a form field to send. ColdFusion URL encodes the Form field by default.
  • cookie: specifies a cookie to send as an HTTP header. ColdFusion URL encodes the cookie.

name

Required. Optional (and ignored) for Body and XML types

Variable name for data that is passed. Ignored for Body and XML types. For File type, specifies the filename to send in the request.

value

Required. Optional (and ignored) for File type

Value of the data that is sent. Ignored for File type. The value must contain string data or data that ColdFusion can convert to a string for all type attributes except Body. Body types can have string or binary values.

file

Required only if type="File"

Applies to File type; ignored for all other types. The absolute path to the file that is sent in the request body.

encoded

Optional

yes

Applies to FormField and CGI types; ignored for all other types. Specifies whether to URL encode the form field or header.

mimeType

Optional

Applies to File type; invalid for all other types. Specifies the MIME media type of the file contents. The content type can include an identifier for the character encoding of the file; for example, text/html; charset=ISO-8859-1 indicates that the file is HTML text in the ISO Latin-1 character encoding.

Usage

Specifies header or body data to send in the HTTP request. The type attribute identifies the information that the parameter specifies. A cfhttp tag can have multiple cfhttpparam tags, subject to the following limitations:

  • An XML type attribute cannot be used with additional XML type attributes, or with body, file, or formField type attributes.
  • A body type attribute cannot be used with additional body type attributes, or with XML, file, or formField type attributes.
  • The XML and body type attributes cannot be used with the cfhttp tag TRACE method.
  • The file type attribute is only meaningful with the cfhttp tag POST and PUT methods.
  • The formField type attribute is only meaningful with the cfhttp tag POST and GET methods.

If you send an HTTP request to a ColdFusion page, all HTTP headers, not just those sent using the CGI type, are available as CGI scope variables, However, any custom variables (such as "myVar") do not appear in a dump of the CGI scope.

When you send a file using the type="file" attribute, the file content is sent in the body of a multipart/form-data request. If you send the file to a ColdFusion page, the Form scope of the receiving page contains an entry with the name you specified in the cfhttpparam tag name attribute as the key. The value of this variable is the path to a temporary file containing the file that you sent. If you also send Form field data, the location of the filename in the form.fieldnames key list depends on the position of the cfhttpparam tag with the file relative to the cfhttp tags with the form data.

URL-encoding preserves special characters (such as the ampersand) when they are passed to the server. For more information, see the function URLEncodedFormat.

To send arbitrary data in a "raw" HTTP message, use a cfhttpparam tag with a type="body" attribute to specify the body content and use cfhttpparam tags with a type="header" attributes to specify the headers.

Example

<!--- This example consists of two CFML pages.
        The first page posts to the second. --->

<!--- The first, posting page.
        This page posts variables to another page and displays the body
        of the response from the second page.
        Change the URL and port as necessary for your environment. --->

<cfhttp
        method="post"
        url="http://127.0.0.1/tests/http/cfhttpparamexample.cfm"
        port="8500"
        throwonerror="Yes">
    <cfhttpparam name="form_test" type="FormField" value="This is a form variable">
    <cfhttpparam name="url_test" type="URL" value="This is a URL variable">
    <cfhttpparam name="cgi_test" type="CGI" value="This is a CGI variable">
    <cfhttpparam name="cookie_test" type="Cookie" value="This is a cookie">
</cfhttp>

<!--- Output the results returned by the posted-to page. --->
<cfoutput>
    #cfhttp.fileContent#
</cfoutput>

<!--- This is the cfhttpparamexample.cfm page that receives and processes the Post request. Its response body is the generated HTML output. --->

<h3>Output the passed variables</h3>
<cfoutput>
    Form variable: #form.form_test#
    <br>URL variable: #URL.url_test#
    <br>Cookie variable: #Cookie.cookie_test#
    <br>CGI variable: #CGI.cgi_test#<br>
    <br>Note that the CGI variable is URL encoded.
</cfoutput>


cfif

Description

Creates simple and compound conditional statements in CFML. Tests an expression, variable, function return value, or string. Used, optionally, with the cfelse and cfelseif tags.

Category

Flow-control tags

Syntax

<cfif expression>
    HTML and CFML tags
<cfelseif expression>
    HTML and CFML tags
<cfelse>
    HTML and CFML tags
</cfif>

See also

cfelse, cfelseif, cfabort, cfbreak, cfexecute, cfexit, cflocation, cfloop, cfswitch, cfthrow, cftry

Usage

If the value of the expression in the cfif tag is True, ColdFusion processes all the code that follows, up to any cfelseif or cfelse tag, and then skips to the cfif end tag. Otherwise, ColdFusion does not process the code that immediately follows the cfif tag, and continues processing at any cfelseif or cfelse tag, or with the code that follows the cfif end tag.

When testing the return value of a function that returns a Boolean, you do not have to define the True condition explicitly. This example uses the IsArray function:

<cfif IsArray(myarray)>

If successful, IsArray evaluates to yes, the string equivalent of the Boolean True. This is preferred over explicitly defining the True condition this way:

<cfif IsArray(myarray) IS True>

This tag requires an end tag.

Example

In this example, variables are shown within number signs. This is not required.

<!--- This example shows the interaction of cfif, cfelse, and cfelseif. --->
<!----- First, perform a query to get some data. ----->
<cfquery name="getCenters" datasource="cfdocexamples">
    SELECT Center_ID, Name, Address1, Address2, City, State, Country,
        PostalCode, Phone, Contact
    FROM Centers
    ORDER by City, State, Name
</cfquery>
<p>CFIF gives us the ability to perform conditional logic based on a condition
or set of conditions.
<p>For example, we can output the list of Centers from the snippets datasource
by group and only display them <b>IF</b> City = San Diego.
<hr>
<!---- Use CFIF to test a condition when outputting a query. ----->
<p>The following centers are in San Diego:
<cfoutput query="getCenters">
        <cfif Trim(City) is "San Diego">
            <br><b>Name/Address:</b>#Name#, #Address1#, #City#, #State#
            <br><b>Contact:</b> #Contact#
            <br>
        </cfif>
</cfoutput>
<hr>
<p>If we would like more than one condition to be the case, we can ask for
a list of the centers in San Diego <b>OR</b> Santa Ana. If the center
does not follow this condition, we can use CFELSE to show only
the names and cities of the other centers.
<p>Notice how a nested CFIF is used to specify the location of
the featured site (Santa Ana or San Diego).
<!----- Use CFIF to specify a conditional choice for multiple options;
also note the nested CFIF. --->
<p>Complete information is shown for centers in San Diego or Santa Ana.
All other centers are listed in italics:
<cfoutput query="getCenters">
    <cfif Trim(City) is "San Diego" OR Trim(City) is "Santa Ana">
        <h4>Featured Center in
            <cfif Trim(City) is "San Diego">
                San Diego
            <cfelse>
                Santa Ana
            </cfif>
            </h4> <b>Name/Address:</b>#Name#, #Address1#, #City#, #State#
            <br><b>Contact:</b> #Contact#<br>
    <cfelse>
        <br><i>#Name#, #City#</i>
    </cfif>
</cfoutput>
<hr>
<p>Finally, we can use CFELSEIF to cycle through a number of conditions and
produce varying output. Note that you can use CFCASE and CFSWITCH for a more
elegant representation of this behavior.
<!--- Use CFIF in conjunction with CFELSEIF to specify more than one
    branch in a conditional situation. --->
<cfoutput query="getCenters">
    <cfif Trim(City) is "San Diego" OR Trim(City) is "Santa Ana">
        <br><i>#Name#, #City#</i> (this one is in
                <cfif Trim(City) is "San Diego">San Diego
                <cfelse>Santa Ana
                </cfif>)
            <cfelseif Trim(City) is "San Francisco">
                <br><i>#Name#, #City#</i> (this one is in San Francisco)
            <cfelseif Trim(City) is "Suisun">
                <br><i>#Name#, #City#</i> (this one is in Suisun)
            <cfelse> <br><i>#Name#</i>
                <b>Not in a city we track</b>
            </cfif>
</cfoutput>


cfimpersonate

Description

This tag is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide.

History

ColdFusion MX: This tag is obsolete. It does not work in ColdFusion MX and later releases.


cfimport

Description

You can use the cfimport tag to import either of the following:

  • All ColdFusion pages in a directory, as a tag custom tag library.
  • A Java Server Page (JSP) tag library. A JSP tag library is a packaged set of tag handlers that conform to the JSP 1.1 tag extension API.

Category

Application framework tags

Syntax

<cfimport
    taglib = "taglib-location"
    prefix = "custom">

See also

cfapplication

History

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

taglib

Required

Tag library URI. The path must be relative to the web root (and start with /), the current page location, or a directory specified in the Administrator ColdFusion mappings page.

  • A directory in which custom ColdFusion tags are stored. In this case, all the cfm pages in this directory are treated as custom tags in a tag library.
  • A path to a JAR in a web-application; for example, "/WEB-INF/lib/sometags.jar"
  • A path to a tag library descriptor; for example,
    "/sometags.tld"

Note: You must put JSP custom tag libraries in the
/WEB-IN/lib directory. This limitation does not apply to ColdFusion pages.

prefix

Required

Prefix by which to access the imported custom CFML tags JSP tags.

If you import a CFML custom tag directory and specify an empty value, "", for this attribute, you can call the custom tags without using a prefix. You must specify and use a prefix for a JSP tag library.

Usage

The following example imports the tags from the directory myCustomTags:

<cfimport
    prefix="mytags"
    taglib="myCustomTags">

You can import multiple tag libraries using one prefix. If there are duplicate tags in a library, the first one takes precedence.

JSP tags have fixed attributes; however, if the tag supports runtime attribute expressions, most tag libraries support the use of the syntax #expressions#.

To reference a JSP tag in a CFML page, use the syntax <prefix:tagname>. Set the prefix value in the prefix attribute.

To use JSP custom tags in a ColdFusion page:

  1. Put a JSP tag library JAR file (for example, myjsptags.jar) into the ColdFusion server directory wwwroot/WEB-INF/lib. If the tag library has a separate TLD file, put it in the same directory as the JAR file.
  2. At the top of a CFML page, insert code such as the following:
    <cfimport
    prefix="mytags"
    taglib="/WEB-INF/lib/myjsptags.jar">

To reference a JSP tag from a JAR file, use the following syntax:

<cfoutput>
    <mytags:helloTag message="#mymessage#" />
<cfoutput>

The cfimport tag must be on the page that uses the imported tags. For example, if you use a cfimport tag on a page that you include with the cfinclude call, you cannot use the imported tags on the page that has the cfinclude tag. Similarly, if you have a cfimport tag on your Application.cfm page, the imported tags are available on the Application.cfm page only, not on the other pages in the application. ColdFusion does not throw an error in these situations, but the imported tags do not run.

You cannot use the cfimport tag to suppress output from a tag library.

For more information, see the Java Server Page 1.1 specification.

Example

<h3>cfimport example</h3>
<p>This example uses the random JSP tag library that is available from the
Jakarta Taglibs project, at http://jakarta.apache.org/taglibs/

<cfimport taglib="/WEB-INF/lib/taglibs-random.jar" prefix="randomnum">

<randomnum:number id="randPass" range="000000-999999" algorithm="SHA1PRNG" provider="SUN" />
<cfset myPassword = randPass.random>
<cfoutput>
  Your password is #myPassword#<br>
</cfoutput>


cfinclude

Description

Embeds references to ColdFusion pages in CFML. You can embed cfinclude tags recursively. For another way to encapsulate CFML, see cfmodule. (A ColdFusion page was formerly sometimes called a ColdFusion template or a template.)

Category

Flow-control tags, Page processing tags

Syntax

<cfinclude
    template = "template_name">

See also

cfcache , cfflush , cfheader , cfhtmlhead , cfsetting , cfsilent

History

ColdFusion MX: Changed error behavior: if you use this tag to include a CFML page whose length is zero bytes, you do not get an error.

Attributes

Attribute | Req/Opt | Default | Description
template | Required |  | A logical path to a ColdFusion page.

Usage

ColdFusion searches for included files in the following locations:

  1. In the directory of the current page or a directory relative to the current page
  2. In directories mapped in the ColdFusion MX Administrator

You cannot specify an absolute URL or file system path for the file to include. You can only use paths relative to the directory of the including page or a directory that is registered in the ColdFusion MX Administrator Mappings. The following cfinclude statements will work, assuming that the myinclude.cfm file exists in the specified directory:

<cfinclude template="myinclude.cfm">
<cfinclude template="../myinclude.cfm">
<cfinclude template="/CFIDE/debug/myinclude.cfm">

But these will not work:

<cfinclude template="C:\CFusionMX7\wwwroot\doccomments\myinclude.cfm">
<cfinclude template="http://localhost:8500/doccomments/myinclude.cfm">

The included file must be a syntactically correct and complete CFML page. For example, to output data from within the included page, you must have a cfoutput tag, including the end tag, on the included page, not the referring page. Similarly, you cannot span a cfif tag across the referring page and the included page; it must be complete within the included page.

You can specify a variable for the template attribute, as the following example shows:

<cfset templatetouse="../header/header.cfm">
<cfinclude template="#templatetouse#">

Example

<!--- This example shows the use of cfinclude to paste CFML
or HTML code into another page dynamically. --->

<h4>This example includes the dochome.htm page from the CFDOCS directory.
The images do not display, because they are located in
a separate directory. However, the page appears fully rendered
within the contents of this page.</h4>
<cfinclude template = "../cfdocs/dochome.htm">


cfindex

Description

Populates a Verity collection with metadata and creates indexes for searching it. Verity is a search engine that you can integrate in a ColdFusion application to search physical files of various types or a database query. Indexing database columns that result from a query lets users search the query data much faster than they could if you used multiple SQL queries to return the same data.

You must define a Verity collection using the ColdFusion MX Administrator or the cfcollection tag before creating indexes for the collection.

You also can index a Verity collection using the ColdFusion MX Administrator or by using a native Verity indexing tool, such as Vspider or MKVDK. These options, however, limit you to indexing a collection of files in a directory path.

For more information on creating, indexing, and searching a Verity collection, see Chapter 24, "Building a Search Interface" in ColdFusion MX Developer’s Guide.

Category

Extensibility tags

Syntax

<cfindex
    collection = "collection_name"
    action = "action"
    type = "type"
    title = "title"
    key = "ID"
    body = "body"
    custom1 = "custom_value"
    custom2 = "custom_value"
custom3 = "custom_value"
custom4 = "custom_value"
    category = "category_name"
    categoryTree = "category_tree"
    URLpath = "URL"
    extensions = "file_extensions"
    query = "query_name"
    recurse = "yes" or "no"
    language = "language">
    status = "status">

See also

cfcollection , cfexecute , cfobject , cfreport , cfsearch , cfwddx

History

ColdFusion MX 7:

  • Added the status, category, and categoryTree attributes.
  • Removed reference to external collections.
  • Removed suggested cflock usage.

ColdFusion MX:

  • The action attribute value optimize is obsolete. It does not work, and might cause an error, in ColdFusion MX.
  • Changed the external attribute behavior: it is not necessary to specify the external attribute. (ColdFusion automatically detects whether a collection is internal or external.)
  • Changed Verity operations behavior: ColdFusion supports Verity operations on Acrobat PDF files.
  • Changed thrown exceptions: this tag can throw the SEARCHENGINE exception.
  • Changed acceptable collection naming: this tag accepts collection names that include spaces.
  • Changed query result behavior: the cfindex tag can index the query results from a cfsearch tag.

Attributes

Attribute

Req/Opt

Default

Description

collection

Required

Name of a collection that is registered by ColdFusion; for example, "personnel".

action

Required

  • update: updates a collection and adds key to the index.
  • delete: removes collection documents as specified by the key attribute.
  • purge: deletes all of the documents in a collection. Causes the collection to be taken offline, preventing searches.
  • refresh: deletes all of the documents in a collection, and then performs an update.

type

Optional

custom, if query attribute is specified. Otherwise, file.

  • file: applies action value to filename, including path. Expects a filename in the key attribute.
  • path: applies action to files in a directory path that pass the extensions filter. Expects a directory name in the key attribute.
  • custom: applies action to custom data; for example, to data from a query.

title

Optional

Provides a title for the document if one cannot be extracted from the document.

key

Required

(empty string)

The value specified for key depends on the type attribute:

  • If type = "file", the directory path and filename for the file,
  • If type = "path", the directory path for the location of the files.
  • If type = "custom", a unique identifier that specifies the location of the data, For a query, the name of the column that holds the primary key, for example. If not a query, an identifier such as the URL for a web page, for example.

body

Required if type = custom

  • ASCII text to index.
  • Query column names, if name is specified in query.

You can specify columns in a delimited list; for example: "emp_name, dept_name, location".

This attribute is ignored if type is file or path, and is invalid if action is delete.

custom1

Optional

Use to index discrete values in collection records, which lets you search for specific records using the Verity MATCHES operator. By contrast, values specified in the body attribute are concatenated and searched as a body of text using the specified criteria.

If type = query, a query column name. If type = custom, a data field to be indexed.

custom2

Optional

Usage is the same as for custom1.

custom3

Optional

Usage is the same as for custom1.

custom4

Optional

Usage is the same as for custom1.

category

Optional

A string value that specifies one or more search categories for which to index the data. You can define multiple categories, separated by commas, for a single index.

categoryTree

Optional

A string value that specifies a hierarchical category or category tree for searching. It is a series of categories separated by forward slashes ("/"). You can specify only one category tree.

URLpath

Optional

If type is file or path, specifies the URL path. During indexing, this pathname is prefixed to filenames and returned from a search as the url.

extensions

Optional

htm,

html,

cfm,

cfml,

dbm,

dbml

Delimited list of file extensions that ColdFusion uses to index files, if type = "Path".

"*." returns files with no extension. ".*" returns all files.

For example, the following code returns files with a listed extension or no extension:

extensions == ".htm, .html, .cfm, .cfml, "*."

query

Optional.

The name of the query against which the collection is generated.

recurse

Optional

no
  • yes: if type = "path", indexes qualified files in directories below the path specified in the key attribute.
  • no

language

Optional

English

For options, see cfcollection. Requires the appropriate Verity Locales language pack (Western Europe, Asia, Multilanguage, Eastern Europe/Middle Eastern).

status

Optional

The name of the structure into which ColdFusion MX returns status information.

Usage

The attributes settings that the cfindex tag requires depend on whether you set the query attribute. If you set the query attribute to a valid query name, it specifies that cfindex is to index the data in the query rather than indexing documents on a disk. If you do not set the query attribute, cfindex assumes it is indexing a file (type = file), a set of files in a directory path (type = path), or text that you provide in the body attribute (type = custom).

If you set the query attribute to a valid query name, the cfindex tag creates indexes as specified by the following attributes and their values:

Type | Attribute values
File | The key attribute is the name of a column in the query that contains a full filename (including path).
Path | The key attribute is the name of a column in the query that contains a directory pathname.
 | The extensions and recurse attributes, if specified, elaborate on which files are included. If the action is delete, cfindex deletes keys for the collection.
Custom | The key attribute specifies a column name that contains anything you want; for example, the primary key value in the database. It must be unique because this is the primary key in the collection. If the action is delete, the key attribute is the name of a column in the query that contains the keys to delete.
 | The body attribute is required and is a comma-delimited list of the names of the columns that contain the text data to be indexed.

If you do not set the query attribute, the cfindex tag creates indexes as specified by the following attributes and their values:

Type | Attribute values
File | The key attribute is required and is a full pathname to a file.
Path | The key attribute is required and it is a directory pathname.
 | The extensions and recurse attributes, if specified, designate which types of files are included. If the action is delete, both the keys and the document files are deleted.
Custom | The key attribute is an identifier that specifies the key. If the action is delete, the key attribute is the document key to delete.
 | The body attribute is required and is the text to be indexed.

If type is not specified but query is set, ColdFusion sets the type to the default value of custom.

If neither type nor query is set, ColdFusion sets type to the default value of file.

If type equals custom, all attributes except for key and body can specify a literal value, not only a column name. This allows you to change a field to empty in the collection.

Status attribute

The status attribute provides the following information and diagnostics about the result of a cfindex operation:

Key | Type | Description
BADKEYS | Struct | A structure of keys with diagnostic messages about the indexing of these keys. If there are no bad keys, this key does not exist.
DELETED | Number | The number of keys deleted.
MESSAGES | Array | An array of diagnostic messages, including nonfatal errors and warnings, returned from the Verity K2 Index server. If there are no messages, this key does not exist.
INSERTED | Number | The number of keys inserted into the collection.
UPDATED | Number | The number of keys updated in the collection.

Example

<!--- EXAMPLE #1 Index a file, type = "file". ---------------------------->
<!--- Example dumps content of status variable (info). ------------------->
<cfindex collection="CodeColl"
    action="refresh"
    type="file"
    key="C:\blackstone\wwwroot\vw_files\cfindex.htm"
    urlpath="http://localhost:8500/vw_files/"
    language="English"
    title="Cfindex Reference page"
    status="info">

<!--- Search for Attributes. --->
<cfsearch
    name = "mySearch"
    collection = "CodeColl"
    criteria = "Attributes"
    contextpassages = "1"
    maxrows = "100">
<cfoutput>
    key=#mySearch.key#<br />
    title=#mySearch.title#<br />
    context=#mySearch.context#<br />
    url=#mySearch.url#<br />
</cfoutput>

<cfdump var="#info#">

<!--- EXAMPLE #2 Index a path (type = "path"). ------------------------------>
<cfindex collection="CodeColl"
    action="refresh"
    type="path"
    key="C:\inetpub\wwwroot\vw_files\newspaper\sports"
    urlpath="http://localhost/vw_files/newspaper/sports"
    extensions = ".htm, .html"
    recurse="no"
    language="English"
    categoryTree="vw_files/newspaper/sports"
    category="Giants">

<!--- Search for any references to criteria. --->
<cfsearch
    name = "mySearch"
    collection = "CodeColl"
    categoryTree="vw_files/newspaper/sports"
    category="Giants"
    criteria = "Williams"
    contextpassages = "1"
    maxrows = "100">
<cfoutput>
    key=#mySearch.key#<br />
    title=#mySearch.title#<br />
    context=#mySearch.context#<br />
    url=#mySearch.url#<br />
</cfoutput>

<!---EXAMPLE #3: Index a QUERY (type = "custom") using custom1. ------------>
<!--- Retrieve data from the table. --->
<cfquery name="getCourses" datasource="cfdocexamples">
   SELECT * FROM COURSES
</cfquery>

<!--- Update the collection with the above query results. --->
<!--- key is Course_ID in the Courses table. ---->
<!--- body specifies the columns to be indexed for searching. --->
<!--- custom1 specifies the value of the Course_Number column. --->

<cfindex
   query="getCourses"
   collection="CodeColl"
   action="Update"
   type="Custom"
   key="Course_ID"
   title="Courses"
   body="Course_ID,Descript"
   custom1="Course_Number"
>
<h2>Indexing Complete</h2>
<!--- cno supplies value for searching custom1;
        could be form input instead. --->
<cfset cno = "540">
<cfsearch
    name = "mySearch"
    collection = "CodeColl"
    criteria = "CF_CUSTOM1 <MATCHES> #cno#"
    contextpassages = "1"
    maxrows = "100">
<!--- Returns indexed values (Course_ID and Descript) for
        Course_Number 540. --->
<cfoutput>
    key=#mySearch.key#<br />
    title=#mySearch.title#<br />
    context=#mySearch.context#<br />
    url=#mySearch.url#<br />
</cfoutput>

<!--- EXAMPLE #4 Index a FILE within a QUERY (type= "file"). --------------->
<!--- Retrieve row with a column that contains a filename (Contract_File). --->
<cfquery name="getEmps" datasource="cfdocexamples">
    SELECT * FROM EMPLOYEE WHERE EMP_ID = 1
</cfquery>

<!--- Update the collection with the above query results. --->
<!--- key specifies the column that contains a complete filename. --->
<!--- file is indexed in same way as if no query involved. --->
<cfindex
    query="getEmps"
    collection="CodeColl"
    action="Update"
    type="file"
    key="Contract_File"
    title="Contract_File"
    body="Emp_ID,FirstName,LastName,Contract_File">

<h2>Indexing Complete</h2>
<cfsearch
    name = "mySearch"
    collection = "CodeColl"
    criteria = "vacation"
    contextpassages = "1"
    maxrows = "100">
<cfoutput>
    key=#mySearch.key#<br />
    title=#mySearch.title#<br />
    context=#mySearch.context#<br />
    url=#mySearch.url#<br />
</cfoutput>

<!--- EXAMPLE # 5 Index a PATH within a QUERY. ---------------------------->
<!--- Retrieve a row with a column that contains a path (Project_Docs). --->
<cfquery name="getEmps" datasource="cfdocexamples">
    SELECT * FROM EMPLOYEE WHERE Emp_ID = 15
</cfquery>

<!--- Update the collection with the above query results. --->
<!--- key specifies a column that contains a directory path. --->
<!--- path is indexed in same way as if no query involved. --->
<cfindex
    query="getEmps"
    collection="CodeColl"
    action="update"
    type="path"
    key="Project_Docs"
    title="Project_Docs"
    body="Emp_ID,FirstName,LastName,Project_Docs">

<h2>Indexing Complete</h2>

<cfsearch
    name = "getEmps"
    collection = "CodeColl"
    criteria = "cfsetting"
    contextpassages = "1"
    maxrows = "100">
<cfoutput>
    key=#getEmps.key#<br />
    title=#getEmps.title#<br />
    context=#getEmps.context#<br />
    url=#getEmps.url#<br />
</cfoutput>

<!--- EXAMPLE #6 Deletes keys in the CodeColl collection for html files --->
<!--- in the specified directory (but not in subdirectories). ------------->

<cfindex collection="CodeColl"
    action="delete"
    type="path"
    key="C:\CFusionMX7\wwwroot\vw_files\newspaper"
    urlpath="http://localhost:8500/vw_files/newspaper"
    extensions = ".htm, .html"
    recurse="no">

<!--- EXAMPLE #7 Purges all keys in the CodeColl collection --->
<!--- with recursion. ------------------------------------------------------->

<cfindex collection="CodeColl"
    action="purge"
    type="path"
    key="C:\CFusionMX7\wwwroot\vw_files\newspaper">


cfinput

Description

Used within the cfform tag, to place input controls that support input validation on a form.

Category

Forms tags

Syntax

<cfinput
name = "name"
type = "input type"
label = "text"
style = "style specification"
required = "yes" or "no"
mask = "masking pattern"
validate = "data type"
validateAt= one or more of "onBlur", "onServer", "onSubmit"
message = "text"
range = "min_value, max_value"
maxlength = "number"
pattern = "regexp"
onValidate = "script name"
onError = "script name"
size = "integer"
value = "initial value"
bind = "bind expression"
checked
disabled = "true" or "false" or no attribute value
src = "image URL"
onKeyUp = "JavaScript or ActionScript"
onKeyDown = "JavaScript or ActionScript"
onMouseUp = "JavaScript or ActionScript"
onMouseDown = "JavaScript or ActionScript"
onChange = "JavaScript or ActionScript"
onClick = "JavaScript or ActionScript"
firstDayOfWeek = "day name"
dayNames = "days-of-the-week labels"
monthNames = "month labels"
enabled = "Yes" or "No"
visible = "Yes" or "No"
toolTip = "Tip text"
height = "number of pixels"
width = "number of pixels"
>

See also

cfapplet , cfcalendar , cfform , cfformgroup , cfformitem , cfgrid , cfselect , cfslider , cftextarea , cftree

History

ColdFusion MX 7:

  • Added support for button, file, hidden, image, reset, and submit controls.
  • Added support for generating Flash and XML controls (specified in the cfform tag).
  • Added datefield type (Flash forms only) and the supporting daynames and monthnames attributes.
  • Added bind, enabled, height, label, tooltip, visible, and width attributes for use in Flash forms.
  • Added support for onBlur and onServer validation, including the validateAt attribute.
  • Added USdate, range, boolean, email, URL, uuid, guid, maxlength, noblanks, and submitOnce validation attribute values.
  • Added support for preventing multiple submissions.
  • Added the mask attribute.
  • Deprecated the passthrough attribute. The tag now supports all HTML input tag attributes directly.

ColdFusion MX: Changed the cfform tag preserveData attribute behavior: if it is set to True, ColdFusion checks radio and check box values only if their value matches the posted value for the control. (In earlier releases, if the posted value did not match any of the cfinput check boxes or radio buttons for the control, the checked attribute was used.

Attributes

The following table lists attributes that ColdFusion uses directly. The tag also supports all HTML form tag attributes that are not on this list, and passes them directly to the browser.

Note: Attributes that are not marked as supported in XML are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML.

Attribute

Req/Opt;

Formats

Default

Description

name

Required;

All

Name for form input element.

type

Optional;

All

text

The input control type to create:

  • button: push button.
  • checkbox: check box.
  • file: file selector; not supported in Flash.
  • hidden: invisible control.
  • image: clickable button with an image.
  • password: password entry control; hides input values.
  • radio: radio button.
  • reset: form reset button.
  • submit: form submission button.
  • text: text entry box.
  • datefield: Flash only; date entry field with an expanding calendar for selecting dates.

label

Optional;

Flash and XML

Label to put next to the control on a Flash form. Not used for button, hidden, image, reset, or submit types.

style

Optional;

All

In HTML or XML format, ColdFusion passes the style attribute to the browser or XML.

In Flash format, must be a style specification in CSS format. For detailed information on specifying Flash styles, see Creating Forms in Macromedia Flash in ColdFusion MX Developer’s Guide.

In XML format, ColdFusion passes the style attribute to the XML.

required

Optional;

All

no
  • yes: the field must contain data.
  • no: allows an empty field.

mask

Optional;

Flash and HTML

A mask pattern that controls the character pattern that users can enter, or that the form sends to ColdFusion.

HTML and Flash: For tags with type="text". Mask characters and the corresponding valid input characters are:

  • A = [A-Za-z]
  • X = [A-Za-z0-9]
  • 9 = [0-9]
  • ? = Any character
  • All other characters = insert the literal character

Flash only: For tags with type="datefield". ColdFusion uses the mask pattern to format the selected date. Mask characters are:

  • D = day; can use 0-2 mask characters.
  • M = month; can use 0-4 mask characters.
  • Y = year; can use 0, 2, or 4 characters.
  • E = day in week; can use 0-4 characters.

For more information, see Masking input data in Usage.

validate

Optional;

All

The type or types of validation to do. Available validation types and algorithms depend on the format. For details, see Usage.

validateAt

Optional;

All

onSubmit

How to do the validation; one or more of the following:

  • onSubmit
  • onServer
  • onBlur

onBlur and onSubmit are identical in Flash forms. For multiple values, use a comma-delimited list.

For details, see Usage.

message

Optional;

All

Message text to display if validation fails.

range

Optional;

All

Minimum and maximum allowed numeric values. ColdFusion uses this attribute only if you specify range in the validate attribute.

If you specify a single number or a single number followed by a comma, it is treated as a minimum, with no maximum. If you specify a comma followed by a number, the maximum is set to the specified number, with no minimum.

maxLength

Optional;

All

Maximum length of text entered, if type = "Text" or "password". For complete length validation, specify maxLength validation in a validate attribute; otherwise, this attribute prevents users from typing beyond the specified length, but does not prevent them from pasting in a longer value.

pattern

Required if validate = "regex";

HTML and XML format only

JavaScript regular expression pattern to validate input. ColdFusion uses this attribute only if you specify regex in the validate attribute.

Omit leading and trailing slashes. For examples and syntax, see Building Dynamic Forms with cfform Tags in ColdFusion MX Developer’s Guide.

onValidate

Optional;

HTML and XML only

Custom JavaScript function to validate user input. The form object, input object, and input object values are passed to the routine, which should return True if validation succeeds, and False otherwise. If used, the validate attribute is ignored.

onError

Optional;

HTML and XML only

Custom JavaScript function to execute if validation fails.

size

Optional;

All

Size of input control. Ignored, if type = "radio" or "checkbox". If specified in a Flash form, ColdFusion sets the control width pixel value to 10 times the specified size and ignores the width attribute

value

depends on type setting;

All

HTML: corresponds to the HTML value attribute. Its use depends on control type.

Flash: optional; specifies text for button type inputs: button, submit, and image.

bind

Optional; Flash only

A Flash bind expression that populates the field with information from other form fields. For details, see Usage.

checked

Optional;

All

False

Selects a radio or checkbox control:

  • True
  • False

disabled

Optional;

All

not disabled

Disables user input, making the control read-only. To disable input, specify disabled without an attribute or disabled="Yes" (or any ColdFusion positive Boolean value, such as True). To enable input, omit the attribute or specify disabled="No" (or any ColdFusion negative Boolean value, such as False).

src

Optional;

Flash and HTML

Applies to Flash button, reset, submit, and image types, and the HTML image type. URL of an image to use on the button. Flash does not support GIF images.

onKeyUp

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user releases a keyboard key in the control.

onKeyDown

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) ActionScript to run when the user presses a keyboard key in the control.

onMouseUp

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user presses a mouse button in the control.

onMouseDown

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user releases a mouse button in the control.

onChange

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the control changes due to user action. In Flash, applies to datefield, password, and text types only.

onClick

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user clicks the control. In Flash, applies to button, checkbox, image, radio, reset, and submit types only.

dayNames

Optional;

All

S, M, T, W, Th, F, S

Applies to datefield type only. A comma-delimited list that sets the names of the weekdays displayed in the calendar. Sunday is the first day; the rest of the weekday names follow in the normal order.

firstDayOfWeek

Optional;

All

0

Applies to datefield type only. Integer in the range 0-6 specifying the first day of the week in the calendar: 0 indicates Sunday; 6 indicates Saturday.

monthNames

Optional;

All

January, February, March, April, May, June, July, August, September, October, November, December

Applies to datefield type only. A comma-delimited list of the month names that are displayed at the top of the calendar.

enabled

Optional; Flash

Yes

Boolean value specifying whether the control is enabled. A disabled control appears in light gray. The inverse of the disabled attribute.

visible

Optional; Flash

Yes

Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank.

tooltip

Optional; Flash

Text to display when the mouse pointer hovers over the control.

height

Optional; see Description

Applies to most Flash types, HTML image type on some browsers. The height of the control, in pixels. The displayed height might be less than the specified size.

width

Optional; see Description

Applies to most Flash types, HTML image type on some browsers. The width of the control, in pixels. For Flash forms, ColdFusion ignores this attribute if you also specify a size attribute value.
<em>

Note: Attributes that are marked as not supported in XML are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML.

Usage

For this tag to work properly. the browser must be JavaScript-enabled.

If the cfform preserveData attribute is true and the form posts back to the same page, the posted value of the cfinput control is used, instead of its Value or Checked attribute.

You can use the keyboard to access and select dates from a datefield Flash input: press Tab to go to the field and press the Spacebar to open the menu. Use the Up, Down, Left, and Right Arrow keys to change the selected date. Use the Home and End keys to reach the first and last enabled date in a month, respectively. Use the Page Up and Page Down keys to reach the previous and next month, respectively.

Note: To clear a datefield entry, select the field to open the menu, and click the selected date.

For more information, see cfform. For information on using JavaScript regular expressions with this tag, see Building Dynamic Forms with cfform Tags in ColdFusion MX Developer’s Guide.

Validation

The following sections describe how to do validation in cfinput tags.

Validation methods ColdFusion provides four methods of validation of cfinput text and password fields.

You can specify one or a combination of the following in the validateAt attribute:

  • onSubmit The form page on the browser includes JavaScript functions that perform validation before the form is submitted to the server. In Flash format forms, this option is identical to onBlur.
  • onBlur In HTML format the form page on the browser includes JavaScript functions that perform validation when the field loses the focus. In Flash format, the attribute is equivalent to onSubmit. OnBlur validation uses the same algorithms as onSubmit validation. OnBlur validation was added in ColdFusion MX 7.
  • onServer ColdFusion performs the validation on the server. Some onServer algorithms vary from the onSubmit algorithms. OnServer Date and Time validation allow more patterns than onSubmit validation. OnServer validation was added in ColdFusion MX 7, and automatically generates hidden fields to support the validation.

You can also omit a validate attribute and specify the type of validation for the field in a separate hidden form field. This form of validation is equivalent to onServer validation, but it allows you to specify separate messages for each validation that you do on the field. It is backward compatible with previous ColdFusion releases. For more information on hidden form field validation, see cfform and Validating form data using hidden fields in Validating form data using hidden fields in ColdFusion MX Developer’s Guide.

validation types You can use the following values in the validate attribute to specify input validation for all validation methods. Most attributes apply only to password or text fields. You can specify multiple validation types in a comma-delimited list, but only some combinations are meaningful.

Type | Description
date | If validateAt="onServer", allows any date format that returns True in the IsDate function; otherwise, same as USdate.
USdate | A US date of the format mm/dd/yy mm-dd-yy or mm.dd.yy, with 1-2 digit days and months, 1-4 digit years.
eurodate | A date of the format dd/mm/yy, with 1-2 digit days and months, 1-4 digit years.. The format can use /, -, or . characters as delimiters.
time | Time format hh:mm:ss
float or numeric | A number; allows integers.
integer | An integer.
range | A numeric range.
boolean | A value that can be converted to a Boolean value: Yes, No, True, False, or a number.
telephone | Standard U.S. telephone formats. Allows an initial 1 long-distance designator and up to 5-digit extensions, optionally starting with x.
zipcode | U.S. 5- or 9-digit ZIP code format #####-####. The separator can be a hyphen (-) or a space.
creditcard | Strips blanks and dashes; verifies number using mod10 algorithm. Number must have 13-16 digits.
ssn or social_security_number | US. Social Security number format, ###-##-####. The separator can be a hyphen (-) or a space.
email | A valid e-mail address of the form name@server.domain. ColdFusion validates the format only; it does not check that entry is a valid active e-mail address.
URL | A valid URL pattern; supports http, https, ftp file, mailto, and news URLs.
guid | A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number.
uuid | A universally unique identifier (UUID) that follows the ColdFusion format, xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx, where x is a hexadecimal number.
maxlength | Limits the input to a maximum number of characters.
noblanks | Does not allow fields that consist only of blanks.
regex or regular_expression | Matches input against the pattern attribute. Valid in HTML and XML format only; ignored in Flash format.
SubmitOnce | Used only with submit and image types; prevents the user from submitting the same form multiple times before until the next page loads (for example, submitting an order a second time before getting the first order confirmation). Valid in HTML and XML format only; ignored in Flash format.

Validation differences The preceding table describes the general validation behavior. The underlying validation code must differ depending on the validation method and the form type. As a result, the algorithms used vary in some instances, including the following:

  • The validation algorithms used for date/time values varies between onSubmit/OnBlur and OnServer.
  • The algorithms used for onSubmit/OnBlur validation in Flash vary from those used for HTML/XML format, and generally follow simpler rules.

The table describes the onSubmit/OnBlur behavior in HTML format. For detailed information on the OnServer validation algorithms, see Data validation types in Data validation types in ColdFusion MX Developer’s Guide.

For more information on validation, including discussions of the advantages and disadvantages of different validation types, see Validating Data in ColdFusion MX Developer’s Guide.

Masking input data

The mask attribute controls the format of data that can be entered into a field. You can combine masking and validation on a field.

  • In HTML and Flash form format the mask can control the format of data entered into a text field.
  • In Flash format, the mask can also control the format of the date chosen using the datefield input control.

In text fields, ColdFusion automatically inserts any literal mask characters, such as - characters in telephone numbers. Users type only the variable part of the field.

The following pattern enforces entry of a part number of the format EB-1234-c1-098765, where the user starts the entry by typing the first numeric character, such as 3. ColdFusion fills in the preceding EA prefix and all - characters. The user must enters four numbers, followed by two alphanumeric characters, followed by six numbers.

<cfinput type="text" name="newPart" mask="EB-9999-XX-999999" />

Note: To force a pattern to be all-uppercase or all-lowercase, use the ColdFusion UCase or LCase functions in the action page.

For tags with type="datefield" (and cfcalendar tags), the number of pattern characters determines the format of the output, as follows:

Mask | Pattern
D | Single- or double-digit day of month, such as 1 or 28
DD | Double-digit day of month, such as 01 or 28
M | Single- or double-digit month, such as 1 or 12
MM | Double-digit month, such as 01 or 12
MMM | Abbreviated month name, such as Jan or Dec
MMMM | Full month name, such as January or December
YY | Two-character year, such as 05
YYYY | Four-character year, such as 2005
E | Single-digit day of week, such as 1 or 7
EEE | Abbreviated day of week name, such as Mon or Sun
EEEE | Full month day of week name, such as Monday or Sunday

The following pattern specifies that the Flash forms sends the date selected using a datefield input control to ColdFusion as text in the format 04/29/2004:

<cfinput name="startDate" type="datefield" label="date:" mask="mm/dd/yyyy"/>

Flash form data binding

The bind attribute lets you populate form fields using the contents of other form fields. To specify text from another field in a cftextarea bind attribute, use the following format:

{sourceTagName.text}

For example, the following line uses the values from the firstName and lastName fields to construct an email address. (The user can change or replace this value with a typed entry.)

            <cfinput type="text" name="email" label="email"
                bind="{firstName.text}.{lastName.text}@mm.com">

Example

<!--- This example shows the use of cfinput within a cfform to ensure simple
validation of text items. --->
<cfform action = "cfinput.cfm">
<!--- Phone number validation. --->
Phone Number Validation (enter a properly formatted phone number): <br>
<cfinput
    type = "Text" name = "MyPhone"
    message = "Enter telephone number, formatted xxx-xxx-xxxx (e.g. 617-761-2000)"
    validate = "telephone" required = "yes">
    <font size = -1 color = red>Required</font>
<!--- Zip code validation. --->
<p>Zip Code Validation (enter a properly formatted zip code):<br>
<cfinput
    type = "Text" name = "MyZip"
    message = "Enter zip code, formatted xxxxx or xxxxx-xxxx"
    validate = "zipcode" required = "yes">
    <font size = -1 color = red>Required</font>
<!--- Range validation. --->
<p>Range Validation (enter an integer from 1 to 5): <br>
<cfinput
    type = "Text" name = "MyRange" range = "1,5"
    message = "You must enter an integer from 1 to 5"
    validate = "integer" required = "no">
<!--- Date validation. --->
<p>Date Validation (enter a properly formatted date):<br>
<cfinput
    type = "Text" name = "MyDate"
    message = "Enter a correctly formatted date (dd/mm/yy)"
    validate = "date" required = "no">
<input
    type = "Submit" name = ""
    value = "send my information">
</cfform>


cfinsert

Description

Inserts records in data sources from data in a ColdFusion form or form Scope.

Category

Database manipulation tags

Syntax

<cfinsert
    dataSource = "ds_name"
    tableName = "tbl_name"
    tableOwner = "owner"
    tableQualifier = "tbl_qualifier"
    username = "username"
    password = "password"
    formFields = "formfield1, formfield2, ...">

See also

cfprocparam , cfprocresult , cfquery , cfqueryparam , cfstoredproc , cftransaction , cfupdate

History

ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider, and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5.

Attributes

Attribute | Req/Opt | Default | Description
dataSource | Required |  | Data source; contains table.
tableName | Required |  | Table in which to insert form fields. ORACLE drivers: must be uppercase. Sybase driver: case-sensitive. Must be the same case used when table was created
tableOwner | Optional |  | For data sources that support table ownership (such as SQL Server, Oracle, and Sybase SQL Anywhere), use this field to specify the owner of the table.
tableQualifier | Optional |  | For data sources that support table qualifiers, use this field to specify qualifier for table. The purpose of table qualifiers varies among drivers. For SQL Server and Oracle, qualifier refers to name of database that contains table. For Intersolv dBASE driver, qualifier refers to directory where DBF files are located.
username | Optional |  | Overrides username specified in ODBC setup.
password | Optional |  | Overrides password specified in ODBC setup.
formFields | Optional | (all on form, except keys) | Comma-delimited list of form fields to insert. If not specified, all fields in the form are included. If a form field is not matched by a column name in the database, ColdFusion throws an error. The database table key field must be present in the form. It may be hidden.

Example

<!--- This example shows how to use cfinsert instead of cfquery to put
data in a datasource. --->
<!--- If form.POSTED exists, we insert new record, so begin cfinsert tag. --->
<cfif IsDefined ("form.posted")>
    <cfinsert dataSource = "cfdocexamples"
        tableName = "Comments"
        formFields = "Email,FromUser,Subject,MessText,Posted">
    <h3><I>Your record was added to the database.</i></h3>
</cfif>

<cfif IsDefined ("form.posted")>
    <cfif Server.OS.Name IS "Windows NT">
        <cfinsert datasource="cfdocexamples" tablename="Comments"
            formfields="EMail,FromUser,Subject,MessText,Posted">
    <cfelse>
        <cfinsert datasource="cfdocexamples" tablename="Comments"
            formfields="CommentID,EMail,FromUser,Subject,MessText,Posted">
    </cfif>
    <h3><i>Your record was added to the database.</i></h3> </cfif>

<!--- Use a query to show the existing state of the database. --->
<cfquery name = "GetComments" dataSource = "cfdocexamples">
    SELECT
        CommentID, EMail, FromUser, Subject, CommtType, MessText, Posted, Processed
    FROM
        Comments
</cfquery>

<html>
<head></head>
<h3>cfinsert Example</h3>
<p>First, show a list of the comments in the cfdocexamples datasource.
<!--- show all the comments in the db --->
<table>
    <tr>
        <td>From User</td><td>Subject</td><td>Comment Type</td>
        <td>Message</td><td>Date Posted</td>
    </tr>
    <cfoutput query = "GetComments">
        <tr>
            <td valign = top><a href = "mailto:#Email#">#FromUser#</A></td>
            <td valign = top>#Subject#</td>
            <td valign = top>#CommtType#</td>
            <td valign = top><font size = "-2">#Left(MessText, 125)#</font></td>
            <td valign = top>#Posted#</td>
        </tr>
    </cfoutput>
</table>
<p>Next, we’ll offer the opportunity to enter a comment:
<!--- make a form for input --->
<form action = "cfinsert.cfm" method = "post">
    <pre>
    Email:	 <input type = "Text" name = "email">
    From: 	<input type = "Text" name = "fromUser">
    Subject:<input type = "Text" name = "subject">
    Message:<textarea name = "MessText" COLS = "40" ROWS = "6"></textarea>
    Date Posted: 	<cfoutput>#DateFormat(Now())#</cfoutput>
    <!--- dynamically determine today’s date --->
    <input type = "hidden"
        name = "posted" value = "<cfoutput>#Now()#</cfoutput>">
    </pre>
    <input type = "Submit"
        name = "" value = "insert my comment">
</form>


cfinvoke

Description

Does either of the following:

  • Invokes a component method from within a ColdFusion page or component.
  • Invokes a web service.

This tag works as follows:

  • Transiently instantiates a component or web service and invokes a method on it.
  • Invokes a method on an instantiated component or web service.

This tag can pass parameters to a method in the following ways:

  • With the cfinvokeargument tag
  • As named attribute-value pairs, one attribute per parameter
  • As a structure, in the argumentCollection attribute

Category

Extensibility tags

Syntax

Syntax 1

<!--- This syntax invokes a method of a component. --->
<cfinvoke
    component = "component name or reference"
    method = "method name"
    returnVariable = "variable name"
    argumentCollection = "argument collection"
    ...>
OR

Syntax 2

<!--- This syntax can invoke a method of a component only
    from within the component. --->
<cfinvoke
    method = "method name"
    returnVariable = "variable name"
    argumentCollection = "argument collection"
    ...
>
OR

Syntax 3

<!--- This syntax invokes a web service. --->
<cfinvoke
    webservice = "URLtoWSDL_location"
    method = "operation_name"
    username = user name"
    password = "password"
    timeout = "request timeout in seconds"
    proxyServer = "WSDL proxy server URL
    proxyPort = "port on proxy server"
    proxyUser = "user id for proxy server"
    proxyPassword = "password for proxy server"
    servicePort = "WSDL port name"
    inputParam1 = "value1"
    inputParam2 = "value2"
    ...
    returnVariable = "var_name"
    ...>
OR

Syntax 4A

<!--- This syntax invokes a component.
This syntax shows instantiation with the cfobject tag.
This cfinvoke syntax applies to instantiating a component
with the cfobject tag and to instantiating a component
with the CreateObject function. --->
<cfobject
    component = "component name"
    name = "mystringname for instantiated object">
<cfinvoke
    <!--- value is object name, within number signs. --->
    component = "#mystringname for instantiated component#"
    method = "method name"
    returnVariable = "variable name"
    argumentCollection = "argument collection"
    ...
>
OR
Syntax 4B
<!--- This syntax invokes a web service.
This syntax shows instantiation with the cfobject tag.
This cfinvoke syntax applies to instantiating a web service
with the cfobject tag and to instantiating a web service
with the CreateObject function. --->
<cfobject
    webservice = "web service name"
    name = "mystringname for instantiated object"
    method = "operation_name">
<cfinvoke
    <!--- value is object name, within number signs. --->
    webservice = "#my stringname for instantiated web service#"
    timeout = "request timeout in seconds"
    proxyServer = "WSDL proxy server url
    proxyPort = "numeric port on proxy server"
    proxyUser = "string user id for proxy server"
    servicePort = "WSDL port name"
    proxyPassword = "string user password for proxy server"
>

See also

cfargument , cfcomponent , cffunction , cfinvokeargument , cfobject , cfproperty , cfreturn

History

ColdFusion MX 7: Added the servicePort attribute.

ColdFusion MX 6.1: Added the following attributes: timeout, proxyServer, proxyPort, proxyUser, and proxyPassword.

ColdFusion MX: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
component | See Usage. |  | String or component object; a reference to a component, or component to instantiate.
method | See Usage. |  | Name of a method. For a web service, the name of an operation.
returnVariable | Optional |  | Name of a variable for the invocation result.
argumentCollection | Optional |  | Name of a structure; associative array of arguments to pass to the method.
username | Optional |  | Overrides username specified in Administrator > Web Services.
password | Optional |  | Overrides password specified in Administrator > Web Services.
webservice | Required |  | The URL of the WSDL file for the web service.
timeout | Optional |  | The timeout for the web service request, in seconds
proxyServer | Optional | http.proxyHost system property, if any. | The proxy server required to access the webservice URL.
proxyPort | Optional | http.proxyPort system property, if any. | The port to use on The proxy server.
proxyUser | Optional | http.proxyUser system property, if any | The user ID to send to the proxy server.
proxyPassword | Optional | http.proxyPassword system property, if any | The user’s password on the proxy server.
servicePort | Optional | First port found in the WSDL | The port name for the web service. This value is case-sensitive and corresponds to the port element’s name attribute under the service element. Specify this attribute if the web service contains multiple ports.
input_params ... |  |  | Input parameters. For each named input parameter specify paramName=paramValue.

Note: If you do not specify any the proxy attributes, and a corresponding system property is set (typically in the JVM startup arguments) ColdFusion uses the system property value.

Usage

The following table shows when you can use each attribute:

This attribute is required, optional, ignored, or invalid: | For this cfinvoke tag syntax:
 | Syntax 1 | Syntax 2 | Syntax 3 | Syntax 4A | Syntax 4B
component | Required | Optional | Invalid | Required | Invalid
method | Required | Required | Required | Required | Required
returnVariable | Optional | Optional | Optional | Optional | Optional
argumentCollection | Optional | Optional | Optional | Optional | Optional
username | Ignored | Ignored | Optional | Ignored | Optional
password | Ignored | Ignored | Optional | Ignored | Optional
webservice | Ignored | Ignored | Required | Ignored | Required
timeout | Invalid | Invalid | Optional | Invalid | Optional
proxyServer | Invalid | Invalid | Optional | Invalid | Optional
proxyPort | Invalid | Invalid | Optional | Invalid | Optional
proxyUser | Invalid | Invalid | Optional | Invalid | Optional
proxyPassword | Invalid | Invalid | Optional | Invalid | Optional
servicePort | Invalid | Invalid | Optional | Invalid | Optional
input_params ... | Optional | Optional | Optional | Optional | Optional

If the component attribute specifies a component name, the component with the corresponding name is instantiated, the requested method is invoked, and then the component instance is immediately destroyed. If the attribute contains a reference to an instantiated component object, no instantiation or destruction of the component occurs.

On UNIX systems, ColdFusion searches first for a file with a name that matches the specified component name, but is all lower case. If it does not find the file, it looks for a file name that matches the component name exactly, with the identical character casing.

Method arguments can be passed in any of the following ways. If an argument is passed in more than one way with the same name, this order of precedence applies:

  1. Using the cfinvokeargument tag
  2. Passing directly as attributes of the cfinvoke tag (they cannot have the same name as a registered cfinvoke attribute: method, component, webservice, returnVariable)
  3. Passing as struct keys, using the argumentCollection attribute

For example, the params struct contains three keys: a=1, b=1, c=1. The following call is evaluated as if the arguments were passed to the method in the order a=3, b=2, c=1:

<cfinvoke ... a=2 b=2 argumentCollection=params>
        <cfinvokeargument name="a" value="3">
    </cfinvoke>

Note: The following cfinvoke tag attribute names are reserved; they cannot be used for argument names: component, method, argumentCollection, and result.

Example1

This example uses Syntax 1.

<!--- Immediate instantiation and destruction. --->
<cfinvoke
    component="nasdaq.quote"
    method="getLastTradePrice"
    returnVariable="res">
    <cfinvokeargument
        name="symbol"
        value="macr">
</cfinvoke>
<cfoutput>#res#</cfoutput>

Example2

This example uses Syntax 1.

<!--- Passing the arguments using argumentCollection. --->
<cfset args = StructNew()>
<cfset args.symbol = "macr">
<cfinvoke
    component="nasdaq.quote"
    method="getLastTradePrice"
    argumentCollection="#args#"
    returnVariable="res">
<cfoutput>#res#</cfoutput>

Example3

This example uses Syntax 2.

<!--- Called only from within a component, MyComponent.--->
<cfinvoke
    method = "a method name of MyComponent"
    returnVariable = "variable name">

Example4

This example uses Syntax 3.

<!--- Using cfinvoke to consume a web service using a ColdFusion component.--->
<cfinvoke
  webservice="http://www.xmethods.net/sd/2001/TemperatureService.wsdl"
  method="getTemp"
  returnvariable="aTemp">
    <cfinvokeargument name="zipcode" value="55987"/>
</cfinvoke>
<cfoutput>The temperature at zip code 55987 is #aTemp#</cfoutput>

For more information on web services, see Using Web Services in ColdFusion MX Developer’s Guide.

Example5

This example uses Syntax 4A.

<!--- Separate instantiation and method invocation; useful for
    multiple invocations using different methods or values. --->
<cfobject
    name="quoteService"
    component="nasdaq.quote">
<cfinvoke
    component="#quoteService#"
    method="getLastTradePrice"
    symbol="macr"
    returnVariable="res_macr">
<cfoutput>#res#</cfoutput>
<cfinvoke
    component="#quoteService#"
    method="getLastTradePrice"
    symbol="mot"
    returnVariable="res_mot">
<cfoutput>#res#</cfoutput>


cfinvokeargument

Description

Passes the name and value of a parameter to a component method or a web service. This tag is used within the cfinvoke tag.

Category

Extensibility tags

Syntax

<cfinvokeargument
    name="argument name"
    value="argument value"
    omit = "yes" or "no">

See also

cfargument , cfcomponent , cffunction , cfinvoke , cfobject , cfproperty , cfreturn

History

ColdFusion MX 7: Added the omit attribute.

ColdFusion MX: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
name | Required |  | Argument name.
value | Required |  | Argument value.
omit | Optional | "no" | Enables you to omit a parameter when invoking a web service. It is an error to specify omit="yes" if the cfinvoke webservice attribute is not specified. "yes": omit this parameter when invoking a web service. "no": do not omit this parameter when invoking a web service.

Usage

You can have multiple cfinvokeargument tags in a cfinvoke tag body.

You can use cfinvokeargument tag to dynamically determine the arguments to be passed. For example, you can use conditional processing to determine the argument name, or you can use a cfif tag to determine whether to execute the cfinvokeargument tag.

If you are invoking a web service, you can omit a parameter by setting the omit attribute to "yes". If the WSDL specifies that the argument is nillable, ColdFusion MX sets the associated argument to null. If the WSDL specifies minoccurs=0, ColdFusion MX omits the argument from the WSDL.

Example1

<cfinvoke
    component="nasdaq.quote"
    method="getLastTradePrice"
    returnVariable="res">
    <cfinvokeargument
        name="symbol" value="mot">
    <cfinvokeargument
        name="symbol" 	value="macr">
</cfinvoke>

<cfoutput>#res#</cfoutput>

Example2

<cfinvoke
    webservice ="http://www.xmethods.net/sd/2001/BabelFishService.wsdl"
    method ="BabelFish"
    returnVariable = "varName"
    >
    <cfinvokeargument
        name="translationmode" value="en_es">
    <cfinvokeargument
        name="sourcedata" value="Hello world, friend">
</cfinvoke>
<cfoutput>#varName#</cfoutput>


cfldap

Description

Provides an interface to a Lightweight Directory Access Protocol (LDAP) directory server, such as the Netscape Directory Server.

Category

Internet Protocol tags

Syntax

<cfldap
    server = "server_name"
    port = "port_number"
    username = "name"
    password = "password"
    action = "action"
    name = "name"
    timeout = "seconds"
    maxRows = "number"
    start = "distinguished_name"
    scope = "scope"
    attributes = "attribute, attribute"
returnAsBinary = "column_name, column_name"
    filter = "filter"
    sort = "attribute[, attribute]..."
    sortControl = "nocase" and/or "desc" or "asc"
    dn = "distinguished_name"
    startRow = "row_number"
    modifyType = "replace" or "add" or "delete"
    rebind = "yes" or "no"
    referral = "number_of_allowed_hops"
    secure = "multi_field_security_string"
    separator = "separator_character"
    delimiter = "delimiter_character">

See also

cfftp , cfhttp , cfmail , cfmailparam , cfpop , Managing LDAP Directories in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the returnAsBinary attribute.

ColdFusion MX:

  • Changed the name attribute behavior: this tag validates the query name in the name attribute.
  • Changed sorting behavior: this tag does not support client-side sorting of query results. (It supports server-side sorting; use the sort and sortcontrol attributes.)
  • Changed how results are sorted: server-side sorting results might be sorted slightly differently than in ColdFusion 5. If you attempt a sort against a server that does not support it, ColdFusion MX throws an error.
  • Deprecated the filterfile attribute. It might not work, and might cause an error, in later releases.

Attributes

Attribute

Req/Opt

Default

Description

server

Required

Host name or IP address of LDAP server.

port

Optional

389

Port.

username

Required if secure = "CFSSL_BASIC"

(anonymous)

User ID.

password

Required if secure = "CFSSL_BASIC"

Password that corresponds to user name.

If secure = "CFSSL_BASIC", V2 encrypts the password before transmission.

action

Required

query
  • query: returns LDAP entry information only. Requires name, start, and attributes attributes.
  • add: adds LDAP entries to LDAP server. Requires attributes attribute.
  • modify: modifies LDAP entries, except distinguished name dn attribute, on LDAP server. Requires dn. See modifyType attribute.
  • modifyDN: modifies distinguished name attribute for LDAP entries on LDAP server. Requires dn.
  • delete: deletes LDAP entries on an LDAP server. Requires dn.

name

Required if action = "Query"

Name of LDAP query. The tag validates the value.

timeout

Optional

60000

Maximum length of time, in milliseconds, to wait for LDAP processing.

maxRows

Optional

Maximum number of entries for LDAP queries.

start

Required if action = "Query"

Distinguished name of entry to be used to start a search.

scope

Optional

oneLevel

Scope of search, from entry specified in start attribute for action = "Query".

  • oneLevel: entries one level below entry.
  • base: only the entry.
  • subtree: entry and all levels below it.

attributes

Required if action = "Query", "Add", "ModifyDN", or "Modify"

For queries: comma-delimited list of attributes to return. For queries, to get all attributes, specify "*".

If action = "add" or "modify", you can specify a list of update columns. Separate attributes with a semicolon.

If action = "ModifyDN", ColdFusion passes attributes to the LDAP server without syntax checking.

returnAsBinary

Optional

A comma-delimited list of columns that are to be returned as binary values.

filter

Optional

"objectclass = *"

Search criteria for action = "query".

List attributes in the form:
"(attribute operator value)"
For example: "(sn = Smith)"

sort

Optional

Attribute(s) by which to sort query results. Use a comma delimiter.

sortControl

Optional

asc
  • nocase: case-insensitive sort.
  • asc: ascending (a to z) case-sensitive sort.
  • desc: descending (z to a) case-sensitive sort.

You can enter a combination of sort types; for example, sortControl = "nocase, asc".

dn

Required if action = "Add", "Modify", "ModifyDN", or "delete"

Distinguished name, for update action; for example, "cn = Bob Jensen, o = Ace Industry,
c = US"

startRow

Optional

1

Used with action = "query". First row of LDAP query to insert into a ColdFusion query.

modifyType

Optional

replace

How to process an attribute in a multi-value list:

  • add: appends it to any attributes.
  • delete: deletes it from the set of attributes.
  • replace: replaces it with specified attributes.

You cannot add an attribute that is already present or that is empty.

rebind

Optional

no

  • yes: attempts to rebind referral callback and reissue query by referred address using original credentials.
  • no: referred connections are anonymous.

referral

Optional

Integer. Number of hops allowed in a referral. A value of 0 disables referred addresses for LDAP; no data is returned.

secure

Optional

Security to employ, and required information. One option:

  • CFSSL_BASIC

"CFSSL_BASIC" provides V2 SSL encryption
and server authentication.

separator

Optional

, [comma]

Delimiter to separate attribute values of multi-value attributes. Used by query, add, and modify actions, and by cfldap to output multi-value attributes.

For example, if $ (dollar sign), the attributes attribute could be "objectclass = top$person", where the first value of objectclass is top, and the second value is person. This avoids confusion if values include commas.

delimiter

Optional

; [semicolon]

Separator between attribute name-value pairs. Use this attribute if either of these situations exist:

  • the attributes attribute specifies more than one item
  • an attribute contains the default delimiter (semicolon). For example: mgrpmsgrejecttext;lang-en

Used by query, add, and modify actions, and by cfldap to output multivalue attributes.

For example, if $ (dollar sign), you could specify
"cn = Double Tree Inn$street = 1111 Elm; Suite 100, where the semicolon is part of the street value.

Usage

If you use the query action, cfldap creates a query object, allowing access to information in the query variables, as follows:

Variable name | Description
queryname.recordCount | Number of records returned by query
queryname.currentRow | Current row of query that cfoutput is processing
queryname.columnList | Column names in query

If you use the security="CFSSL_BASIC" option, ColdFusion determines whether to trust the server by comparing the server’s certificate with the information in the jre/lib/security/cacerts keystore of the JRE used by ColdFusion MX. The ColdFusion MX default cacerts file contains information about many certificate granting authorities. If you must update the file with additional information, you can use the keytool utility in the ColdFusion jre/bin directory to import certificates that are in X.509 format. For example, enter the following:

keytool -import -keystore cacerts -alias ldap -file ldap.crt -keypass bl19mq

Then restart ColdFusion MX. The keytool utility initial keypass password is "change it". For more information on using the keytool utility, see the Sun JDK documentation

Characters that are illegal in ColdFusion can be used in LDAP attribute names. As a result, the cfldap tag could create columns in the query result set whose names contain illegal characters and are, therefore, inaccessible in CFML. In ColdFusion, illegal characters are automatically mapped to the underscore character; therefore, column names in the query result set might not exactly match the names of the LDAP attributes.

For usage examples, see ColdFusion MX Developer’s Guide.

Example

<h3>cfldap Example</h3>
<p>Provides an interface to LDAP directory servers. The example uses the
University of Connecticut public LDAP server. For more public LDAP servers,
see <a href="http://www.emailman.com">http://www.emailman.com</a>.</p>
<p>Enter a name and search the public LDAP resource.
An asterisk before or after the name acts as a wildcard.</p>
<!--- If form.name exists, the form was submitted; run the query. --->
<cfif IsDefined("form.name")>
    <!--- Check to see that there is a name listed. --->
    <cfif form.name is not "">
        <!--- Make the LDAP query. --->
        <cfldap
             server = "ldap.uconn.edu"
             action = "query"
             name = "results"
             start = "dc=uconn,dc=edu"
             filter = "cn=#name#"
             attributes = "cn,o,title,mail,telephonenumber"
             sort = "cn ASC">
        <!--- Display results. --->
        <center>
        <table border = 0 cellspacing = 2 cellpadding = 2>
            <tr>
                <th colspan = 5>
                    <cfoutput>#results.recordCount# matches found
                    </cfoutput></TH>
            </tr>
            <tr>
                <th><font size = "-2">Name</font></TH>
                <th><font size = "-2">Organization</font></TH>
                <th><font size = "-2">Title</font></TH>
                <th><font size = "-2">E-Mail</font></TH>
                <th><font size = "-2">Phone</font></TH>
            </tr>
            <cfoutput query = "results">
                <tr>
                    <td><font size = "-2">#cn#</font></td>
                    <td><font size = "-2">#o#</font></td>
                    <td><font size = "-2">#title#</font></td>
                    <td><font size = "-2">
                        <A href = "mailto:#mail#">#mail#</A></font></td>
                    <td><font size = "-2">#telephonenumber#</font></td>
                </tr>
            </cfoutput>
            </table>
            </center>
        </cfif>
</cfif>

<form action="#cgi.script_name#" method="POST">
<p>Enter a name to search in the database.
<p>
<input type="Text" name="name">
<input type="Submit" value="Search" name="">
</form>


cflocation

Description

Stops execution of the current page and opens a ColdFusion page or HTML file.

Category

Flow-control tags, Page processing tags

Syntax

<cflocation
    url = "url"
    addToken = "yes" or "no">

See also

cfabort , cfbreak , cfexecute , cfexit , cfif , cfloop , cfswitch , cfthrow , cftry

Attributes

Attribute

Req/Opt

Default

Description

url

Required

URL of HTML file or CFML page to open.

addToken

Optional

clientManagement must be enabled (see cfapplication).

  • yes: appends client variable information to URL.
  • no

Usage

You might write a standard message or response in a file, and call it from several applications. You could use this tag to redirect the user’s browser to the standard file.

This tag has no effect if you use it after the cfflush tag on a page.

Example

<h3>cflocation Example</h3>
<p>This tag redirects the browser to a web resource; normally, you would
use this tag to go to a CF page or an HTML file on the same server.
The addToken attribute lets you send client information to the
target page.
<p>If you remove the comments, this code redirects you to CFDOCS home page:

<!--- <cflocation url = "http://localhost:8500/cfdocs/dochome.htm"
addToken = "no"> --->


cflock

Description

Ensures the integrity of shared data. Instantiates the following kinds of locks:

Exclusive Allows single-thread access to the CFML constructs in its body. The tag body can be executed by one request at a time. No other requests can start executing code within the tag while a request has an exclusive lock. ColdFusion issues exclusive locks on a first-come, first-served basis.

Read-only Allows multiple requests to access CFML constructs within the tag body concurrently. Use a read-only lock only when shared data is read and not modified. If another request has an exclusive lock on shared data, the new request waits for the exclusive lock to be released.

Category

Application framework tags

Syntax

<cflock
    timeout = "timeout in seconds "
    scope = "Application" or "Server" or "Session"
    name = "lockname"
    throwOnTimeout = "yes" or "no"
    type = "readOnly" or "exclusive ">
    <!--- CFML to be synchronized --->
</cflock>

See also

cfapplication , cfassociate , cfmodule , Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

timeout

Required

Maximum length of time, in seconds, to wait to obtain a lock. If lock is obtained, tag execution continues. Otherwise, behavior depends on throwOnTimeout attribute value. If you set timout="0", the timeout is determined by the "Timeout Requests after x" setting in the ColdFusion MX Administrator Settings page, if that setting is enabled. However, if the setting is not enabled, and you set timeout="0", ColdFusion can wait indefinitely to obtain the lock.

scope

Optional

Lock scope. Mutually exclusive with the name attribute. Lock name. Only one request in the specified scope can execute the code within this tag (or within any other cflock tag with the same lock scope) at a time.

  • Application
  • Server
  • Session

name

Optional

Lock name. Mutually exclusive with the scope attribute. Only one request can execute the code within a cflock tag with a given name at a time. Cannot be an empty string.

Permits synchronizing access to resources from different parts of an application. Lock names are global to a ColdFusion server. They are shared among applications and user sessions, but not clustered servers.

throwOnTimeout

Optional

yes

How timeout conditions are handled:

  • yes: exception is generated for the timeout.
  • no: execution continues past this tag.

type

Optional

Exclusive
  • readOnly: lets more than one request read shared data.
  • exclusive: lets one request read or write shared data.

Note: Limit the scope of code that updates shared data structures, files, and CFXs. Exclusive locks are required to ensure the integrity of updates, but read-only locks are faster. In a performance-sensitive application, substitute read-only locks for exclusive locks where possible; for example, when reading shared data.

Usage

ColdFusion MX is a multithreaded server; it can process multiple page requests at a time. Use the cflock tag for these purposes:

  • To ensure that modifications to shared data and objects made in concurrently executing requests occur sequentially.
  • Around file manipulation constructs, to ensure that file updates do not fail because files are open for writing by other applications or tags.
  • Around CFX invocations, to ensure that ColdFusion can safely invoke CFXs that are not implemented in a thread-safe manner. (This applies only to CFXs developed in C++.)

To work safely with ColdFusion, a C++ CFX that maintains and manipulates shared (global) data structures must be made thread-safe; however, this requires advanced knowledge. You can use a CFML custom tag wrapper around a CFX to make its invocation thread-safe.

When you display, set, or update variables in a shared scope, use the scope attribute to identify the scope as Server, Application or Session.

Deadlocks

A deadlock is a state in which no request can execute the locked section of a page. Once a deadlock occurs, neither user can break it, because all requests to the protected section of the page are blocked until the deadlock can be resolved by a lock timeout.

The cflock tag uses kernel level synchronization objects that are released automatically upon timeout and/or the abnormal termination of the thread that owns them. Therefore, while processing a cflock tag, ColdFusion never deadlocks for an infinite period of time. However, very large timeouts can block request threads for long periods, and radically decrease throughput. To prevent this, always use the minimum timeout value.

Another cause of blocked request threads is inconsistent nesting of cflock tags and inconsistent naming of locks. If you nest locks, everyone accessing the locked variables must consistently nest cflock tags in the same order. Otherwise, a deadlock can occur.

These examples show situations that cause deadlocks:

Example deadlock with two users
User 1 | User 2
Locks the session scope. | Locks the Application scope.
Deadlock: Tries to lock the Application scope, but it is already locked by User 2. | Deadlock: Tries to lock the Session scope, but it is already locked by User 1.

The following deadlock could occur if you tried to nest an exclusive lock inside a read lock:

Example deadlock with one user

User 1

Locks the Session scope with a read lock.

Attempts to lock the Session scope with an exclusive lock.

Deadlock: Cannot lock the Session scope with an exclusive lock because the scope is already locked for reading.

The following code shows this scenario:

<cflock timeout = "60" scope = "SESSION" type = "readOnly">
    ...............
    <cflock timeout = "60" scope = "SESSION" type = "Exclusive">
    .........
    </cflock>
</cflock>

To avoid a deadlock, everyone who nests locks must do so in a well-specified order and name the locks consistently. If you must lock access to the Server, Application, and Session scopes, you must do so in this order:

  1. Lock the Session scope. In the cflock tag, specify scope = "session".
  2. Lock the Application scope. In the cflock tag, specify scope = "Application".
  3. Lock the Server scope. In the cflock tag, specify scope = "server".
  4. Unlock the Server scope.
  5. Unlock the Application scope.
  6. Unlock the Session scope.

Note: If you do not have to lock a scope, you can skip any pair of these lock/unlock steps. For example, if you do not have to lock the Server scope, you can skip Steps 3 and 4. Similar rules apply for named locks.

For more information, see the following:

  • Using Persistent Data and Locking in ColdFusion MX Developer’s Guide
  • Article #20370, ColdFusion Locking Best Practices, on the Macromedia website at www.macromedia.com/support/service/

Example

<!--- This example shows how cflock can guarantee consistency of data updates
to variables in the Application, Server, and Session scopes. --->

<!--- Copy the following code into an Application.cfm file in the application
        root directory. --->
<!----------------   Beginning of Application.cfm code   --------------->
<!--- cfapplication defines scoping for a ColdFusion application and
enables or disables storing of application and session variables.
Put this tag in a special file called Application.cfm.
It is run before any other ColdFusion page in its directory. --->

<!--- Enable session management for this application. --->
<cfapplication name = "ETurtle"
    sessionTimeout = #CreateTimeSpan(0,0, 0, 60)#
    sessionManagement = "yes">

<!--- Initialize session and application variables used by E-Turtleneck.
Use session scope for the session variables. --->
<cflock scope = "Session"
    timeout = "30" type = "Exclusive">
    <cfif NOT IsDefined("session.size")>
        <cfset session.size = "">
    </cfif>
    <cfif NOT IsDefined("session.color")>
        <cfset session.color = "">
    </cfif>
</cflock>

<!--- Use an application lock for the application-wide variable that
      keeps track of the number of turtlenecks sold.
      For a more efficient, but more complex, way of handling Application scope
      locking, see "ColdFusion MX Developer’s Guide"--->
<cflock scope = "Application" 		timeout = "30" type = "Exclusive">
    <cfif NOT IsDefined("application.number")>
        <cfset application.number = 0>
    </cfif>
</cflock>

<!----------------------- End of Application.cfm ----------------------->

<h3>cflock Example</h3>

<cfif IsDefined("form.submit")>
<!--- The form has been submitted; process the request. --->
    <cfoutput>
        Thanks for shopping E-Turtleneck. You chose size <b>#form.size#</b>,
        color <b>#form.color#</b>.<br><br>
    </cfoutput>

<!--- Lock the code that assigns values to session variables. ---->
    <cflock scope = "Session" timeout = "30" type = "Exclusive">
        <cfparam name = session.size Default = #form.size#>
        <cfparam name = session.color Default = #form.color#>
    </cflock>

<!---- Lock the code that updates the Application scope number of
        turtlenecks sold. --->
    <cflock scope = "Application" timeout = "30" type = "Exclusive">
        <cfset application.number = application.number + 1>
    <cfoutput>
        E-Turtleneck has now sold #application.number# turtlenecks!
    </cfoutput>
    </cflock>

<cfelse>
<!--- Show the form only if it has not been submitted. --->
    <cflock scope = "Application" timeout = "30" type = "Readonly">
        <cfoutput>
            E-Turtleneck has sold #application.number# turtlenecks to date.
        </cfoutput>
    </cflock>

    <form method="post" action="cflocktest.cfm">
        <p>Congratulations! You selected the most comfortable turtleneck in the world.
        Please select color and size.</p>
        <table cellspacing = "2" cellpadding = "2" border = "0">
            <tr>
                <td>Select a color.</td>
                <td><select type = "Text" name = "color">
                        <option>red
                        <option>white
                        <option>blue
                        <option>turquoise
                        <option>black
                        <option>forest green
                    </select>
                </td>
            </tr>
            <tr>
                <td>Select a size.</td>
                <td><select type = "Text" name = "size" >
                        <option>XXsmall
                        <option>Xsmall
                        <option>small
                        <option>medium
                        <option>large
                        <option>Xlarge
                    </select>
                </td>
            </tr>
            <tr>
                <td>Press Submit when you are finished making your selection.</td>
                <td><input type = "Submit" name = "submit" value = "Submit"> </td>
            </tr>
        </table>
    </form>
</cfif>


cflog

Description

Writes a message to a log file.

Category

Data output tags

Syntax

<cflog
    text = "text"
    log = "log type"
    file = "filename"
    type = "message type"
    application = "yes" or "no">

See also

cfcol , cfcontent , cfoutput , cftable

History

ColdFusion MX: Deprecated the thread, date, and time attributes. They might not work, and might cause an error, in later releases. (In earlier releases, these attributes determined whether the respective data items were output to the log. In ColdFusion MX, this data is always output.)

Attributes

Attribute

Req/Opt

Default

Description

text

Required

Message text to log.

log

Optional

If you omit the file attribute, writes messages to standard log file. Ignored, if you specify file attribute.

  • Application: writes to Application.log, normally used for application-specific messages.
  • Scheduler: writes to Scheduler.log, normally used to log the execution of scheduled tasks.

file

Optional

Message file. Specify only the main part of the filename. For example, to log to the Testing.log file, specify "Testing".

The file must be located in the default log directory. You cannot specify a directory path. If the file does not exist, it is created automatically, with the suffix .log.

type

Optional

Information

Type (severity) of the message:

  • Information
  • Warning
  • Error
  • Fatal

application

Optional

yes
  • yes: logs the application name, if it is specified in a cfapplication tag or Application.cfc file.
  • no

Usage

This tag logs custom messages to standard or custom log files. You can specify a file for the log message or send messages to the default application or scheduler log. The log message can include ColdFusion expressions. Log files must have the suffix .log and must be located in the ColdFusion log directory.

Log entries are written as comma-delimited lists with these fields:

  • type
  • coio
  • date
  • time
  • application
  • text

Values are enclosed in double-quotation marks. If you specify no for the application attribute, the corresponding entry in the list is empty.

You can disable cflog tag execution. For more information, see the ColdFusion Administrator Basic Security page.

The following example logs the name of a user that logs on an application. The message is logged to the file myAppLog.log in the ColdFusion log directory. It includes the date, time, and thread ID, but not the application name.

<cflog file="myAppLog" application="no"
    text="User #Form.username# logged on.">

For example, if a user enters "Sang Thornfield" in a form’s username field, this entry is added to the myApplog.log file entry:

"Information","153","02/28/01","14:53:40",,"User Sang Thornfield logged on."


cflogin

Description

A container for user login and authentication code. ColdFusion runs the code in this tag if a user is not already logged in. You put code in the tag that authenticates the user and identifies the user with a set of roles. Used with cfloginuser tag.

Category

Security tags

Syntax

<cflogin
    idletimeout = "value"
    applicationToken = "token"
    cookieDomain = "domain"
    ...
    <cfloginuser
        name = "name"
        password = "password-string"
        roles = "roles">
    ...>
</cflogin>

See also

cfloginuser , cflogout , GetAuthUser , IsUserInRole , Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.1: Changed behavior: the cflogin variable exists when ColdFusion receives a request with NTLM or Digest (CFHTTP Negotiated header) authentication information.

ColdFusion MX: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
idletimeout | Optional | 1800 | Time interval, in seconds, after which ColdFusion logs off the user.
applicationtoken | Optional | The current application name | Unique application identifier. Limits the login validity to one application, as specified by the cfapplication tag or the Application.cfc file.
cookiedomain | Optional |  | Domain of the cookie that is used to mark a user as logged in. Use this attribute to enable a user login cookie to work with multiple clustered servers in the same domain.

Usage

The body of this tag executes only if there is no logged-in user. When using application-based security, you put code in the body of the cflogin tag to check the user-provided ID and password against a data source, LDAP directory, or other repository of login identification. The body must include a cfloginuser tag to establish the authenticated user's identity in ColdFusion.

You control the data source and are responsible for coding the SQL within the cflogin tag, and you must make sure that the associated database has user, password, and role information.

The cflogin tag has a built-in cflogin structure that contains two variables, cflogin.name and cflogin.password, if the page is executing in response to any of the following:

  • Submission of a form that contains input fields with the names j_username and j_password.
  • A request that uses CFHTTP Basic authentication, and therefore includes an Authorization header with the username and password.
  • A request that uses NTLM or Digest authentication. In this case, the username and password are hashed using a one-way algorithm in the Authorization header; ColdFusion gets the username from the web server and sets the cflogin.password value to the empty string.

You can use these values in the cflogin tag body to authenticate the user, and, in the cfloginuser tag, to log the user in. The structure is only available in the cflogin tag body.

Example

The following example shows a simple authentication. This code is typically in the Application.cfc onRequestStart method or in the application.cfm page.

<cflogin>
    <cfif NOT IsDefined("cflogin")>
        <cfinclude template="loginform.cfm">
        <cfabort>
    <cfelse>
        <cfif cflogin.name eq "admin">
            <cfset roles = "user,admin">
        <cfelse>
                <cfset roles = "user">
        </cfif>
        <cfloginuser name = "#cflogin.name#" password = "#cflogin.password#"
            roles = "#roles#" />
    </cfif>
</cflogin>

The following view-only example checks the user ID and password against a data source:

<cfquery name="qSecurity"
    datasource="UserRolesDb">
    select Roles FROM SecurityRoles
    where username=<cfqueryparam value="#cflogin.name#"
        CFSQLTYPE="CF_SQL_VARCHAR"
    and password=<cfqueryparam value="#cflogin.password#"
        CFSQLTYPE="CF_SQL_VARCHAR"
</cfquery>

<cfif qSecurity.recordcount gt 0>
<cfloginuser name = "#cflogin.name#"
password = "#cflogin.password#"
roles = "#trim(qSecurity.Roles)#" >
</cfif>


cfloginuser

Description

Identifies an authenticated user to ColdFusion. Specifies the user ID and roles. Used within a cflogin tag.

Category

Security tags

Syntax

<cfloginuser
    name = "name"
    password = "password-string"
    roles = "roles">

See also

cflogin , cflogout , GetAuthUser , IsUserInRole , cfapplication , Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.1: Changed behavior: if the Session scope is enabled, and the cfapplication tag loginStorage attribute is set to Session, the login remains in effect until the session expires or the user is logged out by the cflogout tag.

ColdFusion MX: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
name | Required |  | A username.
password | Required |  | A user password.
roles | Required |  | A comma-delimited list of role identifiers. ColdFusion processes spaces in a list element as part of the element.

Usage

Used inside the cflogin tag to identify the authenticated user to ColdFusion. After you call this function, the GetAuthUser and IsUserInRoles return the user name and role information.

Note: By default, the user information is stored as memory-only cookies. The cfapplication tag or the Application.cfc This.loginStorage variable can specify that login information be stored in the Session scope.

Example

See cflogin.


cflogout

Description

Logs the current user out. Removes knowledge of the user ID, password, and roles from the server. If you do not use this tag, the user is automatically logged out when the session ends.

Category

Security tags

Syntax

<cflogout>

See also

cflogin , cfloginuser , Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.1: Changed behavior: if the Session scope is enabled, a login remains in effect until the session expires or the user is logged out by the cflogout tag.

ColdFusion MX: Added this tag.

Example

<cflogin>
    <cfloginuser
        name = "foo"
        password ="bar"
        roles = "admin">
</cflogin>
<cfoutput>Authorized user: #getAuthUser()#</cfoutput>
<cflogout>
<cfoutput>Authorized user: #getAuthUser()#</cfoutput>


cfloop

Description

Looping is a programming technique that repeats a set of instructions or displays output repeatedly until one or more conditions are met. This tag supports the following types of loops:

  • cfloop: index loop
  • cfloop: conditional loop
  • cfloop: looping over a date or time range
  • cfloop: looping over a query
  • cfloop: looping over a list or file
  • cfloop: looping over a COM collection or structure

For more information, see cfloop and cfbreak in Elements of CFML and Populating arrays with data in Using Arrays and Structures in ColdFusion MX Developer’s Guide.

Category

Flow-control tags


cfloop: index loop

Description

An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.

Syntax

<cfloop
    index = "parameter_name"
    from = "beginning_value"
    to = "ending_value"
    step = "increment">
    ... HTML or CFML code ...
</cfloop>

See also

cfabort, cfbreak, cfdirectory, cfexecute, cfexit, cfif, cflocation, cfrethrow, cfswitch, cfthrow, cftry; cfloop and cfbreak in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
index | Required |  | Index value. ColdFusion sets it to the from value and increments or decrements by step value, until it equals the to value.
from | Required |  | Beginning value of index.
to | Required |  | Ending value of index.
step | Optional | 1 | Step by which to increment or decrement the index value.

Usage

Using anything other than integer values in the from and to attributes of an index loop can product unexpected results. For example, if you increment through an index loop from 1 to 2, with a step of 0.1, ColdFusion outputs "1,1.1,1.2,...,1.9", but not "2". This is a programming language problem regarding the internal representation of floating point numbers.

Note: The to value is evaluated once, when the cfloop tag is encountered. Any change to this value within the loop block, or within the expression that evaluates to this value, does not affect the number of times the loop is executed.

Example

In this example, the code loops five times, displaying the index value each time:

<cfloop index = "LoopCount" from = "1" to = "5">
    The loop index is <cfoutput>#LoopCount#</cfoutput>.<br>
</cfloop>

The output of this loop is as follows:

The loop index is 1.
The loop index is 2.
The loop index is 3.
The loop index is 4.
The loop index is 5.

In this example, the code loops four times, displaying the index value each time. The value of j is decreased by one for each iteration. This does not affect the value of to, because it is a copy of j that is made before entering the loop.

<cfset j = 4>
<cfloop index = "LoopCount" from = "1" to = #j#>
    <cfoutput>The loop index is #LoopCount#</cfoutput>.<br>
    <cfset j = j - 1>
</cfloop>

The output of this loop is as follows:

The loop index is 1.
The loop index is 2.
The loop index is 3.
The loop index is 4.

As before, the value of j is decremented by one for each iteration, but this does not affect the value of to, because its value is a copy of j that is made before the loop is entered.

In this example, step has the default value, 1. The code decrements the index:

<cfloop index = "LoopCount"
    from = "5"
    to = "1"
    step = "-1">
The loop index is <cfoutput>#LoopCount#</cfoutput>.<br>
</cfloop>

The output of this loop is as follows:

The loop index is 5.
The loop index is 4.
The loop index is 3.
The loop index is 2.
The loop index is 1.


cfloop: conditional loop

Description

A conditional loop iterates over a set of instructions as long as a condition is True. To use this type of loop correctly, the instructions must change the condition every time the loop iterates, until the condition is False. Conditional loops are known as WHILE loops, as in, "loop WHILE this condition is true."

Syntax

<cfloop
    condition = "expression">
    ...
</cfloop>

See also

cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfswitch, cfthrow, cftry; cfloop and cfbreak in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
condition | Required |  | Condition that controls the loop.

Example

The following example increments CountVar from 1 to 5.

<!--- Set the variable CountVar to 0. --->
<cfset CountVar = 0>
<!--- Loop until CountVar = 5. --->
<cfloop condition = "CountVar LESS THAN OR EQUAL TO 5">
    <cfset CountVar = CountVar + 1>
    The loop index is <cfoutput>#CountVar#</cfoutput>.<br>
</cfloop>

The output of this loop is as follows:

The loop index is 1.
The loop index is 2.
The loop index is 3.
The loop index is 4.
The loop index is 5.


cfloop: looping over a date or time range

Description

Loops over the date or time range specified by the from and to attributes. By default, the step is 1 day, but you can change the step by creating a timespan. The cfloop tag loops over tags that cannot be used within a cfoutput tag.

Syntax

<cfloop
    from = "start_time"
    to = "end_time"
    index = "current_value"
    step = "increment">
</cfloop>

See also

cfabort, cfbreak, cfdirectory, cfexecute, cfexit, cfif, cflocation, cfrethrow, cfswitch, cfthrow, cftry; cfloop and cfbreak in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
from | Required |  | The beginning of the date or time range.
to | Required |  | The end of the date or time range.
index | Required | 1 day | Index value. ColdFusion sets it to the from value and increments by the step value, until it equals the to value.
step | Optional |  | Step, expressed as a timespan, by which the index increments.

Example

The following example loops from today’s date to today’s date plus 30 days, stepping by 7 days at a time and displaying the date:

<cfset startDate = Now()>
<cfset endDate = Now() + 30>
<cfloop from="#startDate#" to="#endDate#" index="i" step="#CreateTimeSpan(7,0,0,0)#">
  <cfoutput>#dateformat(i, "mm/dd/yyyy")#<br /></cfoutput>
</cfloop>

The following example displays the time in 30-minute increments, starting from midnight and ending 23 hours, 59 minutes, and 59 seconds later:

<cfset startTime = CreateTime(0,0,0)>
<cfset endTime = CreateTime(23,59,59)>
<cfloop from="#startTime#" to="#endTime#" index="i" step="#CreateTimeSpan(0,0,30,0)#">
 <cfoutput>#TimeFormat(i, "hh:mm tt")#<br /></cfoutput>
</cfloop>


cfloop: looping over a query

Description

A loop over a query executes for each record in a query record set. The results are similar to those of the cfoutput tag. During each iteration, the columns of the current row are available for output. The cfloop tag loops over tags that cannot be used within a cfoutput tag.

Syntax

<cfloop
    query = "query_name"
    startRow = "row_num"
    endRow = "row_num">
</cfloop>

See also

cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfoutput, cfswitch, cfthrow, cftry; For more information, see cfloop and cfbreak in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
query | Required |  | Query that controls the loop.
startRow | Optional |  | First row of query that is included in the loop.
endRow | Optional |  | Last row of query that is included in the loop.

Example

<cfquery name = "MessageRecords"
dataSource = "cfdocexamples">
SELECT * FROM Messages
</cfquery>
<cfloop query = "MessageRecords">
<cfoutput>#Message_ID#</cfoutput><br>
</cfloop>

The cfloop tag also iterates over a record set with dynamic start and stop points. This gets the next n sets of records from a query. This example loops from the fifth through the tenth record returned by the MessageRecords query:

<cfset Start = 5>
<cfset End = 10>
<cfloop query = "MessageRecords"
startRow = "#Start#"
endRow = "#End#">
<cfoutput>#MessageRecords.Message_ID#</cfoutput><br>
</cfloop>

The loop stops when there are no more records, or when the current record index is greater than the value of the endRow attribute.

The following example combines the pages that are returned by a query of a list of page names into one document, using the cfinclude tag:

<cfquery name = "GetTemplate"
dataSource = "Library"
maxRows = "5">
SELECT TemplateName
FROM Templates
</cfquery>
<cfloop query = "GetTemplate">
<cfinclude template = "#TemplateName#">
</cfloop>


cfloop: looping over a list or file

Description

Looping over a list steps through elements contained in any of these entities:

  • A variable
  • A value that is returned from an expression
  • A file

Syntax

<cfloop
    index = "index_name"
    list = "list_items"
    delimiters = "item_delimiter">
    ...
</cfloop>

See also

cfabort, cfbreak, cfexecute, cfexit, cfif, cflocation, cfswitch, cfthrow, cftry; cfloop and cfbreak in Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
index | Required |  | In a list loop, the variable to receive the next list element.
list | Required |  | A list, variable, or filename; contains a list.
delimiters | Optional |  | Character(s) that separates items in list.

Example

This loop displays four names:

<cfloop index = "ListElement"
    list = "John,Paul,George,Ringo">
        <cfoutput>#ListElement#</cfoutput><br>
</cfloop>

You can put more than one character in the delimiters attribute, in any order. For example, this loop processes commas, colons, and slashes as list delimiters:

<cfloop index = "ListElement"
    list = "John/Paul,George::Ringo"
    delimiters = ",:/">
        <cfoutput>#ListElement#</cfoutput><br>
</cfloop>

ColdFusion skips the second and subsequent consecutive delimiters between list elements. Thus, in the example, the two colons between "George" and "Ringo" are processed as one delimiter.

To loop over each line of a file, use the tag this way:

<cfloop list="#theFile#"
    index="curLine"
    delimiters="#chr(10)##chr(13)#">
    ...
</cfloop>


cfloop: looping over a COM collection or structure

Description

The cfloop collection attribute loops over every object within a COM/DCOM collection object, or every element in a structure:

  • A COM/DCOM collection object is a set of similar items referenced as a group. For example, the group of open documents in an application is a collection.
  • A structure contains a related set of items, or it can be used as an associative array. Looping is particularly useful when using a structure as an associative array.

In the loop, each item is referenced by the variable name in the item attribute. The loop executes until all items have been accessed.

The collection attribute is used with the item attribute. In the example that follows, item is assigned a variable called file2, so that with each cycle in the cfloop, each item in the collection is referenced. In the cfoutput section, the name property of the file2 item is referenced for display.

For more information, see Integrating COM and CORBA Objects in CFML Applications in ColdFusion MX Developer’s Guide.

Example

This example uses a COM object to output a list of files. In this example, FFunc is a collection of file2 objects.

<cfobject
    class = FileFunctions.files
    name = FFunc
    action = Create>
<cfset FFunc.Path = "c:\">
<cfset FFunc.Mask = "*.*" >
<cfset FFunc.attributes = 16 >
<cfset x = FFunc.GetFileList()>
<cfloop collection = #FFUNC# item = "file2">
    <cfoutput>		#file2.name# <br> 	</cfoutput>
</cfloop>
<!---Loop through a structure that is used as an associative array: --->
...<!--- Create a structure and loop through its contents. --->
<cfset Departments = StructNew()>
<cfset val = StructInsert(Departments, "John ", "Sales ")>
<cfset val = StructInsert(Departments, "Tom ", "Finance ")>
<cfset val = StructInsert(Departments, "Mike ", "Education ")>
<!--- Build a table to display the contents --->
<cfoutput>
<table cellpadding = "2 " cellspacing = "2 ">
    <tr>
        <td><b>Employee</b></td>
        <td><b>Dept.</b></td>
    </tr>
<!--- Use item to create the variable person to hold value of key
as loop runs. --->
<cfloop collection = #Departments# item = "person ">
    <tr>
        <td>#person#</td>
        <td>#StructFind(Departments, person)#</td>
    </tr>
</cfloop>
</table>
</cfoutput>

Previous


cfmail

Description

Sends an e-mail message that optionally contains query output, using an SMTP server.

Category

Internet Protocol tags

Syntax

<cfmail
    to = "recipient"
    from = "sender"
    cc = "copy_to"
    bcc = "blind_copy_to"
    subject = "msg_subject"
    replyto = "reply_to_addr"
    failto = "fail_message_addr"
    username = "user name"
    password = "password"
    wraptext = "column number"
    charset = "character encoding"
    type = "msg_type"
    mimeattach = "path"
    query = "query_name"
    group = "query_column"
    groupcasesensitive = "yes" or "no"
    startrow = "query_row"
    maxrows = "max_msgs"
    server = "serverspecs"
    port = "port_id"
    mailerid = "headerid"
    timeout = "seconds"
    spoolenable = "yes" or "no"
    debug = "yes" or "no">

(Optional) Mail message body and/or cfhttpparam tags

</cfmail>

See also

cfmailparam, cfmailpart, cfpop, cfftp, cfhttp, cfldap, Wrap; Using ColdFusion with mail servers in Sending and Receiving E-Mail in ColdFusion MX Developer’s Guide

ColdFusion MX 6.1:

  • Added the following attributes: charset, failto, replyto, username, password and wraptext.
  • Added support for multiple mail servers in the server attribute.
  • Added several configuration options to the ColdFusion MX Administrator Mail Settings page.

ColdFusion MX: Added the SpoolEnable attribute.

Attributes

Attribute

Req/Opt

Default

Description

to

Required

Message recipient e-mail addresses:

  • Static address; for example, "support@macromedia.com".
  • Variable that contains an address; for example, "#Form.Email#".
  • Name of a query column that contains an address; for example, "#EMail#". An e-mail message is sent for each returned row.

from

Required

E-mail message sender:

  • A static string; for example, "support@mex.com"
  • A variable; for example, "#GetUser.EMailAddress#" .

This attribute does not have to be a valid Internet address; it can be any text string.

cc

Optional

Address(es) to which to copy the message.

bcc

Optional

Address(es) to which to copy the message, without listing them in the message header.

subject

Required

Message subject. Can be dynamically generated. For example, to send messages that give customers status updates: "Status of Order Number #Order_ID#".

replyto

Optional

Address(es) to which the recipient is directed to send replies.

failto

Optional

Address to which mailing systems should send delivery failure notifications. Sets the mail envelope reverse-path value.

username

Optional

A user name to send to SMTP servers that require authentication. Requires a password attribute.

password

Optional

A password to send to SMTP servers that require authentication. Requires a username attribute.

wraptext

Optional

Do not wrap text

Specifies the maximum line length, in characters of the mail text. If a line has more than the specified number of characters, replaces the last white space character, such as a tab or space, preceding the specified position with a line break. If there are no white space characters, inserts a line break at the specified position. A common value for this attribute is 72.

charset

Optional

Character encoding selected in ColdFusion MX Administrator Mail page; default is UTF-8

Character encoding of the mail message, including the headers. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • iso-2022-kr
  • big5
  • hz-gb-2312
  • euc-cn
  • utf-16

For more information on character encodings, see
www.w3.org/International/O-charset.html.

type

Optional

text/plain

MIME type of the message. Can be a valid MIME media type or one of the following:

  • text: specifies text/plain type.
  • plain: specifies text/plain type.
  • html: specifies text/html type.

For a list of all registered MIME media types, see www.iana.org/assignments/media-types/.

MIMEAttach

Optional

Path of file to attach to message. Attached file is MIME-encoded. ColdFusion attempts to determine the MIME type of the file; use the cfmailparam tag to send an attachment and specify the MIME type.

query

Optional

Name of cfquery from which to draw data for message(s). Use this attribute to send more than one message, or to send query results within a message.

group

Optional

CurrentRow

Query column to use when you group sets of records to send as a message. For example, to send a set of billing statements to a customer, group on "Customer_ID." Case-sensitive. Eliminates adjacent duplicates when data is sorted by the specified field.

groupCase
Sensitive

Optional

No

Boolean. Whether to consider case when using the group attribute. To group on case-sensitive records, set this attribute to Yes.

startRow

Optional

1

Row in a query to start from.

maxRows

Optional

Maximum number of messages to send when looping over a query.

server

Optional

SMTP server address, or (Enterprise edition only) a comma-delimited list of server addresses, to use for sending messages. At least one server must be specified here or in the ColdFusion MX Administrator. A value here overrides the Administrator. A value that includes a port specification overrides the port attribute. See the Usage section for details.

port

Optional

TCP/IP port on which SMTP server listens for requests (normally 25). A value here overrides the Administrator.

mailerID

Optional

ColdFusion MX Application Server

Mailer ID to be passed in X-Mailer SMTP header, which identifies the mailer application.

timeout

Optional

Number of seconds to wait before timing out connection to SMTP server. A value here overrides the Administrator.

spoolEnable

Optional

Specifies whether to spool mail or always send it Immediately. Overrides the ColdFusion MX Administrator Spool mail messages to disk for delivery setting.

  • Yes: saves a copy of the message until the sending operation is complete. Pages that use this option might run slower than those that use the No option.
  • No: queues the message for sending, without storing a copy until the operation is complete. If a delivery error occurs when this option is No, ColdFusion generates an Application exception and logs the error to the mail.log file.

debug

Optional

No
  • Yes: sends debugging output to standard output. By default, if the console window is unavailable, ColdFusion sends output to cf_root\runtime\logs\coldfusion-out.log on server configurations. On J2EE configurations, with JRun, the default location is jrun_home/logs/servername-out.log.
    Caution: If you set this option to Yes, ColdFusion MX writes detailed debugging information to the log, including all message contents, and can generate large logs quickly.
  • No: does not generate debugging output.

Usage

Sends a mail message to the specified address. Mail messages can include attachments. The tag body can include CFML code to generate mail output. The cfmailparam and cfmailpart tags can only be used in the cfmail tag body.

Mail messages can be single or multipart. If you send a multi-part mail message, all message content must be in cfmailpart tags; ColdFusion ignores multipart message text that is not in cfmailpart tags.

Note: The cfmail tag does not make copies of attachments when spooling mail to disk. If you use the cfmail tag to send a message with an attachment with spooling enabled and you use the cffile tag to delete the attachment file, ColdFusion might not send the mail because the mailing process might execute after the file was is deleted. (When this happens, the mail log includes a FileNotFound exception and the e-mail is not sent.) You can prevent this problem by setting SpoolEnable="No" in the attribute or disabling spooling in the ColdFusion MX Administrator. Disabling spooling causes the e-mail to be delivered immediately.

Mail addressing

Mail addresses can have any of the following forms:

Format | Example
user@server | rsmith@company.com
<user@server> | <rsmith@company.com>
DisplayName <user@server> | Rob Smith <rsmith@company.com>
"DisplayName" <user@server> | "Rob Smith" <rsmith@company.com>
user@server (DisplayName) | rsmith@company.com (Rob Smith)

Specifying mail servers

The server attribute can specify one or more mail servers.

Note: If you specify multiple mail servers in ColdFusion MX Standard, the cfmail tag uses only the first server in the specification. ColdFusion logs a warning message to the mail log file and ignores the additional servers.

For each server, you can optionally specify a username, password, and port. These values override the corresponding attributes, if any. The server attribute has the following format:

[user:password@]server[:port],[user:password@]server[:port],....

For example, the following line specifies one server, mail.myco.com that uses the default port and no user or password, and a second server with a user, password, and specific port:

server=mail.myco.com,mail_admin:adm2qzf@mail2.myco.com:24

When you specify multiple mail servers in ColdFusion Enterprise, ColdFusion tries the available servers in the order they are listed until it connects to a server. ColdFusion does not try to connect to a server that was unavailable in the last 60 seconds.

Example

<h3>cfmail Example</h3>

<!--- Delete the surrounding comments to use this example.

<cfif IsDefined("form.mailto")>
    <cfif form.mailto is not ""
                AND form.mailfrom is not ""
                AND form.Subject is not "">
        <cfmail to = "#form.mailto#"
            from = "#form.mailFrom#"
            subject = "#form.subject#">
                This message was sent by an automatic mailer built with cfmail:
                = = = = = = = = = = = = = = = = = = = = = = = = = = =
                #form.body#
        </cfmail>
        <h3>Thank you</h3>
        <p>Thank you, <cfoutput>#mailfrom#: your message, #subject#, has
                been sent to #mailto#</cfoutput>.
    </cfif>
</cfif>
<p>
<form action = "cfmail.cfm">
    <pre>
    TO: 		 <input type = "Text" name = "MailTo">
    FROM: <input type = "Text" name = "MailFrom">
    SUBJECT:	 <input type = "Text" name = "Subject">
    <hr>
    MESSAGE BODY:
    <textarea name ="body" cols="40" rows="5" wrap="virtual"></textarea>
    </pre>
    <!--- Establish required fields. --->
    <input type = "hidden" name = "MailTo_required" value = "You must enter
a recipient">
    <input type = "hidden" name = "MailFrom_required" value = "You must
enter a sender">
    <input type = "hidden" name = "Subject_required" value = "You must enter
a subject">
    <input type = "hidden" name = "Body_required" value = "You must enter
some text">
    <p><input type = "Submit" name = "">
</form>
--->
Next


cfmailparam

Description

Attaches a file or adds a header to an e-mail message.

Category

Internet Protocol tags

Syntax

<cfmail
    to = "recipient"
    subject = "msg_subject"
    from = "sender"
    ...more attributes... >

    <cfmailparam
        file = "file-name"
        type ="media type"
        contentID = "content ID"
        disposition = "disposition type">
    or
    <cfmailparam
        name = "header-name"
         value = "header-value" >
    ...
</cfmail>

See also

cfmail, cfmailpart, cfftp, cfhttp, cfldap, cfpop; Using the cfmailparam tag in Sending and Receiving E-Mail in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.x: Added the Disposition and ContentID attributes.

ColdFusion MX 6.1: Added the type attribute.

Attributes

Attribute

Req/Opt

Default

Description

file

Required if you do not specify name attribute

Attaches a file in a message. Mutually exclusive with name attribute. The file is MIME encoded before sending.

name

Required if you do not specify file attribute

Name of header. Case-insensitive. Mutually exclusive with file attribute.

type

Optional

The MIME media type of the file. Not used with the name attribute. Can be a valid MIME media type or one of the following:

  • text: specifies text/plain type.
  • plain: specifies text/plain type.
  • html: specifies text/html type.

Note: For a list of all registered MIME media types, see www.iana.org/assignments/media-types/.

value

Optional

Value of the header. Not used with the file attribute.

contentID

Optional

The Identifier for the attached file. This ID should be globally unique and is used to identify the file in an IMG or other tag in the mail body that references the file content.

disposition

Optional

attachment

How the attached file is to be handled. Can be one of the following:

  • attachment: presents the file as an attachment.
  • inline: displays the file contents in the message.

Usage

This tag attaches a file or adds a header to an e-mail message. It can only be used in the cfmail tag. You can use multiple cfmailparam tags within a cfmail tag.

You can use this tag to include a file, such as an image, in an HTML mail message. The file can be displayed inline in an HTML message, or as an attachment. To include multiple files, use multiple cfmailparam tags.

To display a file inline in a mail message:

  1. Specify type="html" in the cfmail tag.
  2. Specify disposition="inline" and a ContentID attribute in the cfmailparam tag.
  3. Use a src="cid:ContentIDValue" attribute to identify the content to include in the HTML tag such as the img tag.

The second example shows this use.

Examples

<h3>cfmailparam Examples</h3>
<p>This view-only example uses cfmailparam to 1) add header to a message and 2) attach files and 3) to return a receipt to the sender.</p>
<cfmail from = "peter@domain.com" To = "paul@domain.com"
Subject = "See Important Attachments and Reply">
    <cfmailparam name = "Importance" value = "High">
    Please review the new logo. Tell us what you think.
    <cfmailparam file = "c:\work\readme.txt" type="text/plain">
    <cfmailparam file = "c:\work\logo.gif" type="image/gif">
    <cfmailparam name="Disposition-Notification-To" value="peter@domain.com">
</cfmail>
<p>This view-only example displays an image in the body of
    an HTML message.</p>
<cfmail type="HTML"
        to = "#form.mailto#"
        from = "#form.mailFrom#"
        subject = "Sample inline image">
    <cfmailparam file="C:\Inetpub\wwwroot\web.gif"
        disposition="inline"
        contentID="image1">
    <P>There should be an image here</p>
    <img src="cid:image1">
    <p> After the picture</p>
</cfmail>


cfmailpart

Description

Specifies one part of a multipart e-mail message. Can only be used in the cfmail tag. You can use more than one cfmailpart tag within a cfmail tag.

Category

Internet Protocol tags

Syntax

<cfmail
    ... >
    (Optional cfmailparam entries)
    <cfmailpart
        type="mime type"
        charset="character encoding"
        wraptext="number"
    >
    Mail part contents
</cfmailpart>
    ...
</cfmail>

History

ColdFusion MX 6.1: Added this tag.

See also

cfmail, cfmailparam, cfpop, cfftp, cfhttp, cfldap, cfcontent, Wrap; E-mail in Developing Globalized Applications in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

type

Required

The MIME media type of the part. Can be a can be valid MIME media type or one of the following:

  • text: specifies text/plain type.
  • plain: specifies text/plain type.
  • html: specifies text/html type.

Note: For a list of all registered MIME media types, see www.iana.org/assignments/media-types/.

wraptext

Optional

Do not wrap text

Specifies the maximum line length, in characters of the mail text. If a line has more than the specified number of characters, replaces the last white space character, such as a tab or space, preceding the specified position with a line break. If there are no white space characters, inserts a line break at the specified position. A common value for this attribute is 72.

charset

Optional

Character encoding specified by charset attribute of cfmail tag

The character encoding in which the part text is encoded. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • iso-2022-kr
  • big5
  • hz-gb-2312
  • euc-cn
  • utf-16

For more information on character encodings, see
www.w3.org/International/O-charset.html.

Usage

Use this tag to create mail messages with alternative versions of the message that duplicate the content in multiple formats. The most common use is to send a plain text version of the message that can be read by all mail readers followed by a version formatted in HTML for display by HTML-compatible mail readers. Specify the simplest version first, with more complex versions afterwards. For more information, see www.ietf.org/rfc/rfc2046.txt.

Example

<h3>cfmailpart Example</h3>
<cfmail from = "peter@domain.com" To = "paul@domain.com"
Subject = "Which version do you see?">
    <cfmailpart
        type="text"
        wraptext="74">
            You are reading this message as plain text, because your mail reader
            does not handle HTML text.
    </cfmailpart>>
    <cfmailpart
        type="html">
            <h3>HTML Mail Message</h3>
            <p>You are reading this message as <strong>HTML</strong>.</p>
            <p>Your mail reader handles HTML text.</p>
    </cfmailpart>
</cfmail>


cfmodule

Description

Invokes a custom tag for use in ColdFusion application pages. This tag processes custom tag name conflicts.

Category

Application framework tags

Syntax

<cfmodule
    template = "path"
    name = "tag_name"
    attributeCollection = "collection_structure"
    attribute_name1 = "valuea"
    attribute_name2 = "valueb"
    ...>

See also

cfapplication, cfassociate, cflock; Creating and Using Custom CFML Tags in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior when using this tag within a custom tag: if the attribute_name parameter is the same as a key element within the attributeCollection parameter, ColdFusion now uses the name value that is within the attributeCollection parameter. (Earlier releases did not process this consistently.)

Attributes

Attribute

Req/Opt

Default

Description

template

Required unless name attribute is used

Mutually exclusive with the name attribute. A path to the page that implements the tag.

  • Relative path: expanded from the current page.
  • Absolute path: expanded using ColdFusion mapping.

A physical path is not valid.

name

Required unless template attribute is used

Mutually exclusive with the template attribute. A custom tag name, in the form "Name.Name.Name..." Identifies subdirectory, under the ColdFusion tag root directory, that contains custom tag page. For example (Windows format):

<cfmodule name = "macromedia.Forums40.
GetUserOptions">

This identifies the page GetUserOptions.cfm in the directory CustomTags\macromedia\Forums40 under the ColdFusion root directory.

attributeCollection

Optional

Structure. A collection of key-value pairs that represent attribute names and values. You can specify multiple key-value pairs. You can specify this attribute only once.

attribute_name

Optional

Attribute for a custom tag. You can include multiple instances of this attribute to specify the parameters of a custom tag.

Usage

To name a ColdFusion page that contains the custom tag definition, including its path, use the template attribute. To refer to the custom tag in the ColdFusion installation directory, using dot notation to indicate its location, use the name attribute.

On UNIX systems, ColdFusion searches first for a file with a name that matches the name attribute, but is all lower case. If it does not find the file, it looks for a file name that matches the attribute with identical character casing.

You can use attributeCollection and attribute_name in the same call.

Within the custom tag code, the attributes passed with attributeCollection are saved as independent attribute values, with no indication that they are grouped into a structure by the custom tag’s caller.

Similarly, if the custom tag uses a cfassociate tag to save its attributes, the attributes passed with attributeCollection are saved as independent attribute values, with no indication that they are grouped into a structure by the custom tag’s caller.

If you specify an end tag to cfmodule, ColdFusion calls your custom tag as if it had both a start and an end tag. For more information, see Handling end tags of Creating and Using Custom CFML Tags in ColdFusion MX Developer’s Guide.

Example

<h3>cfmodule Example</h3>
<p>This view-only example shows use of cfmodule to call a custom tag inline.</p>
<p>This example uses a sample custom tag that is saved in myTag.cfm in
the snippets directory. You can also save ColdFusion custom tags in the CFusionMX7\CustomTags directory.
<cfset attrCollection1 = StructNew()>
<cfparam name="attrCollection1.value1" default="22">
<cfparam name="attrCollection1.value2" default="45">
<cfparam name="attrcollection1.value3" default="88">
<!--- Call the tag with CFMODULE with Name--->
<cfmodule
    Template="myTag.cfm"
    X="3"
    attributeCollection=#attrCollection1#
    Y="4">
<!--- Show the code. --->
<HR size="2" color="#0000A0">
<P>Here is one way in which to invoke the custom tag,
using the TEMPLATE attribute.</P>
<cfoutput>#HTMLCodeFormat(" <CFMODULE
    Template=""myTag.cfm""
    X=3
    attributeCollection=##attrCollection1##
    Y=4>")#
</cfoutput>
<P>The result: <cfoutput>#result#</cfoutput>
<!--- Call the tag with CFMODULE with Name.--->
<!---
    <CFMODULE
        Name="myTag"
        X="3"
        attributeCollection=#attrCollection1#
        Y="4">
--->
<!--- Show the code. --->
<HR size="2" color="#0000A0">
<P>Here is another way to invoke the custom tag,
using the NAME attribute.</P>
<cfoutput>#HTMLCodeFormat(" <CFMODULE
        NAME='myTag'
        X=3
        attributeCollection=##attrCollection1##
        Y=4>")#
</cfoutput>
<P>The result: <cfoutput>#result#</cfoutput>
<!--- Call the tag using the shortcut notation. --->
<!---
<CF_myTag
    X="3"
    attributeCollection=#attrCollection1#
    Y="4">
--->

<!--- Show the code. --->
<p>Here is the short cut to invoking the same tag.</p>
<cfoutput>#HTMLCodeFormat(	"<cf_mytag
    x = 3
    attributeCollection = ##attrcollection1##
    y = 4>")#
</cfoutput>
<p>The result: <cfoutput>#result#</cfoutput></p>


cfNTauthenticate

Description

Authenticates a user name and password against the Windows NT domain on which the ColdFusion server is running, and optionally retrieves the user’s groups.

Category

Security tags

Syntax

<cfNTauthenticate
username="username"
password="password"
domain="nt_domain"
result="result variable"
listGroups = "yes" or "no"
throwOnError = "yes" or "no">

See also

cflogin, cfloginuser, IsUserInRole, GetAuthUser

History

ColdFusion MX 7: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
name | Required |  | User’s login name.
password | Required |  | User’s password.
domain | Required |  | Domain against which to authenticate the user. The ColdFusion J2EE server must be running on this domain.
result | Optional | cfntauthenticate | Name of the variable in which to return the results.
listGroups | Optional | No | Boolean value specifying whether to include a comma-delimited list of the user’s groups in the result structure.
throwOnError | Optional | No | Boolean value specifying whether to throw an exception if the validation fails. If this attribute is Yes, ColdFusion throws an error if the user name or password is invalid; the application must handle such errors in a try/catch block or ColdFusion error handler page.

Usage

Use this function to authenticate a user against a Windows NT domain and optionally get the user’s groups. This function does not work with the Microsoft Active Directory directory service, and does nothing on UNIX and Linux systems. You typically use this tag inside a cflogin tag to authenticate the user for a cfloginuser tag, as shown in the example.

Note: ColdFusion must run as a user that has the privilege to authenticate other users in the specified domain.

The structure specified in the result attribute contains the following information:

Field

Value

auth

Whether the user is authenticated:

  • Yes
  • No

groups

A comma-delimited list of the user’s groups in the specified domain. The structure includes this field only if the listGroups attribute is Yes.

name

The user name; equals the tag’s name attribute.

status

The authentication status. One of the following:

  • success
  • UserNotInDirFailure: the user is not listed in the directory.
  • AuthenticationFailure: the user is in the directory, but the password is not valid.

This tag provides two models for handling authentication: status checking and exception handling. If the throwOnError attribute is No, use the result variable’s auth and status fields to determine whether the user was authenticated and, if not, the reason for the failure. If the throwOnError attribute is Yes, ColdFusion throws an exception error if the user is not valid. In this case, use try/catch error handling. The catch block must handle any authentication failure.

Example

The following example uses the auth and status fields to determine whether the user is authenticated and the failure cause. It consists of three files that you put in the same directory:

  • A main cfntauthexample.cfm page that displays the name if the user is authenticated and contains a logout link.
  • A login form page that is displayed if the user is not logged in.
  • The Application.cfm page, which contains all the login, authentication, and logout processing code.

For a full description of login processing, see ColdFusion MX Developer’s Guide. For information on how this example works, see the comments in the code.

Save the following page as cfntauthenticateexample.cfm. To run the example, request this page in your browser or IDE.

<!--- The Application.cfm page, which is processed each time a user
    requests this page, ensures that you log in first. --->
<cfoutput>
    <h3>Welcome #GetAuthUser()#</h3>
    <!--- A link to log out the user. --->
    <a href="#CGI.script_name#?logout=Yes">Log Out</a>
</cfoutput>

Save the following page as loginform.cfm:

<!--- A simple login form that posts back to the page whose request initiated
    the login. --->
<H2>Please Log In</H2>
<cfform action="#CGI.script_name#">
    <!--- j_username and j_password are special names that populate cflogin tag
        variables. --->
    User Name: <cfinput type="text" name="j_username" value="cfqa_user1"
        required="Yes"><br>
    Password: <cfinput type="password" name="j_password" value="cfqa_user1"
        required="Yes"><br>
    Domain: <cfinput type="text" name="domain" value="rnd" required="Yes"><br>
    <input type="submit" value="Log In">
</cfform>

Save the following page as Application.cfm:

<!--- If this page is executing in response to the user clicking a logout link,
        log out the user. The cflogin tag code will then run. --->
<cfif IsDefined("URL.logout") AND URL.logout>
   <cflogout>
</cfif>

<!--- The cflogin body code runs only if a user is not logged in. --->
<cflogin>
    <!--- cflogin variable exists only if login credentials are available. --->
    <cfif NOT IsDefined("cflogin")>
        <!--- Show a login form that posts back to the page whose request
        initiated the login, and do not process the rest of this page. --->
        <cfinclude template="loginform.cfm">
        <cfabort>
    <cfelse>
        <!--- Trim any leading or trailing spaces from the username and password
        submitted by the form. --->
        <cfset theusername=trim(form.j_username)>
        <cfset thepassword=trim(form.j_password)>
        <cfset thedomain=trim(form.domain)>
        <cfntauthenticate username="#theusername#" password="#thepassword#"
            domain="#thedomain#" result="authresult" listgroups="yes">
        <!--- authresult.auth is True if the user is authenticated. --->
        <cfif authresult.auth>
            <!--- Log user in to ColdFusion and set roles to the user's Groups. --->
            <cfloginuser name="#theusername#" password="#thepassword#"
                roles="authresult.groups">
        <cfelse>
            <!--- The user was not authenticated.
                    Display an error message and the login form. --->
            <cfoutput>
                <cfif authresult.status IS "AuthenticationFailure">
                    <!--- The user is valid, but not the password. --->
                    <H2>The password for #theusername# is not correct<br>
                        Please Try again</H2>
                <cfelse>
                    <!--- There is one other status value, invalid user name. --->
                    <H2>The user name #theusername# is not valid<br>
                        Please Try again</H2>
                </cfif>
            </cfoutput>
            <cfinclude template="loginform.cfm">
            <cfabort>
        </cfif>
    </cfif>
</cflogin>


cfobject

Description

Creates a ColdFusion object, of a specified type.

Note: You can enable and disable this tag in the ColdFusion Administrator page, under ColdFusion Security, Sandbox Security.

Category

Extensibility tags

Syntax

The tag syntax depends on the object type. Some types use the type attribute; others do not. See the following sections:

  • cfobject: COM object
  • cfobject: component object
  • cfobject: CORBA object
  • cfobject: Java or EJB object
  • cfobject: web service object

Note: On UNIX, this tag does not support COM objects.

See also

cfargument, cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfproperty, cfreturn; Using Java objects in Integrating J2EE and Java Elements in CFML Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed instantiation behavior: this tag, and the CreateObject function, can now instantiate ColdFusion components (CFCs); you can use them within the cfscript tag.
  • For CORBA object: changed the Naming Service separator format for addresses from a dot to a forward slash. For example, if "context=NameService", for a class, use either of the following formats for the class parameter:
    • "Macromedia/Eng/CF"
    • "Macromedia.current/Eng.current/CF"

    (In earlier releases, the format was "Macromedia.Eng.CF".)

  • For CORBA object: changed the locale attribute; it specifies the Java configuration that contains the properties file.


cfobject: COM object

Description

Creates and manipulates a Component Object Model (COM) object. Invokes a registered automation server object type.

For information on OLEView, and about COM and DCOM, see the Microsoft OLE Development website: www.microsoft.com.

To use this tag, you must provide the object’s program ID or filename, the methods and properties available through the IDispatch interface, and the arguments and return types of the object's methods. For most COM objects, you can get this information with the OLEView utility.

Note: On UNIX, this tag does not support COM objects.

Syntax

<cfobject
    type = "com"
    action = "action"
    class = "program_ID"
    name = "text"
    context = "context"
    server = "server_name">

See also

ReleaseComObject, cfcollection, cfexecute; COM in Developing Globalized Applications in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

Object type:

  • com
  • corba
  • java

(The other object types do not take the type attribute.)

action

Required

  • create: instantiates a COM object (typically, a DLL) before invoking methods or properties.
  • connect: connects to a COM object (typically, an EXE) running on server.

class

Required

Component ProgID for the object to invoke. When using Java stubs to connect to the COM object, the class must be the ProgID of the COM object.

name

Required

String; name for the instantiated component.

context

Optional

  • inproc
  • local
  • remote

On Windows: If not specified, uses Registry setting.

server

Required if context = "Remote"

Server name, using Universal Naming Convention (UNC) or Domain Name Serve (DNS) convention, in one of these forms:

  • \\lanserver
  • lanserver
  • http://www.servername.com
  • www.servername.com
  • 127.0.0.1

Example

<h3>cfobject (COM) Example</h3>
<!--- Create a COM object as an inproc server (DLL). (class = prog-id)--->
<cfobject action = "Create"
    type = "COM"
    class = Allaire.DocEx1.1
    name = "obj">

<!--- Call a method. Methods that expect no arguments should be called
using empty parentheses. --->
<cfset obj.Init()>

<!--- This is a collection object. It should support, at a minimum:
    Property : Count
    Method : Item(inarg, outarg)
    and a special property called _NewEnum
--->
<cfoutput>
    This object has #obj.Count# items.
    <br> <HR>
</cfoutput>

<!--- Get the 3rd object in the collection. --->
<cfset emp = obj.Item(3)>
<cfoutput>
    The last name in the third item is #emp.lastname#.
    <br> <HR>
</cfoutput>
<!---Loop over all the objects in the collection.--->
<p>Looping through all items in the collection:
<br>
<cfloop
    collection = #obj#
    item = file2>
    <cfoutput>Last name: #file2.lastname# <br></cfoutput>
</cfloop>


cfobject: component object

Description

Creates an instance of a ColdFusion component (CFC) object.

Syntax

<cfobject
    name = "variable name"
    component = "component name">

See also

cfcollection, cfcomponent, cfexecute, cfindex, cfreport, cfsearch, cfwddx; Using ColdFusion components in Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
name | Required |  | String; name for the instantiated component. The name must not have a period as the first or last character.
component | Required |  | Name of component to instantiate.

Usage

When the cfobject tag creates an instance of the CFC, ColdFusion executes any constructor code in the CFC; that is, it runs code that is not in the method definitions.

On UNIX systems, ColdFusion searches first for a file with a name that matches the specified component name, but is all lowercase. If it does not find the file, it looks for a filename that matches the component name exactly, with the identical character casing.

Example

<!--- Separate instantiation and method invocation; permits multiple
invocations. --->
<cfobject
name="quoteService"
component="nasdaq.quote">
<cfinvoke
component="#quoteService#"
method="getLastTradePrice"
symbol="macr"
returnVariable="res">
<cfoutput>#res#</cfoutput><br>

<cfinvoke
component="#quoteService#"
method="getLastTradePrice"
symbol="mot"
returnVariable="res">
<cfoutput>#res#</cfoutput>


cfobject: CORBA object

Description

Calls methods on a registered CORBA object.

Syntax

<cfobject
    type = "corba"
    context = "context"
    class = "file or naming service"
    name = "text"
    locale = "type-value arguments">

See also

cfcollection, cfexecute, cfindex, cfreport, cfsearch, cfwddx; CORBA in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

See the History section of the main cfobject tag page.

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

Object type:

  • com
  • corba
  • java

(The other object types do not take the type attribute.)

context

Required

  • ior: ColdFusion uses Interoperable Object Reference (IOR) to access CORBA server.
  • nameservice: ColdFusion uses naming service to access server. This option is valid only with the InitialContext of a VisiBroker Orb.

class

Required

  • If context = "ior": absolute path of file that contains string version of the Interoperable Object Reference (IOR). ColdFusion must be able to read file; it should be local to ColdFusion server or accessible on network.
  • If context = "nameservice": forward slash-delimited naming context for naming service. For example: Allaire//Doc/empobject.

name

Required

String; name for the instantiated component. An application uses it to reference the CORBA object’s methods and attributes.

locale

Optional

Sets arguments for a call to init_orb. Use of this attribute is specific to VisiBroker ORBs. It is available on C++, Version 3.2. The value must be in the form:

locale = " -ORBagentAddr 199.99.129.33  -ORBagentPort 19000"

Each type-value pair must start with a hyphen.

Usage

ColdFusion Enterprise version 4.0 and later supports CORBA through the Dynamic Invocation Interface (DII). To use cfobject with CORBA objects, you must provide the name of the file that contains a string-formatted version of the IOR, or the object’s naming context in the naming service; and the object’s attributes, method names, and method signatures.

User-defined types (for example, structures) are not supported.

Example

<cfobject type = "corba"
  context = "ior"
  class = "c:\\myobject.ior"
  name = "GetName">


cfobject: Java or EJB object

Description

Creates and manipulates a Java and Enterprise Java Bean (EJB) object.

Syntax

<cfobject
    type = "Java"
    action = "Create"
    class = "Java class"
    name = "object name">

See also

cfcollection, cfexecute, cfindex, cfreport, cfsearch, cfwddx; Using Java objects in Integrating J2EE and Java Elements in CFML Applications in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

Object type:

  • com
  • corba
  • java

(The other object types do not take the type attribute.)

action

Required

Create: Creates a Java or WebLogic Environment object.

class

Required

Java class.

name

Required

String; name for the instantiated component.

Usage

To call Java CFXs or Java objects, ColdFusion uses a Java Virtual Machine (JVM) that is embedded in the process. You can configure JVM loading, location and settings in the ColdFusion Administrator.

Any Java class available in the class path that is specified in the ColdFusion Administrator can be loaded and used from ColdFusion, using the cfobject tag.

To access Java methods and fields, do the following steps:

  1. Call the cfobject tag, to load the class. See the example code.
  2. Use the init method with appropriate arguments, to call a constructor. For example:
    <cfset ret = myObj.init(arg1, arg2)>

Calling a public method on the object without first calling the init method results in an implicit call to the default constructor. Arguments and return values can be any Java type (simple, array, object). ColdFusion makes the conversions if strings are passed as arguments, but not if they are received as return values.

Overloaded methods are supported if the number of arguments is different.

Calling EJBs

To create and call EJB objects, use the cfobject tag. In the second example below, the WebLogic JNDI is used to register and find EJBHome instances.

Example

<!--- Example of a Java Object, this cfobject call loads the class MyClass
but does not create an instance object. Static methods and fields
are accessible after a call to cfobject. --->
<cfobject
    action = "create"
    type = "java"
    class = "myclass"
    name = "myobj">

<!---- Example of an EJB - The cfobject tag creates the Weblogic Environment
object, which is used to get InitialContext. The context object is
used to look up the EJBHome interface. The call to Create() results
in getting an instance of stateless session EJB. --->

<cfobject
    action = "create"
    type = "java"
    class = "weblogic/jndi/Environment"
    name = "wlEnv">

<cfset ctx = wlEnv.getInitialContext()>
<cfset ejbHome = ctx.lookup("statelessSession.TraderHome")>
<cfset trader = ejbHome.Create()>
<cfset value = trader.shareValue(20, 55.45)>
<cfoutput>
     Share value = #value#
</cfoutput>
<cfset value = trader.remove()>


cfobject: web service object

Description

Creates a web service proxy object.

Syntax

<cfobject
    webservice= "http://....?wsdl" or "name set in Administrator"
    name = "myobjectname">

See also

cfcollection, cfexecute, cfindex, cfreport, cfsearch, cfwddx; Consuming web services in Using Web Services in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

webservice

Required

URL to web service WSDL file:

  • Absolute URL of web service.
  • Name (string) assigned in the Administrator to the web service.

name

Required

Local name for the web service. String.

Usage

Instantiates a proxy object for a web service. You can enter the absolute URL in this tag, or refer to a web service that is entered in the ColdFusion Administrator. To minimize potential code maintenance, enter the web service in the Administrator, and then refer to that name in this tag.


cfobjectcache

Description

Flushes the query cache.

Category

Database manipulation tags

Syntax

<cfobjectcache
    action = "clear">

See also

cfobject

History

ColdFusion 5: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
action | Required |  | clear: clears queries from the cache in the Application scope.


cfoutput

Description

Displays output that can contain the results of processing ColdFusion variables and functions. Can loop over the results of a database query.

Category

Data output tags

Syntax

<cfoutput
    query = "query_name"
    group = "query_column"
    groupCaseSensitive = "yes" or "no"
    startRow = "start_row"
    maxRows = "max_rows_output">
</cfoutput>

See also

cfcol, cfcontent, cfdirectory, cftable

History

ColdFusion 4.5.0: Added the groupCaseSensitive attribute.

Attributes

Attribute | Req/Opt | Default | Description
query | Optional |  | Name of cfquery from which to draw data for output section.
group | Optional |  | Query column to use to group sets of records. Eliminates adjacent duplicate rows when data is sorted. Use if you retrieved a record set ordered on one or more a query columns. For example, if a record set is ordered on "Customer_ID" in the cfquery tag, you can group the output on "Customer_ID."
groupCaseSensitive | Optional | Yes | Boolean. Whether to consider the case in grouping rows.
startRow | Optional | 1 | Row from which to start output.
maxRows | Optional | displays all rows | Maximum number of rows to display.

Usage

In the cfoutput tag body, ColdFusion treats text that is surrounded by number signs (#) as a ColdFusion variable or function call. For example, the following code displays the text "Hello World!":

<cfset myVar="Hello World!">
<cfoutput>#myVar#</cfoutput>

When you specify a query attribute, this tag loops over the query rows and produces output for each row within the range specified by the startRow and maxRows values, and groups or eliminates duplicate entries as specified by the grouping attribute values, if any. It also sets the query.currentRow variable to the current row being processed.

If you nest cfoutput blocks that process a query, you specify the query and group attributes at the top-most level; you can specify a group attribute for each inner block except the innermost cfoutput block.

This tag requires an end tag.

Example

<!--- EXAMPLE: This example shows how cfoutput operates. --->
<!--- Run a sample query. --->
<cfquery name = "GetCourses" dataSource = "cfdocexamples">
    SELECT Dept_ID, CorName, CorLevel
    FROM courseList
    ORDER by Dept_ID, CorLevel, CorName
</cfquery>
<h3>cfoutput Example</h3>
<p>cfoutput tells ColdFusion Server to begin processing, and then to hand back control of page rendering to the web server.
<p>For example, to show today's date, you could write #DateFormat("#Now()#"). If you enclosed that expression in cfoutput, the result would be<cfoutput>#DateFormat(Now())#</cfoutput>.

<p>In addition, cfoutput may be used to show the results of a query operation, or only a partial result, as shown:

<p>There are <cfoutput>#getCourses.recordCount#</cfoutput> total records in our query. Using the maxRows parameter, we are limiting our display to 4 rows.
<p><cfoutput query = "GetCourses" maxRows = 4>
    #Dept_ID# #CorName# #CorLevel#<br>
</cfoutput>

<p>EXAMPLE: The next example uses the group attribute to eliminate duplicate lines from a list of course levels taught in each department.</p>
<p><cfquery name = "GetCourses" dataSource = "cfdocexamples">
    SELECT Dept_ID, CorLevel
    FROM courseList
    ORDER by Dept_ID, CorLevel
</cfquery>
<p><cfoutput query = "GetCourses" group="CorLevel" GroupCaseSensitive="True">
#Dept_ID# #CorLevel#<br>
</cfoutput>

<p>cfoutput can also show the results of a more complex expression,
such as getting the day of the week from today's date. We first
extract the integer representing the Day of the Week from
the server function Now() and then apply the result to
the DayofWeekAsString function:

<br>Today is #DayofWeekAsString(DayofWeek(Now()))#
<br>Today is <cfoutput>#DayofWeekAsString(DayofWeek(Now()))#</cfoutput>
<p> EXAMPLE: This last example shows nested cfoutput tags:<p>
<cfquery datasource="cfdocexamples" name="empSalary">
SELECT Emp_ID, firstname, lastname, e.dept_id, salary, d.dept_name
FROM employee e, departmt d
WHERE e.dept_id = d.dept_id
ORDER BY d.dept_name
</cfquery>

<!--- Outer cfoutput. --->
<cfoutput query="empSalary" group="dept_id">
   <h2>#dept_name#</h2>
   <table width="95%" border="2" cellspacing="2" cellpadding="2" >
    <tr>
     <th>Employee</th>
     <th>Salary</th>
    </tr>
    <cfset deptTotal = 0 >
    <!--- Inner cfoutput. --->
    <cfoutput>
    <tr>
          <td>#empSalary.lastname#, #empSalary.firstname#</td>
          <td align="right">#DollarFormat(empSalary.salary)#</td>
        </tr>
    <cfset deptTotal = deptTotal + empSalary.salary>
    </cfoutput>
    <tr>
          <td align="right">Total</td>
      <td align="right">#DollarFormat(deptTotal)#</td>
        </tr>
     <cfset deptTotal = 0>
   </table>
</cfoutput>


cfparam

Description

Tests for the existence of a parameter (that is, a variable), validates its data, and, if a default value is not assigned, optionally provides one.

Category

Variable manipulation tags

Syntax

<cfparam
    name = "param_name"
    type = "data_type"
    default = "value"
max = "value"
min = "value"
pattern = "regular expression">

See also

cfcookie, cfregistry, cfsavecontent, cfschedule, cfset; Validating data with the IsValid function and the cfparam tag in Validating Data in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added min, max, and pattern attributes.
  • Added creditcard, email, eurodate, float, integer, range, regex, regular_expression, ssn, social_security_number, time, URL, USdate, and zipcode attributes of the type attribute.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

Name of the parameter (variable) to test (such as "Client.Email " or "Cookie.BackgroundColor "). If omitted, and if the parameter does not exist, an error is thrown.

type

Optional

any

The valid format for the data; one of the following. For detailed information on validation algorithms, see Validating form data using hidden fields in Validating Data in ColdFusion MX Developer’s Guide.

  • any: any type of value.
  • array: an array of values.
  • binary: a binary value.
  • boolean: a Boolean value: yes, no, true, false, or a number.
  • creditcard: a 13-16 digit number conforming to the mod10 algorithm.
  • date or time: a date-time value.
  • email: a valid e-mail address.
  • eurodate: a date-time value. Any date part must be in the format dd/mm/yy, The format can use /, -, or . characters as delimiters.
  • float or numeric: a numeric value.
  • guid: a Universally Unique Identifier of the form "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" where ‘X’ is a hexadecimal number.
  • integer: an integer.
  • query: a query object.
  • range: a numeric range, specified by the min and max attributes.
  • regex or regular_expression: matches input against pattern attribute.
  • ssn or social_security_number: a U.S. social security number.
  • string: a string value or single character.
  • struct: a structure.
  • telephone: a standard U.S. telephone number.
  • URL: an http, https, ftp, file, mailto, or news URL.
  • UUID: a ColdFusion Universally Unique Identifier, formatted ‘XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXX’, where ‘X’ is a hexadecimal number. See CreateUUID.
  • USdate: a U.S. date of the format mm/dd/yy, with 1-2 digit days and months, 1-4 digit years.
  • variableName: a string formatted according to ColdFusion variable naming conventions.
  • xml: XML objects and XML strings.
  • zipcode: U.S., 5- or 9-digit format ZIP codes.

default

Optional

Value to set parameter to if it does not exist. Any expression used for the default attribute is evaluated, even if the parameter exists. The result is not assigned if the parameter exists, but if the expression has side effects, they still occur.

max

Optional

The maximum valid value; used only for range validation.

min

Optional

The minimum valid value; used only for range validation.

pattern

Optional

A JavaScript regular expression that the parameter must match; used only for regex or regular_expression validation.

Usage

You can use this tag to make the following tests:

  • To test whether a required variable exists, use this tag with only the name attribute. If it does not exist, ColdFusion MX stops processing the page and returns an error.
  • To test whether a required variable exists, and that it is of the specified type, use this tag with the name and type attributes. If the variable does not exist or its value is not of the specified type, ColdFusion returns an error.
  • To set a default value for the variable, use this tag with the name and default attributes. If the variable does not exist, it is created and set to the default attribute value. If the variable exists, processing continues; the value is not changed.

If you specify variableName for the type attribute, the parameter’s value must be a string that is in ColdFusion variable name format; that is, starts with a letter, underscore (_), or Unicode currency symbol, and contains letters, numbers, underscores, periods, and Unicode currency symbols, only. ColdFusion does not check whether the parameter value corresponds to an existing ColdFusion variable.

Tip: To improve performance, avoid using the cfparam tag in ColdFusion functions, including in CFC methods. Instead, place the cfparam tags in the body of the CFML pages.

Example

<!--- This example shows how to use CFPARAM to define default values for page
    variables. -------->
<cfparam name = "storeTempVar" default = "my default value">
<cfparam name = "tempVar" default = "my default value">

<!--- Check if form.tempVar was passed. --->
<cfif IsDefined("form.tempVar") is "True">
    <!--- Check if form.tempVar is not blank. --->
    <cfif form.tempVar is not "">
        <!--- If not, set tempVar to value of form.tempVar --->
        <cfset tempVar = form.tempVar>
    </cfif>
</cfif>

<body>
<h3>cfparam Example</h3>
<p>cfparam is used to set default values so that a developer does not have to
check for the existence of a variable using a function like IsDefined.

<p>The default value of our tempVar is
    "<cfoutput>#StoreTempVar# </cfoutput>"

<!--- Check if tempVar is still the same as StoreTempVar.
and that tempVar is not blank --->
<cfif tempVar is not #StoreTempVar#
    and tempVar is not "">
        <h3>The value of tempVar has changed: the new value is
        <cfoutput>#tempVar#</cfoutput></h3>
</cfif>

<p>
<form action = "cfparam.cfm" method = "post">
    Type in a new value for tempVar, and hit submit:<br>
    <input type = "Text" name = "tempVar">
    <input type = "Submit" name = "" value = "submit">
</form>


cfpop

Description

Retrieves or deletes e-mail messages from a POP mail server.

Category

Internet Protocol tags

Syntax

<cfpop
    server = "servername"
    port = "port_number"
    username = "username"
    password = "password"
    action = "action"
    name = "queryname"
    messageNumber = "number"
    uid = "number"
    attachmentPath = "path"
    timeout = "seconds"
    maxRows = "number"
    startRow = "number"
    generateUniqueFilenames = "yes" or "no"
    debug = "yes" or "no">

See also

cfftp, cfhttp, cfldap, cfmail, cfmailparam, SetLocale; Sending and Receiving E-Mail in ColdFusion MX Developer’s Guide.

History

ColdFusion MX 6.1:

  • Added support for multipart mail messages with Text and HTML parts.
  • Changed the attachment name separator: the TAB character is now the separator between attachment names in the attachments and attachmentfiles query fields if a message has multiple attachments. This behavior is identical to ColdFusion 5 and earlier versions.

ColdFusion MX: Changed the attachment name separator: the comma separates names in the attachments and attachmentfiles query fields if a message has multiple attachments.

Attributes

Attribute

Req/Opt

Default

Description

server

Required

POP server identifier:

  • A host name; for example, "biff.upperlip.com".
  • An IP address; for example, "192.1.2.225".

port

Optional

110

POP port.

username

Optional

A user name.

password

Optional

Password that corresponds to username.

action

Optional

getHeaderOnly
  • getHeaderOnly: returns message header information only
  • getAll: returns message header information, message text, and attachments if attachmentPath is specified
  • delete: deletes messages on POP server

name

Required if action = "getAll" or "getHeaderOnly"

Name for query object that contains the retrieved message information.

message
Number

Message number or comma-delimited list of message numbers to get or delete. Invalid message numbers are ignored.

Ignored if uid is specified.

uid

UID or a comma-delimited list of UIDs to get or delete. Invalid UIDs are ignored.

attachmentPath

Optional

If action="getAll", specifies a directory in which to save any attachments. If the directory does not exist, ColdFusion creates it.

If you omit this attribute, ColdFusion does not save any attachments. If you specify a relative path, the path root is the ColdFusion temporary directory, which is returned by the GetTempDirectory function.

timeout

Optional

60

Maximum time, in seconds, to wait for mail processing.

maxRows

Optional

retrieves all available rows

Number of messages to return or delete, starting with the number in startRow. Ignored if messageNumber or uid is specified.

startRow

Optional

1

First row number to get or delete. Ignored if messageNumber or uid is specified.

generate
Unique
Filenames

Optional

No
  • Yes: generate unique filenames for files attached to an e-mail message, to avoid naming conflicts when files are saved.
  • No

debug

Optional

No
  • Yes: sends debugging output to standard output. By default, if the console window is unavailable on server configurations, ColdFusion sends output to cf_root/runtime/logs/coldfusion-out.log. On J2EE configurations, with JRun, the default location is jrun_home/logs/servername-out.log.
    Caution: If you set this option to Yes, ColdFusion MX writes detailed debugging information to the log, including all retrieved message contents, and can generate large logs quickly.
  • No: does not generate debugging output.

Usage

The cfpop tag retrieves one or more mail messages from a POP server and populates a ColdFusion query object with the resulting messages, one message per row. Alternatively, it deletes one or more messages from the POP server.

Note: When the cfpop tag encounters malformed mail messages, it does not generate errors; instead, it returns empty fields.

To optimize performance, two retrieve options are available. Message header information is typically short, and therefore quick to transfer. Message text and attachments can be very long, and therefore take longer to process.

cfpop query variables

The following table describes the variables that provide information about the query that is returned by cfpop:

Variable names | Description
queryname.recordCount | Number of records returned by query
queryname.currentRow | Current row that cfoutput is processing
queryname.columnList | List of column names in query
queryname.UID | Unique identifier for the e-mail message file

Query message header and body columns

The following table lists the message header and body columns that are returned if action = "getHeaderOnly" or "getAll":

Column name | getHeaderOnly returns | getAll returns
queryname.date | yes | yes
queryname.from | yes | yes
queryname.messagenumber | yes | yes
queryname.messageid | yes | yes
queryname.replyto | yes | yes
queryname.subject | yes | yes
queryname.cc | yes | yes
queryname.to | yes | yes
queryname.body | no | yes
queryname.textBody | no | yes
queryname.HTMLBody | no | yes
queryname.header | yes | yes
queryname.attachments | no | yes
queryname.attachmentfiles | no | yes

If the mail message includes a part with a Content-Type of text/plain, the queryname.textBody column contains the part’s message content. If the mail message includes a part with a Content-Type of text/HTML, the queryname.HTMLBody column contains the part’s message content. If no Content-Type matches these types, the columns are empty. The queryname.Body column always contains the first message body found.

The queryname.attachments column contains a tab-separated list of all the attachment names. The queryname.attachmentfiles column contains a tab-separated list of the locations of the attachment files. Use the cffile tag to delete these temporary files when you have processed them.

To create a ColdFusion date/time object from the date-time string that is extracted from a mail message in the queryname.date column, use the following table:

Locale | How to create a ColdFusion date/time object from queryname.date
English (US) | Use the ParseDateTime function. If you specify the pop-conversion attribute, the function adjusts the date/time object to UTC.
Other | Extract the date part of string; pass it to the LSParseDateTime function.

Note: To set the default display format of date, time, number, and currency values, use the SetLocale function.

For more information on cfpop, see Sending and Receiving E-Mail in ColdFusion MX Developer’s Guide.

Example

<!--- This view-only example shows the use of cfpop. --->
<h3>cfpop Example</h3>
<p>cfpop lets you retrieve and manipulate mail in a POP3 mailbox.
This view-only example shows how to create one feature of
a mail client, to display the mail headers in a POP3 mailbox.
<p>To execute this, un-comment this code and run with a mail-enabled CF Server.
<!---
<cfif IsDefined("form.server ")>
    <!--- Make sure server, username are not empty. --->
    <cfif form.server is not "" and form.username is not "">
        <cfpop server = "#form.popserver# " username = #form.username# password = #form.pwd#
        action = "getHeaderOnly" name = "GetHeaders ">
        <h3>Message Headers in Your Inbox</h3>
        <p>Number of Records:
        <cfoutput>#GetHeaders.recordCount#</cfoutput></p>

        <ul>
            <cfoutput query = "GetHeaders">
            <li>Row: #currentRow#: From: #From# -- Subject: #Subject#
            </cfoutput>
        </ul>
    </cfif>
</cfif>

<form action = "cfpop.cfm " method = "post">
    <p>Enter your mail server:
    <p><input type = "Text" name = "popserver">
    <p>Enter your username:
    <p><input type = "Text" name = "username">
    <p>Enter your password:
    <p><input type = "password" name = "pwd">
    <input type = "Submit" name = "get message headers">
</form>
--->


cfprocessingdirective

Description

Provides the following information to ColdFusion about how to process the current page:

  • Specifies whether to remove excess whitespace character from ColdFusion generated content in the tag body.
  • Identifies the character encoding (character set) of the page contents.

Category

Data output tags, Page processing tags

Syntax

<cfprocessingdirective
    pageencoding = "page-encoding literal string" />
or
<cfprocessingdirective
    suppressWhiteSpace = "yes" or "no"
    pageEncoding = "page-encoding literal string">
    CFML tags
</cfprocessingdirective>

See also

cfcol , cfcontent, cfoutput, cfsetting, cfsilent, cftable, SetEncoding; Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed suppresswhitespace attribute value behavior: you can specify the suppresswhitespace attribute value as a string variable. (ColdFusion 5 supported setting it only as a constant.)
  • Added the pageEncoding attribute.

Attributes

Attribute

Req/Opt

Default

Description

suppressWhiteSpace

Optional

Boolean; whether to suppress white space characters within the cfprocessingdirective block that are generated by CFML tags and often do not affect HTML appearance. Does not affect any white space in HTML code.

pageEncoding

Optional

Character encoding identified by the page byte order mark, if any; otherwise, system default encoding

A string literal; cannot be a variable. Identifies the character encoding of the current CFML page. This attribute affects the entire page, not just the cfprocessing tag body. The value may be enclosed in single- or double-quotation marks, or none.

The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information on character encodings, see
www.w3.org/International/O-charset.html.

Usage

The cfprocssingdirective tag has limitations that depend on the attribute you use. For this reason, Macromedia recommends that you include either the pageencoding or suppresswhitespace attribute in a cfprocessingdirective tag, not both. To specify both values, use separate tags.

In a ColdFusion component (.cfc file), the cfprocessingdirective tag must follow the cfcomponent tag.

If you use the pageEncoding attribute, the following rules apply:

  • You must put the tag within the first 4096 bytes of a page. It can be positioned after a cfsetting or cfsilent tag.
  • If you use the tag on a page that includes other pages by using the cfinclude or cfmodule tags, custom tag invocation, and so on, the tag has no effect on the included pages.
  • You cannot embed the tag within conditional logic, because the pageEncoding attribute is evaluated when ColdFusion compiles a page (not when it executes the page). For example, the following code has no effect at execution time, because the cfprocessingdirective tag has already been evaluated:
    <cfif dynEncoding is not "dynamic encoding is not possible">
    <cfprocessingdirective pageencoding=#dynEncoding#>
</cfif>
  • If you have multiple cfprocessingdirective tags in one page that specify the pageEncoding attribute, they must all specify the same value; if not, ColdFusion throws an error.
  • If you specify only the pageencoding attribute, do not use a separate end tag.
  • ColdFusion accepts character encoding names that are supported by the Java platform. If an invalid name is specified, ColdFusion throws an InvalidEncodingSpecification exception.
  • If a page has a byte order mark (BOM), and a pageencoding attribute specifies an encoding that differs from the BOM, ColdFusion generates an error.

The following rules apply to the suppressWhiteSpace attribute:

  • You can specify the suppresswhitespace attribute value as a constant or a variable. To use a variable: define the variable (for example, whitespaceSetting), assign it the value yes or no, and code a statement such as the following:
    <!--- ColdFusion allows suppression option to be set at runtime --->
<cfprocessingdirective suppresswhitespace=#whitespaceSetting#>
    code to whose output the setting is applied
</cfprocessingdirective>
  • The suppresswhitespace attribute only affects code that you put between the <cfprocessingdirective> begin tag and the </cfprocessingdirective> end tag.

The following example shows the use of a nested cfprocessingdirective tag. The outer tag suppresses unnecessary whitespace during computation of a large table; the inner tag retains whitespace, to output a preformatted table.

Example

<cfprocessingdirective suppressWhiteSpace = "Yes">
    <!--- CFML code --->
    <cfprocessingdirective suppressWhiteSpace = "No">
        <cfoutput>#table_data#
        </cfoutput>
    </cfprocessingdirective>
</cfprocessingdirective>

The following example shows the use of the pageencoding attribute:

<cfprocessingdirective pageencoding = "shift_jis">


cfprocparam

Description

Defines stored procedure parameters. This tag is nested within a cfstoredproc tag.

Category

Database manipulation tags

Syntax

<cfprocparam
    type = "in" or "out" or "inout"
    variable = "variable name"
    value = "parameter value"
    CFSQLType = "parameter datatype"
    maxLength = "length"
    scale = "decimal places"
    null = "yes" or "no">

See also

cfinsert, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cftransaction, cfupdate; Optimizing ColdFusion applications in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • The maxrows attribute is obsolete.
  • Changed the dbvarname attribute behavior: it is now ignored for all drivers. ColdFusion MX uses JDBC 2.2 and does not support named parameters.
  • Changed the maxLength attribute behavior: it now applies to IN and INOUT parameter values.

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

in
  • in: the parameter is used to send data to the database system only. Passes the parameter by value.
  • out: the parameter is used to receive data from the database system only. Passes the parameter as a bound variable.
  • inout: the parameter is used to send and receive data. Passes the parameter as a bound variable.

variable

Required if type = "OUT" or "INOUT"

ColdFusion variable name; references the value that the output parameter has after the stored procedure is called. This is ignored for IN parameters.

value

Required if type = "IN"

Value that ColdFusion passes to the stored procedure.This is optional for INOUT parameters.

CFSQLType

Required

SQL type to which the parameter (any type) is bound. ColdFusion supports the following values, where the last element of the name corresponds to the SQL data type. Different database systems might support different subsets of this list. See your DBMS documentation for information on supported parameter types.

  • CF_SQL_BIGINT
  • CF_SQL_BIT
  • CF_SQL_BLOB
  • CF_SQL_CHAR
  • CF_SQL_CLOB
  • CF_SQL_DATE
  • CF_SQL_DECIMAL
  • CF_SQL_DOUBLE
  • CF_SQL_FLOAT
  • CF_SQL_IDSTAMP
  • CF_SQL_INTEGER
  • CF_SQL_LONGVARCHAR
  • CF_SQL_MONEY
  • CF_SQL_MONEY4
  • CF_SQL_NUMERIC
  • CF_SQL_REAL
  • CF_SQL_REFCURSOR
  • CF_SQL_SMALLINT
  • CF_SQL_TIME
  • CF_SQL_TIMESTAMP
  • CF_SQL_TINYINT
  • CF_SQL_VARCHAR

For a mapping of ColdFusion SQL data types to JDBC data types, See also cfqueryparam.

maxLength

Optional

0

Maximum length of a string or character IN or INOUT value attribute. A maxLength of 0 allows any length. The maxLength attribute is not required when specifying type=out.

scale

Optional

0

Number of decimal places in numeric parameter. A scale of 0 limits the value to an integer.

null

Optional

No

Whether the parameter is passed in as a null value. Not used with OUT type parameters.

  • Yes: tag ignores the value attribute.
  • No

Usage

Use this tag to identify stored procedure parameters and their data types. Code one cfprocparam tag for each parameter. The parameters that you code vary based on parameter type and DBMS. ColdFusion MX supports positional parameters only and you must code cfprocparam tags in the same order as the associated parameters in the stored procedure definition.

Output variables are stored in the ColdFusion variable specified by the variable attribute.

You cannot use the cfprocparam tag for Oracle 8 and 9 reference cursors. Instead, use the cfprocresult tag.

Example

The following example shows how to invoke an Oracle 8 PL/SQL stored procedure. It makes use of Oracle 8 support of the Reference Cursor type.

The following package, Foo_Data, houses a procedure refcurproc that declares output parameters as Reference Cursor:

  • Parameter pParam1 returns the rows in the EMP table
  • Parameter pParam2 returns the rows in the DEPT table

The procedure declares one input parameter as an integer, and one output parameter as a two-byte char varying type. Before the cfstoredproc tag can call this procedure, it must be created, compiled, and bound in the RDBMS environment.

CREATE OR REPLACE PACKAGE Foo_Data AS
     TYPE EmpTyp IS REF CURSOR RETURN Emp%ROWTYPE;
     TYPE DeptTyp IS REF CURSOR RETURN Dept%ROWTYPE;
 PROCEDURE refcurproc(pParam1 in out EmpTyp, pParam2 in out DeptTyp,
pParam3 in integer, pParam4 out varchar2);
END foo_data;

CREATE OR REPLACE PACKAGE BODY Foo_Data AS
    PROCEDURE RefCurProc(pParam1 in out EmpTyp,
           pParam2 in out DeptTyp,
           pParam3 in integer,
           pParam4 out varchar2) IS
    BEGIN
        OPEN pParam1 FOR select * from emp;
        OPEN pParam2 FOR select * from dept;
        IF pParam3 = 1
        THEN
            pParam4 : = 'hello';
        ELSE
            pParam4 : = 'goodbye';
        END IF;
    END RefCurProc;
END Foo_Data;

The following CFML example shows how to invoke the RefCurProc procedure using cfstoredproc, cfprocparam, and cfprocresult:

<cfstoredproc  procedure = "foo_data.refcurproc"
    dataSource = "oracle8i"
    username = "scott"
    password = "tiger"
    returnCode = "No">

    <cfprocparam type = "Out" CFSQLType = "CF_SQL_REFCURSOR"
        variable = "param1">
    <cfprocparam type = "Out" CFSQLType = "CF_SQL_REFCURSOR"
        variable = "param2">
    <cfprocparam type = "IN" CFSQLType = "CF_SQL_INTEGER" value = "1">

    <cfprocparam type = "OUT" CFSQLType = "CF_SQL_VARCHAR"
        variable = "FOO">
    <cfprocresult name = "rs1">
    <cfprocresult name = "rs2" resultSet = "2">
</cfstoredproc>

<b>The first result set:</b><br>
<hr>
<cftable query = "rs1" colHeaders HTMLTable border = "1">
    <cfcol header = "EMPNO" text = "#EMPNO#">
    <cfcol header = "EMPLOYEE name" text = "#ENAME#">
    <cfcol header = "JOB" text = "#JOB#">
    <cfcol header = "SALARY" text = "#SAL#">
    <cfcol header = "DEPT NUMBER" text = "#DEPTNO#">
</cftable>

<hr>
<b>The second result set:</b><br>

<cftable query = "rs2" colHeaders HTMLTable border = "1">
    <cfcol header = "DEPT name" text = "#DNAME#">
    <cfcol header = "DEPT NUMBER" text = "#DEPTNO#">
</cftable>
<hr>
<cfoutput>
    <b>The output parameter is:</b>'#FOO#'
</cfoutput>


cfprocresult

Description

Associates a query object with a result set returned by a stored procedure. Other ColdFusion tags, such as cfoutput and cftable, use this query object to access the result set. This tag is nested within a cfstoredproc tag.

Category

Database manipulation tags

Syntax

<cfprocresult
    name = "query_name"
    resultSet = "1-n"
    maxRows = "maxrows">

See also

cfinsert, cfprocparam, cfquery, cfqueryparam, cfstoredproc, cftransaction, cfupdate; Optimizing database use in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
name | Required |  | Name for the query result set.
resultSet | Optional | 1 | Names one result set, if stored procedure returns more than one.
maxRows | Optional | -1 (All) | Maximum number of rows returned in result set.

Usage

To enable access to data returned by the stored procedure, specify one or more cfprocresult tags. If the stored procedure returns more than one result set, use the resultSet attribute to specify which of the stored procedure’s result sets to return.

The resultSet attribute must be unique within the scope of the cfstoredproc tag. If you specify a result set twice, the second occurrence overwrites the first.

CFML supports Oracle 8 and 9 Reference Cursor type, which passes a parameter by reference. Parameters that are passed this way can be allocated and deallocated from memory within the execution of one application. To use reference cursors in packages or stored procedures, use the cfprocresult tag. This causes the ColdFusion JDBC database driver to put Oracle reference cursors into a result set. (You cannot use this method with Oracle’s ThinClient JDBC drivers.)

Example

<!--- This example executes a Sybase stored procedure that returns three
result sets, two of which we want. The stored procedure returns
status code and one output parameter, which we display. We use
named notation for parameters. --->
<!--- cfstoredproc tag --->
<cfstoredproc procedure = "foo_proc"
        dataSource = "MY_SYBASE_TEST"	 username = "sa"
        password = ""	 dbServer = "scup" 	dbName = "pubs2"
        returnCode = "Yes"	 debug = "Yes">
    <!--- cfprocresult tags --->
    <cfprocresult name = RS1>
    <cfprocresult name = RS3 resultSet = 3>
    <!--- cfprocparam tags --->
    <cfprocparam type = "IN"
        CFSQLType = CF_SQL_INTEGER
            value = "1" 	dbVarName = @param1>

    <cfprocparam type = "OUT"	 CFSQLType = CF_SQL_DATE
        variable = FOO dbVarName = @param2>
    <!--- Close the cfstoredproc tag. --->
</cfstoredproc>
<cfoutput>
    The output param value: ’#foo#’<br>
</cfoutput>
<h3>The Results Information</h3>
<cfoutput query = RS1>#name#,#DATE_COL#<br>
</cfoutput>
<p>
<cfoutput>
    <hr>
    <p>Record Count: #RS1.recordCount# <p>Columns: #RS1.columnList#
    <hr>
</cfoutput>
<cfoutput query = RS3>#col1#,#col2#,#col3#<br>
</cfoutput>
<p>
<cfoutput>
    <hr>
    <p>Record Count: #RS3.recordCount# <p>Columns: #RS3.columnList#
    <hr>
    The return code for the stored procedure is:
’#cfstoredproc.statusCode#’<br>
</cfoutput>
...


cfproperty

Description

Defines properties of a ColdFusion component (CFC). Used to create complex data types for web services. The attributes of this tag are exposed as component metadata and are subject to inheritance rules.

Category

Extensibility tags

Syntax

<cfproperty
    name="name"
    type="type"
    required="boolean"
    default="default value"
    displayname="descriptive name"
    hint="extended description"
    >

See also

cfargument, cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfobject, cfreturn; Documenting CFCs in Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

A string; a property name. Must be a static value.

type

Optional

any

A string; identifies the property data type:

  • any
  • array
  • binary
  • boolean
  • date
  • guid: the argument must be a UUID or GUID of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where each x is a character representing a hexadecimal number (0-9A-F).
  • numeric
  • query
  • string
  • struct
  • uuid: The argument must be a ColdFusion UUID of the form xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx where each x is a character representing a hexadecimal number (0-9A-F).
  • variableName: a string formatted according to ColdFusion variable naming conventions.
  • a component name: if the type attribute value is not one of the preceding items, ColdFusion treats it as the name of a ColdFusion component. When The function executes, it generates an error if the argument that is passed in is not a CFC with the specified name.

required

Optional

no

Whether the parameter is required:

  • yes
  • no

default

Optional

If no property value is set when the component is used for a web service, specifies a default value.

If this attribute is present, the required attribute must be set to "no" or not specified.

displayname

Optional

A value to be displayed when using introspection to show information about the CFC. The value appears in parentheses following the property name.

hint

Optional

Text to be displayed when using introspection to show information about the CFC. This attribute can be useful for describing the purpose of the parameter.

Usage

You must position cfproperty tags at the beginning of a component, above executable code and function definitions.

If a component is not used as a web service, The cfproperty only provides metadata information when the component is viewed using introspection; for example, by opening the CFC file directly in the browser. It does not define variables or set values that you can then use in your component.

For web services that you create in ColdFusion, the cfproperty tag defines complex variables used by the web service.

Example

The following code defines a component in the file address.cfc that contains properties that represent a street address:

<cfcomponent>
    <cfproperty name="Number" type="numeric">
    <cfproperty name="Street" type="string">
    <cfproperty name="City" type="string">
    <cfproperty name="State" type="string">
    <cfproperty name="Country" type="string">
</cfcomponent>

This component represents a complex data type that can be used in a component that is exported as a web service, such as the following:

<cfcomponent>
    <cffunction name="echoAddress" returnType="address" access="remote">
            <cfargument name="input" type="address">
            <cfreturn arguments.input>
    </cffunction>
</cfcomponent>


cfquery

Description

Passes queries or SQL statements to a data source.

Macromedia recommends that you use the cfqueryparam tag within every cfquery tag, to help secure your databases from unauthorized users. For more information, see Security Bulletin ASB99-04, "Multiple SQL Statements in Dynamic Queries," in the Macromedia Security Zone, www.macromedia.com/devnet/security/security_zone/asb99-04.html, and Accessing and Retrieving Data in ColdFusion MX Developer’s Guide.

Category

Database manipulation tags

Syntax

<cfquery
    name = "query_name"
    dataSource = "ds_name"
    dbtype = "query"
    username = "username"
    password = "password"
    maxRows = "number"
    blockFactor = "blocksize"
    timeout = "seconds"
    cachedAfter = "date"
    cachedWithin = "timespan"

    Either of the following:
        debug = "yes" or "no"
    or:
        debug
>
result = "result_name"
</cfquery>

See also

cfinsert, cfprocparam, cfprocresult, cfqueryparam, cfstoredproc, cftransaction, cfupdate; Optimizing database use in Designing and Optimizing a ColdFusion Application and Chapters 19–22 in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added the result attribute for specifying an alternate name for the structure that holds the result variables.
  • Added result variables for the SQL statement executed (sql), the number of records returned (recordcount), whether the query was cached (cached), an array of cfqueryparam values (sqlparameters), and the list of columns in the returned query (columnlist).

ColdFusion MX:

  • Changed Query of Queries behavior: it now supports a larger subset of standard SQL.
  • Changed dot notation support: ColdFusion now supports dot notation within a record set name. ColdFusion interprets such a name as a structure.
  • Deprecated the connectString, dbName, dbServer, provider, providerDSN, and sql attributes, and all values of the dbtype attribute except query. They do not work, and might cause an error, in releases later than ColdFusion 5.
  • New query object variable: cfquery.ExecutionTime.
  • No longer supports native drivers. It now uses JDBC (and ODBC-JDBC bridge) for database connectivity.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

Name of query. Used in page to reference query record set. Must begin with a letter. Can include letters, numbers, and underscores.

dataSource

Required unless dbtype=query.

Name of data source from which query gets data. You must specify either dbtype or dataSource.

dbtype

Optional

Use this value to specify the results of a query as input. You must specify either dbtype or dataSource.

username

Optional

Overrides username in data source setup.

password

Optional

Overrides password in data source setup.

maxRows

Optional

-1 (All)

Maximum number of rows to return in record set.

blockFactor

Optional

1

Maximum rows to get at a time from server. Range: 1 - 100. Might not be supported by some database systems.

timeout

Maximum number of seconds that each action of a query is permitted to execute before returning an error. The cumulative time may exceed this value.

For JDBC statements, ColdFusion sets this attribute. For other drivers, check driver documentation.

cachedAfter

Optional

Date value (for example, April 16, 1999, 4-16-99). If date of original query is after this date, ColdFusion uses cached query data. To use cached data, current query must use same SQL statement, data source, query name, user name, password.

A date/time object is in the range 100 AD–9999 AD.

When specifying a date value as a string, you must enclose it in quotation marks.

cachedWithin

Optional

Timespan, using the CreateTimeSpan function. If original query date falls within the time span, cached query data is used. CreateTimeSpan defines a period from the present, back. Takes effect only if query caching is enabled in the Administrator.

To use cached data, the current query must use the same SQL statement, data source, query name, user name, and password.

debug

Optional; value and equals sign may be omitted

  • Yes, or if omitted: if debugging is enabled, but the Administrator Database Activity option is not enabled, displays SQL submitted to datasource and number of records returned by query.
  • No: if the Administrator Database Activity option is enabled, suppresses display.

result

Optional

Specifies a name for the structure in which cfquery returns the result variables. For more information, see the Usage section .

Usage

Use this tag to execute a SQL statement against a ColdFusion data source. Although you can use the cfquery tag to execute any SQL Data Definition Language (DDL) or Data Manipulation Language (DML) statement, you typically use it to execute a SQL SELECT statement.

Note: To call a stored procedure, use the cfstoredproc tag.

This tag creates a query object, providing this information in query variables:

Variable name

Description

query_name.currentRow

Current row of query that cfoutput is processing.

query_name.columnList

Comma-delimited list of the query columns.

query_name.RecordCount

Number of records (rows) returned from the query.

The cfquery tag also returns the following result variables in a structure. You can access these variables with a prefix of the name you specified in the result attribute. For example, if you assign the name myResult to the result attribute, you would retrieve the name of the SQL statement that was executed by accessing #myResult.sql#. The result attribute provides a way for functions or CFCs that are called from multiple pages, possibly at the same time, to avoid overwriting results of one call with another.

Variable name

Description

result_name.sql

The SQL statement that was executed.

result_name.recordcount

Current row of query that cfoutput is processing.

result_name.cached

True if the query was cached; False otherwise.

result_name.sqlparameters

An ordered Array of cfqueryparam values.

result_name.columnList

Comma-delimited list of the query columns.

result_name.ExecutionTime

Cumulative time required to process the query.

You can cache query results and execute stored procedures. For information about this and about displaying cfquery output, see ColdFusion MX Developer’s Guide.

Because the timeout attribute only affects the maximum time for each suboperation of a query, the cumulative time may exceed its value. To set a timeout for a page that might get a very large result set, set the Administrator > Server Settings > Timeout Requests option to an appropriate value or use the RequestTimeout attribute of the cfsetting tag (for example, <cfsetting requestTimeout="300">).

The Caching page of the ColdFusion MX Administrator specifies the maximum number of cached queries. Setting this value to 0 disables query caching.

You cannot use ColdFusion reserved words as query names.

You cannot use SQL reserved words as variable or column names in a Query of Queries, unless they are escaped. The escape character is the bracket []; for example:

SELECT [count] FROM MYTABLE.

For a list of reserved keywords in ColdFusion MX, see Escaping reserved keywords in Using Query of Queries in ColdFusion MX Developer’s Guide.

Example

<!--- This example shows the use of CreateTimeSpan with CFQUERY ------>
<!--- to cache a record set. Define startrow and maxrows to ---->
<!--- facilitate 'next N' style browsing. ---->
<cfparam name="MaxRows" default="10">
<cfparam name="StartRow" default="1">
<!--------------------------------------------------------------------
Query database for information if cached database information has
not been updated in the last six hours; otherwise, use cached data.
--------------------------------------------------------------------->
<cfquery
name="GetParks" datasource="cfdocexamples"
cachedwithin="#CreateTimeSpan(0, 6, 0, 0)#">
SELECT PARKNAME, REGION, STATE
FROM Parks
ORDER BY ParkName, State
</cfquery>
<!--- Build HTML table to display query. ------------------------->
<table cellpadding="1" cellspacing="1">
    <tr>
        <td bgcolor="f0f0f0">
            &nbsp;
        </td>
        <td bgcolor="f0f0f0">
            <b><i>Park Name</i></b>
        </td>
        <td bgcolor="f0f0f0">
            <b><i>Region</i></b>
        </td>
        <td bgcolor="f0f0f0">
            <b><i>State</i></b>
        </td>
    </tr>
<!--- Output the query and define the startrow and maxrows parameters.
Use the query variable CurrentCount to keep track of the row you
are displaying. ------>
<cfoutput query="GetParks" startrow="#StartRow#" maxrows="#MaxRows#">
    <tr>
        <td valign="top" bgcolor="ffffed">
            <b>#GetParks.CurrentRow#</b>
        </td>
        <td valign="top">
            <font size="-1">#ParkName#</font>
        </td>
        <td valign="top">
            <font size="-1">#Region#</font>
        </td>
        <td valign="top">
            <font size="-1">#State#</font>
        </td>
    </tr>
</cfoutput>
<!--- If the total number of records is less than or equal
to the total number of rows, then offer a link to
the same page, with the startrow value incremented by
maxrows (in the case of this example, incremented by 10). --------->
    <tr>
        <td colspan="4">
        <cfif (StartRow + MaxRows) LTE GetParks.RecordCount>
            <cfoutput><a href="#CGI.SCRIPT_NAME#?startrow=#Evaluate(StartRow + MaxRows)#">
            See next #MaxRows# rows</a></cfoutput>
        </cfif>
        </td>
    </tr>
</table>


cfqueryparam

Description

Verifies the data type of a query parameter and, for DBMSs that support bind variables, enables ColdFusion to use bind variables in the SQL statement. Bind variable usage enhances performance when executing a cfquery statement multiple times.

This tag is nested within a cfquery tag, embedded in a query SQL statement. If you specify optional parameters, this tag performs data validation.

Macromedia recommends that you use the cfqueryparam tag within every cfquery tag, to help secure your databases from unauthorized users. For more information, see Security Bulletin ASB99-04, "Multiple SQL Statements in Dynamic Queries," at
www.macromedia.com/devnet/security/security_zone/asb99-04.html, and Accessing and Retrieving Data in ColdFusion MX Developer’s Guide.

Category

Database manipulation tags

Syntax

<cfquery
    name = "query_name"
    dataSource = "ds_name"
    ...other attributes...
    SQL STATEMENT column_name =
    <cfqueryparam value = "parameter value"
        CFSQLType = "parameter type"
        maxLength = "maximum parameter length"
        scale = "number of decimal places"
        null = "yes" or "no"
        list = "yes" or "no"
        separator = "separator character">
    AND/OR ...additional criteria of the WHERE clause...
    </cfquery>

See also

cfinsert, cfprocparam, cfprocresult, cfquery, cfstoredproc, cftransaction, cfupdate; Enhancing security with cfqueryparam in Accessing and Retrieving Data in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

value

Required

Value that ColdFusion passes to the right of the comparison operator in a where clause.

If CFSQLType is a date or time option, ensure that the date value uses your DBMS-specific date format. Use the CreateODBCDateTime or DateFormat and TimeFormat functions to format the date value.

CFSQLType

Optional

CF_SQL_CHAR

SQL type that parameter (any type) is bound to:

  • CF_SQL_BIGINT
  • CF_SQL_BIT
  • CF_SQL_CHAR
  • CF_SQL_BLOB
  • CF_SQL_CLOB
  • CF_SQL_DATE
  • CF_SQL_DECIMAL
  • CF_SQL_DOUBLE
  • CF_SQL_FLOAT
  • CF_SQL_IDSTAMP
  • CF_SQL_INTEGER
  • CF_SQL_LONGVARCHAR
  • CF_SQL_MONEY
  • CF_SQL_MONEY4
  • CF_SQL_NUMERIC
  • CF_SQL_REAL
  • CF_SQL_REFCURSOR
  • CF_SQL_SMALLINT
  • CF_SQL_TIME
  • CF_SQL_TIMESTAMP
  • CF_SQL_TINYINT
  • CF_SQL_VARCHAR

maxLength

Optional

Length of string in value attribute

Maximum length of parameter. Ensures that the length check is done by ColdFusion before the string is sent to the DBMS, thereby helping to prevent the submission of malicious strings.

scale

Optional

0

Number of decimal places in parameter. Applies to CF_SQL_NUMERIC and CF_SQL_DECIMAL.

null

Optional

No

Whether parameter is passed as a null value:

  • Yes: tag ignores the value attribute.
  • No

list

Optional

No
  • Yes: the value attribute value is a delimited list.
  • No

separator

Required, if you specify a list in value attribute

, (comma)

Character that separates values in list, in value attribute.

Usage

Use the cfqueryparam tag in any SQL statement (for example, SELECT, INSERT, UPDATE, and DELETE) that uses ColdFusion variables.

You cannot use the cfquery cachedAfter or cachedWithin attributes with cfqueryparam.

For maximum validation of string data, specify the maxlength attribute.

This tag does the following:

  • Allows the use of SQL bind parameters, which improves performance.
  • Ensures that variable data matches the specified SQL type.
  • Allows long text fields to be updated from a SQL statement.
  • Escapes string variables in single-quotation marks.

To benefit from the enhanced performance of bind variables, you must use cfqueryparam for all ColdFusion variables, and your DBMS must support bind variables. If a DBMS does not support bind parameters, ColdFusion validates and substitutes the validated parameter value back into the string. If validation fails, it returns an error message.

The validation rules are as follows:

  • For these types, a data value can be converted to a numeric value: CF_SQL_SMALLINT, CF_SQL_INTEGER, CF_SQL_REAL, CF_SQL_FLOAT, CF_SQL_DOUBLE, CF_SQL_TINYINT, CF_SQL_MONEY, CF_SQL_MONEY4, CF_SQL_DECIMAL, CF_SQL_NUMERIC, and CF_SQL_BIGINT
  • For these types, a data value can be converted to a date supported by the target data source: CF_SQL_DATE, CF_SQL_TIME, CF_SQL_TIMESTAMP
  • For all other types, if the maxLength attribute is used, a data value cannot exceed the maximum length specified.

ColdFusion debug output shows the bind variables as question marks and lists the values beneath the query, in order of usage.

Note: To insert an empty string into a Microsoft Access table using the SequelLink ODBC Socket or SequelLink Access driver, the CFSQLType attribute must specify CF_SQL_LONGVARCHAR.

The following table shows the mapping of ColdFusion SQL data types with JDBC SQL types and those of the listed database management systems:

ColdFusion | JDBC | DB2 | Informix | Oracle | MSSQL
CF_SQL_ARRAY | ARRAY |  |  |  |
CF_SQL_BIGINT | BIGINT | Bigint | int8, serial8 |  |
CF_SQL_BINARY | BINARY | Char for Bit Data |  |  | binary timestamp
CF_SQL_BIT | BIT |  | boolean |  | bit
CF_SQL_BLOB | BLOB | Blob | blob | blob, bfile |
CF_SQL_CHAR | CHAR | Char | char, nchar | char, nchar | char, nchar, unique identifier
CF_SQL_CLOB | CLOB | Clob | clob | clob,nclob |
CF_SQL_DATE | DATE | Date | date, datetime, year to day |  |
CF_SQL_DECIMAL | DECIMAL | Decimal | decimal, money | number | decimal, money, small money
CF_SQL_DISTINCT | DISTINCT |  |  |  |
CF_SQL_DOUBLE | DOUBLE | Double |  |  |
CF_SQL_FLOAT | FLOAT | Float | float | number | float
CF_SQL_IDSTAMP | CHAR | Char | char, nchar | char, nchar | char, nchar, unique identifier
CF_SQL_INTEGER | INTEGER | Integer | integer, serial |  | int
CF_SQL_LONGVARBINARY | LONGVARBINARY | Long Varchar for Bit Data | byte | long raw | image
CF_SQL_LONGVARCHAR | LONGVARCHAR | Long Varchar | text | long | text, ntext
CF_SQL_MONEY | DOUBLE | Double |  |  |
CF_SQL_MONEY4 | DOUBLE | Double |  |  |
CF_SQL_NULL | NULL |  |  |  |
CF_SQL_NUMERIC | NUMERIC | Numeric |  |  | numeric
CF_SQL_OTHER | OTHER |  |  |  |
CF_SQL_REAL | REAL | Real | smallfloat |  | real
CF_SQL_REFCURSOR | REF |  |  |  |
CF_SQL_SMALLINT | SMALLINT | Smallint | smallint |  | smallint
CF_SQL_STRUCT | STRUCT |  |  |  |
CF_SQL_TIME | TIME | Time | datetime hour to second |  |
CF_SQL_TIMESTAMP | TIMESTAMP | Timestamp | datetime year to fraction(5), datetime year to second | date | datetime, smalldate time
CF_SQL_TINYINT | TINYINT |  |  |  | tinyint
CF_SQL_VARBINARY | VARBINARY | Rowid |  | raw | varbinary
CF_SQL_VARCHAR | VARCHAR | Varchar | varchar, nvarchar, lvarchar | varchar2, nvarchar2 | varchar, nvarchar, sysname

Example

<!--- This example shows cfqueryparam with VALID input in Course_ID. --->
<h3>cfqueryparam Example</h3>
<cfset Course_ID = 12>
<cfquery name = "getFirst" dataSource = "cfdocexamples">
    SELECT *
    FROM courses
    WHERE Course_ID = <cfqueryPARAM value = "#Course_ID#"
    CFSQLType = "CF_SQL_INTEGER">
</cfquery>
<cfoutput query = "getFirst">
    <p>Course Number: #Course_ID#<br> Description: #descript#</p>
</cfoutput>

<!--- This example shows the use of CFQUERYPARAM when INVALID string data is
    in Course_ID. ---->
<p>This example throws an error because the value passed in the CFQUERYPARAM
tag exceeds the MAXLENGTH attribute</p>

<cfset LastName="Peterson; DELETE employees WHERE LastName='Peterson'">
<!------- Note that for string input you must specify the MAXLENGTH attribute
    for validation. -------------------------------------------------->
<cfquery
    name="getFirst" datasource="cfdocexamples">
    SELECT *
    FROM employees
    WHERE LastName=<cfqueryparam
                                value="#LastName#"
                                cfsqltype="CF_SQL_VARCHAR"
                                maxlength="17">
</cfquery>
<cfoutput
    query="getFirst"> 		<p>
        Course Number: #FirstName# #LastName#
        Description: #Department# </p>
</cfoutput>


cfregistry

Description

This tag is deprecated for the UNIX platform.

Reads, writes, and deletes keys and values in the system registry. Provides persistent storage of client variables.

Note: For this tag to execute, it must be enabled in the ColdFusion MX Administrator. For more information, see Configuring and Administering ColdFusion MX.

Category

Other tags, Variable manipulation tags

Syntax

The tag syntax depends on the action attribute value. See the following sections:

  • cfregistry action = "getAll"
  • cfregistry action = "get"
  • cfregistry action = "set"
  • cfregistry action = "delete"

See also

cfcookie, cfparam, cfsavecontent, cfschedule, cfset; About resource and sandbox security in Securing Applications and Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Deprecated this tag on the UNIX platform. It might not work, and might cause an error, in later releases.
  • Changed how persistent data is stored: ColdFusion now stores most persistent data outside the system registry, in XML files.


cfregistry action = "getAll"

Description

Returns all registry keys and values defined in a branch. You can access the values as you would any record set.

Syntax

<cfregistry
    action = "getAll"
    branch = "branch"
    type = "data type"
    name = "query name"
    sort = "criteria">

See also

Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Always getall.

branch

Required

Name of a registry branch.

type

Optional

String
  • string: returns string values.
  • dWord: returns DWord values.
  • key: returns keys.
  • any: returns keys and values.

name

Required

Name of record set to contain returned keys and values.

sort

Optional

ASC

Sorts query column data (case-insensitive). Sorts on Entry, Type, and Value columns as text. Specify a combination of columns from query output, in a comma-delimited list. For example:

sort = "value desc, entry asc"

  • asc: ascending (a to z) sort order.
    •

  • desc: descending (z to a) sort order.
    •

Usage

This tag returns #entry#, #type#, and #value# in a record set that you can access through tags such as cfoutput. To fully qualify these variables, use the record set name, as specified in the name attribute.

If #type# is a key, #value# is an empty string.

If you specify type= "any", getAll also returns binary registry values. For binary values, the #type# variable contains UNSUPPORTED and #value# is blank.

Example

<!--- This example uses cfregistry with the getAll action. --->
<cfregistry action = "getAll"
    branch = "HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM"
    type = "Any" name = "RegQuery">
<p><h1>cfregistry action = "getAll"</h1>
<cftable query = "RegQuery" colHeaders HTMLTable border = "Yes">
<cfcol header = "<b>Entry</b>" width = "35" text = "#RegQuery.Entry#">
<cfcol header = "<b>Type</b>" width = "10" text = "#RegQuery.type#">
<cfcol header = "<b>Value</b>" width = "35" text = "#RegQuery.Value#">
</cftable>


cfregistry action = "get"

Description

Accesses a registry value and stores it in a ColdFusion variable.

Syntax

<cfregistry
    action = "get"
    branch = "branch"
    entry = "key or value"
    variable = "variable"
    type = "data type">

See also

Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Always get.

branch

Required

Name of a registry branch.

entry

Required

Registry value to access.

variable

Required

Variable into which to put value.

type

Optional

string
  • string: returns string value.
  • dWord: returns DWord value.
  • key: returns key’s default value.

Usage

If the value does not exist, the cfregistry tag does not create an entry.

Example

<!--- This example uses cfregistry with the get action. --->
<cfregistry action = "get"
 branch = "HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM"
 entry = "ClassPath" type = "String" variable = "RegValue">
<h1>cfregistry action = "get"</h1>
<cfoutput>
    <p>Java ClassPath value is #RegValue#
</cfoutput>


cfregistry action = "set"

Description

Adds a registry key, adds a value, or updates a value.

Syntax

<cfregistry
    action = "set"
    branch = "branch"
    entry = "key or value"
    type = "value type"
    value = "data">

See also

Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Always set.

branch

Required

Name of a registry branch.

entry

Required

Key or value to set.

type

Optional

  • string: sets a string value (default).
  • dWord: sets a DWord value.
  • key: creates a key.

value

Optional

Value data to set. If you omit this attribute, the cfregistry tag creates default value, as follows:

  • string: creates an empty string: "".
  • dWord: creates a value of 0 (zero).

Usage

If it does not exist, the cfregistry tag creates the key or value.

Example

<!--- This example uses the cfregistry set action to modify registry value data. --->
<!--- Normally you pass in a filename instead of setting one here. --->
<cfset FileName = "dummy.cfm">
<cfregistry action = "set"
 branch = "HKEY_LOCAL_MACHINE\Software\cflangref"
 entry = "LastCFM01" type = "String" value = "#FileName#">
<h1>cfregistry action = "set"</h1>


cfregistry action = "delete"

Description

Deletes a registry key or value.

Syntax

<cfregistry
    action = "delete"
    branch = "branch"
    entry = "keyorvalue">

See also

Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

action

Required

Always delete.

branch

Required

  • For key deletion: name of registry key to delete. Do not specify the entry attribute.
  • For value deletion: name of registry branch that contains value to delete. You must specify the entry attribute.

entry

Required for value deletion

Value to delete.

Usage

If you delete a key, the cfregistry tag also deletes values and subkeys defined beneath it.

Example

<cfregistry action = "delete"
 branch = "HKEY_LOCAL_MACHINE\Software\cflangref\tempkey"
 entry = "LastCFM01">
<h1>cfregistry action = "delete"</h1>


cfreport

Description

Used to do either of the following:

  • Execute a report definition created with the ColdFusion Report Builder, displaying it in PDF, FlashPaper, or Excel format. You can optionally save this report to a file.
  • Run a predefined Crystal Reports report. Applies only to Windows systems. Uses the CFCRYSTAL.exe file to generate reports. Sets parameters in the Crystal Reports engine according to its attribute values.

Category

Data output tags

Syntax

<!--- Syntax 1 - Use this syntax with the ColdFusion Report Builder. --->
<cfreport
        template = "report definition filename"
        format = "PDF or FlashPaper" or "excel"
        name = "cf variable"
        filename = "output filename"
        query = "query variable"
        overwrite = "yes" or "no"
        encryption = "128-bit" or "40-bit" or "none"
        ownerpassword = "password"
        userpassword = "password"
        permissions = "permission list"
>
        cfreportparam tags [optional]

</cfreport>
OR
<!--- Syntax 2 - Use this syntax with Crystal Reports. --->
<cfreport
        report = "report_path"
        dataSource = "ds_name"
        type = "type"
        timeout = "number of seconds"
        orderBy = "result_order"
        username = "username"
        password = "password"
        formula = "formula">
</cfreport>

See also

cfcollection, cfdocument, cfdocumentitem, cfdocumentsection, cfexecute, cfindex, cfobject, cfreportparam, cfsearch, cfwddx; Creating Reports for Printing in ColdFusion MX Developer’s Guide; Report Builder online Help

History

ColdFusion MX 7: Added support for the ColdFusion Report Builder.

ColdFusion MX: Changed data source connection behavior: Crystal Reports now establishes an independent connection to the data source. The connection is not subject to any ColdFusion data source-specific restrictions. For example, the Crystal Reports server can access a data source, regardless of whether it is disabled in the ColdFusion MX Administrator.

Attributes

Attribute

Applies to

Req/Opt

Default

Description

template

Report Builder

Req

Specifies the path to the report definition file, relative to the web root.

format

Report Builder

Req

Specify one of the following:

  • PDF
  • FlashPaper
  • Excel

name

Report Builder

Opt

The name of the ColdFusion variable that will hold the report output. You cannot specify both name and filename.

filename

Report Builder

Opt

The filename to contain the report. You cannot specify both name and filename.

query

Report Builder

Opt

The name of the query that contains input data for the report. If you omit this parameter, the report definition obtains data from the internal SQL or from cfreportparam items.

overwrite

Report Builder

Opt

No

Specifies whether to overwrite files that have the same name as that specified in the filename attribute. Specify Yes or No.

encryption

Report Builder

Opt

None

(format="PDF" only) Specifies whether the output is encrypted. Specify one of the following:

  • 128-bit
  • 40-bit
  • none

ownerpassword

Report Builder

Opt

(format="PDF" only) Specifies an owner password.

userpassword

Report Builder

Opt

(format="PDF" only) Specifies a user password.

permissions

Report Builder

Opt

(format="PDF" only) Specifies one or more of the following permissions:

  • AllowPrinting
  • AllowModifyContents
  • AllowCopy
  • AllowModifyAnnotations
  • AllowFillIn
  • AllowScreenReaders
  • AllowAssembly
  • AllowDegradedPrinting

Separate multiple permissions with a comma.

datasource

Crystal Reports

Opt

Name of registered or native data source.

type

Crystal Reports

Opt

standard
  • standard (not valid for Crystal Reports 8.0)
  • netscape
  • microsoft

timeout

Crystal Reports

Opt

Maximum time, in seconds, in which a connection must be made to a Crystal Reports file.

report

Crystal Reports

Required

Report path. Store Crystal Reports files in the same directories as ColdFusion page files.

orderBy

Crystal Reports

Opt

Orders results according to your specifications.

username

Crystal Reports

Opt

Username required for entry into database from which report is created. Overrides default settings for data source in ColdFusion MX Administrator.

password

Crystal Reports

Opt

Password that corresponds to username required for database access. Overrides default settings for data source in the ColdFusion Administrator.

formula

Crystal Reports

Opt

One or more named formulas. Terminate each formula with a semicolon. Use the format:

formula = "formulaname1 = 'formula1';formulaname2 = 'formula2';"

If you use a semicolon in a formula, you must escape it by typing it twice (;;). For example:

formula = "Name1 = 'Val_1a;;Val_1b';Name2 = 'Val2';"

Usage

Use this tag to generate a report using a report definition created in either ColdFusion Report Builder or in Crystal Reports. (For more information on using the ColdFusion Report Builder, display the online help by opening the Report Builder and pressing F1.)

Note: The Excel report output format type provides limited support for the formatting options available in ColdFusion MX 7 Reporting. Images and charts are not supported and numeric data containing formatting (commas, percents, currency, and so on) appear as plain text in Excel. The Excel output format supports simple reports only and Macromedia recommends that you give careful design and layout consideration to reports designed for Excel output.

This tag requires an end tag.

Example

<!--- Example 1: This example shows the use of cfreport for the
      ColdFusion Report Builder. --->
<cfquery name="northwindemployees" datasource="localnorthwind">
    SELECT EmployeeID, LastName, FirstName, Title, City, Region, Country
        FROM Employees
        ORDER BY Country, City
</cfquery>

<CFREPORT format="PDF" template="FifthReport.cfr"
   query="#northwindemployees#" />

<!--- Example 2:
This view-only example shows the use of cfreport for Crystal Reports. --->
<h3>cfreport Tag<h3>
<p>cfreport lets reports from the Crystal Reports Professional report writer
display through a ColdFusion interface. To run, the tag requires the
name of the report. cfreport can also pass information to the report
file displayed, to change the output conditions.
<p>This example would run a report called "monthlysales.rpt " and pass it an
optional filter condition to show only the information for a subset
of the report.

<cfreport report = ’/reports/monthlysales.rpt’>
     {Departments.Department} = ‘International’
</cfreport>

<p>Substitute your report files and filters for this code. cfreport can put
Crystal Reports into web pages.


cfreportparam

Description

Passes input parameters to a ColdFusion Report Builder report definition. Allowed inside cfreport tag bodies only.

Category

Data output tags

Syntax

<cfreportparam
    name = "data name"
    value = "data value">

See also

cfreport; Creating Reports for Printing in ColdFusion MX Developer’s Guide; Report Builder online Help

History

ColdFusion MX 7: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
name | Required |  | Variable name for data that is passed. The ColdFusion Report Builder report definition must include an input parameter that matches this name.
value | Required |  | Value of the data that is sent.

Usage

Specifies an input parameter to a ColdFusion Report Builder report definition. The ColdFusion Report Builder report definition must include an input parameter that matches the name attribute.

You can use cfreportparam to pass data to a report definition, as an alternative to the cfreport query attribute.

Example

<cfquery name="coursedept" datasource="cfdocexamples">
    SELECT Departments.Dept_ID as dDept_ID, Departments.Dept_Name,
           CourseList.Course_ID, CourseList.Dept_ID as cDept_ID,
           CourseList.CorNumber, CourseList.CorName,
           CourseList.CorLevel
        FROM Departments, CourseList
        WHERE Departments.Dept_ID = CourseList.Dept_ID
        ORDER BY CourseList.Dept_ID
</cfquery>

<cfreport format="PDF" template="FourthReport.cfr" query="#coursedept#" overwrite="yes">
  <cfreportparam NAME="ReportTime" VALUE="#DateFormat(Now())#, #TimeFormat(Now())#">
</cfreport>


cfrethrow

Description

Rethrows the currently active exception. Preserves the exception’s cfcatch.type and cfcatch.tagContext variable values.

Category

Exception handling tags, Extensibility tags

Syntax

<cfrethrow>

See also

cferror, cfthrow, cftry; Handling runtime exceptions with ColdFusion tags in Handling Errors in ColdFusion MX Developer’s Guide

Usage

Use this tag within a cfcatch block. This tag is useful in error handling code, if the error handler cannot handle an error that it catches. For example, if cfcatch type = "any" gets a DATABASE exception, and the code is designed to handle only CFX exceptions, the handler raises the exceptions again, with details intact, so that a higher-level handler can process the error information. If you used the cfthrow tag, the type and details of the original exception would be lost.

Example

<h3>cfrethrow Example</h3>
<!--- Rethrow a DATABASE exception. --->
<cftry>
    <cftry>
        <cfquery name = "GetMessages" dataSource = "cfdocexamples">
            SELECT  *
            FROM   Messages
        </cfquery>
    <cfcatch type = "DATABASE">
        <!--- If database signalled a 50555 error, ignore; otherwise, rethrow
exception. --->
        <cfif cfcatch.sqlstate neq 50555>
            <cfrethrow>
        </cfif>
    </cfcatch>
    </cftry>
<cfcatch>
    <h3>Sorry, this request can't be completed</h3>
    <h4>Catch variables</h4>
    <cfoutput>
        <cfloop collection = #cfcatch# item = "c">
            <br>
            <cfif IsSimpleValue(cfcatch[c])>#c# = #cfcatch[c]#
            </cfif>
        </cfloop>
    </cfoutput>
</cfcatch>
</cftry>


cfreturn

Description

Returns result values from a component method. Contains an expression returned as result of the function.

Return value

An expression; the result of the function from which this tag is called.

Category

Extensibility tags

Syntax

<cfreturn
    expr>

See also

cfargument, cfcomponent, cffunction, cfinvoke, cfinvokeargument, cfobject, cfproperty; Creating reports with the ColdFusion MX 7 reporting in Creating Reports for Printing in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this tag.

Attributes

Attribute | Req/Opt | Default | Description
expr | Required |  | Function result; value of any type.

Usage

This tag is equivalent to a return statement within a cfscript tag. It accepts one return variable argument. To return more than one value, populate a structure with name-value-pairs, and return the structure with this tag.

To access the result value from this tag, you use the variable scope that is the value of the cfinvoke tag returnVariable attribute.

You can code a maximum of one cfreturn tag within a function.

For example code, see Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide.

Example

<cfcomponent>
    <cffunction name="getEmp">
         <cfquery name="empQuery" datasource="ExampleApps" >
             SELECT FIRSTNAME, LASTNAME, EMAIL
             FROM tblEmployees
         </cfquery>
         <cfreturn empQuery>
    </cffunction>
    <cffunction name="getDept">
        <cfquery name="deptQuery" datasource="ExampleApps" >
             SELECT *
             FROM tblDepartments
         </cfquery>
         <cfreturn deptQuery>
    </cffunction>
</cfcomponent>


cfsavecontent

Description

Saves the generated content of the cfsavecontent tag, including the results of evaluating expressions and executing custom tags, in the specified variable.

Category

Variable manipulation tags

Syntax

<cfsavecontent
    variable = "variable name">
    the content
</cfsavecontent>

See also

Caching parts of ColdFusion pages in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
variable | Required |  | Name of the variable in which to save the generated content of the tag.

Usage

This tag requires an end tag.

You cannot use this tag to suppress output from a tag library.

Example

The following example uses a custom tag to generate a report and saves the report in the variable CONTENT. It replaces all instances of the word "report" with the phrase "MyCompany Quarterly Report" and outputs the result.

<cfsavecontent variable="content">
    <CF_OutputBigReport>
</cfsavecontent>
<cfoutput>
    #replace(content, "report", "MyCompany Quarterly Report", "all")#
</cfoutput>


cfschedule

Description

Provides a programmatic interface to the ColdFusion scheduling engine. Can run a CFML page at scheduled intervals, with the option to write the page output to a static HTML page. This feature enables you to schedule pages that publish data, such as reports, without waiting while a database transaction is performed to populate the page.

Category

Variable manipulation tags

Syntax

<cfschedule
    action = "update"
    task = "taskname"
    operation = "HTTPRequest"
    file = "filename"
    path = "path_to_file"
    startDate = "date"
    startTime = "time"
    url = "URL"
    port = "port_number"
    publish = "yes" or "no"
    endDate = "date"
    endTime = "time"
    interval = "seconds"
    requestTimeOut = "seconds"
    username = "username"
    password = "password"
    proxyServer = "hostname"
    proxyPort = "port_number">
    proxyUser = "username"
    proxyPassword = "password"
    resolveURL = "yes" or "no"

<cfschedule
    action = "delete"
    task = "TaskName">

<cfschedule
    action = "run"
    task = "TaskName">

See also

cfcookie, cfparam, cfregistry, cfsavecontent, cfset

History

ColdFusion MX 6.1: Changed the way intervals are calculated. The day length now reflects changes between standard and daylight saving times. The month length is now the calendar month length, not four weeks. The scheduler handles leap years correctly.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

  • delete: deletes the specified task .
  • update: updates an existing task or creates a new task, if one with the name specified by the task attribute does not exist.
  • run: executes the specified task.

task

Required

Name of the task.

operation

Required if action = "update"

Operation that the scheduler performs. Must be HTTPRequest.

file

Required if publish = "Yes"

Name of the file in which to store the published output of the scheduled task.

path

Required if publish = "Yes"

Path to the directory in which to put the published file.

startDate

Required if action = "update"

Date on which to first run the scheduled task.

startTime

Required if action = "update"

Time at which to run the scheduled of task starts.

url

Required if action = "update"

URL of the page to execute.

port

Optional

80

Port to use on the server that is specified by the url parameter. If resolveURL = "yes", retrieved document URLs that specify a port number are automatically resolved, to preserve links in the retrieved document. A port value in the url attribute overrides this value.

publish

Optional

No
  • Yes: saves the result to a file.
  • No

endDate

Optional

Date when scheduled task ends.

endTime

Optional

Time when scheduled task ends (seconds).

interval

Required if action = "update"

Interval at which task is scheduled:

  • number of seconds
  • once
  • daily
  • weekly
  • monthly

requestTimeOut

Optional

Can be used to extend the default timeout period.

username

Optional

Username, if URL is protected.

password

Optional

Password, if URL is protected.

proxyServer

Optional

Host name or IP address of a proxy server.

proxyPort

Optional

80

Port number to use on the proxy server.

proxyUser

Opt

User name to provide to the proxy server.

proxyPassword

Opt

Password to provide to the proxy server.

resolveURL

Optional

No
  • Yes: resolves links in the output page to absolute references.
  • No

Usage

This tag and the ColdFusion MX Administrator Scheduled task page schedule ColdFusion tasks. Tasks that you add or change using this tag are visible in the Administrator. You can disable this tag in the Administrator Sandbox/Resource security page. This tag’s success or failure status is written to the schedule.log file in the cf_root/logs directory (cf_webapp_root/WEB-INF/cfusion/logs in the multiserver and J2EE configurations).

When you create a task, you specify the URL of the ColdFusion page to execute, the date, time and frequency of execution, and whether to publish the task output to a HTML file. If the output is published, you specify the output file path and file.

If you schedule a job to run monthly on any date in the range 28-31, the scheduler does the following:

  • If you schedule a monthly job to run on the last day of a month, the scheduled job will run on the last day of each month. For example, if you schedule a monthly job to start on January 31, it will run on January 31, February 28 or 29, March 31, April 30, and so on.
  • If you schedule a monthly job to run on the 29th or 30th of the month, the job will run on the specified day of each month for 30 or 31-day months, and the last day of February. For example, if you schedule a monthly job to start on January 30, the job will run on January 30, February 28 or 29, March 30, April 30, and so on.

If you schedule a job to run once, the starting time is in the past, and the task has not yet run, it runs immediately. If you schedule a recurring job with a start time in the past, ColdFusion schedules the job to run on the next closest interval in the future.

The Scheduler configuration file, cf_root\lib\neo-cron.xml contains all scheduled events, as individual entries.

Example

<h3>cfschedule Example</h3>
<!--- This read-only example schedules a task.
        To run the example, remove the comments around the code
        and change the startDate, startTime, url, file, and path attributes
        to appropriate values. --->
<!---
<cfschedule action = "update"
    task = "TaskName"
    operation = "HTTPRequest"
    url = "http://127.0.0.1/playpen/history.cfm"
    startDate = "8/7/03"
    startTime = "12:25 PM"
    interval = "3600"
    resolveURL = "Yes"
    publish = "Yes"
    file = "sample.html"
    path = "c:\inetpub\wwwroot\playpen"
    requestTimeOut = "600">
--->


cfscript

Description

Encloses a code block that contains cfscript statements.

Category

Application framework tags, Other tags

Syntax

<cfscript>
    cfscript code here
</cfscript>

See also

cfinvoke, cfmodule, CreateObject; Extending ColdFusion Pages with CFML Scripting in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed how to invoke component methods: this tag can now invoke component methods, using the CreateObject function
  • Changed use of reserved words: you cannot use ColdFusion reserved words within this tag
  • Added the try and catch statements.

Usage

Performs processing in CFScript. This tag uses ColdFusion functions, expressions, and operators. You can read and write ColdFusion variables within this tag.

For a detailed description of the CFScript scripting language, including documentation of CFScript statements and the CFScript equivalents of CFML tags, see Extending ColdFusion Pages with CFML Scripting in ColdFusion MX Developer’s Guide.

You can use this tag to enclose a series of assignment statements that would otherwise require cfset statements.

Caution: If you code a cftry/cfcatch block within this tag using an exception’s Java class name, you must provide the fully qualified class name.

You cannot use some ColdFusion reserved words in this tag. You cannot put a user-defined function whose name begins with any of these strings within this tag:

  • cf
  • cf_
  • _cf
  • coldfusion
  • coldfusion_
  • _coldfusion

You cannot use the elseif construct within a cfscript tag. You can use code such as the following:

else if ( condition )
{
...
}

Exception handling with the cfscript tag

To handle exceptions with this tag, use try and catch statements, which are equivalent to the cftry and cfcatch tags. For each try statement, you must have a catch statement. In the catch block, the variable exceptionVariable contains the exception type. This variable is the equivalent of the cfcatch tag built-in variable cfcatch.Type. For more information, see Extending ColdFusion Pages with CFML Scripting in ColdFusion MX Developer’s Guide.

Invoking ColdFusion components with the cfscript tag

CFScript invokes component methods using the CreateObject function.

The following example shows how to invoke a component object with the cfscript tag, using ordered arguments:

<cfscript>
quote = CreateObject( "component", "nasdaq.quote" ) ;
<!--- Invocation using ordered arguments. --->
res = quote.getLastTradePrice( "macr" ) ;
</cfscript>

The following example shows how to use an attribute collection within the cfscript tag to pass parameters when invoking a component object. An attribute collection is a structure in which each key corresponds to a parameter name and each value is the parameter value passed for the corresponding key.

<cfscript>
    stArgs = structNew();
    stArgs.translationmode = "en_es";
    stArgs.sourceData= "Hello world, friend";
</cfscript>
...
<cfinvoke
    webservice = "http://www.xmethods.net/sd/2001/BabelFishService.wsdl"
    method     = "BabelFish"
    argumentCollection = "#stArgs#"
    returnVariable = "varName"	>
<cfoutput>#varName#</cfoutput>

In this example, the structure is created in a cfscript block, but you can use any ColdFusion method to create the structure.

Consuming web services with the cfscript tag

The following example shows how to consume a web service with the cfscript tag. You use the CreateObject function to connect to the web service.

<cfscript>
    ws = CreateObject("webservice",
                "http://www.xmethods.net/sd/2001/BabelFishService.wsdl");
    xlatstring = ws.BabelFish("en_es", "Hello world, friend");
    writeoutput(xlatstring);
</cfscript>

For more information, see Using Web Services in ColdFusion MX Developer’s Guide.

Example

<p>This simple example shows variable declaration and manipulation.
<cfif IsDefined("form.myValue")>
    <cfif IsNumeric(form.myValue)>
        <cfset x = form.myValue>
        <cfscript>
            y = x;
            z = 2 * y;
            StringVar = form.myString;
        </cfscript>
    <cfoutput>		<p>twice #x# is #z#.
        <p>Your string value was: <b><I>#StringVar#</i></b>	</cfoutput>
<cfelse>
Previous


cfsearch

Description

Searches one or more Verity collections.

A collection must be created and indexed before this tag can return search results.

A collection can be created in these ways:

  • With the cfcollection tag
  • In the ColdFusion MX Administrator
  • Using a native Verity indexing tool, such as Vspider or MKVDK. For more information on Vspider and MKVDK, see Introducing Verity and Verity Tools in Configuring and Administering ColdFusion MX.

If you use a native Verity tool to create a collection, it must be registered. A collection can be registered with ColdFusion in the following ways:

  • With the cfcollection tag
  • In the ColdFusion MX Administrator

A collection can be indexed in the following ways:

  • In ColdFusion, with the cfindex tag
  • In the ColdFusion MX Administrator, which calls the cfindex tag
  • Using a native Verity indexing tool, such as Vspider or MKVDK

For more information, see Building a Search Interface in ColdFusion MX Developer’s Guide.

Category

Extensibility tags

Syntax

<cfsearch
    name = "search_name"
    collection = "collection_name"
category = "category[,category2,...]"
categoryTree = "tree_location"
    status = ""
    type = "criteria"
    criteria = "search_expression"
    maxRows = "number"
    startRow = "row_number"
    suggestions = "suggestion_option"
    contextPassages = "number_of_passages"
    contextBytes = "number_of_bytes"
    contextHighlightBegin = "html_string"
    contextHighlightEnd = "html_string"
    previousCriteria = "criteria"
    language = "language">

See also

cfcollection, cfexecute, cfindex, cfobject, cfreport, cfwddx

History

ColdFusion MX 7:

  • Added category, categoryTree, status, suggestions, contextPassages, contextBytes, contextHighlightBegin, contextHighlightEnd, and previousCriteria attributes.
  • Added author, category, categoryTree, context, rank, size, recordsSearched, and type result columns.
  • Added information on the status structure and its associated keys.
  • Removed references to a separate K2 server and k2server.ini file.
  • Removed references to unregistered collections.
  • Removed references to external collections. ColdFusion MX now manages all collections through the Verity Search service.
  • Changed cflock recommendation. It is no longer a best practice to surround the cfsearch tag with a cflock tag.

ColdFusion MX:

  • Deprecated the external attribute. It might not work, and might cause an error, in later releases. (ColdFusion stores this information about each collection; it automatically detects whether a collection is internal or external.) This tag supports absolute (also known as fully qualified) collection pathnames and mapped collection names.
  • Changed query result behavior: the cfindex tag can index the query results from a cfsearch operation.
  • Changed Verity operations behavior: ColdFusion supports Verity operations on Acrobat PDF files.
  • Changed multiple collection behavior: this tag can search multiple collections. In a multiple collection search, you cannot combine collections that are registered with K2Server and registered in another way.
  • Changed acceptable collection naming: this tag accepts collection names that include spaces.
  • Changed the following support: this tag supports Verity 2.6.1 and the LinguistX and ICU locales.
  • Changed thrown exceptions: this tag can throw the SEARCHENGINE exception.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

Name of the search query.

collection

Required

One or more collection names. You can specify more than one collection unless you are performing a category search (that is, specifying category or categoryTree).

category

Optional

A list of categories, separated by commas, to which the search is limited. If specified, and the collection does not have categories enabled, ColdFusion throws an exception.

categoryTree

Optional

The location in a hierarchical category tree at which to start the search. ColdFusion searches at and below this level. If specified, and the collection does not have categories enabled, ColdFusion throws an exception. Can be used in addition to the category attribute.

status

Optional

Specifies the name of the structure variable into which ColdFusion places search information, including alternative criteria suggestions (spelling corrections). For a list of keys in this structure, see Status structure keys.

type

Optional

simple

Used to specify the parser that Verity uses to process the criteria.

  • simple: STEM and MANY operators are implicitly used.
  • explicit: operators must be invoked explicitly. Also known as Bool_Plus.
  • internet: for documents that are mostly WYSIWIG (what-you-see-is-what-you-get) documents. Also known as Internet_advanced.
  • internet_basic: minimizes search time.
  • natural: specifies the Query By Example (QBE) parser. Also known as FreeText.

For more information, see Using Verity Search Expressions in ColdFusion MX Developer’s Guide. Also see your Verity documentation.

criteria

Optional

Search criteria. Follows the syntax rules of the type attribute. If you pass a mixed-case entry in this attribute, the search is case-sensitive. If you pass all uppercase or all lowercase, the search is case-insensitive. Follow Verity syntax and delimiter character rules; see Using Verity Search Expressions in ColdFusion MX Developer’s Guide.

maxRows

Optional

All

Maximum number of rows to return in query results.

startRow

Optional

1

First row number to get.

suggestions

Optional

never

Specifies whether Verity returns spelling suggestions for possibly misspelled words. Use one of the following options:

  • Always: Verity always returns spelling suggestions.
  • Never: Verity never returns spelling suggestions.
  • positive integer: Verity returns spelling suggestions if the number of documents retrieved by the search is less than or equal to the number specified.

There is a small performance penalty for retrieving suggestion data.

contextPassages

Optional

0

The number of passages/sentences Verity returns in the context summary (that is, the context column of the results). The default i s 0, which disables context summary.

contextBytes

Optional

300

The maximum number of bytes Verity returns in the context summary.

contextHighlightBegin

Optional

<b>

The HTML to prepend to search terms in the context summary. Use this attribute in conjunction with contextHighlightEnd to highlight search terms in the context summary.

contextHighlightEnd

Optional

</b>

The HTML to append to search terms in the context summary. Use this attribute in conjunction with contextHighlightBegin to highlight search terms in the context summary.

previousCriteria

Optional

The name of a result set from an existing set of search results. Verity searches the result set for criteria without regard to the previous search score or rank. Use this attribute to implement searching within result sets.

language

Optional

english

Deprecated. This attribute is now ignored and the language of the collection is used to perform the search.

Usage

The cfsearch tag returns a query object whose columns you can reference in a cfoutput tag. For example, the following code specifies a search for the exact terms "filming" or "filmed":

<cfsearch
name = "mySearch"
collection = "myCollection"
criteria = '<WILDCARD>`film{ing,ed}`'
type="explicit"
startrow=1
    maxrows = "100">
<cfdump var = "#mySearch#>

In this example, the single-quotation mark (') and backtick (`) characters are used as delimiters; for more information, see Using Verity Search Expressions in ColdFusion MX Developer’s Guide.

To optimize search performance, always specify the maxrows attribute, setting it to a value that matches your application’s needs. A value less than 300 helps to ensure optimal performance.

Macromedia does not recommend using the cflock tag with this tag; Verity provides the locking function. Using the cflock tag slows search performance.

The cfsearch tag result columns

Variable

Description

context

A context summary containing the search terms, highlighted in bold (by default). This is enabled if you set the contextpassages attribute to a number greater than zero.

url

Value of URLpath attribute in the cfindex tag used to populate a collection.

key

Value of the key attribute in the cfindex tag used to populate a collection.

title

Value of title attribute in cfindex tag used to populate the collection, including PDF and Office document titles. If a title is not extracted from the document, the tag uses the cfindex title attribute value for each row.

score

Relevancy score of document based on search criteria

custom1, custom2,
custom3, custom4

Value of custom fields in cfindex tag used to populate a collection.

size

The number of bytes in the index document.

rank

The rank of this document in the search results.

author

Extracted from the HTML, Office, and PDF documents when available.

type

The MIME type of the document.

category

A list of the categories that were specified for this document when it was indexed.

categoryTree

A hierarchical category tree, or serial list of categories, that was specified for this document when it was indexed. Only a single tree is returned.

summary

Contents of automatic summary generated by cfindex.

recordCount

Number of records returned in record set

currentRow

Current row that cfoutput is processing.

columnList

List of column names within record set.

recordsSearched

Number of records searched. This is the same value for each row in the record set. Corresponds to the searched key in the status structure.

Status structure keys

Variable

Description

found

The number of documents that contain the search criteria.

searched

The number of documents searched. Corresponds to the recordsSearched column in the search results.

time

The number of milliseconds the search took, as reported by the Verity K2 search service.

suggestedQuery

An alternative query, as suggested by Verity, that might produce better results. This often contains corrected spellings of search terms. Present only when the suggestions tag attribute criteria is met.

keywords

A structure containing each search term as a key to an array of up to five possible alternative terms, in order of preference. Present only when the suggestions attribute criteria is met.

keywordScore

A structure in the same format as for keywords, except it also includes Verity-reported weighted values from 0 to .99, in which higher scores indicate better-quality results.

To permit application users to search Verity collections for nonstandard strings, words, or characters (for example, "AB23.45.67" or "--->") that would otherwise cause an error, you can create a text file that lists these elements and defines their formats for Verity. Name the file style.lex and put copies of the file in these directories:

  • Windows:
    • cf_root\verity\k2\common\style (typically, cf_root = C:\CFusionMX7)
    • cf_root\verity\Data\stylesets\ColdFusionK2
  • UNIX:
    • cf_root//verity/k2/common/style (typically, cf_root = /opt/coldfusionmx7)
    • cf_root/verity/Data/stylesets/ColdFusionK2

In the multiserver and J2EE configurations, you install Verity in a separate directory.

Note: To search for a character such as an angle bracket (< or >), you must use a criteria attribute value such as "&lt:" or "&lt:". The bracket characters are reserved in Verity, and using a backslash to escape the character (criteria="\<") does not work in this context. For more information, see Using Verity Search Expressions in ColdFusion MX Developer’s Guide.

Example

<!--- #1 (TYPE=SIMPLE) ----------------------------->
<cfsearch
    name="name"
    collection="snippets,syntax,snippets"
    criteria="example"
    maxrows = "100">
<p>
<cfoutput>Search Result total =  #name.RecordCount# </cfoutput><br>
<cfoutput>
    url=#name.url#<br>
    key=#name.key#<br>
    title=#name.title#<br>
    score=#name.score#<br>
    custom1=#name.custom1#<br>
    custom2=#name.custom2#<br>
    summary=#name.summary#<br>
    recordcount=#name.recordcount#<br>
    currentrow=#name.currentrow#<br>
    columnlist=#name.columnlist#<br>
    recordssearched=#name.recordssearched#<br>
</cfoutput>
<cfdump var = #name#>
<br>

<!--- #2 (TYPE=EXPLICIT) ----------------------------->
<cfsearch
    name = "snippets"
    collection = "snippets"
    criteria = '<wildcard>`film{ing,ed}`'
    type="explicit"
    startrow=1
    maxrows = "100">
<cfoutput
    query="snippets">
    url=#url#<br>
    key=#key#<br>
    title=#title#<br>
    score=#score#<br>
    custom1=#custom1#<br>
    custom2=#custom2#<br>
    summary=#summary#<br>
    recordcount=#recordcount#<br>
    currentrow=#currentrow#<br>
    columnlist=#columnlist#<br>
    recordssearched=#recordssearched#<br>
</cfoutput>
<cfdump var = #snippets#>
<br>

<!--- #3 (search by CF key) ----------------------------->
<cfsearch
    name = "book"
    collection = "custom_book"
    criteria = "cf_key=bookid2"
    maxrows = "100">
<cfoutput>
    url=#book.url#<br>
    key=#book.key#<br>
    title=#book.titleE#<br>
    score=#book.score#<br>
    custom1=#book.custom1#<br>
    custom2=#book.custom2#<br>
    summary=#book.summary#<br>
    recordcount=#book.recordcount#<br>
    currentrow=#book.currentrow#<br>
    columnlist=#book.columnlist#<br>
    recordssearched=#book.recordssearched#<br>
</cfoutput>
<cfdump var = #book#>
Next


cfselect

Description

Constructs a drop-down list box form control. Used within a cfform tag. You can populate the list from a query, or by using the HTML option tag.

Category

Forms tags

Syntax

<cfselect
    name = "name"
label = "label"
style = "style specification"
    size = "integer"
    required = "yes" or "no"
    message = "text"
    onError = "text"
    multiple = "yes" or "no"
    query = "queryname"
    value = "text"
    display = "text">
    group = "query column name
    queryPosition = "above" or "below"
    selected = "value or list"
onKeyUp = "JavaScript or ActionScript"
onKeyDown = "JavaScript or ActionScript"
onMouseUp = "JavaScript or ActionScript"
onMouseDown = "JavaScript or ActionScript"
onChange = "JavaScript or ActionScript"
onClick = "JavaScript or ActionScript"
visible = "Yes" or "No"
enabled = "Yes" or "No"
tooltip = "tip text"
height = "number of pixels" Flash only
width = "number of pixels" Flash only
>
zero or more HTML option tags
</cfselect>

See also

cfapplet, cfcalendar, cfform, cfformgroup, cfformitem, cfgrid, cfinput, cfslider, cftextarea, cftree; Introduction to Retrieving and Formatting Data in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added support for specifying multiple values to the selected attribute.
  • Deprecated the passthrough attribute. The tag now supports all HTML select tag attributes directly.
  • Added on-prefixed attributes.
  • Added enabled, group, height, label, queryPosition, tooltip, visible, and width attributes.

Attributes

The following table lists attributes that ColdFusion uses directly. The tag also supports all HTML select tag attributes that are not on this list, and passes them directly to the browser.

Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML.

Attribute

Req/Opt;

Format

Default

Description

name

Required;

All

Name of the select form element.

label

Optional;

Flash and XML

Label to put next to the control on a Flash or XML-format form.

style

Optional;

All

In HTML or XML format forms, ColdFusion passes the style attribute to the browser or XML.

In Flash format, must be a style specification in CSS format, with the same syntax and contents as used in Macromedia Flex for the corresponding Flash element.

size

Optional;

All

1

Number of entries to display at one time. The default, 1, displays a drop-down list. Any other value displays a list box with size number of entries visible at one time.

required

Optional;

All

No
  • Yes: a list element must be selected when the form is submitted.

Note: This attribute has no effect if you omit the size attribute or set it to 1, because the browser always submits the displayed item. You can work around this issue: format forms by having an initial option tag with value=" " (note the space character between the quotation marks).

  • No

message

Optional;

All

Message to display if required = "Yes" and no selection is made.

onError

Optional;

HTML and XML

Custom JavaScript function to execute if validation fails.

multiple

Optional;

All

No
  • Yes: allows selecting multiple elements in drop-down list.
  • No

query

Optional;

All

Name of query to populate drop-down list.

value

Optional;

All

Query column to use for the value of each list element. Used with the query attribute.

display

Optional;

All

Value of value attribute

Query column to use for the display label of each list element. Used with the query attribute.

group

Optional; HTML and XML

Query column to use to group the items in the drop-down list into a two-level hierarchical list.

queryPosition

Optional;

All

above

If you populate the options list with a query and use HTML option child tags to specify additional entries, determines the location of the items from the query relative to the items from the option tags:

  • above: puts the query items above the options items.
  • below: puts the query items below the options items.

selected

Optional;

All

One or more option values to preselect in the selection list. To specify multiple values, use a comma-delimited list. This attribute applies only if selection list items are generated from a query. The cfform preservedata attribute value can override this value.

onKeyUp

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user releases a keyboard key in the control.

onKeyDown

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) ActionScript to run when the user presses a keyboard key in the control.

onMouseUp

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user presses a mouse button in the control.

onMouseDown

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user releases a mouse button in the control.

onChange

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the control changes due to user action.

onClick

Optional; HTML and XML

JavaScript to run when the user clicks the control.

enabled

Optional; Flash

Yes

Boolean value specifying whether the control is enabled. A disabled control appears in light gray. The inverse of the disabled attribute.

visible

Optional; Flash

Yes

Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank.

tooltip

Optional; Flash

Text to display when the mouse pointer hovers over the control.

height

Optional; Flash

The height of the control, in pixels.

width

Optional; Flash

The width of the control, in pixels.

Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML.

Usage

This tag requires an end tag and can include HTML option and optgroup child tags.

To ensure that a selected list box item persists across postbacks, use the cfform preserveData attribute with a list generated from a query. (This strategy works only with data that is populated from a query.)

If the cfform preserveData attribute is true and the form posts back to the same page, and if the control is populated by a query, the posted selection(s) for the cfselect control are used instead of the Selected attribute. For controls that are populated with regular HTML option tags, the developer must dynamically add the Selected attribute to the appropriate option tag(s).

The group option generates a query using SQL GROUP BY syntax and places the value column entries from each group in an indented list under the group column’s field value. This option generates an HTML optgroup tag for each entry in the group column.

Close each HTML option tag in the cfselect tag body with a </option> end tag. If you do not do so, and you specify queryPosition="below", the first item from the query might not appear in the list.

For this tag to work properly. the browser must be JavaScript-enabled.

For more information, see the cfform tag entry.

Example

The following example lets you select one or more employee names from a list of all employees, grouped by departments, and displays the selected names and the employee’s email addresses. It includes an option to get data for all employees.

<!--- Get the employee names from the database. --->
<!--- Use SQL to create a Name field with first and last names. --->
<cfquery name = "GetAllEmployees" dataSource = "cfdocexamples"
        cachedwithin="#createTimeSpan(0,1,0,0)#">
    SELECT Emp_ID, EMail, Phone, Department, FirstName, LastName, FirstName +' '
        +lastName as Name
    FROM   Employees
    GROUP BY Department, Emp_ID, EMail, Phone, FirstName, LastName, FirstName
</cfquery>

<h2>cfselect Example</h2>
<!-- The cfif statement is true if the form was submitted.
    Show the selected names. --->
<cfif IsDefined("form.employeeid")>
    <!--- The form was submitted. --->
    <h4>You Selected the following employees</h3>
    <cfif form.employeeid IS "">
        <!--- Select All option was selected. Show all employees. --->
        <cfoutput query="GetAllEmployees">
            #name#<br>
            Email: #email#<br><br>
        </cfoutput>
    <cfelse>
        <!--- Use a query of queries to get the data for the selected users.
            Form.employeeid is a comma-delimited list of selected employee IDs. --->
        <cfquery name = "GetSelectedEmployees" dbtype="query">
            SELECT Emp_ID, EMail, Phone, Department, FirstName, LastName, FirstName
                +' ' +lastName as Name
            FROM   GetAllEmployees
            WHERE Emp_ID in (#form.employeeid#)
        </cfquery>
        <!--- Display the names and e-mail addresses from the query. --->
        <cfoutput query="GetSelectedEmployees">
            #firstName# #lastName#<br>
            Email: #email#<br>
            <br>
        </cfoutput>
    </cfif>
</cfif>

<!--- The cfform tag posts back to the current page. --->
<h3>Select one or more employees</h3>
<cfform action = "#CGI.SCRIPT_NAME#">
    <!--- Use cfselect to present the query’s LastName column, grouped by department.
        Allow Multiple selections.--->
    <cfselect
        name = "employeeid"
        size = "15"
        multiple="yes"
        required = "Yes"
        message = "Select one or more employee names"
        query = "GetAllEmployees"
        group="Department"
        display ="name"
        value ="emp_id"
        queryPosition="Below">
        <!--- Add an option to select all employees. --->
        <option value = "">Select All</option>
    </cfselect><br><br>
    <input type="Submit">
</cfform>


cfservlet

Description

This tag is deprecated. Executes a Java servlet on a JRun engine.

To access servlets that run on the same server as ColdFusion, use code such as the following, in which path specifies a servlet, JSP, or anything else:

GetPageContext().include(path)
GetPageContext().forward(path)

For more information, see the JSP PageContext API or the Servlet RequestDispatcher API.

History

ColdFusion MX: Deprecated this tag. It might not work, and it might cause an error, in later releases.


cfservletparam

Description

This tag is deprecated.

A child tag of the cfservlet tag. Passes data to a servlet. Each cfservletparam tag within the cfservlet block passes a separate item of data to the servlet.

To access servlets that run on the same server as ColdFUsion, use code such as the following, in which path specifies a servlet, JSP, or anything else:

GetPageContext().include(path)
GetPageContext().forward(path)

For more information, see the JSP PageContext API or the Servlet RequestDispatcher API.

History

ColdFusion MX: Deprecated this tag. It might not work, and it might cause an error, in later releases.


cfset

Description

Sets a value in ColdFusion. Used to create a variable, if it does not exist, and assign it a value. Also used to call functions.

Category

Variable manipulation tags

Syntax

<cfset
    var variable_name = expression
    >

See also

cfcookie, cfparam, cfregistry, cfsavecontent, cfschedule; Elements of CFML in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
var | Optional |  | A keyword. Does not take a value. Identifies the variable as being local to a function. The variable only exists for the time of the current invocation of the function.
variable_name | Required |  | A variable.

Usage

The following sections provide detailed descriptions of some of the uses for the cfset tag.

Calling functions

When you use the cfset tag to call a function, you do not need to assign the function return value to a variable if the function does not return a value or you do not need to use the value returned by the function. For example, the following line is a valid ColdFusion cfset tag for deleting the MyVariable variable from the Application scope:

<cfset StructDelete(Application, "MyVariable")>

Arrays

The following example assigns a new array to the variable months:

<cfset months = ArrayNew(1)>

This example creates a variable Array_Length that resolves to the length of the array Scores:

<cfset Array_Length = ArrayLen(Scores)>

This example assigns, to index position two in the array months, the value February:

<cfset months[2] = "February">

Dynamic variable names

In this example, the variable name is itself a variable:

<cfset myvariable = "current_value">
<cfset "#myvariable#" = 5>

Function local variables

The var keyword specifies that the variable being defined is only available inside the body of a function that you define using the cffunction tag. The variable value that is set in one invocation of the function is not available in any other invocation of the function. The var keyword is the equivalent of the var statement in CFScript. The following rules apply to the var keyword:

  • Any cfset tag that uses the var keyword must be inside the body of a cffunction tag. If you use the var keyword in a cfset tag outside a cffunction tag body, ColdFusion displays an error message.
  • You must place all cfset tags that use the var keyword at the beginning of the cffunction tag body, before any other ColdFusion tags.

The following example shows how to use the new keyword:

<cffunction name="myFunct">
   <cfset var myVar = "This is a test">
   <cfreturn myVar & " Message.">
</cffunction>
<cfoutput>#myFunct()#</cfoutput>

In this example, the variable myVar exists only when the function myFunct executes, and it is not available elsewhere on the ColdFusion page.

COM objects

In this example, a COM object is created. A cfset defines a value for each method or property in the COM object interface. The last cfset creates a variable to store the return value from the COM object’s SendMail method.

<cfobject action = "Create"
    name = "Mailer"
    class = "SMTPsvg.Mailer">

<cfset MAILER.FromName = form.fromname>
<cfset MAILER.RemoteHost = RemoteHost>
<cfset MAILER.FromAddress = form.fromemail>
<cfset MAILER.AddRecipient("form.fromname", "form.fromemail")>
<cfset MAILER.Subject = "Testing cfobject">
<cfset MAILER.BodyText = "form.msgbody">
<cfset Mailer.SMTPLog = "logfile">
<cfset success = MAILER.SendMail()>
<cfoutput> #success# </cfoutput>

Example

<!--- This example shows how to use cfset. --->
<cfquery name = "GetMessages" dataSource = "cfdocexamples">
    SELECT *
    FROM   Messages
</cfquery>

<h3>cfset Example</h3>
<p>cfset sets and reassigns values to local or global variables within a page.

<cfset NumRecords = GetMessages.recordCount>
<p>For example, the variable NumRecords has been declared on this
page to hold the number of records returned from query
(<cfoutput>#NumRecords#</cfoutput>).

<p>In addition, cfset can be used to pass variables from other pages,
such as this example, which takes the url parameter Test from this link:
(<a href = "cfset.cfm?test = <cfoutput>
                        #URLEncodedFormat("hey, you, get off of my cloud")#					</cfoutput>
                    ">click here</A>) to display a message:
<p>
<cfif IsDefined ("url.test") is "True">
    <cfoutput><b><I>#url.test#</i></b></cfoutput>
<cfelse>
    <h3>The variable url.test has not been passed from another page.</h3>
</cfif>

<p>cfset can also be used to collect environmental variables, such as the
time, the IP address of the user, or another function or expression.

<cfset the_date = #DateFormat(Now())# & " " & #TimeFormat(Now())#>
<cfset user_ip = CGI.REMOTE_ADDR>
<cfset complex_expr = (23 MOD 12) * 3>
<cfset str_example = Reverse(Left(GetMessages.body, 35))>

<cfoutput>
    <ul>
        <li>The date: #the_date#
        <li>User IP Address: #user_ip#
        <li>Complex Expression ((23 MOD 12) * 3): #complex_expr#
        <li>String Manipulation (the first 35 characters of
                the body of the first message in our query)
                <br><b>Reversed</b>: #str_example#
                <br><b>Normal</b>: #Reverse(str_example)#
    </ul>
</cfoutput>


cfsetting

Description

Controls aspects of page processing, such as the output of HTML code in pages.

Category

Page processing tags, Variable manipulation tags

Syntax

<cfsetting
    enableCFoutputOnly = "yes" or "no"
    showDebugOutput = "yes" or "no"
    requestTimeOut = "value in seconds" >

See also

cfcache, cfflush, cfheader, cfhtmlhead, cfinclude, cfprocessingdirective, cfsilent; Controlling debugging output with the cfsetting tag in Debugging and Troubleshooting Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.1: Changed behavior: if the tag has a body, ColdFusion executes its contents.

ColdFusion MX:

  • Added the requestTimeOut attribute.
  • The catchExceptionsByPattern attribute is obsolete. It does not work, and causes an error, in releases later than ColdFusion 5.
  • Changed exception handling: the structured exception manager searches for the best-fit cfcatch handler. (In earlier releases, an exception was handled by the first cfcatch block that could handle an exception of its type.)

Attributes

Attribute

Req/Opt

Default

Description

enableCFoutputOnly

Required

  • Yes: blocks output of HTML that is outside cfoutput tags.
  • No: displays HTML that is outside cfoutput tags.

showDebugOutput

Optional

Yes
  • Yes: if debugging is enabled in the Administrator, displays debugging information.
  • No: suppresses debugging information that would otherwise display at the end of the generated page.

requestTimeout

Optional

  • Integer; number of seconds. Time limit, after which ColdFusion processes the page as an unresponsive thread. Overrides the timeout set in the ColdFusion Administrator.

Usage

The cfsetting requestTimeout attribute replaces the use of requestTimeOut within a URL. To enforce a page timeout, detect the URL variable and use code such as the following to change the page timeout:

<cfsetting RequestTimeout = "#URL.RequestTimeout#">

You can use this tag to manage whitespace in ColdFusion output pages.

If you nest cfsetting tags: to make HTML output visible, you must match each enableCFoutputOnly = "Yes" statement with an enableCFoutputOnly = "No" statement. For example, after five enableCFoutputOnly = "Yes" statements, to enable HTML output, you must have five corresponding enableCFoutputOnly = "No" statements.

If HTML output is enabled (no matter how many enableCFoutputOnly = "No" statements have been processed) the first enableCFoutputOnly = "Yes" statement blocks output.

If the debugging service is enabled and showDebugOutput =" Yes", the IsDebugMode function returns Yes; otherwise, No.

Note: Releases after ColdFusion MX allow a </cfsetting> end tag; however, this end tag does not affect processing. The cfsetting attributes affect code inside and outside the cfsetting tag body. ColdFusion MX ignored code between cfsetting start and end tags.

Example

<p>CFSETTING is used to control the output of HTML code in ColdFusion pages.
    This tag can be used to minimize the amount of generated whitespace.

<cfsetting enableCFoutputOnly = "Yes">
    This text is not shown
<cfsetting enableCFoutputOnly = "No">
    <p>This text is shown
<cfsetting enableCFoutputOnly = "Yes">
    <cfoutput>
        <p>Text within cfoutput is always shown
    </cfoutput>
<cfsetting enableCFoutputOnly = "No">
    <cfoutput>
        <p>Text within cfoutput is always shown
    </cfoutput>


cfsilent

Description

Suppresses output produced by CFML within a tag’s scope.

Category

Data output tags, Page processing tags

Syntax

<cfsilent>
...
</cfsilent>

See also

cfcache, cfflush, cfheader, cfhtmlhead, cfinclude, cfsetting; Writing and Calling User-Defined Functions in ColdFusion MX Developer’s Guide

Usage

This tag requires an end tag.

Example

<h3>cfsilent</h3>

<cfsilent>
  <cfset a = 100>
  <cfset b = 99>
  <cfset c = b-a>
  <cfoutput>Inside cfsilent block<br>
  b-a = #c#</cfoutput><br>
</cfsilent>

<p>Even information within cfoutput tags does not display within a
cfsilent block.<br>
<cfoutput>
    b-a = #c#
</cfoutput>
</p>


cfslider

Description

Puts a slider control, for selecting a numeric value from a range, in a ColdFusion form. The slider moves over the slider groove. As the user moves the slider, the current value displays. Used within a cfform tag. Not supported with Flash forms.

Category

Forms tags

Syntax

<cfslider
name = "name"
    label = "text"
    range = "min_value, max_value"
    scale = "uinteger"
    value = "integer"
    onValidate = "script_name"
    message = "text"
    onError = "text"
    height = "integer"
    width = "integer"
    vSpace = "integer"
    hSpace = "integer"
    align = "alignment"
    lookAndFeel = "motif" or "windows" or "metal"
    vertical = "yes" or "no"
    bgColor = "color"
    textColor = "color"
    font = "font_name"
    fontSize = "integer"
    italic = "yes" or "no"
    bold = "yes" or "no"
    notSupported = "text">

See also

cfapplet, cfcalendar, cfform, cfformgroup, cfformitem, cfgrid, cfinput, cfselect, cftextarea, cftree; Introduction to Retrieving and Formatting Data and Building Dynamic Forms with cfform Tagsin ColdFusion MX Developer’s Guide

History

ColdFusion MX: Deprecated the img, imgStyle, grooveColor, refreshLabel, tickmarklabels, tickmarkmajor, tickmarkminor, and tickmarkimages attributes. They might not work, and might cause an error, in later releases.

Attributes

Attribute

Req/Opt

Default

Description

name

Required

Name of cfslider control.

label

Optional

Label to display with control; for example, "Volume" This displays: "Volume %value%"

To reference the value, use "%value%". If %% is omitted, slider value displays directly after label.

range

Optional

"0,100"

Numeric slider range values.

Separate values with a comma.

scale

Optional

Unsigned integer. Defines slider scale, within range. For example, if range = "0,1000" and scale = "100", the display values are:
0, 100, 200, 300, ...

Signed and unsigned integers in ColdFusion are in the range -2,147,483,648 to 2,147,483,647.

value

Optional

Minimum in range

Starting slider setting. Must be within the range values.

onValidate

Optional

Custom JavaScript function to validate user input; in this case, a change to the default slider value.

Specify only the function name.

message

Optional

Message text to appear if validation fails.

onError

Optional

Custom JavaScript function to execute if validation fails.

Specify only the function name.

height

Optional

40

Slider control height, in pixels.

width

Optional

Slider control width, in pixels.

vSpace

Optional

Vertical spacing above and below slider, in pixels.

hSpace

Optional

Horizontal spacing to left and right of slider, in pixels.

align

Optional

Alignment of slider:

  • top
  • left
  • bottom
  • baseline
  • texttop
  • absbottom
  • middle
  • absmiddle
  • right

lookAndFeel

Optional

Windows
  • motif: renders slider using Motif style.
  • windows: renders slider using Windows style.
  • metal: renders slider using Java Swing style.

If platform does not support choice, the tag defaults to the platform’s default style.

vertical

Optional

No
  • Yes: renders slider in browser vertically. You must set width and height attributes; ColdFusion does not automatically swap width and height values.
  • No: renders slider horizontally.

bgColor

Optional

Background color of slider label.

For a hexadecimal value, use the form: bgColor = "##xxxxxx", where x = 0-9 or A-F; use two number signs or none.

  • Any color, in hexadecimal format
  • black
  • red
  • blue
  • magenta
  • cyan
  • orange
  • darkgray
  • pink
  • gray
  • white
  • lightgray
  • yellow

textColor

Optional

Options: same as for bgcolor attribute.

font

Optional

Font name for label text.

fontSize

Optional

Font size for label text, in points.

italic

Optional

No
  • Yes: label text in italics.
  • No: normal text.

bold

Optional

No
  • Yes: label text in bold.
  • No: medium text.

notSupported

Optional

Text to display if a page that contains a Java applet-based cfform control is opened by a browser that does not support Java or has Java support disabled. For example:

"<b> Browser must support Java to view ColdFusion Java Applets</b>"

Default message:

<b>Browser must support Java to <br>view ColdFusion Java Applets!</b>

Usage

This tag requires the client to download a Java applet. Using this tag may be slightly slower than using an HTML form element to display the same information. Also, if the client does not have an up-to-date Java plugin installed, the system might also have to download an updated Java plugin to display the tag.

For this tag to work properly, the browser must be JavaScript-enabled.

If the following conditions are true, a user’s selection from query data that populates this tag’s options continues to display after the user submits the form:

  • The cfform preserveData attribute is set to "Yes".
  • The cfform action attribute posts to the same page as the form itself (this is the default), or the action page has a form that contains controls with the same names as corresponding controls on the user entry form.

For more information, see the cfform tag entry.

Example

<!--- This example shows how to use cfslider within cfform. --->
<h3>cfslider Example</h3>
<p>cfslider, used within a cfform, can provide functionality
    to Java-enabled browsers.
<p>Try moving the slider back and forth to see the real-time value change.
    Then, submit the form to show how cfslider passes its value on to a new page.
<cfif isdefined("form.mySlider") is true>
    <h3>You slid to a value of 	<cfoutput>#mySlider#</cfoutput></h3>
    Try again!
</cfif>
<cfform action = "cfslider.cfm">
    <cfslider name = "mySlider" value = "12"
        label = "Actual Slider Value "
        range = "1,100" align = "BASELINE"
        message = "Slide the bar to get a value between 1 and 100"
        height = "50" 		width = "150" font = "Verdana"
        bgColor = "Silver" bold = "No"
        italic = "Yes" refreshLabel = "Yes"> 100
<p><input type = "Submit" name = "" value = "Show the Result">
</cfform>


cfstoredproc

Description

Executes a stored procedure in a server database. It specifies database connection information and identifies the stored procedure.

Category

Database manipulation tags

Syntax

<cfstoredproc
    procedure = "procedure name"
    dataSource = "ds_name"
    username = "username"
    password = "password"
    blockFactor = "blocksize"
    debug = "yes" or "no"
    returnCode = "yes" or "no">
result = "result_name"

See also

cfinsert, cfqueryparam, cfprocparam, cfprocresult, cftransaction, cfquery, cfupdate; Optimizing database use in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the result attribute.

ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider, and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5. (ColdFusion MX uses Type 4 JDBC drivers.)

Attributes

Attribute

Req/Opt

Default

Description

procedure

Required

Name of stored procedure on database server.

dataSource

Required

Name of data source that points to database that contains stored procedure.

username

Optional

Overrides username in data source setup.

password

Optional

Overrides password in data source setup.

blockFactor

Optional

1

Maximum number of rows to get at a time from server. Range is 1 to 100.

debug

Optional

No
  • Yes: lists debug information on each statement.
  • No

returnCode

Optional

No
  • Yes: populates cfstoredproc.statusCode with status code returned by the stored procedure.
  • No

result

Optional

Specifies a name for the structure in which cfstoredproc returns the statusCode and ExecutionTime variables. If set, this value replaces cfstoredproc as the prefix to use when accessing those variables. For more information, see the Usage section.

Usage

Use this tag to call a database stored procedure. Within this tag, you code cfprocresult and cfprocparam tags as follows:

  • cfprocresult If the stored procedure returns one or more result sets, code one cfprocresult tag per result set.
  • cfprocparam If the stored procedure uses input or output parameters, code one cfprocparam tag per parameter, ensuring that you include every parameter in the stored procedure definition. Additionally, you must code cfprocparam tags in the same order as the parameters in the stored procedure definition.

If you set returnCode = "Yes", this tag sets the variable prefix.statusCode, which holds the status code for a stored procedure. Status code values vary by DBMS. For the meaning of code values, see your DBMS documentation.

This tag sets the variable prefix.ExecutionTime, which contains the execution time of the stored procedure, in milliseconds.

The value of prefix is either cfstoredproc or the value specified by the result attribute, if it is set. The result attribute provides a way for stored procedures that are called from multiple pages, possibly at the same time, to avoid overwriting the results of one call with another. If you set the result attribute to myResult, for example, you would access ExecutionTime as myResult.ExecutionTime. Otherwise, you would access it as cfstoredproc.ExecutionTime.

Before implementing this tag, ensure that you understand stored procedures and their usage.

The following examples use a Sybase stored procedure; for an example of an Oracle 8 or 9 stored procedure, see cfprocparam.

Example

<!--- This view-only example executes a Sybase stored procedure that
returns three result sets, two of which we want. The stored
procedure returns the status code and one output parameter,
which we display. We use named notation for the parameters. --->
<!---
<cfstoredproc procedure = "foo_proc"
    dataSource = "MY_SYBASE_TEST" username = "sa"
    password = "" dbServer = "scup" dbName = "pubs2"
    returnCode = "Yes" debug = "Yes">
    <cfprocresult name = RS1>
    <cfprocresult name = RS3 resultSet = 3>

    <cfprocparam type = "IN" 		CFSQLType = CF_SQL_INTEGER
            value = "1" dbVarName = @param1>
    <cfprocparam type = "OUT" CFSQLType = CF_SQL_DATE
        variable = FOO dbVarName = @param2>
</cfstoredproc>
--->
<!---
<cfoutput>	The output param value: ’#foo#’<br></cfoutput>
<h3>The Results Information</h3>
<cfoutput query = RS1>#name#,#DATE_COL#<br></cfoutput><p>
<cfoutput>
    <hr>
    <p>Record Count: #RS1.recordCount# >p>Columns: #RS1.columnList#	<hr>
</cfoutput>
<cfoutput query = RS3>#col1#,#col2#,#col3#<br>
</cfoutput><p>
<cfoutput>
    <hr>
    <p>Record Count: #RS3.recordCount# <p>Columns: #RS3.columnList#	<hr>
    The return code for the stored procedure is: ’#cfstoredproc.statusCode#’<br>
</cfoutput>
--->


cfswitch

Description

Evaluates a passed expression and passes control to the cfcase tag that matches the expression result. You can, optionally, code a cfdefaultcase tag, which receives control if there is no matching cfcase tag value.

Category

Flow-control tags

Syntax

<cfswitch
    expression = "expression">
        one or more cfcase tags
        zero or one cfdefaultcase tags
</cfswitch>

See also

cfcase, cfdefaultcase, cfabort, cfloop, cfbreak, cfexecute, cfexit, cfif, cflocation, cfrethrow, cfthrow, cftry; cfswitch, cfcase, and cfdefaultcase in Elements of CFML in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed cfdefaultcase tag placement requirements: you can put the cfdefaultcase tag at any position within a cfswitch statement; it is not required to be the last item.

Attributes

Attribute | Req/Opt | Default | Description
expression | Required |  | ColdFusion expression that yields a scalar value. ColdFusion converts integers, real numbers, Booleans, and dates to numeric values. For example, True, 1, and 1.0 are all equal.

Usage

This tag requires an end tag. All code within this tag must be within a cfcase or cfdefaultcase tag. Otherwise, ColdFusion throws an error.

Use this tag followed by one or more cfcase tags. Optionally, include a cfdefaultcase tag. This tag selects the matching alternative from the cfcase and cfdefaultcase tags, jumps to the matching tag, and executes the code between the cfcase start and end tags.

The cfswitch tag provides better performance than a series of cfif/cfelseif tags, and the code is easier to read.

Example

<!--- This example shows the use of cfswitch and cfcase to
exercise a case statement in CFML. --->
<cfquery name = "GetEmployees" dataSource = "cfdocexamples">
    SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
    FROM   Employees
</cfquery>

<h3>cfswitch Example</h3>
<!--- By outputting the query and using cfswitch, we classify the
output without using a cfloop construct. --->
<p>Each time the case is fulfilled, the specific information is printed;
if the case is not fulfilled, the default case is output </p>
<cfoutput query="GetEmployees">
<cfswitch expression="#Trim(Department)#">
    <cfcase value="Sales">
        #FirstName# #LastName# is in <b>sales</b><br><br>
    </cfcase>
    <cfcase value="Accounting">
        #FirstName# #LastName# is in <b>accounting</b><br><br>
    </cfcase> <cfcase value="Administration">
        #FirstName# #LastName# is in <b>administration</b><br><br>
    </cfcase>
    <cfdefaultcase>
        #FirstName# #LastName# is not in Sales, Accounting, or
            Administration.<br><br>
    </cfdefaultcase>
</cfswitch>
</cfoutput>


cftable

Description

Builds a table in a ColdFusion page. This tag renders data as preformatted text, or, with the HTMLTable attribute, in an HTML table. If you don't want to write HTML table tag code, or if your data can be presented as preformatted text, use this tag.

Preformatted text (defined in HTML with the <pre> and </pre> tags) displays text in a fixed-width font. It displays white space and line breaks exactly as they are written within the pre tags. For more information, see an HTML reference guide.

To define table column and row characteristics, use the cfcol tag within this tag.

Category

Data output tags

Syntax

<cftable
    query = "query_name"
    maxRows = "maxrows_table"
    colSpacing = "number_of_spaces"
    headerLines = "number_of_lines"
    HTMLTable
    border
    colHeaders
    startRow = "row_number">
    ...
</cftable>

See also

cfcol, cfcontent, cflog, cfoutput, cfprocessingdirective, cftable; Retrieving data in Accessing and Retrieving Data in ColdFusion MX Developer’s Guide

Attributes

Attribute | Req/Opt | Default | Description
query | Required |  | Name of cfquery from which to draw data.
maxRows | Optional |  | Maximum number of rows to display in the table.
colSpacing | Optional | 2 | Number of spaces between columns.
headerLines | Optional | 2 | Number of lines to use for table header (the default leaves one line between header and first row of table).
HTMLTable | Optional |  | Renders data in an HTML 3.0 table. If you use this attribute (regardless of its value), ColdFusion renders data in an HTML table.
border | Optional |  | Displays border around table. If you use this attribute (regardless of its value), ColdFusion displays a border around the table. Use this only if you use the HTMLTable attribute.
colHeaders | Optional |  | Displays column heads. If you use this attribute, you must also use the cfcol tag header attribute to define them. If you use this attribute (regardless of its value), ColdFusion displays column heads.
startRow | Optional | 1 | The query result row to put in the first table row.

Usage

This tag aligns table data, sets column widths, and defines column heads.

At least one cfcol tag is required within this tag. You must put cfcol and cftable tags adjacent in a page. The only tag that you can nest within this tag is the cfcol tag. You cannot nest cftable tags.

To display the cfcol header text, you must specify the cfcol header and the cftable colHeader attribute. If you specify either attribute without the other, the header does not display and no error is thrown.

Example

<!--- This example shows the use of cfcol and cftable to align information
returned from a query. --->
<!--- This query selects employee information from cfdocexamples
datasource. --->
<cfquery name = "GetEmployees" dataSource = "cfdocexamples">
    SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
    FROM Employees
</cfquery>

<html>
<body>
<h3>cftable Example</h3>

<!--- Note use of HTMLTable attribute to display cftable as an HTML table,
rather than as PRE formatted information. --->
<cftable query = "GetEmployees"
    startRow = "1" colSpacing = "3" HTMLTable>
<!--- Each cfcol tag sets width of a column in table, and specifies header
information and text/CFML with which to fill cell. --->
    <cfcol header = "<b>ID</b>"
        align = "Left"
        width = 2
        text  = "#Emp_ID#">

    <cfcol header = "<b>Name/Email</b>"
        align = "Left"
        width = 15
        text  = "<a href = ’mailto:#Email#’>#FirstName# #LastName#</A>">

    <cfcol header = "<b>Phone Number</b>"
        align = "Center"
        width = 15
        text  = "#Phone#">
</cftable>
</body>
</html>


cftextarea

Description

Puts a multiline text entry box in a cfform tag and controls its display characteristics.

Category

Forms tags

Syntax

<cftextarea
name = "name"
label = "text"
required = "yes" or "no"
style = "style specification"
validate = "data type"
validateAt= one or more of "onBlur", "onServer", "onSubmit"
message = "text"
range = "min_value, max_value"
maxlength = "number"
pattern = "regexp"
onValidate = "script name"
onError = "script name"
disabled = "true" "false" or no attribute value
value = "text"
onKeyUp = "JavaScript or ActionScript"
onKeyDown = "JavaScript or ActionScript"
onMouseUp = "JavaScript or ActionScript"
onMouseDown = "JavaScript or ActionScript"
onChange = "JavaScript or ActionScript"
onClick = "JavaScript or ActionScript"
visible = "Yes" or "No"
enabled = "Yes" or "No"
tooltip = "Tip text"
height = "number of pixels" Flash only
width = "number of pixels" Flash only
>
   text
</cftextarea>

See also

cfapplet, cfcalendar, cfform, cfformgroup, cfformitem, cfgrid, cfinput, cfselect, cfslider, cftree; Introduction to Retrieving and Formatting Data in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this tag.

Attributes

The following table lists attributes that ColdFusion uses directly. In HTML format, the tag also supports all HTML textarea tag attributes that are not on this list, and passes them directly to the browser.

Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML.

Attribute

Req/Opt;

Format

Default

Description

name

Required;

All

Name of the cftextinput control.

label

Optional;

Flash and XML

Label to put beside the control on a form.

style

Optional;

All

In HTML or XML format forms, ColdFusion passes the style attribute to the browser or XML.

In Flash format forms, must be a style specification in CSS format, with the same syntax and contents as used in Macromedia Flex for the corresponding Flash element.

required

Optional;

All

no
  • yes: the field must contain text.
  • no: the field can be empty.

validate

Optional;

All

The type or types of validation to do. Available validation types and algorithms depend on the format. For details, see the Usage section of the cfinput tag reference.

validateAt

Optional;

HTML and XML

onSubmit

How to do the validation; one or more of the following:

  • onSubmit
  • onServer
  • onBlur

For Flash format forms, onSubmit and onBlur are identical; validation is done when the user submits the form. For multiple values, use a comma-delimited list.

For details, see the Usage section of the cfinput tag reference.

message

Optional;

All

Message text to display if validation fails.

range

Optional;

All

Minimum and maximum allowed numeric values. ColdFusion uses this attribute only if you specify range in the validate attribute.

If you specify a single number or a single number followed by a comma, it is treated as a minimum, with no maximum. If you specify a comma followed by a number, the maximum is set to the specified number, with no minimum.

maxLength

Optional;

All

The maximum length of text that can be entered. ColdFusion uses this attribute only if you specify maxlength in the validate attribute.

pattern

Required if validate = "regular_
expression"

HTML and XML.

JavaScript regular expression pattern to validate input. Omit leading and trailing slashes. ColdFusion uses this attribute only if you specify regex in the validate attribute. For examples and syntax, see Building Dynamic Forms with cfform Tags in ColdFusion MX Developer’s Guide.

onValidate

Optional;

HTML and XML

Custom JavaScript function to validate user input. The JavaScript DOM form object, input object, and input object value are passed to routine, which should return True if validation succeeds, False otherwise. If you specify this attribute, ColdFusion ignores the validate attribute.

onError

Optional;

HTML and XML

Custom JavaScript function to execute if validation fails.

disabled

Optional;

All

not disabled

Disables user input, making the control read-only. To disable input, specify disabled without an attribute, or disabled="Yes" (or any ColdFusion positive Boolean value, such as True). To enable input, omit the attribute or specify disabled="No" (or any ColdFusion negative Boolean value, such as False).

value

Optional;

All

Initial value to display in text control. You can specify an initial value as an attribute or in the tag body, but not in both places. If you specify the value as an attribute, you must put the closing cftextarea tag immediately after the opening cftextarea tag, with no spaces or line feeds between, or place a closing slash at the end of the opening cftextarea tag; for example <cftextarea name="description" value="Enter a description." />.

bind

Optional;

Flash

A Flex bind expression that populates the field with information from other form fields. For details, see Usage.

onKeyUp

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user releases a keyboard key in the control.

onKeyDown

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) ActionScript to run when the user presses a keyboard key in the control.

onMouseUp

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user presses a mouse button in the control.

onMouseDown

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the user releases a mouse button in the control.

onChange

Optional;

All

JavaScript (HTML/XML) or ActionScript (Flash) to run when the control changes due to user action.

onClick

Optional;

All

JavaScript (HTML/XML) to run when the user clicks the control. Not supported for Flash forms.

enabled

Optional;

Flash

Yes

Boolean value specifying whether the control is enabled. A disabled control appears in light gray. The inverse of the disabled attribute.

visible

Optional;

Flash

Yes

Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank.

tooltip

Optional;

Flash

Text to display when the mouse pointer hovers over the control.

height

Optional;

Flash

The height of the control, in pixels.

width

Optional;

Flash

The width of the control, in pixels.

Note: Attributes that are marked as Flash only are not handled by the skins provided with ColdFusion MX. They are, however, included in the generated XML.

Usage

For this tag to work properly in HTML format. the browser must be JavaScript-enabled.

If you put text in the tag body, the control displays all text characters between the cftextarea opening and closing tags; therefore, if you use line feeds or white space to format your source text, they appear in the control.

If the cfform preserveData attribute is "yes", and the form posts back to the same page, the posted value (not the value of the value attribute) of the cftextinput control is used.

Validation

For a detailed description of the validation attribute and the types of validation supported by ColdFusion, see the Usage section of the cfinput tag reference. For more details on ColdFusion MX validation techniques, see Validating Data in ColdFusion MX Developer’s Guide.

Flash form data binding

The bind attribute lets you populate form fields using the contents of other form fields. To specify text from another field in a cftextarea bind attribute, use the following format:

{sourceTagName.text}

For example, the following line uses the value of the text that the user enters in the from the userName field in the greeting in the comment text box. The user can change or replace this message with a typed entry.

<cfformitem type="text">
Enter your name here</cfformitem>
<cftextarea name="userName" height="20" Width="500"/>
<cftextarea name="comment" html height="300" Width="500"
    bind="Hello {userName.text}!
 Enter your comments here." />

Example

This example has two cftextarea controls. When you submit the form, ColdFusion copies the text from the first control into the second. The onBlur maxlength validation prevents you from entering more than 100 characters. The > character that closes the cftextarea opening tag, the text in the tag body, and the cftextarea closing tag are on a single line to ensure that only the desired text displays, but the line is split in this example for formatting purposes.

<h3>cftextarea Example</h3>
<cfparam name="text2" default="">
<cfif isdefined("form.textarea1") AND (form.textarea1 NEQ "")>
    <cfset text2=form.textarea1>
</cfif>

<cfform name="form1">
    <cftextarea name="textarea1" wrap="virtual" rows="5" cols="25"
    validate="maxlength" validateAt="onBlur" maxlength="100"
    >Replace this text. Maximum length is 100 Characters, and this text is
currently 99 characters long.</cftextarea>
    <cftextarea name="textarea2" wrap="virtual" rows="5" cols="50" value="#text2#" /><br><br>
    <input type="submit" value="submit field"><br>
</cfform>


cftextinput

Description

Puts a single-line text entry box in a cfform tag and controls its display characteristics.

This tag is deprecated, and is not supported in XML format forms. In its place, you should use a cfinput or cftextarea tag and use a cascading style sheet (CSS) to specify the text style characteristics.

History

ColdFusion MX 7: This tag is deprecated. In later releases it might not work, and might cause an error.

ColdFusion MX 6.1: Changed the validate = "creditcard" option requirements: the text entry must have 13-16 digits.


cfthrow

Description

Throws a developer-specified exception, which can be caught with a cfcatch tag that has any of the following type attribute options:

  • type = "custom_type"
  • type = "Application"
  • type = "Any"

Category

Exception handling tags, Flow-control tags

Syntax 1

<cfthrow
    type = "exception_type "
    message = "message"
    detail = "detail_description "
    errorCode = "error_code "
    extendedInfo = "additional_information"
    object = "java_except_object">

Syntax 2

<cfthrow
    object = #object_name#>

See also

cferror, cfrethrow, cftry, onError; Handling Errors in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed thrown exceptions: this tag can throw ColdFusion component method exceptions.

Attributes

Attribute

Req/Opt

Default

Description

type

Optional

Application
  • A custom type
  • Application

Do not enter another predefined type; types are not generated by ColdFusion applications. If you specify Application, you need not specify a type for cfcatch.

message

Optional

Message that describes exception event.

detail

Optional

Description of the event. ColdFusion appends error position to description; server uses this parameter if an error is not caught by your code.

errorCode

Optional

A custom error code that you supply.

extendedInfo

Optional

A custom error code that you supply.

object

Optional

Requires the value of the cfobject tag name attribute.

Throws a Java exception from a CFML tag.

This attribute is mutually exclusive with all other attributes of this tag.

Usage

Use this tag within a cftry block, to throw an error. The cfcatch block can access accompanying information, as follows:

  • Message, with cfcatch.message
  • Detail, with cfcatch.detail
  • Error code, with cfcatch.errorcode

To get more information, use cfcatch.tagContext. This array shows where control switches from one page to another in the tag stack (for example, cfinclude, cfmodule).

To display the information displayed by tagContext: in the ColdFusion MX Administrator, Debugging page, select Enable CFML Stack Trace.

Using the object parameter To use this tag with the object parameter, you must first use a cfobject tag that specifies a valid Java exception class. For example, the following cfobject tag defines an object, obj, of the exception class myException (which you must create in Java):

<cfobject
type="java"
action="create"
class="myException"
name="obj">

If your exception class has constructors that take parameters, such as a message, you can use the special init method to invoke the constructor, as in the following line. If you do not need to specify any constructor attributes, you can omit this step.

<cfset obj.init("You must save your work before preceding")>

You can then use the, the cfthrow statement to throw the exception as follows:

<cfthrow object=#obj#>

For more information on using Java objects in ColdFusion, see Integrating J2EE and Java Elements in CFML Applications in ColdFusion MX Developer’s Guide.

Example 1

<h3>cfthrow Example</h3>
<!--- Open a cftry block. --->
<cftry>
<!--- Define a condition upon which to throw the error. --->
<cfif NOT IsDefined("URL.myID")>
    <!--- throw the error --->
    <cfthrow message = "ID is not defined">
</cfif>

<!--- Perform the error catch. --->
<cfcatch type = "application">
<!--- Display your message. --->
    <h3>You've Thrown an <b>Error</b></h3>
<cfoutput>
    <!--- And the diagnostic feedback from the application server. --->
  <p>#cfcatch.message#</p>
    <p>The contents of the tag stack are:</p>
    <cfloop
        index = i
        from = 1 to = #ArrayLen(cfcatch.tagContext)#>
             <cfset sCurrent = #cfcatch.tagContext[i]#>
                 <br>#i# #sCurrent["ID"]#
                (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#)
                #sCurrent["TEMPLATE"]#
    </cfloop>
</cfoutput>
</cfcatch>
</cftry>

Example2

The following example shows how to throw an exception from a component method:

<cfcomponent>
    <cffunction name="getEmp">
    <cfargument name="lastName" required="yes">
         <cfquery name="empQuery" datasource="cfdocexamples" >
             SELECT LASTNAME, FIRSTNAME, EMAIL
             FROM tblEmployees
            WHERE LASTNAME LIKE '#arguments.lastName#'
         </cfquery>
         <cfif empQuery.recordcount LT 1>
             <cfthrow type="noQueryResult"
                message="No results were found. Please try again.">
            <cfelse>
                  <cfreturn empQuery>
          </cfif>
    </cffunction>
</cfcomponent>

For an explanation of the example and more information, see Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide.


cftimer

Description

Displays execution time for a specified section of CFML code. ColdFusion MX displays the timing information along with any output produced by the timed code.

Note: To permit this tag to execute, you must enable the Timer Information option under Debugging Settings in the ColdFusion MX Administrator.

Category

Debugging tags

Syntax

<cftimer
    label= "text"
    type = "inline" or "outline" or "comment" or "debug" >

    CFML statement(s)

</cftimer>

See also

cfdump, cftrace; Debugging and Troubleshooting Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

label

Optional

" "

Label to display with timing information.

type

Optional

debug
  • inline: displays timing information inline, following the resulting HTML.
  • outline: displays timing information and also displays a line around the output produced by the timed code. The browser must support the FIELDSET tag to display the outline.
  • comment: displays timing information in an HTML comment in the format <!-- label: elapsed-time ms -->. The default label is cftimer.
  • debug: displays timing information in the debug output under the heading CFTimer Times.

Usage

Use this tag to determine how long it takes for a block of code to execute. You can nest cftimer tags.

This tag is useful for debugging CFML code during application development. In production, you can leave cftimer tags in your code as long as you have disabled the debugging option in the ColdFusion MX Administrator.

Example1

...
<!--- type="inline"> --->
     <cftimer label="Query and Loop Time Inline" type="inline">
        <cfquery name="empquery" datasource="cfdocexamples">
                select *
                from Employees
        </cfquery>

        <cfloop query="empquery">
          <cfoutput>#lastname#, #firstname#</cfoutput><br>
        </cfloop>
    </cftimer>
<hr><br>

<!--- type="outline" --->
     <cftimer label="Query and CFOUTPUT Time with Outline" type="outline">
        <cfquery name="coursequery" datasource="cfdocexamples">
                select *
                from CourseList
        </cfquery>
    <table border="1" width="100%">
        <cfoutput query="coursequery">
        <tr>
        <td>#Course_ID#</td>
        <td>#CorName#</td>
        <td>#CorLevel#</td>
        </tr>
        </cfoutput>
        </table>
    </cftimer>
<hr><br>

<!--- type="comment" --->
     <cftimer label="Query and CFOUTPUT Time in Comment" type="comment">
        <cfquery name="parkquery" datasource="cfdocexamples">
                select *
                from Parks
        </cfquery>
        <p>Select View &gt; Source to see timing information</p>
        <table border="1" width="100%">
        <cfoutput query="parkquery">
        <tr>
        <td>#Parkname#</td>
        </tr>
        </cfoutput>
        </table>
    </cftimer>
<hr><br>

<!--- type="debug" --->
     <cftimer label="Query and CFOUTPUT Time in Debug Output" type="debug">
        <cfquery name="deptquery" datasource="cfdocexamples">
                select *
                from Departments
        </cfquery>
        <p>Scroll down to CFTimer Times heading to see timing information</p>
        <table border="1" width="100%">
        <cfoutput query="deptquery">
        <tr>
        <td>#Dept_ID#</td>
        <td>#Dept_Name#</td>
        </tr>
        </cfoutput>
        </table>
    </cftimer>
...


cftrace

Description

Displays and logs debugging data about the state of an application at the time the cftrace tag executes. Tracks runtime logic flow, variable values, and execution time. Displays output at the end of the request or in the debugging section at the end of the request; or, in Dreamweaver MX and later, in the Server Debug tab of the Results window.

ColdFusion logs cftrace output to the file logs\cftrace.log, in the ColdFusion installation directory.

Note: To permit this tag to execute, you must enable debugging in the ColdFusion MX Administrator. Optionally, to report trace summaries, enable the Trace section.

Category

Debugging tags, Variable manipulation tags

Syntax

<cftrace
    abort = "Yes" or "No"
    category = "string"
    inline = "Yes" or "No"
    text = "string"
    type = "format"
    var = "variable_name"
</cftrace>

See also

cfdump, cferror, cfrethrow, cftimer, cftry; Debugging and Troubleshooting Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

abort

Optional

No
  • Yes: calls a cfabort tag when the tag is executed.
  • No

category

Optional

User-defined string for identifying trace groups.

inline

Optional

No
  • Yes: displays trace code in line on the page in the location of the cftrace tag, in addition to the debugging information output.
  • No

text

Optional

User-defined string, which can include simple variables, but not complex variables such as arrays. Outputs to the cflog text attribute.

type

Optional

Information

Corresponds to the cflog type attribute; displays an appropriate icon:

  • Information
  • Warning
  • Error
  • Fatal Information

var

Optional

The name of a simple or complex variable to display.

Useful for displaying a temporary value, or a value that does not display on any CFM page.

Usage

You cannot put application code within this tag. (This avoids problems that can occur if you disable debugging.)

This tag is useful for debugging CFML code during application development.

You can display cftrace tag output in the following ways:

  • As a section in the debugging output
  • In-line in an application page, and as a section in debugging output. If you specify in-line tracing, ColdFusion flushes all output up to the cftrace tag, and displays the trace output when it encounters the tag.

This is an example of a log file entry:

"Information","web-4","04/08/02","23:21:30",   ,"[30 ms (1st trace)]
[C:\CFusionMX7\wwwroot\generic.cfm @ line: 9] -
    [thisPage = /generic.cfm]  "
"Information","web-0","04/08/02","23:58:58",   ,"[5187 ms (10)]
[C:\CFusionMX7\wwwroot\generic.cfm @ line: 14] - [category]
    [thisPage = /generic.cfm] [ABORTED] thisPage "

For a complex variable, ColdFusion lists the variable name and the number of elements in the object; it does not log the contents of the variable.

Example

The following example traces a FORM variable that is evaluated by a cfif block:

<cftrace var="FORM.variable"
    text="doing equivalency check for FORM.variable"
    category="form_vars"
    inline="true">
<cfif isDefined("FORM.variable") AND #FORM.variable# EQ 1>
    <h1>Congratulations, you're a winner!</h1>
<cfelse>
    <h1>Sorry, you lost!</h1>
</cfif>


cftransaction

Description

For enterprise database management systems that support transaction processing, instructs the database management system to treat multiple database operations as a single transaction. Provides database commit and rollback processing. See the documentation for your database management system to determine whether it supports SQL transaction processing.

Category

Database manipulation tags

Syntax

<cftransaction
    action = "begin" or "commit" or "rollback"
    isolation = "read_uncommitted" or "read_committed" or
        "repeatable_read" >
</cftransaction>

See also

cfinsert, cfprocparam, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cfupdate; Commits, rollbacks, and transactions in Introduction to Databases and SQL in ColdFusion MX Developer’s Guide

Attributes

Attribute

Req/Opt

Default

Description

action

Optional

begin
  • begin: the start of the block of code to execute.
  • commit: commits a pending transaction.
  • rollback: rolls back a pending transaction.

isolation

Optional

ODBC lock type:

  • read_uncommitted: reads without regard for other transactions that are taking place. Sometimes called a ‘dirty read’ because data that is read can be in a transitional state and therefore not accurate.
  • read_committed: uses shared locks to assure that no other transaction modifies rows that this transaction uses.
  • repeatable_read: same as read_committed, except that rows in the recordset are exclusively locked until the transaction completes. Due to high overhead, Macromedia does not recommend this isolation level for normal database access.
  • serializable: places an exclusive lock on every data table in use for the duration of the transaction. Causes access to the database to be single-threaded and is therefore not recommended for normal database access.

Usage

If you do not specify a value for the action attribute, automatic transaction processing proceeds as follows:

  • If the cfquery operations within the transaction block complete without an error, the transaction is committed.
  • If a cfquery tag generates an error within a cftransaction block, all cfquery operations in the transaction roll back.

If you do not specify a value for the isolation attribute, ColdFusion uses the default isolation level for the associated database.

Using CFML error handling and the action attribute, however, you can also explicitly control whether a transaction is committed or rolled back, based on the success or failure of the database query. Within a transaction block, you can do the following:

  • Commit a database transaction by nesting the <cftransaction action = "commit"/> tag within the block
  • Roll back a transaction by nesting the <cftransaction action = "rollback"/> tag within the block

(In these examples, the slash is alternate syntax that is the equivalent of an end tag.)

Within a transaction block, you can write queries to more than one database, but you must commit or roll back a transaction to one database before writing a query to another.

To control how the database engine performs locking during the transaction, use the isolation attribute.

Example

<p>CFTRANSACTION can be used to group multiple queries that use CFQUERY
into one business event. Changes to data that is requested by the queries
are not committed to the datasource until all actions within the transaction
block have executed successfully.
<p>This a view-only example.
<!---
<cftransaction>
    <cfquery name='makeNewCourse' datasource='Snippets'>
    INSERT INTO Courses
        (Number, Descript)
    VALUES
        ('#myNumber#', '#myDescription#')
    </cfquery>

    <cfquery name='insertNewCourseToList' datasource='Snippets'>
    INSERT INTO CourseList
        (CorNumber, CorDesc, Dept_ID,
        CorName, CorLevel, LastUpdate)
    VALUES
        ('#myNumber#', '#myDescription#', '#myDepartment#',
        '#myDescription#', '#myCorLevel#', #Now()#)
    </cfquery>
</cftransaction>
--->


cftree

Description

Inserts a tree control in a form. Validates user selections. Used within a cfform tag block. You can use a ColdFusion query to supply data to the tree.

Category

Forms tags

Syntax

<cftree name = "name"
format="applet", "flash", xml, or "object"
    required = "yes" or "no"
    delimiter = "delimiter"
    completePath = "yes" or "no"
    appendKey = "yes" or "no"
    highlightHref = "yes" or "no"
    onValidate = "script_name"
    message = "text"
    onError = "text"
    lookAndFeel = "motif" or "windows" or "metal"
    font = "font"
    fontSize = "size"
    italic = "yes" or "no"
    bold = "yes" or "no"
    height = "integer"
    width = "integer"
    vSpace = "integer"
    hSpace = "integer"
    align = "alignment"
    border = "yes" or "no"
    hScroll = "yes" or "no"
    vScroll = "yes" or "no"
    style= "style specification"
    enabled = "Yes" or "No"
    visible = "Yes" or "No"
    tooltip = "tip text"
onChange = "ActionScript"
    notSupported = "text">

</cftree>

See also

cfapplet, cfcalendar, cfform, cfformgroup, cfformitem, cfgrid, cfinput, cfselect, cfslider, cftextarea, cftreeitem; Working with action pages in Introduction to Retrieving and Formatting Data and Building tree controls with the cftree tag in Building Dynamic Forms with cfform Tags in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added the format attribute and support for generating Flash and XML and object output.
  • Added enabled, onChange, style, tooltip, and visible attributes (Flash format only).

ColdFusion MX: Changed behavior: ColdFusion renders a tree control regardless of whether there are any treeitems within it.

Attributes

Note: In XML format, ColdFusion MX passes all attributes to the XML. The supplied XSLT skins do not handle or display XML format trees, but do display applet and Flash format trees.

Attribute

Req/Opt

Format

Default

Description

name

Required;

All

Name for tree control.

format

Optional;

All

applet
  • applet: displays the tree using a Java applet in the browser.
  • flash: displays the tree using a Flash control
  • object: returns the tree as a ColdFusion structure with the name specified by the name attribute, For details of the structure contents, see object format.
  • xml: generates an XML representation of the tree.
    In XML format forms, includes the generated XML in the form.
    In HTML format forms, puts the XML in a string variable with the name specified by the name attribute.

required

Optional;

Applet, Flash

No
  • Yes: user must select an item in the tree control.
  • No

delimiter

Optional;

All

\\

Character to separate elements in the Forms.treename.path variable of the action page.

completePath

Optional;

Applet, object

No
  • Yes: starts the Form.treename.path variable with the root of the tree path when cftree is submitted.
  • No: omits the root level from the Form.treename.path variable; the value starts with the first child node in the tree.

For the preserveData attribute of cfform to work with the tree, you must set this attribute to Yes.

For tree items populated by a query, if you use the cftreeitem queryasroot attribute to specify a root name, that value is returned. If you do not specify a root name, ColdFusion returns the query name.

appendKey

Optional;

All

Yes
  • Yes: if you use cftreeitem href attributes, ColdFusion appends a CFTREEITEMKEY query string variable with the value of the selected tree item to the cfform action URL.
  • No: does not append the tree item value to the URL.

highlightHref

Optional;

Applet, Object

Yes
  • Yes: highlights as a link the displayed value for any cftreeitem tag that specifies an href attribute.
  • No: disables highlighting.

onValidate

Optional;

Applet

JavaScript function to validate user input. The JavaScript DOM form object, input object, and input object value are passed to the specified routine, which should return True if validation succeeds; False, otherwise.

message

Optional;

Applet

Message to display if validation fails.

onError

Optional;

Applet

JavaScript function to execute if validation fails.

lookAndFeel

Optional;

Applet, object

windows
  • motif: renders the slider in Motif style.
  • windows: renders the slider in Windows style.
  • metal: renders the slider in Java Swing style.

If the platform does not support a style option, the tag defaults to platform default style.

font

Optional;

Applet

Font name for text in the tree control.

fontSize

Optional;

Applet, Flash

Font size for text in the tree control, in points.

italic

Optional;

Applet, Flash

No
  • Yes: displays tree control text in italics.
  • No

bold

Optional;

Applet, Flash

No
  • Yes: displays tree control text in bold.
  • No

height

Optional;

Applet, Flash

320 (applet only)

Tree control height, in pixels. If you omit this attribute in Flash format, Flash automatically sizes the tree.

width

Optional;

Applet, Flash

200 (applet only)

Tree control width, in pixels. If you omit this attribute in Flash format, Flash automatically sizes the tree.

vSpace

Optional;

Applet

Vertical margin above and below tree control, in pixels.

hSpace

Optional;

Applet

Horizontal spacing to left and right of tree control, in pixels.

align

Optional;

Applet, object

  • top
  • left
  • bottom
  • baseline
  • texttop
  • absbottom
  • middle
  • absmiddle
  • right

border

Optional;

Applet, object

Yes
  • Yes: displays a border around the tree control.
  • No

hScroll

Optional;

Applet, object

Yes
  • Yes: permits horizontal scrolling.
  • No

vScroll

Optional;

Applet, object

Yes
  • Yes: permits vertical scrolling.
  • No

style

Optional;

Flash

Must be a style specification in CSS format, with the same syntax and contents as used in Macromedia Flex for the corresponding Flash element.

enabled

Optional;

Flash

Yes

Flash format only: Boolean value specifying whether the control is enabled. A disabled control appears in light gray.

visible

Optional;

Flash

Yes

Flash format only: Boolean value specifying whether to show the control. Space that would be occupied by an invisible control is blank.

tooltip

Optional;

Flash

Flash format only: Text to display when the mouse pointer hovers over the control.

onChange

Optional;

Flash

ActionScript to run when the control changes due to user action.

If you specify an onChange event handler, the Form scope of the ColdFusion action page does not automatically get information about selected items. The ActionScript onChange event handler must handle all changes and selections.

notSupported

Optional;

Applet

Text to display if a page that contains a Java applet-based cfform control is opened by a browser that does not support Java or has Java support disabled. For example:

"<b> Browser must support Java to view ColdFusion Java Applets</b>"

Default message:

<b>Browser must support Java to <br>view ColdFusion Java Applets!</b>

Note: All attributes are passed to the XML generated in XML format, but no ColdFusion MX skin interprets cftree XML.

Usage

This tag must be in a cfform tag block.

The applet format tree requires the client to download a Java applet. Also, if the client does not have an up-to-date Java plugin installed, the system might also have to download an updated Java plugin to display an applet format tree. The Flash format tree uses a Flash control, and can be embedded in an HTML format cfform tag. For this tag to work properly in either Flash or applet format, the browser must also be JavaScript-enabled.

Note: If you specify Flash format for this tag in an HTML format form, and you do not specify height and width attributes, Flash takes up more than the remaining visible area on the screen. If any other output follows the tree, including any form controls, users must scroll to see it. Therefore, if you follow a Flash tree in an HTML form with additional output, specify height and width values.

If the following conditions are true, a user’s selection from query data that populates this tag’s options continues to display after the user submits the form:

  • The cfform preserveData attribute is set to "Yes"
  • The cfform action attribute posts to the same page as the form itself (this is the default), or the action page has a form that contains controls with the same names as corresponding controls on the user entry form

For more information, see the cfform tag entry.

Form variables

When you select a tree item and submit the form that contains the tree, ColdFusion creates a structure with two variables in the action page Form scope. The structure name is the tree name. The fields are as follows:

Field | Value
path | The path through the tree to the selected node, in the form [root\]node_1\node_2\.... In applet format, the path includes the root node only if the completePath attribute is True. In Flash format, the path always includes the root node.
node | The value of the selected tree node.

object format

If you specify object in the format attribute, ColdFusion returns the tree as a ColdFusion structure, and does not send the tree to the browser. You can, for example, loop over the structure to populate a menu, generate "breadcrumb" links for page navigation, or create a dhtml tree.

Note: If you specify an object format tree in an XML format form, ColdFusion does not generate the tree.

The structure variable name is specified by the cftree name attribute. The top level of the structure has two types of entries:

  • Attribute settings
  • A children array

Attribute settings

The structure has top-level entries with the values of the following cftree attributes:

align | completePath | highlightHref | lookAndFeel
appendKey | delimiter | hScroll | name
bold | fontWeight | italic | vscroll
border |  |  |

Children array

The top-level children entry is an array of items entries. Each item has the following entries:

Field | Value
children | This item’s child items; an array of item structures.
display | Tree item label, as determined by the cftreeitem display attribute.
expand | Whether to expand the item to display any children; value of cftreeitem expand attribute.
href | The URL to link to when the user selects the item; value of the cftreeitem href attribute.
img | The tree image icon Image to display as an icon for the tree item; value of cftreeitem img attribute.
imgOpen | Image to display when the tree item is open (expanded); value of cftreeitem imgopen attribute.
parent | Value of this item’s parent item in the tree.
path | The node path from the tree root to the current element.
queryAsRoot | Whether the query is the root of the item; value of cftreeitem queryAsRoot attribute.
target | The link target, such as _blank; value of the item’s cftreeitem target attribute.
value | The item’s value, as determined by the cftreeitem value attribute.

Example

The following example creates a tree that shows available courses from the CourseList table of the cfdocexamples database, and puts each department’s courses in a folder. This example is displayed in Flash and uses the Departments list to get department names.

<cfquery name="getCourses" datasource="cfdocexamples">
    select d.dept_name, c.course_id, c.CorName, c.CorLevel, c.corName +' ( ' +c.corLevel +' )' as corLabel
    from CourseList c, Departments d
    where d.Dept_ID = c.Dept_ID
    order by d.dept_Name, c.corName, c.corLevel
</cfquery>

<cfform name="studentForm" format="flash" width="400" height="450">
    <cftree name="courseTree"  width="350" height="400">
        <cftreeitem
            query="getCourses"
            value="dept_name,Course_id"
            display="dept_name,CorLabel" queryasroot="NO" expand="yes,no">
    </cftree>
</cfform>

The following example creates a tree that shows the basic information about all employees in an organization, organized by department. The departments are expanded to show all employees. You can click the + signs to display additional information. If you click the employee name, ColdFusion links back to the same page and displays the Path and node values for the selection.

<!--- Query the datasource to get employee information. --->
<!--- Group the output by Department.
    (All fields are required in Group By clause.) --->
<cfquery name = "GetEmployees" dataSource = "cfdocexamples">
    SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
    FROM Employees
    GROUP BY Department, Emp_ID, FirstName, LastName, EMail, Phone
</cfquery>
<html>
<body>
<h3>cftree Example</h3>

<!--- The following runs if the user clicked on a link in the tree.
    A complete application would use the ID for additional processing. --->

<cfif isdefined("Form.fieldnames")>
<b>Selected item information</b><br>
<cfoutput>
<b>Path: </b>#form.Employees.Path#<br>
<b>node: </b>#form.Employees.node#<br>
<br>
</cfoutput>
</cfif>

<!--- Display the tree. The cftree tag must be in a cfform. --->
<cfform action="#cgi.script_name#" preservedata="Yes" format="Flash">
    <cftree name = "Employees" height = "400" width = "400"
        font = "Arial Narrow" italic="yes" highlighthref="No" HScroll="no" VScroll="no"
        completepath="no" lookandfeel="windows" border="No" required="yes">
        <!--- cfoutput tag with a group attribute loops over the departments. --->
        <cfoutput group="Department" query = "GetEmployees">
            <cftreeitem value="#Department#" parent="Employees" expand="yes">
            <!--- This cfoutput tag loops over the records for the department.
                    The cfoutput tag does not need any attributes. --->
            <cfoutput>
                <!--- Create an item for each employee in the department.
                    Do not expand children. Each employee name links to this page,
                    and sends the employee ID in the query string.--->
                <cftreeitem value = "#LastName#, #FirstName#"
                    parent = "#Department#" expand="false" img="cd"
                    href="#cgi.script_name#?user_id=#emp_id#">
                <!--- Each Employee entry has Id, and contact info children. --->
                <cftreeitem value = "#Emp_ID#" display = "Employee ID: #Emp_ID#"
                    parent = "#LastName#, #FirstName#" img="remote">
                <!--- Each node must be unique value, so use Emp_ID om value. --->
                <cftreeitem value = "#Emp_ID#_ContactInfo" img="computer"
                    display = "Contact Information"
                    parent = "#LastName#, #FirstName#" expand = "false">
                <!--- ContacInfo has two children --->
                <cftreeitem value = "#Phone#" parent = "#Emp_ID#_ContactInfo">
                <cftreeitem value = "#Email#" parent = "#Emp_ID#_ContactInfo">
            </cfoutput>
        </cfoutput>
    </cftree>
    <cfinput type="Submit" name="submitit" value="Submit" width="100">
</cfform>


cftreeitem

Description

Populates a form tree control, created with the cftree tag, with one or more elements.

Category

Forms tags

Syntax

<cftreeitem
    value = "text"
    display = "text"
    parent = "parent_name"
    img = "filename"
    imgopen = "filename"
    href = "URL"
    target = "URL_target"
    query = "queryname"
    queryAsRoot = "yes" or "no"
    expand = "yes" or "no">

See also

cfapplet, cfform, cfformgroup, cfformitem, cfgrid, cfinput, cfselect, cfslider, cftextarea, cftree; Building tree controls with the cftree tag in Building Dynamic Forms with cfform Tags in ColdFusion MX Developer’s Guide

Attributes

Note: In XML format, ColdFusion MX passes all attributes to the XML. The supplied XSLT skins do not handle or display XML format trees, but do display applet and Flash format trees.

Attribute

Req/Opt;

Format

Default

Description

value

Required;

All

Value passed when cfform is submitted. When populating a tree with data from a cfquery, you can specify multiple columns to use in a delimited list; for example, value = "dept_id,emp_id". In this case, each column generates an item that is a child of the column that precedes it in the list.

display

Optional;

All

value

Tree item label. When populating a tree with data from a query, specify names in a delimited list. Example: display = "dept_name,emp_name"

parent

Optional;

All

Value of the tree item parent. Determines the item’s placement in the tree hierarchy. If omitted, the item is placed at the tree root level, or if the queryAsRoot attribute is True, directly under the query.

img

Optional;

Applet, object

folder

Image name, filename, or file URL for tree item icon.

The following values are provided:

  • cd
  • computer
  • document
  • element
  • folder
  • floppy
  • fixed
  • remote

You can also specify a custom image. To do so, include path and file extension; for example:

img = "../images/page1.gif"

Custom images are not supported for Flash format.

To specify more than one image in a tree, or an image at the second or subsequent level, use commas to separate names, corresponding to level; for example:

img = "folder,document"

img = ",document" (example of second level)

imgopen

Optional;

Applet, object

Icon displayed with open tree item, as describe for the img attribute.

href

Optional;

All

URL to link to if the user clicks the tree item. If you use a query attribute, the href attribute can specify a query column that contains URLs. If href is not a query column, the attribute text must be a URL or list of URLs.

When populating a tree with data from a query, specify the URLs in a comma-delimited list; for example:

href = "http://dept_svr,http://emp_svr"

target

Optional;

All

Target attribute of href URL. When populating a tree with data from a query, specify target in delimited list:

target = "FRAME_BODY,_blank"

query

Optional;

Applet,

Flash

Query name to use to populate the treeitem. ColdFusion generates an item for each field value in the query column list specified by the value attribute. The fields in each row are hierarchically linked to the first column.

queryAsRoot

Optional;

All

Yes

Applies only if you specify a query attribute. Defines the query as the root level for all items generated by this tag. This attribute enables you to avoid creating a parent cftreeitem.

  • Yes: generates a parent (root) item for all other items generated by the tag, with the query name as its value; if you specify a parent attribute, the root item is a child of the specified parent.
  • No: uses the item specified by the parent attribute as the immediate parent of all items generated by this tag. If there is no parent attribute, use the query as the parent.
  • A string: creates a root item and uses the specified string as the item name; if you specify a parent attribute, the root item is a child of the specified parent.

expand

Optional;

All

Yes
  • Yes: expands tree to show tree item children.
  • No: keeps tree item collapsed.

Usage

This tag requires the client to download a Java applet. Downloading an applet takes time; therefore, using this tag might be slightly slower than using an HTML form element or the cfinput tag to get the same information.

For this tag to work properly. the browser must be JavaScript-enabled.

If you do not use a query to populate this tag, it creates a single tree item. If you do use a query, it creates multiple items; each row of the query creates a hierarchically nested set of items with one item per column.

Example

The following example creates a simple tree using a single cftreeitem tag and a query:

<cfform action = "#cgi.script_name#">
    <cftree name = "Employees" height = "400" width = "200">
        <cftreeitem value="LastName, FirstName, Emp_ID" query="getEmployees"
         queryAsRoot="False">
    </cftree>
</cfform>

The following example creates a tree that shows the basic information about all employees in an organization, organized by department. The departments are expanded to show all employees. You can click the + signs to display additional information. If you click the employee name, ColdFusion links back to the same page and displays the selected employee’s ID.

<!--- Query the datasource to get employee information.--->
<!--- Group the output by Department.
    (All fields are required in Group By clause.) --->
<cfquery name = "GetEmployees" dataSource = "cfdocexamples">
    SELECT Emp_ID, FirstName, LastName, EMail, Phone, Department
    FROM Employees
    GROUP BY Department, Emp_ID, FirstName, LastName, EMail, Phone
</cfquery>
<html>
<body>
<h3>cftreeitem Example</h3>

<!--- The following runs if the user clicked on a link in the tree.
    A complete application would use the ID for additional processing. --->
<cfif isdefined("URL.user_ID")>
    <cfoutput>
        <!--- URL.cftreeitemkey is the selected tree item's value attribute. --->
        You Requested information on #URL.cftreeitemKey#; User ID #URL.user_ID#
    </cfoutput>
    <br><br>
</cfif>
<!--- Display the tree. The cftree tag must be in a cfform. --->
<cfform>
    <cftree name = "Employees" height = "400" width = "200"
        font = "Arial Narrow" highlighthref="No" hscroll="No">
        <!--- cfoutput tag with a group attribute loops over the departments. --->
        <cfoutput group="Department" query = "GetEmployees">
            <cftreeitem value="#Department#" parent="Employees" expand="yes">
            <!--- This cfoutput tag loops over the records for the department.
                    The cfoutput tag does not need any attributes. --->
            <cfoutput>
                <!--- Create an item for each employee in the department.
                    Do not expand children. Each employee name links to this page,
                    and sends the employee ID in the query string.--->
                <cftreeitem value = "#LastName#, #FirstName#"
                    display = "#LastName#, #FirstName#"
                    parent = "#Department#" expand="no"
                    href="#cgi.script_name#?user_id=#emp_id#">
                <!--- Each Employee entry has ID and ContactInfo children. --->
                <cftreeitem value = "#Emp_ID#" display = "Employee ID: #Emp_ID#"
                    parent = "#LastName#, #FirstName#">
                <!--- Each node must be unique value, so use Emp_ID om value. --->
                <cftreeitem value = "#Emp_ID#_ContactInfo"
                    display = "Contact Information"
                    parent = "#LastName#, #FirstName#" expand = "No">
                <!--- ContactInfo has two children. --->
                <cftreeitem value = "#Phone#" parent = "#Emp_ID#_ContactInfo">
                <cftreeitem value = "#Email#" parent = "#Emp_ID#_ContactInfo">
            </cfoutput>
        </cfoutput>
    </cftree>
</cfform>


cftry

Description

Used with one or more cfcatch tags. Together, they catch and process exceptions in ColdFusion pages. Exceptions are events that disrupt the normal flow of instructions in a ColdFusion page, such as failed database operations, missing include files, and developer-specified events.

Category

Exception handling tags

Syntax

<cftry>
    Code that might throw an exception
    One or more cfcatch blocks
</cftry>

See also

cfcatch, cferror, cfrethrow, cfthrow, onError; Handling Errors in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed cfscript to include try and catch statements that are equivalent to the cftry and cfcatch tags.

Usage

Within a cftry block, put the code that might throw an exception, followed by one ore more cfcatch tags that catch and process exceptions. This tag requires an end tag.

Example

<!--- cftry example, using TagContext to display the tag stack. --->
<h3>cftry Example</h3>
<!--- Open a cftry block. --->
<cftry>
    <!--- Note misspelled tablename "employees" as "employeeas". --->
    <cfquery name = "TestQuery" dataSource = "cfdocexamples">
        SELECT *
        FROM EMPLOYEEAS
    </cfquery>

    <!--- <p>... other processing goes here --->
    <!--- specify the type of error for which we search --->
    <cfcatch type = "Database">
    <!--- the message to display --->
        <h3>You've Thrown a Database <b>Error</b></h3>
        <cfoutput>
            <!--- and the diagnostic message from the ColdFusion server --->
            <p>#cfcatch.message#</p>
            <p>Caught an exception, type = #CFCATCH.TYPE# </p>
            <p>The contents of the tag stack are:</p>
            <cfloop index = i from = 1
                    to = #ArrayLen(CFCATCH.TAGCONTEXT)#>
                <cfset sCurrent = #CFCATCH.TAGCONTEXT[i]#>
                <br>#i# #sCurrent["ID"]#
                    (#sCurrent["LINE"]#,#sCurrent["COLUMN"]#)
                    #sCurrent["TEMPLATE"]#
            </cfloop>
        </cfoutput>
    </cfcatch>
</cftry>


cfupdate

Description

Updates records in a data source from data in a ColdFusion form or form Scope.

Category

Database manipulation tags

Syntax

<cfupdate
    dataSource = "ds_name"
    tableName = "table_name"
    tableOwner = "name"
    tableQualifier = "qualifier"
    username = "username"
    password = "password"
    formFields = "field_names">

See also

cfinsert, cfprocparam, cfprocresult, cfquery, cfqueryparam, cfstoredproc, cftransaction; Creating an update action page with cfupdate in Updating Your Database in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Deprecated the connectString, dbName, dbServer, dbtype, provider, and providerDSN attributes. They do not work, and might cause an error, in releases later than ColdFusion 5.

Attributes

Attribute

Req/Opt

Default

Description

dataSource

Required

Name of the data source that contains the table.

tableName

Required

Name of table to update.

  • For ORACLE drivers, must be uppercase.
  • For Sybase driver, case-sensitive; must be in same case as used when the table was created.

tableOwner

Optional

For data sources that support table ownership (for example, SQL Server, Oracle, Sybase SQL Anywhere), the table owner.

tableQualifier

Optional

For data sources that support table qualifiers. The purpose of table qualifiers is as follows:

  • SQL Server and Oracle: name of the database that contains the table
  • Intersolv dBASE driver: directory of DBF files

username

Optional

Overrides username value specified in ODBC setup.

password

Optional

Overrides the password value specified in ODBC setup.

formFields

Optional

(all on form, except keys)

Comma-delimited list of form fields to update.

If a form field is not matched by a column name in the database, ColdFusion throws an error.

The formFields lies must include the database table primary key field, which must be present in the form. It can be hidden.

Example

<!--- This example allows you to update a person's telephone number in the employee table. --->
<cfif isDefined("form.phone")>
    <cfupdate datasource="cfdocexamples" tablename="Employees">
</cfif>

<cfquery name="empTable" datasource="cfdocexamples">
    select * from employees
</cfquery>

<!--- This code shows the contents of the employee table and allows you to choose a row for updating. --->
<table border="1">
<cfoutput query="empTable">
    <tr>
        <td>#firstName#</td>
        <td>#lastName#</td>
        <td>#phone#</td>
        <td><a href="cfupdate.cfm?id=#emp_id#">Edit</a></td>
    </tr>
</cfoutput>
</table>

<cfif isDefined("url.id")>
    <cfquery name="phoneQuery" datasource="cfdocexamples">
        select * from employees where emp_id=#url.id#
    </cfquery>
<!--- This code displays the row to edit for update. --->
    <cfoutput query="phoneQuery">
        <form action="cfupdate.cfm" method="post">
        #phoneQuery.firstName# #phoneQuery.lastName#
        <input name="phone" type="text" value="#phone#" size="12">
        <input type="submit" value="Update">
        <input name="emp_id" type="hidden" value="#emp_id#">
        <!--- The emp_id is passed as a hidden field to be used as a primary key in 	the CFUPDATE. --->
        </form>
    </cfoutput>
</cfif>


cfwddx

Description

Serializes and deserializes CFML data structures to the XML-based WDDX format. The WDDX is an XML vocabulary for describing complex data structures in a standard, generic way. Implementing it lets you use the HTTP protocol to such information among application server platforms, application servers, and browsers.

This tag generates JavaScript statements to instantiate JavaScript objects equivalent to the contents of a WDDX packet or CFML data structure. Interoperates with Unicode.

Category

Extensibility tags

Syntax

<cfwddx
    action = "action"
    input = "inputdata"
    output = "result variable name"
    topLevelVariable = "top-level variable name for JavaScript"
    useTimeZoneInfo = "yes" or "no"
    validate = "yes" or "no" >

See also

cfcollection, cfdump, cfexecute, cfindex, cfobject, cfreport, cfsearch, ToScript; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX

  • Changed column name case behavior: ColdFusion preserves the case of column names in JavaScript. (Earlier releases converted query column names to lowercase.)
  • Changed encoding format support: this tag supports several encoding formats. The default encoding format is UTF-8. The tag interoperates with Unicode.

Attributes

Attribute

Req/Opt

Default

Description

action

Required

  • cfml2wddx: serializes CFML to WDDX.
  • wddx2cfml: deserializes WDDX to CFML.
  • cfml2js: serializes CFML to JavaScript.
  • wddx2js: deserializes WDDX to JavaScript.

input

Required

A value to process.

output

Required if action = "wddx2cfml"

Name of variable for output. If action = "WDDX2JS" or "CFML2JS", and this attribute is omitted, result is output in HTML stream.

topLevelVariable

Required if action = "wddx2js" or "cfml2js"

Name of top-level JavaScript object created by deserialization. The object is an instance of the WddxRecordset object.

useTimeZoneInfo

Optional

Yes

Whether to output time-zone information when serializing CFML to WDDX.

  • Yes: the hour-minute offset, represented in ISO8601 format, is output.
  • No: the local time is output.

validate

Optional

No

Applies if action = "wddx2cfml" or "wddx2js".

  • yes: validates WDDX input with an XML parser using WDDX DTD. If parser processes input without error, packet is deserialized. Otherwise, an error is thrown.
  • no: does not perform input validation.

Usage

ColdFusion preserves the case of column names cases in JavaScript.

The wddx2js and cfml2js actions create a WddxRecordset javascript object when they encounter a RecordSet java object. The serialized JavaScript code requires a wddx.js file.

This tag performs the following conversions:

From | To
CFML | WDDX
CFML | JavaScript
WDDX | CFML
WDDX | JavaScript

For more information, and a list of the ColdFusion array and structure functions that you can use to manage XML document objects and functions, see Using XML and WDDX in ColdFusion MX Developer’s Guide.

Note: The cfwddx tag throws an exception if you attempt to serialize a CFC or user-defined function (UDF).

Example

<!--- This example shows basic use of the cfwddx tag. --->
<html>
<body>
<!--- Create a simple query. --->
<cfquery name = "q" dataSource = "cfdocexamples">
    select Message_Id, Thread_id, Username from messages
</cfquery>

The recordset data is:...<p>
<cfoutput query = q>
    #Message_ID# #Thread_ID# #Username#<br>
</cfoutput><p>

<!--- Serialize data to WDDX format. --->
Serializing CFML data...<p>
<cfwddx action = "cfml2wddx" input = #q# output = "wddxText">

<!--- Display WDDX XML packet. --->
Resulting WDDX packet is:
<xmp><cfoutput>#wddxText#</cfoutput></xmp>

<!--- Deserialize to a variable named wddxResult. --->
Deserializing WDDX packet...<p>
<cfwddx action = "wddx2cfml" input = #wddxText# output = "qnew">

The recordset data is:...<p>
<cfoutput query = qnew>
    #Message_ID# #Thread_ID# #Username#<br>
</cfoutput><p>


cfxml

Description

Creates a ColdFusion XML document object that contains the markup in the tag body. This tag can include XML and CFML tags. ColdFusion processes the CFML code in the tag body, and then assigns the resulting text to an XML document object variable, which is always stored in Unicode.

Category

Extensibility tags

Syntax

<CFXML
    variable="xmlVarName"
    caseSensitive="yes" or "no">

See also

IsXmlDoc, IsXmlElem, IsXmlRoot, ToString, XmlChildPos, XmlNew, XmlParse, XmlSearch, XmlTransform; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added support for using an XML declaration at the start of the text.

ColdFusion MX: Added this tag.

Attributes

Attribute

Req/Opt

Default

Description

variable

Name of the document object.

caseSensitive

Optional

no
  • yes: maintains the case of document elements and attributes.
  • no

Usage

If your XML object is case-sensitive, you cannot use dot notation to reference an element or attribute name. Use the name in associative array (bracket) notation, or a reference that does not use the case-sensitive name (such as xmlChildren[1]) instead. In the following code, the first line will work with a case-sensitive XML object. The second and third lines cause errors:

MyDoc.xmlRoot.XmlAttributes["Version"] = "12b";
MyDoc.xmlRoot.XmlAttributes.Version = "12b";
MyDoc.MyRoot.XmlAttributes["Version"] = "12b";

Use the XmlFormat function to escape special characters such as &, > and <.

To convert an XML document object back into a string, use the ToString function, at which time ColdFusion automatically prepends the <?xml version="1.0" encoding="UTF-8" ?> XML declaration.

To change the declaration to specify another encoding, use the Replace function. To specify the encoding of the text that is returned to a browser or other application, use the cfcontent tag.

The following example illustrates this process:

<cfprocessingdirective suppresswhitespace="Yes">
<cfcontent type="text/xml; charset=utf-16">
<cfxml variable="xmlobject">
<breakfast_menu>
    <food>
        <name quantity="50">Belgian Waffles</name>
        <description>Our famous Belgian Waffles</description>
    </food>
</breakfast_menu>
</cfxml>

<!--- <cfdump var="#xmlobject#">--->

<cfset myvar=toString(xmlobject)>
<cfset mynewvar=replace(myvar, "UTF-8", "utf-16")>

<!---<cfdump var="#mynewvar#">--->

<cfoutput>#mynewvar#</cfoutput>
</cfprocessingdirective>

The cfprocessingdirective tag prevents ColdFusion from putting white space characters in front of the XML declaration.

Example

This following example creates a document object whose root element is MyDoc. The object includes text that displays the value of the ColdFusion variable testVar. The code creates four nested child elements, which are generated by an indexed cfloop tag. The cfdump tag displays the XML document object.

<cfset testVar = True>
<cfxml variable="MyDoc">
    <?xml version='1.0' encoding='utf-8' ?>
    <MyDoc>
        <cfif testVar IS True>
            <cfoutput>The value of testVar is True.</cfoutput>
        <cfelse>
            <cfoutput>The value of testVar is False.</cfoutput>
        </cfif>
        <cfloop index = "LoopCount" from = "1" to = "4">
            <childNode>
                This is Child node <cfoutput>#LoopCount#.</cfoutput>
            </childNode>
        </cfloop>
    </MyDoc>
</cfxml>
<cfdump var=#MyDoc#>

Previous


ColdFusion Functions

This chapter lists and categorizes ColdFusion Markup Language (CFML) functions.

Contents

Function list

Functions by category

Function changes since ColdFusion 5

Tag descriptions

Function list

ColdFusion Markup Language (CFML) includes a set of functions that you use in Macromedia ColdFusion MX 7 pages to perform logical and arithmetic operations and manipulate data.

The following table lists CFML functions:

Abs

GetFunctionList

Max

ACos

GetGatewayHelper

Mid

AddSOAPRequestHeader

GetHttpRequestData

Min

AddSOAPResponseHeader

GetHttpTimeString

Minute

ArrayAppend

GetLocale

Month

ArrayAvg

GetLocaleDisplayName

MonthAsString

ArrayClear

GetMetaData

Now

ArrayDeleteAt

GetMetricData

NumberFormat

ArrayInsertAt

GetPageContext

ParagraphFormat

ArrayIsEmpty

GetProfileSections

ParseDateTime

ArrayLen

GetProfileString

Pi

ArrayMax

GetSOAPRequest

PreserveSingleQuotes

ArrayMin

GetSOAPRequestHeader

Quarter

ArrayNew

GetSOAPResponse

QueryAddColumn

ArrayPrepend

GetSOAPResponseHeader

QueryAddRow

ArrayResize

GetTempDirectory

QueryNew

ArraySet

GetTempFile

QuerySetCell

ArraySort

GetTickCount

QuotedValueList

ArraySum

GetTimeZoneInfo

Rand

ArraySwap

GetToken

Randomize

ArrayToList

Hash

RandRange

Asc

Hour

REFind

ASin

HTMLCodeFormat

REFindNoCase

Atn

HTMLEditFormat

ReleaseComObject

BinaryDecode

IIf

RemoveChars

BinaryEncode

IncrementValue

RepeatString

BitAnd

InputBaseN

Replace

BitMaskClear

Insert

ReplaceList

BitMaskRead

Int

ReplaceNoCase

BitMaskSet

IsArray

REReplace

BitNot

IsBinary

REReplaceNoCase

BitOr

IsBoolean

Reverse

BitSHLN

IsCustomFunction

Right

BitSHRN

IsDate

RJustify

BitXor

IsDebugMode

Round

Ceiling

IsDefined

RTrim

CharsetDecode

IsLeapYear

Second

CharsetEncode

IsNumeric

SendGatewayMessage

Chr

IsNumericDate

SetEncoding

CJustify

IsObject

SetLocale

Compare

IsQuery

SetProfileString

CompareNoCase

IsSimpleValue

SetVariable

Cos

IsSOAPRequest

Sgn

CreateDate

IsStruct

Sin

CreateDateTime

IsUserInRole

SpanExcluding

CreateObject

IsValid

SpanIncluding

CreateODBCDate

IsWDDX

Sqr

CreateODBCDateTime

IsXML

StripCR

CreateODBCTime

IsXmlAttribute

StructAppend

CreateTime

IsXmlDoc

StructClear

CreateTimeSpan

IsXmlElem

StructCopy

CreateUUID

IsXmlNode

StructCount

DateAdd

IsXmlRoot

StructDelete

DateCompare

JavaCast

StructFind

DateConvert

JSStringFormat

StructFindKey

DateDiff

LCase

StructFindValue

DateFormat

Left

StructGet

DatePart

Len

StructInsert

Day

ListAppend

StructIsEmpty

DayOfWeek

ListChangeDelims

StructKeyArray

DayOfWeekAsString

ListContains

StructKeyExists

DayOfYear

ListContainsNoCase

StructKeyList

DaysInMonth

ListDeleteAt

StructNew

DaysInYear

ListFind

StructSort

DE

ListFindNoCase

StructUpdate

DecimalFormat

ListFirst

Tan

DecrementValue

ListGetAt

TimeFormat

Decrypt

ListInsertAt

ToBase64

DeleteClientVariable

ListLast

ToBinary

DirectoryExists

ListLen

ToScript

DollarFormat

ListPrepend

ToString

Duplicate

ListQualify

Trim

Encrypt

ListRest

UCase

Evaluate

ListSetAt

URLDecode

Exp

ListSort

URLEncodedFormat

ExpandPath

ListToArray

URLSessionFormat

FileExists

ListValueCount

Val

Find

ListValueCountNoCase

ValueList

FindNoCase

LJustify

Week

FindOneOf

Log

Wrap

FirstDayOfMonth

Log10

WriteOutput

Fix

LSCurrencyFormat

XmlChildPos

FormatBaseN

LSDateFormat

XmlElemNew

GetTempDirectory

LSEuroCurrencyFormat

XmlFormat

GetAuthUser

LSIsCurrency

XmlGetNodeType

GetBaseTagData

LSIsDate

XmlNew

GetBaseTagList

LSIsNumeric

XmlParse

GetBaseTemplatePath

LSNumberFormat

XmlSearch

GetClientVariablesList

LSParseCurrency

XmlTransform

GetCurrentTemplatePath

LSParseDateTime

XmlValidate

GetDirectoryFromPath

LSParseEuroCurrency

Year

GetEncoding

LSParseNumber

YesNoFormat

GetException

LSTimeFormat

GetFileFromPath

LTrim
Next


Functions by category

The following tables list functions by their category or purpose.

Array functions

Conversion functions

Conversion functions

Date and time functions

Decision functions

Display and formatting functions

Dynamic evaluation functions

Extensibility functions

Full-text search functions

International functions

List functions

Mathematical functions

Other functions

Query functions

String functions

Structure functions

System functions

XML functions


Array functions

ArrayAppend

ArrayIsEmpty

ArrayPrepend

ArraySwap

ArrayAvg

ArrayLen

ArrayResize

ArrayToList

ArrayClear

ArrayMax

ArraySet

IsArray

ArrayDeleteAt

ArrayMin

ArraySort

ListToArray

ArrayInsertAt

ArrayNew

ArraySum


Conversion functions

ArrayToList

Hash

ToScript

XmlFormat

BinaryDecode

LCase

ToString

XmlParse

BinaryEncode

ListToArray

URLDecode

XmlTransform

CharsetDecode

ToBase64

URLEncodedFormat

CharsetEncode

ToBinary

Val


Date and time functions

CreateDate

DateFormat

GetTimeZoneInfo

MonthAsString

CreateDateTime

DatePart

Hour

Now

CreateODBCDate

Day

IsDate

ParseDateTime

CreateODBCDateTime

DayOfWeek

IsLeapYear

Quarter

CreateODBCTime

DayOfWeekAsString

IsNumericDate

Second

CreateTime

DayOfYear

LSDateFormat

TimeFormat

CreateTimeSpan

DaysInMonth

LSIsDate

Week

DateAdd

DaysInYear

LSParseDateTime

Year

DateCompare

FirstDayOfMonth

LSTimeFormat

DateConvert

GetHttpTimeString

Minute

DateDiff

GetTickCount

Month


Decision functions

DirectoryExists

IsDefined

IsSimpleValue

IsXmlNode

FileExists

IsK2ServerABroker

IsStruct

IsXmlRoot

IIf

IsK2ServerDocCountExceeded

IsUserInRole

LSIsCurrency

IsArray

IsK2ServerOnline

IsValid

LSIsDate

IsBinary

IsLeapYear

IsWDDX

LSIsNumeric

IsBoolean

IsNumeric

IsXML

StructIsEmpty

IsCustomFunction

IsNumericDate

IsXmlAttribute

StructKeyExists

IsDate

IsObject

IsXmlDoc

YesNoFormat

IsDebugMode

IsQuery

IsXmlElem


Display and formatting functions

CJustify

HTMLCodeFormat

LSIsDate

NumberFormat

DateFormat

HTMLEditFormat

LSNumberFormat

ParagraphFormat

DecimalFormat

LJustify

LSParseCurrency

RJustify

DollarFormat

LSCurrencyFormat

LSParseDateTime

StripCR

FormatBaseN

LSDateFormat

LSParseEuroCurrency

TimeFormat

GetLocale

LSEuroCurrencyFormat

LSParseNumber

YesNoFormat

GetLocaleDisplayName

LSIsCurrency

LSTimeFormat


Dynamic evaluation functions

DE

Evaluate

IIf

SetVariable


Extensibility functions

CreateObject

ReleaseComObject

ToScript

GetGatewayHelper

SendGatewayMessage


Full-text search functions

History

ColdFusion MX 6.1: These functions are deprecated. They might not work, and might cause errors, in a future release.

GetK2ServerDocCount

IsK2ServerABroker

IsK2ServerOnline

GetK2ServerDocCountLimit

IsK2ServerDocCountExceeded


International functions

DateConvert

GetTimeZoneInfo

LSIsDate

LSParseEuroCurrency

GetEncoding

LSIsCurrency

LSParseDateTime

LSParseNumber

GetHttpTimeString

LSCurrencyFormat

LSIsNumeric

LSTimeFormat

GetLocale

LSDateFormat

LSNumberFormat

SetEncoding

GetLocaleDisplayName

LSEuroCurrencyFormat

LSParseCurrency

SetLocale


List functions

ArraySort

FindNoCase

ListContainsNoCase

ListQualify

ArrayToList

FindOneOf

ListDeleteAt

ListRest

Asc

FormatBaseN

ListFind

ListSetAt

Chr

GetClientVariablesList

ListFindNoCase

ListSort

CJustify

LCase

ListFirst

ListToArray

Compare

Left

ListGetAt

ListValueCount

CompareNoCase

Len

ListInsertAt

ListValueCountNoCase

Decrypt

ListAppend

ListLast

ReplaceList

Encrypt

ListChangeDelims

ListLen

Find

ListContains

ListPrepend


Mathematical functions

Abs

BitNot

FormatBaseN

Randomize

ACos

BitOr

IncrementValue

RandRange

ArrayAvg

BitSHLN

InputBaseN

Round

ArraySum

BitSHRN

Int

Sgn

ASin

BitXor

Log

Sin

Atn

Ceiling

Log10

Sqr

BitAnd

Cos

Max

Tan

BitMaskClear

DecrementValue

Min

BitMaskRead

Exp

Pi

BitMaskSet

Fix

Rand


Other functions

CreateUUID

GetBaseTagList

PreserveSingleQuotes

DeleteClientVariable

GetBaseTemplatePath

URLSessionFormat

GetBaseTagData

GetClientVariablesList

WriteOutput


Query functions

IsQuery

QueryAddRow

QuerySetCell

ValueList

QueryAddColumn

QueryNew

QuotedValueList


Security functions

Decrypt

GetAuthUser

GetTempDirectory

IsUserInRole

Encrypt

GenerateSecretKey

Hash


String functions

History

ColdFusion MX: ColdFusion now supports the Java UCS-2 representation of Unicode character values 0–65535. (Earlier releases supported ASCII values.)

String-processing functions process any of these characters (including ASCII 0 (NUL) characters), and continue counting subsequent characters of the string, if any. (In earlier releases, some string-processing functions processed the ASCII 0 (NUL) character, but did not process subsequent characters of the string.)

Asc

GetToken

LSParseDateTime

Reverse

BinaryDecode

Hash

LSParseEuroCurrency

Right

BinaryEncode

HTMLCodeFormat

LSParseNumber

RJustify

CharsetDecode

HTMLEditFormat

LTrim

RTrim

CharsetEncode

Insert

Mid

SpanExcluding

Chr

JavaCast

MonthAsString

SpanIncluding

CJustify

JSStringFormat

ParagraphFormat

StripCR

Compare

LCase

ParseDateTime

ToBase64

CompareNoCase

Left

REFind

ToBinary

DayOfWeekAsString

Len

REFindNoCase

ToString

Decrypt

LJustify

RemoveChars

Trim

Encrypt

ListValueCount

RepeatString

UCase

Find

ListValueCountNoCase

Replace

URLDecode

FindNoCase

LSIsDate

ReplaceNoCase

URLEncodedFormat

FindOneOf

LSIsNumeric

REReplace

Val

FormatBaseN

LSParseCurrency

REReplaceNoCase

Wrap

GenerateSecretKey

LSIsCurrency

ReplaceList

XmlFormat

See also Conversion functions.


Structure functions

Duplicate

StructCount

StructGet

StructKeyList

IsStruct

StructDelete

StructInsert

StructNew

StructAppend

StructFind

StructIsEmpty

StructSort

StructClear

StructFindKey

StructKeyArray

StructUpdate

StructCopy

StructFindValue

StructKeyExists


System functions

DirectoryExists

GetFileFromPath

GetTempDirectory

Duplicate

GetFunctionList

GetTempFile

ExpandPath

GetHttpRequestData

GetTemplatePath

FileExists

GetLocale

GetTickCount

GetBaseTemplatePath

GetLocaleDisplayName

SetEncoding

GetContextRoot

GetMetaData

SetLocale

GetCurrentTemplatePath

GetMetricData

SetProfileString

GetDirectoryFromPath

GetPageContext

WriteOutput

GetEncoding

GetProfileSections

GetException

GetProfileString


XML functions

AddSOAPRequestHeader

IsSOAPRequest

IsXmlRoot

XmlGetNodeType

AddSOAPResponseHeader

IsXML

IsWDDX

XmlNew

GetSOAPRequest

IsXmlAttribute

ToString

XmlParse

GetSOAPRequestHeader

IsXmlDoc

XmlChildPos

XmlSearch

GetSOAPResponse

IsXmlElem

XmlElemNew

XmlTransform

GetSOAPResponseHeader

IsXmlNode

XmlFormat

XmlValidate


Function changes since ColdFusion 5

The following tables list functions, parameters and values that have changed since ColdFusion 5.0 and indicate the specific release in which the change was made.

New functions, parameters, and values

Deprecated functions, parameters, and values

Obsolete functions, parameters, and values


New functions, parameters, and values

Function

Parameter or value

Added in this ColdFusion release

BinaryDecode

All

ColdFusion MX 7

BinaryEncode

All

ColdFusion MX 7

CharsetDecode

All

ColdFusion MX 7

CharsetEncode

All

ColdFusion MX 7

CreateObject

portName parameter

ColdFusion MX 7

All

ColdFusion MX

DateAdd

l key of datepart parameter

ColdFusion MX 6.1

DatePart

l key of datepart parameter

ColdFusion MX 6.1

Decrypt

algorithm and encoding parameters

ColdFusion MX 7

Encrypt

algorithm and encoding parameters

ColdFusion MX 7

GenerateSecretKey

All

ColdFusion MX 7

GetGatewayHelper

All

ColdFusion MX 7

GetAuthUser

All

ColdFusion MX

GetContextRoot

All

ColdFusion MX 7

GetEncoding

All

ColdFusion MX

GetLocaleDisplayName

ColdFusion MX 7

GetMetaData

All

ColdFusion MX

GetPageContext

All

ColdFusion MX

GetProfileSections

All

ColdFusion MX

GetSOAPRequest

All

ColdFusion MX 7

GetSOAPRequestHeader

All

ColdFusion MX 7

GetSOAPResponse

All

ColdFusion MX 7

GetSOAPResponseHeader

All

ColdFusion MX 7

Hash

algorithm and encoding parameters

ColdFusion MX 7

IsObject

All

ColdFusion MX

IsSOAPRequest

All

ColdFusion MX 7

IsUserInRole

All

ColdFusion MX

IsValid

All

ColdFusion MX 7

IsXML

All

ColdFusion MX 7

IsXmlAttribute

All

ColdFusion MX 7

IsXmlDoc

All

ColdFusion MX

IsXmlElem

All

ColdFusion MX

IsXmlNode

All

ColdFusion MX 7

IsXmlRoot

All

ColdFusion MX

LSTimeFormat

l key of mask parameter

ColdFusion MX 6.1

QueryAddColumn

datatype parameter

ColdFusion MX 7

QueryNew

columntypelist parameter

ColdFusion MX 7

Rand

algorithm parameter

ColdFusion MX 7

Randomize

algorithm parameter

ColdFusion MX 7

RandRange

algorithm parameter

ColdFusion MX 7

ReleaseComObject

All

ColdFusion MX 6.1

SendGatewayMessage

All

ColdFusion MX 7

SetEncoding

All

ColdFusion MX

TimeFormat

l key of mask parameter

ColdFusion MX 6.1

ToScript

All

ColdFusion MX 7

URLDecode

charset parameter

ColdFusion MX

URLEncodedFormat

charset parameter

ColdFusion MX

URLSessionFormat

All

ColdFusion MX

Wrap

All

ColdFusion MX 6.1

XmlChildPos

All

ColdFusion MX

XmlElemNew

All

ColdFusion MX

XmlElemNew

namespace parameter

ColdFusion MX 7

XmlGetNodeType

All

ColdFusion MX 7

XmlNew

All

ColdFusion MX

XmlParse

All

ColdFusion MX

XmlParse

validator parameter

ColdFusion MX 7

XmlSearch

All

ColdFusion MX

XmlTransform

All

ColdFusion MX

XmlTransform

parameters parameter

ColdFusion MX 7

XmlValidate

All

ColdFusion MX 7


Deprecated functions, parameters, and values

The following functions, parameters, and values are deprecated. Do not use them in ColdFusion applications. They might not work, and might cause an error, in releases later than ColdFusion MX.

Function

Parameter or value

Deprecated as of this ColdFusion release

GetMetricData

cachepops parameter

ColdFusion MX

GetK2ServerDocCount

All

ColdFusion MX 6.1

GetK2ServerDocCount
Limit

All

ColdFusion MX 6.1

GetTemplatePath

All

ColdFusion MX

IsK2ServerABroker

All

ColdFusion MX 6.1

IsK2ServerDocCount
Exceeded

All

ColdFusion MX 6.1

IsK2ServerOnLine

All

ColdFusion MX 6.1

ParameterExists

All

ColdFusion MX. Use the IsDefined function.

SetLocale

locale = "Spanish (Mexican)" value

ColdFusion MX. Use Spanish (Standard).


Obsolete functions, parameters, and values

The following functions, parameters, and values are obsolete. Do not use them in ColdFusion applications. They do not work in releases later than ColdFusion 5.

Function | Parameter or value | Obsolete as of this ColdFusion release
AuthenticatedContext | All | ColdFusion MX
AuthenticatedUser | All | ColdFusion MX
isAuthenticated | All | ColdFusion MX
isAuthorized | All | ColdFusion MX
isProtected | All | ColdFusion MX
Previous


Abs

Description

Absolute-value function. The absolute value of a number is the number without its sign.

Returns

The absolute value of a number.

Category

Mathematical functions

Function syntax

Abs(number)

See also

Sgn

Parameters

Parameter | Description
number | A number

Example

<h3>Abs Example</h3>
<p>The absolute value of the following numbers:
1,3,-4,-3.2,6 is
<cfoutput>
#Abs(1)#,#Abs(3)#,#Abs(-4)#,#Abs(-3.2)#,#Abs(6)#
</cfoutput>

<p>The absolute value of a number is the number without its sign.
Next


ACos

Description

Arccosine function. The arccosine is the angle whose cosine is number.

Returns

The arccosine, in radians, of a number.

Category

Mathematical functions

Function syntax

ACos(number)

See also

Cos , Sin , ASin , Tan , Atn , Pi

Parameters

Parameter | Description
number | Cosine of an angle. The value must be between -1.0 and 1.0, inclusive.

Usage

The range of the result is 0 to p.

To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

Example

<h3>ACos Example</h3>
<!--- output its arccosine value --->
<cfif IsDefined("FORM.CosNum")>
    <cfif IsNumeric(FORM.CosNum)>
        <cfif Abs(FORM.CosNum) LESS THAN OR EQUAL TO 1>
            <cfoutput>ACos(#FORM.CosNum#) = #ACos(FORM.cosNum)# Radians	</cfoutput>
            <br>or<br>
            <cfoutput>ACos(#FORM.CosNum#) = #ACos(FORM.cosNum) * 180/PI()#</cfoutput>
        <cfelse>
            <!--- if it is empty, output an error message --->
            <h4>Enter a number between -1 and 1</h4>
        </cfif>
    </cfif>
</cfif>

<form method="post" action = "acos.cfm">
<p>Enter a number to get its arccosine in Radians and Degrees.
<br><input type = "Text" name = "cosNum" size = "25">
<p><input type = "Submit" name = ""> <input type = "RESET">
</form>


AddSOAPRequestHeader

Description

Adds a SOAP header to a web service request before making the request.

Returns

Nothing.

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

AddSOAPRequestHeader(webservice, namespace, name, value [, mustunderstand])

See also

AddSOAPResponseHeader, GetSOAPRequest, GetSOAPRequestHeader, GetSOAPResponse, GetSOAPResponseHeader, IsSOAPRequest; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
webservice | A web service object as returned from the cfobject tag or the CreateObject function.
namespace | A string that is the namespace for the header.
name | A string that contains the name of the SOAP header in the request.
value | The value for the SOAP header; this can be a CFML XML value.
mustunderstand | Optional. True or False (default). Sets the SOAP mustunderstand value for this header.

Usage

Used within CFML code by a consumer of a web service before it calls the web service.

If you pass XML in the value parameter, ColdFusion ignores the namespace and name parameters. If you require a namespace, define it within the XML itself.

Example

There are two parts to this example. The first part is the web service CFC that this function (as well as the other ColdFusion SOAP functions) uses to demonstrate its interaction with a web service. To implement the web service for this function, see the example for AddSOAPResponseHeader.

Execute the following example as a client to see how the AddSOAPRequestHeader function operates.

<!--- Note that you might need to modify the URL in the CreateObject function
to match your server and the location of the headerservice.cfc file if it is
different than shown here. Likewise for the cfinvoke tag at the end. --->

<h3>AddSOAPRequestHeader Example</h3>
<cfscript>
 // Create the web service object.
 ws = CreateObject("webservice", "http://localhost/soapheaders/headerservice.cfc?WSDL");

 // Set the username header as a string.
 addSOAPRequestHeader(ws, "http://mynamespace/", "username", "tom", false);

 // Set the password header as a CFML XML object.
 doc = XmlNew();
 doc.password = XmlElemNew(doc, "http://mynamespace/", "password");
 doc.password.XmlText = "My Voice is my Password";
 doc.password.XmlAttributes["xsi:type"] = "xsd:string";
 addSOAPRequestHeader(ws, "ignoredNameSpace", "ignoredName", doc);

 // Invoke the web service operation.
 ret = ws.echo_me("argument");

 // Get the first header as an object (string) and as XML.
 header = getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader");
 XMLheader = getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader", true);

 // Get the second header as an object (string) and as XML.
 header2 =  getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader2");
 XMLheader2 = getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader2", true);
</cfscript>
<hr>
<cfoutput>
Soap Header value: #HTMLCodeFormat(header)#<br>
Soap Header XML value: #HTMLCodeFormat(XMLheader)#<br>
Soap Header 2 value: #HTMLCodeFormat(header2)#<br>
Soap Header 2 XML value: #HTMLCodeFormat(XMLheader2)#<br>
Return value: #HTMLCodeFormat(ret)#<br>
</cfoutput>
<hr>

<cfinvoke component="soapheaders.headerservice" method="echo_me" returnvariable="ret" in_here="hi">
</cfinvoke>
<cfoutput>Cfinvoke returned: #ret#</cfoutput>


AddSOAPResponseHeader

Description

Adds a SOAP response header to a web service response. Call only from within a CFC web service function that is processing a request as a SOAP web service.

Returns

Nothing

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

AddSOAPResponseHeader(namespace, name, value [, mustunderstand])

See also

AddSOAPRequestHeader, GetSOAPRequest, GetSOAPRequestHeader, GetSOAPResponse, GetSOAPResponseHeader, IsSOAPRequest; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
namespace | A string that is the namespace for the header.
name | A string that contains the name of the SOAP header in the request.
value | The value for the SOAP header; this can be a CFML XML value.
mustunderstand | Optional. True or False (default). Sets the SOAP mustunderstand value for this header.

Usage

Call this function only from within a CFC web service function. It throws an error if it is invoked in a context that is not a web service request.

If you pass XML in the value parameter, ColdFusion ignores the namespace and name parameters. If you require a namespace, define it within the XML itself.

Use the IsSOAPRequest function to determine if the CFC is running as a web service.

Example

This example creates a CFC web service that illustrates the operation of the AddSOAPResponseHeader function and also provides a web service that illustrates the operation of other ColdFusion SOAP functions.

Save the following code as headerservice.cfc in a folder called soapheaders under your web root. Test its operation, and specifically the operation of the AddSOAPResponseHeader function, by executing the examples that invoke this web service. For example, see the example for AddSOAPRequestHeader.

<h3>AddSOAPResponseHeader Example</h3>
<!--- The headerservice.cfc CFC Web Service.--->
<cfcomponent displayName="tester" hint="Test for SOAP headers">
<cffunction name="echo_me"
            access="remote"
            output="false"
            returntype="string"
            displayname="Echo Test" hint="Header test">

  <cfargument name="in_here" required="true" type="string">

<cfset isSOAP = isSOAPRequest()>
<cfif isSOAP>
    <!--- Get the first header as a string and as XML. --->
    <cfset username = getSOAPRequestHeader("http://mynamespace/", "username")>
    <cfset return = "The service saw username: " & username>
    <cfset xmlusername = getSOAPRequestHeader("http://mynamespace/", "username", "TRUE")>
    <cfset return = return & "<br> as XML: " & xmlusername>

    <!--- Get the second header as a string and as XML. --->
    <cfset password = getSOAPRequestHeader("http://mynamespace/", "password")>
    <cfset return = return & "The service saw password: " & password>
    <cfset xmlpassword = getSOAPRequestHeader("http://mynamespace/", "password", "TRUE")>
    <cfset return = return & "<br> as XML: " & xmlpassword>

    <!--- Add a header as a string. --->
    <cfset addSOAPResponseHeader("http://www.tomj.org/myns", "returnheader", "AUTHORIZED VALUE", false)>

    <!--- Add a second header using a CFML XML value. --->
    <cfset doc = XmlNew()>
    <cfset x = XmlElemNew(doc, "http://www.tomj.org/myns", "returnheader2")>
    <cfset x.XmlText = "hey man, here I am in XML">
    <cfset  x.XmlAttributes["xsi:type"] = "xsd:string">
    <cfset tmp = addSOAPResponseHeader("ignoredNameSpace", "ignoredName", x)>
<cfelse>
    <!--- Add a header as a string - Must generate error!
    <cfset addSOAPResponseHeader("http://www.tomj.org/myns", "returnheader", "AUTHORIZED VALUE", false)>
    --->
    <cfset return = "Not invoked as a web service">
</cfif>

<cfreturn return>
</cffunction>
</cfcomponent>


ArrayAppend

Description

Appends an array element to an array.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArrayAppend(array, value)

See also

ArrayPrepend; Adding elements to an array in Using Arrays and Structures in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
array | Name of an array
value | Value to add at end of array

Example

<h3>ArrayAppend Example</h3>
<cfquery name = "GetEmployeeNames" datasource = "cfdocexamples">
SELECT FirstName, LastName FROM Employees
</cfquery>
<!--- create an array --->
<cfset myArray = ArrayNew(1)>
<!--- set element one to show where we are --->
<cfset myArray[1] = "Test Value">
<!--- loop through the query; append these names successively to the last
element --->
<cfloop query = "GetEmployeeNames">
    <cfoutput>#ArrayAppend(myArray, "#FirstName# #LastName#")#
    </cfoutput>, Array was appended<br>
</cfloop>
<!--- show the resulting array as a list --->
<cfset myList = ArrayToList(myArray, ",")>
<!--- output the array as a list --->
<cfoutput>
    <p>The contents of the array are as follows:
    <p>#myList#
</cfoutput>


ArrayAvg

Description

Calculates the average of the values in an array.

Returns

Number. If the array parameter value is an empty array, returns zero.

Category

Array functions, Mathematical functions

Function syntax

ArrayAvg(array)

See also

ArraySum; Basic array techniques in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
array | Name of an array

Usage

The following example uses the ColdFusion built-in variable Form.fieldNames, which is available on the action page of a form. It contains a comma-delimited list of the names of the fields on the form.

Example

<!--- This example shows the use of ArrayAvg --->
<!-- The following lines of code keep track of the form fields that can
be dynamically generated on the screen. It uses the Fieldnames variable
with the ListLen function to determine the number of fields on the form. --->
<cfset FormElem = 2>
    <cfif Isdefined("Form.Submit")>
        <cfif Form.Submit is "More">
            <cfset FormElem = ListLen(Form.Fieldnames)>
        </cfif>
    </cfif>

<html>
<head>
<title>ArrayAvg Example</title>
</head>
<body>
<h3>ArrayAvg Example</h3>
<p> This example uses ArrayAvg to find the average of the numbers that you enter
into an array.<br>
To enter more than two numbers press the <b>more</b> button.
</p>
<form action = "arrayavg.cfm">
<!--- The following code initially creates two fields. It adds fields if the
user presses MORE. FormElem is initialized to two at the beginning of this
code to show that the form has two fields. ----->
<input type = "submit" name = "submit" value = "more">
<table cellspacing = "2" cellpadding = "2" border = "0">
<cfloop index = "LoopItem" from = "1" to = "#FormElem#">
    <tr>
        <cfoutput>
          <th align = "left">Number #LoopItem#</th>
          <td><input type = "text" name = "number#LoopItem#"></td>
        </cfoutput>
    </tr>
</cfloop>
</table>
<input type = "submit" name = "submit" value = "get the average">
</form>

<!--- create an array --->
<cfif IsDefined("FORM.submit")>
    <cfset myNumberArray = ArrayNew(1)>
    <cfset Count = 1>
    <cfloop index = "ListItem" list = "#Form.Fieldnames#">
         <cfif Left(ListItem,3) is "Num">
            <cfset myNumberArray[Count] = Val("number#Count#")>
            <cfset count = IncrementValue(Count)>
        </cfif>
    </cfloop>

    <cfif Form.Submit is "get the average">
        <!--- use ArrayAvg to get the average of the two numbers --->
        <p>The average of the numbers that you entered is
        <cfoutput>#ArrayAvg(myNumberArray)#.</cfoutput>
    <cfelse>
        <cfoutput>Try again. You must enter at least two numeric values.
        </cfoutput>
    </cfif>
</cfif>
</body>
</html>


ArrayClear

Description

Deletes the data in an array.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArrayClear(array)

See also

ArrayDeleteAt; Functions for XML object management in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
array | Name of an array

Example

<h3>ArrayClear Example</h3>
<!--- create a new array --->
<cfset MyArray = ArrayNew(1)>
<!--- populate an element or two --->
<cfset MyArray[1] = "Test">
<cfset MyArray[2] = "Other Test">
<!--- output the contents of the array --->
<p>Your array contents are:
<cfoutput>#ArrayToList(MyArray)#</cfoutput>
<!--- check if the array is empty --->
<p>Is the array empty?:
<cfoutput>#ArrayIsEmpty(MyArray)#</cfoutput>
<p>Now, clear the array:
<!--- now clear the array --->
<cfset Temp = ArrayClear(MyArray)>
<!--- check if the array is empty --->
<p>Is the array empty?:
<cfoutput>#ArrayIsEmpty(MyArray)#</cfoutput>


ArrayDeleteAt

Description

Deletes an element from an array.

When an element is deleted, ColdFusion recalculates index positions. For example, in an array that contains the months of the year, deleting the element at position 5 removes the entry for May. After this, to delete the entry for June, you would delete the element at position 5 (not 6).

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArrayDeleteAt(array, position)

See also

ArrayInsertAt; Functions for XML object management in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed behavior: this function can be used on XML objects.
  • Changed thrown exceptions: this function can throw the InvalidArrayIndexException error.

Parameters

Parameter | Description
array | Name of an array
position | Array position

Throws

If this function attempts to delete an element at position 0, or specifies a value for position that is greater than the size of array, this function throws an InvalidArrayIndexException error.

Example

<h3>ArrayDeleteAt Example</h3><p>
<!--- create an array --->
<cfset DaysArray = ArrayNew(2)>
<!--- populate an element or two --->
<cfset DaysArray[1][1] = "Monday">
<cfset DaysArray[2][1] = "Tuesday">
<cfset DaysArray[3][1] = "Wednesday">
<cfset DaysArray[1][2] = "April 12">
<cfset DaysArray[2][2] = "April 13">
<cfset DaysArray[3][2] = "April 14">
<p>This is what the array looks like before delete:<br>
<cfoutput>
#DaysArray[1][1]#&nbsp;&nbsp;#DaysArray[1][2]#<br>
#DaysArray[2][1]#&nbsp;&nbsp;#DaysArray[2][2]#<br>
#DaysArray[3][1]#&nbsp;&nbsp;#DaysArray[3][2]#<br>
</cfoutput>

<cfoutput>
We delete this element of the array:<br>
#ArrayDeleteAt(DaysArray,2)#<br>
</cfoutput>
<!--- the formerly third element, "Wednesday" is second element --->
<p>This is what the array looks like after delete:<br>
<cfoutput>
#DaysArray[1][1]#&nbsp;&nbsp;#DaysArray[1][2]#<br>
#DaysArray[2][1]#&nbsp;&nbsp;#DaysArray[2][2]#<br>
</cfoutput>


ArrayInsertAt

Description

Inserts a value into an array. Array elements whose indexes are equal to or greater than the new position are incremented by one. The array length increases by one.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArrayInsertAt(array, position, value)

See also

ArrayDeleteAt ; Functions for XML object management in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed behavior: this function can be used on XML objects.
  • Changed thrown exceptions: this function can throw the InvalidArrayIndexException error.

Parameters

Parameter | Description
array | Name of an array
position | Index position at which to insert value
value | Value to insert

Usage

To apply the ArrayInsert() function to a multidimensional array, you must specify all but the last index in the array parameter. For example, the following code inserts an element at myarray[2][4]:

<cfset ArrayInsertAt(myarray[2], 4, "test")>

Throws

If this function attempts to insert an element at position 0, or specifies a value for position that is greater than the size of array, this function throws an InvalidArrayIndexException error.

Example

<h3>ArrayInsertAt Example</h3><p>
<!--- create a new array --->
<cfset DaysArray = ArrayNew(1)>
<!--- populate an element or two --->
<cfset DaysArray[1] = "Monday">
<cfset DaysArray[2] = "Tuesday">
<cfset DaysArray[3] = "Thursday">
<!--- add an element before position 3 --->
<p>Add an element before position 3:
    <cfoutput>#ArrayInsertAt(DaysArray,3,"Wednesday")#</cfoutput>
<p>Now output the array as a list:
<cfoutput>#ArrayToList(DaysArray)#</cfoutput>
<!--- The array now has four elements. Element 3, "Thursday", has become element four --->


ArrayIsEmpty

Description

Determines whether an array is empty of data elements.

Returns

True, if the array is empty; False, otherwise.

Category

Array functions

Function syntax

ArrayIsEmpty(array)

See also

ArrayLen, Functions for XML object management in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
array | Name of an array

Example

<h3>ArrayIsEmpty Example</h3>
<!--- create a new array --->
<cfset MyArray = ArrayNew(1)>
<!--- populate an element or two --->
<cfset MyArray[1] = "Test">
<cfset MyArray[2] = "Other Test">
<!--- output the contents of the array --->
<p>Your array contents are:
<cfoutput>#ArrayToList(MyArray)#</cfoutput>
<!--- check if the array is empty --->
<p>Is the array empty?:
<cfoutput>#ArrayIsEmpty(MyArray)#</cfoutput>
<p>Now, clear the array:
<!--- now clear the array --->
<cfset Temp = ArrayClear(MyArray)>
<!--- check if the array is empty --->
<p>Is the array empty?:
<cfoutput>#ArrayIsEmpty(MyArray)#</cfoutput>


ArrayLen

Description

Determines the number of elements in an array.

Returns

The number of elements in an array.

Category

Array functions

Function syntax

ArrayLen(array)

See also

ArrayIsEmpty; Functions for XML object management in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on child XML objects.

Parameters

Parameter | Description
array | Name of an array

Example

<h3>ArrayLen Example</h3>
<cfquery name = "GetEmployeeNames" datasource = "cfdocexamples">
SELECT FirstName, LastName FROM Employees
</cfquery>
<!--- create an array --->
<cfset myArray = ArrayNew(1)>
<!--- set element one to show where we are --->
<cfset myArray[1] = "Test Value">
<!--- loop through the query and append these names
successively to the last element --->
<cfloop query = "GetEmployeeNames">
    <cfset temp = ArrayAppend(myArray, "#FirstName# #LastName#")>
</cfloop>
<!--- show the resulting array as a list --->
<cfset myList = ArrayToList(myArray, ",")>
<!--- output the array as a list --->
<cfoutput>
    <p>The contents of the array are as follows:
    <p>#myList#
    <p>This array has #ArrayLen(MyArray)# elements.
</cfoutput>


ArrayMax

Description

Array maximum function.

Returns

The largest numeric value in an array. If the array parameter value is an empty array, returns zero.

Category

Array functions

Function syntax

ArrayMax(array)

Parameters

Parameter | Description
array | Name of an array

Example

<h3>ArrayMax Example</h3>
<p>This example uses ArrayMax to find the largest number in an array.<br> </p>
<!--- After checking whether the form has been submitted, the code creates an array
and assigns the form fields to the first two elements in the array. ---->
<cfif IsDefined("FORM.submit")>
    <cfset myNumberArray = ArrayNew(1)>
    <cfset myNumberArray[1] = number1>
    <cfset myNumberArray[2] = number2>
    <cfif Form.Submit is "Maximum Value">
        <!--- use ArrayMax to find the largest number in the array --->
        <p>The largest number that you entered is
        <cfoutput>#ArrayMax(myNumberArray)#.</cfoutput>
    </cfif>
</cfif>
<!---- The following form provides two numeric fields that are compared when the
form is submitted. --->
<form action = "arraymax.cfm">
<input type = "hidden" name = "number1_Float">
<input type = "hidden" name = "number2_Float">
<input type = "text" name = "number1"><br>
<input type = "text" name = "number2"><br>
<input type = "submit" name = "submit" value = "Maximum Value">
</form>


ArrayMin

Description

Array minimum function.

Returns

The smallest numeric value in an array. If the array parameter value is an empty array, returns zero.

Category

Array functions

Function syntax

ArrayMin(array)

Parameters

Parameter | Description
array | Name of an array

Example

<h3>ArrayMin Example</h3>
<p>This example uses ArrayMin to find the smallest number in an array.<br></p>
<!--- After checking whether the form has been submitted, this code creates an
array and assigns the form fields to the first two elements. ----->
<cfif IsDefined("FORM.submit")>
    <cfset myNumberArray = ArrayNew(1)>
    <cfset myNumberArray[1] = FORM.number1>
    <cfset myNumberArray[2] = FORM.number2>

    <cfif Form.Submit is "Minimum Value">
        <!--- use ArrayMin to find the smallest number in the array --->
        <p>The smallest number that you entered is
        <cfoutput>#ArrayMin(myNumberArray)#.</cfoutput>
    </cfif>
</cfif>
<!---- The following form provides two numeric fields that are compared when the form is submitted. ----->
<form action = "arraymin.cfm">
<input type = "hidden" name = "number1_Float">
<input type = "hidden" name = "number2_Float">
<input type = "text" name = "number1"><br>
<input type = "text" name = "number2"><br>
<input type = "submit" name = "submit" value = "Minimum Value">
</form>


ArrayNew

Description

Creates an array of 1–3 dimensions. Index array elements with square brackets: [ ].

ColdFusion arrays expand dynamically as data is added.

Returns

An array

Category

Array functions

Function syntax

ArrayNew(dimension)

Parameters

Parameter | Description
dimension | Number of dimensions in new array: 1, 2, or 3

Example

<h3>ArrayNew Example</h3>
<!--- Make an array --->
<cfset MyNewArray = ArrayNew(1)>
<!--- ArrayToList does not function properly if the Array is not initialized with
ArraySet --->
<cfset temp = ArraySet(MyNewArray, 1,6, "")>

<!--- set some elements --->
<cfset MyNewArray[1] = "Sample Value">
<cfset MyNewArray[3] = "43">
<cfset MyNewArray[6] = "Another Value">

<!--- is it an array? --->
<cfoutput>
    <p>Is this an array? #IsArray(MyNewArray)#
    <p>It has #ArrayLen(MyNewArray)# elements.
    <p>Contents: #ArrayToList(MyNewArray)#
<!--- the array has expanded dynamically to six elements with the use of ArraySet,
even though we only set three values --->
</cfoutput>


ArrayPrepend

Description

Inserts an array element at the beginning of an array.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArrayPrepend(array, value)

See also

ArrayAppend; Adding elements to an array in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
array | Name of an array
value | Value to insert at beginning of array

Example

<h3>ArrayPrepend Example</h3>
<cfquery name = "GetEmployeeNames" datasource = "cfdocexamples">
    SELECT FirstName, LastName FROM Employees
</cfquery>
<!--- create an array --->
<cfset myArray = ArrayNew(1)>
<!--- set element one to show where we are --->
<cfset myArray[1] = "Test Value">
<!--- loop through query. Append names successively before last element (list
reverses itself from the standard queried output, as it keeps
prepending the array entry) --->
<cfloop query = "GetEmployeeNames">
    <cfoutput>#ArrayPrepend(myArray, "#FirstName# #LastName#")#
    </cfoutput>, Array was prepended<br>
</cfloop>
<!--- show the resulting array as a list --->
<cfset myList = ArrayToList(myArray, ",")>
<!--- output the array as a list --->
<cfoutput>
    <p>The contents of the array are as follows:
    <p>#myList#
</cfoutput>


ArrayResize

Description

Resets an array to a specified minimum number of elements. This can improve performance, if used to size an array to its expected maximum. For more than 500 elements, use ArrayResize immediately after using the ArrayNew tag.

ColdFusion arrays expand dynamically as data is added.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArrayResize(array, minimum_size)

Parameters

Parameter | Description
array | Name of an array
minimum_size | Minimum array size

Example

<h3>ArrayResize Example</h3>
<!--- perform a query to get the list --->
<cfquery name = "GetCourses" datasource = "cfdocexamples">
SELECT * FROM Courses
</cfquery>
<!--- make a new array --->
<cfset MyArray = ArrayNew(1)>
<!--- resize that array to the number of records
in the query --->
<cfset temp = ArrayResize(MyArray, GetCourses.RecordCount)>
<cfoutput>
The array is now #ArrayLen(MyArray)# elements, to match
the query of #GetCourses.RecordCount# records.
</cfoutput>


ArraySet

Description

In a one-dimensional array, sets the elements in a specified index range to a value. Useful for initializing an array after a call to ArrayNew.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArraySet(array, start_pos, end_pos, value)

See also

ArrayNew; Populating arrays with data in Using Arrays and Structures in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
array | Name of an array.
start_pos | Starting index position of range to set.
end_pos | Ending index position of range to set. If this value is greater than array length, ColdFusion adds elements to array.
value | Value to which to set each element in the range.

Example

<h3>ArraySet Example</h3>

<!--- Make an array --->
<cfset MyNewArray = ArrayNew(1)>
<!--- ArrayToList does not function properly if the Array has not been initialized
with ArraySet --->
<cfset temp = ArraySet(MyNewArray, 1,6, "Initial Value")>

<!--- set some elements --->
<cfset MyNewArray[1] = "Sample Value">
<cfset MyNewArray[3] = "43">
<cfset MyNewArray[6] = "Another Value">
...


ArraySort

Description

Sorts array elements numerically or alphanumerically.

Returns

True, if sort is successful; False, otherwise.

Category

Array functions, List functions

Function syntax

ArraySort(array, sort_type [, sort_order ])

History

ColdFusion MX:

  • Changed thrown exceptions: this function can throw the ArraySortSimpleValueException error and ValueNotNumeric error.
  • Changed the order in which sorted elements are returned: in a textnocase, descending sort, this function might return elements in a different sort order than in earlier releases. If sort_type = "textnocase" and sort_order = "desc", ColdFusion MX processes elements that differ only in case differently from earlier releases, as follows:
    • ColdFusion MX reverses the elements’ original order.
    • Earlier releases of ColdFusion do not change the elements’ original order.

    For example, in a textnocase, desc sort of d,a,a,b,A, the following occurs:

    • ColdFusion MX returns d,b,A,a,a
    • Earlier ColdFusion releases return d,b,a,a,A

Parameters

Parameter

Description

array

Name of an array

sort_type
  • numeric: sorts numbers
  • text: sorts text alphabetically, taking case into account (also known as case sensitive). All letters of one case precede the first letter of the other case:

- aabzABZ, if sort_order = "asc" (ascending sort)

 - ZBAzbaa, if sort_order = "desc" (descending sort)

  • textnocase: sorts text alphabetically, without regard to case (also known as case-insensitive). A letter in varying cases precedes the next letter:

- aAaBbBzzZ, in an ascending sort; preserves original intra-letter order

- ZzzBbBaAa, in a descending sort; reverses original intra-letter order

sort_order
  • asc - ascending sort order. Default.

- aabzABZ or aAaBbBzzZ, depending on value of sort_type, for letters

- from smaller to larger, for numbers

  • desc - descending sort order.

- ZBAzbaa or ZzzBbBaAa, depending on value of sort_type, for letters

- from larger to smaller, for numbers

Throws

If an array element is other than a simple element, this function throws an ArraySortSimpleValueException error. If sort_type is numeric and an array element is not numeric, this function throws a ValueNotNumeric error.

Example

<!--- This example shows ArraySort --->
<cfquery name = "GetEmployeeNames" datasource = "cfdocexamples">
SELECT FirstName, LastName FROM Employees
</cfquery>
<!--- create an array --->
<cfset myArray = ArrayNew(1)>
<!--- loop through the query and append these names successively to the last
element --->
<cfloop query = "GetEmployeeNames">
    <cfset temp = ArrayAppend(myArray, "#FirstName# #LastName#")>
</cfloop>
<!--- show the resulting array as a list --->
<cfset myList = ArrayToList(myArray, ",")>
<!--- sort that array descending alphabetically --->
<cfset isSuccessful = ArraySort(myArray, "textnocase", "desc")>
...


ArraySum

Description

Array sum function.

Returns

The sum of values in an array. If the array parameter value is an empty array, returns zero.

Category

Array functions, Mathematical functions

Function syntax

ArraySum(array)

Parameters

Parameter | Description
array | Name of an array

Example

<h3>ArraySum Example</h3>
<p>This example uses ArraySum to add two numbers together.<br> </p>
<!--- After checking whether the form has been submitted, the code creates
an array and assigns the form fields to the first two elements in
the array. --->
<cfif IsDefined("FORM.submit")>
    <cfset myNumberArray = ArrayNew(1)>
    <cfset myNumberArray[1] = number1>
    <cfset myNumberArray[2] = number2>

    <cfif Form.Submit is "Add">
        <!--- use ArraySum to add the number in the array --->
        <p>The sum of the numbers is
        <cfoutput>#ArraySum(myNumberArray)#.</cfoutput>
    </cfif>
</cfif>
<!--- This form provides two numeric fields that are added when the form is
submitted. --->
<form action = "arraysum.cfm" method="post">
    <input type = "hidden" name = "number1_Float">
    <input type = "hidden" name = "number2_Float">
    <input type = "text" name = "number1">
    <br>
    <input type = "text" name = "number2">
    <br>
    <input type = "submit" name = "submit" value = "Add">
</form>


ArraySwap

Description

Swaps array values of an array at specified positions. This function is more efficient than multiple cfset tags.

Returns

True, on successful completion.

Category

Array functions

Function syntax

ArraySwap(array, position1, position2)

See also

Functions for XML object management in Using XML and WDDX in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
array | Name of an array
position1 | Position of first element to swap
position2 | Position of second element to swap

Example

<h3>ArraySwap Example</h3>

<cfset month = ArrayNew(1)>
<cfset month[1] = "February">
<cfset month[2] = "January">
<cfset temp = ArraySwap(month, 1, 2)>
<cfset temp = ArrayToList(month)>

<p>Show the results: <cfoutput>#temp#</cfoutput>


ArrayToList

Description

Converts a one-dimensional array to a list.

Returns

Delimited list, as a string.

Category

Array functions, Conversion functions, List functions

Function syntax

ArrayToList(array [, delimiter ])

Parameters

Parameter | Description
array | Name of array
delimiter | Character or multicharacter string to separate list elements. The default value is comma.

Example

<h3>ArrayToList Example</h3>

<cfquery name = "GetEmployeeNames" datasource = "cfdocexamples">
SELECT FirstName, LastName FROM Employees
</cfquery>

<!--- create an array --->
<cfset myArray = ArrayNew(1)>

<!--- loop through query, append names successively to last element --->
<cfloop query = "GetEmployeeNames">
    <cfset temp = ArrayAppend(myArray, "#FirstName# #LastName#")>
</cfloop>

<!--- show the resulting array as a list --->
<cfset myList = ArrayToList(myArray, ",")>

<!--- sort that array descending alphabetically --->
<cfset myAlphaArray = ArraySort(myArray, "textnocase", "desc")>

<!--- show the resulting alphabetized array as a list --->
<cfset myAlphaList = ArrayToList(myArray, ",")>

<!--- output the array as a list --->
<cfoutput>
    <p>The contents of the array are as follows:
    <p>#myList#
    <p>This array, alphabetized by first name (descending):
    <p>#myAlphaList#
    <p>This array has #ArrayLen(MyArray)# elements.
</cfoutput>


Asc

Description

Determines the value of a character.

Returns

The value of the first character of a string; if string is empty, returns zero.

Category

String functions

Function syntax

Asc(string)

See also

Chr

History

ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode characters, up to a value of 65536. (Earlier releases supported 1-255.)

Parameters

Parameter | Description
string | A string

Example

<h3>Asc Example</h3>
<!--- if the character string is not empty, output its ASCII value --->
<cfif IsDefined("FORM.charVals")>

    <cfif FORM.charVals is not "">
        <cfoutput>#Left(FORM.charVals,1)# =
     #Asc(FORM.charVals)#</cfoutput>
    <cfelse>
<!--- if it is empty, output an error message --->
        <h4>Enter a character</h4>
    </cfif>
</cfif>

<form action = "asc.cfm" method=post>
<p>Enter a character to see its ASCII value
<br><input type = "Text" name = "CharVals" size = "1" maxlength = "1">
<p><input type = "Submit" name = ""> <input type = "RESET">
</form>


ASin

Description

Determines the arcsine of a number. The arcsine is the angle whose sine is number.

Returns

The arcsine, in radians, of a number.

Category

Mathematical functions

Function syntax

ASin(number)

See also

Sin , Cos , ACos , Tan , Atn , Pi

Parameters

Parameter | Description
number | Sine of an angle. The value must be between -1 and 1, inclusive.

Usage

The range of the result is -p/2 to p/2 radians. To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

Example

<h3>ASin Example</h3>
<!--- output its arcsine value --->
<cfif IsDefined("FORM.SinNum")>
    <cfif IsNumeric(FORM.SinNum)>
        <cfif FORM.SinNum LESS THAN OR EQUAL TO 1>
            <cfif FORM.SinNum GREATER THAN OR EQUAL TO -1>
                ASin(<cfoutput>#FORM.SinNum#</cfoutput>) =
                 <cfoutput>#ASin(FORM.sinNum)# Radians</cfoutput>
                 <br> or <br>ASin(<cfoutput>#FORM.SinNum#</cfoutput>) =
                <cfoutput>
                    #ASin(FORM.sinNum) * 180/Pi()# Degrees
                </cfoutput>
            <cfelse>
<!--- if it is less than negative one, output an error message --->
                <h4>Enter the sine of the angle to calculate, in degrees and radians.
                The value must be between 1 and -1, inclusive.</h4>
            </cfif>
        <cfelse>
<!--- if it is greater than one, output an error message --->
        <h4>Enter the sine of the angle to calculate, in degrees and radians. The
value must be between 1 and -1, inclusive.</h4>
        </cfif>
    <cfelse>
<!--- if it is empty, output an error message --->
        <h4>Enter the sine of the angle to calculate, in degrees and radians. The
value must be between 1 and -1,inclusive.</h4>
    </cfif>
</cfif>
<form action = "./evaltest.cfm" method="post">
<p>Enter a number to get its arcsine in Radians and Degrees.
<br><input type = "Text" name = "SinNum" size = "25">
<p><input type = "Submit" name = ""> <input type = "RESET">
</form>


Atn

Description

Arctangent function. The arctangent is the angle whose tangent is number.

Returns

The arctangent, in radians, of a number.

Category

Mathematical functions

Function syntax

Atn(number)

See also

Atn , Sin , ASin , Cos , ACos , Pi

Parameters

Parameter | Description
number | Tangent of an angle

Usage

The range of the result is -p/2 to p/2 radians. To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

Example

<h3>Atn Example</h3>
<!--- output its Atn value --->
<cfif IsDefined("FORM.AtnNum")>
    <cfif IsNumeric(FORM.AtnNum)>
        Atn(<cfoutput>#FORM.AtnNum#</cfoutput>) is
     <cfoutput>#Atn(FORM.AtnNum)# radians is #Atn(FORM.AtnNum * 180/PI())# Degrees</cfoutput>
    <cfelse>
<!--- if it is empty, output an error message --->
        <h4>Enter a number</h4>
    </cfif>
</cfif>
<form action = "evaltest.cfm" method="post">
<p>Enter a number to get its arctangent in Radians and Degrees
<br><input type = "Text" name = "atnNum" size = "25">
<p><input type = "Submit" name = ""> <input type = "RESET">
</form>


AuthenticatedContext

Description

This function is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide.

History

ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases.


AuthenticatedUser

Description

This function is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide.

History

ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases.


BinaryDecode

Description

Converts a string to a binary object. Used to convert binary data that has been encoded into string format back into binary data.

Returns

A binary object.

Category

Conversion functions, String functions

Function syntax

BinaryDecode(string, binaryencoding)

See also

BinaryEncode, CharsetEncode, CharsetDecode

History

ColdFusion MX 7: Added this function.

Parameters

Parameter

Description

string

A string containing encoded binary data.

binaryencoding

A string specifying the algorithm used to encode the original binary data into a string; must be one of the following:

  • Hex: the characters 0-9 and A-F represent the hexadecimal value of each byte; for example, 3A.
  • UU: data is encoded using the UNIX UUencode algorithm.
  • Base64: data is encoded using the Base64 algorithm, as specified by IETF RFC 2045, at www.ietf.org/rfc/rfc2045.txt.

Usage

Use this function to convert a binary-encoded string representation of binary data back to a binary object for use in your application. Binary data is often encoded as a string for transmission over many Internet protocols, such as HTTP and SMTP, or for storage in a database.

Macromedia recommends that you use the BinaryDecode function, not the ToBinary (base64data) function, to convert Base64-encoded data to binary data in all new applications.

See the following pages for additional information on handling binary data:

  • cffile for loading and reading binary data in files
  • cfwddx for serializing and deserializing binary data
  • IsBinary for checking variables for binary format
  • Len for determining the length of a binary object

Example

The following example reads a GIF file as binary data, converts it to a binary-encoded string, converts the binary-encoded data back to binary data and writes the result to a file. It displays the encoded string and the image in the output file.

<h3>Binary Encoding Conversion Example</h3>

<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.binEncoding")>

    <!--- Read in a binary data file. --->
    <cffile action="readbinary" file="C:\CFusionMX7\wwwroot\CFIDE\administrator\images\help.gif" variable="binimage">

    <!--- Convert the read data to binary encoding and back to binary data. --->
    <cfscript>
        binencode=BinaryEncode(binimage, Form.binEncoding);
        bindecode=BinaryDecode(binencode, Form.binEncoding);
    </cfscript>

    <!---  Write the converted results to a file. --->
    <cffile action="write" file="C:\temp\help.gif" output="#bindecode#" addnewline="No" >

    <!--- Display the results. --->
    <cfoutput>
        <p><b>The binary encoding:</b> #Form.binEncoding#</p>

        <p><b>The image converted into a binary-encoded string by BinaryEncode
            </b><br>
            #binencode#</p>
        <p><b>The image as written back to a file after converting back to binary
            using BinaryDecode</b><br>
        <img src="C:\temp\help.gif"><br>
    </cfoutput>
</cfif>

<!--- The input form. --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select binary encoding</b><br>
    <select size="1" name="binEncoding" >
        <option selected>UU</option>
        <option>Base64</option>
        <option>Hex</option>
    </select><br>
    <br>
    <input type = "Submit" value = "convert my data">
</form>


BinaryEncode

Description

Converts binary data to a string.

Returns

An encoded string representing the binary data.

Category

Conversion functions, String functions

Function syntax

BinaryEncode(binarydata, encoding)

See also

BinaryDecode, CharsetEncode, CharsetDecode

History

ColdFusion MX 7: Added this function.

Parameters

Parameter

Description

binarydata

A variable containing the binary data to encode.

encoding

A string specifying the encoding method to use to represent the data; one of the following:

  • Hex: use the characters 0-9 and A-F to represent the hexadecimal value of each byte; for example, 3A.
  • UU: use the UNIX UUencode algorithm to convert the data.
  • Base64: use the Base64 algorithm to convert the data, as specified by IETF RFC 2045, at www.ietf.org/rfc/rfc2045.txt.

Usage

Binary objects and, in some cases, 8-bit characters, cannot be transported over many Internet protocols, such as HTTP and SMTP, and might not be supported by some database systems. By Binary encoding the data, you convert the data into a format that you can transfer over any Internet protocol or store in a database as character data. To convert the data back to a binary format, use the BinaryDecode function.

Macromedia recommends that you use the BinaryEncode function, and not the ToBase64 (binarydata) function, to convert binary data to Base64 data in all new applications.

This function provides a superset of the functionality of the ToBase64(binarydata) function.

See the following pages for additional information on handling binary data:

  • cffile for loading and reading binary data
  • cfwddx for serializing and deserializing binary data
  • IsBinary for checking variables for binary format
  • Len for determining the length of a binary object

Example

The following example reads a GIF file as binary data, converts it to a binary-encoded string, converts the binary-encoded data back to binary data, and writes the result to a file. It displays the encoded string and the image in the output file.

<h3>Binary Encoding Conversion Example</h3>

<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.binEncoding")>

    <!--- Read in a binary data file. --->
    <cffile action="readbinary" file="C:\CFusionMX7\wwwroot\CFIDE\administrator\images\help.gif" variable="binimage">

    <!--- Convert the read data to binary encoding and back to binary data. --->
    <cfscript>
        binencode=BinaryEncode(binimage, Form.binEncoding);
        bindecode=BinaryDecode(binencode, Form.binEncoding);
    </cfscript>

    <!---  Write the converted results to a file. --->
    <cffile action="write" file="C:\temp\help.gif" output="#bindecode#" addnewline="No" >

    <!--- Display the results. --->
    <cfoutput>
        <p><b>The binary encoding:</b> #Form.binEncoding#</p>

        <p><b>The image converted into a binary-encoded string by BinaryEncode
            </b><br>
            #binencode#</p>
        <p><b>The image as written back to a file after converting back to binary
            using BinaryDecode</b><br>
        <img src="C:\temp\help.gif"><br>
    </cfoutput>
</cfif>

<!--- The input form. --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select binary encoding</b><br>
    <select size="1" name="binEncoding" >
        <option selected>UU</option>
        <option>Base64</option>
        <option>Hex</option>
    </select><br>
    <br>
    <input type = "Submit" value = "convert my data">
</form>


BitAnd

Description

Performs a bitwise logical AND operation.

Returns

The bitwise AND of two long integers.

Category

Mathematical functions

Function syntax

BitAnd(number1, number2)

See also

BitNot , BitOr , BitXor

Parameters

Parameter | Description
number1 | 32-bit signed integer
number2 | 32-bit signed integer

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitAnd Example</h3>

<p>Returns the bitwise AND of two long integers.
<p>BitAnd(5,255): <cfoutput>#BitAnd(5,255)#</cfoutput>
<p>BitAnd(5,0): <cfoutput>#BitAnd(5,0)#</cfoutput>
<p>BitAnd(128,128): <cfoutput>#BitAnd(128,128)#</cfoutput>


BitMaskClear

Description

Performs a bitwise mask clear operation.

Returns

A number, bitwise cleared, with length bits beginning at start.

Category

Mathematical functions

Function syntax

BitMaskClear(number, start, length)

See also

BitMaskRead , BitMaskSet

Parameters

Parameter | Description
number | 32-bit signed integer
start | Integer, in the range 0-31, inclusive; start bit for mask
length | Integer, in the range 0-31, inclusive; length of mask

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitMaskClear Example</h3>

<p>Returns number bitwise cleared with length bits beginning from start.

<p>BitMaskClear(255, 4, 4): <cfoutput>#BitMaskClear(255, 4, 4)#
</cfoutput>
<p>BitMaskClear(255, 0, 4): <cfoutput>#BitMaskClear(255, 0, 4)#
</cfoutput>
<p>BitMaskClear(128, 0, 7): <cfoutput>#BitMaskClear(128, 0, 7)#
</cfoutput>


BitMaskRead

Description

Performs a bitwise mask read operation.

Returns

An integer, created from length bits of number, beginning at start.

Category

Mathematical functions

Function syntax

BitMaskRead(number, start, length)

See also

BitMaskClear , BitMaskSet

Parameters

Parameter | Description
number | 32-bit signed integer to mask
start | Integer, in the range 0-31, inclusive; start bit for read
length | Integer, in the range 0-31, inclusive; length of mask

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitMaskRead Example</h3>
<p>Returns integer created from <em>length</em> bits of <em>number</em>, beginning
with <em>start</em>.

<p>BitMaskRead(255, 4, 4): <cfoutput>#BitMaskRead(255, 4, 4)#
</cfoutput>
<p>BitMaskRead(255, 0, 4): <cfoutput>#BitMaskRead(255, 0, 4)#
</cfoutput>
<p>BitMaskRead(128, 0, 7): <cfoutput>#BitMaskRead(128, 0, 7)#
</cfoutput>


BitMaskSet

Description

Performs a bitwise mask set operation.

Returns

A number, bitwise masked with length bits of mask beginning at start.

Category

Mathematical functions

Function syntax

BitMaskSet(number, mask, start, length)

See also

BitMaskClear , BitMaskRead

Parameters

Parameter | Description
number | 32-bit signed integer
mask | 32-bit signed integer; mask
start | Integer, in the range 0-31, inclusive; start bit for mask
length | Integer, in the range 0-31, inclusive; length of mask

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitMaskSet Example</h3>
<p>Returns number bitwise masked with length bits of mask beginning at start.

<p>BitMaskSet(255, 255, 4, 4):
<cfoutput>#BitMaskSet(255, 255, 4, 4)#</cfoutput>
<p>BitMaskSet(255, 0, 4, 4):
<cfoutput>#BitMaskSet(255, 0, 4, 4)#</cfoutput>
<p>BitMaskSet(0, 15, 4, 4):
<cfoutput>#BitMaskSet(0, 15, 4, 4)#</cfoutput>


BitNot

Description

Performs a bitwise logical NOT operation.

Returns

A number; the bitwise NOT of a long integer.

Category

Mathematical functions

Function syntax

BitNot(number)

See also

BitAnd , BitOr , BitXor

Parameters

Parameter | Description
number | 32-bit signed integer

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitNot Example</h3>
<p>Returns the bitwise NOT of a long integer.

<p>BitNot(0): <cfoutput>#BitNot(0)#</cfoutput>
<p>BitNot(255): <cfoutput>#BitNot(255)#</cfoutput>


BitOr

Description

Performs a bitwise logical OR operation.

Returns

A number; the bitwise OR of two long integers.

Category

Mathematical functions

Function syntax

BitOr(number1, number2)

See also

BitAnd , BitNot , BitXor

Parameters

Parameter | Description
number1 | 32-bit signed integer
number2 | 32-bit signed integer

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitOr Example</h3>
<p>Returns the bitwise OR of two long integers.

<p>BitOr(5,255): <cfoutput>#BitOr(5,255)#</cfoutput>
<p>BitOr(5,0): <cfoutput>#BitOr(5,0)#</cfoutput>
<p>BitOr(7,8): <cfoutput>#BitOr(7,8)#</cfoutput>


BitSHLN

Description

Performs a bitwise shift-left, no-rotation operation.

Returns

A number, bitwise shifted without rotation to the left by count bits.

Category

Mathematical functions

Function syntax

BitSHLN(number, count)

See also

BitSHRN

Parameters

Parameter | Description
number | 32-bit signed integer
count | Integer, in the range 0-31, inclusive; number of bits to shift the number

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitSHLN Example</h3>
<p>Returns the number, bitwise shifted, without rotation, to the left by count
bits.

<p>BitSHLN(1,1): <cfoutput>#BitSHLN(1,1)#</cfoutput>
<p>BitSHLN(1,30): <cfoutput>#BitSHLN(1,30)#</cfoutput>
<p>BitSHLN(1,31): <cfoutput>#BitSHLN(1,31)#</cfoutput>
<p>BitSHLN(2,31): <cfoutput>#BitSHLN(2,31)#</cfoutput>


BitSHRN

Description

Performs a bitwise shift-right, no-rotation operation.

Returns

A number, bitwise shifted, without rotation, to the right by count bits.

Category

Mathematical functions

Function syntax

BitSHRN(number, count)

See also

BitSHLN

Parameters

Parameter | Description
number | 32-bit signed integer
count | Integer, in the range 0-31, inclusive. Number of bits to shift the number

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitSHRN Example</h3>
<p>Returns a number, bitwise shifted, without rotation, to the right, by count
bits.

<p>BitSHRN(1,1): <cfoutput>#BitSHRN(1,1)#</cfoutput>
<p>BitSHRN(255,7): <cfoutput>#BitSHRN(255,7)#</cfoutput>
<p>BitSHRN(-2147483548,1): <cfoutput>#BitSHRN(-2147483548,1)#
</cfoutput>


BitXor

Description

Performs a bitwise logical XOR operation.

Returns

Bitwise XOR of two long integers.

Category

Mathematical functions

Function syntax

BitXor(number1, number2)

See also

BitAnd , BitNot , BitOr

Parameters

Parameter | Description
number1 | 32-bit signed integer
number2 | 32-bit signed integer

Usage

Bit functions operate on 32-bit signed integers, in the range -2147483648 – 2147483647.

Example

<h3>BitXOr Example</h3>
<p>Returns the bitwise XOR of two long integers.

<p>BitXOr(5,255): <cfoutput>#BitXOr(5,255)#</cfoutput>
<p>BitXOr(5,0): <cfoutput>#BitXOr(5,0)#</cfoutput>
<p>BitXOr(128,128): <cfoutput>#BitXOr(128,128)#</cfoutput>


Ceiling

Description

Determines the closest integer that is greater than a specified number.

Returns

The closest integer that is greater than a given number.

Category

Mathematical functions

Function syntax

Ceiling(number)

See also

Int , Fix , Round

Parameters

Parameter | Description
number | A real number

Example

<h3>Ceiling Example</h3>

<cfoutput>
<p>The ceiling of 3.4 is #ceiling(3.4)#
<p>The ceiling of 3 is #ceiling(3)#
<p>The ceiling of 3.8 is #ceiling(3.8)#
<p>The ceiling of -4.2 is #ceiling(-4.2)#
</cfoutput>


CharsetDecode

Description

Converts a string to a binary representation.

Returns

A binary object that represents the string.

Category

Conversion functions, String functions

Function syntax

CharsetDecode(string, encoding)

See also

BinaryDecode, BinaryEncode, CharsetEncode; Determining the page encoding of server output in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parametersc

Parameter

Description

string

A string containing data to encode in binary format.

encoding

A string specifying encoding of the input data. Must be a character encoding name recognized by the Java runtime. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For a complete list of character encoding names supported by Sun Java runtimes, see http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html and
http://java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html.

Usage

This function converts a string directly to a binary object. In releases of ColdFusion through ColdFusion MX 6.1, you had to use the ToBase64 function to convert the string to Base64 and then use the ToBinary function to convert strings to binary data.

Example

The following example uses the CharsetDecode function to convert a string from a form to a binary object, and uses the CharsetEncode function to convert it back to the original value. You can change the character encoding that ColdFusion uses for the conversion. Notice that if you select the Asian language encodings, characters that are not in the specified character set do get successfully converted.

<h3>Character Encoding Conversion Example</h3>
<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.myString")>

    <!--- Do the conversions. --->
    <cfscript>
        chardecode=CharsetDecode(Form.myString, Form.charEncoding);
        charencode=CharsetEncode(chardecode, Form.charEncoding);
    </cfscript>

    <!--- Display the input values and results. --->
    <cfoutput>
        <h3>Parameter Settings</h3>
        <p><b>The string:</b><br>
             #Form.myString#</p>
        <p><b>The character encoding:</b> #Form.charEncoding#</p>

        <h3>Results of the operations:</h3>
        <p><b>Dump of the string converted to a binary object by CharsetDecode:
            </b><br>
            <cfdump var="#chardecode#"></p>
        <p><b>The binary object converted back to a string by CharsetEncode:
            </b><br>
        #charencode#</p>
    </cfoutput>
</cfif>

<!--- The input form. --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select the character encoding</b><br>
    <!--- This is a subset, additional encodings are available. --->
    <select size="1" name="charEncoding" >
        <option selected>UTF-8</option>
        <option>ASCII</option>
        <option>ISO8859_1</option>
        <option>CP1252</option>
        <option>SJIS</option>
        <option>MS932</option>
        <option>EUC_CN</option>
        <option>Big5</option>
    </select><br>
    <br>
    <b>Enter a string</b><br>
    <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">
The following four characters are not in all character encodings: ½àç÷
    </textArea><br>
    <br>
    <input type = "Submit" value = "convert my data">
</form>


CharsetEncode

Description

Uses the specified encoding to convert binary data to a string.

Returns

A string representation of the binary object.

Category

Conversion functions, String functions

Function syntax

CharsetEncode(binaryobject, encoding)

See also

BinaryDecode, BinaryEncode, CharsetDecode; Determining the page encoding of server output in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parametersc

Parameter

Description

binaryobject

A variable containing binary data to decode into text.

encoding

The character encoding that was used to encode the string into binary format. It must be a character encoding name recognized by the Java runtime. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For a complete list of character encoding names supported by Sun Java runtimes, see http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html and http://java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html.

Usage

Macromedia recommends that you use this function, and not the ToString function, to convert binary data to strings in all new applications.

Example

The following example uses the CharsetDecode function to convert a string from a form to a binary object, and uses the CharsetEncode function to convert it back to the original value. You can change the character encoding that ColdFusion uses for the conversion. Notice that if you select the Asian language encodings, characters that are not in the specified character set do get successfully converted.

<h3>Character Encoding Conversion Example</h3>
<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.myString")>

    <!--- Do the conversions. --->
    <cfscript>
        chardecode=CharsetDecode(Form.myString, Form.charEncoding);
        charencode=CharsetEncode(chardecode, Form.charEncoding);
    </cfscript>

    <!--- Display the input values and results. --->
    <cfoutput>
        <h3>Parameter Settings</h3>
        <p><b>The string:</b><br>
             #Form.myString#</p>
        <p><b>The character encoding:</b> #Form.charEncoding#</p>

        <h3>Results of the operations:</h3>
        <p><b>Dump of the string converted to a binary object by CharsetDecode:
            </b><br>
            <cfdump var="#chardecode#"></p>
        <p><b>The binary object converted back to a string by CharsetEncode:
            </b><br>
        #charencode#</p>
    </cfoutput>
</cfif>

<!--- The input form. --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select the character encoding</b><br>
    <!--- This is a subset, additional encodings are available. --->
    <select size="1" name="charEncoding" >
        <option selected>UTF-8</option>
        <option>ASCII</option>
        <option>ISO8859_1</option>
        <option>CP1252</option>
        <option>SJIS</option>
        <option>MS932</option>
        <option>EUC_CN</option>
        <option>Big5</option>
    </select><br>
    <br>
    <b>Enter a string</b><br>
    <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">
The following four characters are not in all character encodings: ½àç÷
    </textArea><br>
    <br>
    <input type = "Submit" value = "convert my data">
</form>


Chr

Converts a numeric value to a UCS-2 character.

Returns

A character with the specified UCS-2 character code.

Category

String functions

Function syntax

Chr(number)

See also

Asc

History

ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode characters, up to a value of 65535. (Earlier releases supported 1-255.)

Parameters

Parameter | Description
number | A value (a number in the range 0 to 65535, inclusive)

Usage

The values 0 – 31 are standard, nonprintable codes. For example:

  • Chr(10) returns a linefeed character
  • Chr(13) returns a carriage return character
  • The two-character string Chr(13) & Chr(10) returns a Windows newline

Note: For a complete list of the Unicode characters and their codes, see www.unicode.org/charts/.

Example

<!--- If the character string is not empty, then
        output its Chr value. --->
<cfif IsDefined("form.charVals")>
        <cfoutput>#form.charVals# = #Chr(form.charVals)#</cfoutput>
</cfif>

<cfform action="#CGI.script_name#" method="POST">
    <p>Type an integer character code from 1 to 65535<br>
        to see its corresponding character.<br>
    <cfinput type="Text"
        name="CharVals"
        range="1,65535"
        message="Please enter an integer from 1 to 65535"
        validate="integer"
        required="Yes"
        size="5"
        maxlength="5"
        >
<p><input type="Submit" name=""> <input type="RESET">
</cfform>


CJustify

Description

Centers a string in a field length.

Returns

String, center-justified by adding spaces before or after the input parameter. If length is less than the length of the input parameter string, the string is returned unchanged.

Category

Display and formatting functions, String functions

Function syntax

Cjustify(string, length)

See also

LJustify , RJustify

Parameters

Parameter

Description

string

A string or a variable that contains one. May be empty. If it is a variable that is defined as a number, the function processes it as a string.

length

A positive integer or a variable that contains one. Length of field.

Can be coded as:

  • A number; for example, 6
  • A string representation of a number; for example, "6"

Any other value causes ColdFusion to throw an error.

Example

<!--- This example shows how to use CJustify --->
<CFPARAM name = "jstring" DEFAULT = "">

<cfif IsDefined("FORM.submit")>
<cfdump var="#Form#">
    <cfset jstring = Cjustify("#FORM.justifyString#", 35)>
</cfif>
<html>
<head>
<title>CJustify Example</title>
</head>
<body>
<h3>CJustify</h3>
<p>Enter a string; it will be center-justified within the sample field.
<form action = "cjustify.cfm" method="post">
<p><input type = "Text" value = "<cfoutput>#jString#</cfoutput>"
        size = 35 name = "justifyString">
<p><input type = "Submit" name = "submit">
<input type = "RESET">
</form>
</body>
</html>


Compare

Description

Performs a case-sensitive comparison of two strings.

Returns

  • -1, if string1 is less than string2
  • 0, if string1 is equal to string2
  • 1, if string1 is greater than string2

Category

String functions

Function syntax

Compare(string1, string2)

See also

CompareNoCase , Find

Parameters

Parameter | Description
string1 | A string or a variable that contains one
string2 | A string or a variable that contains one

Usage

Compares the values of corresponding characters in string1 and string2.

Example

<h3>Compare Example</h3>
<p>The compare function performs a <I>case-sensitive</I> comparison of two strings.

<cfif IsDefined("FORM.string1")>
 <cfset comparison = Compare(FORM.string1, FORM.string2)>
 <!--- switch on the variable to give various responses --->
 <cfswitch expression = #comparison#>
    <cfcase value = "-1">
        <h3>String 1 is less than String 2</h3>
        <I>The strings are not equal</I>
    </cfcase>
    <cfcase value = "0">
        <h3>String 1 is equal to String 2</h3>
        <I>The strings are equal!</I>
    </cfcase>
    <cfcase value = "1">
        <h3>String 1 is greater than String 2</h3>
        <I>The strings are not equal</I>
    </cfcase>
    <CFDEFAULTCASE>
        <h3>This is the default case</h3>
    </CFDEFAULTCASE>
    </cfswitch>
</cfif>
<form action = "compare.cfm" method="post">
<p>String 1
<br><input type = "Text" name = "string1">
<p>String 2
<br><input type = "Text" name = "string2">
<p><input type = "Submit" value = "Compare these Strings" name = "">
    <input type = "RESET">
</form>


CompareNoCase

Description

Performs a case-insensitive comparison of two strings.

Returns

An indicator of the difference:

  • A negative number, if string1 is less than string2
  • 0, if string1 is equal to string2
  • A positive number, if string1 is greater than string2

Category

String functions

Function syntax

CompareNoCase(string1, string2)

See also

Compare, FindNoCase; Ambiguous type expressions and strings in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
string1 | A string or a variable that contains one
string2 | A string or a variable that contains one

Example

<H3>CompareNoCase Example</H3>
<P>This function performs a <I>case-insensitive</I> comparison of two strings.
<CFIF IsDefined("form.string1")>
<CFSET comparison = Comparenocase(form.string1, form.string2)>
<!--- switch on the variable to give various responses --->
<CFSWITCH EXPRESSION=#comparison#>
    <CFCASE value="-1">
        <H3>String 1 is less than String 2</H3>
        <I>The strings are not equal</I>
    </CFCASE>
    <CFCASE value="0">
        <H3>String 1 is equal to String 2</H3>
        <I>The strings are equal!</I>
    </CFCASE>
    <CFCASE value="1">
        <H3>String 1 is greater than String 2</H3>
        <I>The strings are not equal</I>
    </CFCASE>
    <CFDEFAULTCASE>
        <H3>This is the default case</H3>
    </CFDEFAULTCASE>
</CFSWITCH>
</CFIF>
<FORM ACTION="comparenocase.cfm" METHOD="POST">
<P>String 1
<BR><INPUT TYPE="Text" NAME="string1">
<P>String 2
<BR><INPUT TYPE="Text" NAME="string2">
<P><INPUT TYPE="Submit" VALUE="Compare these Strings" NAME="">
<INPUT TYPE="RESET">
</FORM>


Cos

Description

Calculates the cosine of an angle that is entered in radians.

Returns

A number; the cosine of the angle.

Category

Mathematical functions

Function syntax

Cos(number)

See also

ACos , Sin , ASin , Tan , Atn , Pi

Parameters

Parameter | Description
number | Angle, in radians, for which to calculate the cosine

Usage

The range of the result is -1 to 1.

To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

Note: Because the function uses floating point arithmetic, it returns a very small number (such as 6.12323399574E-017) for angles that should produce 0. To test for a 0 value, check whether the value is less than 0.0000000000001.

Example

<h3>Cos Example</h3>
<!--- Calculate cosine if form has been submitted --->
<cfif IsDefined("FORM.cosNum")>
<!--- Make sure input is a number --->
    <cfif IsNumeric(#FORM.cosNum#)>
<!--- Convert degrees to radians, call the Cos function. --->
        <cfset cosValue=#Cos((Form.cosNum * PI()) / 180)#>
<!--- 0.0000000000001 is the function's precision limit.
     If absolute value of returned cosine value is
     less, set result to 0 --->
        <cfif Abs(cosValue) LT 0.0000000000001>
           <cfset cosValue=0>
        </cfif>
        <cfoutput>
            Cos(#FORM.cosNum#) = #cosValue#<br><br>
        </cfoutput>
    <cfelse>
<!--- If input is not a number, show an error message --->
        <h4>You must enter a numeric angle in degrees.</h4>
    </cfif>
</cfif>
<form action = "#CGI.script_name#" method="post">
    Enter an angle in degrees to get its cosine:
    <br><input type = "Text" name = "cosNum" size = "15">
    <br><br>
    <input type = "Submit" name = "">&nbsp;&nbsp;
    <input type = "RESET"
</form>


CreateDate

Description

Creates a date/time object.

Returns

A date/time value.

Category

Date and time functions

Function syntax

CreateDate(year, month, day)

See also

CreateDateTime , CreateODBCDate; Date-time functions and queries when ODBC is not supported in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
year | Integer in the range 0-9999. Integers in the range 0-29 are converted to 2000-2029. Integers in the range 30-99 are converted to 1930-1999. You cannot specify dates before AD 100.
month | Integer in the range 1 (January)-12 (December)
day | Integer in the range 1-31

Usage

CreateDate is a subset of CreateDateTime.

The time in the returned object is set to 00:00:00.

Example

<h3>CreateDate Example</h3>
<CFIF IsDefined("form.year")>
<p>Your date value, generated with CreateDate:
<CFSET yourDate = CreateDate(form.year, form.month, form.day)>
<cfoutput>
<ul>
    <li>Formatted with CreateDate: #CreateDate(form.year, form.month, form.day)#
    <li>Formatted with CreateDateTime: #CreateDateTime(form.year, form.month,
form.day, 12,13,0)#
    <li>Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
    <li>Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#
</ul>

<p>The same value can be formatted with DateFormat:
<ul>
    <li>Formatted with CreateDate and DateFormat:
            #DateFormat(CreateDate(form.year, form.month, form.day), "mmm-dd-yyyy")#
    <li>Formatted with CreateDateTime and DateFormat:
            #DateFormat(CreateDateTime(form.year, form.month, form.day, 12,13,0))#
    <li>Formatted with CreateODBCDate and DateFormat:
            #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
    <li>Formatted with CreateODBCDateTime and DateFormat:
            #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#
</ul>
</cfoutput>
</CFIF>
<CFFORM ACTION="createdate.cfm" METHOD="POST">
<p>Enter the year, month and day, as integers:
<PRE>
Year	<CFINPUT TYPE="Text" NAME="year" VALUE="1998" VALIDATE="integer"
        REQUIRED="Yes">
Month	<CFINPUT TYPE="Text" NAME="month" VALUE="6" VALIDATE="integer"
        REQUIRED="Yes">
Day	<CFINPUT TYPE="Text" NAME="day" VALUE="8" VALIDATE="integer"
        REQUIRED="Yes">
</PRE>
<p><INPUT TYPE="Submit" NAME=""> <INPUT TYPE="RESET">
</cfform>


CreateDateTime

Description

Creates a date-time object.

Returns

A date/time value.

Category

Date and time functions

Function syntax

CreateDateTime(year, month, day, hour, minute, second)

See also

CreateDate, CreateTime, CreateODBCDateTime, Now; Date-time functions and queries when ODBC is not supported in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
year | Integer in the range 0-9999. Integers in the range 0-29 are converted to 2000-2029. Integers in the range 30-99 are converted to 1930-1999. You cannot specify dates before AD 100.
month | Integer in the range 1 (January)–12 (December)
day | Integer in the range 1–31
hour | Integer in the range 0–23
minute | Integer in the range 0–59
second | Integer in the range 0–59

Example

<h3>CreateDateTime Example</h3>

<CFIF IsDefined("form.year")>
Your date value, generated with CreateDateTime:
<CFSET yourDate = CreateDateTime(form.year, form.month, form.day,
form.hour, form.minute, form.second)>

<cfoutput>
<ul>
    <li>Formatted with CreateDate: #CreateDate(form.year, form.month, form.day)#
    <li>Formatted with CreateDateTime: #CreateDateTime(form.year, form.month,
form.day, form.hour, form.minute, form.second)#
    <li>Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
    <li>Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#
</ul>

<p>The same value can be formatted with DateFormat:
<ul>
    <li>Formatted with CreateDate and DateFormat:
        #DateFormat(CreateDate(form.year, form.month, form.day), "mmm-dd-yyyy")#
    <li>Formatted with CreateDateTime and DateFormat:
        #DateFormat(CreateDateTime(form.year, form.month, form.day,
form.hour, form.minute, form.second))#
    <li>Formatted with CreateODBCDate and DateFormat:
        #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
    <li>Formatted with CreateODBCDateTime and DateFormat:
        #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#
</ul>
</cfoutput>
</CFIF>

<CFFORM ACTION="createdatetime.cfm" METHOD="POST">
<p>Please enter the year, month, and day, in integer format, for a date to view:
<PRE>
Year	<CFINPUT TYPE="Text" NAME="year" VALUE="1998" VALIDATE="integer"
        REQUIRED="Yes">
Month	<CFINPUT TYPE="Text" NAME="month" VALUE="6" RANGE="1,12"
        MESSAGE="Please enter a month (1-12)" VALIDATE="integer"
        REQUIRED="Yes">
Day	<CFINPUT TYPE="Text" NAME="day" VALUE="8" RANGE="1,31"
        MESSAGE="Please enter a day of the month (1-31)" VALIDATE="integer"
        REQUIRED="Yes">
Hour	<CFINPUT TYPE="Text" NAME="hour" VALUE="16" RANGE="0,23"
        MESSAGE="You must enter an hour (0-23)" VALIDATE="integer"
        REQUIRED="Yes">
Minute	<CFINPUT TYPE="Text" NAME="minute" VALUE="12" RANGE="0,59"
        MESSAGE="You must enter a minute value (0-59)" VALIDATE="integer"
        REQUIRED="Yes">
Second	<CFINPUT TYPE="Text" NAME="second" VALUE="0" RANGE="0,59"
        MESSAGE="You must enter a value for seconds (0-59)" VALIDATE="integer"
        REQUIRED="Yes">
</PRE>
<p><INPUT TYPE="Submit" NAME=""> <INPUT TYPE="RESET">
</cfform>


CreateObject

Description

Creates a ColdFusion object, of a specified type.

Returns

An object, of the specified type.

Note: You can enable and disable this function in the ColdFusion Administrator, ColdFusion Basic Security, Tag Restrictions page.

Category

Extensibility functions

History

ColdFusion MX 7: For web service object: added the portName parameter, which specifies a port named in the service element of the WSDL.

ColdFusion MX:

  • Changed instantiation behavior: this function, and the cfobject tag, can instantiate ColdFusion components and web services. Executing operations on a CFC object executes CFML code that implements the CFC’s method in the CFC file.

    For more information, see ColdFusion MX Developer’s Guide.

  • For CORBA object: changed the Naming Service separator format for addresses from a dot to a forward slash. For example, if "context=NameService", for a class, use either of the following formats for the class parameter:
    • "Macromedia/Eng/CF"
    • "Macromedia.current/Eng.current/CF"

    (In earlier releases, the format was "Macromedia.Eng.CF".)

  • For CORBA object: changed the locale parameter; it specifies the Java config that contains the properties file.


CreateObject object types

For information about using this function, see these sections:

  • CreateObject: COM object
  • CreateObject: component object
  • CreateObject: CORBA object
  • CreateObject: Java or EJB object
  • CreateObject: web service object

Note: On UNIX, this function does not support COM objects.


CreateObject: COM object

Description

The CreateObject function can create a Component Object Model (COM) object.

To create a COM object, you must provide this information:

  • The object’s program ID or filename
  • The methods and properties available to the object through the IDispatch interface
  • The arguments and return types of the object's methods

For most objects, you can get this information from the OLEView utility.

Note: On UNIX, this function does not support COM objects.

Returns

A COM object.

Function syntax

CreateObject(type, class, context, serverName)

See also

ReleaseComObject, cfobject; Integrating COM and CORBA Objects in CFML Applications in ColdFusion MX Developer’s Guide.

Parameters

Parameter

Description

type

Type of object to create.

  • com
  • corba
  • java
  • component
  • webservice

class

Component ProgID for the object to invoke

context
  • InProc
  • Local
  • Remote

serverName

Server name, using UNC or DNS convention, in one of these forms:

  • \\lanserver
  • lanserver
  • http://www.servername.com
  • www.servername.com
  • 127.0.0.1

If context = "remote", this parameter is required.

Usage

The following example creates the Windows Collaborative Data Objects (CDO) for NTS NewMail object to send mail. You would use this code within a cfscript tag.

Mailer = CreateObject("COM", "CDONTS.NewMail");


CreateObject: component object

Description

The CreateObject function can create an instance of a ColdFusion component (CFC) object.

Returns

A component object.

Function syntax

CreateObject(type, component-name)

See also

Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

type

Type of object to create.

  • com
  • corba
  • java
  • component
  • webservice

component-name

The CFC name; corresponds to the name of the file that defines the component; for example, use engineComp to specify the component defined in the engineComp.cfc file

Usage

On UNIX systems, ColdFusion searches first for a file with a name that matches the specified component name, but is all lowercase. If it does not find the file, it looks for a file name that matches the component name exactly, with the identical character casing.

In the following example, the CFScript statements assign the tellTimeCFC variable to the tellTime component using the CreateObject function. The CreateObject function references the component in another directory. To invoke component methods, you use function syntax.

<b>Server's Local Time:</b>
<cfscript>
    tellTimeCFC=CreateObject("component","appResources.components.
        tellTime");
    tellTimeCFC.getLocalTime();
</cfscript>
<br>
<b>Calculated UTC Time:</b>
<cfscript>
    tellTimeCFC.getUTCTime();
</cfscript>


CreateObject: CORBA object

Description

The CreateObject function can call a method on a CORBA object. The object must be defined and registered for use.

Returns

A handle to a CORBA interface.

Function syntax

CreateObject(type, context, class, locale)

See also

Integrating COM and CORBA Objects in CFML Applications in ColdFusion MX Developer’s Guide

History

See the History section of the main CreateObject function page.

Parameters

Parameter

Description

type

Type of object to create.

  • com
  • corba
  • java
  • component
  • webservice

context
  • IOR: ColdFusion uses IOR to access CORBA server
  • NameService: ColdFusion uses naming service to access server. Valid only with the InitialContext of a VisiBroker ORB.

class
  • If context = "ior": absolute path of file that contains string version of the Interoperable Object Reference (IOR). ColdFusion must be able to read file; it should be local to ColdFusion server or accessible on network
  • If context = "nameservice": forward slash-delimited naming context for naming service. For example: Allaire//Doc/empobject

locale

The name of the Java config that holds the properties file. For more information, see Configuring and Administering ColdFusion MX.

Usage

In the class parameter, if "context=NameService", use a dot separator for the first part of the string. Use either of the following formats:

  • "Macromedia/Eng/CF"
  • "Macromedia.current/Eng.current/CF"

ColdFusion Enterprise supports CORBA through the Dynamic Invocation Interface (DII). To use this function with CORBA objects, you must provide the name of the file that contains a string version of the IOR, or the object’s naming context in the naming service. You must provide the object’s attributes, method names and method signatures.

This function supports user-defined types (structures, arrays, and sequences).

Example

myobj = CreateObject("corba", "d:\temp\tester.ior", "ior",
"visibroker") //    uses IOR

myobj = 	CreateObject("corba", "Macromedia/Eng/CF",
"nameservice", "visibroker")    // uses nameservice

myobj = 	CreateObject("corba", "d:\temp\tester.ior",
"nameservice")    // uses nameservice and default configuration


CreateObject: Java or EJB object

Description

The CreateObject function can create a Java object, and, by extension, an EJB object.

Returns

A Java object.

Function syntax

CreateObject(type, class)

Parameters

Parameter

Description

type

Type of object to create.

  • com
  • corba
  • java
  • component
  • webservice

class

A Java class name

Usage

Any Java class available in the class path that is specified in the ColdFusion Administrator can be loaded and used from ColdFusion with the CreateObject function.

To access Java methods and fields:

  1. Call the CreateObject function or the cfobject tag to load the class.
  2. Use the init method, with appropriate arguments, to call an instance of the class. For example:
    <cfset ret = myObj.init(arg1, arg2)>

Calling a public method on the object without first calling the "init" method invokes a static method. Arguments and return values can be any Java type (simple, array, object). If strings are passed as arguments, ColdFusion does the conversions; if strings are received as return values, ColdFusion does no conversion.

Overloaded methods are supported if the number of arguments is different. Future enhancements will let you use cast functions that allow method signatures to be built more accurately.


CreateObject: web service object

Description

This function can create a web service object.

Returns

A web service object.

Function syntax

CreateObject(type, urltowsdl [, portname ])

Parameters

Parameter

Description

type

Type of object to create.

  • com
  • corba
  • java
  • component
  • webservice

urltowsdl

WSDL file URL; location of web service

portname

The port name for the web service. This value is case-sensitive and corresponds to the port element’s name attribute under the service element.

Specify this parameter if the web service contains multiple ports. If no port name is specified, ColdFusion uses the first port found in the WSDL.

Usage

You can use the CreateObject function to create a web service.

Example

<cfscript>
  ws = CreateObject("webservice",
    "http://www.xmethods.net/sd/2001/TemperatureService.wsdl");
  xlatstring = ws.getTemp(zipcode = "55987");
  writeoutput("The temperature at 55987 is " & xlatstring);
</cfscript>


CreateODBCDate

Description

Creates an ODBC date object.

Returns

A date object, in normalized ODBC date format.

Category

Date and time functions

Function syntax

CreateODBCDate(date)

See also

CreateDate, CreateODBCDateTime

Parameters

Parameter | Description
date | Date or date/time object in the range 100 AD–9999 AD.

Usage

This function does not parse or validate values. To ensure that dates are entered and processed correctly (for example, to ensure that a day/month/year entry is not confused with a month/day/year entry, and so on), Macromedia recommends that you parse entered dates with the DateFormat function, using the mm-dd-yyyy mask, into three elements. Ensure that values are within appropriate ranges; for example, to validate a month value, use the attributes validate = "integer" and range = "1,12".

Example

<h3>CreateODBCDate Example</h3>
<CFIF IsDefined("form.year")>
<p>Your date value, generated with CreateDateTime:
<CFSET yourDate = CreateDateTime(form.year, form.month, form.day, form.hour,
form.minute, form.second)>
<cfoutput>
<ul>
    <li>Formatted with CreateDate: #CreateDate(form.year, form.month, form.day)#
    <li>Formatted with CreateDateTime:
        #CreateDateTime(form.year, form.month, form.day, form.hour, form.minute,
form.second)#
    <li>Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
    <li>Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#
</ul>
<p>The same value can be formatted with DateFormat:
<ul>
    <li>Formatted with CreateDate and DateFormat:
        #DateFormat(CreateDate(form.year,form.month, form.day), "mmm-dd-yyyy")#
    <li>Formatted with CreateDateTime and DateFormat:
        #DateFormat(CreateDateTime(form.year, form.month, form.day, form.hour,
form.minute, form.second))#
    <li>Formatted with CreateODBCDate and DateFormat:
        #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
    <li>Formatted with CreateODBCDateTime and DateFormat:
        #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#
</ul>
</cfoutput>
</CFIF>
<CFFORM ACTION="createodbcdate.cfm" METHOD="POST">
<p>Enter the year, month and day, as integers:
<PRE>
Year		<CFINPUT TYPE="Text" NAME="year" VALUE="1998" VALIDATE="integer"
        REQUIRED="Yes">
Month		<CFINPUT TYPE="Text" NAME="month" VALUE="6" RANGE="1,12"
        MESSAGE="Please enter a month (1-12)" VALIDATE="integer"
        REQUIRED="Yes">
Day	    	<CFINPUT TYPE="Text" NAME="day" VALUE="8" RANGE="1,31"
        MESSAGE="Please enter a day of the month (1-31)" VALIDATE="integer"
        REQUIRED="Yes">
Hour		<CFINPUT TYPE="Text" NAME="hour" VALUE="16" RANGE="0,23"
        MESSAGE="You must enter an hour (0-23)" VALIDATE="integer"
        REQUIRED="Yes">
Minute		<CFINPUT TYPE="Text" NAME="minute" VALUE="12" RANGE="0,59"
        MESSAGE="You must enter a minute value (0-59)" VALIDATE="integer"
        REQUIRED="Yes">
Second		<CFINPUT TYPE="Text" NAME="second" VALUE="0" RANGE="0,59"
        MESSAGE="You must enter a value for seconds (0-59)" VALIDATE="integer"
        REQUIRED="Yes">
</PRE>
<p><INPUT TYPE="Submit" NAME=""> <INPUT TYPE="RESET">
</cfform>


CreateODBCDateTime

Description

Creates an ODBC date-time object.

Returns

A date-time object, in ODBC timestamp format.

Category

Date and time functions

Function syntax

CreateODBCDateTime(date)

See also

CreateDateTime, CreateODBCDate, CreateODBCTime, Now; Evaluation and type conversion issues in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
date | Date-time object in the range 100 AD–9999 AD.

Usage

When passing a date-time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date-time object.

Example

<!--- This example shows how to use CreateDate, CreateDateTime, CreateODBCDate, and CreateODBCDateTime --->
<h3>CreateODBCDateTime Example</h3>

<CFIF IsDefined("form.year")>
Your date value, generated using CreateDateTime:
<CFSET yourDate = CreateDateTime (form.year, form.month, form.day,
form.hour,form.minute, form.second)>
<cfoutput>
<ul>
    <li>Formatted with CreateDate: #CreateDate(form.year, form.month,form.day)#
    <li>Formatted with CreateDateTime: #CreateDateTime(form.year,form.month,
        form.day,form.hour,form.minute,form.second)#
    <li>Formatted with CreateODBCDate: #CreateODBCDate(yourDate)#
    <li>Formatted with CreateODBCDateTime: #CreateODBCDateTime(yourDate)#
</ul>
<p>The same value can be formatted with DateFormat:
<ul>
    <li>Formatted with CreateDate and DateFormat:
        #DateFormat(CreateDate(form.year,form.month,form.day), "mmm-dd-yyyy")#
    <li>Formatted with CreateDateTime and DateFormat:
        #DateFormat(CreateDateTime(form.year,form.month,form.day,
        form.hour,form.minute,form.second))#
    <li>Formatted with CreateODBCDate and DateFormat:
        #DateFormat(CreateODBCDate(yourDate), "mmmm d, yyyy")#
    <li>Formatted with CreateODBCDateTime and DateFormat:
        #DateFormat(CreateODBCDateTime(yourDate), "d/m/yy")#
</ul>
</cfoutput>
</CFIF>
<CFFORM ACTION="createodbcdatetime.cfm" METHOD="POST">
<p>Enter a year, month and day, as integers:
<PRE>

Year		<CFINPUT
            TYPE="Text"  NAME="year" VALUE="1998" VALIDATE="integer" REQUIRED="Yes">

Month		<CFINPUT
            TYPE="Text" NAME="month"  VALUE="6"  RANGE="1,12"
            MESSAGE="Enter a month (1-12)" VALIDATE="integer" REQUIRED="Yes">

Day		<CFINPUT TYPE="Text" NAME="day" VALUE="8" RANGE="1,31"
            MESSAGE="Enter a day of the month (1-31)" VALIDATE="integer" REQUIRED="Yes">

Hour		<CFINPUT TYPE="Text" NAME="hour" VALUE="16" RANGE="0,23"
            MESSAGE="You must enter an hour (0-23)" VALIDATE="integer" REQUIRED="Yes">

Minute		<CFINPUT TYPE="Text" NAME="minute" VALUE="12" RANGE="0,59"
            MESSAGE="You must enter a minute value (0-59)" VALIDATE="integer" REQUIRED="Yes">

Second		<CFINPUT TYPE="Text" NAME="second" VALUE="0" RANGE="0,59"
            MESSAGE="You must enter a seconds value (0-59)" VALIDATE="integer" REQUIRED="Yes">
</PRE>
<p><INPUT TYPE="Submit" NAME=""> <INPUT TYPE="RESET">
</cfform>


CreateODBCTime

Description

Creates an ODBC time object.

Returns

A time object, in ODBC timestamp format.

Category

Date and time functions

Function syntax

CreateODBCTime(date)

See also

CreateODBCDateTime, CreateTime, Evaluation and type conversion issues in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
date | Date/time object in the range 100 AD–9999 AD.

Usage

When passing a date-time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date-time object.

Example

<h3>CreateODBCTime Example</h3>
<CFIF IsDefined("form.hour")>
Your time value, created with CreateTime...
<CFSET yourTime = CreateTime(form.hour, form.minute, form.second)>
<cfoutput>
<ul>
    <li>Formatted with CreateODBCTime: #CreateODBCTime(yourTime)#
    <li>Formatted with TimeFormat: #TimeFormat(yourTime)#
</ul></cfoutput>
</CFIF>
<CFFORM action="createodbctime.cfm" METHOD="post">
<PRE>
Hour		<CFINPUT TYPE="Text" NAME="hour" VALUE="16" RANGE="0,23" MESSAGE="You must
enter an hour (0-23)" VALIDATE="integer" REQUIRED="Yes">
Minute		<CFINPUT TYPE="Text" NAME="minute" VALUE="12" RANGE="0,59" MESSAGE="You must
enter a minute value (0-59)" VALIDATE="integer" REQUIRED="Yes">
Second		<CFINPUT TYPE="Text" NAME="second" VALUE="0" RANGE="0,59" MESSAGE="You must
enter a value for seconds (0-59)" VALIDATE="integer" REQUIRED="Yes">
</PRE>
<p><INPUT TYPE="Submit" NAME=""> <INPUT TYPE="RESET">
</cfform>


CreateTime

Description

Creates a time variable.

Returns

A time variable.

Category

Date and time functions

Function syntax

CreateTime(hour, minute, second)

See also

CreateODBCTime, CreateDateTime; Evaluation and type conversion issues in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
hour | Number in the range 0–23
minute | Number in the range 0–59
second | Number in the range 0–59

Usage

CreateTime is a subset of CreateDateTime.

A time variable is a special case of a date-time variable. The date part of a time variable is set to December 30, 1899.

Example

<h3>CreateTime Example</h3>
<cfif IsDefined("FORM.hour")>
Your time value, presented using CreateTime time function:
<cfset yourTime = CreateTime(FORM.hour, FORM.minute, FORM.second)>
<cfoutput><ul>
    <li>Formatted with timeFormat: #TimeFormat(yourTime)#
    <li>Formatted with timeFormat and hh:mm:ss: #TimeFormat(yourTime, 'hh:mm:ss')#
</ul></cfoutput>
</cfif>
<CFFORM action="createtime.cfm" METHOD="post">
<PRE>Hour			<CFINPUT TYPE="Text" NAME="hour" VALUE="16" RANGE="0,23"
    MESSAGE="You must enter an hour (0-23)" VALIDATE="integer" REQUIRED="Yes">
Minute			<CFINPUT TYPE="Text" NAME="minute" VALUE="12" RANGE="0,59"
    MESSAGE="You must enter a minute value (0-59)" VALIDATE="integer"
REQUIRED="Yes">
Second			<CFINPUT TYPE="Text" NAME="second" VALUE="0" RANGE="0,59"
    MESSAGE="You must enter a value for seconds (0-59)" VALIDATE="integer"
REQUIRED="Yes">
</PRE>
<p><INPUT TYPE="Submit" NAME=""> <INPUT TYPE="RESET">
</cfform>


CreateTimeSpan

Description

Creates a date/time object that defines a time period. You can add or subtract it from other date-time objects and use it with the cachedWithin attribute of cfquery.

Returns

A date-time object.

Category

Date and time functions

Function syntax

CreateTimeSpan(days, hours, minutes, seconds)

See also

CreateDateTime, DateAdd, DateConvert; Defining application-level settings and variables in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
days | Integer in the range 0–32768; number of days in time period
hours | Number of hours in time period
minutes | Number of minutes in time period
seconds | Number of seconds in time period

Usage

Creates a special date-time object that should be used only to add and subtract from other date-time objects or with the cfquery cachedWithin attribute.

If you use the cachedWithin attribute of cfquery, and the original query date falls within the time span you define, cached query data is used. In this case, the CreateTimeSpan function is used to define a period of time from the present backwards. The cachedWithin attribute takes effect only if you enable query caching in the ColdFusion Administrator. For more information, see cfquery.

Example

<!--- This example shows the use of CreateTimeSpan with cfquery --->
<h3>CreateTimeSpan Example</h3>
<!--- define startrow and maxrows to facilitate 'next N' style browsing --->
<CFPARAM name = "MaxRows" default = "10">
<CFPARAM name = "StartRow" default = "1">
<!--- Query database for information, if cached database information has not been updated in the last six hours. -------->
<cfoutput>
<cfquery name = "GetParks" datasource = "cfdocexamples"
    cachedWithin = "#CreateTimeSpan(0, 6, 0, 0)#">
SELECT   PARKNAME, REGION, STATE
FROM     Parks
ORDER by ParkName, State
</cfquery>
</cfoutput>
<!--- build HTML table to display query --->
<TABLE cellpadding = 1 cellspacing = 1>
<TR>
    <TD colspan = 2 bgcolor = f0f0f0>
    <B><I>Park Name</I></B>
    </TD>
    <TD bgcolor = f0f0f0>
    <B><i>Region</I></B>
    </TD>
    <TD bgcolor = f0f0f0>
    <B><I>State</I></B>
    </TD>
</TR>
<!--- Output query, define startrow and maxrows. Use query variable CurrentCount to track the row you are displaying. --->
<cfoutput query = "GetParks" StartRow = "#StartRow#"
MAXROWS = "#MaxRows#">
<TR>
    <TD valign = top bgcolor = ffffed>
    <B>#GetParks.CurrentRow#</B>
    </TD>
    <TD valign = top>
    <FONT SIZE = "-1">#ParkName#</FONT>
    </TD>
    <TD valign = top>
    <FONT SIZE = "-1">#Region#</FONT>
    </TD>
    <TD valign = top>
    <FONT SIZE = "-1">#State#</FONT>
    </TD>
</TR>
</cfoutput>
<!--- If number of records is less than or equal to number of rows, offer link to same page, with startrow value incremented by maxrows (in this example,
incremented by 10) --->
<TR>
    <TD colspan = 4>
    <cfif (StartRow + MaxRows) LTE GetParks.RecordCount>
        <a href = "cfquery.cfm?startrow = <cfoutput>#StartRow + MaxRows#
        </cfoutput>">See next <cfoutput>#MaxRows#</cfoutput> rows</A>
    </cfif>
    </TD>
</TR>
</TABLE>


CreateUUID

Description

Creates a Universally Unique Identifier (UUID). A UUID is a 35-character string representation of a unique 128-bit integer.

Returns

A ColdFusion format UUID, in the format xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx, where x is a hexadecimal digit (0-9 or A-F). (The character groups are 8-4-4-16.)

Category

Other functions

Function syntax

CreateUUID()

Usage

The ColdFusion UUID generation algorithm uses the unique time-of-day value, the IEEE 802 Host ID, and a cryptographically strong random number generator to generate UUIDs that conform to the principles laid out in the draft IEEE RFC "UUIDs and GUIDs."

The ColdFusion UUID format is as follows:

xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx (8-4-4-16).

This does not conform to the Microsoft/DCE standard, which is as follows:

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)

There are UUID test tools and a user-defined function called CreateGUID, which converts CFML UUIDs to UUID/Microsoft GUID format, available on the web at www.cflib.org.

Use this function to generate a persistent identifier in a distributed environment. To a very high degree of certainty, this function returns a unique value; no other invocation on the same or any other system returns the same value.

UUIDs are used by distributed computing frameworks, such as DCE/RPC, COM+, and CORBA. In ColdFusion, you can use UUIDs as primary table keys for applications in which data is stored in shared databases. In such cases, using numeric keys can cause primary-key constraint violations during table merges. Using UUIDs, you can eliminate these violations.

Example

<h3>CreateUUID Example</h3>
<p> This example uses CreateUUID to generate a UUID when you submit the form.
You can submit the form more than once. </p>
<!--- Checks whether the form was submitted; if so, creates UUID. --->
<cfif IsDefined("Form.CreateUUID") Is True>
    <hr>
    <p>Your new UUID is: <cfoutput>#CreateUUID()#</cfoutput></p>
</cfif>
<form action = "createuuid.cfm">
<p><input type = "Submit" name = "CreateUUID"> </p>
</form>


DateAdd

Description

Adds units of time to a date.

Returns

A date/time object.

Category

Date and time functions

Function syntax

DateAdd("datepart", number, "date")

See also

DateConvert, DatePart, CreateTimeSpan

History

ColdFusion MX 6.1: Added the datepart character L or l to represent milliseconds.

Parameters

Parameter

Description

datepart

String:

  • yyyy: Year
  • q: Quarter
  • m: Month
  • y: Day of year
  • d: Day
  • w: Weekday
  • ww: Week
  • h: Hour
  • n: Minute
  • s: Second
  • l: Millisecond

number

Number of units of datepart to add to date (positive, to get dates in the future; negative, to get dates in the past). Number must be an integer.

date

Date/time object, in the range 100 AD–9999 AD.

Usage

The datepart specifiers y, d, and w add a number of days to a date.

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Example

<!--- This example shows the use of DateAdd --->
<cfparam name="value" default="70">
<cfparam name="type" default="m">

<!--- if numbers passed, then use those --->
<cfif IsDefined("form.value")>
    <cfset value = form.value>
</cfif>
<cfif IsDefined("form.type")>
    <cfset type = form.type>
</cfif>

<cfquery name="GetMessages" datasource="cfdocexamples">
SELECT   UserName, Subject, Posted
FROM     Messages
</cfquery>

<p>This example uses DateAdd to determine when a message in
the database will expire. Currently, messages older
than <cfoutput>#value#</cfoutput>

<cfswitch expression="#type#">
    <cfcase value="yyyy">years</cfcase>
    <cfcase value="q">quarters</cfcase>
    <cfcase value="m">months</cfcase>
    <cfcase value="y">days of year</cfcase>
    <cfcase value="w">weekdays</cfcase>
    <cfcase value="ww">weeks</cfcase>
    <cfcase value="h">hours</cfcase>
    <cfcase value="n">minutes</cfcase>
    <cfcase value="s">seconds</cfcase>
    <cfdefaultcase>years</cfdefaultcase>
</cfswitch>
 are expired.

<table>
<tr>
    <td>UserName</td>
    <td>Subject</td>
    <td>Posted</td>
</tr>
<cfoutput query="GetMessages">
<tr>
    <td>#UserName#</td>
    <td>#Subject#</td>
    <td>#Posted# <cfif DateAdd(type, value, posted) LT Now()><font color="red">EXPIRED</font></cfif></td>
</tr>
</cfoutput>
</table>

<cfform action="#CGI.Script_Name#" method="post">

Select an expiration value:
<cfinput type="Text" name="value" value="#value#" message="Please enter whole numbers only" validate="integer" required="Yes">
<select name="type">
    <option value="yyyy">years
    <option value="m" selected>months
    <option value="d">days
    <option value="ww">weeks
    <option value="h">hours
    <option value="n">minutes
    <option value="s">seconds
</select>

<input type="Submit" value="Submit">
</cfform>


DateCompare

Description

Performs a full date/time comparison of two dates.

Returns

  • -1, if date1 is earlier than date2
  • 0, if date1 is equal to date2
  • 1, if date1 is later than date2

Category

Date and time functions

Function syntax

DateCompare("date1", "date2" [, "datePart"])

See also

CreateDateTime, DatePart

Parameters

Parameter

Description

date1

Date/time object, in the range 100 AD–9999 AD.

date2

Date/time object, in the range 100 AD–9999 AD.

datePart

Optional. String. Precision of the comparison.

  • s Precise to the second (default)
  • n Precise to the minute
  • h Precise to the hour
  • d Precise to the day
  • m Precise to the month
  • yyyy Precise to the year

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Example

<h3>DateCompare Example</h3>
<p>The DateCompare function compares two date/time values.
<cfif IsDefined("FORM.date1")>
    <cfif IsDate(FORM.date1) and IsDate(FORM.date2)>
        <cfset comparison = DateCompare(FORM.date1, FORM.date2, FORM.precision)>

<!--- switch on the variable to give various responses --->
        <cfswitch expression = #comparison#>
            <cfcase value = "-1">
                <h3><cfoutput>#DateFormat(FORM.date1)#
                #TimeFormat(FORM.date1)#</cfoutput> (Date 1) is
                earlier than <cfoutput>#DateFormat(FORM.date2)#
                #TimeFormat(FORM.date2)#</cfoutput> (Date 2)</h3>
                <I>The dates are not equal</I>
            </cfcase>
            <cfcase value = "0">
                <h3><cfoutput>#DateFormat(FORM.date1)#
                #TimeFormat(FORM.date1)#</cfoutput> (Date 1) is equal
                to <cfoutput>#DateFormat(FORM.date2)#
                #TimeFormat(FORM.date2)#</cfoutput> (Date 2)</h3>
                <I>The dates are equal!</I>
            </cfcase>
            <cfcase value = "1">
                <h3><cfoutput>#DateFormat(FORM.date1)#
                #TimeFormat(FORM.date1)#</cfoutput> (Date 1) is later
                than <cfoutput>#DateFormat(FORM.date2)#
                #TimeFormat(FORM.date2)#</cfoutput> (Date 2)</h3>
                <I>The dates are not equal</I>
            </cfcase>
            <CFDEFAULTCASE>
                <h3>This is the default case</h3>
            </CFDEFAULTCASE>
        </cfswitch>
    <cfelse>
        <h3>Enter two valid date values</h3>
    </cfif>
</cfif>

<form action = "datecompare.cfm" method="post">
<hr size = "2" color = "#0000A0">
<p>Date 1
<br><input type = "Text" name = "date1"
        value = "<cfoutput>#DateFormat(Now())# #TimeFormat(Now())#
</cfoutput>">
<p>Date 2
<br><input type = "Text" name = "date2"
        value = "<cfoutput>#DateFormat(Now())# #TimeFormat(Now())#
</cfoutput>">
<p>Specify precision to the:
<br><select name = "precision">
            <option value = "s">
                Second
            </option>
            <option value = "n">
                Minute
            </option>
            <option value = "h">
                Hour
            </option>
            <option value = "d">
                Day
            </option>
            <option value = "m">
                Month
            </option>
            <option value = "yyyy">
                Year
            </option>
    </select>
<p><input type = "Submit" value = "Compare these dates" name = "">
<input type = "reset">
</form>


DateConvert

Description

Converts local time to Coordinated Universal Time (UTC), or UTC to local time. The function uses the daylight savings settings in the executing computer to compute daylight savings time, if required.

Returns

UTC- or local-formatted time object.

Category

Date and time functions

Function syntax

DateConvert("conversion-type", "date")

See also

GetTimeZoneInfo, CreateDateTime, DatePart

Parameters

Parameter

Description

conversion-type
  • local2Utc: Converts local time to UTC time.
  • utc2Local: Converts UTC time to local time.

date

Date and time string or a variable that contains one.

To create, use CreateDateTime.

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the CreateDate or Now function as the date parameter of this function; for example: #DateConvert(CreateDate(2001, 3, 3))#

Example

<h3>DateConvert Example</h3>
<!--- This shows conversion of current date - time to UTC and back. --->
<cfset curDate = Now()>
<p><cfoutput>The current date and time: #curDate#. </cfoutput></p>
<cfset utcDate = DateConvert("local2utc", curDate)>
<cfoutput>
    <p>The current date and time converted to UTC time: #utcDate#.</p>
</cfoutput>
<!--- This code checks whether form was submitted. If so, the code generates
the CFML date with the CreateDateTime function. --->
<cfif IsDefined("FORM.submit")>
    <cfset yourDate = CreateDateTime(FORM.year, FORM.month, FORM.day,
FORM.hour,FORM.minute, FORM.second)>
    <p><cfoutput>Your date value, presented as a ColdFusion date/time
string:#yourdate#.</cfoutput></p>
  <cfset yourUTC = DateConvert("local2utc", yourDate)>
    <p><cfoutput>Your date and time value, converted to Coordinated Universal Time
(UTC): #yourUTC#.</cfoutput></p>
    <p><cfoutput>Your UTC date and time, converted back to local date and time:
#DateConvert("utc2local", yourUTC)#.
</cfoutput></p>
<cfelse>
    Type the date and time, and press Enter to see the conversion.
</cfif>
<Hr size = "2" color = "#0000A0">
<form action = "dateconvert.cfm">
<p>Enter year, month and day in integer format for date value to view:
<table cellspacing = "2" cellpadding = "2" border = "0">
<tr>
  <td>Year</td>
  <td><input type = "Text" name = "year" value = "1998"
validate = "integer" required = "Yes"></td></tr>
<tr>
  <td>Month</td>
  <td><input type = "Text" name = "month" value = "6"
range = "1,12" message = "Enter a month (1-12)"
validate = "integer" required = "Yes"></td></tr>
<tr>
  <td>Day</td>
  <td><input type = "Text" name = "day" value = "8"
range = "1,31"
message = "Enter a day of the month (1-31)"
validate = "integer" required = "Yes"></td></tr>
<tr>
  <td>Hour</td>
  <td><input type = "Text" name = "hour" value = "16"
range = "0,23"
message = "You must enter an hour (0-23)"
validate = "integer" required = "Yes"></td></tr>
<tr>
  <td>Minute</td>
  <td><input type = "Text" name = "minute" value = "12"
range = "0,59"
message = "You must enter a minute value (0-59)"
validate = "integer" required = "Yes"></td></tr>
<tr>
  <td>Second</td>
  <td><input type = "Text" name = "second" value = "0"
range = "0,59"
message = "You must enter a value for seconds (0-59)"
validate = "integer" required = "Yes"></td></tr>
<tr>
  <td><input type = "Submit" name = "submit" value = "Submit"></td>
  <td><input type = "RESET"></td></tr>
</table>


DateDiff

Description

Determines the integer number of units by which date1 is less than date2.

Returns

A number of units, of type datepart.

Category

Date and time functions

Function syntax

DateDiff("datepart", "date1", "date2")

See also

DateAdd, DatePart, CreateTimeSpan

History

ColdFusion MX:

  • Changed how negative date differences are calculated: this function calculates negative date differences correctly; its output may be different from that in earlier releases.
  • Changed the w and ww masks; they determine the number of full weeks between the two dates.

Parameters

Parameter

Description

datepart

String specifying the units in which to count; for example yyyy requests a date difference in whole years.

  • yyyy: Years
  • q: Quarters
  • m: Months
  • y: Days of year (same as d)
  • d: Days
  • w: Weekdays (same as ww)
  • ww: Weeks
  • h: Hours
  • n: Minutes
  • s: Seconds

date1

Date/time object, in the range 100 AD–9999 AD.

date2

Date/time object, in the range 100 AD–9999 AD.

Usage

The DateDiff function determines the number of complete datepart units between the two dates; for example, if the datepart parameter is "m" and the dates differ by 55 days, the function returns 1.

Enclose string constant dates in quotation marks. If the text contains only numbers (such 1932), and is not surrounded by quotation marks, ColdFusion interprets it as a date/time object, resulting in an incorrect value.

Example

<cfif IsDefined("form.value")>
    <cfset value = form.value>
</cfif>
<cfif IsDefined("form.type")>
    <cfset type = form.type>
</cfif>

<cfif IsDefined("form.date1") and IsDefined("form.date2")>

    <cfif IsDate(form.date1) and IsDate(form.date2)>

        <p>This example uses DateDiff to determine the difference
        in
        <cfswitch expression = "#form.type#">
            <cfcase value="yyyy">years</cfcase>
            <cfcase value="q">quarters</cfcase>
            <cfcase value="m">months</cfcase>
            <cfcase value="y">days</cfcase>
            <cfcase value="d">days</cfcase>
            <cfcase value="w">weekdays</cfcase>
            <cfcase value="ww">weeks</cfcase>
            <cfcase value="h">hours</cfcase>
            <cfcase value="n">minutes</cfcase>
            <cfcase value="s">seconds</cfcase>
            <cfdefaultcase>years</cfdefaultcase>
        </cfswitch>
             dateparts between date1 and date2.

        <cfif DateCompare("#form.date1#","#form.date2#") is not 0>
        <p>The difference is <cfoutput>#Abs(DateDiff(type, form.date2, form.date1))#</cfoutput>
        <cfswitch expression = "#form.type#">
            <cfcase value="yyyy">years</cfcase>
            <cfcase value="q">quarters</cfcase>
            <cfcase value="m">months</cfcase>
            <cfcase value="y">days</cfcase>
            <cfcase value="d">days</cfcase>
            <cfcase value="w">weekdays</cfcase>
            <cfcase value="ww">weeks</cfcase>
            <cfcase value="h">hours</cfcase>
            <cfcase value="n">minutes</cfcase>
            <cfcase value="s">seconds</cfcase>
            <cfdefaultcase>years</cfdefaultcase>
        </cfswitch>.
        <cfelse>
        <p>The two dates are equal!  Try changing one of the values ...
        </cfif>

    <cfelse>
    <p>Please enter two valid date/time values, formatted like this:
    <cfoutput>#DateFormat(Now())#</cfoutput>
    </cfif>

</cfif>
<form action="index.cfm" method="post">

<pre>
Date 1
<input type="Text" name="date1" value="<CFOUTPUT>#DateFormat(Now())#</CFOUTPUT>">
Date 2
<input type="Text" name="date2" value="<CFOUTPUT>#DateFormat(Now())#</CFOUTPUT>">
What kind of unit to show difference?
    <select name="type">
        <option value="yyyy" selected>years
        <option value="q">quarters
        <option value="m">months
        <option value="y">days of year
        <option value="d">days
        <option value="w">weekdays
        <option value="ww">weeks
        <option value="h">hours
        <option value="n">minutes
        <option value="s">seconds
    </select>
</pre>

<input type="Submit" name=""><input type="RESET">
</form>

.


DateFormat

Description

Formats a date value using U.S. date formats. For international date support, use LSDateFormat.

Returns

A text string representing the date formatted according to the mask. If no mask is specified, returns the value in dd-mmm-yy format.

Category

Date and time functions

Function syntax

DateFormat("date" [, "mask" ])

See also

Now, CreateDate, LSDateFormat, LSParseDateTime, LSTimeFormat, TimeFormat, ParseDateTime

History

ColdFusion MX: Added support for the following mask parameter options: short, medium, long, and full.

Parameters

Parameter

Description

date

Date/time object, in the range 100 AD–9999 AD.

mask

Characters that show how ColdFusion displays a date:

  • d: Day of the month as digits; no leading zero for single-digit days.
  • dd: Day of the month as digits; leading zero for single-digit days.
  • ddd: Day of the week as a three-letter abbreviation.
  • dddd: Day of the week as its full name.
  • m: Month as digits; no leading zero for single-digit months.
  • mm: Month as digits; leading zero for single-digit months.
  • mmm: Month as a three-letter abbreviation.
  • mmmm: Month as its full name.
  • yy: Year as last two digits; leading zero for years less than 10.
  • yyyy: Year represented by four digits.
  • gg: Period/era string. Ignored. Reserved.
    The following masks tell how to format the full date and cannot be combined with other masks:
  • short: equivalent to m/d/y
  • medium: equivalent to mmm d, yyyy
  • long: equivalent to mmmm d, yyyy
  • full: equivalent to dddd, mmmm d, yyyy

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example: #DateFormat(CreateDate(2001, 3, 3))#

Date and time values in database query results can vary in sequence and formatting unless you use functions to format them. To ensure that application users correctly understand displayed dates and times, Macromedia recommends that you use this function and the LSDateFormat, TimeFormat, and LSTimeFormat functions to format resultset values. For more information and examples, see TechNote 22183, "ColdFusion Server (5 and 4.5.x) with Oracle: Formatting Date and Time Query Results," on the Macromedia website at www.coldfusion.com/Support/KnowledgeBase/SearchForm.cfm.

Note: The DateFormat function is best used for formatting output, not for formatting input. For formatting input, use one of the date/time creation functions (for example, CreateDate) instead.

Example

<cfset todayDate = Now()>
<body>
<h3>DateFormat Example</h3>
<p>Today’s date is <cfoutput>#todayDate#</cfoutput>.
<p>Using DateFormat, we can display that date in different ways:
<cfoutput>
<ul>
    <li>#DateFormat(todayDate)#
    <li>#DateFormat(todayDate, "mmm-dd-yyyy")#
    <li>#DateFormat(todayDate, "mmmm d, yyyy")#
    <li>#DateFormat(todayDate, "mm/dd/yyyy")#
    <li>#DateFormat(todayDate, "d-mmm-yyyy")#
    <li>#DateFormat(todayDate, "ddd, mmmm dd, yyyy")#
    <li>#DateFormat(todayDate, "short")#
    <li>#DateFormat(todayDate, "medium")#
    <li>#DateFormat(todayDate, "long")#
    <li>#DateFormat(todayDate, "full")#
</ul>
</cfoutput>


DatePart

Description

Extracts a part from a date value.

Returns

Part of a date, as an integer.

Category

Date and time functions

Function syntax

DatePart("datepart", "date")

See also

DateAdd, DateConvert

History

ColdFusion MX 6.1: Added the datepart character L or l to represent milliseconds.

Parameters

Parameter

Description

datepart

String:

  • yyyy: Year
  • q: Quarter
  • m: Month
  • y: Day of year
  • d: Day
  • w: Weekday
  • ww: Week
  • h: Hour
  • n: Minute
  • s: Second
  • l: Millisecond

date

Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Example

<!--- This example shows information available from DatePart --->
<cfset todayDate = Now()>
<h3>DatePart Example</h3>
<p>Today’s date is <cfoutput>#todayDate#</cfoutput>.
<p>Using datepart, we extract an integer representing the dateparts from that value
<cfoutput>
<ul>
    <li>year: #DatePart("yyyy", todayDate)#
    <li>quarter: #DatePart("q", todayDate)#
    <li>month: #DatePart("m", todayDate)#
    <li>day of year: #DatePart("y", todayDate)#
    <li>day: #DatePart("d", todayDate)#
    <li>weekday: #DatePart("w", todayDate)#
    <li>week: #DatePart("ww", todayDate)#
    <li>hour: #DatePart("h", todayDate)#
    <li>minute: #DatePart("n", todayDate)#
    <li>second: #DatePart("s", todayDate)#
</ul>
</cfoutput>


Day

Description

Determines the day of the month, in a date.

Returns

The ordinal for the day of the month, ranging from 1 to 31.

Category

Date and time functions

Function syntax

Day("date")

See also

DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example: #Day(CreateDate(2001, 3, 3))#

Example

<h3>Day Example</h3>
<cfif IsDefined("FORM.year")>
    <p>More information about your date:
    <cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
    <cfoutput>
        <p>Date: #DateFormat(yourDate)#. <br>
It is #DayofWeekAsString(DayOfWeek(yourDate))#,
day #DayOfWeek(yourDate)# in the week.
        <br>This is day #Day(YourDate)#
in the month of #MonthAsString(Month(yourDate))#,
which has #DaysInMonth(yourDate)# days.
        <br>We are in week #Week(yourDate)# of #Year(YourDate)#
         (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
        <br><cfif IsLeapYear(Year(yourDate))>This is a leap year
                <cfelse>This is not a leap year</cfif>
    </cfoutput>
</cfif>


DayOfWeek

Description

Determines the day of the week, in a date.

Returns

The ordinal for the day of the week, as an integer in the range 1 (Sunday) to 7 (Saturday).

Category

Date and time functions

Function syntax

DayOfWeek("date")

See also

Day, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example, #DayOfWeek(CreateDate(2001, 3, 3))#

Example

<h3>DayOfWeek Example</h3>
<cfif IsDefined("FORM.year")>
    More information about your date:
    <cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
    <cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayofWeekAsString(DayOfWeek(yourDate))#, day
     #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(YourDate)# in the month of
     #MonthAsString(Month(yourDate))#, which has
     #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(YourDate)# (day
     #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
    <br><cfif IsLeapYear(Year(yourDate))>This is a leap year
        <cfelse>This is not a leap year</cfif>
    </cfoutput>
</cfif>


DayOfWeekAsString

Description

Determines the day of the week, in a date, as a string function.

Returns

The day of the week, as a string in the current locale, that corresponds to day_of_week.

Category

Date and time functions, String functions

Function syntax

DayOfWeekAsString(day_of_week)

See also

Day, DayOfWeek, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth

History

ColdFusion MX 7: Changed behavior. The returned string is now in the language of the current locale.

Parameters

Parameter | Description
day_of_week | Integer, in the range 1 (Sunday) - 7 (Saturday).

Example

The following example shows the use of the DayOfWeekAsString function. It is the action page for a form that submits year, month, and day fields.

<h3>DayOfWeekAsString Example</h3>
<cfif IsDefined("FORM.year")>
More information about your date:
<cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>

<cfoutput>
<p>Your date, #DateFormat(yourDate)#.
<br>It is #DayofWeekAsString(DayOfWeek(yourDate))#, day
     #DayOfWeek(yourDate)# in the week.
<br>This is day #Day(YourDate)# in the month of
#MonthAsString(Month(yourDate))#, which has
      #DaysInMonth(yourDate)# days.
<br>We are in week #Week(yourDate)# of #Year(YourDate)# (day #DayofYear(yourDate)#
of #DaysinYear(yourDate)#).
<br><cfif IsLeapYear(Year(yourDate))>This is a leap year
    <cfelse>This is not a leap year</cfif>
</cfoutput>
</cfif>


DayOfYear

Description

Determines the day of the year, in a date.

Returns

The ordinal value of day of the year, as an integer.

Category

Date and time functions

Function syntax

DayOfYear("date")

See also

Day, DayOfWeek, DayOfWeekAsString, DaysInMonth, DaysInYear, FirstDayOfMonth

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

This function accounts for leap years.

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the CreateDate function or Now function as the date parameter of this function; for example, #DayOfYear(CreateDate(2001, 3, 3))#

Example

<h3>Day7OfYear Example</h3>
<cfif IsDefined("FORM.year")>
    More information about your date:
    <cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
    <cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayofWeekAsString(DayOfWeek(yourDate))#,
     day #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(yourDate)# in the month of
     #MonthAsString(Month(yourDate))#, which has
     #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(yourDate)#
(day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
    <br><cfif IsLeapYear(Year(yourDate))>This is a leap year
        <cfelse>This is not a leap year</cfif>
    </cfoutput>
</cfif>


DaysInMonth

Description

Determines the number of days in a month.

Returns

The number of days in the month in Date.

Category

Date and time functions

Function syntax

DaysInMonth("date")

See also

Day, DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInYear, FirstDayOfMonth

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the Now function or the CreateDate function as the date parameter of this function; for example: #DaysInMonth(CreateDate(2001, 3, 3))#

Example

<h3>DaysInMonth Example</h3>
<cfif IsDefined("FORM.year")>
    More information about your date:
    <cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
    <cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayofWeekAsString(DayOfWeek(yourDate))#, day
     #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(YourDate)# in the month of
     #MonthAsString(Month(yourDate))#, which has
     #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(YourDate)#
     (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
    <br><cfif IsLeapYear(Year(yourDate))>This is a leap year
        <cfelse>This is not a leap year</cfif>
    </cfoutput>
</cfif>


DaysInYear

Description

Determines the number of days in a year.

Returns

The number of days in a year.

Category

Date and time functions

Function syntax

DaysInYear("date")

See also

Day, DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear, FirstDayOfMonth, IsLeapYear

Parameters

Parameter

Description

date
  • Date/time object, in the range 100 AD–9999 AD.

Usage

DaysInYear accounts for leap years.

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a numeric representation of a date/time object.

Note: You can pass the CreateDate function or the Now function as the date parameter of this function; for example: #DaysInYear(CreateDate(2001, 3, 3))#

Example

<h3>DaysInYear Example</h3>
<cfif IsDefined("FORM.year")>
    More information about your date:
    <cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
    <cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayofWeekAsString(DayOfWeek(yourDate))#, day
     #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(YourDate)# in the month of
     #MonthAsString(Month(yourDate))#, which has
     #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(yourDate)# (day
     #DayofYear(yourDate)# of #DaysinYear(yourDate)#).
</cfif>


DE

Description

Escapes any double-quotation marks in the parameter and wraps the result in double-quotation marks.

Returns

Parameter, surrounded by double-quotation marks, with any inner double-quotation marks escaped.

Category

Dynamic evaluation functions

Function syntax

DE(string)

See also

Evaluate, IIf, Using Expressions and Number Signs in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
string | String to evaluate, after delay

Usage

The DE function postpones evaluation of a string that is passed as a parameter to the IIf or Evaluate functions.

This function is especially useful with the IIf function, which automatically evaluates its second and third parameters as expressions. You can use the DE function to prevent the function from evaluating a string parameter that is to be output as a variable, and should not be treated as an expression. The following example show this use; it uses IIF to alternate table-row background colors, white and gray, and uses the DE function to prevent ColdFusion from evaluating the color strings.

<cfoutput>
<table border="1" cellpadding="3">
<cfloop index="i" from="1" to="10">
    <tr bgcolor="#IIF( i mod 2 eq 0, DE("white"), DE("gray") )#">
        <td>
            hello #i#
        </td>
    </tr>
</cfloop>
</table>
</cfoutput>

The DE function does not delay evaluation of variable names that are surrounded by number signs (#). ColdFusion function evaluates the variable regardless of whether the DE function is present.

The following example shows how you can use the DE function and number signs together, and shows how the function works with an IIF function:

<cfoutput>
<cfset var1=Blue>
<cfset var2=Green>
<cfset myresult=IIf( 1 eq 2, DE(#Var1#), DE(#Var2#))>
The expression is #myresult#
</cfoutput>

ColdFusion processes this code as follows:

  1. ColdFusion sets the variables var1 and var2 to be the strings Blue and Green.
  2. In the fourth line, ColdFusion evaluates the variables surrounded by number signs first, replacing them with the strings Blue and Green, the values of the variables.
  3. The IIF function evaluates the test expression, determines that it is False, and then evaluates the third parameter.
  4. The third parameter is a DE function, which takes the string Green and surrounds it in quotation marks
  5. The IIF function returns the string "Green", including the quotation marks.
  6. The cfset tag gets the expression result="Green", and sets the value of the myresult variable to the string Green.
  7. ColdFusion evaluates #myresult# in the output text, replaces the variable with its value, the string Green, and displays the result.

Example

<!--- This example shows the use of DE and Evaluate --->
<h3>DE Example</h3>
<cfif IsDefined("FORM.myExpression")>
    <cftry>
        <!--- Show the expression and the results of evaluating it --->
        <cfoutput>
            <h3>Evaluate the Expression #FORM.MyExpression#</h3>
        </cfoutput>
        The code:<br>
        #Evaluate(FORM.myExpression)#
        <br><br>
        The result:<br>
        <cfoutput>
            #Evaluate(FORM.myExpression)#
        </cfoutput>

        <h3>Use DE to prevent the Evaluate function from evaluating</h3>
        The code:<br>
        #Evaluate(DE(FORM.MyExpression))#<br><br>
        The result:<br>
        <cfoutput>
            #Evaluate(DE(FORM.MyExpression))#
        </cfoutput>
        <!--- Error handling code for bad expressions and any other error.--->
        <cfcatch type = "Any">
        <!--- the message to display --->
            <h3>Sorry, there’s been an <B>Error</B>.
            Try a simple expression, such as "2+2".</h3>
            <cfoutput>
            <!--- Display the diagnostic message from ColdFusion. --->
                <p>#cfcatch.message#
            </cfoutput>
        </cfcatch>
    </cftry>
</cfif>

<h3>Enter any valid ColdFusion expression</h3>
<cfform>
    <cfinput name="myExpression" type="Text" size="40">
    <cfinput type="submit" name="submitit">
</cfform>


DecimalFormat

Description

Converts a number to a decimal-formatted string.

Returns

A number as a string formatted with two decimal places and a thousands separator.

Category

Display and formatting functions

Function syntax

DecimalFormat(number)

See also

DollarFormat, NumberFormat

Parameters

Parameter | Description
number | Number to format

Example

<h3>DecimalFormat Function</h3>
<p>Returns a number to two decimal places.
<p>
<cfloop FROM = 1 TO = 20 INDEX = "counter">
    <cfoutput>
    #counter# * Square Root of 2:
        #DecimalFormat(counter * sqr(2))#
    </cfoutput>
    <br>
</cfloop>


DecrementValue

Description

Decrements the integer part of a number.

Returns

Integer part of number, decremented by one.

Category

Mathematical functions

Function syntax

DecrementValue(number)

See also

IncrementValue

Parameters

Parameter | Description
number | Number to decrement

Example

<h3>DecrementValue Example</h3>
<p>Returns the integer part of a number decremented by one.
<p>DecrementValue(0):
    <cfoutput>#DecrementValue(0)#</cfoutput>
<p>DecrementValue("1"):
    <cfoutput>#DecrementValue("1")#</cfoutput>
<p>DecrementValue(123.35):
    <cfoutput>#DecrementValue(123.35)#</cfoutput>


Decrypt

Description

Decrypts a string that is encrypted using a standard encryption technique, including strings encrypted by the Encrypt function.

Returns

An unencrypted string.

Category

Security functions, String functions

Function syntax

Decrypt(encrypted_string, key[, algorithm[, encoding]])

See also

Duplicate, Encrypt

ColdFusion MX 7: Added the algorithm and encoding parameters.

Parameters

Parameter

Description

encrypted_string

String to decrypt.

key

String. For the CFMX_COMPAT algorithm, the seed that was used to encrypt the string; for all other algorithms, the key that was used to encrypt the string.

algorithm

(Optional) The algorithm to use to decrypt the string. Must be the same as the algorithm used to encrypt the string. ColdFusion MX installs a cryptography library with the following algorithms:

  • CFMX_COMPAT: the algorithm used in ColdFusion MX and prior releases. This algorithm is the least secure option (default).
  • AES: the Advanced Encryption Standard specified by the National Institute of Standards and Technology (NIST) FIPS-197.
  • BLOWFISH: the Blowfish algorithm defined by Bruce Schneier.
  • DES: the Data Encryption Standard algorithm defined by NIST FIPS-46-3.
  • DESEDE: the "Triple DES" algorithm defined by NIST FIPS-46-3.

If you install a security provider with additional cryptography algorithms, you can also specify any of its string encryption and decryption algorithms.

encoding

(Optional; if you specify this parameter, you must also specify the algorithm parameter.) The binary encoding used to represent the data as a string. Must be the same as the algorithm used to encrypt the string.

  • Base64: the Base64 algorithm, as specified by IETF RFC 2045.
  • Hex: the characters A-F and 0-9 represent the hexadecimal byte values.
  • UU: the UNIX standard UUEncode algorithm (default) .

Usage

This function uses a symmetric key-based algorithm, in which the same key is used to encrypt and decrypt a string. The parameter values must match the values used to encode string. The security of the encrypted string depends on maintaining the secrecy of the key.

ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

Example

<h3>Decrypt Example</h3>

<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.myString")>
    <cfscript>
        /* GenerateSecretKey does not generate key for the CFMX_COMPAT algorithm,
          so use the key from the form.
        */
        if (Form.myAlgorithm EQ "CFMX_COMPAT")
            theKey=Form.MyKey;
        // For all other encryption techniques, generate a secret key.
        else
            theKey=generateSecretKey(Form.myAlgorithm);
        //Encrypt the string
        encrypted=encrypt(Form.myString, theKey, Form.myAlgorithm,
            Form.myEncoding);
        //Decrypt it
        decrypted=decrypt(encrypted, theKey, Form.myAlgorithm, Form.myEncoding);
    </cfscript>

    <!--- Display the values used for encryption and decryption,
            and the results. --->
    <cfoutput>
        <b>The algorithm:</b> #Form.myAlgorithm#<br>
        <b>The key:</B> #theKey#<br>
        <br>
        <b>The string:</b> #Form.myString# <br>
        <br>
        <b>Encrypted:</b> #encrypted#<br>
        <br>
        <b>Decrypted:</b> #decrypted#<br>
    </cfoutput>
</cfif>

<!--- The input form.  --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select the encoding</b><br>
    <select size="1" name="myEncoding" >
        <option selected>UU</option>
        <option>Base64</option>
        <option>Hex</option>
    </select><br>
    <br>
    <b>Select the algorithm</b><br>
    <select size="1" name="myAlgorithm" >
        <option selected>CFMX_COMPAT</option>
        <option>AES</option>
        <option>DES</option>
        <option>DESEDE</option>
    </select><br>
    <br>
    <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br>
    <input type = "Text" name = "myKey" value = "MyKey"><br>
    <br>
    <b>Enter string to encrypt</b><br>
    <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">This string will be encrypted (you can replace it with more typing).
    </textArea><br>
    <input type = "Submit" value = "Encrypt my String">
</form>


DeleteClientVariable

Description

Deletes a client variable. (To test for the existence of a variable, use IsDefined.)

Returns

True, if the variable is successfully deleted; false, otherwise.

Category

Other functions

Function syntax

DeleteClientVariable("name")

See also

GetClientVariablesList

History

ColdFusion MX: Changed behavior: if the variable is not present, this function now returns False. (In earlier releases, it threw an error.)

Parameters

Parameter | Description
name | Name of a client variable to delete, surrounded by double-quotation marks

Example

<!--- This view-only example shows DeleteClientVariable --->
<h3>DeleteClientVariable Example</h3>

<p>This view-only example deletes a client variable called "User_ID", if it
    exists in the list of client variables returned by GetClientVariablesList.
<p>This example requires the existence of an Application.cfm file and client
    management to be in effect.
<!---
<cfset client.somevar = "">
<cfset client.user_id = "">
<p>Client variable list:<cfoutput>#GetClientVariablesList()#</cfoutput>
<cfif ListFindNoCase(GetClientVariablesList(), "User_ID") is not 0>

        <cfset temp = DeleteClientVariable("User_ID")>
        <p>Was variable "User_ID" Deleted? <cfoutput>#temp#</cfoutput>
</cfif>
<p>Amended Client variable list:<cfoutput>#GetClientVariablesList()#
</cfoutput>
--->


DirectoryExists

Description

Determines whether a directory exists.

Returns

Yes, if the specified directory exists; No, otherwise.

Category

System functions

Function syntax

DirectoryExists(absolute_path)

See also

FileExists

Parameters

Parameter | Description
absolute_path | An absolute path

Example

<h3>DirectoryExists Example</h3>
<h3>Enter a directory to check for existence.</h2>
<form action = "directoryexists.cfm" method="post">
    <input type = "text" name = "yourDirectory">
    <br>
    <input type = "submit" name = "submit">
</form>

<cfif IsDefined("FORM.yourDirectory")>
    <cfif FORM.yourDirectory is not "">
    <cfset yourDirectory = FORM.yourDirectory>
        <cfif DirectoryExists(yourDirectory)>
            <cfoutput>
            <p>Your directory exists. Directory name: #yourDirectory#
            </cfoutput>
        <cfelse>
            <p>Your directory does not exist.</p>
        </cfif>
    </cfif>
</cfif>


DollarFormat

Description

Formats a string in U.S. format. (For other currencies, use LSCurrencyFormat or LSEuroCurrencyFormat .)

Returns

A number as a string, formatted with two decimal places, thousands separator, and dollar sign. If number is negative, the return value is enclosed in parentheses. If number is an empty string, returns zero.

Category

Display and formatting functions

Function syntax

DollarFormat(number)

See also

DecimalFormat, NumberFormat

Parameters

Parameter | Description
number | Number to format

Example

<!--- This example shows the use of DollarFormat --->
...
<h3>DollarFormat Example</h3>
<cfloop from = 8 to = 50 index = counter>
    <cfset full = counter>
    <cfset quarter = counter + (1/4)>
    <cfset half = counter + (1/2)>
    <cfset threefourth = counter + (3/4)>
    <cfoutput>
    <pre>
    bill	#DollarFormat(full)#	#DollarFormat(quarter)#
     #DollarFormat(half)# #DollarFormat(threefourth)#
    18% tip	#DollarFormat(full * (18/100))#
     #DollarFormat(quarter * (18/100))#
     #DollarFormat(half * (18/100))#
     #DollarFormat(threefourth * (18/100))#
    </pre>
    </cfoutput>
</cfloop>
...


Duplicate

Description

Returns a clone, also known as a deep copy, of a variable. There is no reference to the original variable.

Returns

A clone of a variable.

Category

Structure functions, System functions

Function syntax

Duplicate(variable_name)

See also

StructCopy, other Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
variable_name | Name of a variable to duplicate

Usage

Use this function to duplicate complex structures, such as nested structures and queries.

Note: The Duplicate function throws an exception if you attempt to duplicate a CFC.

Note: With this function, you cannot duplicate a COM, CORBA, or JAVA object returned from the cfobject tag or the CreateObject function. If an array element or structure field is a COM, CORBA, or JAVA object, you cannot duplicate the array or structure.

Example

<h3>Duplicate Example</h3>
<cfset s1 = StructNew()>
<cfset s1.nested = StructNew()>
<cfset s1.nested.item = "original">
<cfset copy = StructCopy(s1)>
<cfset clone = Duplicate(s1)>
<!--- modify the original --->
<cfset s1.nested.item = "modified">
<cfoutput>
<p>The copy contains the modified value: #copy.nested.item#</p>
<p>The duplicate contains the original value: #clone.nested.item#</p>
</cfoutput>


Encrypt

Description

Encrypts a string using a specific algorithm and encoding method.

Returns

String; can be much longer than the original string.

Category

Security functions, String functions

Function syntax

Encrypt(string, key[, algorithm[, encoding]]))

See also

Decrypt

History

ColdFusion MX 7: Added the algorithm and encoding parameters.

Parameters

Parameter

Description

string

String to encrypt.

key

String. Key or seed used to encrypt the string.

  • For the CFMX_COMPAT algorithm, any combination of any number of characters; used as a seed used to generate a 32-bit encryption key.
  • For all other algorithms, a key in the format used by the algorithm. For these algorithms, use the GenerateSecretKey function to generate the key.

algorithm

(Optional) The algorithm to use to decrypt the string.ColdFusion MX installs a cryptography library with the following algorithms:

  • CFMX_COMPAT: the algorithm used in ColdFusion MX and prior releases. This algorithm is the least secure option (default).
  • AES: the Advanced Encryption Standard specified by the National Institute of Standards and Technology (NIST) FIPS-197.
  • BLOWFISH: the Blowfish algorithm defined by Bruce Schneier.
  • DES: the Data Encryption Standard algorithm defined by NIST FIPS-46-3.
  • DESEDE: the "Triple DES" algorithm defined by NIST FIPS-46-3.

If you install a security provider with additional cryptography algorithms, you can also specify any of its string encryption and decryption algorithms.

encoding

(Optional; if you specify this parameter, you must also specify the algorithm parameter) The binary encoding in which to represent the data as a string.

  • Base64: the Base64 algorithm, as specified by IETF RFC 2045.
  • Hex: the characters !-F0-9 represent the hexadecimal byte values.
  • UU: the UUEncode algorithm (default).

Usage

This function uses a symmetric key-based algorithm, in which the same key is used to encrypt and decrypt a string. The security of the encrypted string depends on maintaining the secrecy of the key.

For all algorithms except the default algorithm, ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

The default algorithm, which is the same as was used in ColdFusion 5 and ColdFusion MX, uses an XOR-based algorithm that uses a pseudo-random 32-bit key, based on a seed passed by the user as a function parameter. This algorithm is less secure than the other available algorithms.

Example

The following example encrypts and decrypts a text string. It lets you specify the encryption algorithm and encoding technique. It also has a field for a key seed to use with the CFMX_COMPAT algorithm. For all other algorithms, it generates a secret key.

<h3>Encrypt Example</h3>
<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.myString")>
    <cfscript>
        /* GenerateSecretKey does not generate key for the CFMX_COMPAT algorithm,
          so use the key from the form.
        */
        if (Form.myAlgorithm EQ "CFMX_COMPAT")
            theKey=Form.MyKey;
        // For all other encryption techniques, generate a secret key.
        else
            theKey=generateSecretKey(Form.myAlgorithm);
        //Encrypt the string
        encrypted=encrypt(Form.myString, theKey, Form.myAlgorithm,
            Form.myEncoding);
        //Decrypt it
        decrypted=decrypt(encrypted, theKey, Form.myAlgorithm, Form.myEncoding);
    </cfscript>

    <!--- Display the values used for encryption and decryption,
            and the results. --->
    <cfoutput>
        <b>The algorithm:</b> #Form.myAlgorithm#<br>
        <b>The key:</B> #theKey#<br>
        <br>
        <b>The string:</b> #Form.myString# <br>
        <br>
        <b>Encrypted:</b> #encrypted#<br>
        <br>
        <b>Decrypted:</b> #decrypted#<br>
    </cfoutput>
</cfif>

<!--- The input form.  --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select the encoding</b><br>
    <select size="1" name="myEncoding" >
        <option selected>UU</option>
        <option>Base64</option>
        <option>Hex</option>
    </select><br>
    <br>
    <b>Select the algorithm</b><br>
    <select size="1" name="myAlgorithm" >
        <option selected>CFMX_COMPAT</option>
        <option>AES</option>
        <option>DES</option>
        <option>DESEDE</option>
    </select><br>
    <br>
    <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br>
    <input type = "Text" name = "myKey" value = "MyKey"><br>
    <br>
    <b>Enter string to encrypt</b><br>
    <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">This string will be encrypted (you can replace it with more typing).
    </textArea><br>
    <input type = "Submit" value = "Encrypt my String">
</form>


Evaluate

Description

Evaluates one or more string expressions, dynamically, from left to right. (The results of an evaluation on the left can have meaning in an expression to the right.) Returns the result of evaluating the rightmost expression.

Returns

An object; the result of the evaluation(s).

Category

Dynamic evaluation functions

Function syntax

Evaluate(string_expression1 [, string_expression2 [, … ] ] )

See also

DE, IIf

Parameters

Parameter | Description
string_expression1, string_expression2... | Expressions to evaluate

Usage

String expressions can be complex. If a string expression contains a single- or double-quotation mark, the mark must be escaped.

This function is useful for forming one variable from multiple variables. For example, to reference a column of the query qNames with a variable, var, using an index value to traverse rows, you could use the following code:

<cfset var=Evaluate("qNames.#colname#[#index#]")>

For more information, see Using Expressions and Number Signs in ColdFusion MX Developer’s Guide.

Example

<!--- This example shows the use of DE and Evaluate --->
<h3>Evaluate Example</h3>
<cfif IsDefined("FORM.myExpression")>
<cftry>
<!--- Evaluate the expression --->
<cfset myExpression = Evaluate(FORM.myExpression)>
<!--- Use DE to output the value of the variable, unevaluated --->
<cfoutput>
The value of the expression #Evaluate(DE(FORM.MyExpression))#
is #MyExpression#.
</cfoutput>
...


Exp

Description

Calculates the exponent whose base is e that represents number. The constant e equals 2.71828182845904, the base of the natural logarithm. This function is the inverse of Log, the natural logarithm of number.

Returns

The constant e, raised to the power of number.

Category

Mathematical functions

Function syntax

Exp(number)

See also

Log, Log10

Parameters

Parameter | Description
number | Exponent to apply to the base e

Usage

To calculate powers of other bases, use the exponentiation operator (^).

Example

<h3>Exp Example</h3>
<cfif IsDefined("FORM.Submit")>
    <cfoutput>
    <p>Your number, #FORM.number#
    <br>#FORM.number# raised to the E power: #exp(FORM.number)#
    <cfif FORM.number LTE 0>
        <br>You must enter a positive real number to see its natural logarithm
        <cfelse><br>
        The natural logarithm of #FORM.number#: #log(FORM.number)#
    </cfif>
    <cfif FORM.number LTE 0><br>
        You must enter a positive real number to see its logarithm to base 10
        <cfelse><br>
            The logarithm of #FORM.number# to base 10: #log10(FORM.number)#
</cfif>
</cfoutput>
</cfif>
<cfform action = "exp.cfm">
Enter a number to see its value raised to the E power, its natural logarithm,
and the logarithm of number to base 10.
<cfinput type = "Text" name = "number" message = "You must enter a number"
validate = "float" required = "No">
<input type = "Submit" name = "Submit">
</cfform>


ExpandPath

Description

Creates an absolute, platform-appropriate path that is equivalent to the value of relative_path, appended to the base path. This function (despite its name) can accept an absolute or relative path in the relative_path parameter

The base path is the currently executing page’s directory path. It is stored in pageContext.getServletContext().

Returns

A string. If the relative path contains a trailing forward slash or backward slash, the return value contains the same trailing character.

Category

System functions

Function syntax

ExpandPath(relative_path)

See also

FileExists, GetCurrentTemplatePath, GetFileFromPath

History

ColdFusion MX: Changed behavior for the relative_path parameter: this function can now accept an absolute or relative path in the relative_path parameter. To resolve a path, this function uses virtual mappings that are defined in the ColdFusion Administrator. This function does not reliably use virtual mappings that are defined in IIS, Apache, or other web servers.

Parameters

Parameter | Description
relative_path | Relative or absolute directory reference or file name, within the current directory, (.\ and ..\) to convert to an absolute path. Can include forward or backward slashes.

Usage

If the parameter or the returned path is invalid, the function throws an error.

These examples show the valid constructions of relative_path:

  • ExpandPath( "*.*")
  • ExpandPath( "/")
  • ExpandPath( "\")
  • ExpandPath( "/mycfpage.cfm")
  • ExpandPath( "mycfpage.cfm")
  • ExpandPath( "myDir/mycfpage.cfm")
  • ExpandPath( "/myDir/mycfpage.cfm")
  • ExpandPath( "../../mycfpage.cfm")

Example

<h3>ExpandPath Example - View Only</h3>
<!---
<cfset thisPath=ExpandPath("*.*")>
<cfset thisDirectory=GetDirectoryFromPath(thisPath)>
<cfoutput>
The current directory is: #GetDirectoryFromPath(thisPath)#

<cfif IsDefined("form.yourFile")>
<cfif form.yourFile is not "">
<cfset yourFile = form.yourFile>
    <cfif FileExists(ExpandPath(yourfile))>
    <p>Your file exists in this directory. You entered
    the correct file name, #GetFileFromPath("#thisPath#/#yourfile#")#
    <CFELSE>
    <p>Your file was not found in this directory:
    <br>Here is a list of the other files in this directory:
    <!--- use CFDIRECTORY to give the contents of the
    snippets directory, order by name and size --->
    <CFDIRECTORY DIRECTORY="#thisDirectory#"
    NAME="myDirectory"
    SORT="name ASC, size DESC">
    <!--- Output the contents of the CFDIRECTORY as a CFTABLE --->
    <CFTABLE QUERY="myDirectory">
    <CFCOL HEADER="NAME:"
            TEXT="#Name#">
    <CFCOL HEADER="SIZE:"
            TEXT="#Size#">
    </CFTABLE>
    </cfif>
</cfif>
<cfelse>
<h3>Please enter a file name</h3>
</CFIF>
</cfoutput>

<FORM action="expandpath.cfm" METHOD="post">
<h3>Enter the name of a file in this directory <I>
<FONT SIZE="-1">(try expandpath.cfm)</FONT></I></h3>
<INPUT TYPE="Text" NAME="yourFile">
<INPUT TYPE="Submit" NAME="">
</form>
 --->


FileExists

Description

Determines whether a file exists.

Returns

Yes, if the file specified in the parameter exists; No, otherwise.

Category

System functions, Decision functions

Function syntax

FileExists(absolute_path)

See also

DirectoryExists, ExpandPath, GetTemplatePath

Parameters

Parameter | Description
absolute_path | An absolute path

Usage

To access a file on a remote system, the account (for Windows) or user (for UNIX and Linux) that is running ColdFusion must have permission to access the file, directory, and remote system. For example, if you run ColdFusion MX in the Server Configuration as a Windows service, by default it runs under the local system account, which does not have sufficient privileges to access remote systems. You can change this, however, on the Log On page of the Services Properties dialog box.

Example

<h3>FileExists Example</h3>

<cfset thisPath = ExpandPath("*.*")>
<cfset thisDirectory = GetDirectoryFromPath(thisPath)>
<cfoutput>
The current directory is: #GetDirectoryFromPath(thisPath)#
<cfif IsDefined("FORM.yourFile")>
<cfif FORM.yourFile is not "">
<cfset yourFile = FORM.yourFile>
    <cfif FileExists(ExpandPath(yourfile))>
    <p>Your file exists in this directory. You entered
    the correct file name, #GetFileFromPath("#thisPath#/#yourfile#")#
    <cfelse>


Find

Description

Finds the first occurrence of a substring in a string, from a specified start position. The search is case-sensitive.

Returns

A number; the position of substring in string; or 0, if substring is not in string.

Category

String functions

Function syntax

Find(substring, string [, start ])

See also

FindNoCase, Compare, FindOneOf, REFind, Replace

Parameters

Parameter | Description
substring | A string or a variable that contains one. String for which to search.
string | A string or a variable that contains one. String in which to search.
start | Start position of search.

Example

<cfoutput>
    <cfset stringToSearch = "The quick brown fox jumped over the lazy dog.">
    #find("the",stringToSearch)#<br>
    #find("the",stringToSearch,35)#<br>
    #find("no such substring",stringToSearch)#<br>
    <br>
    #findnocase("the",stringToSearch)#<br>
    #findnocase("the",stringToSearch,5)#<br>
    #findnocase("no such substring",stringToSearch)#<br>
    <br>
    #findoneof("aeiou",stringToSearch)#<br>
    #findoneof("aeiou",stringToSearch,4)#<br>
    #findoneof("@%^*()",stringToSearch)#<br>
</cfoutput>


FindNoCase

Description

Finds the first occurrence of a substring in a string, from a specified start position. If substring is not in string, returns zero. The search is case-insensitive.

Returns

The position of substring in string; or 0, if substring is not in string.

Category

String functions

Function syntax

FindNoCase(substring, string [, start ])

See also

Find, CompareNoCase, FindOneOf, REFind, Replace

Parameters

Parameter | Description
substring | A string or a variable that contains one. String for which to search.
string | A string or a variable that contains one. String in which to search.
start | Start position of search.

Example

In the following example, the Find function returns 33 as the first position found because "the" is lowercase. The FindNoCase function returns 1 as the first postion because the case is ignored.

<cfset stringToSearch = "The quick brown fox jumped over the lazy dog.">

stringToSearch = <cfoutput>#stringToSearch#</cfoutput><br>
<p>
Find Function:<br>
Find("the",stringToSearch) returns <cfoutput>#find("the",stringToSearch)#</cfoutput><br>
<p>
FindNoCase Function:<br>
FindNoCase("the",stringToSearch) returns <cfoutput>#FindNoCase("the",stringToSearch)#</cfoutput>


FindOneOf

Description

Finds the first occurrence of any one of a set of characters in a string, from a specified start position. The search is case-sensitive.

Returns

The position of the first member of set found in string; or 0, if no member of set is found in string.

Category

String functions

Function syntax

FindOneOf(set, string [, start ])

See also

Find, Compare, REFind

Parameters

Parameter | Description
set | A string or a variable that contains one. String that contains one or more characters to search for.
string | A string or a variable that contains one. String in which to search.
start | Start position of search.

Example

<cfset stringToSearch = "The quick brown fox jumped over the lazy dog.">
#find("the",stringToSearch)#<br>
#find("the",stringToSearch,35)#<br>
#find("no such substring",stringToSearch)#<br>
<br>
#findnocase("the",stringToSearch)#<br>
#findnocase("the",stringToSearch,5)#<br>
#findnocase("no such substring",stringToSearch)#<br>
<br>
#findoneof("aeiou",stringToSearch)#<br>
#findoneof("aeiou",stringToSearch,4)#<br>
#findoneof("@%^*()",stringToSearch)#<br>


FirstDayOfMonth

Description

Determines the ordinal (day number, in the year) of the first day of the month in which a given date falls.

Returns

A number corresponding to a day-number in a year.

Category

Date and time functions

Function syntax

FirstDayOfMonth(date)

See also

Day, DayOfWeek, DayOfWeekAsString, DayOfYear, DaysInMonth, DaysInYear

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Example

<h3>FirstDayOfMonth Example</h3>

<cfoutput>
The first day of #MonthAsString(Month(Now()))#, #Year(Now())# was
day #FirstDayOfMonth(Now())# of the year.
</cfoutput>


Fix

Description

Converts a real number to an integer.

Returns

If number is greater than or equal to 0, the closest integer less than number.

If number is less than 0, the closest integer greater than number.

Category

Mathematical functions

Function syntax

Fix(number)

See also

Ceiling, Int, Round

Parameters

Parameter | Description
number | A number

Example

<h3>Fix Example</h3>
<p>Fix returns the closest integer less than the number if the number is
greater than or equal to 0. Fix returns the closest integer greater than
the number if number is less than 0.
<cfoutput>
<p>The fix of 3.4 is #Fix(3.4)#
<p>The fix of 3 is #Fix(3)#
<p>The fix of 3.8 is #Fix(3.8)#
<p>The fix of -4.2 is #Fix(-4.2)#
</cfoutput>


FormatBaseN

Description

Converts number to a string, in the base specified by radix.

Returns

String that represents number, in the base radix.

Category

Display and formatting functions, Mathematical functions, String functions

Function syntax

FormatBaseN(number, radix)

See also

InputBaseN

Parameters

Parameter | Description
number | Number to convert
radix | Base of the result

Example

<h3>FormatBaseN Example</h3>
<p>Converts a number to a string in the base specified by Radix.
<p>
<cfoutput>
<br>FormatBaseN(10,2): #FormatBaseN(10,2)#
<br>FormatBaseN(1024,16): #FormatBaseN(1024,16)#
<br>FormatBaseN(125,10): #FormatBaseN(125,10)#
<br>FormatBaseN(10.75,2): #FormatBaseN(10.75,2)#
</cfoutput>
<h3>InputBaseN Example</h3>
<p>InputBaseN returns the number obtained by converting a string,
using base specified by Radix (an integer from 2 to 36).

<cfoutput>
<br>InputBaseN("1010",2): #InputBaseN("1010",2)#
<br>InputBaseN("3ff",16): #InputBaseN("3ff",16)#
<br>InputBaseN("125",10): #InputBaseN("125",10)#
<br>InputBaseN(1010,2): #InputBaseN(1010,2)#
</cfoutput>


GenerateSecretKey

Description

Gets a secure key value for use in the Encrypt function.

Returns

A string containing the encryption key.

Category

Security functions, String functions

Function syntax

GenerateSecretKey(algorithm)

See also

Decrypt, Encrypt

History

ColdFusion MX 7: Added this function.

Parameters

Parameter

Description

algorithm

The encryption algorithm for which to generate the key. ColdFusion MX installs a cryptography library with the following algorithms:

  • AES: the Advanced Encryption Standard specified by the National Institute of Standards and Technology (NIST) FIPS-197.
  • BLOWFISH: the Blowfish algorithm defined by Bruce Schneier.
  • DES: the Data Encryption Standard algorithm defined by NIST FIPS-46-3.

DESEDE: the "Triple DES" algorithm defined by NIST FIPS-46-3.

Usage

You cannot use the GenerateSecretKey function to generate a key for the ColdFusion default encryption algorithm (CFMX_COMPAT) of the Encrypt and Decrypt functions.

ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

Example

The following example encrypts and decrypts a text string. It lets you specify the encryption algorithm and encoding technique. It also has a field for a key seed to use with the CFMX_COMPAT algorithm. For all other algorithms, it uses the GenerateSecretKey function to generate a secret key.

<h3>Decrypt Example</h3>

<!--- Do the following if the form has been submitted. --->
<cfif IsDefined("Form.myString")>
    <cfscript>
        /* GenerateSecretKey does not generate keys for the CFMX_COMPAT algorithm,
          so we use a key from the form.
        */
        if (Form.myAlgorithm EQ "CFMX_COMPAT")
            theKey=Form.MyKey;
        // For all other encryption techniques, generate a secret key.
        else
            theKey=generateSecretKey(Form.myAlgorithm);
        //Encrypt the string.
        encrypted=encrypt(Form.myString, theKey, Form.myAlgorithm,
            Form.myEncoding);
        //Decrypt it.
        decrypted=decrypt(encrypted, theKey, Form.myAlgorithm, Form.myEncoding);
    </cfscript>

    <!--- Display the values used for encryption and decryption,
            and the results. --->
    <cfoutput>
        <b>The algorithm:</b> #Form.myAlgorithm#<br>
        <b>The key:</B> #theKey#<br>
        <br>
        <b>The string:</b> #Form.myString# <br>
        <br>
        <b>Encrypted:</b> #encrypted#<br>
        <br>
        <b>Decrypted:</b> #decrypted#<br>
    </cfoutput>
</cfif>

<!--- The input form. --->
<form action="#CGI.SCRIPT_NAME#" method="post">
    <b>Select the encoding</b><br>
    <select size="1" name="myEncoding" >
        <option selected>UU</option>
        <option>Base64</option>
        <option>Hex</option>
    </select><br>
    <br>
    <b>Select the algorithm</b><br>
    <select size="1" name="myAlgorithm" >
        <option selected>CFMX_COMPAT</option>
        <option>AES</option>
        <option>DES</option>
        <option>DESEDE</option>
    </select><br>
    <br>
    <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br>
    <input type = "Text" name = "myKey" value = "foobar"><br>
    <br>
    <b>Enter string to encrypt</b><br>
    <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">This string will be encrypted (you can replace it with more typing).
    </textArea><br>
    <input type = "Submit" value = "Encrypt my String">
</form>


GetAuthUser

Description

Gets the name of an authenticated user.

Returns

The name of an authenticated user.

Category

Security functions

Function syntax

GetAuthUser()

See also

IsUserInRole , cflogin, cfloginuser; Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Usage

This function works with cflogin authentication or web server authentication. It checks for a logged-in user as follows:

  1. It checks for a login made with cfloginuser.
  2. If no user was logged in with cfloginuser, it checks for a web server login (cgi.remote_user).

Example

<H3>GetAuthUser Example</H3>

<P>Authenticated User: <cfoutput>#GetAuthUser()#</cfoutput>


GetBaseTagData

Description

Used within a custom tag. Finds calling (ancestor) tag by name and accesses its data.

Returns

An object that contains data (variables, scopes, and so on) from an ancestor tag. If there is no ancestor by the specified name, or if the ancestor does not expose data (for example, cfif), an exception is thrown.

Category

Other functions

Function syntax

GetBaseTagData(tagname [, instancenumber ] )

See also

GetBaseTagList; High-level data exchange in Creating and Using Custom CFML Tags in ColdFusion MX Developer’s Guide

Parameters

Parameter | Req/Opt | Description
tagname | Required | Ancestor tag name for which to return data
instancenumber | Optional | Number of ancestor levels to jump before returning data. The default value is 1 (closest ancestor).

Example

<!--- This example shows the use of GetBaseTagData
function. Typically used in custom tags.--->
...
<cfif trim(inCustomTag) neq "">
        <cfoutput>
            Running in the context of a custom
            tag named #inCustomTag#.<p>
        </cfoutput>
        <!--- Get the tag instance data --->
        <cfset tagData = GetBaseTagData(inCustomTag)>
        <!--- Find the tag's execution mode --->
        Located inside the
        <cfif tagData.thisTag.executionMode neq ’inactive’>
            template
        <cfelse>
            BODY
        </cfif>


GetBaseTagList

Description

Gets ancestor tag names, starting with the parent tag.

Returns

A comma-delimited list of uppercase ancestor tag names, as a string. The first list element is the current tag. If the current tag is nested, the next element is the parent tag. If the function is called for a top-level tag, it returns an empty string. If an ancestor does not expose data (see GetBaseTagData), its name might not be returned.

Category

Other functions

Function syntax

GetBaseTagList()

See also

GetBaseTagData; High-level data exchange in Creating and Using Custom CFML Tags in ColdFusion MX Developer’s Guide

Usage

This function does not display the following tags or end tags in the ancestor tag list:

  • cfif, cfelseif, cfelse
  • cfswitch, cfcase, cfdefaultcase
  • cftry, cfcatch

This function displays the following tags only under the following conditions:

  • cfloop: if it uses a query attribute
  • cfoutput: if at least one of its children is a complex expression
  • cfprocessingdirective: if it has at least one other attribute besides pageencoding

Example

<!--- This example shows the use of GetBaseTagList function.
Typically used in custom tags. --->
<cfif thisTag.executionMode is "start">
    <!--- Get the tag context stack
    The list will look something like "CFIF,MYTAGNAME..." --->
    <cfset ancestorList = GetBaseTagList()>
    <br><br>Dump of GetBaseTagList output:<br>
    <cfdump var="#ancestorList#"><br><br>
    <!--- Output current tag name --->
    <cfoutput>This is custom tag  #ListGetAt(ancestorList,1)#</cfoutput><br>
    <!--- Determine whether this is nested inside a loop --->
    <cfset inLoop = ListFindNoCase(ancestorList, "cfloop")>
    <cfif inLoop>
        Running in the context of a cfloop tag.<br>
    </cfif>
</cfif>


GetBaseTemplatePath

Description

Gets the absolute path of an application’s base page.

Returns

The absolute path of the application base page, as a string.

Category

Other functions, System functions

Function syntax

GetBaseTemplatePath()

See also

GetCurrentTemplatePath, FileExists, ExpandPath

Example

<h3>GetBaseTemplatePath Example</h3>

<p>The template path of the current page is:
<cfoutput>#GetBaseTemplatePath()#</cfoutput>


GetClientVariablesList

Description

Finds the client variables to which a page has write access.

Returns

Comma-delimited list of non-read-only client variables, as a string.

Category

List functions, Other functions

Function syntax

GetClientVariablesList()

See also

DeleteClientVariable

Usage

The list of variables returned by this function is compatible with ColdFusion list functions.

Example

<!--- This example is view-only. --->

<h3>GetClientVariablesList Example</h3>

<p>This view-only example deletes a client variable called "User_ID", if it exists
in the list of client variables returned by GetClientVariablesList().
<p>This example requires the existence of an Application.cfm file and that client
management be in effect.
<!---
<cfset client.somevar = "">
<cfset client.user_id = "">
<p>Client variable list:<cfoutput>#GetClientVariablesList()#</cfoutput>

<cfif ListFindNoCase(GetClientVariablesList(), "User_ID") is not 0>
<!--- delete that variable
    <cfset temp = DeleteClientVariable("User_ID")>
    <p>Was variable "User_ID" Deleted? <cfoutput>#temp#</cfoutput>
</cfif>

<p>Amended Client variable list:<cfoutput>#GetClientVariablesList()#
 </cfoutput>
--->


GetContextRoot

Description

Returns path to the J2EE server context root for the current request.

Returns

The path from the web root to the context root for the current page. The path starts with a forward slash character (/) but does not end with a forward slash character (/). For applications in the default (root) context, returns the empty string.

Category

System functions

History

ColdFusion MX 7: Added this function.

Function syntax

GetContextRoot()

See also

GetPageContext

Usage

This function is equivalent to calling GetPageContext().GetRequest().GetContextPath(). On J2EE configurations, it returns the path from the Web root to the J2EE context root of the ColdFusion MX J2EE application. On server configurations, it returns the empty string, because the context root is at the web root.

This function is useful in applications that might be installed at varying J2EE context roots.

Example

The ColdFusion MX Administrator uses the following line to get the location of the administrator directory:

<cfset request.thisURL = "#getContextRoot()#/CFIDE/administrator/">

The Administrator uses the returned value in places where it uses a URL to access Administrator resources, such as images, as in the following line:

<a href="index.cfm"><img src="#request.thisURL#images/back.gif" width="16"
            height="16" border="0" alt=" "></a>


GetCurrentTemplatePath

Description

Gets the path of the page that calls this function.

Returns

The absolute path of the page that contains the call to this function, as a string.

Category

System functions

Function syntax

GetCurrentTemplatePath()

See also

GetBaseTemplatePath, FileExists, ExpandPath

Usage

If the function call is made from a page included with a cfinclude tag, this function returns the page path of an included page. Contrast this with the GetBaseTemplatePath function, which returns the path of the top-level page, even if it is called from an included page.

Example

<!--- This example uses GetCurrentTemplatePath to show the
template path of the current page --->
<h3>GetCurrentTemplatePath Example</h3>

<p>The template path of the current page is:
<cfoutput>#GetCurrentTemplatePath()#</cfoutput>


GetDirectoryFromPath

Description

Extracts a directory from an absolute path.

Returns

Absolute path, without the filename. The last character is a forward or backward slash, depending on the operating system.

Category

System functions

Function syntax

GetDirectoryFromPath(path)

See also

ExpandPath, GetFileFromPath

Parameters

Parameter | Description
path | Absolute path (drive, directory, filename, and extension)

Example

<h3>GetDirectoryFromPath Example</h3>
<cfset thisPath = ExpandPath("*.*")>
<cfset thisDirectory = GetDirectoryFromPath(thisPath)>
<cfoutput>
The current directory is: #GetDirectoryFromPath(thisPath)#
<cfif IsDefined("FORM.yourFile")>
    <cfif FORM.yourFile is not "">
        <cfset yourFile = FORM.yourFile>
            <cfif FileExists(ExpandPath(yourfile))>
            <p>Your file exists in this directory. You entered the correct file name,
    #GetFileFromPath("#thisPath#/#yourfile#")#
    <cfelse>
        <p>Your file was not found in this directory:
        <br>Here is a list of the other files in this directory:
        <!--- use cfdirectory show directory, order by name & size --->
        <cfdirectory directory = "#thisDirectory#"
            name = "myDirectory" SORT = "name ASC, size DESC">
        <!--- Output the contents of the cfdirectory as a CFTABLE --->
        <cftable query = "myDirectory">
            <cfcol header = "NAME:" text = "#Name#">
        <cfcol header = "SIZE:" text = "#Size#">
        </cftable>
        </cfif>
    </cfif>
<cfelse>
    <H3>Please enter a file name</H3>
    </cfif>
    </cfoutput>
    <form action="getdirectoryfrompath.cfm" METHOD="post">
        <H3>Enter the name of a file in this directory <I><FONT SIZE="-1">
(try expandpath.cfm)</FONT></I></H3>
        <input type="Text" NAME="yourFile">
        <input type="Submit" NAME="">
    </form> --->


GetEncoding

Description

Returns the encoding (character set) of the Form or URL scope.

Returns

String; the character encoding of the specified scope.

Category

International functions, System functions

Function syntax

GetEncoding(scope_name)

See also

SetEncoding, cfcontent, cfprocessingdirective, URLDecode, URLEncodedFormat

History

ColdFusion MX: Added this function.

Parameters

Parameter

Description

scope_name
  • Form
  • URL.

Usage

Use this function to determine the character encoding of the URL query string or the fields of a form that was submitted to the current page. The default encoding, if none has been explicitly set, is UTF-8.

For more information, see www.iana.org/assignments/character-sets.

Example

<!--- This example sends the contents of two fields and interprets them as
        big5 encoded text. --->
<cfcontent type="text/html; charset=big5">
<form action='#cgi.script_name#' method='get'>
<input name='xxx' type='text'>
<input name='yyy' type='text'>
<input type="Submit" value="Submit">
</form>

<cfif IsDefined("URL.xxx")>
<cfscript>
    SetEncoding("url", "big5");
    WriteOutput("URL.XXX is " & URL.xxx & "<br>");
    WriteOutput("URL.YYY is " & URL.yyy & "<br>");
    theEncoding = GetEncoding("URL");
     WriteOutput("The URL variables were decoded using '" & theEncoding & "' encoding.");

    WriteOutput("The encoding is " & theEncoding);
</cfscript>
</cfif>


GetException

Description

Used with the cftry and cfcatch tags. Retrieves a Java exception object from a Java object.

Returns

Any Java exception object raised by a previous method call on the Java object.

Category

System functions

Syntax

GetException(object)

Parameters

Parameter | Description
object | A Java object.

Usage

ColdFusion stores a Java exception object for each method call on a Java object. Subsequent method calls reset the exception object. To get the current exception object, you must call GetException on the Java object before other methods are invoked on it.

Example

<!--- Create the Java object reference --->
<cfobject action = create type = java class = primativetype name = myObj>
<!--- Calls the object's constructor --->
<cfset void = myObj.init()>
<cftry>
<cfset void = myObj.DoException() >
<Cfcatch type = "Any">
    <cfset exception = GetException(myObj)>
<!--- User can call any valid method on the exception object.--->
    <cfset message = exception.toString()>
    <cfoutput>
        Error<br>
        I got exception <br>
        <br> The exception message is: #message# <br>
    </cfoutput>
</cfcatch>
</cftry>


GetFileFromPath

Description

Extracts a filename from an absolute path.

Returns

Filename, as a string.

Category

System functions

Function syntax

GetFileFromPath(path)

See also

ExpandPath, GetCurrentTemplatePath

Parameters

Parameter | Description
path | Absolute path (drive, directory, filename, and extension)

Example

<h3>GetFileFromPath Example</h3>
<cfset thisPath = ExpandPath("*.*")>
<cfset thisDirectory = GetDirectoryFromPath(thisPath)>
<cfoutput>
The current directory is: #GetDirectoryFromPath(thisPath)#
<cfif IsDefined("FORM.yourFile")>
<cfif FORM.yourFile is not "">
<cfset yourFile = FORM.yourFile>
<cfif FileExists(ExpandPath(yourfile))>
        <p>Your file exists in this directory. You entered the correct file
name, #GetFileFromPath("#thisPath#/#yourfile#")#
    <cfelse>
        <p>Your file was not found in this directory:
        <br>Here is a list of the other files in this directory:
        <!--- use CFDIRECTORY to give the contents of the snippets
directory, order by name and size --->
        <CFDIRECTORY
            DIRECTORY = "#thisDirectory#"
            name = "myDirectory"
            SORT = "name ASC, size DESC">
        <!--- Output the contents of the CFDIRECTORY as a CFTABLE --->
        <CFTABLE QUERY = "myDirectory">
        <CFCOL HEADER = "NAME:" TEXT = "#Name#">
    <CFCOL HEADER = "SIZE:" TEXT = "#Size#">
...


GetFunctionList

Description

Displays a list of the functions that are available in ColdFusion.

Returns

A structure of functions.

Category

System functions

Function syntax

GetFunctionList()

Example

<!----- This example shows the use of GetFunctionList. ---->
<cfset fList = GetFunctionList()>
<cfoutput>#StructCount(fList)# functions<br><br>
    </cfoutput>
<cfloop COLLECTION = "#fList#" ITEM = "key">
    <cfoutput>#key#<br>
    </cfoutput>
</cfloop>


GetGatewayHelper

Description

Gets a Java GatewayHelper object that provides methods and properties for use with a ColdFusion event gateway.

Returns

A Java GatewayHelper object.

Category

Extensibility functions

Function syntax

GetGatewayHelper(gatewayID)

See also

SendGatewayMessage

History

ColdFusion MX 7: Added the function.

Parameters

Parameter | Description
gatewayID | Identifier of the gateway that provides the GatewayHelper object. Must be the Gateway ID of one of the ColdFusion event gateway instances configured on the ColdFusion MX Administrator Event Gateways section’s Gateways page.

Usage

The ColdFusion GetGatewayHelper function returns a Java GatewayHelper object that provides event gateway-specific helper methods and properties. To use this function, the event gateway must provide access to a class that implements the GatewayHelper class. For example, an instant messaging event gateway might make buddy-list management functions available in a GatewayHelper object.

An event gateway listener CFC can get the gatewayID value from the CFEvent structure of the incoming message.

You access the GatewayHelper object’s methods and properties using standard ColdFusion Java object access techniques. For more information, see The role of the GatewayHelper object in Using Event Gateways in ColdFusion MX Developer’s Guide.

Example

If an event gateway’s helper class includes an addBuddy method that takes a single String parameter, you could use the following code to get the GatewayHelper object and add a buddy to the buddies list:

<h3>GetGatewayHelper Example</h3>
<cfscript>
    myHelper = getGatewayHelper(myGatewayID);
    status = myHelper.addBuddy("jsmith");
</cfscript>


GetHttpRequestData

Description

Makes HTTP request headers and body available to CFML pages. Useful for capturing SOAP request data, which can be delivered in an HTTP header.

Returns

A ColdFusion structure.

Category

System functions

Function syntax

GetHttpRequestData()

Returns

The function returns a structure containing the following entries:

Parameter | Description
content | Raw content from form submitted by client, in string or binary format. For content to be considered string data, the FORM request header "CONTENT_TYPE" must start with "text/" or be special case "application/x-www-form-urlencoded". Other types are stored as a binary object.
headers | Structure that contains HTTP request headers as value pairs. Includes custom headers, such as SOAP requests.
method | String that contains the CGI variable Request_Method.
protocol | String that contains the Server_Protocol CGI variable.

Usage

To determine whether data is binary, use IsBinary(x.content). To convert data to a string value, if it can be displayed as a string, use ToString(x.content).

Example

The following example shows how this function can return HTTP header information.

<cfset x = GetHttpRequestData()>
<cfoutput>
<table cellpadding = "2" cellspacing = "2">
  <tr>
     <td><b>HTTP Request item</b></td>
     <td><b>Value</b></td> </tr>
<cfloop collection = #x.headers# item = "http_item">
     <tr>
        <td>#http_item#</td>
        <td>#StructFind(x.headers, http_item)#</td>	</tr>
</cfloop>
<tr>
    <td>request_method</td>
    <td>#x.method#</td></tr>
<tr>
    <td>server_protocol</td>
    <td>#x.protocol#</td></tr>
</table>
<b>http_content --- #x.content#</b>
</cfoutput>


GetHttpTimeString

Description

Gets the current time, in the Universal Time code (UTC).

Returns

The time, as a string, according to the HTTP standard described in RFC 1123 and its underlying RFC, 822. This format is commonly used in Internet protocols, including HTTP.

Category

Date and time functions, International functions

Function syntax

GetHttpTimeString(date_time_object)

See also

GetLocale, GetTimeZoneInfo, SetLocale

Parameters

Parameter | Description
date_time_object | A ColdFusion date-time object string or Java Date object

Usage

The time in the returned string is UTC, consistent with the HTTP standard.

Example

<cfoutput>
#GetHttpTimeString(now())#
</cfoutput>


GetK2ServerDocCount

Description

This function is deprecated.

Returns

The number of collection metadata items stored in Verity collections.

Category

Full-text search functions, Query functions

Function syntax

GetK2ServerDocCount()

See also

GetK2ServerDocCountLimit

History

ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases.

ColdFusion MX: Added this function.

Example

<cfoutput>GetK2ServerDocCount =
$*#GetK2ServerDocCount()#*$</cfoutput>


GetK2ServerDocCountLimit

Description

This function is deprecated.

Returns

Number of collection metadata items that the K2 server permits, as an integer

Category

Full-text search functions, Query functions

Function syntax

GetK2ServerDocCountLimit()

See also

GetK2ServerDocCount

History

ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases.

ColdFusion MX: Added this function.

Usage

If a search generates a larger number of documents than the limit, ColdFusion puts a warning message in the Administrator and in the log file.

Example

<cfoutput>GetK2ServerDocCountLimit =
$*#GetK2ServerDocCountLimit()#*$</cfoutput>


GetLocale

Description

Gets the current ColdFusion MX geographic/language locale value.

To set the default display format of date, time, number, and currency values in a ColdFusion application session, you use the SetLocale function.

Returns

The current locale value, as an English string. If a locale has a Java name and a name that ColdFusion MX used prior to the ColdFusion MX 7 release (for example, en_US and English (US)), ColdFusion MX returns the ColdFusion name (for example, English (US)).

Category

Display and formatting functions, International functions, System functions

Function syntax

GetLocale()

See also

GetLocaleDisplayName, SetLocale

History

ColdFusion MX 7: Added support for all Java locales and locale names.

ColdFusion MX: Changed behavior to that described in usage.

Usage

This function returns the locale name as it is represented in ColdFusion MX; for example, Portuguese (Brazilian), or ca_ES. To get a locale name in the language of the locale, use the GetLocaleDisplayName function, which returns português (Brasil) and català (Espanya).

This function determines whether a locale value is set for ColdFusion MX. (The value is set with the SetLocale function.)

  • If the ColdFusion MX locale value is present, the function returns it.
  • If the ColdFusion MX locale has not been explicitly set, ColdFusion now determines whether the default locale of the ColdFusion server computer operating system is among the locale values it supports. (The default locale is stored in the user environment variables user.language and user.region.)

    If the default locale value is not supported, the function returns English (US). ColdFusion sets the locale in the JVM to this value; it persists until the server is restarted or it is reset with the SetLocale function.

This function does not access a web browser’s Accept-Language HTTP header setting.

Note: When ColdFusion is started, it stores the supported locale values in the variable Server.ColdFusion.SupportedLocales. ColdFusion MX supports the locales supported by its Java runtime environment. The SupportedLocales value lists the Java names for the supported locales and the corresponding names that ColdFusion MX used prior to the ColdFusion MX 7 release.

For more information, see Locales in Developing Globalized Applications in ColdFusion MX Developer’s Guide.

Example

<h3>Example: Using SetLocale and GetLocale</h3>
<cfoutput>
    <!--- For each new request, the locale gets reset to the JVM locale --->
    Initial locale's ColdFusion name: #GetLocale()#<br>
    <br>
    <!--- Do this only if the form was submitted. --->
    <cfif IsDefined("form.mylocale")>
        <b>Changing locale to #form.mylocale#</b><br>
        <br>
        <!--- Set the locale to the submitted value and save the old ColdFusion locale name.  --->
        <cfset oldlocale=SetLocale("#form.mylocale#")>
        <!--- Get the current locale. It should have changed. --->
        New locale: #GetLocale()#<br>
    </cfif>

    <!--- Self-submitting form to select the new locale. --->
    <cfform>
        <h3>Please select the new locale:</h3>
        <cfselect name="mylocale">
            <!--- The server.coldfusion.supportedlocales variable is a
                    list of all supported locale names. Use a list cfloop tag
                    to create an HTML option tag for each name in the list. --->
            <cfloop index="i" list="#server.coldfusion.supportedlocales#">
                <option value="#i#">#i#</option>
            </cfloop>
        </cfselect><br>
        <br>
        <cfinput type="submit" name="submitit" value="Change Locale">
    </cfform>
</cfoutput>


GetLocaleDisplayName

Description

Gets a locale value and displays the name in a manner that is appropriate to a specific locale. By default, gets the current locale in the current locale’s language.

Returns

The localized display name of the locale, in the language of the specified locale.

Category

Display and formatting functions, International functions, System functions

Function syntax

GetLocaleDisplayName([locale[, inLocale]])

See also

GetLocale, SetLocale

History

ColdFusion MX 7: Added this function.

Parameters

Parameter | Description
locale | The locale whose name you want. The default is the current ColdFusion locale, or if no ColdFusion locale has been set, the JVM locale.
inlocale | The locale in which to return the name. The default is the current ColdFusion locale, or if no ColdFusion locale has been set, the JVM locale.

Example

The following example expands on the GetLocale example to show the use of the GetLocaleDisplayName function to display locale names in the current locale and in other locales. It lets you select a locale from all supported locales, changes the ColdFusion MX locale to the selected locales, and displays the old and new locale names.

<html>
<head>
    <title>Displaying locales</title>
</head>

<body>
<h3>Example: Changing and Displaying Locales</h3>
<cfoutput>
    <!--- For each new request, the locale gets reset to the JVM locale --->
    Initial locale's ColdFusion name: #GetLocale()#<br>
    Initial locale's display name: #GetLocaleDisplayName()#<br>
    <br>
    <!--- Do this only if the form was submitted. --->
    <cfif IsDefined("form.mylocale")>
        <b>Changing locale to #form.mylocale#</b><br>
        <br>
        <!--- Set the locale to the submitted value.
            SetLocale returns the old ColdFusion locale name.  --->
        <cfset oldlocale=SetLocale("#form.mylocale#")>
        <!--- Get the current locale's ColdFusion name.
            It should have changed. --->
        <cfset newlocale=GetLocale()>
        New locale's ColdFusion name: #newlocale#<br>
        New locale's display name in current locale: #GetLocaleDisplayName()#<br>
        New locale's display name in old locale:
            #GetLocaleDisplayName(newlocale, oldlocale)#<br>
        New locale's display name in en_US:
            #GetLocaleDisplayName(newlocale, "en_US")#<br>
        <br>
        Old locale's display name in current locale:
            #GetLocaleDisplayName(oldlocale)#<br>
        Old locale's display name in en_US:
            #GetLocaleDisplayName(oldlocale, "en_US")#<br>
    </cfif>

    <!--- Self-submitting form to select the new locale. --->
    <cfform>
        <h3>Please select the new locale:</h3>
        <cfselect name="mylocale">
            <!--- The server.coldfusion.supportedlocales variable is a
                    list of all supported locale names. Use a list cfloop tag
                    to create an HTML option tag for each name in the list. --->
            <cfloop index="i" list="#server.coldfusion.supportedlocales#">
            <!--- In the select box, we use the US English display names for
                    the locales. You can change en_US to your prefered locale. --->
                <option value="#i#">#GetLocaleDisplayName(i, "en_US")#</option>
            </cfloop>
        </cfselect><br>
        <br>
        <cfinput type="submit" name="submitit" value="Change Locale">
    </cfform>
</cfoutput>

</body>
</html>


GetMetaData

Description

Gets metadata (such as the methods, properties, and parameters of a component) associated with an object that is deployed on the ColdFusion server.

Returns

Structured metadata information: for ColdFusion components (CFCs) and user defined functions (UDFs), a structure; for query objects, an array of structures.

Category

System functions

Function syntax

GetMetaData(object)

See also

CreateObject, QueryAddColumn, QueryNew

History

ColdFusion MX 7: Added support for getting query object metadata.

ColdFusion MX: Added this function.

Parameters

Parameter | Description
object | A ColdFusion component, user-defined function, or query object. Within a CFC, the parameter can also specify the This scope.

Usage

This function provides information about application data, and lets applications dynamically determine the structure of an object and how to use it. This function is useful for CFCs and query objects. The metadata for a CFC includes information on the component and its functions, arguments, and properties. The getMetaData function also returns metadata for user-defined functions that not part of CFCs.

The following table lists the data returned by the function for supported object types:

Object | Field | Description
Component |  | A structure containing the following fields:
 | displayname | Value of the cfcomponent tag displayname attribute, if any.
 | extends | Metadata for the component’s ancestor component. Components that do not explicitly extend another component extend the WEB-INF.cftags.component.
 | functions | Array of metadata structures for the component’s functions.
 | hint | Value of the cfcomponent tag displayname attribute, if any.
 | name | Component name, including the period-delimited path from a component search root such as the web root or a directory specified in the administrator Custom Tag Paths page.
 | output | Value of the cfcomponent tag output attribute, if any
 | path | Absolute path to the component.
 | properties | Array of structures containing metadata specified by the component’s cfproperty tags, if any.
 | type | Always, component.
 | userMetadata | User-specified attributes in the cfcomponent tag
Function |  | A structure containing the following fields.
 | access | Value of the cffunction tag access attribute, if any.
 | displayname | Value of the cffunction tag displayname attribute, if any.
 | hint | Value of the cffunction tag hint attribute, if any.
 | name | Function name.
 | output | Value of the cffunction tag output attribute, if any.
 | parameters | Array of structures containing metadata for the function parameters.
 | returntype | Value of the cffunction tag returntype attribute, if any.
 | roles | Value of the cffunction tag output attribute, if any.
 | userMetadata | User-specified attributes in the cffunction tag.
Parameter or Property |  | A structure containing the following fields:
 | default | Value of the cfargument or cfproperty tag default attribute, if any.
 | displayname | Value of the cfargument or cfproperty tag displayname attribute, if any.
 | hint | Value of the cfargument or cfproperty tag hint attribute, if any.
 | name | Function parameter or CFC propery name.
 | required | Value of the cfargument or cfproperty tag required attribute, if any.
 | type | Value of the cfargument or cfproperty tag type attribute, if any.
 | userMetadata | User-specified attributes in the argument tag.
Query |  | An array of structures containing the following elements:
 | IsCaseSensitive | Boolean value indicating whether character data must be case correct.
 | Name | The column name.
 | TypeName | The SQL data type (Omitted if the query object is created with QueryNew without specifying types.)

Note: Use the This scope to access component metadata inside the CFC. The This scope is available at runtime in the component body and in the CFC methods. It is used to read and write variables that are present during the life of the component.

For more information, see Using introspection to get information about components in Building and Using ColdFusion Components in ColdFusion MX Developer’s Guide.

Example

The following example uses the cfdump tag to display metadata for the utilities CFC that is used by the ColdFusion component browser. It also displays the names and data types of the fields in the cfdocexamples database Employees table.

<!--- Create an instance of the Component Explorer utilities CFC.
        and get its metadata --->
<cfscript>
componentutils = createObject("component", "cfide.componentutils.utils");
utilmetadata = getMetaData(componentutils);
</cfscript>

<h4>Metadata for the CFC component utilities</h4>
<cfdump var="#utilmetadata#">

<!--- use GetMetadata to get the names and data types of the fields in the
        cfdocexamples Employees table --->
<cfquery name="getemployees" datasource="cfdocexamples">
SELECT      *
FROM         Employees
</cfquery>
<cfset employeemeta=getMetaData(getemployees)>

<h4>The Employees table has the following columns</h4>
<cfloop index="i" from="1" to="#arrayLen(employeemeta)#">
    <cfoutput>
        #employeemeta[i].name# #employeemeta[i].TypeName# #employeemeta[i].isCaseSensitive#<br>
    </cfoutput>
</cfloop>


GetMetricData

Description

Gets server performance metrics.

Returns

ColdFusion structure that contains metric data, depending on the mode value.

Category

System functions

Function syntax

GetMetricData(mode)

History

ColdFusion MX: Deprecated the cachepops parameter. It might not work, and it might cause an error, in later releases.

Parameters

Parameter | Option | Description
mode | perf_monitor | Returns internal data, in a structure. To receive data, you must enable PerfMonitor in ColdFusion Administrator before executing the function. On Windows, this data is otherwise displayed in the Windows PerfMonitor.
 | simple_load | Returns an integer value that is computed from the state of the server's internal queues. Indicates the overall server load.
 | prev_req_time | Returns the time, in milliseconds, that it took the server to process the previous request.
 | avg_req_time | Returns the average time, in milliseconds, that it takes the server to process a request. Changing the setting to 0 prevents the server from calculating the average and removes overhead associated with gathering data. The default value is 120 seconds.

Usage

If mode = "perf_monitor", the function returns a structure with these data fields:

Field | Description
InstanceName | The name of the ColdFusion server. The default value is cfserver.
PageHits | Number of HTTP requests received since ColdFusion MX was started.
ReqQueued | Number of HTTP requests in the staging queue, waiting for processing.
DBHits | Number of database requests since the server was started.
ReqRunning | Number of HTTP requests currently running. In the ColdFusion Administrator, you can set the maximum number of requests that run concurrently.
ReqTimedOut | Number of HTTP requests that timed out while in the staging queue or during processing.
BytesIn | Number of bytes in HTTP requests to ColdFusion MX.
BytesOut | Number of bytes in HTTP responses from ColdFusion MX.
AvgQueueTime | For the last two HTTP requests (current and previous), the average length of time the request waited in the staging queue.
AvgReqTime | For the last two HTTP requests (current and previous), the average length of time the server required to process the request
AvgDBTime | For the last two HTTP requests (current and previous), the average length of time the server took to process CFQueries in the request.
cachepops | This parameter is deprecated. ColdFusion automatically sets its value to -1.

Example

<!--- This example gets and displays metric data from Windows NT PerfMonitor --->
<cfset pmData = GetMetricData( "PERF_MONITOR" ) >
<cfoutput>
    Current PerfMonitor data is: <p>
    InstanceName:	#pmData.InstanceName# <p>
    PageHits:		#pmData.PageHits# <p>
    ReqQueued:		 #pmData.ReqQueued# <p>
    DBHits:	 #pmData.DBHits# <p>
    ReqRunning:		 #pmData.ReqRunning# <p>
    ReqTimedOut: #pmData.ReqTimedOut# <p>
    BytesIn:		 #pmData.BytesIn# <p>
    BytesOut:		 #pmData.BytesOut# <p>
    AvgQueueTime: #pmData.AvgQueueTime# <p>
    AvgReqTime:		 #pmData.AvgReqTime# <p>
    AvgDBTime:		 #pmData.AvgDBTime# <p>
</cfoutput>


GetPageContext

Description

Gets the current ColdFusion MX PageContext object that provides access to page attributes and configuration, request, and response objects.

Returns

The current ColdFusion MX Java PageContext Java object.

Category

System functions

Function syntax

GetPageContext()

History

ColdFusion MX: Added this function.

Usage

The ColdFusion MX PageContext class is a wrapper class for the Java PageContext object that can resolve scopes and perform case-insensitive variable lookups.

The PageContext object exposes fields and methods that can be useful in J2EE integration. It includes the include and forward methods that provide the equivalent of the corresponding standard JSP tags. You use these methods to call JSP pages and servlets. For example, you use the following code in CFScript to include the JSP page hello.jsp and pass it a name parameter:

GetPageContext().include("hello.jsp?name=Bobby"); ===

When you use GetPageContext to include a JSP page in a CFML page on WebLogic, you may need to flush the output of the CFML page with cfflush before calling the JSP page. Otherwise, the ColdFusion output appears after the JSP output.

For more information, see your Java Server Pages (JSP) documentation.

Example

<!--- this example shows using the page context to set a page
variable and access the language of the current locale --->
<cfset pc = GetPageContext()>

<cfset pc.setAttribute("name","John Doe")>
<cfoutput>name: #variables.name#<br></cfoutput>

<cfoutput>Language of the current locale is
#pc.getRequest().getLocale().getDisplayLanguage()#</cfoutput>>.


GetProfileSections

Description

Gets all the sections of an initialization file.

An initialization file assigns values to configuration variables, also known as entries, that are set when the system boots, the operating system comes up, or an application starts. An initialization file has the suffix INI; for example, boot.ini, Win32.ini.

Returns

An initialization file, as a struct whose format is as follows:

  • Each initialization file section name is a key in the struct
  • Each list of entries in a section of an initialization file is a value in the struct

If there is no value, returns an empty string.

Category

System functions

Function syntax

GetProfileSections(iniFile)

See also

GetProfileString, SetProfileString

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
iniFile | Absolute path (drive, directory, filename, extension) of initialization file; for example, C:\boot.ini


GetProfileString

Description

Gets an initialization file entry.

An initialization file assigns values to configuration variables, also known as entries, that are set when the system boots, the operating system comes up, or an application starts. An initialization file has the suffix INI; for example, boot.ini, Win32.ini.

Returns

An entry in an initialization file, as a string. If there is no value, returns an empty string.

Category

System functions

Function syntax

GetProfileString(iniPath, section, entry)

See also

GetProfileSections, GetProfileString, SetProfileString

Parameters

Parameter | Description
iniPath | Absolute path (drive, directory, filename, extension) of initialization file; for example, C:\boot.ini
section | Section of initialization file from which to extract information
entry | Name of value to get

Example

<h3>GetProfileString Example</h3>
Uses GetProfileString to get the value of timeout in an initialization file. Enter
the full path of your initialization file, and submit the form.
<!--- If the form was submitted, it gets the initialization path and timeout value specified in the form --->
<cfif Isdefined("Form.Submit")>
    <cfset IniPath = FORM.iniPath>
    <cfset Section = "boot loader">
    <cfset timeout = GetProfileString(IniPath, Section, "timeout")>
    <h4>Boot Loader</h4>
    <!--- If no entry in an initialization file, nothing displays --->
    <p>Timeout is set to: <cfoutput>#timeout#</cfoutput>.</p>
</cfif>
<form action = "getprofilestring.cfm">
<table cellspacing = "2" cellpadding = "2" border = "0">
    <tr>
         <td>Full Path of Init File</td>
         <td><input type = "Text" name = "IniPath" value = "C:\myboot.ini">
        </td>
    </tr>
    <tr>
     <td><input type = "Submit" name = "Submit" value = "Submit"></td>
     <td></td>
    </tr></table>
</form>


GetSOAPRequest

Description

Returns an XML object that contains the entire SOAP request. Usually called from within a web service CFC.

Returns

An XML object that contains the entire SOAP request.

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

GetSOAPRequest()

See also

AddSOAPRequestHeader, AddSOAPResponseHeader, GetSOAPRequestHeader, GetSOAPResponse, GetSOAPResponseHeader, IsSOAPRequest; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
webservice | Optional. A webservice object as returned from the cfobject tag or the CreateObject function. Required if the function is called from the client.

Usage

Call this function to obtain a web service request object after the web service has been invoked. If you call this function from outside a web service CFC without the webservice parameter, it throws the following expression error:

Unable to use getSOAPRequest: not processing a web service request.

If you call this function from within a web service CFC, you can omit the webservice argument. The function executes against the request that it is currently processing.

You can use CFML XML functions to examine the returned XML object.

Example

This example makes a request to execute the echo_me function of the headerservice.cfc web service. For information on implementing the headerservice.cfc web service and also to see the echo_me function and the content of the web service CFC, see the example for either the AddSOAPResponseHeader function or the GetSOAPRequestHeader function.

<!--- Note that you might need to modify the URL in the CreateObject function
to match your server and the location of the headerservice.cfc file if it is
different than shown here.
Note, too, that getSOAPRequest is called from the client here, whereas often it
would be called from within the web service CFC. --->

<cfscript>
    ws = CreateObject("webservice",
        "http://localhost/soapheaders/headerservice.cfc?WSDL");
    ws.echo_me("hello world");
    req = getSOAPRequest(ws);
</cfscript>
<cfdump var="#req#">


GetSOAPRequestHeader

Description

Obtains a SOAP request header. Call only from within a CFC web service function that is processing a request as a SOAP web service.

Returns

A SOAP request header.

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

GetSOAPRequestHeader(namespace, name [, asXML])

See also

AddSOAPRequestHeader, AddSOAPResponseHeader, GetSOAPRequest, GetSOAPResponse, GetSOAPResponseHeader, IsSOAPRequest; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
namespace | A String that is the namespace for the header.
name | A String that is the name of the header.
asXML | If True, the header is returned as a CFML XML object; if False (default), the header is returned as a Java object.

Usage

If you specify False for the asXML parameter, ColdFusion first attempts to retrieve the header using the data type specified in the header’s xsi:type attribute. If the xsi:type attribute is not available, ColdFusion attempts to retrieve the header as a string. If you specify True for the asXML parameter, ColdFusion retrieves the header as raw XML.

This function throws an error if it is invoked in a context that is not a web service request. Use the IsSOAPRequest function to determine whether the CFC is running as a web service.

Example

This example creates a CFC web service that illustrates the operation of the GetSOAPRequestHeader function and also provides a web service that illustrates the operation of other ColdFusion SOAP functions.

Save the following code as headerservice.cfc in a folder called soapheaders under your web root. Test its operation, and specifically the operation of the GetSOAPRequestHeader function, by executing the examples that invoke this web service. For example, see the example for AddSOAPRequestHeader.

<h3>GetSOAPRequestHeader Example</h3>
<cfcomponent displayName="tester" hint="Test for SOAP headers">

<cffunction name="echo_me"
            access="remote"
            output="false"
            returntype="string"
            displayname="Echo Test" hint="Header test">

  <cfargument name="in_here" required="true" type="string">

<cfset isSOAP = isSOAPRequest()>
<cfif isSOAP>

    <!--- Get the first header as a string and as XML --->
    <cfset username = getSOAPRequestHeader("http://mynamespace/", "username")>
    <cfset return = "The service saw username: " & username>
    <cfset xmlusername = getSOAPRequestHeader("http://mynamespace/", "username", "TRUE")>
    <cfset return = return & "<br> as XML: " & xmlusername>

    <!--- Get the second header as a string and as XML --->
    <cfset password = getSOAPRequestHeader("http://mynamespace/", "password")>
    <cfset return = return & "The service saw password: " & password>
    <cfset xmlpassword = getSOAPRequestHeader("http://mynamespace/", "password", "TRUE")>
    <cfset return = return & "<br> as XML: " & xmlpassword>

    <!--- Add a header as a string --->
    <cfset addSOAPResponseHeader("http://www.tomj.org/myns", "returnheader", "AUTHORIZED VALUE", false)>

    <!--- Add a second header using a CFML XML value --->
    <cfset doc = XmlNew()>
    <cfset x = XmlElemNew(doc, "http://www.tomj.org/myns", "returnheader2")>
    <cfset x.XmlText = "hey man, here I am in XML">
    <cfset  x.XmlAttributes["xsi:type"] = "xsd:string">
    <cfset tmp = addSOAPResponseHeader("ignoredNameSpace", "ignoredName", x)>

<cfelse>
    <!--- Add a header as a string - Must generate error!
    <cfset addSOAPResponseHeader("http://www.tomj.org/myns", "returnheader", "AUTHORIZED VALUE", false)>
    --->
    <cfset return = "Not invoked as a web service">
</cfif>

<cfreturn return>

</cffunction>

</cfcomponent>


GetSOAPResponse

Description

Returns an XML object that contains the entire SOAP response after invoking a web service.

Returns

An XML object that contains the entire SOAP response.

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

GetSOAPResponse(webservice)

See also

AddSOAPRequestHeader, AddSOAPResponseHeader, GetSOAPRequest, GetSOAPRequestHeader, GetSOAPResponseHeader, IsSOAPRequest; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
webservice | A webservice object as returned from the cfobject tag or the CreateObject function.

Usage

You must first invoke the web service before attempting to get the response. You can use CFML XML functions to examine the XML response.

Example

This example makes a request to execute the echo_me function of the headerservice.cfc web service. Following the request, the example calls the GetSOAPResponse function to get the SOAP response, and then calls cfdump to display its content.

for information on implementing the headerservice.cfc web service and also to see the echo_me function and the content of the web service CFC, see the example for either the AddSOAPResponseHeader function or the GetSOAPRequestHeader function.

<!--- Note that you might need to modify the URL in the CreateObject function
to match your server and the location of the headerservice.cfc file if it is
different than shown here. --->

<cfscript>
    ws = CreateObject("webservice",
        "http://localhost/soapheaders/headerservice.cfc?WSDL");
    ws.echo_me("hello world");
    resp = getSOAPResponse(ws);
</cfscript>
<cfdump var="#resp#">


GetSOAPResponseHeader

Description

Returns a SOAP response header. Call this function from within code that is invoking a web service after making a web service request.

Returns

A SOAP response header.

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

GetSOAPResponseHeader(webservice, namespace, name [, asXML])

See also

AddSOAPRequestHeader, AddSOAPResponseHeader, GetSOAPRequest, GetSOAPRequestHeader, GetSOAPResponse, IsSOAPRequest; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
webservice | A webservice object as returned from the cfobject tag or the CreateObject function.
namespace | A String that is the namespace for the header.
name | A String that is the name of the SOAP header.
asXML | If True, the header is returned as a CFML XML object. If False (default), the header is returned as a Java object.

Usage

If you specify false for the asXML parameter, ColdFusion first attempts to retrieve the header using the data type specified in the header’s xsi:type attribute. If the xsi:type attribute is not available, ColdFusion attempts to retrieve the header as a string. If you specify True for the asXML parameter, ColdFusion retrieves the header as raw XML.

Used within CFML code by a consumer of a web service after it calls the web service with cfinvoke.

Example

There are two parts to this example. The first part is the web service CFC that this function (as well as the other ColdFusion SOAP functions) uses to demonstrate its interaction with a web service. To implement the web service for this function, see the example for either the AddSOAPResponseHeader function or the GetSOAPRequestHeader function.

Execute the following example to see how the GetSOAPResponseHeader function operates:

<!--- Note that you might need to modify the URL in the CreateObject function
to match your server and the location of the headerservice.cfc file if it is
different than shown here. Likewise for the cfinvoke tag at the end --->

<h3>GetSOAPResponseHeader Example</h3>
<cfscript>
 // Create the web service object
 ws = CreateObject("webservice", "http://localhost/soapheaders/headerservice.cfc?WSDL");

 // Set the username header as a string
 addSOAPRequestHeader(ws, "http://mynamespace/", "username", "tom", false);

 // Set the password header as a CFML XML object
 doc = XmlNew();
 doc.password = XmlElemNew(doc, "http://mynamespace/", "password");
 doc.password.XmlText = "My Voice is my Password";
 doc.password.XmlAttributes["xsi:type"] = "xsd:string";
 addSOAPRequestHeader(ws, "ignoredNameSpace", "ignoredName", doc);

 // Invoke the web service operation
 ret = ws.echo_me("argument");

 // Get the first header as an object (string) and as XML
 header = getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader");
 XMLheader = getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader", true);

 // Get the second header as an object (string) and as XML
 header2 =  getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader2");
 XMLheader2 = getSOAPResponseHeader(ws, "http://www.tomj.org/myns", "returnheader2", true);
</cfscript>
<hr>
<cfoutput>
Soap Header value: #HTMLCodeFormat(header)#<br>
Soap Header XML value: #HTMLCodeFormat(XMLheader)#<br>
Soap Header 2 value: #HTMLCodeFormat(header2)#<br>
Soap Header 2 XML value: #HTMLCodeFormat(XMLheader2)#<br>
Return value: #HTMLCodeFormat(ret)#<br>
</cfoutput>
<hr>

<cfinvoke component="soapheaders.headerservice" method="echo_me" returnvariable="ret" in_here="hi">
</cfinvoke>
<cfoutput>Cfinvoke returned: #ret#</cfoutput>


GetTempDirectory

Description

Gets the path of the directory that ColdFusion uses for temporary files. The directory depends on the account under which ColdFusion is running and other factors. Before using this function in an application, test to determine the directory it returns under your account.

Returns

The absolute pathname of a directory, including a trailing slash, as a string.

Category

System functions

Function syntax

GetTempDirectory()

See also

GetTempFile

History

ColdFusion MX: Changed behavior: on Windows, this function now returns the temporary directory of the embedded Java application server. On other platforms, it returns the temporary directory of the operating system.

Example

<h3>GetTempDirectory Example</h3>

<p>The temporary directory for this ColdFusion server is
<cfoutput>#GetTempDirectory()#</cfoutput>.
<p>We have created a temporary file called:
<cfoutput>#GetTempFile(GetTempDirectory(),"testFile")#</cfoutput>


GetTempFile

Description

Creates a temporary file in a directory whose name starts with (at most) the first three characters of prefix.

Returns

Name of a temporary file, as a string.

Category

System functions

Function syntax

GetTempFile(dir, prefix)

See also

GetTempDirectory

Parameters

Parameter | Description
dir | Directory name
prefix | Prefix of a temporary file to create in the dir directory

Example

<h3>GetTempFile Example</h3>
<p>The temporary directory for this ColdFusion Server is
<cfoutput>#GetTempDirectory()#</cfoutput>.
<p>We have created a temporary file called:
<cfoutput>#GetTempFile(GetTempDirectory(),"testFile")#</cfoutput>


GetTemplatePath

Description

This function is deprecated. Use the GetBaseTemplatePath function instead.

Gets the absolute path of an application’s base page.

History

ColdFusion MX: Deprecated this function. It might not work, and it might cause an error, in later releases.


GetTickCount

Description

Returns the current value of an internal millisecond timer.

Returns

A string representation of the system time, in milliseconds.

Category

Date and time functions, System functions

Function syntax

GetTickCount()

Usage

This function is useful for timing CFML code segments or other page processing elements. The value of the counter has no meaning. To generate useful timing values, take the difference between the results of two GetTickCount calls.

Example

<!--- Setup timing test --->
<cfset iterationCount = 1000>
<!--- Time an empty loop with this many iterations --->
<cfset tickBegin = GetTickCount()>
<cfloop Index = i From = 1 To = #iterationCount#></cfloop>
<cfset tickEnd = GetTickCount()>
<cfset loopTime = tickEnd - tickBegin>

<!--- Report --->
<cfoutput>Loop time (#iterationCount# iterations) was: #loopTime#
     milliseconds</cfoutput>


GetTimeZoneInfo

Description

Gets local time zone information for the computer on which it is called, relative to Universal Time Coordinated (UTC). UTC is the mean solar time of the meridian of Greenwich, England, used as the basis for calculating standard time throughout the world.

ColdFusion stores date and time values as date-time objects: real numbers on a universal time line. It converts an object to a time zone when it formats an object; it converts a date/time value from a time zone to a real number when it parses a value.

Returns

Structure that contains these elements and keys:

  • utcTotalOffset: offset of local time, in seconds, from UTC
    • A plus sign indicates a time zone west of UTC (such as a zone in North America)
    • A minus sign indicates a time zone east of UTC (such as a zone in Germany)
  • utcHourOffset: offset, in hours of local time, from UTC
  • utcMinuteOffset: offset, in minutes, beyond the hours offset. For North America, this is 0. For countries that are not exactly on the hour offset, the number is between 0 and 60. For example, standard time in Adelaide, Australia is offset 9 hours and 30 minutes from UTC.
  • isDSTOn: True, if Daylight Savings Time (DST) is on in the host; False, otherwise

Category

Date and time functions, International functions

Function syntax

GetTimeZoneInfo()

See also

DateConvert, CreateDateTime, DatePart

Example

<h3>GetTimeZoneInfo Example</h3>
<!--- This example shows the use of GetTimeZoneInfo --->
<cfoutput>
The local date and time are #now()#.
</cfoutput>

<cfset info = GetTimeZoneInfo()>
<cfoutput>
<p>Total offset in seconds is #info.utcTotalOffset#.</p>
<p>Offset in hours is #info.utcHourOffset#.</p>
<p>Offset in minutes minus the offset in hours is
    #info.utcMinuteOffset#.</p>
<p>Is Daylight Savings Time in effect? #info.isDSTOn#.</p>
</cfoutput>


GetToken

Description

Determines whether a token of the list in the delimiters parameter is present in a string.

Returns

The token found at position index of the string, as a string. If index is greater than the number of tokens in the string, returns an empty string.

Category

String functions

Function syntax

GetToken(string, index [, delimiters ])

See also

Left, Right, Mid, SpanExcluding, SpanIncluding

Parameters

Parameter

Description

string

A string or a variable that contains one. String in which to search.

index

Positive integer or a variable that contains one. The position of a token.

delimiters

A string or a variable that contains one. A delimited list of delimiters. Elements may consist of multiple characters.

Default list of delimiters: space character, tab character, newline character; or their codes: "chr(32)", "chr(9)", chr(10).

Default list delimiter: comma character.

Usage

The following examples show how this function works.

Example A: Consider the following code:

GetToken("red,blue:;red,black,tan:;red,pink,brown:;red,three", 2, ":;")

This function call requests element number 2 from the string, using the delimiter ":;". The output is as follows:

red,black,tan

Example B: Consider the following code:

<cfset mystring = "four,"
& #chr(32)# & #chr(9)# & #chr(10)#
& ",five, nine,zero:;"
& #chr(10)#
& "nine,ten:, eleven:;twelve:;thirteen,"
& #chr(32)# & #chr(9)# & #chr(10)#
& ",four">
<cfoutput>
#mystring#<br><br>
</cfoutput>

The output is as follows:

four,
,five, nine,zero:;
nine,ten:, eleven:;twelve:;thirteen,
,four

The GetToken function recognizes explicit spaces, tabs, or newline characters as the parameter delimiters (To specify a space character, the code is chr(32); a tab character, chr(9); and a newline character, chr(10).)

In the example string mystring, there is:

  • A forced space between the substrings "four," and ",five"
  • A literal space between "five," and "nine"
  • A literal space between "ten:," and "eleven,"
  • A forced space between "thirteen," and ",four"

In the following call against mystring, no spaces are specified in delimiters (it is omitted), so the function uses the space character as the string delimiter:

<br>
<cfoutput>
GetToken(mystring, 3) is : #GetToken(mystring, 3)#
</cfoutput><br>

The output of this code is as follows:

GetToken(mystring, 3) is : nine,zero:;

The function finds the third delimiter, and returns the substring just before it that is between the second and third delimiter. This substring is "nine,zero:;".

Example C: Consider the following code:

<cfset mystring2 = "four,"
&#chr(9)# & #chr(10)#
& ",five,nine,zero:;"
& #chr(10)#
& "nine,ten:,eleven:;twelve:;thirteen,"
& #chr(9)# & #chr(10)# & ",four">
<cfoutput>
#mystring2#<br>
</cfoutput>

The output is as follows:

four,
,five,nine,zero:;
nine,ten:,eleven:;twelve:;thirteen,
,four

The following is a call against mystring2:

<cfoutput>
GetToken(mystring2, 2) is : #GetToken(mystring2, 2)#
</cfoutput>

The output is as follows:

GetToken(mystring2, 2) is : ,five,nine,zero:;

The function finds the second delimiter, and returns the substring just before it that is between the first and second delimiter. This substring is ",five,nine,zero:;".

Example

<h3>GetToken Example</h3>
<cfif IsDefined("FORM.yourString")>
<!--- set delimiter --->
<cfif FORM.yourDelimiter is not "">
        <cfset yourDelimiter = FORM.yourDelimiter>
    <cfelse>
        <cfset yourDelimiter = " ">
</cfif>
<!--- check whether number of elements in list is greater than or
equal to the element sought to return --->
<cfif ListLen(FORM.yourString, yourDelimiter) GTE FORM.returnElement>
    <cfoutput>
    <p>Element #FORM.ReturnElement# in #FORM.yourString#,
    delimited by "#yourDelimiter#"
    <br>is:#GetToken(FORM.yourString, FORM.returnElement, yourDelimiter)#
    </cfoutput>
...


Hash

Description

Converts a variable-length string to a fixed-length string that can act as a "fingerprint" or unique identifier for the original string. It is not possible to convert the hash result back to the source string.

Returns

A string.

Category

Conversion functions, Security functions, String functions

Function syntax

Hash(string[, algorithm[, encoding]] )

History

ColdFusion MX 7: Added the algorithm and encoding parameters.

Parameters

Parameter

Description

string

String to hash.

algorithm

(Optional) The algorithm to use to hash the string. ColdFusion MX installs a cryptography library with the following algorithms:

  • CFMX_COMPAT: Generates a hash string identical to that generated by ColdFusion MX and ColdFusion MX 6.1 (default).
  • MD5: (Default) Generates a 32-character, hexadecimal string, using the MD5 algorithm (The algorithm used in ColdFusion MX and prior releases).
  • SHA: Generates a 28-character string using the Secure Hash Standard SHA-1 algorithm specified by Nation Institute of Standards and Technology (NIST) FIPS-180-2.
  • SHA-256: Generates a 44-character string using the SHA-256 algorithm specified by FIPS-180-2.
  • SHA-384: Generates a 64-character string using the SHA-384 algorithm specified by FIPS-180-2.
  • SHA-512: Generates an 88-character string using the SHA-1 algorithm specified by FIPS-180-2.

If you install a security provider with additional cryptography algorithms, you can also specify any of its hashing algorithms.

encoding

(Optional; to use this attribute you must also specify the algorithm parameter) A string specifying the encoding to use when converting the string to byte data used by the hash algorithm. Must be a character encoding name recognized by the Java runtime. The default value is the value specified by the defaultCharset entry in the neo-runtime.xml file, which is normally UTF-8. Ignored when using the CFMX_COMPAT algorithm.

Usage

The result of this function is useful for comparison and validation. For example, you can store the hash of a password in a database without exposing the password. You can check the validity of the password by hashing the entered password and comparing the result with the hashed password in the database.

ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

The encoding attrbute is normally not required. It provides a mechanism for generating identical hash values on systems with different default encodings. ColdFusion uses a default encoding of UTF-8 unless you modify the defaultCharset entry in the neo-runtime.xml file.

Example

The following example lets you enter a password and compares the hashed password with a hash value saved in the SecureData table of the cfdocexamples database. This table has the following three entries:

User ID | Password
12 | abc
14 | def
15 | ghi
<h3>Hash Example</h3> <!--- Do the following if the form is submitted. ---> <cfif IsDefined("Form.UserID")> <!--- query the data base. ---> <cfquery name = "CheckPerson" datasource = "cfdocexamples"> SELECT PasswordHash FROM SecureData WHERE UserID = <cfqueryparam value = "#Form.userID#" cfsqltype = "CF_SQL_CHARVAR"> </cfquery> <!--- Compare query PasswordHash field and the hashed form password and display the results. ---> <cfoutput> <cfif Hash(Form.password, "SHA") is not checkperson.passwordHash> User ID #Form.userID# or password is not valid. Try again. <cfelse> Password is valid for User ID #Form.userID#. </cfif> </cfoutput> </cfif> <!--- Form for entering ID and password. ---> <form action="#CGI.SCRIPT_NAME#" method="post"> <b>User ID: </b> <input type = "text" name="UserID" ><br> <b>Password: </b> <input type = "text" name="password" ><br><br> <input type = "Submit" value = "Encrypt my String"> </form>


Hour

Description

Gets the current hour of the day.

Returns

Ordinal value of the hour, in the range 0 - 23.

Category

Date and time functions

Function syntax

Hour(date)

See also

DatePart, Minute, Second

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Example

<!--- This example shows the use of Hour, Minute, and Second --->
<h3>Hour Example</h3>
<cfoutput>
The time is currently #TimeFormat(Now())#.
We are in hour #Hour(Now())#, Minute #Minute(Now())#
and Second #Second(Now())# of the day.
</cfoutput>


HTMLCodeFormat

Description

Replaces special characters in a string with their HTML-escaped equivalents and inserts <pre> and </pre> tags at the beginning and end of the string.

Returns

HTML-escaped string string, enclosed in <pre> and </pre> tags. Return characters are removed; line feed characters are preserved. Characters with special meanings in HTML are converted to HTML character entities such as &gt;.

Category

Display and formatting functions

Function syntax

HTMLCodeFormat(string [, version ])

See also

HTMLEditFormat

Parameters

Parameter

Description

string

A string or a variable that contains one.

version

HTML version to use; currently ignored.

  • -1: The latest implementation of HTML
  • 2.0: HTML 2.0 (Default)
  • 3.2: HTML 3.2

Usage

This function converts the following characters to HTML character entities:

Text character | Encoding
< | &lt;
> | &gt;
& | &amp;
" | &quot;

This function typically increases the length of a string. This can cause unpredictable results when performing certain string functions (Left, Right, and Mid, for example) against the expanded string.

The only difference between this function and HTMLEditFormat is that HTMLEditFormat does not surround the text in an HTML pre tag.

Example

<!--- This example shows the effects of HTMLCodeFormat and
      HTMLEditFormat. View it in your browser, then View it
      using your browser's the View Source command. --->
<cfset testString="This is a test
        & this is another
<This text is in angle brackets>

Previous line was blank!!!">

<cfoutput>
    <h3>The text without processing</h3>
    #testString#<br>
    <h3>Using HTMLCodeFormat</h3>
    #HTMLCodeFormat(testString)#
    <h3>Using HTMLEditFormat</h3>
    #HTMLEditFormat(testString)#
</cfoutput>


HTMLEditFormat

Description

Replaces special characters in a string with their HTML-escaped equivalents.

Returns

HTML-escaped string string. Return characters are removed; line feed characters are preserved. Characters with special meanings in HTML are converted to HTML character entities such as &gt;.

Category

Display and formatting functions

Function syntax

HTMLEditFormat(string [, version ])

See also

HTMLCodeFormat , cfapplication

Parameters

Parameter

Description

string

A string or a variable that contains one.

version

HTML version to use; currently ignored.

  • -1: The latest implementation of HTML
  • 2.0: HTML 2.0 (Default)
  • 3.2: HTML 3.2

Usage

This function converts the following characters to HTML character entities:

Text character | Encoding
< | &lt;
> | &gt;
& | &amp;
" | &quot;

This function can usefed to help protect ColdFusion pages that return user-provided data to the client browser from cross-site scripting attacks. However, the scriptprotect attribute of the cfapplication tag or the equivalent This.scriptProtect variable setting in Application.cfc can be preferable in most instances, because you only need to specify it once for an application.

This function typically increases the length of a string. This can cause unpredictable results when performing certain string functions (Left, Right, and Mid, for example) against the expanded string.

The only difference between this function and HTMLCodeFormat is that HTMLCodeFormat surrounds the text in an HTML pre tag.

Example

<!--- This example shows the effects of HTMLCodeFormat and
      HTMLEditFormat. View it in your browser, then View it
      using your browser's the View Source command. --->
<cfset testString="This is a test
        & this is another
<This text is in angle brackets>

Previous line was blank!!!">

<cfoutput>
    <h3>The text without processing</h3>
    #testString#<br>
    <h3>Using HTMLCodeFormat</h3>
    #HTMLCodeFormat(testString)#
    <h3>Using HTMLEditFormat</h3>
    #HTMLEditFormat(testString)#
</cfoutput>


IIf

Description

Evaluates a Boolean conditional dynamic expression. Depending on whether the expression is true or false, dynamically evaluates one of two string expressions and returns the result. This function is convenient for incorporating a cfif tag in-line in HTML.

For general conditional processing, see cfif. For error handling, see cftry. For more information, see ColdFusion MX Developer’s Guide.

Returns

If result is True, returns the value of Evaluate(string_expression1); otherwise, returns the value of Evaluate(string_expression2).

Category

Decision functions, Dynamic evaluation functions

Function syntax

IIf(condition, string_expression1, string_expression2)

See also

DE, Evaluate

Parameters

Parameter | Description
condition | An expression that can be evaluated as a Boolean.
string_expression1 | A string or a variable that contains one. Expression to evaluate and return if condition is True.
string_expression2 | A string or a variable that contains one. Expression to evaluate and return if condition is False.

Usage

The IIf function is a shortcut for the following construct:

<cfif condition>
    <cfset result = Evaluate(string_expression1)>
<cfelse>
    <cfset result = Evaluate(string_expression2)>
</cfif>

The expressions string_expression1 and string_expression2 must be string expressions, so that they are not evaluated immediately as the parameters of IIf. For example:

IIf(y is 0, DE("Error"), x/y)

If y = 0, this generates an error, because the third expression is the value of x/0 (invalid expression).

ColdFusion evaluates string_expression1 and string_expression2. To return the string itself, use the DE function.

Note: If you use number signs (#) in string_expression1 or string_expression2, ColdFusion evaluates the part of the expression in number signs first. If you misuse the number signs, you can cause unexpected results from the IIf function. For example, if you use number signs around the whole expression in string_expression1, and if there is an undefined variable in string_expression1, the function might fail, with the error 'Error Resolving Parameter,'

If a variable is undefined, ColdFusion throws an error when it processes this function. The following example shows this problem:

#IIf(IsDefined("Form.Deliver"), DE(Form.Deliver), DE("no"))#

This returns "Error resolving parameter FORM.DELIVER".

To avoid this problem, use the DE and Evaluate functions in code such as the following:

#IIf(IsDefined("Form.Deliver"), Evaluate(DE("Form.Deliver")), DE("no"))#

This returns "no"; ColdFusion does not throw an error.

In the following example, LocalVar is undefined; however, if you omit number signs around LocalVar, the code works properly:

<cfoutput>
    #IIf(IsDefined("LocalVar"), "LocalVar",
        DE("The variable is not defined."))#
</cfoutput>

The output is:

    The variable is not defined.

The number signs around LocalVar in the following code cause it to fail with the error message 'Error Resolving Parameter', because ColdFusion never evaluates the original condition IsDefined("LocalVar").

Here is another example:

<cfoutput>
#IIf(IsDefined("LocalVar"), DE("#LocalVar#"), DE("The variable is not defined."))#
</cfoutput>

The error message would be as follows:

    Error resolving parameter LOCALVAR

The DE function has no effect on the evaluation of LocalVar, because the number signs cause it to be evaluated immediately.

Example

<h3>IIf Function Example</h3>
<p>IIf evaluates a condition, and does an Evaluate on string
expression 1 or string expression 2 depending on the Boolean
outcome <I>(True: run expression 1; False: run expression 2)</I>.</p>
<p>The result of the expression
IIf( Hour(Now()) GTE 12,
    DE("It is afternoon or evening"),
    DE("It is morning"))
is:<br><b>
<cfoutput>
    #IIf( Hour(Now()) GTE 12,
DE("It is afternoon or evening"),
DE("It is morning"))#
</cfoutput>
</b>


IncrementValue

Description

Adds one to an integer.

Returns

The integer part of number, incremented by one.

Category

Mathematical functions

Function syntax

IncrementValue(number)

See also

DecrementValue

Parameters

Parameter | Description
number | Number to increment

Example

<h3>IncrementValue Example</h3>
<p>Returns the integer part of a number incremented by one.
<p>IncrementValue(0): <cfoutput>#IncrementValue(0)#</cfoutput>
<p>IncrementValue("1"): <cfoutput>#IncrementValue("1")#</cfoutput>
<p>IncrementValue(123.35): <cfoutput>#IncrementValue(123.35)#</cfoutput>


InputBaseN

Description

Converts string, using the base specified by radix, to an integer.

Returns

A number in the range 2-36, as a string.

Category

Mathematical functions

Function syntax

InputBaseN(string, radix)

See also

FormatBaseN

Parameters

Parameter | Description
string | A string or a variable that contains one. String that represents a number, in the base specified by radix.
radix | Base of the number represented by string, in the range 2--36.

Example

<h3>InputBaseN Example</h3>

<p>FormatBaseN converts a number to a string in the base specified by Radix.
<p>
<cfoutput>
<br>FormatBaseN(10,2): #FormatBaseN(10,2)#
<br>FormatBaseN(1024,16): #FormatBaseN(1024,16)#
<br>FormatBaseN(125,10): #FormatBaseN(125,10)#
<br>FormatBaseN(10.75,2): #FormatBaseN(10.75,2)#
</cfoutput>
<h3>InputBaseN Example</h3>
<p>InputBaseN returns the number obtained by converting a string,
using the base specified by Radix,.
<cfoutput>
<br>InputBaseN("1010",2): #InputBaseN("1010",2)#
<br>InputBaseN("3ff",16): #InputBaseN("3ff",16)#
<br>InputBaseN("125",10): #InputBaseN("125",10)#
<br>InputBaseN(1010,2): #InputBaseN(1010,2)#
</cfoutput>


Insert

Description

Inserts a substring in a string after a specified character position. If position = 0, prefixes the substring to the string.

Returns

A string.

Category

String functions

Function syntax

Insert(substring, string, position)

See also

RemoveChars, Len

Parameters

Parameter | Description
substring | A string or a variable that contains one. String to insert.
string | A string or a variable that contains one. String into which to insert substring.
position | Integer or variable; position in string after which to insert substring.

Example

<h3>Insert Example</h3>

<cfif IsDefined("FORM.myString")>
    <!--- if the position is longer than the length of the string, err --->
    <cfif FORM.insertPosition GT Len(MyString)>
        <cfoutput>
        <p>This string only has #Len(MyString)# characters; therefore,
you cannot insert the substring 		#FORM.mySubString# at position
#FORM.insertPosition#.
        </cfoutput>
    </cfif>
<cfelse>
    <cfoutput>
    <p>You inserted the substring #FORM.MySubstring# into the string
#FORM.MyString#, resulting in the following string:
<br>#Insert(FORM.MySubString, FORM.myString,
FORM.insertposition)#
    </cfoutput>
</cfif>


Int

Description

Calculates the closest integer that is smaller than number. For example, it returns 3 for Int(3.3) and for Int(3.7); it returns -4 for Int(-3.3) and for Int(-3.7).

Returns

An integer, as a string.

Category

Mathematical functions

Function syntax

Int(number)

See also

Ceiling, Fix, Round

Parameters

Parameter | Description
number | Real number to round down to an integer.

Example

<h3>Int Example</h3>
<p>Int returns the closest integer smaller than a number.

<p>Int(11.7) : <cfoutput>#Int(11.7)#</cfoutput>
<p>Int(-11.7) : <cfoutput>#Int(-11.7)#</cfoutput>
<p>Int(0) : <cfoutput>#Int(0)#</cfoutput>


IsArray

Description

Determines whether a value is an array.

Returns

True, if value is an array, or a query column object.

Category

Array functions, Decision functions

Function syntax

IsArray(value [, number ])

See also

Array functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed behavior: if the value parameter contains a reference to a query result column, this function now returns True. For example: isArray(MyQuery[’Column1’]) returns True. (In earlier releases, it returns False.)
  • Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
value | Variable or array name
number | Dimension; function tests whether the array has exactly this dimension

Usage

Use this function to determine whether a value is an array or query column. This function evaluates a Java array object, such as a vector object, as having one dimension.

Example

<h3>IsArray Example</h3>

<!--- Make an array --->
<cfset MyNewArray = ArrayNew(1)>
<!--- set some elements --->
<cfset MyNewArray[1] = "element one">
<cfset MyNewArray[2] = "element two">
<cfset MyNewArray[3] = "element three">
<!--- is it an array? --->
<cfoutput>
    <p>Is this an array? #IsArray(MyNewArray)#
    <p>It has #ArrayLen(MyNewArray)# elements.
    <p>Contents: #ArrayToList(MyNewArray)#
</cfoutput>


IsAuthenticated

Description

This function is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide.

History

ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later ColdFusion releases.


IsAuthorized

Description

This function is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later releases.


IsBinary

Description

Determines whether a value is stored as binary data.

Returns

True, if the value is binary; False, otherwise.

Category

Decision functions

Function syntax

IsBinary(value)

See also

ToBinary, ToBase64, IsNumeric, YesNoFormat

Parameters

Parameter | Description
value | Number or string

Example

<!--- Create a string of all ASCII characters (32-255)
     and concatenate them together. --->
<cfset charData ="">
<cfloop index="data" from="32" to="255">
    <cfset ch=chr(data)>
    <cfset charData=charData & ch>
</cfloop>

<b>The following string is the concatenation of all characters (32 to 255) from the ASCII table.</b><br><br>
<cfoutput>#htmleditformat(charData)#</cfoutput>
<br><br>
<!--- Create a Base 64 representation of this string. --->
<cfset data64=toBase64(charData)>
<!--- Convert string to binary. --->
<cfset binaryData=toBinary(data64)>
<!--- Check to see if it really is a binary value. --->
<cfif IsBinary(binaryData)>
    The binaryData variable is binary!<br>
</cfif>
<!--- Convert binary data back to Base 64. --->
<cfset another64=toBase64(binaryData)>
<cfif Not IsBinary(another64)>
    The another64 variable is NOT binary!<br>
</cfif>
<!--- Compare another64 with data64 to ensure that they are equal. --->
<cfif another64 eq data64>
    Base 64 representation of binary data is identical to the Base 64
    representation of string data.
<cfelse>
    <h3>Conversion error.</h3>
</cfif>


IsBoolean

Description

Determines whether a value can be converted to Boolean

Returns

True, if the parameter can be converted to Boolean; False, otherwise.

Category

Decision functions

Function syntax

IsBoolean(value)

See also

IsNumeric, IsValid, YesNoFormat

Parameters

Parameter | Description
value | Number or string

Example

<h3>IsBoolean Example</h3>

<cfif IsDefined("FORM.theTestValue")>
    <cfif IsBoolean(FORM.theTestValue)>
        <h3>The expression <cfoutput>#DE(FORM.theTestValue)#</cfoutput> is
Boolean</h3>
    <cfelse>
        <h3>The expression <cfoutput>#DE(FORM.theTestValue)#</cfoutput> is not Boolean</h3>
    </cfif>
</cfif>

<form action = "isBoolean.cfm">
<p>Enter an expression, and discover whether it can be evaluated to a
Boolean value.

<input type = "Text" name = "TheTestValue" value = "1">
<input type = "Submit" value = "Is it Boolean?" name = "">
</form>


IsCustomFunction

Description

Determines whether a name represents a custom function.

Returns

True, if name can be called as a custom function; False, otherwise.

Category

Decision functions

Function syntax

IsCustomFunction(name)

Parameters

Parameter | Description
name | Name of a custom function. Must not be in quotation marks. If not a defined variable or function name, ColdFusion generates an error.

Usage

The IsCustomFunction function returns True for any function that can be called as a custom function, including functions defined using CFScript function declarations and cffunction tags, and functions that are ColdFusion component methods. For CFC methods, you must first instantiate the component.

Note: To prevent undefined variable exceptions, always precede IsCustomFunction with an IsDefined test, as shown in the example.

Example

<h3>IsCustomFunction Example</h3>
<cfscript>
function realUDF() {
    return 1;
}
</cfscript>
<cfset X = 1>

<!--- Example that fails existence test --->
<cfif IsDefined("Foo") AND IsCustomFunction(Foo)>
    Foo is a UDF.<br>
</cfif>

<!--- Example that passes existence test but fails IsCustomFunction --->
<cfif IsDefined("X") AND IsCustomFunction(X)>
    X is a UDF.<br>
</cfif>

<!--- Example that passes both tests--->
<cfif IsDefined("realUDF") AND IsCustomFunction(realUDF)>
    realUDF is a function.<br>
</cfif>

<!--- Example using a CFC, defined in TestCFC.cfc--->
<cfobject component="TestCFC" name="myTestCFCobject">
<CFIF IsDefined("myTestCFCobject.testFunc") AND
        IsCustomFunction(myTestCFCobject.testFunc)>
    myTestCFCobject.testFunc is a function.
</CFIF>


IsDate

Description

Determines whether a string or Java object can be converted to a date/time value.

Returns

True, if string can be converted to a date/time value; False, otherwise. ColdFusion converts the Boolean return value to its string equivalent, "Yes" or "No."

Category

Date and time functions, Decision functions

Function syntax

IsDate(string)

See also

CreateDateTime, IsNumericDate, IsValid, LSDateFormat, LSIsDate, ParseDateTime

Parameters

Parameter | Description
string | A string or a variable that contains one.

Usage

This function checks against U.S. date formats only. For other date support, see LSDateFormat.

A date/time object falls in the range 100 AD–9999 AD.

Example

<h3>IsDate Example</h3>
<cfif IsDefined("FORM.theTestValue")>
    <cfif IsDate(FORM.theTestValue)>
    <h3>The string <cfoutput>#DE(FORM.theTestValue)#</cfoutput>
     is a valid date</h3>
    <cfelse>
    <h3>The string <cfoutput>#DE(FORM.theTestValue)#</cfoutput>
     is not a valid date</h3>
    </cfif>
</cfif>
<form action = "isDate.cfm">
<p>Enter a string, find whether it can be evaluated to a date value.
<p><input type = "Text" name = "TheTestValue" value = "<cfoutput>#Now()#
</cfoutput>">
<input type = "Submit" value = "Is it a Date?" name = "">
</form>


IsDebugMode

Description

Determines whether debugging output is enabled.

Returns

True, if debugging mode is set in the ColdFusion Administrator; False if debugging mode is disabled.

Category

Decision functions

Function syntax

IsDebugMode()

See also

cfsetting

Description

If debugging output is enabled in ColdFusion Administrator and has not been overridden by setting the cfsetting tag showDebugOutput attribute to No, the IsDebugMode function returns Yes; No, otherwise.

Example

<h3>IsDebugMode Example</h3>
<cfif IsDebugMode()>
 <h3>Debugging is set in the ColdFusion Administrator</h3>
<cfelse>
 <h3>Debugging is disabled</h3>
</cfif>


IsDefined

Description

Evaluates a string value to determine whether the variable named in it exists.

This function is an alternative to the ParameterExists function, which is deprecated.

Returns

True, if the variable is found, or, for a structure, if the specified key is defined; False, otherwise.

The return value is False for an array or structure element referenced using bracket notation. For example, IsDefined("myArray[3]") always returns False, even if the array element myArray[3] has a value.

Category

Decision functions

Function syntax

IsDefined("variable_name")

See also

Evaluate

History

ColdFusion MX: Changed behavior: this function can process only the following constructs:

  • A simple variable
  • A named variable with dot notation
  • A named structure with dot notation (for example: mystruct.key)

Parameters

Parameter | Description
variable_name | String, enclosed in quotation marks. Name of variable to test for.

Usage

When working with scopes that ColdFusion exposes as structures, the StructKeyExists function can sometimes replace this function. The following lines are equivalent:

if(isDefined("form.myVariable"))
if(structKeyExists(form,"myVariable"))

Example

<cfif IsDefined("form.myString")>
    <p>The variable form.myString has been defined, so show its contents.
    This construction allows us to place a form and its resulting action code
    on the same page and use IsDefined to control the flow of execution.</p>
    <p>The value of "form.myString" is <b><i>
    <cfoutput>#form.myString#</cfoutput></i></b>
<cfelse>
    <p>During the first time through this template, the variable "form.myString"
    has not yet been defined, so we do not try to evaluate it.
</cfif>

<form action="#CGI.Script_Name" method="POST">
<input type="Text" name="MyString" value="My sample value">
<input type="Submit" name="">
</form>


IsK2ServerABroker

Description

This function is deprecated.

Returns

True, if K2Broker is in configured with ColdFusion; False, otherwise.

Category

Decision functions, Full-text search functions, Query functions

Function syntax

IsK2ServerABroker()

See also

GetK2ServerDocCountLimit, IsK2ServerDocCountExceeded, IsK2ServerOnline

History

ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases.

ColdFusion MX: Added this function.

Example

<cfoutput>IsK2ServerABroker =
$*#IsK2ServerABroker()#*$</cfoutput>


IsK2ServerDocCountExceeded

Description

This function is deprecated.

Returns

True, if the document count limit is exceeded; False, otherwise.

Category

Decision functions, Full-text search functions, Query functions

Function syntax

IsK2ServerDocCountExceeded()

See also

GetK2ServerDocCountLimit, IsK2ServerABroker

History

ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases.

ColdFusion 5: Added this function.

Example

<cfoutput>IsK2ServerDocCountExceeded =
$*#IsK2ServerDocCountExceeded()#*$</cfoutput>


IsK2ServerOnline

Description

This function is deprecated because the K2Server is always running when ColdFusion is running.

Returns

True, if the K2Server is available to perform a search; False, otherwise.

Category

Decision functions, Full-text search functions, Query functions

Function syntax

IsK2ServerOnline()

See also

IsK2ServerABroker

History

ColdFusion MX 6.1: Deprecated this function. It might not work, and it might cause an error, in later releases.

ColdFusion MX: Added this function.

Example

<cfoutput>IsK2ServerOnline =
$*#IsK2ServerOnline()#*$</cfoutput>


IsLeapYear

Description

Determines whether a year is a leap year.

Returns

True, if year is a leap year; False, otherwise.

Category

Date and time functions, Decision functions

Function syntax

IsLeapYear(year)

See also

DaysInYear

Parameters

Parameter | Description
year | Number representing a year

Example

<h3>IsLeapYear Example</h3>

<cfif IsDefined("FORM.theTestValue")>
    <cfif IsLeapYear(FORM.theTestValue)>
        <h3>The year value <cfoutput>#DE(FORM.theTestValue)#</cfoutput> is a Leap Year</h3>
    <cfelse>
        <h3>The year value <cfoutput>#DE(FORM.theTestValue)#</cfoutput> is not a Leap Year</h3>
    </cfif>
</cfif>

<form action = "isLeapYear.cfm">
<p>Enter a year value, and find out whether it is a Leap Year.
<p><input type = "Text" name = "TheTestValue" value = "
<cfoutput>#Year(Now())#</cfoutput>">
<input type = "Submit" value = "Is it a Leap Year?" name = "">
</form>


IsNumeric

Description

Determines whether a string can be converted to a numeric value. Supports numbers in U.S. number format. For other number support, use LSIsNumeric.

Returns

True, if string can be converted to a number; False, otherwise.

Category

Decision functions

Function syntax

IsNumeric(string)

See also

IsBinary, IsValid

Parameters

Parameter | Description
string | A string or a variable that contains one.

Example

<h3>IsNumeric Example</h3>
<cfif IsDefined("FORM.theTestValue")>
    <cfif IsNumeric(FORM.theTestValue)>
    <h3>The string <cfoutput>#DE(FORM.theTestValue)#</cfoutput> can be
converted to a number</h3>
    <cfelse>
    <h3>The string <cfoutput>#DE(FORM.theTestValue)#</cfoutput> cannot be
converted to a number</h3>
    </cfif>
</cfif>

<form action = "isNumeric.cfm">
<p>Enter a string, and find out whether it can be evaluated to a numeric value.

<p><input type = "Text" name = "TheTestValue" value = "123">
<input type = "Submit" value = "Is it a Number?" name = "">
</form>


IsNumericDate

Description

Evaluates whether a real number is a valid representation of a date (date/time object).

Returns

True, if the parameter represents a valid date/time object; False, otherwise.

Category

Date and time functions, Decision functions

Function syntax

IsNumericDate(number)

See also

IsDate, ParseDateTime

Parameters

Parameter | Description
number | A real number

Usage

ColdFusion, by default, evaluates any input parameter and attempts to convert it to a real number before it passes the parameter to the IsNumericDate function. As a result, parameter values such as 12/12/03 and {ts '2003-01-14 10:04:13'} return True, because ColdFusion converts valid date string formats to date/time objects, which are real numbers.

Example

<h3>IsNumericDate Example</h3>
<cfif IsDefined("form.theTestValue")>
<!--- test if the value represents a number or a pre-formatted Date value --->

    <cfif IsNumeric(form.theTestValue) or IsDate(form.theTestValue)>
<!--- if this value is a numericDate value, then pass --->
        <cfif IsNumericDate(form.theTestValue)>
            <h3>The string <cfoutput>#DE(form.theTestValue)#</cfoutput> can be converted to a valid numeric date</h3>
        <cfelse>
            <h3>The string <cfoutput>#DE(form.theTestValue)#</cfoutput> can not be converted to a valid numeric date</h3>
        </cfif>
    <cfelse>
        <h3>The string <cfoutput>#DE(form.theTestValue)#</cfoutput> is not a valid numeric date</h3>
    </cfif>

</cfif>

<form action="#cgi.script_name#" method="POST">
<p>Enter a value, and discover if it can be evaluated to a date value.
<p>
<input type="Text" name="TheTestValue" value="<CFOUTPUT>#Now()#</CFOUTPUT>">
<input type="Submit" value="Is it a Date?" name="">
</form>


IsObject

Description

Determines whether a value is an object.

Returns

True, if the value represents a ColdFusion object. False if the value is any other type of data, such as an integer, string, date, or struct.

Category

Decision functions

Function syntax

IsObject(value)

See also

IsDate, IsNumeric, IsNumericDate, IsQuery, IsSimpleValue, IsStruct, IsWDDX, IsXmlDoc, IsXmlElem, IsXmlRoot

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
value | A value, typically the name of a variable.

Usage

This function returns False for query and XML objects.

Example

<!--- to use this example, create a color.cfc component as follows: --->
<!---
<cfcomponent>
    <cffunction name="myFunction" access="public" returntype="string">
        <!--- Create a structure object --->
        <cfset myColor = "Blue">
        <cfreturn myColor>
    </cffunction>
</cfcomponent>
--->

<!--- Create an instance of the color.cfc component --->
<cfobject name="getColor" component="color">

<cfif IsObject(getColor)>
    <!--- Invoke the myFunction method --->
    <cfinvoke
        component="#getColor#"
        method="myFunction"
        returnVariable="myColor">
    </cfinvoke>

    <cfif IsDefined("myColor")>
        <!--- Output the returned variable --->
        The value of myColor = <cfoutput>#myColor#</cfoutput><p>
    </cfif>
</cfif>


IsProtected

Description

This function is obsolete. Use the newer security tools; see Conversion functions and Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: This function is obsolete. It does not work in ColdFusion MX and later releases.


IsQuery

Description

Determines whether value is a query.

Returns

True, if value is a query.

Category

Decision functions, Query functions

Function syntax

IsQuery(value)

See also

QueryAddRow

Parameters

Parameter | Description
value | Query variable

Example

<!--- Shows an example of IsQuery and IsSimpleValue --->
<h3>IsQuery Example</h3>
<!--- define a variable called "GetEmployees" --->
<CFPARAM name = "GetEmployees" DEFAULT = "#Now()#">

<p>Before the query is run, the value of GetEmployees is
<cfoutput>#GetEmployees#</cfoutput>

<cfif IsSimpleValue(GetEmployees)>
    <p>GetEmployees is currently a simple value
</cfif>
<!--- make a query on the snippets datasource --->
<cfquery name = "GetEmployees" datasource = "cfdocexamples">
SELECT *
FROM employees
</cfquery>

<p>After the query is run, GetEmployees contains a number of rows
that look like this (display limited to three rows):
<cfoutput QUERY = "GetEmployees" MaxRows = "3">
<pre>#Emp_ID# #FirstName# #LastName#</pre>
</cfoutput>
<cfif IsQuery(GetEmployees)>
    GetEmployees is no longer a simple value, but the name of a query
</cfif>


IsSimpleValue

Description

Determines the type of a value.

Returns

True, if value is a string, number, Boolean, or date/time value; False, otherwise.

Category

Decision functions

Function syntax

IsSimpleValue(value)

See also

IsValid

Parameters

Parameter | Description
value | Variable or expression

Example

<!--- Shows an example of IsQuery and IsSimpleValue --->
<h3>IsSimpleValue Example</h3>
<!--- define a variable called "GetEmployees" --->
<cfparam name = "GetEmployees" default = "#Now()#">

<p>Before the query is run, the value of GetEmployees is
<cfoutput>#GetEmployees#</cfoutput>

<cfif IsSimpleValue(GetEmployees)>
    <p>GetEmployees is currently a simple value
</cfif>
<!--- make a query on the snippets datasource --->
<cfquery name = "GetEmployees" datasource = "cfdocexamples">
SELECT *
FROM employees
</cfquery>
<p>After the query is run, GetEmployees contains a number of rows
that look like this (display limited to three rows):
<cfoutput QUERY = "GetEmployees" MaxRows = "3">
<pre>#Emp_ID# #FirstName# #LastName#</pre>
</cfoutput>

<cfif IsQuery(GetEmployees)>
    GetEmployees is no longer a simple value, but the name of a query
</cfif>


IsSOAPRequest

Description

Determines whether a CFC is being called as a web service.

Returns

True if CFC is being called as a web service; False, otherwise.

Category

XML functions

History

ColdFusion MX 7: Added this function.

Function syntax

IsSOAPRequest()

See also

AddSOAPRequestHeader, AddSOAPResponseHeader, GetSOAPRequest, GetSOAPRequestHeader, GetSOAPResponse, GetSOAPResponseHeader; Basic web service concepts in Using Web Services in ColdFusion MX Developer’s Guide.

Usage

Call this function within a CFC to determine if it is running as a web service.

Example

This example creates a CFC web service that illustrates the operation of the IsSOAPRequest function and also provides a web service that illustrates the operation of other ColdFusion SOAP functions.

Save the following code as headerservice.cfc in a folder called soapheaders under your web root. Test its operation, and specifically the operation of the IsSOAPRequest function, by executing the examples that invoke this web service. For example, see the example for AddSOAPRequestHeader.

<h3>IsSOAPRequest Example</h3>
<cfcomponent displayName="tester" hint="Test for SOAP headers">

<cffunction name="echo_me"
            access="remote"
            output="false"
            returntype="string"
            displayname="Echo Test" hint="Header test">

  <cfargument name="in_here" required="true" type="string">

<cfset isSOAP = isSOAPRequest()>
<cfif isSOAP>

    <!--- Get the first header as a string and as XML --->
    <cfset username = getSOAPRequestHeader("http://mynamespace/", "username")>
    <cfset return = "The service saw username: " & username>
    <cfset xmlusername = getSOAPRequestHeader("http://mynamespace/", "username", "TRUE")>
    <cfset return = return & "<br> as XML: " & xmlusername>

    <!--- Get the second header as a string and as XML --->
    <cfset password = getSOAPRequestHeader("http://mynamespace/", "password")>
    <cfset return = return & "The service saw password: " & password>
    <cfset xmlpassword = getSOAPRequestHeader("http://mynamespace/", "password", "TRUE")>
    <cfset return = return & "<br> as XML: " & xmlpassword>

    <!--- Add a header as a string --->
    <cfset addSOAPResponseHeader("http://www.tomj.org/myns", "returnheader", "AUTHORIZED VALUE", false)>

    <!--- Add a second header using a CFML XML value --->
    <cfset doc = XmlNew()>
    <cfset x = XmlElemNew(doc, "http://www.tomj.org/myns", "returnheader2")>
    <cfset x.XmlText = "hey man, here I am in XML">
    <cfset  x.XmlAttributes["xsi:type"] = "xsd:string">
    <cfset tmp = addSOAPResponseHeader("ignoredNameSpace", "ignoredName", x)>

<cfelse>
    <!--- Add a header as a string - Must generate error!
    <cfset addSOAPResponseHeader("http://www.tomj.org/myns", "returnheader", "AUTHORIZED VALUE", false)>
    --->
    <cfset return = "Not invoked as a web service">
</cfif>

<cfreturn return>

</cffunction>

</cfcomponent>


IsStruct

Description

Determines whether a variable is a structure.

Returns

True, if variable is a ColdFusion structure or is a Java object that implements the java.lang.Map interface. The return value is False if the object in variable is a user-defined function (UDF).

Category

Decision functions, Structure functions

Function syntax

IsStruct(variable)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
variable | Variable name

Example

<!--- This view-only example shows the use of IsStruct. --->
<p>This file is similar to addemployee.cfm, which is called by StructNew,
StructClear, and StructDelete. It is an example of a custom tag used to
add employees. Employee information is passed through the employee
structure (the EMPINFO attribute). In UNIX, you must also add the Emp_ID.
<!---
<cfswitch expression = "#ThisTag.ExecutionMode#">
  <cfcase value = "start">
   <cfif IsStruct(attributes.EMPINFO)>
    <cfoutput>Error. Invalid data.</cfoutput>
    <cfexit method = "ExitTag">
   <cfelse>
    <cfquery name = "AddEmployee" datasource = "cfdocexamples">
    INSERT INTO Employees
    (FirstName, LastName, Email, Phone, Department)
    VALUES
    <cfoutput>
    (
    ‘#StructFind(attributes.EMPINFO, "firstname")#’ ,
    ‘#StructFind(attributes.EMPINFO, "lastname")#’ ,
    ‘#StructFind(attributes.EMPINFO, "email")#’ ,
    ‘#StructFind(attributes.EMPINFO, "phone")#’ ,
    ‘#StructFind(attributes.EMPINFO, "department")#’
    )
    </cfoutput>
    </cfquery>
</cfif>
<cfoutput><hr>Employee Add Complete</cfoutput>
</cfcase>
</cfswitch> --->


IsUserInRole

Description

Determines whether an authenticated user belongs to the specified Role.

Returns

True, if the authenticated user, belongs to the specified Role; False, otherwise.

Category

Security functions, Decision functions

Function syntax

IsUserInRole("role_name")

See also

GetAuthUser, cflogin, cfloginuser; Securing Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
role_name | Name of a security role

Usage

Role names are case-sensitive.

To check if a user is in multiple roles, specify them in a comma-delimited list, such as "Admin,HR". Lists with multiple roles cannot contain spaces as separators; for example, do not use "Admin, HR".

Example

<cfif IsUserInRole("Admin") >
    <cfoutput>Authenticated user is an administrator</cfoutput>
<cfelse IsUserInRole("User") >
    <cfoutput>Authenticated user is a user</cfoutput>
</cfif>


IsValid

Description

Tests whether a value meets a validation or data type rule.

Returns

True, if the value conforms to the rule; False, otherwise.

Category

Decision functions

Function syntax

IsValid(type, value)
isValid("range", value, min, max)
isValid("regex" or "regular_expression", value, pattern)

See also

cfparam, cfform, IsBoolean, IsDate, IsNumeric, IsSimpleValue; Validating data with the IsValid function and the cfparam tag in Validating Data in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter

Description

type

The valid format for the data; one of the following. For detailed information on validation algorithms, see Validating form data using hidden fields in Validating Data in ColdFusion MX Developer’s Guide.

  • any: any simple value. Returns false for complex values, such as query objects;; equivalent to the IsSimpleValue function.
  • array: an ColdFusion array; equivalent to the IsArray function.
  • binary: a binary value;; equivalent to the IsBinary function.
  • boolean: a Boolean value: yes, no, true, false, or a number; equivalent to the IsBoolean function.
  • creditcard: a 13-16 digit number conforming to the mod10 algorithm.
  • date or time: any date-time value, including dates or times;; equivalent to the IsDate function..
  • email: a valid email address.
  • eurodate: any date-time value, including US date formats and time values,
  • float or numeric: a numeric value; equivalent to the IsNumeric function.
  • guid: a Universally Unique Identifier of the form "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" where ‘X’ is a hexadecimal number.
  • integer: an integer.
  • query: a query object; equivalent to the IsQuery function.
  • range: a numeric range, specified by the min and max attributes.
  • regex or regular_expression: matches input against pattern attribute.
  • ssn or social_security_number: A U.S. social security number.
  • string: a string value, including single characters and numbers
  • struct: a structure; equivalent to the IsStruct function.
  • telephone: a standard US telephone number.
  • URL: an http, https, ftp, file, mailto, or news URL,
  • UUID: a ColdFusion Universally Unique Identifier, formatted ‘XXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXX’, where ‘X’ is a hexadecimal number. See CreateUUID.
  • USdate: a U.S. date of the format mm/dd/yy, with 1-2 digit days and months, 1-4 digit years.
  • variableName: a string formatted according to ColdFusion variable naming conventions.
  • zipcode: U.S., 5- or 9-digit format ZIP codes.

value

The value to test

min

The minimum valid value; used only for range validation

max

The maximum valid value; used only for range validation

pattern

A JavaScript regular expression that the parameter must match; used only for regex or regular_expression validation.

Usage

The IsValid function lets you assure that validation is performed on the server. You can use the cfparam tag to perform equivalent validation.

Example

The following example checks whether a user has submitted a numeric ID and a valid email address and phone number. If any of the submitted values does not meet the validation test, it displays an error message.

<cfif isDefined("form.saveSubmit")>
    <cfif isValid("integer", form.UserID) and isValid("email", form.emailAddr)
            and isValid("telephone", form.phoneNo)>
        <cfoutput>
            <!--- Application code to update the database goes here --->
            <h3>The email address and phone number for user #Form.UserID#
                have been added</h3>
        </cfoutput>
    <cfelse>
        <H3>You must supply a valid User ID, phone number, and email address.</H2>
    </cfif>
    <cfelse>
</cfif>

<cfform action="#CGI.SCRIPT_NAME#">
    User ID:<cfinput type="Text" name="UserID"><br>
    Phone: <cfinput type="Text" name="phoneNo"><br>
    email: <cfinput type="Text" name="emailAddr"><br>
    <cfinput type="submit" name="saveSubmit" value="Save Data"><br>
</cfform>


IsWDDX

Description

Determines whether a value is a well-formed WDDX packet.

Returns

True, if the value is a well-formed WDDX packet; False, otherwise.

Category

Decision functions, XML functions

Syntax

IsWDDX(value)

See also

Using WDDX in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: if the value parameter is not a WDDX packet, ColdFusion returns False. (In earlier releases, ColdFusion threw an error.)

Parameters

Parameter | Description
value | A WDDX packet

Usage

This function processes a WDDX packet with a validating XML parser, which uses the WDDX Document Type Definition (DTD).

To prevent CFWDDX deserialization errors, you can use this function to validate WDDX packets from unknown sources.

Example

<cfset packet="
    <wddxPacket version=’1.0’>
    <header></header>
    <data>
        <struct>
        <var name=’ARRAY’>
            <array length=’3’>
                <string>one</string>
            <string>two</string>
            </array>
        </var>
        <var name=’NUMBER’>
            <string>5</string>
        </var>
        <var name=’STRING’>
            <string>hello</string>
        </var>
        </struct>
    </data>
    </wddxPacket>"
    >
<hr>
<xmp>
<cfoutput>#packet#
</xmp>
IsWDDX() returns #IsWDDX(packet)#<br>
</cfoutput>


IsXML

Description

Determines whether a string is well-formed XML text.

Returns

True, if the function parameter is a string that contains well-formed XML text; False, otherwise.

Category

Decision functions, XML functions

Function syntax

IsXML(value)

See also

IsXmlAttribute, IsXmlDoc, IsXmlElem, IsXmlNode, IsXmlRoot, XmlParse, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter | Description
value | A string containing the XML document text

Usage

This function determines whether text is well-formed XML, that is, it conforms to all XML syntax and structuring rules. The string does not have to be a complete XML document. The function does not validate against a Document Type Definition (DTD) or XML Schema.

Example

The following example creates two strings, and tests whether they are well-formed XML text:

<!--- A well formed XML string --->
<cfset xmlString1='<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>'
>

<!--- An invalid XML string, missing the </item> close tag --->
<cfset xmlString2='<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
    </items>
</order>'
>

<!--- Test the strings to see if they are well formed XML --->
<cfoutput>
xmlString1 contains the following text:<br><br>
#HTMLCodeFormat(xmlstring1)#
Is it well formed XML text? #IsXML(xmlString1)#<br><br>
<hr>
xmlString2 contains the following text:<br><br>
#HTMLCodeFormat(xmlstring2)#
Is it well formed XML text? #IsXML(xmlString2)#
</cfoutput>


IsXmlAttribute

Description

Determines whether the function parameter is an XML Document Object Model (DOM) attribute node.

Returns

True, if the function argument is an XML attribute node; False, otherwise.

Category

Decision functions, XML functions

Function syntax

IsXmlAttribute(value)

See also

IsXML, IsXmlDoc, IsXmlElem, IsXmlNode, IsXmlRoot, XmlGetNodeType, XmlValidate, Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter | Description
value | Name of an XML attribute

Usage

This function determines whether the parameter is an XML DOM attribute node, a node with an XMLType value of ATTRIBUTE. It is useful for determining whether a value returned by the XmlSearch function is an XML attribute.

The DOM, and therefore ColdFusion MX, treats XML attributes as properties of an element and does not directly expose them as DOM nodes. For this reason, the XmlAttributes entries in ColdFusion XML document objects do not represent DOM attribute nodes, and tests such as the following always return False:

IsXmlAttribute(myxmlelement.XMlAttributes);
IsXmlAttribute(myxmlelement.XMlAttributes.myattribute);

The XmlSearch function does return attributes as XML DOM attribute nodes. For example, the following line returns an array of attribute nodes containing the quantity attributes in the xmlobject document object:

quantities = XmlSearch(xmlobject, '//@quantity');

Example

The following example creates an XML document object and gets parts of it. It then tests whether these parts are attribute nodes.

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>
</cfxml>

<!--- Get an array with all lastname quantity DOM attribute nodes
    (In this example there is only one entry) --->
<cfset lastnames = XmlSearch(xmlobject, '//@lastname')>

<!--- Test objects to see if they are attributes --->
<cfoutput>
<h3>Are the following XML Attribute nodes?</h3>
<!--- The order element id attribute.
         This a simple variable, not a DOM attribute node.--->
node.xmlobject.order.XmlAttributes.id:
    #IsXmlAttribute(xmlobject.order.XmlAttributes.id)#<br>
<!--- The items element --->
xmlobject.order.items: #IsXmlAttribute(xmlobject.order.items)#<br>
lastnames[1] returned by XmlSearch:
#isXmlAttribute(lastnames[1])#<br>
</cfoutput>


IsXmlDoc

Description

Determines whether the function parameter is a ColdFusion XML document object.

Returns

True, if the function argument is an XML document object; False, otherwise.

Category

Decision functions, XML functions

Function syntax

IsXmlDoc(value)

See also

IsXML, IsXmlAttribute, IsXmlElem, IsXmlNode, IsXmlRoot, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
value | Name of an XML document object

Example

The following example creates an XML Document object and a Java object and tests whether they are XML document objects:

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>
</cfxml>

<!--- Create a Java object --->
<cfobject type="JAVA" action="create" class="java.lang.Error" name="javaobject" >

<!--- Test the objects --->
<cfoutput>
Is xmlobject an XML document object? #IsXmlDoc(xmlobject)#<br>
Is javaobject an XML document object? #IsXmlDoc(javaobject)#<br>
</cfoutput>


IsXmlElem

Description

Determines whether the function parameter is an XML document object element.

Returns

True, if the function argument is an XML document object element; False, otherwise.

Category

Decision functions, XML functions

Function syntax

IsXmlElem(value)

See also

IsXML, IsXmlAttribute, IsXmlDoc, IsXmlNode, IsXmlRoot, XmlGetNodeType, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
value | Name of an XML document object element

Example

The following example tests whether an XML document object, the document root, and an element are elements:

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>
</cfxml>

<!--- Test parts of the document object to see if they are elements --->
<cfoutput>
    <h3>Are the following XML document object elements?</h3>
    xmlobject: #IsXmlElem(xmlobject)#<br>
    xmlobject.XMLRoot: #IsXmlElem(xmlobject.XMLRoot)#<br>
    xmlobject.order.items: #IsXmlElem(xmlobject.order.items)#<br>
</cfoutput>


IsXmlNode

Description

Determines whether the function parameter is an XML document object node.

Returns

True, if the function argument is an XML document object node, including an element; False, otherwise.

Category

Decision functions, XML functions

Function syntax

IsXmlNode(value)

See also

IsXML, IsXmlAttribute, IsXmlDoc, IsXmlElem, IsXmlRoot, XmlGetNodeType, XmlSearch, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter | Description
value | Name of an XML document object node.

Usage

This function returns True for the following components of an XML document object:

  • The document object
  • Elements in the object
  • XmlNode objects in an element’s XmlNodes array

It also returns True for XML node objects returned by the XmlSearch function. It does not return True for most entries in an element, including XmlText, XmlComment, XmlCdata, or the XmlAttributes array (or individual XML attributes).

Example

The following example tests whether an XML document object, an element, an attribute in the object, and an attribute returned by an XmlSearch function are nodes:

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<?xml version="1.0" encoding="UTF-8"?>
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>
</cfxml>

<!--- use XmlSearch to get an attribute node. --->
<cfset lastnames = XmlSearch(xmlobject, '//@lastname')>

<!--- Test the objects to see if they are XML nodes--->
<cfoutput>
<h3>Are the following XML nodes?</h3>
xmlobject: #IsXmlNode(xmlobject)#<br>
<!--- The items element --->
xmlobject.order.items: #IsXmlNode(xmlobject.order.items)#<br>
<!--- The order element id attribute; a simple variable, not a DOM node.--->
xmlobject.order.XmlAttributes.id:
    #IsXmlNode(xmlobject.order.XmlAttributes.id)#<br>
lastnames[1] returned by XmlSearch:
#isXmlNode(lastnames[1])#
</cfoutput>


IsXmlRoot

Description

Determines whether the function parameter is the root element of an XML document object.

Returns

True, if the function argument is the root object of an XML document object; False, otherwise.

Category

Decision functions, XML functions

Function syntax

IsXmlRoot(value)

See also

IsXML, IsXmlAttribute, IsXmlDoc, IsXmlElem, IsXmlNode, XmlGetNodeType, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
value | Name of an XML document object

Example

The following example tests whether an XML document object, its root element, and a child element are XML root elements:

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<?xml version="1.0" encoding="UTF-8"?>
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>
</cfxml>

<!--- Test objects to see if they are XML root elements --->
<cfoutput>
<h3>Are the following the XML Root?</h3>
xmlobject: #IsXmlRoot(xmlobject)#<br>
xmlobject.order: #IsXmlRoot(xmlobject.order)#<br>
<!--- The order element id attribute --->
xmlobject.order.XmlAttributes.id:
    #IsXmlRoot(xmlobject.order.XmlAttributes.id)#<br>
</cfoutput>


JavaCast

Description

Converts the data type of a ColdFusion variable to pass as an argument to an overloaded method of a Java object. Use only for scalar and string arguments.

Returns

The variable, as type type.

Category

String functions

Function syntax

JavaCast(type, variable)

See also

CreateObject, cfobject

Parameters

Parameter

Description

type

Data type to which to convert variable:

  • boolean
  • int
  • long
  • float
  • double
  • string
  • null

variable

A ColdFusion variable that holds a scalar or string type. Must be "" if type is null.

Usage

Use after creating a Java object with the cfobject tag, before calling one of its methods. If the method takes more than one overloaded argument, you must call JavaCast for each one. Use JavaCast only when a method is overloaded (because its arguments can take more than one data type, not because the method can take a variable number of arguments).

JavaCast cannot be used to cast between complex objects, nor to cast to a super-class.

Use the result of this function only on calls to Java objects, as shown in the following example:

<cfscript>
     x = CreateObject("java", "test.Hello");
     x.init();
     ret = x.sayHello(JavaCast("null", ""));
</cfscript>

Warning: Do not assign the results of JavaCast("null","") to a ColdFusion variable. Unexpected results will occur.

Because there is not a one-to-one correspondence between internally stored ColdFusion types and Java scalar types, some conversions cannot be performed.

Example

The method fooMethod in the class fooClass takes one overloaded argument. The fooClass class is defined as follows:

public class fooClass {
    public fooClass () {
    }
    public String fooMethod(String arg) {
        return "Argument was a String";
    }
    public String fooMethod(int arg) {
        return "Argument was an Integer";
    }

}

Within ColdFusion, you use the following code:

<cfobject
action="create"
    type = "java"
    class = "fooClass"
    name = obj>

<!--- ColdFusion can treat this as a string or a real number --->
<cfset x = 33>

Perform an explicit cast to an int and call fooMethod:<br>
<cfset myInt = JavaCast("int", x)>
<cfoutput>#obj.fooMethod(myInt)#</cfoutput>
<br><br>
Perform an explicit cast to a string and call fooMethod:<br>
<cfset myString = javaCast("String", x)>
<cfoutput>#obj.fooMethod(myString)#</cfoutput>


JSStringFormat

Description

Escapes special JavaScript characters, such as single-quotation mark, double-quotation mark, and newline.

Returns

A string that is safe to use with JavaScript.

Category

String functions

Function syntax

JSStringFormat(string)

Parameters

Parameter | Description
string | A string or a variable that contains one.

Usage

Escapes special JavaScript characters, so you can put arbitrary strings safely into JavaScript.

Example

<!--- This example shows the use of the JSStringFormat function. ---->
<h3>JSStringFormat</h3>
<cfset stringValue = "An example string value with a tab chr(8),
a newline (chr10) and some ""quoted"" 'text'">

<p>This is the string we have created:<br>
<cfoutput>#stringValue#</cfoutput>
</p>
<cfset jsStringValue = JSStringFormat(#stringValue#)>
<!----- Generate an alert from the JavaScript string jsStringValue. ---->
<SCRIPT>
s = "<cfoutput>#jsStringValue#</cfoutput>";
alert(s);
</SCRIPT>

Previous


LCase

Description

Converts the alphabetic characters in a string to lowercase.

Returns

A string, converted to lowercase.

Category

String functions

Function syntax

LCase(string)

See also

UCase

Parameters

Parameter | Description
string | A string or a variable that contains one

Example

<h3>LCase Example</h3>

<cfif IsDefined("FORM.sampleText")>
    <cfif FORM.sampleText is not "">
        <cfoutput>
        <p>Your text, <b>#FORM.sampleText#</b>, returned in lowercase is
        <b>#LCase(FORM.sampleText)#</b>.</p>
    <	/cfoutput>
    <cfelse>
        <	p><b><i>Please enter some text.</i></b></p>
    </cfif>
</cfif>

<p>Enter your text. Press "submit" to see it returned in lowercase: </p>

<form method="post" action = "<cfoutput>#cgi.script_name#</cfoutput>" name="lcaseForm">
<input type = "Text" name = "SampleText" value = "SAMPLE">
<input type = "Submit" name = "" value = "submit">
</form>
Next


Left

Description

Returns the leftmost count characters in a string.

Returns

String; the first count characters in the string parameter.

Category

String functions

Function syntax

Left(string, count)

See also

Right , Mid , Len

Parameters

Parameter | Description
string | A string or a variable that contains one.
count | A positive integer or a variable that contains one. Number of characters to return.

Example

<h3>Left Example</h3>

<cfif IsDefined("Form.myText")>
<!--- If len returns 0 (zero), then show error message. --->
    <cfif Len(Form.myText)>
        <cfif Len(Form.myText) LTE Form.RemoveChars>
            <cfoutput><p style="color: red; font-weight: bold">Your string #Form.myText# only has #Len(Form.myText)# characters. You cannot output
    the #Form.removeChars# leftmost characters of this string because it is
    not long enough.</p></cfoutput>
        <cfelse>
            <cfoutput><p>Your original string: <strong>#Form.myText#</strong></p>
                <p>Your changed string, showing only the <strong>#Form.removeChars#
                    </strong> leftmost characters:
                    <strong>#Left(Form.myText, Form.removeChars)#</strong></p>
            </cfoutput>
        </cfif>
    <cfelse>
        <p style="color: red; font-weight: bold">Please enter a string of more than 0 (zero) characters.</p>
</cfif>
</cfif>

<form action="<cfoutput>#CGI.ScriptName#</cfoutput>" method="POST">
<p>Type in some text<br />
<input type="Text" name="myText"></p>
<p>How many characters from the left do you want to show?
<select name="RemoveChars">
<option value="1">1
<option value="3" selected>3
<option value="5">5
<option value="7">7
<option value="9">9</select>
<input type="Submit" name="Submit" value="Remove characters"></p>
</form>


Len

Description

Determines the length of a string or binary object.

Returns

Number; length of a string or a binary object.

Category

String functions

Function syntax

Len(string or binary object)

See also

ToBinary , Left , Right , Mid

History

ColdFusion MX: Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535. (ColdFusion 5 and earlier releases supported ASCII values 1–255. When calculating a length, some string-processing functions processed the ASCII 0 (NUL) character, but did not process subsequent characters of the string.)

Parameters

Parameter | Description
string | A string, the name of a string, or a binary object

Example

<h3>Len Example</h3>

<cfif IsDefined("Form.MyText")>
    <!--- If len returns 0 (zero), then show error message. --->
    <cfif Len(FORM.myText)>
        <cfoutput><p>Your string, <strong>"#FORM.myText#"</strong>,
        has <strong>#Len(FORM.myText)#</strong> characters.</cfoutput>
    <cfelse>
        <p style="color: red; font-weight: bold">Please enter a string of more
        than 0 characters.</p>
    </cfif>
</cfif>

<form action = "<cfoutput>#CGI.SCRIPT_NAME#</cfoutput>" method="POST">
<p>Type in some text to see the length of your string.</p>

<input type = "Text" name = "MyText"><br />
<input type = "Submit" name="Submit" value = "Count characters"><br>
</form>


ListAppend

Description

Concatenates a list or element to a list.

Returns

A copy of the list, with value appended. If delimiter = "", returns a copy of the list, unchanged.

Category

List functions

Function syntax

ListAppend(list, value [, delimiters ])

See also

ListPrepend, ListInsertAt, ListGetAt, ListLast, ListSetAt; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
list | A list or a variable that contains one.
value | An element or a list of elements.
delimiters | A string or a variable that contains one. Character(s) that separate list elements. The default value is comma. If this parameter contains more than one character, ColdFusion uses only the first character.

Usage

ColdFusion inserts a delimiter character before value.

The following table shows examples of ListAppend processing:

Statement

Output

Comment

ListAppend('elem1,elem2', '' )

elem1,elem2,

Appended element is empty; delimiter is last character in list; list length is 2.

ListAppend('', 'elem1,elem2' )

elem1,elem2

List length is 2.

ListAppend
("one___two", "three", "___")

"one___two_three"

Inserted the first character of delimiters before "three."

Example

<h3>ListAppend Example</h3>
<!--- First, query to get some values for our list elements--->
<cfquery name = "GetParkInfo" datasource = "cfdocexamples">
SELECT PARKNAME,CITY,STATE
FROM PARKS WHERE PARKNAME LIKE ‘AL%’
</cfquery>
<cfset temp = ValueList(GetParkInfo.ParkName)>
<cfoutput>
<p>The original list: #temp#
</cfoutput>
<!--- now, append a park name to the list --->
<cfset temp2 = ListAppend(Temp, "ANOTHER PARK")>
...


ListChangeDelims

Description

Changes a list delimiter.

Returns

A copy of the list, with each delimiter character replaced by new_delimiter.

Category

List functions

Function syntax

ListChangeDelims(list, new_delimiter [, delimiters ])

See also

ListFirst, ListQualify; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

new_delimiter

Delimiter string or a variable that contains one. Can be an empty string. ColdFusion processes the string as one delimiter.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Example

<h3>ListChangeDelims Example</h3>
<p>ListChangeDelims lets you change the delimiters of a list.
<!--- First, query to get some values for our list elements--->
<CFQUERY NAME="GetParkInfo" DATASOURCE="cfdocexamples">
SELECT 	PARKNAME,CITY,STATE
FROM 	Parks
WHERE	 PARKNAME LIKE 'BA%'
</CFQUERY>
<CFSET temp = ValueList(GetParkInfo.ParkName)>
<cfoutput>
<p>The original list: <p>#temp#
</cfoutput>
<!--- Change the delimiters in the list --->
<CFSET temp2 = ListChangeDelims(Temp, "|:P|", ",")>
<cfoutput>
<p>After executing the statement
<strong>ListChangeDelims(Temp, "|:P|", ",")</strong>,
the updated list: <p>#temp2#
</cfoutput>


ListContains

Description

Determines the index of the first list element that contains a specified substring.

Returns

Index of the first list element that contains substring. If not found, returns zero.

Category

List functions

Function syntax

ListContains(list, substring [, delimiters ])

See also

ListContainsNoCase, ListFind; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

substring

A string or a variable that contains one. The search is case-sensitive.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<!--- This example shows differences between ListContains and ListFind --->
<!--- Create a list composed of the elements one, two, three. ---->
<cfset aList = "one">
<cfset aList = ListAppend(aList, "two")>
<cfset aList = ListAppend(aList, "three")>
<p>Here is a list: <cfoutput>#aList#</cfoutput>
<p><strong>ListContains</strong> checks for substring "wo" in the list elements:
<cfoutput>
    <p>&nbsp;&nbsp;&nbsp;Substring "wo" is in
<B>element #ListContains(aList, "wo")#</B> of list.
</cfoutput>
<p>ListFind cannot check for a substring within an element; therefore, in the
    code, it does not find substring "wo" (it returns 0):
<cfoutput>
    <p>&nbsp;&nbsp;&nbsp;Substring "wo" is in <b>element #ListFind(aList, "wo")#
    </b> of the list.</cfoutput>
<p><p>If you specify a string that exactly equals an entire list element, such
    as "two", both ListContains and ListFind find it, in the second element:
    <p>&nbsp;&nbsp;&nbsp;<strong>ListContains</strong>:
<cfoutput>
The string "two" is in <b>element #ListContains(aList, "two")#</b> of the list.
</cfoutput>
&nbsp;&nbsp;&nbsp;<p><strong>ListFind</strong>:
<cfoutput>
The string "two" is in <b>element #ListFind(aList, "two")#</b> of the list.
</cfoutput>


ListContainsNoCase

Description

Determines the index of the first list element that contains a specified substring.

Returns

Index of the first list element that contains substring, regardless of case. If not found, returns zero.

Category

List functions

Function syntax

ListContainsNoCase(list, substring [, delimiters ])

See also

ListContains, ListFindNoCase; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

substring

A string or a variable that contains one. The search is case-insensitive.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListContainsNoCase Example</h3>
<cfif IsDefined("form.letter")>
    <!--- First, query to get some values for our list --->
    <cfquery name="GetParkInfo" datasource="cfdocexamples">
        SELECT PARKNAME,CITY,STATE
        FROM Parks
        WHERE PARKNAME LIKE '#form.letter#%'
    </cfquery>
    <cfset tempList = #ValueList(GetParkInfo.City)#>
    <cfif ListContainsNoCase(tempList, form.yourCity) is not 0>
        There are parks in your city!
    <cfelse>
        <p>Sorry, there were no parks found for your city.
        Try searching under a different letter.
    </cfif>
</cfif>


ListDeleteAt

Description

Deletes an element from a list.

Returns

A copy of the list, without the specified element.

Category

List functions

Function syntax

ListDeleteAt(list, position [, delimiters ])

See also

ListGetAt, ListSetAt, ListLen; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

position

A positive integer or a variable that contains one. Position at which to delete element. The first list position is 1.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

To use this and other functions with the default delimiter (comma), you can code as follows:

<cfset temp2 = ListDeleteAt(temp, "3")>

To specify another delimiter, you code as follows:

<cfset temp2 = ListDeleteAt(temp, "3", ";")>

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<!--- First, query to get some values for our list elements--->
<CFQUERY NAME="GetParkInfo" DATASOURCE="cfdocexamples">
    SELECT 	PARKNAME,CITY,STATE
    FROM Parks
    WHERE	 PARKNAME LIKE 'CHI%'
</CFQUERY>
<CFSET temp = ValueList(GetParkInfo.ParkName)>
<CFSET deleted_element = ListGetAt(temp, "3", ",")>
<cfoutput>
<p>The original list: #temp#
</cfoutput>
<!--- Delete the third element from the list --->
<CFSET temp2 = ListDeleteAt(Temp, "3")>
<cfoutput>
<p>The changed list: #temp2#
<p><I>This list element:<br>#deleted_element#<br> is no longer present
at position three of the list.</I> </cfoutput>


ListFind

Description

Determines the index of the first list element in which a specified value occurs. Case-sensitive.

Returns

Index of the first list element that contains value, with matching case. If not found, returns zero. The search is case-sensitive.

Category

List functions

Function syntax

ListFind(list, value [, delimiters ])

See also

ListContains, ListFindNoCase; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one

value

A string, a number, or a variable that contains one. Item for which to search. The search is case-sensitive.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<!--- Uses ListFind and ListFindNoCase to see if a substring exists
in a list --->
<form action="./listfind.cfm" method="POST">
    <p>Try changing the case in Leary's last name:
    <br><input type="Text" size="25" name="myString" value="Leary">
    <p>Pick a search type:
        <select name="type">
            <option value="ListFind" selected>Case-Sensitive
            <option value="ListFindNoCase">Case-Insensitive
        </select>
    <input type="Submit" name="" value="Search Employee List">
</form>

<!--- wait to have a string for searching defined --->
<cfif IsDefined("form.myString") and IsDefined("form.type")>

<cfquery name="SearchEmpLastName" datasource="cfdocexamples">
    SELECT  FirstName, RTrim(LastName) AS LName, Phone, Department
    FROM    Employees
</cfquery>

<cfset myList = ValueList(SearchEmpLastName.LName)>
<!--- Is this case-sensitive or case-insensitive searching --->
<cfif form.type is "ListFind">
    <cfset temp = ListFind(myList, form.myString)>
        <cfif temp is 0>
            <h3>An employee with that exact last name was not found</h3>
        <cfelse>
            <cfoutput>
            <p>Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)#
            #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the
            #ListGetAt(ValueList(SearchEmpLastName.Department), temp)# Department,
            can be reached at #ListGetAt(ValueList(SearchEmpLastName.Phone),
            temp)#.
            <p>This was the first employee found under this case-sensitive last name
            search.
            </cfoutput>
        </cfif>
        <cfelse>
            <cfset temp = ListFindNoCase(myList, form.myString)>
            <cfif temp is 0>
                <h3>An employee with that exact last name was not found</h3>
            <cfelse>
                <cfoutput>
                <p>Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)#
                #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the
                #ListGetAt(ValueList(SearchEmpLastName.Department), temp)#
                Department, can be reached at
                #ListGetAt(ValueList(SearchEmpLastName.Phone), temp)#.
                <p>This was the first employee found under this case-insensitive last
                name search.
            </cfoutput>
        </cfif>
    </cfif>
</cfif>


ListFindNoCase

Description

Determines the index of the first list element in which a specified value occurs.

Returns

Index of the first list element that contains value. If not found, returns zero. The search is case-insensitive.

Category

List functions

Function syntax

ListFindNoCase(list, value [, delimiters ])

See also

ListContains, ListFind; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

value

Number or string for which to search. The search is case-insensitive.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<!--- Uses ListFind and ListFindNoCase to see if a substring exists
in a list --->
<form action="./listfind.cfm" method="POST">
    <p>Try changing the case in Leary's last name:
    <br><input type="Text" size="25" name="myString" value="Leary">
    <p>Pick a search type:
        <select name="type">
            <option value="ListFind" selected>Case-Sensitive
            <option value="ListFindNoCase">Case-Insensitive
        </select>
    <input type="Submit" name="" value="Search Employee List">
</form>

<!--- wait to have a string for searching defined --->
<cfif IsDefined("form.myString") and IsDefined("form.type")>

<cfquery name="SearchEmpLastName" datasource="cfdocexamples">
    SELECT  FirstName, RTrim(LastName) AS LName, Phone, Department
    FROM    Employees
</cfquery>

<cfset myList = ValueList(SearchEmpLastName.LName)>
<!--- Is this case-sensitive or case-insensitive searching --->
<cfif form.type is "ListFind">
    <cfset temp = ListFind(myList, form.myString)>
        <cfif temp is 0>
            <h3>An employee with that exact last name was not found</h3>
        <cfelse>
            <cfoutput>
            <p>Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)#
            #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the
            #ListGetAt(ValueList(SearchEmpLastName.Department), temp)# Department,
            can be reached at #ListGetAt(ValueList(SearchEmpLastName.Phone),
            temp)#.
            <p>This was the first employee found under this case-sensitive last name
            search.
            </cfoutput>
        </cfif>
        <cfelse>
            <cfset temp = ListFindNoCase(myList, form.myString)>
            <cfif temp is 0>
                <h3>An employee with that exact last name was not found</h3>
            <cfelse>
                <cfoutput>
                <p>Employee #ListGetAt(ValueList(SearchEmpLastName.FirstName), temp)#
                #ListGetAt(ValueList(SearchEmpLastName.LName), temp)#, of the
                #ListGetAt(ValueList(SearchEmpLastName.Department), temp)#
                Department, can be reached at
                #ListGetAt(ValueList(SearchEmpLastName.Phone), temp)#.
                <p>This was the first employee found under this case-insensitive last
                name search.
            </cfoutput>
        </cfif>
    </cfif>
</cfif>


ListFirst

Description

Gets the first element of a list.

Returns

The first element of a list. If the list is empty, returns an empty string.

Category

List functions

Function syntax

ListFirst(list [, delimiters ])

See also

ListGetAt, ListLast, ListQualify; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains a list.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListFirst Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
    SELECT Username, Subject, Posted
    FROM  Messages
</cfquery>

<cfset temp = ValueList(GetMessageUser.Username)>
<p>Before editing the list, it is:&nbsp;
<cfoutput>#ValueList(GetMessageUser.Username)#</cfoutput>.
<p>(Users who posted more than once are listed more than once.)
<!--- Show the first user in the list --->
<p>The first user in the list is:
<cfoutput>#ListFirst(temp)#</cfoutput>
<p>The rest of the list is:&nbsp;<cfoutput>#ListRest(temp)#</cfoutput>.
<p>(Users who posted more than once are listed more than once.)
<p>The last user in the list is: <cfoutput>#ListLast(temp)#</cfoutput>


ListGetAt

Description

Gets a list element at a specified position.

Returns

Index of the list element at position position.

Category

List functions

Function syntax

ListGetAt(list, position [, delimiters ])

See also

ListFirst, ListLast, ListQualify, ListSetAt; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

position

A positive integer or a variable that contains one. Position at which to get element. The first list position is 1.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

If you use list functions on strings that are delimited by a delimiter character and a space, a returned list element might contain a leading space; you use the trim function to remove such spaces from a returned element. For example, consider this list:

<cfset myList = "one hundred, two hundred, three hundred">

To get a value from this list, use the trim function to remove the space before the returned value:

<cfset MyValue = #trim(listGetAt(myList, 2))#>

With this usage, MyValue = "two hundred", not " two hundred", and spaces within a list element are preserved.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListGetAt Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
    SELECT Username, Subject, Posted
    FROM  Messages
</cfquery>
<cfset temp = ValueList(GetMessageUser.Username)>
<!--- loop through the list and show it with ListGetAt --->
<h3>This list of usernames who have posted messages numbers
<cfoutput>#ListLen(temp)#</cfoutput> users.</h3>
<ul>
<cfloop From = "1" To = "#ListLen(temp)#" index = "Counter">
    <cfoutput><li>Username #Counter#: #ListGetAt(temp, Counter)# </cfoutput>
</cfloop>
</ul>


ListInsertAt

Description

Inserts an element in a list.

Returns

A copy of the list, with value inserted at the specified position.

Category

List functions

Function syntax

ListInsertAt(list, position, value [, delimiters ])

See also

ListDeleteAt, ListAppend, ListPrepend, ListSetAt; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

position

A positive integer or a variable that contains one. Position at which to insert element. The first list position is 1.

value

An element or a list of elements.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

When inserting an element, ColdFusion inserts a delimiter. If delimiters contains more than one delimiter, ColdFusion uses the first delimiter in the string; if delimiters is omitted, ColdFusion uses a comma.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<!--- This example shows ListInsertAt --->
<cfquery name = "GetParkInfo" datasource = "cfdocexamples">
SELECT PARKNAME,CITY,STATE
FROM PARKS
WHERE PARKNAME LIKE ‘DE%’
</cfquery>
<cfset temp = ValueList(GetParkInfo.ParkName)>
<cfset insert_at_this_element = ListGetAt(temp, "3", ",")>
<cfoutput>
<p>The original list: #temp#
</cfoutput>
<cfset temp2 = ListInsertAt(Temp, "3", "my Inserted Value")>


ListLast

Description

Gets the last element of a list.

Returns

The last element of the list.

Category

List functions

Function syntax

ListLast(list [, delimiters ])

See also

ListGetAt, ListFirst; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains a list.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter; you cannot specify a multicharacter delimiter.

Usage

If you use list functions on strings that separated by a delimiter character and a space, a returned list element might contain a leading space; use the trim function to remove leading and trailing spaces from a returned element. For example, consider this list:

<cfset myList = "one hundred, two hundred, three hundred">

To get a value from this list, use the trim function to remove the space before the returned value:

<cfset MyValue = #trim(ListLast(myList)#>

With this usage, the MyValue variable gets the value "three hundred", not " three hundred", and spaces within a list element are preserved.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListFirst, ListLast, and ListRest Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
    SELECT Username, Subject, Posted
    FROM  Messages
</cfquery>
<cfset temp = ValueList(GetMessageUser.Username)>
<p>Before editing the list, it is:&nbsp;
<cfoutput>#ValueList(GetMessageUser.Username)#</cfoutput>.
<p>(Users who posted more than once are listed more than once.)
<!--- Show the first user in the list --->
<p>The first user in the list is: <cfoutput>#ListFirst(temp)#</cfoutput>
<p>The rest of the list is:&nbsp;<cfoutput>#ListRest(temp)#</cfoutput>.
<p>(Users who posted more than once are listed more than once.)
<p>The last user in the list is: <cfoutput>#ListLast(temp)#</cfoutput>


ListLen

Description

Determines the number of elements in a list.

Integer; the number of elements in a list.

Category

List functions

Function syntax

ListLen(list [, delimiters ])

See also

ListAppend, ListDeleteAt, ListInsertAt, ListPrepend; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Here are some examples of ListLen processing:

Statement

Output

Comment

ListLen('a,b, c,,,d')

4

Third element is " c"

ListLen('a,b, c,,,d',',')

4

Fourth element is "d'"

ListLen('elem_1___elem_2___elem_3')

1

ListLen('elem*1***elem*2***elem*3')

1

ListLen('elem_1___elem_2___elem_3','_')

6

Example

<h3>ListLen Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
    SELECT Username, Subject, Posted
    FROM  Messages
</cfquery>
<cfset temp = ValueList(GetMessageUser.Username)>
<!--- loop through the list and show it with ListGetAt --->
<h3>This is a list of usernames who have posted messages
<cfoutput>#ListLen(temp)#</cfoutput> users.</h3>
<ul>
<cfloop From = "1" TO = "#ListLen(temp)#" INDEX = "Counter">
    <cfoutput><li>Username #Counter#:
     #ListGetAt(temp, Counter)#</cfoutput>
</cfloop>
</ul>


ListPrepend

Description

Inserts an element at the beginning of a list.

Returns

A copy of the list, with value inserted at the first position.

Category

List functions

Function syntax

ListPrepend(list, value [, delimiters ])

See also

ListAppend, ListInsertAt, ListSetAt; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

value

An element or a list of elements.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion only uses the first character and ignores the others.

Usage

When prepending an element to a list, ColdFusion inserts a delimiter. If delimiters contains more than one delimiter character, ColdFusion uses the first delimiter in the string; if delimiters is omitted, ColdFusion uses a comma.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

If the delimiters parameter is the empty string (""), ColdFusion returns the contents of the value parameter.

Example

<!--- This example shows ListPrepend --->
<cfquery name = "GetParkInfo" datasource = "cfdocexamples">
    SELECT PARKNAME,CITY,STATE
    FROM PARKS
    WHERE PARKNAME LIKE ‘DE%’
</cfquery>
<cfset temp = ValueList(GetParkInfo.ParkName)>
<cfset first_element = ListFirst(temp)>
<cfoutput><p>The original list: #temp#</cfoutput>
<!--- now, insert an element at position 1--->
<cfset temp2 = ListPrepend(Temp, "my Inserted Value")>


ListQualify

Description

Inserts a string at the beginning and end of list elements.

Returns

A copy of the list, with qualifier before and after the specified element(s).

Category

List functions

Function syntax

ListQualify(list, qualifier [, delimiters ] [, elements ])

See also

Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: as the elements parameter value, you must specify "all" or "char"; otherwise, ColdFusion throws an exception. (In earlier releases, the function ignored an invalid value, and used "all"; this was inconsistent with other functions.)

Parameters

Parameter

Description

list

A list or a variable that contains one.

qualifier

A string or a variable that contains one. Character or string to insert before and after the list elements specified in the elements parameter.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion uses the first character as the delimiter and ignores the remaining characters.

elements
  • all: all elements
  • char: elements that are composed of alphabetic characters

Usage

The new list might not preserve all of the delimiters in the list.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<cfquery name = "GetEmployeeNames" datasource = "cfdocexamples">
SELECT 	FirstName, LastName
FROM 	Employees
</cfquery>

<h3>ListQualify Example</h3>
<p>This example uses ListQualify to put the full names of the
employees in the query within quotation marks.</p>
<cfset myArray = ArrayNew(1)>

<!--- loop through query; append these names successively
to the last element --->
<cfloop query = "GetEmployeeNames">
    <cfset temp = ArrayAppend(myArray, "#FirstName# #LastName#")>
</cfloop>

<!--- sort that array descending alphabetically --->
<cfset myAlphaArray = ArraySort(myArray, "textnocase")>

<!--- show the resulting array as a list --->
<cfset myList = ArrayToList(myArray, ",")>

<cfoutput>
    <p>The contents of the unqualified list are as follows:	</p>
    #myList#
</cfoutput>

<!--- show the resulting alphabetized array as a qualified list with
single quotation marks around each full name.    --->
<cfset qualifiedList1 = ListQualify(myList,"'",",","CHAR")>

<!--- output the array as a list --->
<cfoutput>
    <p>The contents of the qualified list are as follows:	</p>
    <p>#qualifiedList1#</p>
</cfoutput>

<!--- show the resulting alphabetized array as a qualified list with quotation
marks around each full name. We use &quot; to denote quotation marks
because the quotation mark character is a control character. --->
<cfset qualifiedList2 = ListQualify(myList,"&quot;",",","CHAR")>

<!--- output the array as a list --->
<cfoutput>
    <p>The contents of the second qualified list are:	</p>
    <p>#qualifiedList2#</p>
</cfoutput>


ListRest

Description

Gets a list, without its first element.

Returns

A copy of list, without the first element. If list has one element, returns an empty list.

Category

List functions

Function syntax

ListRest(list [, delimiters ])

See also

ListFirst, ListGetAt, ListLast; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

If the list begins with one or more empty entries, this function drops them, as well as the first element.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListFirst, ListLast, and ListRest Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
    SELECT Username, Subject, Posted
    FROM  Messages
</cfquery>

<cfset temp = ValueList(GetMessageUser.Username)>
<p>Before editing the list, it is:&nbsp;
<cfoutput>#ValueList(GetMessageUser.Username)#</cfoutput>.
<p>(Users who posted more than once are listed more than once.)
<p>The first user in the list is:
<cfoutput>#ListFirst(temp)# </cfoutput>
<p>The rest of the list is:&nbsp;<cfoutput>#ListRest(temp)#</cfoutput>.
<p>(Users who posted more than once are listed more than once.)
<p>The last user in the list is: <cfoutput>#ListLast(temp)#</cfoutput>


ListSetAt

Description

Replaces the contents of a list element.

Returns

A copy of a list, with a new value assigned to the element at a specified position.

Category

List functions

Function syntax

ListSetAt(list, position, value [, delimiters ])

See also

ListDeleteAt, ListGetAt, ListInsertAt; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed delimiter modification: ColdFusion MX does not modify delimiters in the list. (In earlier releases, in some cases, replaced delimiters with the first character in the delimiters parameter.)

Parameters

Parameter

Description

list

A list or a variable that contains one.

position

A positive integer or a variable that contains one. Position at which to set a value. The first list position is 1.

value

An element or a list of elements.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Usage

When assigning an element to a list, ColdFusion inserts a delimiter. If delimiters contains more than one delimiter, ColdFusion uses the first delimiter in the string, or, if delimiters was omitted, a comma.

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListSetAt Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
SELECT Username, Subject, Posted
FROM  Messages
</cfquery>

<cfset temp = ValueList(GetMessageUser.Subject)>

<!--- loop through the list and show it with ListGetAt --->
<h3>This is a list of <cfoutput>#ListLen(temp)#</cfoutput>
subjects posted in messages.</h3>

<cfset ChangedElement = ListGetAt(temp, 2)>
<cfset TempToo = ListSetAt(temp, 2, "I changed this subject", ",")>
<ul>
<cfloop From = "1" To = "#ListLen(temptoo)#" INDEX = "Counter">
    <cfoutput><li>(#Counter#) SUBJECT: #ListGetAt(temptoo, Counter)#
    </cfoutput>
</cfloop>
</ul>
<p>Note that element 2, "<cfoutput>#changedElement#</cfoutput>",
has been altered to "I changed this subject" using ListSetAt.


ListSort

Description

Sorts list elements according to a sort type and sort order.

Returns

A copy of a list, sorted.

Category

List functions

Function syntax

ListSort(list, sort_type [, sort_order] [, delimiters ])

See also

Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed the order in which sorted elements are returned: in a textnocase, descending sort, this function might return elements in a different sort order than in earlier releases. If sort_type = "textnocase" and sort_order = "desc", ColdFusion MX processes elements that differ only in case differently from earlier releases. ColdFusion MX outputs the elements in the reverse of the ascending order. Earlier releases do not change order of elements that differ only in case. Both operations are correct. The new operation ensures that an ascending and descending sort output elements in exactly reverse order.

For example, in a textnocase, desc sort of d,a,a,b,A, the following occurs:

  • ColdFusion MX returns d,b,A,a,a
  • Earlier ColdFusion releases return d,b,a,a,A

(In a textnocase, asc sort, all ColdFusion releases return a,a,A,b,d.)

Parameters

Parameter

Description

list

A list or a variable that contains one.

sort_type
  • numeric: sorts numbers
  • text: sorts text alphabetically, taking case into account (also known as case sensitive). All letters of one case precede the first letter of the other case:

- aabzABZ, if sort_order = "asc" (ascending sort)

- ZBAzbaa, if sort_order = "desc" (descending sort)

  • textnocase: sorts text alphabetically, without regard to case (also known as case-insensitive). A letter in varying cases precedes the next letter:

- aAaBbBzzZ, in an ascending sort; preserves original intra-letter order

- ZzzBbBaAa, in a descending sort; reverses original intra-letter order

sort_order
  • asc - ascending sort order. Default.

- aabzABZ or aAaBbBzzZ, depending on value of sort_type, for letters

- from smaller to larger, for numbers

  • desc - descending sort order.

- ZBAzbaa or ZzzBbBaAa, depending on value of sort_type, for letters

- from larger to smaller, for numbers

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion uses the first character in the string as the delimiter, and ignores the rest.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

Example

<h3>ListSort Example</h3>

<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
SELECT   Username, Subject, Posted
FROM     Messages
</cfquery>

<cfset myList = ValueList(GetMessageUser.UserName)>
<p>Here is the unsorted list. </p>
<cfoutput>#myList#
    </cfoutput>
<p>Here is the list sorted alphabetically:</p>
<cfset sortedList = ListSort(myList, "Text")>
<cfoutput>#sortedList#
    </cfoutput>

<p>Here is a numeric list that is to be sorted in descending order.</p>
<cfset sortedNums = ListSort("12,23,107,19,1,65","Numeric", "Desc")>
<cfoutput>#sortedNums# </cfoutput>

<p>Here is a list that must be sorted numerically, since it contains
negative and positive numbers, and decimal numbers. </p>
<cfset sortedNums2 = ListSort("23.75;-34,471:100,-9745","Numeric", "ASC", ";,:")>
<cfoutput>#sortedNums2# </cfoutput>

<p>Here is a list to be sorted alphabetically without consideration of case.</p>
<cfset sortedMix =
    ListSort("hello;123,HELLO:jeans,-345,887;ColdFusion:coldfusion",
        "TextNoCase", "ASC", ";,:")>
<cfoutput>#sortedMix# </cfoutput>


ListToArray

Description

Copies the elements of a list to an array.

Returns

An array

Category

Array functions, Conversion functions, List functions

Function syntax

ListToArray(list [, delimiters ])

See also

ArrayToList; Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
list | A list or a variable that contains one. You define a list variable with a cfset statement.
delimiters | A string or a variable that contains one. ColdFusion treats each character in the string as a delimiter. The default value is comma.

Usage

ColdFusion ignores empty list elements; thus, the list "a,b,c,,,d" has four elements.

ColdFusion treats each character in the delimiters parameter as a separate delimiter. Therefore, if the parameter is ",+" ColdFusion will break the list at either a comma or a plus sign.

Example

<h3>ListToArray Example</h3>
<!--- Find a list of users who wrote messages --->
<cfquery name = "GetMessageUser" datasource = "cfdocexamples">
SELECT Username, Subject, Posted
FROM  Messages
</cfquery>
<cfset myList = ValueList(GetMessageUser.UserName)>
<p>My list is a list with <cfoutput>#ListLen(myList)#</cfoutput>
 elements.
<cfset myArrayList = ListToArray(myList)>
<p>My array list is an array with <cfoutput>#ArrayLen(myArrayList)#
 </cfoutput> elements.


ListValueCount

Description

Counts instances of a specified value in a list. The search is case-sensitive.

Returns

The number of instances of value in the list.

Category

List functions, String functions

Function syntax

ListValueCount(list, value [, delimiters ])

See also

ListValueCountNoCase; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

value

String or number, or a variable that contains one. Item for which to search. The search is case-sensitive.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Example

<cfquery name = "SearchByDepartment" datasource = "cfdocexamples">
SELECT 	Department
FROM 	Employees
</cfquery>
<h3>ListValueCount Example</h3>
<p>This example uses ListValueCount to count employees in a department.

<form action = "listvaluecount.cfm">
<p>Select a department:</p>
    <select name = "departmentName">
            <option value = "Accounting">
                Accounting
            </OPTION>
            <option value = "Administration">
                Administration
            </OPTION>
            <option value = "Engineering">
                Engineering
            </OPTION>
            <option value = "Sales">
                Sales
            </OPTION>
    </select>
<input type = "Submit" name = "Submit" value = "Search Employee List">
</form>

<!--- wait to have a string for searching defined --->
<cfif IsDefined("FORM.Submit") and IsDefined("FORM.departmentName")>
    <cfset myList = ValueList(SearchByDepartment.Department)>
    <cfset numberInDepartment = ListValueCount(myList, FORM.departmentName)>

    <cfif numberInDepartment is 0>
        <h3>There are no employees in <cfoutput>#FORM.departmentName#</cfoutput></h3>
    <cfelseIf numberInDepartment is 1>
        <cfoutput>		<p>There is only one person in #FORM.departmentName#.
        </cfoutput>
    <cfelse>
        <cfoutput>		<p>There are #numberInDepartment# people in #FORM.departmentName#.
        </cfoutput>
    </cfif>
</cfif>


ListValueCountNoCase

Description

Counts instances of a specified value in a list. The search is case-insensitive.

Returns

The number of instances of value in the list.

Category

List functions

Function syntax

ListValueCountNoCase(list, value [, delimiters ])

See also

ListValueCount; Lists in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

list

A list or a variable that contains one.

value

String or number, or a variable that contains one. Item for which to search. The search is case-insensitive.

delimiters

A string or a variable that contains one. Character(s) that separate list elements. The default value is comma.

If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

Example

<cfquery name = "SearchByDepartment" datasource = "cfdocexamples">
SELECT 	Department
FROM 	Employees
</cfquery>

<h3>ListValueCountNoCase Example</h3>
<p>This example uses ListValueCountNoCase to count employees in a department.

<form action = "listvaluecountnocase.cfm">
<p>Select a department:</p>
    <select name = "departmentName">
            <option value = "Accounting">
                Accounting
            </OPTION>
            <option value = "Administration">
                Administration
            </OPTION>
            <option value = "Engineering">
                Engineering
            </OPTION>
            <option value = "Sales">
                Sales
            </OPTION>
    </select>
    </select>
<input type = "Submit" name = "Submit" value = "Search Employee List">
</form>
<!--- wait to have a string for searching defined --->
<cfif IsDefined("FORM.Submit") and IsDefined("FORM.departmentName")>
    <cfset myList = ValueList(SearchByDepartment.Department)>
    <cfset numberInDepartment = ListValueCountNoCase(myList,
        FORM.departmentName)>

    <cfif numberInDepartment is 0>
        <h3>There are no employees in <cfoutput>#FORM.departmentName#		</cfoutput></h3>
    <cfelseIf numberInDepartment is 1>
        <cfoutput>		<p>There is only one person in #FORM.departmentName#.
        </cfoutput>
    <cfelse>
        <cfoutput>		<p>There are #numberInDepartment# people in #FORM.departmentName#.
        </cfoutput>
    </cfif>
</cfif>


LJustify

Description

Left justifies characters in a string of a specified length.

Returns

A copy of a string, left-justified.

Category

Display and formatting functions, String functions

Function syntax

LJustify(string, length)

See also

CJustify, RJustify

Parameters

Parameter | Description
string | A string or a variable that contains one
length | Length of field in which to justify string

Example

<!--- This example shows how to use LJustify --->
<cfparam name = "jstring" default = "">

<cfif IsDefined("FORM.justifyString")>
    <cfset jstring = LJustify(FORM.justifyString, 35)>
</cfif>
<html>
<head>
    <title>LJustify Example</title>
</head>
<body>

<h3>LJustify Function</h3>
<p>Enter a string, and it will be left justified within the sample field

<form action = "ljustify.cfm">
<p><input type = "Text" value = "<cfoutput>#jString#</cfoutput>"
 size = 35 name = "justifyString">

<p><input type = "Submit" name = ""> <input type = "RESET">
</form>


Log

Description

Calculates the natural logarithm of a number. Natural logarithms are based on the constant e (2.71828182845904).

Returns

The natural logarithm of a number.

Category

Mathematical functions

Function syntax

Log(number)

See also

Exp, Log10

Parameters

Parameter | Description
number | Positive real number for which to calculate the natural logarithm

Example

<h3>Log Example</h3>

<cfif IsDefined("FORM.number")>
    <cfoutput>
        <p>Your number, #FORM.number#
        <br>#FORM.number# raised to the E power: #exp(FORM.number)#
        <cfif FORM.number LTE 0><br>Enter a positive real number to get its
natural logarithm
            <cfelse><br>The natural logarithm 	of #FORM.number#: #log(FORM.number)#
        </cfif>
        <cfif FORM.number LTE 0><br>Enter a positive real number to get its
logarithm to base 10
            <cfelse><br>The logarithm of #FORM.number# to base 10: #log10(FORM.number)#
        </cfif>
    </cfoutput>
</cfif>
<cfform action = "log.cfm">
Enter a number to see its value raised to the E power, its natural logarithm,
and the logarithm of number to base 10.
<cfinput type = "Text" name = "number" message = "You must enter a number"
validate = "float" required = "No">
<input type = "Submit" name = "">
</cfform>


Log10

Description

Calculates the logarithm of number, to base 10.

Returns

Number; the logarithm of number, to base 10.

Category

Mathematical functions

Function syntax

Log10(number)

See also

Exp, Log

Parameters

Parameter | Description
number | Positive real number for which to calculate the logarithm

Example

<h3>Log10 Example</h3>
<cfif IsDefined("FORM.number")>
    <cfoutput>
        <p>Your number, #FORM.number#
        <br>#FORM.number# raised to the E power: #exp(FORM.number)#
        <cfif FORM.number LTE 0><br>You must enter a positive real number to
see the natural logarithm of that number
        <cfelse><br>The natural logarithm of #FORM.number#: #log(FORM.number)#
        </cfif>
        <cfif #FORM.number# LTE 0><br>You must enter a positive real number to
see the logarithm of that number to base 10
        <cfelse><br>The logarithm of #FORM.number# to base 10: #log10(FORM.number)#
        </cfif>
    </cfoutput>
</cfif>
<cfform action = "log10.cfm">
Enter a number to find its value raised to the E power, its natural
logarithm, and the logarithm of number to base 10.
<cfinput type = "Text" name = "number" message = "You must enter a number"
validate = "float" required = "No">
<input type = "Submit" name = "">
</cfform>


LSCurrencyFormat

Description

Formats a number in a locale-specific currency format. For countries that use the euro, the result depends on the JVM.

Returns

A formatted currency value.

Category

Display and formatting functions, International functions

Function syntax

LSCurrencyFormat(number [, type ])

See also

LSEuroCurrencyFormat, LSIsCurrency, LSParseCurrency, LSParseEuroCurrency, SetLocale; Handling data in ColdFusion MX in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. If a negative number is passed to it, it returns a negative number. If type = "local", it returns the value in the current locale’s standard format. If type = "international", it returns the value in the current locale’s international standard format. This function uses Java standard locale formatting rules on all platforms.

Parameters

Parameter

Description

number

Currency value

type
  • local: the currency format and currency symbol used in the locale.

- With JDK 1.3, the default for Euro Zone countries is their local currency.

- With JDK 1.4, the default for Euro Zone countries is the euro.

  • international: the international standard currency format and currency symbol of the locale.
  • none: the currency format used in the locale; no currency symbol

Usage

This function uses Java standard locale formatting rules on all platforms.

Note: With a Sun 1.3.1-compliant JVM, use the LSEuroCurrencyFormat function to format euro currency values.

Currency output

The following table shows sample currency output. For locales that use Euro, the Local and International columns contains two entries. The first is entry is the result with a Sun the 1.4.1-compliant JVM, the second entry is the result with a 1.3.1-compliant JVM.

Locale | Type = Local | Type = International | Type = None
Chinese (China) | ¥100,000.00 | CNY100,000.00 | 100,000.00
Chinese (Hong Kong) | HK$100,000.00 | HKD100,000.00 | 100,000.00
Chinese (Taiwan) | NT$100,000.00 | TWD100,000.00 | 100,000.00
Dutch (Belgian) | 100.000,00 ¤ 100.000,00 BF | BEF100.000,00 EUR100.000,00 | 100.000,00
Dutch (Standard) | ¤ 100.000,00 fl 100.000,00 | NLG100.000,00 EUR100.000,00 | 100.000,00
English (Australian) | $100,000.00 | AUD100,000.00 | 100,000.00
English (Canadian) | $100,000.00 | CAD100,000.00 | 100,000.00
English (New Zealand) | $100,000.00 | NZD100,000.00 | 100,000.00
English (UK) | £100,000.00 | GBP100,000.00 | 100,000.00
English (US) | $100,000.00 | USD100,000.00 | 100,000.00
French (Belgian) | 100.000,00 ¤ 100.000,00 FB | EUR100.000,00 BEF100.000,00 | 100.000,00
French (Canadian) | 100 000,00 $ | CAD100 000,00 | 100 000,00
French (Standard) | 100 000,00 ¤ 100 000,00 F | EUR100 000,00 FRF100 000,00 | 100 000,00
French (Swiss) | SFr. 100'000.00 | CHF100'000.00 | 100'000.00
German (Austrian) | ¤ 100.000,00 öS 100.000,00 | EUR100.000,00 ATS100.000,00 | 100.000,00
German (Standard) | 100.000,00 ¤ 100.000,00 DM | EUR100.000,00 DEM100.000,00 | 100.000,00
German (Swiss) | SFr. 100'000.00 | CHF100'000.00 | 100'000.00
Italian (Standard) | ¤ 100.000,00 L. 10.000.000 | EUR10.000.000 ITL10.000.000 | 10.000.000
Italian (Swiss) | SFr. 100'000.00 | CHF100'000.00 | 100'000.00
Japanese | ¥100,000 | JPY100,000 | JPY100,000
Korean | W100,000 | KRW100,000 | 100,000
Norwegian (Bokmal) | kr 100 000,00 | NOK100 000,00 | 100 000,00
Norwegian (Nynorsk) | kr 100 000,00 | NOK100 000,00 | 100 000,00
Portuguese (Brazilian) | R$100.000,00 | BRC100.000,00 | 100.000,00
Portuguese (Standard) | 100.000,00 ¤ R$100.000,00 | EUR100.000,00 BRC100.000,00 | 100.000,00
Spanish (Mexican) | $100,000.00 | MXN100,000.00 | 100,000.00
Spanish (Modern) | 100.000,00 ¤ 10.000.000 Pts | EUR10.000.000 ESP10.000.000 | 10.000.000
Spanish (Standard) | 100.000,00 ¤ 10.000.000 Pts | ESP10.000.000 EUR10.000.000 | 10.000.000
Swedish | 100.000,00 kr | SEK100.000,00 | 100.000,00

Note: ColdFusion maps Spanish (Modern) to the Spanish (Standard) format.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>LSCurrencyFormat Example</h3>
<p>LSCurrencyFormat returns a currency value using the locale
convention. Default value is "local."
<!--- loop through list of locales; show currency values for 100,000 units --->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>
    <cfoutput><p><b><I>#locale#</I></b><br>
        Local: #LSCurrencyFormat(100000, "local")#<br>
        International: #LSCurrencyFormat(100000, "international")#<br>
        None: #LSCurrencyFormat(100000, "none")#<br>
        <hr noshade>
    </cfoutput>
</cfloop>


LSDateFormat

Description

Formats the date part of a date/time value in a locale-specific format.

Returns

A formatted date/time value. If no mask is specified, the value is formatted according to the locale setting of the client computer.

Category

Date and time functions, Display and formatting functions, International functions

Function syntax

LSDateFormat(date [, mask ])

See also

LSParseDateTime, LSTimeFormat, DateFormat, SetLocale; Handling data in ColdFusion MX in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms.
  • Added support for the following mask parameter options: short, medium, long, and full.

Parameters

Parameter

Description

date

A date/time object, in the range 100 AD–9999 AD.

mask

Characters that show how ColdFusion displays the date:

  • d: Day of month. Digits; no leading zero for single-digit days
  • dd: Day of month. Digits; leading zero for single-digit days
  • ddd: Day of week, abbreviation
  • dddd: Day of week. Full name
  • m: Month. Digits; no leading zero for single-digit months
  • mm: Month. Digits; leading zero for single-digit months
  • mmm: Month. abbreviation (if appropriate)
  • mmmm: Month. Full name
  • y: Year. Last two digits; no leading zero for years less than 10
  • yy: Year. Last two digits; leading zero for years less than 10
  • yyyy: Year. Four digits
  • gg: Period/era string. Not processed. Reserved for future use

The following conform to Java locale-specific time encoding standards. Their exact formats depend on the locale:

  • short: dd, mm, and yy separated by / marks
  • medium: text format using mmm, d, and yyyy
  • long: text format using mmmm, d, and yyyy
  • full: text format using dddd, mmmm, d, and yyyy

The default value is medium

For more information on formats, see LSParseDateTime.

Usage

This function uses Java standard locale formatting rules on all platforms.

When passing date/time value as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

To calculate a difference between time zones, use the GetTimeZoneInfo function.

Example

<h3>LSDateFormat Example</h3>
<p>LSDateFormat formats the date part of a date/time value using the
locale convention.
<!--- loop through a list of locales; show date values for Now()--->
<cfloop list = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>

    <cfoutput><p><B><I>#locale#</I></B><br>
        #LSDateFormat(Now(), "mmm-dd-yyyy")#<br>
        #LSDateFormat(Now(), "mmmm d, yyyy")#<br>
        #LSDateFormat(Now(), "mm/dd/yyyy")#<br>
        #LSDateFormat(Now(), "d-mmm-yyyy")#<br>
        #LSDateFormat(Now(), "ddd, mmmm dd, yyyy")#<br>
        #LSDateFormat(Now(), "d/m/yy")#<br>
        #LSDateFormat(Now())#<br>
        <hr noshade>
    </cfoutput>
</cfloop>


LSEuroCurrencyFormat

Description

Formats a number in a locale-specific currency format.

Returns

A formatted currency value. For countries in the Euro currency zone, the function uses the locale’s rule’s for formatting currency in euros.

Category

Display and formatting functions, International functions

Function syntax

LSEuroCurrencyFormat(currency-number [, type ])

See also

LSParseEuroCurrency, LSCurrencyFormat, SetLocale; Locale-specific content in Developing Globalized Applications ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java locale formatting rules on all platforms, except that it uses the rule detailed in the Usage section for countries in the Euro currency zone. As a result, it format currencies for non Euro zone locales using the country’s currency, not euros.

Parameters

Parameter

Description

currency-number

Currency value.

type
  • local: the currency format used in the locale. (Default.)
  • international: the international standard currency format of the locale. For example, EUR10.00
  • none: the currency format used in the locale; no currency symbol

Usage

This function uses euro currency formatting rules for all JVM versions, as follows:

  • If the country of the current locale belongs to the Euro Zone (whose members have converted to the euro) the formatted output for the local type includes the Euro currency sign (€); for the international type, the output includes the euro currency symbol (EUR). If the value is negative, the format includes a negative sign before the value or parentheses around the value, according to the formatting rules of the current locale.
  • If the country of the current locale is not in the Euro Zone, the currency sign or symbol of the current locale displays. If the value is negative, the format includes a negative sign before the value or parentheses around the value, according to the formatting rules of the current locale.

For a list of the locale options that ColdFusion supports, and information on setting the default display format of date, time, number, and currency values, see SetLocale .


Currency output

The following table shows examples of currency output:

Locale | Type = Local | Type = International | Type = None
Chinese (China) | ¥100,000.00 | CNY100,000.00 | 100,000.00
Chinese (Hong Kong) | HK$100,000.00 | HKD100,000.00 | 100,000.00
Chinese (Taiwan) | NT$100,000.00 | TWD100,000.00 | 100,000.00
Dutch (Belgian) | 100.000,00 ¤ | EUR100.000,00 | 100.000,00
Dutch (Standard) | ¤ 100.000,00 | EUR100.000,00 | 100.000,00
English (Australian) | $100,000.00 | AUD100,000.00 | 100,000.00
English (Canadian) | $100,000.00 | CAD100,000.00 | 100,000.00
English (New Zealand) | $100,000.00 | NZD100,000.00 | 100,000.00
English (UK) | £100,000.00 | GBP100,000.00 | 100,000.00
English (US) | $100,000.00 | USD100,000.00 | 100,000.00
French (Belgian) | 100.000,00 ¤ | EUR100.000,00 | 100.000,00
French (Canadian) | 100 000,00 $ | CAD100 000,00 | 100 000,00
French (Standard) | 100 000,00 ¤ | EUR100 000,00 | 100 000,00
French (Swiss) | SFr. 100'000.00 | CHF100'000.00 | 100'000.00
German (Austrian) | ¤ 100.000,00 | EUR100.000,00 | 100.000,00
German (Standard) | 100.000,00 ¤ | EUR100.000,00 | 100.000,00
German (Swiss) | SFr. 100'000.00 | CHF100'000.00 | 100'000.00
Italian (Standard) | ¤ 100.000,00 | EUR10.000.000 | 10.000.000
Italian (Swiss) | SFr. 100'000.00 | CHF100'000.00 | 100'000.00
Japanese | ¥100,000 | JPY100,000 | JPY100,000
Korean | W100,000 | KRW100,000 | 100,000
Norwegian (Bokmal) | kr 100 000,00 | NOK100 000,00 | 100 000,00
Norwegian (Nynorsk) | kr 100 000,00 | NOK100 000,00 | 100 000,00
Portuguese (Brazilian) | R$100.000,00 | BRC100.000,00 | 100.000,00
Portuguese (Standard) | 100.000,00 ¤ | EUR100.000,00 | 100.000,00
Spanish (Mexican) | $100,000.00 | MXN100,000.00 | 100,000.00
Spanish (Modern) | 100.000,00 ¤ | EUR10.000.000 | 10.000.000
Spanish (Standard) | 100.000,00 ¤ | ESP10.000.000 | 10.000.000
Swedish | 100.000,00 kr | SEK100.000,00 | 100.000,00

Note: ColdFusion uses the Spanish (Standard) formats for Spanish (Modern) and Spanish (Standard).

The following example shows how the function formats negative values. The format includes a negative sign before the value, or parentheses around the value, according to the formatting rules of the current locale.

Input value | Output if locale = French (Standard) | Output if locale = English (US)
-1234.56 | -1 234,56 ¤ | ($1,234.56)

Example

<h3>LSEuroCurrencyFormat Example</h3>
<p>LSEuroCurrencyFormat returns a currency value using the locale
convention. Default value is "local."
<!--- Loop through list of locales, show currency values for 100,000 units --->
<cfloop list = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>
    <cfoutput><p><B><I>#locale#</I></B><br>
        Local: #LSEuroCurrencyFormat(100000, "local")#<br>
        International: #LSEuroCurrencyFormat(100000, "international")#<br>
        None: #LSEuroCurrencyFormat(100000, "none")#<br>
        <Hr noshade>
    </cfoutput>
</cfloop>


LSIsCurrency

Description

Determines whether a string is a valid representation of a currency amount in the current locale.

Returns

True, if the parameter is formatted as a valid currency amount, including the appropriate currency indicator. The return value is True for amounts in the local, international, or none currency formats.

Category

Display and formatting functions, Decision functions, International functions

Function syntax

LSIsCurrency(string)

See also

GetLocale, SetLocale, LSCurrencyFormat

History

ColdFusion MX: Changed formatting behavior: this function might return a different result than in earlier releases. This function uses Java standard locale formatting rules on all platforms; the results might vary depending upon the JVM; for example, Sun JVM 1.4.1 requires euro format the local currency if the current locale’s country belongs to the Euro Zone.

Parameters

Parameter | Description
string | A currency string or a variable that contains one.

Usage

For examples of ColdFusion code and output that shows differences between earlier ColdFusion releases and ColdFusion MX in accepting input formats and displaying output, see LSCurrencyFormat .

Note: If the locale belongs to a Euro zone country and the currency is a correctly formatted euro value for the locale, this function returns True for all JVMs, including Sun 1.3.1. As a result, with 1.3.1-compliant JVMs, the LSIsCurrency function does not ensure that LSParseCurrency returns a value. If a currency uses the older country-specific format for Euro Zone locales, the LSIsCurrency function returns False for newer JVMs, such as Sun 1.4.1, and True for older JVMs, such as Sun 1.3.1.

Note: To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>LSIsCurrency Example</h3>

<cfif IsDefined("FORM.locale")>
<!--- if locale is defined, set locale to that entry --->
<cfset NewLocale = SetLocale(FORM.locale)>

<p>Is the value "<cfoutput>#FORM.myValue#</cfoutput>"
a proper currency value for <cfoutput>#GetLocale()#</cfoutput>?
<p>Answer: <cfoutput>#LSIsCurrency(FORM.myValue)#</cfoutput>
</cfif>

<p><form action = "LSIsCurrency.cfm">
<p>Select a locale for which you would like to check a currency value:
<!--- check the current locale for server --->
<cfset serverLocale = GetLocale()>


LSIsDate

Description

Determines whether a string is a valid representation of a date/time value in the current locale.

Returns

True, if the string can be formatted as a date/time value in the current locale; False, otherwise.

Category

Date and time functions, Display and formatting functions, International functions

Function syntax

LSIsDate(string)

See also

CreateDateTime, GetLocale, IsNumericDate, LSDateFormat, ParseDateTime, SetLocale; Handling data in ColdFusion MX in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed formatting behavior: this function might return a different result than in earlier releases. This function uses Java standard locale formatting rules on all platforms.
  • Changed behavior: this function accepts a dash or hyphen character only in the Dutch(Standard) and Portuguese (Standard) locales. If called this way (for example, LsIsDate("3-1-2002") in any other locale, this function returns False. (Earlier releases returned True.)
  • Changed behavior: when using the SUN JRE 1.3.1 on an English(UK) locale, this function returns False for a date that has a one-digit month or day (for example, 1/1/01). To work around this, insert a zero in a one-digit month or day (for example, 01/01/01).

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

A date/time object is in the range 100 AD–9999 AD.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>LSIsDate Example</h3>
<cfif IsDefined("FORM.locale")>
    <!--- if locale is defined, set locale to that entry --->
    <cfset NewLocale = SetLocale(FORM.locale)>
    <p>Is the value "<cfoutput>#FORM.myValue#</cFOUTPUT>" a proper date
value for <cfoutput>#GetLocale()#</cfoutput>?
    <p>Answer: <cfoutput>#LSIsDate(FORM.myValue)#</cfoutput>
</cfif>
<p><form action = "LSIsDate.cfm">
<p>Select a locale for which you would like to check a date value:
<!--- check the current locale for server --->
<cfset serverLocale = GetLocale()>


LSIsNumeric

Description

Determines whether a string is a valid representation of a number in the current locale.

Returns

True, if the string represents a number the current locale; False, otherwise.

Category

Decision functions, International functions, String functions

Function syntax

LSIsNumeric(string)

See also

GetLocale, SetLocale; Handling data in ColdFusion MX in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed formatting behavior: this function might return a different result than in earlier releases. This function uses Java standard locale formatting rules on all platforms.

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>LSIsNumeric Example</h3>

<cfif IsDefined("FORM.locale")>
<!--- if locale is defined, set locale to that entry --->
<cfset NewLocale = SetLocale(FORM.locale)>

<p>Is the value "<cfoutput>#FORM.myValue#</cFOUTPUT>"
a proper numeric value for <cfoutput>#GetLocale()#</cfoutput>?

<p>Answer: <cfoutput>#LSIsNumeric(FORM.myValue)#</cfoutput>
</cfif>

<p><form action = "LSIsNumeric.cfm">

<p>Select a locale for which to check a numeric value:
...


LSNumberFormat

Description

Formats a number in a locale-specific format.

Returns

A formatted number.

  • If no mask is specified, it returns the number formatted as an integer
  • If no mask is specified, truncates the decimal part; for example, it truncates 34.57 to 35
  • If the specified mask cannot correctly mask a number, it returns the number unchanged
  • If the parameter value is "" (an empty string), it returns 0.

Category

Display and formatting functions, International functions

Function syntax

LSNumberFormat(number [, mask ])

See also

GetLocale, SetLocale; Handling data in ColdFusion MX in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed behavior: if the specified mask format cannot correctly mask a number, this function returns the number unchanged. (In earlier releases, it truncated the number or threw an error.) (If no mask is specified, ColdFusion MX truncates the decimal part as ColdFusion 5 does. For example, it truncates 1234.567 to 1235.)
  • Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms.

Parameters

Parameter | Description
number | Number to format
mask | LSNumberFormat mask characters apply, except: dollar sign, comma, and dot are mapped to their locale-specific equivalents.

The following table lists the LSNumberFormat mask characters:

Character | Meaning
_ | (Underscore.) Digit placeholder.
9 | Digit placeholder. (Shows decimal places more clearly than _ .)
. | Location of a mandatory decimal point (or locale-appropriate symbol).
0 | Located to the left or right of a mandatory decimal point. Pads with zeros.
( ) | If number is less than zero, puts parentheses around the mask.
+ | Puts plus sign before positive number; minus sign before negative number.
- | Puts space before positive number; minus sign before negative number.
, | Separates every third decimal place with a comma (or locale-appropriate symbol).
L,C | Left-justifies or center-justifies number within width of mask column. First character of mask must be L or C. The default value is right-justified.
$ | Puts a dollar sign (or locale-appropriate symbol) before formatted number. First character of mask must be the dollar sign ($).
^ | Separates left and right formatting.

Note: If you do not specify a sign for the mask, positive and negative numbers do not align in columns. To put a plus sign or space before positive numbers and a minus sign before negative numbers, use the plus or hyphen mask character, respectively.

Usage

This function uses Java standard locale formatting rules on all platforms.

The position of symbols in format masks determines where the codes take effect. For example, if you put a dollar sign at the far left of a format mask, ColdFusion displays a dollar sign at the left edge of the formatted number. If you separate the dollar sign on the left edge of the format mask by at least one underscore, ColdFusion displays the dollar sign just to the left of the digits in the formatted number.

These examples show how symbols determine formats:

Number | Mask | Result
4.37 | $____.__ | "$ 4.37"
4.37 | _$___.__ | " $4.37"

The positioning can also show where to put a minus sign for negative numbers:

Number | Mask | Result
-4.37 | -____.__ | "- 4.37"
-4.37 | _-___.__ | " -4.37"

The positions for a symbol are: far left, near left, near right, and far right. The left and right positions are determined by the side of the decimal point on which the code character is shown. For formats that do not have a fixed number of decimal places, you can use a caret (^) to separate the left fields from the right.

An underscore determines whether the code is placed in the far or near position. Most code characters’ effect is determined by the field in which they are located. This example shows how to specify where to put parentheses to display negative numbers:

Number | Mask | Result
3.21 | C(__^__) | "( 3.21 )"
3.21 | C__(^__) | " (3.21 )"
3.21 | C(__^)__ | "( 3.21) "
3.21 | C__(^)__ | " (3.21) "

To set the default display format of date, time, number, and currency values, use the SetLocale function.

When converting from string to double, to prevent rounding errors, this function adds a rounding factor of 1.5543122344752E-014 to the converted number. For example, without adding the rounding factor, converting the string value 1.275 to double with two digits of precision results in a value of 1.27499999999999999, which would be rounded up to 1.27. By adding the rounding factor, the conversion correctly results in a value of 1.28.

If you round off a double, such as 1.99499999999999999999999999999, where the last decimal is 10E-14, the rounding factor can cause an incorrect result.

Example

<h3>LSNumberFormat Example</h3>
<p>LSNumberFormat returns a number value using the locale convention.
<!--- loop through a list of locales and show number values --->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>
    <cfoutput><p><b><i>#locale#</i></b><br>
        #LSNumberFormat(-1234.5678, "_________")#<br>
        #LSNumberFormat(-1234.5678, "_________.___")#<br>
        #LSNumberFormat(1234.5678, "_________")#<br>
        #LSNumberFormat(1234.5678, "_________.___")#<br>
        #LSNumberFormat(1234.5678, "$_(_________.___)")#<br>
        #LSNumberFormat(-1234.5678, "$_(_________.___)")#<br>
        #LSNumberFormat(1234.5678, "+_________.___")#<br>
        #LSNumberFormat(1234.5678, "-_________.___")#<br>
    </cfoutput>
</cfloop>


LSParseCurrency

Description

Converts a locale-specific currency string into a formatted number. Attempts conversion by comparing the string with each the three supported currency formats (none, local, international) and using the first that matches.

Returns

A formatted number (string representation of a number) that matches the value of the parameter.

Category

International functions, String functions

Function syntax

LSParseCurrency(string)

See also

LSParseEuroCurrency , LSCurrencyFormat, LSEuroCurrencyFormat, LSIsCurrency; Locale-specific content in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms.

Parameters

Parameter | Description
string | A locale-specific string a variable that contains one

Usage

This function uses the locale formatting rules of the JVM (specified in the ColdFusion Administrator Java and JVM page) on all platforms. These rules changed between Sun JVM 1.3.1 and JVM 1.4.1:

  • JVM 1.3.1 requires that the local and international versions of currencies of countries in the Euro zone be formatted using the older, country-specific designations, such as 100.000,00 DM or DEM100.000,00 for the German (Standard) locale. Use the LSParseEuroCurrency function to parse euro currencies in these locales with JVM 1.3.1.
  • JVM 1.4.1 requires that currencies for Euro zone countries be expressed as euros; for example 100.000,00 € or EUR100.000,00.

Note: The LSIsCurrency function always returns True if the locale is in the Euro currency zone and the currency is expressed in euros, including when using JVM 1.3.1. As a result, with older JVMs, LSIsCurrency does not ensure that LSParseCurrency returns a value.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

For a list of the locale-specific formats used to parse the currency, see LSCurrencyFormat.

Example

<h3>LSParseCurrency Example</h3>
<p>LSParseCurrency coverts a locale-specific currency string to a number.
Attempts conversion through each of the three default currency formats.
<!--- loop through a list of locales; show currency values for 123,456 units --->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>
    <cfoutput><p><B><I>#locale#</I></B><br>
        Local: #LSCurrencyFormat(123456.78, "local")#<br>
        Parsed local Currency:
#LSParseCurrency(LSCurrencyFormat(123456,"local"))#<br>
        International: #LSCurrencyFormat(123456.78999, "international")#<br>
        Parsed International Currency:
#LSParseCurrency(LSCurrencyFormat(123456.78999,"international"))#<br>
        None: #LSCurrencyFormat(123456.78999, "none")#<br>
        Parsed None formatted currency:
#LSParseCurrency(LSCurrencyFormat(123456.78999,"none"))#<br>
        <hr noshade>
    </cfoutput>
</cfloop>


LSParseDateTime

Description

Converts a string that is a valid date/time representation in the current locale into a date/time object.

Returns

A date/time object.

Category

Date and time functions, Display and formatting functions, International functions, String functions

Function syntax

LSParseDateTime(date/time-string)

See also

LSDateFormat, ParseDateTime, SetLocale, GetLocale; Locales in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed formatting behavior: this function might not parse string formats that worked with earlier releases. This function uses Java standard locale formatting rules on all platforms.
  • Changed how the date/time-string parameter value is processed: ColdFusion processes the date/time-string parameter value time zone information differently than in earlier releases, as described in the Usage section.

Parameters

Parameter | Description
date/time-string | A string a variable that contains one, in a format that is readable in the current locale.

Usage

This function can parse any date, time, or date/time combination that conforms to Java standard locale formatting rules for the current locale.

The following table lists some of the date/time values you can pass to this function in the English (US) locale. You can also pass only the date or the time parts of these formats:

Format | Example
m/dd/yy h:mm:ss | 1/30/02 7:02:33
m/dd/yy h:mm tt | 1/30/02 7:02 AM
m/dd/yyyy h:mm | 1/30/2002 7:02 AM
mmm dd, yyyy h:mm:ss tt | Jan 30, 2002 7:02:12 AM
mmmm dd, yyyy h:mm:ss tt zzz | January 30, 2002 7:02:23 AM PST
ddd, mmm dd, yyyy hh:mm:ss | Wed, Jan 30, 2002 07:02:12
dddd, mmmm dd, yyyy h:mm:ss tt zzz | Wednesday, January 30, 2002 7:02:12 AM PST

Valid dates are in the range 100 AD–9999 AD. Two digit years in the range 00-29 are interpreted as being 2000-2029. Two digit years in the range 30-99 are interpreted as being 1930-1999

This function corrects for differences between the current time zone and any time zone specified in the input parameter.

  • If a time zone specified in the date/time-string parameter is different from the time zone setting of the computer, ColdFusion adjusts the time value to its equivalent in the computer time zone.
  • If a time zone is not specified in the date/time-string parameter, ColdFusion does not adjust the time value.

Note: This function does not accept POP dates, which include a time zone offset value.

Example

<h3>LSParseDateTime Example - returns a locale-specific date/time object</h3>
<!--- loop through a list of locales and show date values for Now()--->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>
    <cfoutput><p><B><I>#locale#</I></B><br>
        <p>Locale-specific formats:
        <br>#LSDateFormat(Now(), "mmm-dd-yyyy")# #LSTimeFormat(Now())#<br>
        #LSDateFormat(Now(), "mmmm d, yyyy")# #LSTimeFormat(Now())#<br>
        #LSDateFormat(Now(), "mm/dd/yyyy")# #LSTimeFormat(Now())#<br>
        #LSDateFormat(Now(), "d-mmm-yyyy")# #LSTimeFormat(Now())#<br>
        #LSDateFormat(Now(), "ddd, mmmm dd, yyyy")# #LSTimeFormat(Now())#<br>
        #LSDateFormat(Now(), "d/m/yy")# #LSTimeFormat(Now())#<br>
        #LSDateFormat(Now())# #LSTimeFormat(Now())#<br>
    <p>Standard Date/Time:
    #LSParseDateTime("#LSDateFormat(Now())# #LSTimeFormat(Now())#")#<br>
    </cfoutput>
</cfloop>


LSParseEuroCurrency

Description

Formats a locale-specific currency string as a number. Attempts conversion through each of the default currency formats (none, local, international). Ensures correct handling of euro currency for Euro zone countries.

Returns

A formatted number that matches the value of the string.

Category

International functions, String functions

Function syntax

LSParseEuroCurrency(currency-string)

See also

LSParseCurrency, LSEuroCurrencyFormat, SetLocale; Locale-specific content in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java locale formatting rules on all platforms, except that it uses the rule detailed in the Usage section for countries in the Euro currency zone.

Parameters

Parameter | Description
currency-string | Locale-specific string or a variable that contains one.

Usage

This function determines whether the current locale’s country belongs to the Euro Zone, whose members have converted to the euro; if so, the currency-string parameter must be formatted in euros on all JVMs, including Sun JVM 1.3.1. If the country is not in the Euro zone, the string must follow the locale formatting rules of the JVM. For examples of valid currency formats in all supported locales, see LSEuroCurrencyFormat .

For a list of the locale options that ColdFusion supports, and information on setting the default display format of date, time, number, and currency values, see SetLocale .

Example

<h3>LSParseEuroCurrency Example</h3>
<p>Loop through all available locales. Create string representations of the value
    123,456 in the three supported currency formats,
    and parse the results back to numbers.<p>
<cfloop list="#Server.Coldfusion.SupportedLocales#" index="locale" delimiters=",">
    <cfset oldlocale = SetLocale(locale)>
    <cfoutput><p>Current Locale: <b><i>#locale#</i></b><br>
    <cfset localCurrency = LSEuroCurrencyFormat(123456, "local")>
        Value in local currency: #localCurrency#<br>
        Parsed using LSParseEuroCurrency:
        #LSParseEuroCurrency(localCurrency)#<br>
    <cfset IntlCurrency = LSEuroCurrencyFormat(123456, "international")>
        Value with International currency formatting: #IntlCurrency#<br>
        Parsed using LSParseEuroCurrency:
        #LSParseEuroCurrency(IntlCurrency)#<br>
    <cfset Currency = LSEuroCurrencyFormat(123456, "none")>
        Value with no currency formatting: #currency#<br>
        Parsed using LSParseEuroCurrency:
        #LSParseEuroCurrency(Currency)#<br>
        <hr noshade>
    </cfoutput>
</cfloop>


LSParseNumber

Description

Converts a string that is a valid numeric representation in the current locale into a formatted number.

Returns

A formatted number that matches the value of the string.

Category

International functions, String functions

Function syntax

LSParseNumber(string)

See also

LSParseDateTime, SetLocale; Locales in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms.

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

This function uses Java standard locale formatting rules on all platforms.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>LSParseNumber Example</h3>
<p>LSParseNumber converts a locale-specific string to a number.
Returns the number matching the value of string.
<!--- loop through a list of locales and show number values --->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>

    <cfoutput><p><B><I>#locale#</I></B><br>
        #LSNumberFormat(-1234.5678, "_________")#<br>
        #LSNumberFormat(-1234.5678, "_________.___")#<br>
        #LSNumberFormat(1234.5678, "_________")#<br>
        #LSNumberFormat(1234.5678, "_________.___")#<br>
        #LSNumberFormat(1234.5678, "$_(_________.___)")#<br>
        #LSNumberFormat(-1234.5678, "$_(_________.___)")#<br>
        #LSNumberFormat(1234.5678, "+_________.___")#<br>
        #LSNumberFormat(1234.5678, "-_________.___")#<br>
        The actual number:
            #LSParseNumber(LSNumberFormat(1234.5678, "_________"))#<br>
        <hr noshade>
    </cfoutput>
</cfloop>


LSTimeFormat

Description

Formats the time part of a date/time string into a string in a locale-specific format.

Returns

A string representing the time value.

Category

Date and time functions, Display and formatting functions, International functions

Function syntax

LSTimeFormat(time [, mask ])

See also

LSParseDateTime, LSDateFormat, TimeFormat; Locales in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.1: Added the mask character L or l to represent milliseconds.

ColdFusion MX:

  • Changed formatting behavior: this function might return different formatting than in earlier releases. This function uses Java standard locale formatting rules on all platforms.
  • Added support for the following mask parameter options: short, medium, long, and full.

Parameters

Parameter

Description

string
  • A date/time value
  • A string that is convertible to a time value

A date/time object is in the range 100 AD–9999 AD.

mask

Masking characters that determine the format:

  • h: Hours; no leading zero for single-digit hours (12-hour clock)
  • hh: Hours; leading zero for single-digit hours. (12-hour clock)
  • H: Hours; no leading zero for single-digit hours (24-hour clock)
  • HH: Hours; leading zero for single-digit hours (24-hour clock)
  • m: Minutes; no leading zero for single-digit minutes
  • mm: Minutes; leading zero for single-digit minutes
  • s: Seconds; no leading zero for single-digit seconds
  • ss: Seconds; leading zero for single-digit seconds
  • l: Milliseconds
  • t: One-character time marker string, such as A or P.
  • tt: Multiple-character time marker string, such as AM or PM

The following conform to Java locale-specific time encoding standards. Their exact formats depend on the locale:

  • short: includes hours, minutes; may include AM or PM
  • medium: includes hours, minutes; may include AM or PM
  • long: medium plus time zone
  • full: long, may also include an hour designator

The default value is short.

Usage

This function uses Java standard locale formatting rules on all platforms.

When passing date/time value as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

To calculate a difference between time zones, use the GetTimeZoneInfo function.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

If no seconds value is passed to this function, and the mask value is s, the default output seconds format is one zero; for example, lstimeformat(6:39, "h:m:s") returns 6:39:0. If the mask value is ss, it returns 6:39:00.

Example

<h3>LSTimeFormat Example</h3>

<p>LSTimeFormat returns a time value using the locale convention.

<!--- loop through a list of locales and show time values --->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>

    <cfoutput><p><B><I>#locale#</I></B><br>
    #LSTimeFormat(Now())#<br>
    #LSTimeFormat(Now(), ‘hh:mm:ss’)#<br>
    #LSTimeFormat(Now(), ‘hh:mm:sst’)#<br>
    #LSTimeFormat(Now(), ‘hh:mm:sstt’)#<br>
    #LSTimeFormat(Now(), ‘HH:mm:ss’)#<br>
        <hr noshade>
    </cfoutput>

</cfloop>


LTrim

Description

Removes leading spaces from a string.

Returns

A copy of the string, without leading spaces.

Category

Display and formatting functions, String functions

Function syntax

LTrim(string)

See also

RTrim, ToBase64

Parameters

Parameter | Description
string | A string or a variable that contains one

Example

<h3>LTrim Example</h3>

<cfif IsDefined("FORM.myText")>
<cfoutput>
<pre>
Your string:	"#FORM.myText#"
Your string:	"#LTrim(FORM.myText)#"
(left trimmed)
</pre>
</cfoutput>
</cfif>

<form action = "ltrim.cfm">
<p>Type in some text, and it will be modified by LTrim to remove
leading spaces from the left
<p><input type = "Text" name = "myText" value = "   TEST">

<p><input type = "Submit" name = "">
</form>


Max

Description

Determines the greater of two numbers.

Returns

The greater of two numbers.

Category

Mathematical functions

Function syntax

Max(number1, number2)

See also

Min

Parameters

Parameter | Description
number1, number2 | Numbers

Example

<h3>Max Example</h3>
<cfif IsDefined("FORM.myNum1")>
    <cfif IsNumeric(FORM.myNum1) and IsNumeric(FORM.myNum2)>
    <p>The maximum of the two numbers is <cfoutput>#Max(FORM.myNum1,
     FORM.myNum2)#</cfoutput>
    <p>The minimum of the two numbers is <cfoutput>#Min(FORM.myNum1,
     FORM.myNum2)#</cfoutput>
    <cfelse>
    <p>Please enter two numbers
    </cfif>
</cfif>

<form action = "max.cfm">
<h3>Enter two numbers, see the maximum and minimum of them</h3>

Number 1 <input type = "Text" name = "MyNum1">
<br>Number 2 <input type = "Text" name = "MyNum2">

<br><input type = "Submit" name = "" value = "See results">
</form>


Mid

Description

Extracts a substring from a string.

Returns

A string; the set of characters from string, beginning at start, of length count.

Category

String functions

Function syntax

Mid(string, start, count)

See also

Left, Len, Right

Parameters

Parameter | Description
string | A string or a variable that contains one. Must be single-quotation mark or double-quotation mark delimited.
start | A positive integer or a variable that contains one. Position at which to start count. Positions start with 1, not 0.
count | A positive integer or a variable that contains one. Number of characters to return. (Zero is not valid, but it does not throw an error.)

Example

<h3>Mid Example</h3>

<cfif IsDefined("Form.myText")>
    <!--- If len returns 0 (zero), then show error message. --->
    <cfif Len(Form.myText)>
        <cfif Len(Form.myText) LTE Form.RemoveChars>
            <cfoutput><p style="color: red; font-weight: bold">Your string
            #Form.myText# only has #Len(Form.myText)# characters. You cannot output
            the #Form.removeChars# middle characters of this string because it is
            not long enough.</p></cfoutput>
        <cfelseif Form.startPos GTE Len(Form.myText)>
            <cfoutput><p style="color: red; font-weight: bold">Your string
            #Form.myText# only has #Len(Form.myText)# characters. You cannot start
            at position #Form.startPos#.</p></cfoutput>
        <cfelse>
            <cfoutput><p>Your original string: <strong>#Form.myText#</strong></p>
            <p>Your changed string, showing only the <strong>#Form.removeChars#
            </strong> middle characters: <strong>#Mid(Form.myText,
            Form.startPos, Form.removeChars)#</strong></p></cfoutput>
        </cfif>
    <cfelse>
        <p style="color: red; font-weight: bold">Please enter a string of more
        than 0 (zero) characters.</p>
    </cfif>
</cfif>

<form action="<cfoutput>#CGI.ScriptName#</cfoutput>" method="POST">
<p>Type in some text<br />
<input type="Text" name="myText"></p>
<p>Enter a starting position (from the beginning of the entered text)<br />
<input name="startPos" type="text" size="1"></p>
<p>How many characters do you want to show?
<select name="RemoveChars">
<option value="1">1
<option value="3" selected>3
<option value="5">5
<option value="7">7
<option value="9">9</select>
<input type="Submit" name="Submit" value="Remove characters"></p>
</form>


Min

Description

Determines the lesser of two numbers.

Returns

The lesser of two numbers.

Category

Mathematical functions

Function syntax

Min(number1, number2)

See also

Max

Parameters

Parameter | Description
number1, number2 | Numbers

Example

<h3>Min Example</h3>
<cfif IsDefined("FORM.myNum1")>
    <cfif IsNumeric(FORM.myNum1) and IsNumeric(FORM.myNum2)>
    <p>The maximum of the two numbers is <cfoutput>#Max(FORM.myNum1,
     FORM.myNum2)#</cfoutput>
    <p>The minimum of the two numbers is <cfoutput>#Min(FORM.myNum1,
     FORM.myNum2)#</cfoutput>
    <cfelse>
    <p>Please enter two numbers
    </cfif>
</cfif>

<form action = "min.cfm">
<h3>Enter two numbers, and see the maximum and minimum of the two numbers</h3>

Number 1 <input type = "Text" name = "MyNum1">
<br>Number 2 <input type = "Text" name = "MyNum2">

<br><input type = "Submit" name = "" value = "See results">
</form>


Minute

Description

Extracts the minute value from a date/time object.

Returns

The ordinal value of the minute, in the range 0–59.

Category

Date and time functions

Function syntax

Minute(date)

See also

DatePart, Hash, Second

Parameters

Parameter

Description

date
  • A date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Example

<h3>Minute Example</h3>

<cfoutput>
The time is currently #TimeFormat(Now())#.
We are in hour #Hour(Now())#, Minute #Minute(Now())#
and Second #Second(Now())# of the day.
</cfoutput>


Month

Description

Extracts the month value from a date/time object.

Returns

The ordinal value of the month, in the range 1 (January) – 12 (December).

Category

Date and time functions

Function syntax

Month(date)

See also

DatePart, MonthAsString, Quarter

Parameters

Parameter | Description
date | Date/time object, in the range 100 AD–9999 AD.

Usage

When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Note: You can pass the CreateDate function or the Now function as the date parameter of this function; for example: #Month(CreateDate(2001, 3, 3))#.

Example

<h3>Month Example</h3>
<cfif IsDefined("FORM.year")>
More information about your date:
<cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
<cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayofWeekAsString(DayOfWeek(yourDate))#, day
     #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(yourDate)# in the month of
     #MonthAsString(Month(yourDate))#, which has
     #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(yourDate)#
     (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#). <br>
    <cfif IsLeapYear(Year(yourDat"))>This is a leap year
        <cfelse>This is not a leap year
    </cfif>
</cfoutput>
</cfif>


MonthAsString

Description

Determines the name of the month that corresponds to month_number.

Returns

A string; the name of the specified month, in the current locale.

Category

Date and time functions, String functions

Function syntax

MonthAsString(month_number)

See also

DatePart, Month, Quarter

Parameters

Parameter | Description
month_number | An integer in the range 1 – 12.

Example

<h3>MonthAsString Example</h3>

<cfif IsDefined("FORM.year")>
<p>More information about your date:
<cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>

<cfoutput>
<p>Your date, #DateFormat(yourDate)#.
<br>It is #DayofWeekAsString(DayOfWeek(yourDate))#, day
 #DayOfWeek(yourDate)# in the week.
<br>This is day #Day(YourDate)# in the month of
 #MonthAsString(Month(yourDate))#, which has
  #DaysInMonth(yourDate)# days.
<br>We are in week #Week(yourDate)# of #Year(yourDate)#
    (day #DayofYear(yourDate)# of #DaysinYear(yourDate)#). <br>
    <cfif IsLeapYear(Year(yourDate))>This is a leap year
        <cfelse>This is not a leap year
    </cfif>
</cfoutput>
</cfif>


Now

Description

Gets the current date and time of the computer running the ColdFusion server. The return value can be passed as a parameter to date functions such as DaysInYear or FirstDayOfMonth.

Returns

A date/time object; the current date and time of the computer running the ColdFusion server.

Category

Date and time functions

Function syntax

Now()

See also

CreateDateTime, DatePart

Example

<h3>Now Example</h3>
<p>Now returns the current date and time as a valid date/time object.

<p>The current date/time value is <cfoutput>#Now()#</cfoutput>
<p>You can also represent this as <cfoutput>#DateFormat(Now())#,
 #TimeFormat(Now())#</cfoutput>


NumberFormat

Description

Creates a custom-formatted number value. Supports the numeric formatting used in the U.S. For international number formatting, see LSNumberFormat.

Returns

A formatted number value:

  • If no mask is specified, returns the value as an integer with a thousands separator.
  • If the parameter value is "" (an empty string), returns 0.

Category

Display and formatting functions

Function syntax

NumberFormat(number [, mask ])

See also

DecimalFormat, DollarFormat, IsNumeric, LSNumberFormat

History

ColdFusion MX: Changed behavior: if the mask format cannot correctly mask a number, this function returns the number unchanged. (It does not truncate the number nor throw an error.) (If no mask is selected, ColdFusion MX rounds the decimal part as ColdFusion 5 does. For example, it rounds 34.567 to 35.)

Parameters

Parameter | Description
number | A number.
mask | A string or a variable that contains one. Set of characters that determine how ColdFusion displays the number

The following table explains mask characters:

Mask character | Meaning
_ (underscore) | Optional. Digit placeholder.
9 | Optional. Digit placeholder. (Shows decimal places more clearly than _.)
. | Location of a mandatory decimal point.
0 | Located to the left or right of a mandatory decimal point. Pads with zeros.
( ) | If number is less than zero, puts parentheses around the mask.
+ | Puts plus sign before positive number; minus sign before negative number.
- | Puts a space before positive number; minus sign before negative number.
, | Separates every third decimal place with a comma.
L,C | Left-justifies or center-justifies number within width of mask column. First character of mask must be L or C. The default value is right-justified.
$ | Puts a dollar sign before formatted number. First character of mask must be the dollar sign ($).
^ | Separates left and right formatting.

Note: If you do not specify a sign for the mask, positive and negative numbers do not align in columns. To put a plus sign or space before positive numbers and a minus sign before negative numbers, use the plus or minus sign, respectively.

Usage

This function uses Java standard locale formatting rules on all platforms.

The position of symbols in format masks determines where the codes take effect. For example, if you put a dollar sign at the far left of a format mask, ColdFusion displays a dollar sign at the left edge of the formatted number. If you separate the dollar sign on the left edge of the format mask by at least one underscore, ColdFusion displays the dollar sign just to the left of the digits in the formatted number.

These examples show how symbols determine formats:

Number | Mask | Result
4.37 | $____.__ | "$ 4.37"
4.37 | _$___.__ | " $4.37"

The positioning can also show where to place the minus sign for negative numbers:

Number | Mask | Result
-4.37 | -____.__ | "- 4.37"
-4.37 | _-___.__ | " -4.37"

The positions for a symbol are: far left, near left, near right, and far right. The left and right positions are determined by the side of the decimal point on which the code character is shown. For formats that do not have a fixed number of decimal places, you can use a caret (^) to separate the left fields from the right.

An underscore determines whether the code is placed in the far or near position. Most code characters’ effect is determined by the field in which they are located. This example shows how to specify where to put parentheses to display negative numbers:

Number | Mask | Result
3.21 | C(__^__) | "( 3.21 )"
3.21 | C__(^__) | " (3.21 )"
3.21 | C(__^)__ | "( 3.21) "
3.21 | C__(^)__ | " (3.21) "

When converting from string to double, to prevent rounding errors, this function adds a rounding factor of 1.5543122344752E-014 to the converted number. For example, without adding the rounding factor, converting the string value 1.275 to double with two digits of precision results in a value of 1.27499999999999999, which would be rounded up to 1.27. By adding the rounding factor, the conversion correctly results in a value of 1.28.

If you round off a double such as 1.99499999999999999999999999999, where the last decimal is 10E-14, the rounding factor can cause an incorrect result.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>NumberFormat Example</h3>

<cfloop FROM = 1000 TO = 1020 INDEX = "counter">
<cfset CounterRoot2 = counter * sqr(2)>

<!--- Show result in default format, adding comma for thousands place;
and in custom format, displaying to two decimal places --->
<cfoutput>
<pre>#counter# * Square Root of 2: #NumberFormat(CounterRoot2,
  ‘_____.__’)#</pre>
<pre>#counter# * Square Root of 2: #NumberFormat(CounterRoot2)#</pre>
</cfoutput>
</cfloop>


ParagraphFormat

Description

Replaces characters in a string:

  • Single newline characters (CR/LF sequences) with spaces
  • Double newline characters with HTML paragraph tags (<p>)

Returns

A copy of the string, with characters converted.

Category

Display and formatting functions, String functions

Function syntax

ParagraphFormat(string)

See also

StripCR

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

This function is useful for displaying data entered in textarea fields.

Example

<h3>ParagraphFormat Example</h3>
<p>Enter text into this textarea, and see it returned as HTML.
<cfif IsDefined("FORM.myTextArea")>
    <p>Your text area, formatted
    <p><cfoutput>#ParagraphFormat(FORM.myTextArea)#</cfoutput>
</cfif>
<!--- use #Chr(10)##Chr(13)# to simulate a line feed/carriage
return combination; i.e, a return --->
<form action = "paragraphformat.cfm">
<textArea name = "MyTextArea" cols = "35" ROWS = 8>
This is sample text and you see how it scrolls
<cfoutput>#Chr(10)##Chr(13)#</cfoutput>
From one line
<cfoutput>#Chr(10)##Chr(13)##Chr(10)##Chr(13)#</cfoutput>
to the next
</textArea>
<input type = "Submit" name = "Show me the HTML version">
</form>


ParameterExists

Description

This function is deprecated. Use the IsDefined function.

Determines whether a parameter exists. ColdFusion does not evaluate the argument.

History

ColdFusion MX: Deprecated this function. It might not work, and might cause an error, in later releases.


ParseDateTime

Description

Parses a date/time string according to the English (U.S.) locale conventions. (To format a date/time string for other locales, use the LSParseDateTime function.)

Returns

A date/time object

Category

Date and time functions, Display and formatting functions

Function syntax

ParseDateTime(date/time-string [, pop-conversion ] )

See also

IsDate, IsNumericDate, SetLocale

Parameters

Parameter

Description

date/time string

A string containing a date/time value formatted according to U.S. locale conventions. Can represent a date/time in the range 100 AD–9999 AD. Years 0-29 are interpreted as 2000-2029; years 30-99 are interpreted as 1930-1999.

pop-conversion
  • pop: specifies that the date/time string is in POP format, which includes the local time of the sender and a time-zone offset from UTC. ColdFusion applies the offset and returns a value with the UTC time.
  • standard: (the default) function does no conversion.

Usage

This function is similar to CreateDateTime, but it takes a string instead of enumerated date/time values. These functions are provided primarily to increase the readability of code in compound expressions.

To calculate a difference between time zones, use the GetTimeZoneInfo function.

To set the default display format of date, time, number, and currency values, use the SetLocale function.

Example

<h3>ParseDateTime Example</h3>
<cfif IsDefined("form.theTestValue")>
    <cfif IsDate(form.theTestValue)>
        <h3>The expression <cfoutput>#DE(form.theTestValue)#</cfoutput> is a valid date</h3>
        <p>The parsed date/time is:
           <cfoutput>#ParseDateTime(form.theTestValue)#</cfoutput>
    <cfelse>
        <h3>The expression <cfoutput>#DE(form.theTestValue)#</cfoutput> is not a valid date</h3>
    </cfif>
</cfif>

<form action="#CGI.ScriptName#" method="POST">
<p>Enter an expression, and discover if it can be evaluated to a date value.
<input type="Text" name="TheTestValue" value="<CFOUTPUT>#DateFormat(Now())#
     #TimeFormat(Now())#</CFOUTPUT>">
<input type="Submit" value="Parse the Date" name="">
</form>


Pi

Description

Gets the mathematical constant p, accurate to 15 digits.

Returns

The number 3.14159265358979.

Category

Mathematical functions

Function syntax

Pi()

See also

ASin, Cos, Sin, Tan

Example

<h3>Pi Example</h3>
<!--- By default, ColdFusion displays only 11 significant digits.
       Use NumberFormat to display all 15. --->
The Pi function Returns the number
<cfoutput>
#NumberFormat(Pi(), "_._______________")#,
</cfoutput> the mathematical constant pi, accurate to 15 digits.


PreserveSingleQuotes

Description

Prevents ColdFusion from automatically escaping single-quotation mark characters that are contained in a variable. ColdFusion does not evaluate the argument.

Returns

(None)

Category

Other functions

Function syntax

PreserveSingleQuotes(variable)

History

ColdFusion MX: Changed behavior: ColdFusion automatically escapes simple-variable, array-variable, and structure-variable references within a cfquery tag body or block. (Earlier releases did not automatically escape array-variable references.)

Parameters

Parameter | Description
variable | Variable that contains a string in which to preserve single-quotation marks.

Usage

This function is useful in SQL statements to defer evaluation of a variable reference until runtime. This prevents errors that result from the evaluation of a single-quote or apostrophe data character (for example, "Joe’s Diner") as a delimiter.

Example A: Consider this code:

<cfset mystring = "'Newton's Law', 'Fermat's Theorem'">
PreserveSingleQuotes(#mystring#) is
<cfoutput>
#PreserveSingleQuotes(mystring)#
</cfoutput>

The output is as follows:

PreserveSingleQuotes(#mystring#) is 'Newton's Law', 'Fermat's Theorem'

Example B: Consider this code:

<cfset list0 = " '1','2', '3' ">
<cfquery sql = "select * from foo where bar in (#list0#)">

ColdFusion escapes the single-quote characters in the list as follows:

""1"", ""2"", ""3""

The cfquery tag throws an error.

You code this function correctly as follows:

<cfquery sql = "select * from foo where bar in (#preserveSingleQuotes(list0)#)">

This function ensures that ColdFusion evaluates the code as follows:

'1', '2', '3'

Example

<h3>PreserveSingleQuotes Example</h3><p>This is a useful function for
    creating lists of information to return from a query. In this example,
    we pick the list of Centers in Suisun, San Francisco, and San Diego,
    using the SQL grammar IN to modify a WHERE clause, rather than looping
    through the result set after the query is run.
<cfset List = "'Suisun', 'San Francisco', 'San Diego'">
<cfquery name = "GetCenters" datasource = "cfdocexamples">
    SELECT Name, Address1, Address2, City, Phone
    FROM Centers
    WHERE City IN (#PreserveSingleQuotes(List)#)
</cfquery>
<p>We found <cfoutput>#GetCenters.RecordCount#</cfoutput> records.
<cfoutput query = "GetCenters">
<p>#Name#<br>
#Address1#<br>
<cfif Address2 is not "">#Address2#
</cfif>
#City#<br>
#Phone#<br>
</cfoutput>


Quarter

Description

Calculates the quarter of the year in which a date falls.

Returns

An integer, 1–4.

Category

Date and time functions

Function syntax

Quarter(date)

See also

DatePart, Month

Parameters

Parameter | Description
date | A date/time object in the range 100 AD–9999 AD.

Usage

When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Example

<h3>Quarter Example</h3>

Today, <cfoutput>#DateFormat(Now())#</cfoutput>,
is in Quarter <cfoutput>#Quarter(Now())#</cfoutput>.


QueryAddColumn

Description

Adds a column to a query and populates its rows with the contents of a one-dimensional array. Pads query columns, if necessary, to ensure that all columns have the same number of rows.

Returns

The number of the column that was added.

Category

Query functions

Function syntax

QueryAddColumn(query, column-name[, datatype], array-name)

See also

QueryNew, QueryAddRow, QuerySetCell; Managing data types for columns in Using Query of Queries in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the datatype parameter.

ColdFusion MX: Changed behavior: if a user attempts to add a column whose name is invalid, ColdFusion throws an error. (In earlier releases, ColdFusion permitted the add operation, but the user could not reference the column after adding it.)

Parameters

Parameter

Description

query

Name of a query object.

column-name

Name of the new column.

datatype

(Optional) Column data type. ColdFusion generates an error if data you add to the column is not of this type, or if it cannot convert the data to this type. The following data types are valid:

  • Integer: 32-bit integer
  • BigInt: 64-bit integer
  • Double: 64-bit decimal number
  • Decimal: Variable length decimal, as specified by java.math.BigDecimal
  • VarChar: String
  • Binary: Byte array
  • Bit: Boolean (1=True, 0=False)
  • Time: Time
  • Data: Date (can include time information)

array-name

Name of an array whose elements populate the new column.

Usage

You can add columns to query objects, such as queries retrieved with the cfquery tag or queries created with the QueryNew function. You cannot use the QueryAddColumn function on a cached query. This function is useful for generating a query object from the arrays of output parameters that Oracle stored procedures can generate.

Macromedia recommends that you use the optional datatype parameter. Without this parameter, ColdFusion must try to determine the column’s data type when it uses the query object in a query of queries. Determining the data type requires additional processing, and can result in errors if ColdFusion does not guess the type correctly.

Example

The following example creates a new query object, uses the QueryAddColumn function to add three columns to the object, and displays the results. Because two of the arrays that provide the data are shorter than the third, QueryAddColumn adds padding to the corresponding columns in the query.

<!--- Make a query. --->
<cfset myQuery = QueryNew("")>

<!--- Create an array. --->
<cfset FastFoodArray = ArrayNew(1)>
<cfset FastFoodArray[1] = "French Fries">
<cfset FastFoodArray[2] = "Hot Dogs">
<cfset FastFoodArray[3] = "Fried Clams">
<cfset FastFoodArray[4] = "Thick Shakes">
<!--- Use the array to add a column to the query. --->
<cfset nColumnNumber = QueryAddColumn(myQuery, "FastFood", "VarChar",
        FastFoodArray)>

<!--- Create a second array. --->
<cfset FineCuisineArray = ArrayNew(1)>
<cfset FineCuisineArray[1] = "Lobster">
<cfset FineCuisineArray[2] = "Flambe">
<!--- Use the array to add a second column to the query. --->
<cfset nColumnNumber2 = QueryAddColumn(myQuery, "FineCuisine", "VarChar",
         FineCuisineArray)>

<!--- Create a third array. --->
<cfset HealthFoodArray = ArrayNew(1)>
<cfset HealthFoodArray[1] = "Bean Curd">
<cfset HealthFoodArray[2] = "Yogurt">
<cfset HealthFoodArray[3] = "Tofu">
<!--- Use the array to add a third column to the query. --->
<cfset nColumnNumber3 = QueryAddColumn(myQuery, "HealthFood", "VarChar",
         HealthFoodArray)>

<!--- Display the results. --->
<table cellspacing = "2" cellpadding = "2" border = "0">
<tr>
  <th align = "left">Fast Food</th>
  <th align = "left">Fine Cuisine</th>
  <th align = "left">Health Food</th>
</tr>
<cfoutput query = "myQuery">
<tr>
  <td>#FastFood#</td>
  <td>#FineCuisine#</td>
  <td>#HealthFood#</td>
</tr>
</cfoutput>
</table>


QueryAddRow

Description

Adds a specified number of empty rows to a query.

Returns

The number of rows in the query

Category

Query functions

Function syntax

QueryAddRow(query [, number ])

See also

QueryAddColumn, QueryAddRow, QuerySetCell, QueryNew; Creating a record set with a function in Using Query of Queries in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
query | Name of an executed query.
number | Number of rows to add to the query. The default value is 1.

Example

<h3>QueryAddRow Example</h3>

<!--- start by making a query --->
<cfquery name = "GetCourses" datasource = "cfdocexamples">
    SELECT Course_ID, Descript
    FROM Courses
</cfquery>
<p>The Query "GetCourses" has <cfoutput>#GetCourses.RecordCount#</cfoutput> rows.

<cfset CountVar = 0>
<cfloop CONDITION = "CountVar LT 15">
    <cfset temp = QueryAddRow(GetCourses)>
    <cfset CountVar = CountVar + 1>
    <cfset Temp = QuerySetCell(GetCourses, "Number", 100*CountVar)>
    <cfset CountVar = CountVar + 1>
    <cfset Temp = QuerySetCell(GetCourses, "Descript",
"Description of variable #Countvar#")>
</cfloop>

<P>After the QueryAddRow action, the query has
    <CFOUTPUT>#GetCourses.RecordCount#</CFOUTPUT>
    records.
    <CFOUTPUT query="GetCourses">
    <PRE>#Course_ID# #Course_Number# #Descript#</pre> </cfoutput>


QueryNew

Description

Creates an empty query (query object).

Returns

An empty query with a set of named columns, or an empty query.

Category

Query functions

Function syntax

QueryNew(columnlist [, columntypelist])

History

ColdFusion MX 7: Added columntypelist parameter.

See also

QueryAddColumn, QueryAddRow, QuerySetCell; Managing data types for columns in Using Query of Queries ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

columnlist

Comma-delimited list of column names, or an empty string.

columntypelist

(Optional) Comma-delimited list specifying column data types. ColdFusion generates an error if the data you add to the column is not of this type, or if it cannot convert the data to this type. The following data types are valid:

  • Integer: 32-bit integer
  • BigInt: 64-bit integer
  • Double: 64-bit decimal number
  • Decimal: Variable length decimal, as specified by java.math.BigDecimal
  • VarChar: String
  • Binary: Byte array
  • Bit: Boolean (1=True, 0=False)
  • Time: Time
  • Date: Date (can include time information)

Usage

If you specify an empty string in the columnlist parameter, you must use the QueryAddColumn function to add columns to the query.

Macromedia recommends that you use the optional columntypelist parameter. Without this parameter, ColdFusion must try to determine data types when it uses the query object in a query of queries. Determining data types requires additional processing, and can result in errors if ColdFusion does not guess a type correctly.

Example

The following example uses the QueryNew function to create an empty query with three columns. It populates two rows of the query and displays the contents of the query object and its metadata.

<!--- Create a new three-column query, specifying the column data types --->
<cfset myQuery = QueryNew("Name, Time, Advanced", "VarChar, Time, Bit")>

<!--- Make two rows in the query --->
<cfset newRow = QueryAddRow(MyQuery, 2)>

<!--- Set the values of the cells in the query --->
<cfset temp = QuerySetCell(myQuery, "Name", "The Wonderful World of CMFL", 1)>
<cfset temp = QuerySetCell(myQuery, "Time", "9:15 AM", 1)>
<cfset temp = QuerySetCell(myQuery, "Advanced", False, 1)>
<cfset temp = QuerySetCell(myQuery, "Name", "CFCs for Enterprise
        Applications", 2)>
<cfset temp = QuerySetCell(myQuery, "Time", "12:15 PM", 2)>
<cfset temp = QuerySetCell(myQuery, "Advanced", True, 2)>

<h4>The query object contents</h4>
<cfoutput query = "myQuery">
    #Name# #Time# #Advanced#<br>
</cfoutput><br>
<br>
<h4>Using individual query data values</h4>
<cfoutput>
    #MyQuery.name[2]# is at #MyQuery.Time[2]#<br>
</cfoutput><br>
<br>
<h4>The query metadata</h4>
<cfset querymetadata=getMetaData(myQuery)>
<cfdump var="#querymetadata#">


QuerySetCell

Description

Sets a cell to a value. If no row number is specified, the cell on the last row is set.

Returns

True, if successful; False, otherwise.

Category

Query functions

Function syntax

QuerySetCell(query, column_name, value [, row_number ])

See also

QueryAddColumn, QueryAddRow, QueryNew; Creating a record set with a function in Using Query of Queries in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
query | Name of an executed query.
column_name | Name of a column in the query.
value | Value to set in the cell.
row_number | Row number. The default value is last row.

Example

<!--- This example shows the use of QueryAddRow and QuerySetCell --->

<!--- start by making a query --->
<cfquery name = "GetCourses" datasource = "cfdocexamples">
    SELECT Course_ID, Descript
    FROM Courses
</cfquery>
<p>The Query "GetCourses" has <cfoutput>#GetCourses.RecordCount#</cfoutput> rows.

<cfset CountVar = 0>
<cfloop CONDITION = "CountVar LT 15">
    <cfset temp = QueryAddRow(GetCourses)>
    <cfset CountVar = CountVar + 1>
    <cfset Temp = QuerySetCell(GetCourses, "Number", 100*CountVar)>
    <cfset CountVar = CountVar + 1>
    <cfset Temp = QuerySetCell(GetCourses, "Descript",
"Description of variable #Countvar#")>
</cfloop>

<P>After the QueryAddRow action, the query has
    <CFOUTPUT>#GetCourses.RecordCount#</CFOUTPUT>
    records.
    <CFOUTPUT query="GetCourses">
    <PRE>#Course_ID# #Course_Number# #Descript#</pre> </cfoutput>


QuotedValueList

Description

Gets the values of each record returned from an executed query. ColdFusion does not evaluate the arguments.

Returns

A delimited list of the values of each record returned from an executed query. Each value is enclosed in single-quotation marks.

Category

Query functions, List functions

Function syntax

QuotedValueList(query.column [, delimiter ])

See also

ValueList

Parameters

Parameter | Description
query.column | Name of an executed query and column. Separate query name and column name with a period.
delimiter | A string or a variable that contains one. Character(s) that separate column data.

Example

<!--- use the contents of one query to create another dynamically --->
<cfset List = "'BIOL', 'CHEM'">
<!--- first, get the department IDs in our list --->
<cfquery name = "GetDepartments" datasource = "cfdocexamples">
SELECT Dept_ID FROM Departments
WHERE Dept_ID IN (#PreserveSingleQuotes(List)#)
</cfquery>

<!--- now, select the courses for that department based on the
quotedValueList produced from our previous query --->
<cfquery name = "GetCourseList" datasource = "cfdocexamples">
SELECT *
FROM CourseList
WHERE Dept_ID IN ('#GetDepartments.Dept_ID#')
</cfquery>

<!--- now, output the results --->

List the course numbers that are in BIOL and CHEM (uses semicolon (;) as the delimiter):<br>
<cfoutput>
#QuotedValueList(GetCourseList.CorNumber,";")#<br>
</cfoutput>


Rand

Description

Generates a pseudo-random number.

Returns

A pseudo-random decimal number, in the range 0 – 1.

Category

Mathematical functions, Security functions

Function syntax

Rand([algorithm])

History

ColdFusion MX 7: Added the algorithm parameter.

See also

Randomize, RandRange

Parameters

Parameter

Description

algorithm

(Optional) The algorithm to use to generated the random number. ColdFusion MX installs a cryptography library with the following algorithms:

  • CFMX_COMPAT: the algorithm used in ColdFusion MX (default).
  • SHA1PRNG: generates a number using the Sun Java SHA1PRNG algorithm. This algorithm provides greater randomness than the default algorithm
  • IBMSecureRandom: for IBM WebSphere (IBM JVM does not support the SHA1PRNG algorithm).

Usage

Call the Randomize function before calling this function to seed the random number generator. Seeding the generator ensures that the Rand function always generates the same sequence of pseudo-random numbers. This behavior is useful if you must reproduce a pattern consistently.

ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section (except the default algorithm). The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

Example

The following example uses the SHA1PRNG algorithm to generate a single random number:

<h3>Rand Example</h3>
<cfoutput>
    <p>Rand("SHA1PRNG") returned: #Rand("SHA1PRNG")#</p>
    <p><A HREF = "#CGI.SCRIPT_NAME#">Try again</A>
</cfoutput>


Randomize

Description

Seeds the pseudo-random number generator with an integer number, ensuring repeatable number patterns.

Returns

A pseudo-random decimal number, in the range 0–1.

Category

Mathematical functions, Security functions

Function syntax

Randomize(number[, algorithm])

History

ColdFusion MX 7: Added the algorithm parameter.

See also

Rand, RandRange

Parameters

Parameter

Description

number

Integer number. If the number is not in the range -2,147,483,648 – 2,147,483,647, ColdFusion generates an error.

algorithm

(Optional) The algorithm to use to generate the seed number. ColdFusion MX installs a cryptography library with the following algorithms:

  • CFMX_COMPAT: the algorithm used in ColdFusion MX (default).
  • SHA1PRNG: generates a number using the Sun Java SHA1PRNG algorithm. This algorithm provides greater randomness than the default algorithm.
  • IBMSecureRandom: for IBM WebSphere (IBM JVM does not support the SHA1PRNG algorithm).

Usage

Call this function before calling Rand to seed the random number generator. Seeding the generator ensures that the Rand function always generates the same sequence of pseudo-random numbers. This behavior is useful if you must reproduce a pattern consistently.

ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section (except the default algorithm). The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

Example

The following example calls the Randomize function to seed the random number generator and generates 10 random numbers. To show the effect of the seed, submit the form with the same value multiple times.

<h3>Randomize Example</h3>

    <!--- Do the following only if the form has been submitted. --->
<cfif IsDefined("Form.myRandomInt")>

    <!--- Make sure submitted value is a number and display its value. --->
    <cfif IsNumeric(FORM.myRandomInt)>
        <cfoutput>
            <b>Seed value is #FORM.myRandomInt#</b><br>
        </cfoutput><br>

        <!--- Call Randomize to seed the random number generator. --->
        <cfset r = Randomize(FORM.myRandomInt, "SHA1PRNG")>

        <cfoutput>
            <b>Random number returned by Randomize(#Form.myRandomInt#,
                "SHA1PRNG"):</b><br>
            #r#<br>
            <br>
            <b>10 random numbers generated using the SHA1PRNG algorithm:</b><br>
            <cfloop index = "i" from = "1" to = "10" step = "1">
                #Rand("SHA1PRNG")#<br>
            </cfloop><br>
        </cfoutput>

    <cfelse>
        <p>Please enter a number.
    </cfif>
</cfif>

<!--- Form to specify the seed value. --->
<form action="#CGI.SCRIPT_NAME#" method="post">
<p>Enter a number to seed the randomizer:
<input type = "Text" name = "MyRandomInt" value="12345">
<p><input type = "Submit" name = "">
</form>


RandRange

Description

Generates a pseudo-random integer in the range between two specified numbers.

Returns

A pseudo-random integer.

Category

Mathematical functions, Security functions

Function syntax

RandRange(number1, number2[, algorithm])

History

ColdFusion MX 7: Added the algorithm parameter.

See also

Rand, Randomize

Parameters

Parameter

Description

number1, number2

Integer numbers. If the numbers are not in the range -2,147,483,648 – 2,147,483,647, ColdFusion generates an error.

algorithm

(Optional) The algorithm to use to generated the random number. ColdFusion MX installs a cryptography library with the following algorithms:

  • CFMX_COMPAT: the algorithm used in ColdFusion MX (default).
  • SHA1PRNG: generates a number using the Sun Java SHA1PRNG algorithm. This algorithm provides greater randomness than the default algorithm
  • IBMSecureRandom: for IBM WebSphere (IBM JVM does not support the SHA1PRNG algorithm.)

Usage

Very large positive or negative values for the number1 and number2 parameters might result in poor randomness in the results. To prevent this problem, do not specify numbers outside the range -1,000,000,000 – 1,000,000,000.

ColdFusion MX 7 uses the Java Cryptography Extension (JCE) and installs a Sun Java 1.4.2 runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section (except the default algorithm). The JCE framework includes facilities for using other provider implementations; however, Macromedia cannot provide technical support for third-party security providers.

Example

The following example contains a form that requires random number range values, and lets you optionally specify a random number seed value. It uses cfform controls and attributes to specify a default range, ensure that the range fields have values, and validate that the field values are in a specified integer range. When you submit the form, it checks whether the seed field has an empty string; if the field has a value, the code uses the number to seed the random number generator. It then generates and displays the random number.

<h3>RandRange Example</h3>

<!--- Do the following only if the form has been submitted. --->
<cfif IsDefined("Form.mySeed")>

    <!--- Do the following only if the seed field has a non-empty string. --->
    <cfif Form.mySeed NEQ "">
        <cfoutput>
            <b>Seed value is #FORM.mySeed#</b><br>
        </cfoutput>
        <br>

        <!--- Call Randomize to seed the random number generator. --->
        <cfset r = Randomize(FORM.mySeed, "SHA1PRNG")>
    <cfelse>
        <b>No Seed value submitted</b><br>
    </cfif>

    <!--- Generate and display the random number. --->
    <cfoutput><p><b>
        RandRange returned: #RandRange(FORM.myInt, FORM.myInt2, "SHA1PRNG")#
    </cfoutput></b></p>
</cfif>

<!--- This form uses cfform input validation to check the input range. --->
<cfform action = "#CGI.SCRIPT_NAME#">
<p>Enter the random number Range: From
<cfinput type = "Text" name = "MyInt" value = "1"
    RANGE = "-1000000000,1000000000"
    message = "Please enter a value between -1,000,000,000 and 1,000,000,000"
    validate = "integer" required = "Yes">
To
<cfinput type = "Text" name = "MyInt2" value = "9999"
    RANGE = "-1000000000,1000000000"
    message = "Please enter a value between --1,000,000,000  and 1,000,000,000"
    validate = "integer" required = "Yes"></p>
<p>Enter a number to seed the randomizer:
<cfinput type = "Text" name = "mySeed" RANGE = "-1000000000,1000000000"
    message = "Please enter a value between -1,000,000,000 and 1,000,000,000"
    validate = "integer" required = "No"></p>
<p><input type = "Submit" name = "">
</cfform>


REFind

Description

Uses a regular expression (RE) to search a string for a pattern. The search is case sensitive.

For more information on regular expressions, including escape sequences, anchors, and modifiers, see Using Regular Expressions in Functions in ColdFusion MX Developer’s Guide.

Returns

Depends on the value of the returnsubexpressions parameter:

  • If returnsubexpressions = "False":
    • The position in the string where the match begins
    • 0, if the regular expression is not matched in the string
  • If returnsubexpressions = "True": a structure that contains two arrays, len and pos. The array elements are as follows:
    • If the regular expression is found in the string, the first element of the len and pos arrays contains the length and position, respectively, of the first match of the entire regular expression.
      If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group.
    • If the regular expression is not found in the string, the first element of the len and pos arrays contains 0.

Category

String functions

Function syntax

REFind(reg_expression, string [, start ] 	[, returnsubexpressions ] )

See also

Find, FindNoCase, REFindNoCase, REReplace, REReplaceNoCase

Parameters

Parameter

Description

reg_expression

Regular expression for which to search. Case-sensitive.

string

A string, or a variable that contains one, in which to search.

start

Optional. A positive integer, or a variable that contains one. Position in the string at which to start search. The default value is 1.

returnsubexpressions

Optional. Boolean. Whether to return substrings of reg_expression, in arrays named len and pos:

  • True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match.
    If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group.
    If the regular expression is not found, the arrays each contain one element with the value 0.
  • False: the function returns the position in the string where the match begins. Default.

Usage

This function finds the first occurrence of a regular expression in a string. To find the second and subsequent instances of the expression or of subexpressions in it, you call this function more than once, each time with a different start position. To determine the next start position, use the returnsubexpressions parameter, and add the value returned in the first element of the length array to the value in the first element of the position array.

Example

<h3>REFind Example</h3>
<p>This example shows the use of the REFind function with and without the
<i>returnsubexpressions</i> parameter set to True.
If you do not use the <i>returnsubexpressions</i> parameter,
REFind returns the position of the first occurrence of a regular
expression in a string starting from the specified position.
Returns 0 if no occurrences are found.</p>

<p>REFind("a+c+", "abcaaccdd"):
<cfoutput>#REFind("a+c+", "abcaaccdd")#</cfoutput></p>
<p>REFind("a+c*", "abcaaccdd"):
<cfoutput>#REFind("a+c*", "abcaaccdd")#</cfoutput></p>
<p>REFind("[[:upper:]]", "abcaacCDD"):
<cfoutput>#REFind("[[:upper:]]", "abcaacCDD")#</cfoutput></p>
<p>REFind("[\?&]rep = ", "report.cfm?rep = 1234&u = 5"):
    <cfoutput>#REFind("[\?&]rep = ", "report.cfm?rep = 1234&u = 5")#
    </cfoutput>
</p>
<!--- Set startPos to one; returnMatchedSubexpressions = TRUE --->
<hr size = "2" color = "#0000A0">
<p>If you use the <i>returnssubexpression</i> parameter, REFind returns the
position and length of the first occurrence of a regular expression
in a string starting from the specified position. The position and
length variables are stored in a structure. To access position and length
information, use the keys <i>pos</i> and <i>len</i>, respectively.</p>
<cfset teststring = "The cat in the hat hat came back!">
<p>The string in which the function is to search is:
<cfoutput><b>#teststring#</b></cfoutput>.</p>
<p>The first call to REFind to search this string is:
        <b>REFind("[A-Za-z]+",testString,1,"TRUE")</b></p>
<p>This function returns a structure that contains two arrays: pos and len.</p>
<p>To create this structure you can use a CFSET statement, for example: </p>
&lt;CFSET st = REFind("[[:alpha:]]",testString,1,"TRUE")&gt;
<cfset st = REFind("[[:alpha:]]",testString,1,"TRUE")>
<p>
    <cfoutput>
    The number of elements in each array: #ArrayLen(st.pos)#.
    </cfoutput></p>
<p><b>The number of elements in the pos and len arrays is always one
if you do not use parentheses in the regular expression.</b></p>
<p>The value of st.pos[1] is: <cfoutput>#st.pos[1]#.</cfoutput></p>
<p>The value of st.len[1] is: <cfoutput>#st.len[1]#.</cfoutput></p>
<p>
<cfoutput>
    Substring is <b>[#Mid(testString,st.pos[1],st.len[1])#]</B>
    </cfoutput></p>
<hr size = "2" color = "#0000A0">
<p>However, if you use parentheses in the regular expression, the first
element contains the position and length of the first instance
of the whole expression. The position and length of the first instance
of each parenthesized subexpression within is included in additional
array elements.</p>
<p>For example:
&lt;CFSET st1 = REFind("([[:alpha:]])[ ]+(\1)",testString,1,"TRUE")&gt;</p>
<cfset st1 = REFind("([[:alpha:]]+)[ ]+(\1)",testString,1,"TRUE")>
<p>The number of elements in each array is <cfoutput>#ArrayLen(st1.pos)#
</cfoutput>.</p>
<p>First whole expression match; position is
    <cfoutput>#st1.pos[1]#;
        length is #st1.len[1]#; whole expression match is
        <B>[#Mid(testString,st1.pos[1],st1.len[1])#]</B>
    </cfoutput></p>
<p>Subsequent elements of the arrays provide the position and length of
the first instance of each parenthesized subexpression therein.</p>
 <cfloop index = "i" from = "2" to = "#ArrayLen(st1.pos)#">
    <p><cfoutput>Position is #st1.pos[i]#; Length is #st1.len[i]#;
Substring is <B>[#Mid(testString,st1.pos[i],st1.len[i])#]
</B></cfoutput></p>
</cfloop><br>


REFindNoCase

Description

Uses a regular expression (RE) to search a string for a pattern, starting from a specified position. The search is case-insensitive.

For more information on regular expressions, including escape sequences, anchors, and modifiers, see Using Regular Expressions in Functions in ColdFusion MX Developer’s Guide.

Returns

Depends on the value of the returnsubexpressions parameter:

  • If returnsubexpressions = "False":
    • The position in the string where the match begins
    • 0, if the regular expression is not matched in the string
  • If returnsubexpressions = "True": a structure that contains two arrays, len and pos. The array elements are as follows:
    • If the regular expression is found in the string, the first element of the len and pos arrays contains the length and position, respectively, of the first match of the entire regular expression.
    • If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group.
    • If the regular expression is not found in the string, the first element of the len and pos arrays contains 0.

Category

String functions

Function syntax

REFindNoCase(reg_expression, string [, start] [, returnsubexpressions] )

See also

Find, FindNoCase, REFind, REReplace, REReplaceNoCase

Parameters

Parameter

Description

reg_expression

Regular expression for which to search. Case-insensitive.

For more information, see Using Regular Expressions in Functions in ColdFusion MX Developer’s Guide.

string

A string or a variable that contains one. String in which to search.

start

Optional. A positive integer or a variable that contains one. Position at which to start search. The default value is 1.

returnsubexpressions

Optional. Boolean. Whether to return substrings of reg_expression, in arrays named len and pos:

  • True: if the regular expression is found, the first array element contains the length and position, respectively, of the first match.
    If the regular expression contains parentheses that group subexpressions, each subsequent array element contains the length and position, respectively, of the first occurrence of each group.
    If the regular expression is not found, the arrays each contain one element with the value 0.
  • False: the function returns the position in the string where the match begins. Default.

Usage

This function finds the first occurrence of a regular expression in a string. To find the second and subsequent instances of the expression or of subexpressions in it, you call this function more than once, each time with a different start position. To determine the next start position, use the returnsubexpressions parameter, and add the value returned in the first element of the length array to the value in the first element of the position array.

Example

<h3>REFindNoCase Example</h3>
<p>This example demonstrates the use of the REFindNoCase function with and
without the <i>returnsubexpressions</i> parameter set to True.</p>
<p>If you do not use the <i>returnsubexpressions</i> parameter, REFindNoCase
returns the position of the first occurrence of a regular expression
in a string starting from the specified position. Returns 0 if no
occurrences are found. </p>
<p>REFindNoCase("a+c+", "abcaaccdd"):
<cfoutput>#REFindNoCase("a+c+", "abcaaccdd")#</cfoutput></p>
<p>REFindNoCase("a+c*", "abcaaccdd"):
<cfoutput>#REFindNoCase("a+c*", "abcaaccdd")#</cfoutput></p>
<p>REFindNoCase("[[:alpha:]]+", "abcaacCDD"):
<cfoutput>#REFindNoCase("[[:alpha:]]+", "abcaacCDD")#</cfoutput></p>
<p>REFindNoCase("[\?&]rep = ", "report.cfm?rep = 1234&u = 5"):
<cfoutput>#REFindNoCase("[\?&]rep = ", "report.cfm?rep = 1234&u = 5")#
</cfoutput></p>
<!--- Set startPos to one; returnMatchedSubexpressions = True --->
<hr size = "2" color = "#0000A0">
<p>If you do use the <i>returnssubexpression</i> parameter, REFindNoCase returns
the position and length of the first occurrence of a regular expression
in a string starting from the specified position. The position and length
variables are stored in a structure. To access position and length
information, use the keys <i>pos</i> and <i>len</i>, respectively.</p>

<cfset teststring = "The cat in the hat hat came back!">
<p>The string in which the function is to search is:
<cfoutput><b>#teststring#</b></cfoutput>.</p>
<p>The first call to REFindNoCase to search this string is:
<b>REFindNoCase("[[:alpha:]]+",testString,1,"True")</b></p>
<p>This function returns a structure that contains two arrays: pos and len.</p>
<p>To create this structure you can use a CFSET statement,
for example:</p>
&lt;CFSET st = REFindNoCase("[[:alpha:]]+",testString,1,"True")&gt;
<cfset st = REFindNoCase("[[:alpha:]]+",testString,1,"True")>
<p>
    <cfoutput>
    The number of elements in each array: #ArrayLen(st.pos)#.
    </cfoutput></p>
<p><b>The number of elements in the pos and len arrays will always be one,
if you do not use parentheses to denote subexpressions in the regular
expression.</b></p>
<p>The value of st.pos[1] is: <cfoutput>#st.pos[1]#.</cfoutput></p>
<p>The value of st.len[1] is: <cfoutput>#st.len[1]#.</cfoutput></p>
<p>
    <cfoutput>
    Substring is <b>[#Mid(testString,st.pos[1],st.len[1])#]</B>
    </cfoutput></p>
<hr size = "2" color = "#0000A0">
<p>However, if you use parentheses to denote subexpressions in the regular
expression, the first element contains the position and length of
the first instance of the whole expression. The position and length
of the first instance of each subexpression within will be included
in additional array elements.</p>
<p>For example:
&lt;CFSET st1 = REFindNoCase("([[:alpha:]]+)[ ]+(\1)",testString,1,"True")&gt;</p>
<cfset st1 = REFindNoCase("([[:alpha:]]+)[ ]+(\1)",testString,1,"True")>

<p>The number of elements in each array is
<cfoutput>
    #ArrayLen(st1.pos)#
</cfoutput>.</p>

<p>First whole expression match; position is
<cfoutput>
    #st1.pos[1]#; length is #st1.len[1]#;
    whole expression match is <B>[#Mid(testString,st1.pos[1],st1.len[1])#]</B>
</cfoutput></p>

<p>Subsequent elements of the arrays provide the position and length of the
first instance of each parenthesized subexpression therein.</p>
 <cfloop index = "i" from = "2" to = "#ArrayLen(st1.pos)#">
    <p><cfoutput>Position is #st1.pos[i]#; Length is #st1.len[i]#;
    Substring is <B>[#Mid(testString,st1.pos[i],st1.len[i])#]</B>
    </cfoutput></p>
</cfloop><br>


ReleaseComObject

Description

Releases a COM Object and frees up resources that it used.

Returns

Nothing.

Category

Extensibility functions

Function syntax

ReleaseComObject(objectName)

See also

CreateObject, cfobject

History

ColdFusion MX 6.1: Added this function.

Parameters

Parameter | Description
objectName | Variable name of a COM object that was created using the CreateObject function or cfobject tag.

Usage

This function forcefully terminates and releases the specified COM object and all COM objects that it created. Use this function when the object is no longer in use, to quickly free up resources. If the COM object has a method, such as a quit method, that terminates the program, call this method before you call the ReleaseComObject function.

This function can improve processing efficiency, but is not required for an application to work. If you do not use this function, the Java garbage collection mechanism eventually frees the resources. If you use this function on an object that is in use, the object is prematurely released and your application will get exceptions.

Example

<h3>ReleaseComObject Example</h3>
    <cfscript>
    obj = CreateObject("Com", "excel.application.9");
    //code that uses the object goes here
    obj.quit();
    ReleaseComObject(obj);
    </cfscript>


RemoveChars

Description

Removes characters from a string.

Returns

A copy of the string, with count characters removed from the specified start position. If no characters are found, returns zero.

Category

String functions

Function syntax

RemoveChars(string, start, count)

See also

Insert, Len

Parameters

Parameter | Description
string | A string or a variable that contains one. String in which to search.
start | A positive integer or a variable that contains one. Position at which to start search.
count | Number of characters to remove.

Example

<h3>RemoveChars Example</h3>
Returns a string with <I>count</I> characters removed from the
start position. Returns 0 if no characters are found.

<cfif IsDefined("FORM.myString")>
    <cfif (FORM.numChars + FORM.start) GT Len(FORM.myString)>
        <p>Your string is only <cfoutput>#Len(FORM.myString)#
         </cfoutput> characters long.
        Please enter a longer string, select fewer characters to remove or
        begin earlier in the string.
    <cfelse>
        <cfoutput>
        <p>Your original string: 	#FORM.myString#
        <p>Your modified string:	#RemoveChars(FORM.myString,
FORM.start, FORM.numChars)#
        </cfoutput>
    </cfif>
</cfif>


RepeatString

Description

Creates a string that contains a specified number of repetitions of the specified string.

Returns

A string.

Category

String functions

Function syntax

RepeatString(string, count)

See also

CJustify, LJustify, RJustify

Parameters

Parameter | Description
string | A string or a variable that contains one.
count | Number of repeats.

Example

<h3>RepeatString Example</h3>
<p>RepeatString returns a string created from <I>string</I>, repeated
a specified number of times.
<ul>
    <li>RepeatString("-", 10): <cfoutput>#RepeatString("-", 10)#</cfoutput>
    <li>RepeatString("&lt;BR&gt;", 3): <cfoutput>#RepeatString("<br>", 3)#
</cfoutput>
    <li>RepeatString("", 5): <cfoutput>#RepeatString("", 5)#</cfoutput>
    <li>RepeatString("abc", 0): <cfoutput>#RepeatString("abc", 0)#</cfoutput>
    <li>RepeatString("Lorem Ipsum", 2):
     <cfoutput>#RepeatString("Lorem Ipsum", 2)#</cfoutput>
</ul>


Replace

Description

Replaces occurrences of substring1 in a string with substring2, in a specified scope. The search is case-sensitive.

Returns

The string, after making replacements.

Category

String functions

Function syntax

Replace(string, substring1, substring2 [, scope ])

See also

Find, REFind, ReplaceNoCase, ReplaceList, REReplace

Parameters

Parameter

Description

string

A string or a variable that contains one. String in which to search.

substring1

A string or a variable that contains one. String for which to search

substring2

String that replaces substring1

scope
  • one: replaces the first occurrence (default)
  • all: replaces all occurrences

Usage

To remove a string, specify the empty string ("") as substring2.

You do not need to escape comma characters in strings. For example, the following code deletes the commas from the sentence:

replace("The quick brown fox jumped over the lazy cow, dog, and cat.",",","","All")

Example

<h3>Replace Example</h3>

<p>The Replace function returns <I>string</I> with <I>substring1</I>
replaced by <I>substring2</I> in the specified scope. This
is a case-sensitive search.

<cfif IsDefined("FORM.MyString")>
<p>Your original string, <cfoutput>#FORM.MyString#</cfoutput>
<p>You wanted to replace the substring <cfoutput>#FORM.MySubstring1#
</cfoutput>
with the substring <cfoutput>#FORM.MySubstring2#</cfoutput>.
<p>The result: <cfoutput>#Replace(FORM.myString,
FORM.MySubstring1, FORM.mySubString2)#</cfoutput>
</cfif>


ReplaceList

Description

Replaces occurrences of the elements from a delimited list in a string with corresponding elements from another delimited list. The search is case-sensitive.

Returns

A copy of the string, after making replacements.

Category

List functions, String functions

Function syntax

ReplaceList(string, list1, list2)

See also

Find, REFind, Replace, REReplace

Parameters

Parameter | Description
string | A string, or a variable that contains one, within which to replace substring
list1 | Comma-delimited list of substrings for which to search
list2 | Comma-delimited list of replacement substrings

Usage

The list of substrings to replace is processed sequentially. If a list1 element is contained in list2 elements, recursive replacement might occur. The second example shows this.

Example

<p>The ReplaceList function returns <I>string</I> with
<I>substringlist1</I> (e.g. "a,b") replaced by <I>substringlist2</I>
(e.g. "c,d") in the specified scope.
<cfif IsDefined("FORM.MyString")>
<p>Your original string, <cfoutput>#FORM.MyString#</cfoutput>
<p>You wanted to replace the substring <cfoutput>#FORM.MySubstring1#
 </cfoutput>
with the substring <cfoutput>#FORM.MySubstring2#</cfoutput>.
<p>The result: <cfoutput>#Replacelist(FORM.myString,
FORM.MySubstring1, FORM.mySubString2)#</cfoutput>
</cfif>
<form action = "replacelist.cfm" method="post">
<p>String 1
<br><input type = "Text" value = "My Test String" name = "MyString">
<p>Substring 1 (find this list of substrings)
<br><input type = "Text" value = "Test, String" name = "MySubstring1">
<p>Substring 2 (replace with this list of substrings)
<br><input type = "Text" value = "Replaced, Sentence" name = "MySubstring2">
<p><input type = "Submit" value = "Replace and display" name = "">
</form>

<h3>Replacelist Example Two</h3>
<cfset stringtoreplace = "The quick brown fox jumped over the lazy dog.">
<cfoutput>
    #ReplaceList(stringtoreplace,"dog,brown,fox,black", "cow,black,ferret,white")#
</cfoutput>


ReplaceNoCase

Description

Replaces occurrences of substring1 with substring2, in the specified scope. The search is case-insensitive.

Returns

A copy of the string, after making replacements.

Category

String functions

Function syntax

ReplaceNoCase(string, substring1, substring2 [, scope ])

See also

Find, REFind, Replace, ReplaceList, REReplace

Parameters

Parameter

Description

string

A string (or variable that contains one) within which to replace substring.

substring1

String (or variable that contains one) to replace, if found.

substring2

String (or variable that contains one) that replaces substring1.

scope
  • one: replaces the first occurrence (default).
  • all: replaces all occurrences.

Example

<h3>ReplaceNoCase Example</h3>
<p>The ReplaceNoCase function returns <I>string</I> with <I>substring1</I>
replaced by <I>substring2</I> in the specified scope.
The search/replace is case-insensitive.

<cfif IsDefined("FORM.MyString")>
<p>Your original string, <cfoutput>#FORM.MyString#</cfoutput>
<p>You wanted to replace the substring <cfoutput>#FORM.MySubstring1#
 </cfoutput>
with the substring <cfoutput>#FORM.MySubstring2#</cfoutput>.
<p>The result: <cfoutput>#ReplaceNoCase(FORM.myString,
FORM.MySubstring1, FORM.mySubString2)#</cfoutput>
</cfif>


REReplace

Description

Uses a regular expression (RE) to search a string for a string pattern and replace it with another. The search is case-sensitive.

Returns

If the scope parameter is set to one, returns a string with the first occurrence of the regular expression replaced by the value of substring.

If the scope parameter is set to all, returns a string with all occurrences of the regular expression replaced by the value of substring.

If the function finds no matches, it returns a copy of the string unchanged.

Category

String functions

Function syntax

REReplace(string, reg_expression, substring [, scope ])

See also

REFind, Replace, ReplaceList, REReplaceNoCase

History

ColdFusion MX: Added supports for the following special codes in a replacement substring, to control case conversion:

  • \u - uppercase the next character
  • \l - lowercase the next character
  • \U - uppercase until \E
  • \L - lowercase until \E
  • \E - end \U or \L

For more information on new features, see REFind.

Parameters

Parameter

Description

string

A string or a variable that contains one. String within which to search.

reg_expression

Regular expression to replace. The search is case-sensitive.

substring

A string or a variable that contains one. Replaces reg_expression.

scope
  • one: replaces the first occurrence (default).
  • all: replaces all occurrences.

Usage

For details on using regular expressions, see Using Regular Expressions in Functions in ColdFusion MX Developer’s Guide.

Example

<p>The REReplace function returns <i>string</i> with a regular expression replaced
with <i>substring</i> in the specified scope. Case-sensitive search.
<p>REReplace("CABARET","C|B","G","ALL"):
<cfoutput>#REReplace("CABARET","C|B","G","ALL")#</cfoutput>
<p>REReplace("CABARET","[A-Z]","G","ALL"):
<cfoutput>#REReplace("CABARET","[A-Z]","G","ALL")#</cfoutput>
<p>REReplace("I love jellies","jell(y|ies)","cookies"):
<cfoutput>#REReplace("I love jellies","jell(y|ies)","cookies")#
 </cfoutput>
<p>REReplace("I love jelly","jell(y|ies)","cookies"):
<cfoutput>#REReplace("I love jelly","jell(y|ies)","cookies")#</cfoutput>


REReplaceNoCase

Description

Uses a regular expression to search a string for a string pattern and replace it with another. The search is case-insensitive.

Returns

  • If scope = "one": returns a string with the first occurrence of the regular expression replaced by the value of substring.
  • If scope = "all": returns a string with all occurrences of the regular expression replaced by the value of substring.
  • If the function finds no matches: returns a copy of the string, unchanged.

Category

String functions

Function syntax

REReplaceNoCase(string, reg_expression, substring [, scope ])

See also

REFind, REFindNoCase, Replace, ReplaceList

History

ColdFusion MX: Changed behavior: this function inserts the following special characters in regular expression replacement strings, to control case conversion: \u, \U, \l, \L, and \E. If any of these strings is present in a ColdFusion 5 application, you must insert a backslash before it (for example, change "\u" to "\\u").

Parameters

Parameter

Description

string

A string or a variable that contains one.

reg_expression

Regular expression to replace. For more information, see Using Regular Expressions in Functions in ColdFusion MX Developer’s Guide.

substring

A string or a variable that contains one. Replaces reg_expression.

scope
  • one: replaces the first occurrence of the regular expression. Default.
  • all: replaces all occurrences of the regular expression.

Usage

For details on using regular expressions, see Using Regular Expressions in Functions in ColdFusion MX Developer’s Guide.

Example

<p>The REReplaceNoCase function returns <i>string</i> with a regular
expression replaced with <i>substring</i> in the specified scope.
This is a case-insensitive search.
<p>REReplaceNoCase("cabaret","C|B","G","ALL"):
<cfoutput>#REReplaceNoCase("cabaret","C|B","G","ALL")#</cfoutput>
<p>REReplaceNoCase("cabaret","[A-Z]","G","ALL"):
<cfoutput>#REReplaceNoCase("cabaret","[A-Z]","G","ALL")#</cfoutput>
<p>REReplaceNoCase("I LOVE JELLIES","jell(y|ies)","cookies"):
<cfoutput>#REReplaceNoCase("I LOVE JELLIES","jell(y|ies)","cookies")#
</cfoutput>
<p>REReplaceNoCase("I LOVE JELLY","jell(y|ies)","cookies"):
<cfoutput>#REReplaceNoCase("I LOVE JELLY","jell(y|ies)","cookies")#
</cfoutput>


Reverse

Description

Reverses the order of items, such as the characters in a string, the digits in a number, or the elements in an array.

Returns

A copy of string, with the characters in reverse order.

Category

String functions

Function syntax

Reverse(string)

See also

Left, Mid, Right

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

You can call this function on a number with code such as the following:

<cfoutput>reverse(6*2) equals #reverse(6*2)#<cfoutput>

This code outputs the following:

reverse(6*2) equals 21

Example

<h3>Reverse Example</h3>

<p>Reverse returns your string with the positions of the characters reversed.
<cfif IsDefined("FORM.myString")>
    <cfif FORM.myString is not "">
        <p>Reverse returned:
        <cfoutput>#Reverse(FORM.myString)#</cfoutput>
    <cfelse>
        <p>Please enter a string to be reversed.
    </cfif>
</cfif>

<form action = "reverse.cfm">
<p>Enter a string to be reversed:
<input type = "Text" name = "MyString">
<p><input type = "Submit" name = "">
</form>


Right

Description

Gets a specified number of characters from a string, beginning at the right.

Returns the specified number of characters from the end (or right side) of the specified string.

Returns

  • If the length of the string is greater than or equal to count, the rightmost count characters of the string
  • If count is greater than the length of the string, the whole string
  • If count is greater than 1, and the string is empty, an empty string

Category

String functions

Function syntax

Right(string, count)

See also

Left, Mid, Reverse

Parameters

Parameter | Description
string | A string or a variable that contains one.
count | A positive integer that specifies the number of characters to return.

Example

<!--- Simple Right Example--->
<cfoutput>
#Right("See the quick red fox jump over the fence", 9)#
<br>
#Right("ColdFusion", 6)#
</cfoutput>

<!--- Right Example using form input --->
<h3>Right Example</h3>
<cfif IsDefined("Form.MyText")>
<!--- If len returns 0 (zero), then show error message. --->
    <cfif Len(FORM.myText)>
        <cfif Len(FORM.myText) LTE FORM.RemoveChars>
            <cfoutput><p style="color: red; font-weight: bold">Your string
            #FORM.myText# only has #Len(FORM.myText)# characters. You cannot output
            the #FORM.removeChars# rightmost characters of this string because it
            is not long enough.</p></cfoutput>
        <cfelse>
            <cfoutput><p>Your original string: <strong>#FORM.myText#</strong>
            <p>Your changed string, showing only the <strong>#FORM.removeChars#
            </strong> rightmost characters:
            <strong>#right(Form.myText, FORM.removeChars)#</strong></p>
            </cfoutput>
        </cfif>
    <cfelse>
        <p style="color: red; font-weight: bold">Please enter a string of more
        than 0 (zero) characters.</p>
    </cfif>
</cfif>

<form action="<cfoutput>#CGI.ScriptName#</cfoutput>" method="POST">
<p>Type in some text<br />
<input type="Text" name="myText"></p>
<p>How many characters from the right do you want to show?
<select name="RemoveChars">
<option value="1">1
<option value="3" selected>3
<option value="5">5
<option value="7">7
<option value="9">9</select>
<input type="Submit" name="Submit" value="Remove characters"></p>
</form>


RJustify

Description

Right justifies characters of a string.

Returns

A copy of a string, right-justified in the specified field length.

Category

Display and formatting functions, String functions

Function syntax

RJustify(string, length)

See also

CJustify, LJustify

Parameters

Parameter | Description
string | A string enclosed in quotation marks, or a variable that contains one.
length | A positive integer or a variable that contains one. Length of field in which to justify string.

Example

<!--- This example shows how to use RJustify --->
<cfparam name = "jstring" default = "">

<cfif IsDefined("FORM.justifyString")>
    <cfset jstring = rjustify(FORM.justifyString, 35)>
</cfif>
<html>
<head>
<title>RJustify Example</title>
</head>
<body>
<h3>RJustify Function</h3>
<p>Enter a string. It will be right justified within the sample field

<form action = "rjustify.cfm">
<p><input type = "Text" value = "<cfoutput>#jString#</cfoutput>"
size = 35 name = "justifyString">

<p><input type = "Submit" name = ""> <input type = "reset">
</form>


Round

Description

Rounds a number to the closest integer that is larger than the input parameter.

Returns

An integer.

Category

Mathematical functions

Function syntax

Round(number)

See also

Ceiling, Fix, Int

Parameters

Parameter | Description
number | Number to round

Usage

Use this function to round a number. This function rounds numbers that end with .5 up to the nearest integer. It rounds 3.5 to 4 and -3.5 to -3.

Example

<h3>Round Example</h3>
<p>This function rounds a number to the closest integer.
<ul>
   <li>Round(7.49) : <cfoutput>#Round(7.49)#</cfoutput>
   <li>Round(7.5) : <cfoutput>#Round(7.5)#</cfoutput>
   <li>Round(-10.775) : <cfoutput>#Round(-10.775)#</cfoutput>
   <li>Round(-35.5) : <cfoutput>#Round(-35.5)#</cfoutput>
   <li>Round(35.5) : <cfoutput>#Round(35.5)#</cfoutput>
   <li>Round(1.2345*100)/100 : <cfoutput>#Round(1.2345*100)/100#</cfoutput>
</ul>


RTrim

Description

Removes spaces from the end of a string.

Returns

A copy of string, after removing trailing spaces.

Category

String functions

Function syntax

RTrim(string)

See also

LTrim, Trim

Parameters

Parameter | Description
string | A string or a variable that contains one

Example

<h3>RTrim Example</h3>

<cfif IsDefined("FORM.myText")>
<cfoutput>
<pre>
Your string:	"#FORM.myText#"
Your string:	"#RTrim(FORM.myText)#"
(right trimmed)
</pre>
</cfoutput>
</cfif>

<form action = "Rtrim.cfm" method="post">
<p>Enter some text. It will be modified by Rtrim to remove spaces from the right.
<p><input type = "Text" name = "myText" value = "TEST   ">

<p><input type = "Submit" name = "">
</form>


Second

Description

Extracts the ordinal for the second from a date/time object.

Returns

An integer in the range 0–59.

Category

Date and time functions

Function syntax

Second(date)

See also

DatePart, Hash, Minute

Parameters

Parameter | Description
date | A date/time object

Usage

When passing a date/time object as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Example

<!--- This example shows the use of Hour, Minute, and Second --->
<h3>Second Example</h3>
<cfoutput>
The time is currently #TimeFormat(Now())#.
We are in hour #Hour(Now())#, Minute #Minute(Now())#
and Second #Second(Now())# of the day.
</cfoutput>


SendGatewayMessage

Description

Sends an outgoing message through a ColdFusion MX event gateway.

Returns

String. The value returned depends on the gateway type.

Category

Extensibility functions

Function syntax

SendGatewayMessage(gatewayID, data)

See also

GetGatewayHelper; IM gateway message sending commands, SMS Gateway CFEvent structure and commands, CFML event gateway SendGatewayMessage data parameter, and Sending a message using the SendGatewayMessage function in Using Event Gateways in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter | Description
gatewayID | Identifier of the gateway to send the message. Must be the Gateway ID of one of the ColdFusion event gateway instances configured on the ColdFusion MX Administrator Event Gateways section’s Gateways page.
data | A ColdFusion structure. The contents of the structure depend on the event gateway type, but typically include a MESSAGE field that contains the message to send and a field that contains the destination address.

Usage

The SendGatewayMessage function calls the specified gateway’s outgoingMessage method. The value returned by the function depends on the gateway type. The following table describes the return values for standard ColdFusion MX gateway types:

Gateway type | Return values
Asynchronous CFML | If the message was queued for delivery to the CFC, returns True; False, otherwise.
Lotus SameTime | If the message or command was successful, returns OK. If an error occurred, returns a string indicating the cause.
SMS | If the gateway is in asynchronous mode, returns the empty string immediately. If the gateway is in synchronous mode, the function waits for the gateway to return a response. If the message was succesfully sent to the short message service center (SMSC), returns the message ID from the SMSC. If an error occured, returns a string indicating the cause.
XMPP | If the message or command was successful, returns OK If an error occured, returns a string indicating the cause.

Example

The following example uses an instance of the CFML gateway to log messages asynchronously to a file. To use this example, you must configure an instance of the CFML gateway with the name "Asynch Logger" in the ColdFusion MX Administrator. This gateway instance must use a CFC that takes the message and logs it. For sample CFC code, see Using the CFML event gateway for asynchronous CFCs in Using Event Gateways in ColdFusion MX Developer’s Guide.

Sending an event to the CFML event gateway that is registered in the
    ColdFusion MX Administrator as Asynch Logger.<br>
<cfscript>
    status = false;
    props = structNew();
    props.message = "Replace me with a variable with data to log";
    status = SendGatewayMessage("Asynch Logger", props);
    if (status IS True) WriteOutput(’Event Message "#props.message#" has been sent.’);
</cfscript>


SetEncoding

Description

Sets the character encoding (character set) of Form and URL scope variable values; used when the character encoding of the input to a form, or the character encoding of a URL, is not in UTF-8 encoding.

Returns

None

Category

International functions, System functions

Function syntax

SetEncoding(scope_name,charset)

See also

GetEncoding, cfcontent, cfprocessingdirective, URLDecode, URLEncodedFormat; Locales in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter

Description

scope_name
  • url
  • form

charset

The character encoding in which text in the scope variables is encoded. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

Usage

Use this function when the character encoding of the input to a form or the character encoding of a URL is not in UTF-8 encoding. For example, Traditional Chinese characters are often in Big5 encoding. This function resets URL and Form variables, so you should call it before using these variables (typically, in the Application.cfm page or Application.cfc file). Calling this function first also avoids interpreting the characters of the variables incorrectly.

For more information on character encoding, see the following web pages:

  • www.w3.org/International/O-charset.html provides general information on character encoding and the web, and has several useful links.
  • www.iana.org/assignments/character-sets is a complete list of character sets names used on the Internet, maintained by the Internet Assigned Numbers Authority.
  • java.sun.com/j2se/1.4.1/docs/guide/intl/encoding.doc.html lists the character encoding that Java 1.4.1, and therefore the default ColdFusion configuration, can interpret. If you use a JVM that does not conform to the Sun Java 2 Platform, Standard Edition, v 1.4.1, the supported locales may differ. The list uses Java internal names, not the IANA character encoding names that you normally use in the SetEncoding charset parameter and other ColdFusion attributes and parameters. Java automatically converts standard IANA names to its internal names as needed.

Example

<!--- This example sends and interprets the contents of two fields as
        big5 encoded text. Note that the form fields are received as URL variables
        because the form uses the GET method. --->
<cfcontent type="text/html; charset=big5">
<form action='#cgi.script_name#' method='get'>
<input name='xxx' type='text'>
<input name='yyy' type='text'>
<input type="Submit" value="Submit">
</form>

<cfif IsDefined("URL.xxx")>
<cfscript>
    SetEncoding("url", "big5");
    WriteOutput("URL.XXX is " & URL.xxx & "<br>");
    WriteOutput("URL.YYY is " & URL.yyy & "<br>");
    theEncoding = GetEncoding("URL");
     WriteOutput("The URL variables were decoded using '" &
theEncoding & "' encoding.");
</cfscript>
</cfif>


SetLocale

Description

Sets the country/language locale for ColdFusion processing and the page returned to the client. The locale value determines the default format of date, time, number, and currency values, according to language and regional conventions.

Returns

The locale value prior to setting the new locale, as a string.

Category

International functions, System functions

Function syntax

SetLocale(new_locale)

See also

GetHttpTimeString, GetLocale, GetLocaleDisplayName; Locales in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added support for all locales supported by the ColdFusion MX Java runtime.

ColdFusion MX:

  • Changed formatting behavior: this function might return a different value than in earlier releases. This function uses Java standard locale determination and formatting rules on all platforms.
  • Deprecated the Spanish (Mexican) locale option. It might not work, and it might cause an error, in later releases.
  • Changed the Spanish (Modern) option: it now sets the locale to Spanish (Standard).

Parameters

Parameter | Description
new_locale | The name of a locale; for example, "English (US)"

Usage

You can specify any locale name that is listed in the Server.Coldfusion.SupportedLocales variable. This variable is a comma-delimited list of all locale names supported by the JVM, plus the locale names that were required by ColdFusion MX prior to ColdFusion MX 7.

The following locale names were used in ColdFusion releases through ColdFusion MX 6.1, and continue to be supported. If you use any of these values in the SetLocale function, the GetLocale function returns the name you set, not the corresponding Java locale name.

Chinese (China) | French (Belgian) | Korean
Chinese (Hong Kong) | French (Canadian) | Norwegian (Bokmal)
Chinese (Taiwan) | French (Standard) | Norwegian (Nynorsk)
Dutch (Belgian) | French (Swiss) | Portuguese (Brazilian)
Dutch (Standard) | German (Austrian) | Portuguese (Standard)
English (Australian) | German (Standard) | Spanish (Modern)
English (Canadian) | German (Swiss) | Spanish (Standard)
English (New Zealand) | Italian (Standard) | Swedish
English (UK) | Italian (Swiss) |
English (US) | Japanese |

ColdFusion determines the locale value as follows:

  • By default, ColdFusion uses the JVM locale, and the default JVM locale is the operating system locale. You can set JVM locale value explicitly in ColdFusion MX in the ColdFusion Administrator Java and JVM Settings page JVM Arguments field; for example:
    -Duser.language=de -Duser.region=DE.
  • A locale set using the SetLocale function persists for the current request or until it is reset by another SetLocale function in the request.
  • If a request has multiple SetLocale functions, the current locale setting affects how locale-sensitive ColdFusion tags and functions, such as the functions that start with LS format data. The last SetLocale function that ColdFusion processes before sending a response to the requestor (typically the client browser) determines the value of the response Content-Language HTTP header. The browser that requested the page displays the response according to the rules for the language specified by the Content-Language header.
  • ColdFusion ignores any SetLocale functions that follow a cfflush tag.

Because this function returns the previous locale setting, you can save the original locale value. You can restore the original locale by calling SetLocale again with the saved variable. For example, the following line saves the original locale ins a Session variable:

<cfset Session.oldlocale = SetLocale(newLocale)>

The variable server.ColdFusion.SupportedLocales is initialized at startup with a comma-delimited list of the locales that ColdFusion and the operating system support. If you call SetLocale with a locale that is not in the list, the call generates an error.

Note: ColdFusion uses the Spanish (Standard) formats for Spanish (Modern) and Spanish (Standard).

Example

<h3>SetLocale Example</h3>
<p>SetLocale sets the locale to the specified new locale for the current session.
<p>A locale encapsulates the set of attributes that govern the display and
formatting of date, time, number, and currency values.
<p>The locale for this system is <cfoutput>#GetLocale()#</cfoutput>
<p><cfoutput><I>the old locale was #SetLocale("English (UK)")#</I>
<p>The locale is now #GetLocale()#</cfoutput>


SetProfileString

Description

Sets the value of a profile entry in an initialization file.

Returns

An empty string, upon successful execution; otherwise, an error message.

Category

System functions

Function syntax

SetProfileString(iniPath, section, entry, value)

See also

GetProfileSections, GetProfileString, SetProfileString

Parameters

Parameter | Description
iniPath | Absolute path of initialization file
section | Section of the initialization file in which the entry is to be set
entry | Name of the entry to set
value | Value to which to set the entry

Example

<h3>SetProfileString Example</h3>
This example uses SetProfileString to set the timeout value in an
initialization file. Enter the full path of your initialization
file, specify the timeout value, and submit the form.
<!--- This section checks whether the form was submitted. If so, this
section sets the initialization path and timeout value to the
path and timeout value specified in the form --->
<cfif Isdefined("Form.Submit")>

    <cfset IniPath = FORM.iniPath>
    <cfset Section = "boot loader">
    <cfset MyTimeout = FORM.MyTimeout>
    <cfset timeout = GetProfileString(IniPath, Section, "timeout")>

    <cfif timeout Is Not MyTimeout>
     <cfif MyTimeout Greater Than 0>
         <hr size = "2" color = "#0000A0">
        <p>Setting the timeout value to <cfoutput>#MyTimeout#</cfoutput>
        </p>
            <cfset code = SetProfileString(IniPath,
                Section, "timeout", MyTimeout)>
        <p>Value returned from SetProfileString:
                <cfoutput>#code#</cfoutput></p>
        <cfelse>
            <hr size = "2" color = "red">
            <p>Timeout value should be greater than zero in order to
                provide time for user response.</p>
            <hr size = "2" color = "red">
        </cfif>
    <cfelse>
        <p>The timeout value in your initialization file is already
            <cfoutput>#MyTimeout#</cfoutput>.</p>
    </cfif>
    <cfset timeout = GetProfileString(IniPath, Section, "timeout")>
    <cfset default = GetProfileString(IniPath, Section, "default")>

    <h4>Boot Loader</h4>
    <p>Timeout is set to: <cfoutput>#timeout#</cfoutput>.</p>
    <p>Default directory is: <cfoutput>#default#</cfoutput>.</p>

</cfif>

<form action = "setprofilestring.cfm">
<hr size = "2" color = "#0000A0">
<table cellspacing = "2" cellpadding = "2" border = "0">
<tr>
  <td>Full Path of Init File</td>
  <td><input type = "Text" name = "IniPath"
                value = "C:\myboot.ini"></td>
</tr>
<tr>
  <td>Timeout</td>
  <td><input type = "Text" name = "MyTimeout" value = "30"></td>
</tr>
<tr>
  <td><input type = "Submit" name = "Submit" value = "Submit"></td>
  <td></td>
</tr>
</table>
</form>


SetVariable

Description

This function is no longer required in well-formed ColdFusion pages.

Sets a variable in the name parameter to the value of the value parameter.

Returns

The new value of the variable.

Category

Dynamic evaluation functions

Function syntax

SetVariable(name, value)

See also

DE , Evaluate , IIf

Parameters

Parameter | Description
name | Variable name
value | A string, the name of a string, or a number

Usage

You can use direct assignment statements in place of this function to set values of dynamically named variables. To do so, put the dynamically named variable in quotation marks and number signs (#); for example:

<cfset DynamicVar2 = "ABD">
<cfset "#DynamicVar2#" = "Test Value2">

Also, the following lines are equivalent:

<cfset "myVar#i#" = myVal>
SetVariable("myVar" & i, myVal)

For more information, see Using Expressions and Number Signs in ColdFusion MX Developer’s Guide.

Example

<h3>SetVariable Example</h3>

<cfif IsDefined("FORM.myVariable")>
<!--- strip out url, client., cgi., session., caller. --->
<!--- This example only lets you set form variables --->
<cfset myName = ReplaceList(FORM.myVariable,
 "url,client,cgi,session,caller", "FORM,FORM,FORM,FORM,FORM")>

<cfset temp = SetVariable(myName, FORM.myValue)>
<cfset varName = myName>
<cfset varNameValue = Evaluate(myName)>
<cfoutput>
    <p>Your variable, #varName#
    <p>The value of #varName# is #varNameValue#
</cfoutput>
</cfif>


Sgn

Description

Determines the sign of a number.

Returns

  • 1, if number is positive.
  • 0, if number is 0.
  • -1, if number is negative.

Category

Mathematical functions

Function syntax

Sgn(number)

See also

Abs

Parameters

Parameter | Description
number | A number

Example

<h3>Sgn Example</h3>
<p>Sgn determines the sign of a number. Returns 1 if number is positive;
0 if number is 0; -1 if number is negative.
<p>Sgn(14): <cfoutput>#Sgn(14)#</cfoutput>
<p>Sgn(21-21): <cfoutput>#Sgn(21-21)#</cfoutput>
<p>Sgn(-0.007): <cfoutput>#Sgn(-0.007)#</cfoutput>


Sin

Description

Calculates the sine of an angle that is entered in radians.

Returns

A number; the sine of the angle.

Category

Mathematical functions

Function syntax

Sin(number)

See also

ASin, Cos, ACos, Tan, Atn, Pi

Parameters

Parameter | Description
number | Angle, in radians for which to calculate the sine.

Usage

The range of the result is -1 to 1.

To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

Note: Because the function uses floating point arithmetic, it returns a very small number (such as 6.12323399574E-017) for angles that should produce 0. To test for a 0 value, check whether the value is less than 0.0000000000001.

Example

<h3>Sin Example</h3>
<!--- Calculate sine if form has been submitted --->
<cfif IsDefined("FORM.sinNum")>
<!--- Make sure input is a number --->
    <cfif IsNumeric(#FORM.sinNum#)>
<!--- Convert degrees to radians, call the Sin function. --->
        <cfset sinValue=#Sin((Form.sinNum * PI()) / 180)#>
<!--- 0.0000000000001 is the function's precision limit.
     If absolute value of returned sine value is
     less, set result to 0 --->
        <cfif Abs(sinValue) LT 0.0000000000001>
           <cfset sinValue=0>
        </cfif>
        <cfoutput>
            Sin(#FORM.sinNum#) = #sinValue#<br><br>
        </cfoutput>
    <cfelse>
<!--- If input is not a number, show an error message --->
        <h4>You must enter a numeric angle in degrees.</h4>
    </cfif>
</cfif>
<form action = "#CGI.script_name#" method="post">
    Enter an angle in degrees to get its sine:
    <br><input type = "Text" name = "sinNum" size = "15">
    <br><br>
    <input type = "Submit" name = "">&nbsp;&nbsp;
    <input type = "RESET"
</form>


SpanExcluding

Description

Gets characters from a string, from the beginning to a character that is in a specified set of characters. The search is case-sensitive.

Returns

A string; characters from string, from the beginning to a character that is in set.

Category

String functions

Function syntax

SpanExcluding(string, set)

See also

GetToken, SpanIncluding; Caching parts of ColdFusion pages in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
string | A string or a variable that contains one
set | A string or a variable that contains one. Must contain one or more characters

Example

<h3>SpanExcluding Example</h3>

<cfif IsDefined("FORM.myString")>
<p>Your string was <cfoutput>#FORM.myString#</cfoutput>
<p>Your set of characters was <cfoutput>#FORM.mySet#</cfoutput>
<p>Your string up until one of the characters in the set is:
<cfoutput>#SpanExcluding(FORM.myString, FORM.mySet)#</cfoutput>
</cfif>

<p>Returns all characters from string from beginning to a character
from the set of characters. The search is case-sensitive.

<form method = post action = "spanexcluding.cfm">
<p>Enter a string:
<br><input type = "Text" name = "myString" value = "Hey, you!">
<p>And a set of characters:
<br><input type = "Text" name = "mySet" value = "Ey">
<br><input type = "Submit" name = "">
</form>


SpanIncluding

Description

Gets characters from a string, from the beginning to a character that is not in a specified set of characters. The search is case-sensitive.

Returns

A string; characters from string, from the beginning to a character that is not in set.

Category

String functions

Function syntax

SpanIncluding(string, set)

See also

GetToken, SpanExcluding; Caching parts of ColdFusion pagesin Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
string | A string or a variable that contains the search string.
set | A string or a variable that contains a set of characters. Must contain one or more characters.

Example

<h3>SpanIncluding Example</h3>
<cfif IsDefined("FORM.myString")>
<p>Your string was <cfoutput>#FORM.myString#</cfoutput>
<p>Your set of characters was <cfoutput>#FORM.mySet#</cfoutput>
<p>Your string, until the characters in the set have been found, is:
<cfoutput>#SpanIncluding(FORM.myString, FORM.mySet)#</cfoutput>
</cfif>

<p>Returns characters of a string, from beginning to a character
that is not in set. The search is case-sensitive.

<form action = "spanincluding.cfm" method="post">
<p>Enter a string:
<br><input type = "Text" name = "myString" value = "Hey, you!">
<p>And a set of characters:
<br><input type = "Text" name = "mySet" value = "ey,H">
<br><input type = "Submit" name = "">
</form>


Sqr

Description

Calculates the square root of a number.

Returns

Number; square root of number.

Category

Mathematical functions

Function syntax

Sqr(number)

See also

Abs

Parameters

Parameter | Description
number | A positive integer or a variable that contains one. Number whose square root to get.

Usage

The value in number must be greater than or equal to 0.

Example

<h3>Sqr Example</h3>

<p>Returns the square root of a positive number.

<p>Sqr(2): <cfoutput>#Sqr(2)#</cfoutput>
<p>Sqr(Abs(-144)): <cfoutput>#Sqr(Abs(-144))#</cfoutput>
<p>Sqr(25^2): <cfoutput>#Sqr(25^2)#</cfoutput>


StripCR

Description

Deletes return characters from a string.

Returns

A copy of string, after removing return characters.

Category

Display and formatting functions, String functions

Function syntax

StripCR(string)

See also

ParagraphFormat

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

Useful for preformatted (between <pre> and </pre> tags) HTML display of data entered in textarea fields.

Example

<h3>StripCR Example</h3>

<p>Function StripCR is useful for preformatted HTML display of data
(PRE) entered in textarea fields.
<cfif isdefined("Form.myTextArea")>

<pre>
<cfoutput>#StripCR(Form.myTextArea)#</cfoutput>
</pre>
</cfif>
<!--- use #Chr(10)##Chr(13)# to simulate line feed/carriage return combination --->
<form action = "stripcr.cfm">
<textarea name = "MyTextArea" cols = "35" rows = 8>
This is sample text and you see how it scrolls
    <cfoutput>#Chr(10)##Chr(13)#</cfoutput>
From one line
    <cfoutput>#Chr(10)##Chr(13)##Chr(10)##Chr(13)#</cfoutput>
to the next
</textarea>
<input type = "Submit" name = "Show me the HTML version">
</form>


StructAppend

Description

Appends one structure to another.

Returns

True, upon successful completion; False, otherwise.

Category

Structure functions

Function syntax

StructAppend(struct1, struct2, overwriteFlag)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter

Description

struct1

Structure to which struct2 is appended.

struct2

Structure that contains the data to append to struct1

overwriteFlag
  • True or "Yes": values in struct2 overwrite corresponding values in struct1. Default.
  • False or "No": values in struct2 do not overwrite corresponding values in struct1.

Usage

This function appends the fields and values of struct2 to struct1; struct2 is not modified. If struct1 already contains a field of struct2, overwriteFlag determines whether the value in struct2 overwrites it.

A structure’s keys are unordered.

Example

<html>
<body>
<!---- Create a Name structure --->
<cfset nameCLK=StructNew()>
<cfset nameCLK.first="Chris">
<cfset nameCLK.middle="Lloyd">
<cfset nameCLK.last="Gilson">
<!--- Create an address struct --->
<cfset addrCLK=StructNew()>
<cfset addrCLK.street="17 Gigantic Rd">
<cfset addrCLK.city="Watertown">
<cfset addrCLK.state="MA">
<cfset addrCLK.zip="02472">
<!---- Create a Person structure --->
<cfset personCLK=StructNew()>
<cfset personCLK.name=#nameCLK#>
<cfset personCLK.addr=#addrCLK#>
<!--- Display the contents of the person struct before the Append --->
<p>
The person struct <b>before</b> the Append call:<br>
<cfloop collection=#personCLK# item="myItem">
<cfoutput>
#myItem#<br>
</cfoutput>
</cfloop>
<!--- Merge the address struct into the top-level person struct --->
<cfset bSuccess = StructAppend( personCLK, addrCLK )>

<!--- Display the contents of the person struct, after the Append --->
<p>
The person struct <b>after</b> the Append call:<br>
<cfloop collection=#personCLK# item="myItem">
    <cfoutput>
        #myItem#<br>
    </cfoutput>
</cfloop>


StructClear

Description

Removes all data from a structure.

Returns

True, on successful execution; False, otherwise.

Category

Structure functions

Function syntax

StructClear(structure)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
structure | Structure to clear

Usage

Do not call this function on a session variable. For more information, see TechNote 14143, "ColdFusion 4.5 and the StructClear(Session) function," at www.coldfusion.com/Support/KnowledgeBase/SearchForm.cfm. (The article applies to ColdFusion 4.5, 5.x, and ColdFusion MX.)

Example

<!--- Shows StructClear function. Calls cf_addemployee custom tag which
    uses the addemployee.cfm file. --->
<body>
<h1>Add New Employees</h1>
<!--- Establish params for first time through --->
<cfparam name = "Form.firstname" default = "">
<cfparam name = "Form.lastname" default = "">
<cfparam name = "Form.email" default = "">
<cfparam name = "Form.phone" default = "">
<cfparam name = "Form.department" default = "">
<cfif form.firstname eq "">
 <p>Please fill out the form.
<cfelse>
 <cfoutput>
  <cfscript>
   employee = StructNew();
   StructInsert(employee, "firstname", Form.firstname);
   StructInsert(employee, "lastname", Form.lastname);
   StructInsert(employee, "email", Form.email);
   StructInsert(employee, "phone", Form.phone);
   StructInsert(employee, "department", Form.department);
  </cfscript>
 </cfoutput>
<!--- Call the custom tag that adds employees --->
 <cf_addemployee empinfo = "#employee#">
 <cfscript>StructClear(employee);</cfscript>
 </cfif>


StructCopy

Description

Copies a structure. Copies top-level keys, values, and arrays in the structure by value; copies nested structures by reference.

Returns

A copy of a structure, with the same keys and values; if structure does not exist, throws an exception.

Category

Structure functions

Function syntax

StructCopy(structure)

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
structure | Structure to copy

Usage

The following code shows how this function copies a structure that contains a string field, a number field, and a two-dimensional array at the top level:

<cfoutput>
    <cfset assignedCopy = StructNew()>
  <cfset assignedCopy.string = #struct.string#>
    <cfset assignedCopy.number = #struct.number#>
    <cfset assignedCopy.array = ArrayNew(2)>
    <cfset assignedCopy.array[1][1] = #struct.array[1][1]#>
    <cfset assignedCopy.array[1][2] = #sruct.array[1][2]#>
</cfoutput>

The following code shows how StructCopy copies a nested structure:

<cfoutput>
  <cfset assignedCopy.nestedStruct = struct.nestedStruct>
</cfoutput>

To copy a structure entirely by value, use Duplicate.

The following table shows how variables are assigned:

Variable type | Assigned by
structure.any_simple_value Boolean Binary Base64 | Value
structure.array | Value
structure.nested_structure | Reference
structure.object | Reference
structure.query | Reference

Example

<!--- This code shows assignment by-value and by-reference. --->
// This script creates a structure that StructCopy copies by value. <br>
<cfscript>
    // Create elements.
    s = StructNew();
    s.array = ArrayNew(2);

    // Assign simple values to original top-level structure fields.
    s.number = 99;
    s.string = "hello tommy";

    // Assign values to original top-level array.
    s.array[1][1] = "one one";
    s.array[1][2] = "one two";
</cfscript>

<!--- Output original structure --->
<hr>
<b>Original Values</b><br>
<cfoutput>
    // Simple values <br>
    s.number = #s.number#<br>
    s.string = #s.string#<br>
    // Array value <br>
    s.array[1][1] = #s.array[1][1]#<br>
    s.array[1][2] = #s.array[1][2]#<br>
</cfoutput>

// Copy this structure to a new structure. <br>
<cfset copied = StructCopy(s)>

<cfscript>
// Change the values of the original structure. <br>
    s.number = 100;
    s.string = "hello tommy (modified)";
    s.array[1][1] = "one one (modified)";
    s.array[1][2] = "one two (modified)";
</cfscript>
<hr>
<b>Modified Original Values</b><br>
<cfoutput>
    // Simple values <br>
    s.number = #s.number#<br>
    s.string = #s.string#<br>
    // Array value <br>
    s.array[1][1] = #s.array[1][1]#<br>
    s.array[1][2] = #s.array[1][2]#<br>
</cfoutput>
<hr>
<b>Copied structure values should be the same as the original.</b><br>
<cfoutput>
    // Simple values <br>
    copied.number = #copied.number#<br>
    copied.string = #copied.string#<br>
    // Array value <br>
    copied.array[1][1] = #copied.array[1][1]#<br>
    copied.array[1][2] = #copied.array[1][2]#<br>
</cfoutput>

// This script creates a structure that StructCopy copies by reference.
<cfscript>
    // Create elements.
    s = StructNew();
    s.nested = StructNew();
    s.nested.array = ArrayNew(2);
    // Assign simple values to nested structure fields.
    s.nested.number = 99;
    s.nested.string = "hello tommy";
    // Assign values to nested array.
    s.nested.array[1][1] = "one one";
    s.nested.array[1][2] = "one two";
</cfscript>

<!--- Output original structure --->
<hr>
<b>Original Values</b><br>
<cfoutput>
    // Simple values <br>
    s.nested.number = #s.nested.number#<br>
    s.nested.string = #s.nested.string#<br>

    // Array values <br>
    s.nested.array[1][1] = #s.nested.array[1][1]#<br>
    s.nested.array[1][2] = #s.nested.array[1][2]#<br>
</cfoutput>

// Use StructCopy to copy this structure to a new structure. <br>
<cfset copied = StructCopy(s)>
// Use Duplicate to clone this structure to a new structure. <br>
<cfset duplicated = Duplicate(s)>

<cfscript>
// Change the values of the original structure.
    s.nested.number = 100;
    s.nested.string = "hello tommy (modified)";
    s.nested.array[1][1] = "one one (modified)";
    s.nested.array[1][2] = "one two (modified)";
</cfscript>
<hr>
<b>Modified Original Values</b><br>
<cfoutput>
    // Simple values <br>
    s.nested.number = #s.nested.number#<br>
    s.nested.string = #s.nested.string#<br>

    // Array value <br>
    s.nested.array[1][1] = #s.nested.array[1][1]#<br>
    s.nested.array[1][2] = #s.nested.array[1][2]#<br>
</cfoutput>

<hr>
<b>Copied structure values should reflect changes to original.</b><br>
<cfoutput>
    // Simple values <br>
    copied.nested.number = #copied.nested.number#<br>
    copied.nested.string = #copied.nested.string#<br>
    // Array values <br>
    copied.nested.array[1][1] = #copied.nested.array[1][1]#<br>
    copied.nested.array[1][2] = #copied.nested.array[1][2]#<br>
</cfoutput>

<hr>
<b>Duplicated structure values should remain unchanged.</b><br>
<cfoutput>
    // Simple values <br>
    duplicated.nested.number = #duplicated.nested.number#<br>
    duplicated.nested.string = #duplicated.nested.string#<br>
    // Array value <br>
    duplicated.nested.array[1][1] = #duplicated.nested.array[1][1]#<br>
    duplicated.nested.array[1][2] = #duplicated.nested.array[1][2]#<br>
</cfoutput>


StructCount

Description

Counts the keys in a structure.

Returns

A number; if structure does not exist, throws an exception.

Category

Structure functions

Function syntax

StructCount(structure)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
structure | Structure to access

Example

<!--- This view-only example shows use of StructCount. --->
<p>This file is similar to addemployee.cfm, which is called by
StructNew, StructClear, and StructDelete. To test, copy
StructCount function to appropriate place in addemployee.cfm.
<!---
<cfswitch expression = "#ThisTag.ExecutionMode#">
  <cfcase value = "start">
   <cfif StructIsEmpty(attributes.EMPINFO)>
    <cfoutput>Error. No employee data was passed.</cfoutput>
     <cfexit method = "ExitTag">
   <cfelse>
    <cfquery name = "AddEmployee" datasource = "cfdocexamples">
     INSERT INTO Employees
       (FirstName, LastName, Email, Phone, Department)
      VALUES
       <cfoutput>
        (
         ‘#StructFind(attributes.EMPINFO, "firstname")#’ ,
         ‘#StructFind(attributes.EMPINFO, "lastname")#’ ,
         ‘#StructFind(attributes.EMPINFO, "email")#’ ,
         ‘#StructFind(attributes.EMPINFO, "phone")#’ ,
         ‘#StructFind(attributes.EMPINFO, "department")#’
         )
       </cfoutput>
     </cfquery>
   </cfif>
   <cfoutput><hr>Employee Add Complete
     <p>#StructCount(attributes.EMPINFO)# columns added.</cfoutput>
  </cfcase>
</cfswitch> --->


StructDelete

Description

Removes an element from a structure.

Returns

Boolean value. The value depends on the indicatenotexisting parameter value.

Category

Structure functions

Function syntax

StructDelete(structure, key [, indicatenotexisting ])

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter

Description

structure

Structure or a variable that contains one. Contains element to remove.

key

Element to remove.

indicatenotexisting
  • True: returns Yes if key exists; No if it does not.
  • False: returns Yes regardless of whether key exists. Default.

Example

<h3>StructDelete Function</h3>
<!--- Delete the surrounding comments to make this page work
<p>This example uses the StructInsert and StructDelete functions.
<!--- Establish params for first time through --->
<cfparam name = "firstname" default = "Mary">
<cfparam name = "lastname" default = "Sante">
<cfparam name = "email" default = "msante@allaire.com">
<cfparam name = "phone" default = "777-777-7777">
<cfparam name = "department" default = "Documentation">

 <cfif IsDefined("FORM.Delete")>
     <cfoutput>
     Field to be deleted: #form.field#
    </cfoutput>
    <p>
    <CFScript>
       employee = StructNew();
       StructInsert(employee, "firstname", firstname);
       StructInsert(employee, "lastname", lastname);
       StructInsert(employee, "email", email);
       StructInsert(employee, "phone", phone);
       StructInsert(employee, "department", department);
    </CFScript>
      Before deletion, employee structure looks like this:
    <cfdump var="#employee#">
    <br>
     <cfset rc = StructDelete(employee, "#form.field#", "True")>
     <cfoutput>
        Did I delete the field "#form.field#"? The code indicates: #rc#<br>
         The structure now looks like this:<br>
        <cfdump var="#employee#">
        <br>
    </cfoutput>
</cfif>
<br><br>
<form method="post" action = "#CGI.Script_Name#">
    <p>Select the field to be deleted:&nbsp;
    <select name = "field">
    <option value = "firstname">first name
    <option value = "lastname">last name
    <option value = "email">email
    <option value = "phone">phone
    <option value = "department">department
    </select>
    <input type = "submit" name = "Delete" value = "Delete">
</form>
Delete this comment to make this page work --->


StructFind

Description

Determines the value associated with a key in a structure.

Returns

The value associated with a key in a structure; if structure does not exist, throws an exception.

Category

Structure functions

Function syntax

StructFind(structure, key)

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
structure | Structure that contains the value to return
key | Key whose value to return

Usage

A structure’s keys are unordered.

Example

<!--- This view-only example shows the use of StructFind. --->
<p>This file is identical to addemployee.cfm, which is called by StructNew,
StructClear, and StructDelete. It adds employees. Employee information
is passed through the employee structure (EMPINFO attribute). In UNIX,
you must also add the Emp_ID.
<!---
<cfswitch expression = "#ThisTag.ExecutionMode#">
  <cfcase value = "start">
   <cfif StructIsEmpty(attributes.EMPINFO)>
    <cfoutput>Error. No employee data was passed.</cfoutput>
     <cfexit method = "ExitTag">
   <cfelse>
     <cfquery name = "AddEmployee" datasource = "cfdocexamples">
     INSERT INTO Employees (FirstName, LastName, Email, Phone, Department)
      VALUES
       <cfoutput>
        (
         ‘#StructFind(attributes.EMPINFO, "firstname")#’ ,
         ‘#StructFind(attributes.EMPINFO, "lastname")#’ ,
         ‘#StructFind(attributes.EMPINFO, "email")#’ ,
         ‘#StructFind(attributes.EMPINFO, "phone")#’ ,
         ‘#StructFind(attributes.EMPINFO, "department")#’ )
       </cfoutput>
    </cfquery>
   </cfif>
   <cfoutput><hr>Employee Add Complete</cfoutput>
  </cfcase>
</cfswitch> --->


StructFindKey

Description

Searches recursively through a substructure of nested arrays, structures, and other elements, for structures whose values match the search key in the value parameter.

Returns

An array that contains structures with values that match value.

Category

Structure functions

Function syntax

StructFindKey(top, value, scope)

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

top

ColdFusion object (structure or array) from which to start search. This parameter requires an object, not a name of an object.

value

String or a variable that contains one for which to search.

scope
  • one: returns one matching key. Default.
  • all: returns all matching keys.

Usage

Returns an array that includes one structure for each of the specified values it finds. The fields of each of these structures are:

  • Value: value held in the found key
  • Path: string that can be used to reach the found key
  • Owner: parent object that contains the found key

A structure’s keys are unordered.

Example

<cfset aResults = StructFindKey( #request#, "bass" )>


StructFindValue

Description

Searches recursively through a substructure of nested arrays, structures, and other elements for structures with values that match the search key in the value parameter.

Returns

An array that contains structures with values that match the search key value. If none are found, returns an array of size 0.

Category

Structure functions

Function syntax

StructFindValue( top, value [, scope])

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

top

ColdFusion object (a structure or an array) from which to start search. This parameter requires an object, not a name of an object.

value

String or a variable that contains one for which to search.

The type must be a simple object. Arrays and structures are not supported.

scope
  • one: function returns one matching key (default).
  • all: function returns all matching keys.

Usage

The fields of each structure in the returned array are:

  • Key: name of the key in which the value was found
  • Path: string which could be used to reach the found key
  • Owner: parent object that contains the found key

A structure’s keys are unordered.

Example

<cfset aResults = StructFindValue( #request#, "235" )>


StructGet

Description

Gets a structure(s) from a specified path.

Returns

An alias to the variable in the pathDesired parameter. If necessary, StructGet creates structures or arrays to make pathDesired a valid variable "path."

Category

Structure functions

Function syntax

StructGet(pathDesired)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed behavior: this function can be used on XML objects.
  • Changed behavior: if there is no structure or array present in pathDesired, this function creates structures or arrays to make pathDesired a valid variable "path."

Parameters

Parameter | Description
pathDesired | Pathname of variable that contains structure or array from which ColdFusion retrieves structure.

Usage

You can inadvertently create invalid structures using this function. For example, if array notation is used to expand an existing array, the specified new element is created, regardless of the type currently held in the array.

Example

<!--- GetStruct() test --->
<cfset test = StructGet( "dog.myscope.test" )>
<cfset test.foo = 1>
<cfif NOT IsDefined("dog")>
    Dog is not defined<br>
</cfif>
<cfif NOT IsDefined("dog.myscope")>
    Dog.Myscope is not defined<br>
</cfif>
<cfif NOT Isdefined("dog.myscope.test")>
    Dog.Myscope.Test is not defined<br>
</cfif>
<cfif NOT Isdefined("dog.myscope.test.foo")>
    Dog.Myscope.Test.Foo is not defined<br>
</cfif>
<cfoutput>
    #dog.myscope.test.foo#<br>
</cfoutput>
<cfset test = StructGet( "request.myscope[1].test" )>
<cfset test.foo = 2>
<cfoutput>
    #request.myscope[1].test.foo#<br>
</cfoutput>
<cfset test = StructGet( "request.myscope[1].test[2]" )>
<cfset test.foo = 3>
<cfoutput>
    #request.myscope[1].test[2].foo#<br>
</cfoutput>


StructInsert

Description

Inserts a key-value pair into a structure.

Returns

True, upon successful completion. If structure does not exist, or if key exists and allowoverwrite = "False", ColdFusion throws an exception.

Category

Structure functions

Function syntax

StructInsert(structure, key, value [, allowoverwrite ])

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
structure | Structure to contain the new key-value pair.
key | Key that contains the inserted value.
value | Value to add.
allowoverwrite | Optional. Whether to allow overwriting a key. The default value is False.

Usage

A structure’s keys are unordered.

Example

<h1>Add New Employees</h1>
<!--- Establish params for first time through --->
<cfparam name = "FORM.firstname" default = "">
<cfparam name = "FORM.lastname" default = "">
<cfparam name = "FORM.email" default = "">
<cfparam name = "FORM.phone" default = "">
<cfparam name = "FORM.department" default = "">

<cfif FORM.firstname EQ "">
 <p>Please fill out the form.
<cfelse>
 <cfoutput>
  <CFScript>
   employee = StructNew();
   StructInsert(employee, "firstname", FORM.firstname);
   StructInsert(employee, "lastname", FORM.lastname);
   StructInsert(employee, "email", FORM.email);
   StructInsert(employee, "phone", FORM.phone);
   StructInsert(employee, "department", FORM.department);
 </CFScript>

 <p>First name is #StructFind(employee, "firstname")#</p>
 <p>Last name is #StructFind(employee, "lastname")#</p>
 <p>EMail is #StructFind(employee, "email")#</p>
 <p>Phone is #StructFind(employee, "phone")#</p>
 <p>Department is #StructFind(employee, "department")#</p>
 </cfoutput>

 <!--- Call the custom tag that adds employees --->
 <CF_ADDEMPLOYEE EMPINFO = "#employee#">
</cfif>

<Hr>
<form action = "structinsert.cfm">
    <p>First Name:&nbsp;
    <input name = "firstname" type = "text" hspace = "30" maxlength = "30">
    <p>Last Name:&nbsp;
    <input name = "lastname" type = "text" hspace = "30" maxlength = "30">
    <p>EMail:&nbsp;
    <input name = "email" type = "text" hspace = "30" maxlength = "30">
    <p>Phone:&nbsp;
    <input name = "phone" type = "text" hspace = "20" maxlength = "20">
    <p>Department:&nbsp;
    <input name = "department" type = "text" hspace = "30" maxlength = "30">
    <p>
    <input type = "submit" value = "OK">
</form>


StructIsEmpty

Description

Determines whether a structure contains data.

Returns

True, if structure is empty; if structure does not exist, ColdFusion throws an exception.

Category

Decision functions, Structure functions

Function syntax

StructIsEmpty(structure)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
structure | Structure to test

Example

<!--- This example illustrates use of StructIsEmpty. --->
<p>This file is identical to addemployee.cfm, which is called by StructNew,
StructClear, and StructDelete. It adds employees. Employee information
is passed through employee structure (EMPINFO attribute). In UNIX, you
must also add the Emp_ID.
<cfswitch expression = "#ThisTag.ExecutionMode#">
  <cfcase value = "start">
   <cfif StructIsEmpty(attributes.EMPINFO)>
    <cfoutput>Error. No employee data was passed.</cfoutput>
     <cfexit method = "ExitTag">
   <cfelse>
    <!--- Add the employee; In UNIX, you must also add the Emp_ID --->
     <cfquery name = "AddEmployee" datasource = "cfdocexamples">
     INSERT INTO Employees
       (FirstName, LastName, Email, Phone, Department)
      VALUES
       <cfoutput>
        (
         ‘#StructFind(attributes.EMPINFO, "firstname")#’ ,
         ‘#StructFind(attributes.EMPINFO, "lastname")#’ ,
         ‘#StructFind(attributes.EMPINFO, "email")#’ ,
         ‘#StructFind(attributes.EMPINFO, "phone")#’ ,
         ‘#StructFind(attributes.EMPINFO, "department")#’
         )
       </cfoutput>
    </cfquery>
   </cfif>
   <cfoutput><hr>Employee Add Complete</cfoutput>
  </cfcase>
</cfswitch>


StructKeyArray

Description

Finds the keys in a ColdFusion structure.

Returns

An array of keys; if structure does not exist, ColdFusion throws an exception.

Category

Structure functions

Function syntax

StructKeyArray(structure)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
structure | Structure from which to extract a list of keys

Usage

A structure’s keys are unordered.

Example

<!--- Shows StructKeyArray function to copy keys from a structure to an array.
Uses StructNew to create structure and fills its fields with the
information the user enters in the form fields. --->
<h3>StructKeyArray Example</h3>
<h3>Extracting the Keys from the Employee Structure</h3>
<!-- Create structure. Check whether Submit was pressed. If so, define fields
in employee structure with user entries on form. ----->
<cfset employee = StructNew()>
<cfif Isdefined("Form.Submit")>
    <cfif Form.Submit is "OK">
        <cfset employee.firstname = FORM.firstname>
        <cfset employee.lastname = FORM.lastname>
        <cfset employee.email = FORM.email>
        <cfset employee.phone = FORM.phone>
        <cfset employee.company = FORM.company>
    <cfelseIf Form.Submit is "Clear">
        <cfset rc = StructClear(employee)>
    </cfif>
</cfif>
<p> This example uses the StructNew function to create a structure called
"employee" that supplies employee info. Its fields are filled by
the form. After you enter employee information in structure, the
example uses StructKeyArray function to copy all of the keys from
the structure into an array. </p>
<hr size = "2" color = "#0000A0">
<form action = "structkeyarray.cfm">
<table cellspacing = "2" cellpadding = "2" border = "0">
    <tr>
    <td>First Name:</td>
    <td><input name = "firstname" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td>Last Name:</td>
    <td><input name = "lastname" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td>EMail</td>
    <td><input name = "email" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td>Phone:</td>
    <td><input name = "phone" type = "text"
        value = "" hspace = "20" maxlength = "20"></td>
    </tr>
    <tr>
    <td>Company:</td>
    <td><input name = "company" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td><input type = "submit" name = "submit"
        value = "OK"></td>
    <td><b>After you submit the FORM, scroll down to see the array.</b>
    </td>
    </tr>
</table>
</form>
<cfif NOT StructISEmpty(employee)>
    <hr size = "2" color = "#0000A0">
    <cfset keysToStruct = StructKeyArray(employee)>
    <cfloop index = "i" from = "1" to = "#ArrayLen(keysToStruct)#">
        <p><cfoutput>Key#i# is #keysToStruct[i]#</cfoutput></p>
        <p><cfoutput>Value#i# is #employee[keysToStruct[i]]#</cfoutput>
        </p>
    </cfloop>
</cfif>


StructKeyExists

Description

Determines whether a specific key is present in a structure.

Returns

True, if key is in structure; if structure does not exist, ColdFusion throws an exception.

Category

Decision functions, Structure functions

Function syntax

StructKeyExists(structure, "key")

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
structure | Name of structure to test
key | Key to test

Usage

This function can sometimes be used in place of the IsDefined function, when working with the URL and Form scopes, which are structures. The following pieces of code are equivalent:

cfif IsDefined("Form.JediMaster")>
<cfif StructKeyExists(Form,"JediMaster")>

A structure’s keys are unordered.

Example

<!--- This example shows the use of StructKeyExists. --->
<p>This file is similar to addemployee.cfm, which is called by StructNew,
StructClear, and StructDelete. To test, copy the &LT;CFELSEif&GT;
statement to the appropriate place in addemployee.cfm. It is a custom tag
to add employees. Employee information is passed through the employee
structure (the EMPINFO attribute). In UNIX, you must also add the Emp_ID.

<cfswitch expression = "#ThisTag.ExecutionMode#">
  <cfcase value = "start">
   <cfif StructIsEmpty(attributes.EMPINFO)>
    <cfoutput>Error. No employee data was passed.</cfoutput>
     <cfexit method = "ExitTag">
   <cfelseIf NOT StructKeyExists(attributes.EMPINFO, "department")>
    <cfscript>StructUpdate(attributes.EMPINFO, "department",
      "Unassigned");
        </cfscript>
    <cfexit method = "ExitTag">
           <cfelse>


StructKeyList

Description

Extracts keys from a ColdFusion structure.

Returns

A list of keys; if structure does not exist, ColdFusion throws an exception.

Category

Structure functions

Function syntax

StructKeyList(structure [, delimiter])

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
structure | Structure from which to extract a list of keys.
delimiter | Optional. Character that separates keys in list. The default value is comma.

Usage

A structure’s keys are unordered.

Example

<!--- This example shows how to use StructKeyList to list the keys
in a structure. It uses StructNew function to create structure
and fills it with information user enters in form fields. --->
<!--- This section creates structure and checks whether Submit has been pressed.
If so, code defines fields in the employee structure with what the
user entered in the form. --->
<cfset employee = StructNew()>
<cfif Isdefined("Form.Submit")>
    <cfif Form.Submit is "OK">
        <cfset employee.firstname = FORM.firstname>
        <cfset employee.lastname = FORM.lastname>
        <cfset employee.email = FORM.email>
        <cfset employee.phone = FORM.phone>
        <cfset employee.company = FORM.company>
    <cfelseIf Form.Submit is "Clear">
        <cfset rc = StructClear(employee)>
    </cfif>
</cfif>
<html>
<head>
    <title>StructKeyList Function</title>
</head>
<body>
<h3>StructKeyList Function</h3>
<h3>Listing the Keys in the Employees Structure</h3>
<p>This example uses StructNew function to create structure "employee" that
supplies employee information. The fields are filled with the
contents of the following form.</p>
<p>After you enter employee information into structure, example uses
<b>StructKeyList</b> function to list keys in structure.</p>
<p>This code does not show how to insert information into a database.
See cfquery for more information about database insertion.
<hr size = "2" color = "#0000A0">
<form action = "structkeylist.cfm">
<table cellspacing = "2" cellpadding = "2" border = "0">
    <tr>
    <td>First Name:</td>
    <td><input name = "firstname" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td>Last Name:</td>
    <td><input name = "lastname" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td>EMail</td>
    <td><input name = "email" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td>Phone:</td>
    <td><input name = "phone" type = "text"
        value = "" hspace = "20" maxlength = "20"></td>
    </tr>
    <tr>
    <td>Company:</td>
    <td><input name = "company" type = "text"
        value = "" hspace = "30" maxlength = "30"></td>
    </tr>
    <tr>
    <td><input type = "submit" name = "submit" 		value = "OK"></td>
    <td><b>After you submit form, scroll down 		to see the list.</b></td>
    </tr>
</table>
</form>
<cfif NOT StructISEmpty(employee)>
    <hr size = "2" color = "#0000A0">
    <cfset keysToStruct = StructKeyList(employee,"<li>")>
    <p>Here are the keys to the structure:</p>
    <ul>
    <li>	<cfoutput>#keysToStruct#</cfoutput>
    </ul>
    <p>If fields are correct, we can process new employee information.
If they are not correct, consider rewriting application.</p>
</cfif>


StructNew

Description

Creates a structure.

Returns

A structure.

Category

Structure functions

Function syntax

StructNew()

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

None

Example

<!--- Shows StructNew. Calls CF_ADDEMPLOYEE, which uses the |
addemployee.cfm file to add employee record to database. --->
<h1>Add New Employees</h1>
<cfparam name = "FORM.firstname" default = "">
<cfparam name = "FORM.lastname" default = "">
<cfparam name = "FORM.email" default = "">
<cfparam name = "FORM.phone" default = "">
<cfparam name = "FORM.department" default = "">
<cfif FORM.firstname EQ "">
 <p>Please fill out the form.
<cfelse>
    <cfoutput>
  <cfscript>
   employee = StructNew();
   StructInsert(employee, "firstname", FORM.firstname);
   StructInsert(employee, "lastname", FORM.lastname);
   StructInsert(employee, "email", FORM.email);
   StructInsert(employee, "phone", FORM.phone);
   StructInsert(employee, "department", FORM.department);
 </cfscript>
    <p>First name is #StructFind(employee, "firstname")#
    <p>Last name is #StructFind(employee, "lastname")#
    <p>EMail is #StructFind(employee, "email")#
    <p>Phone is #StructFind(employee, "phone")#
    <p>Department is #StructFind(employee, "department")#
    </cfoutput>
<!--- Call the custom tag that adds employees --->
 <CF_ADDEMPLOYEE EMPINFO = "#employee#">
</cfif>


StructSort

Description

Returns a sorted array of the top level keys in a structure. Sorts using alphabetic or numeric sorting, and can sort based on the values of any structure element.

Returns

An array of top-level key names (strings), sorted by the value of the specified subelement.

Category

Structure functions

Function syntax

StructSort(base, sortType, sortOrder, pathToSubElement)

See also

Structure functions; Structure functions in Using Arrays and Structures in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

base

A ColdFusion struct with one field (an associative array).

sortType

  • numeric
  • text: case-sensitive (all lowercase letters precede the first uppercase letter). Default.
  • textnocase

sortOrder
  • asc: ascending (a to z) sort order. Default.
  • desc: descending (z to a) sort order

pathToSubElement

String or a variable that contains one.

Path to apply to each top-level key, to reach element value by which to sort. The default value is nothing (top-level entries sorted by their own values).

Usage

The pathToSubElement string does not support array notation, and only supports substructures of structures.

This function does not sort or change the structure.

Example

<cfscript>
    salaries = StructNew() ;
    employees = StructNew() ;
    departments = StructNew() ;
    for ( i=1; i lt 6; i=i+1 )
    {
        salary = 120000 - i*10000 ;
        salaries["employee#i#"] = salary ;

        employee = StructNew() ;
        employee["salary"] = salary ;
        // employee.salary = salary ;
        employees["employee#i#"] = employee ;

        departments["department#i#"] = StructNew() ;
        departments["department#i#"].boss = employee ;
    }
</cfscript>

<cfoutput>
<p>list of employees based on the salary (text search): <br>
1) #ArrayToList( StructSort( salaries ) )#<br>
2) #ArrayToList( StructSort( salaries, "text", "ASC" ) )#<br>
3) #ArrayToList( StructSort( salaries, "textnocase", "ASC" ) )#<br>
4) #ArrayToList( StructSort( salaries, "text", "DESC" ) )#<br>
<p>list of employees based on the salary (numeric search): <br>
5) #ArrayToList( StructSort( salaries, "numeric", "ASC" ) )#<br>
6) #ArrayToList( StructSort( salaries, "numeric", "DESC" ) )#<br>
<p>list of employees based on the salary (subfield search): <br>
7) #ArrayToList( StructSort( employees, "numeric", "DESC", "salary" ) )#<br>
8) #ArrayToList( StructSort( employees, "text", "ASC",  "salary" ) )#<br>
<p>list of departments based on the salary (sub-sub-field search): <br>
9) #ArrayToList( StructSort( departments, "text", "ASC", "boss.salary" ) )#<br>
</cfoutput>

<!--- add an invalid element and test that it throws an error --->
<p><p>
<cfset employees[ "employee4" ] = StructNew()>
<cftry>
    <cfset temp = StructSort( employees, "text", "ASC", "salary" )>
    <cfoutput>We have a problem - this was supposed to throw an exception!<br>
</cfoutput>
<cfcatch type="any">
    <cfoutput>
        ERROR: <b>This error was expected!</b><br>
        #cfcatch.message# - #cfcatch.detail#<br>
    </cfoutput>
</cfcatch>
</cftry>


StructUpdate

Description

Updates a key with a value.

Returns

True, on successful execution; if the structure does not exist, ColdFusion throws an error.

Category

Structure functions

Function syntax

StructUpdate(structure, key, value)

See also

Structure functions; Modifying a ColdFusion XML object in Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Changed behavior: this function can be used on XML objects.

Parameters

Parameter | Description
structure | Structure to update
key | Key, the value of which to update
value | New value

Example

<!--- This example shows the use of StructUpdate. --->
<p>This file is similar to addemployee.cfm, which is called by StructNew,
StructClear, and StructDelete. To test this file, copy the
&LT;CFELSEIF&GT; statement to the appropriate place in
addemployee.cfm. It is an example of a custom tag used to add
employees. Employee information is passed through the employee
structure (the EMPINFO attribute). In UNIX, you must also add the Emp_ID.

<cfswitch expression = "#ThisTag.ExecutionMode#">
  <cfcase value = "start">
   <cfif StructIsEmpty(attributes.EMPINFO)>
    <cfoutput>Error. No employee data was passed.</cfoutput>
        <cfexit method = "ExitTag">
   <cfelseIf StructFind(attributes.EMPINFO, "department") EQ "">
    <cfscript>
     StructUpdate(attributes.EMPINFO, "department", "Unassigned");
    </cfscript>
    <cfexit method = "ExitTag">
            <cfelse>


Tan

Description

Calculates the tangent of an angle that is entered in radians.

Returns

A number; the tangent of an angle.

Category

Mathematical functions

Function syntax

Tan(number)

See also

Atn, Cos, ACos, Sin, ASin, Pi

Parameters

Parameter | Description
number | Angle, in radians, for which to calculate the tangent.

Usage

To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

Note: Because the function uses floating point arithmetic, it can return a very small number (such as 6.12323399574E-017) for angles that should produce 0 and can return a very large number (such as 1.63312393532E+016) for infinity or not a number. To test for a 0 value, check whether the value is less than 0.0000000000001. To test for an infinite value, check whether the value is more than 1E15.

Example

<h3>Tan Example</h3>
<!--- Calculate tangent if form has been submitted --->
<cfif IsDefined("FORM.tanNum")>
<!--- Make sure input is a number --->
    <cfif IsNumeric(#FORM.tanNum#)>
<!--- Convert degrees to radians, call the Tan function. --->
        <cfset tanValue=#Tan((Form.tanNum * PI()) / 180)#>
<!--- 0.0000000000001 is the function's precision limit.
     If absolute value of returned value is
     less, set result to 0 --->
        <cfif Abs(tanValue) LT 0.0000000000001>
           <cfset tanValue=0>
        </cfif>
        <cfoutput>
            Tan(#FORM.tanNum#) = #tanValue#<br><br>
        </cfoutput>
    <cfelse>
<!--- If input is not a number, show an error message --->
        <h4>You must enter a numeric angle in degrees.</h4>
    </cfif>
</cfif>
<form action = "#CGI.script_name#" method="post">
    Enter an angle in degrees to get its tangent:
    <br><input type = "Text" name = "tanNum" size = "15">
    <br><br>
    <input type = "Submit" name = "">&nbsp;&nbsp;
    <input type = "RESET"
</form>


TimeFormat

Description

Formats a time value using U.S. English time formatting conventions.

Returns

A custom-formatted time value. If no mask is specified, returns a time value using the hh:mm tt format. For international time formatting, see LSTimeFormat.

Category

Date and time functions, Display and formatting functions

Function syntax

TimeFormat(time [, mask ])

See also

CreateTime, Now, ParseDateTime, LSTimeFormat, DateFormat

History

ColdFusion MX 6.1: Added the mask character L or l to represent milliseconds.

ColdFusion MX:

  • Changed the way extra characters are processed: this function processes extra characters within the mask value differently than in earlier releases, as follows:
    • ColdFusion 5 and earlier: the function returns the time format and an apostrophe-delimited list of the extra characters. For example, TimeFormat(Now(), "hh:mm:ss dog") returns 8:17:23 d'o'g.
    • ColdFusion MX: the function returns the time format and the extra characters. For example, for the call above, it returns 8:17:23 dog.

    If the extra characters are single-quoted (for example, hh:mm:ss 'dog'), ColdFusion 5 and ColdFusion MX return the time format and the extra characters: 8:17:23 dog.

  • Added support for the following mask parameter options: short, medium, long, and full.

Parameters

Parameter

Description

time

A date/time value or string to convert

mask

Masking characters that determine the format:

  • h: hours; no leading zero for single-digit hours (12-hour clock)
  • hh: hours; leading zero for single-digit hours (12-hour clock)
  • H: hours; no leading zero for single-digit hours (24-hour clock)
  • HH: hours; leading zero for single-digit hours (24-hour clock)
  • m: minutes; no leading zero for single-digit minutes
  • mm: minutes; a leading zero for single-digit minutes
  • s: seconds; no leading zero for single-digit seconds
  • ss: seconds; leading zero for single-digit seconds
  • l or L: milliseconds. l gives 3 digits. L gives 2 digits.
  • t: one-character time marker string, such as A or P
  • tt: multiple-character time marker string, such as AM or PM
  • short: equivalent to h:mm tt
  • medium: equivalent to h:mm:ss tt
  • long: medium followed by three-letter time zone; as in, 2:34:55 PM EST
  • full: same as long

Usage

When passing a date/time value as a string, you must enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date/time object.

Database query results for date and time values can vary in sequence and formatting unless you use functions to format the results. To ensure that dates and times display with appropriate formatting, and that users of your ColdFusion application are not confused by dates and times displayed, Macromedia recommends that you use the DateFormat and TimeFormat functions to format date and time values from queries. For more information and examples, see TechNote 22183, "ColdFusion Server (5 and 4.5.x) with Oracle: Formatting Date and Time Query Results," at www.coldfusion.com/Support/KnowledgeBase/SearchForm.cfm.

Example

<cfset todayDate = #Now()#>
<body>
<h3>TimeFormat Example</h3>
<p>Today’s date is <cfoutput>#todayDate#</cfoutput>.
<p>Using Timeformat, we can display the value in different ways:
<cfoutput>
<ul>
    <li>#TimeFormat(todayDate)#
    <li>#TimeFormat(todayDate, "hh:mm:ss")#
    <li>#TimeFormat(todayDate, "hh:mm:sst")#
    <li>#TimeFormat(todayDate, "hh:mm:sstt")#
    <li>#TimeFormat(todayDate, "HH:mm:ss")#
</ul>
</cfoutput>
<p>To generate a standard ISO 8601 W3C Date and Time string like
1997-07-16T19:20, concatenate a DateFormat function, the character T, and a
TimeFormat function.
For example: dateformat(now(), "yyyy-mm-dd")#T#TimeFormat(now(), "HH:mm:ss")
produces:</p>
<cfoutput>#dateformat(now(), "yyyy-mm-dd")#T#TimeFormat(now(), "HH:mm:ss")#</cfoutput>
</body>


ToBase64

Description

Calculates the Base64 representation of a string or binary object. The Base64 format uses printable characters, allowing binary data to be sent in forms and e-mail, and stored in a database or file.

Returns

The Base64 representation of a string or binary object.

Category

Conversion functions, String functions

Function syntax

ToBase64(string or binary_object[, encoding])

See also

  • BinaryEncode for converstion of binary data to base64
  • cffile for information about loading and reading binary data
  • cfwddx for information about serializing and deserializing binary data
  • IsBinary and ToBinary for checking for binary data and converting a Base64 object to binary format

History

ColdFusion MX: Added the encoding parameter.

Parameters

Parameter

Description

string or binary_object

A string, the name of a string, or a binary object.

encoding

For a string, defines how characters are represented in a byte array. The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information on character encoding, see:
www.w3.org/International/O-charset.html.

The default value is the encoding of the page on which the function is called. See cfcontent. For a binary object, this parameter is ignored.

Usage

Macromedia recommends that you use the BinaryEncode function to convert binary data to Base64-encoded data in all new applications.

<h3>ToBase64 Example</h3>
<!--- Initialize data. ---->
<cfset charData = "">
<!--- Create string of ASCII characters (32-255); concatenate them --->
<cfloop index = "data" from = "32" to = "255">
    <cfset ch = chr(data)>
    <cfset charData = charData & ch>
</cfloop>
<p>
The following string is the concatenation of all characters (32 to 255)
from the ASCII table.<br>
<cfoutput>#charData#</cfoutput>
</p>
<!--- Create a Base64 representation of this string. ---->
<cfset data64 = toBase64(charData)>

<!----- Convert string to binary. ------->
<cfset binaryData = toBinary(data64)>
<!--- Convert binary back to Base64. ---->
<cfset another64 = toBase64(binaryData)>
<!---- Compare another64 with data64 to ensure that they are equal. ---->
<cfif another64 eq data64>
    <h3>Base64 representations are identical.</h3>
<cfelse>
    <h3>Conversion error.</h3>
</cfif>


ToBinary

Description

Calculates the binary representation of Base64-encoded data.

Returns

The binary representation of Base64-encoded data.

Category

Conversion functions, String functions

Function syntax

ToBinary(string_in_Base64 or binary_value)

See also

  • BinaryDecode for conversion of binary-encoded data, including Base64, to binary data
  • cffile for information about loading and reading binary data
  • cfwddx for information about serializing and deserializing binary data
  • IsBinary and ToBase64 for checking format and converting to Base64
  • Len for determining the length of a binary object
  • Binary data type and binary encoding in Using ColdFusion Variables in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
string_in_Base64 | A string in Base64 format to convert to binary.

Usage

Macromedia recommends that you use the BinaryDecode function to convert Base64 encoded data to binary data in all new applications.

If you pass a binary value to this function, it returns the input value.

Example

<h3>ToBinary Example</h3>
<!---- Initialize data. ---->
<cfset charData = "">
<!---- Create a string of ASCII characters (32-255); concatenate them. ---->
<cfloop index = "data" from = "32" to = "255">
    <cfset ch = chr(data)>
    <cfset charData = charData & ch>
</cfloop>
<p>The following string is the concatenation of all characters (32 to 255)
from the ASCII table.<br>
<cfoutput>#charData#</cfoutput></p>
<!----- Create a Base64 representation of this string. ----->
<cfset data64 = toBase64(charData)>

<!--- Convert string to binary. ---->
<cfset binaryData = toBinary(data64)>
<!--- Convert binary back to Base64. --->
<cfset another64 = toBase64(binaryData)>
<!---- Compare another64 with data64 to ensure that they are equal. ---->
<cfif another64 eq data64>
    <h3>Base64 representation of binary data is identical to the Base64
representation of string data.</h3>
<cfelse>
    <h3>Conversion error.</h3>
</cfif>


ToScript

Description

Creates a JavaScript or ActionScript expression that assigns the value of a ColdFusion variable to a JavaScript or ActionScript variable. This function can convert ColdFusion strings, numbers, arrays, structures, and queries to JavaScript or ActionScript syntax that defines equivalent variables and values.

Returns

A string that contains a JavaScript or ActionScript variable definition corresponding to the specified ColdFusion variable value.

Category

Conversion functions, Extensibility functions

Function syntax

ToScript(cfvar, javascriptvar, outputformat, ASFormat)

See also

cfwddx ; WDDX JavaScript Objects in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter

Description

cfvar

A ColdFusion variable. This can contain one of the following:

  • String
  • Number
  • Array
  • Structure
  • Query

javascriptvar

A string that specifies the name of the JavaScript variable that the ToScript function creates.

outputformat

Optional. A Boolean value that determines whether to create WDDX (JavaScript) or ActionScript style output for structures and queries:

  • True: creates WDDX-style output (default).
  • False: creates ActionScript-style output.

ASFormat

Optional. A Boolean value that specifies whether to use ActionScript shortcuts in the script:

  • True: creates new Objects and Arrays with ActionScript shortcuts: [] for New Array(), and {} for New Object. Using ActionScript shortcuts allows you to pass ActionScript into cfform attributes without triggering ActionScript validation.
  • False: does not use ActionScript shortcuts to create new Objects and new Arrays when generating the script. Instead, generates New Object() and New Array() in the script (default).

Usage

To use a ColdFusion variable in JavaScript or ActionScript, the ToScript function must be in a cfoutput region and be surrounded by number signs (#). For example, the following code uses the ToScript function to convert a ColdFusion variable to a JavaScript variable:

<cfset thisString="hello world">
<script type="text/javascript" language="JavaScript">
    <cfoutput>
        var #toScript(thisString, "jsVar")#;
    </cfoutput>
</script>

When ColdFusion runs this code, it sends the following to the client:

<script type="text/javascript" language="JavaScript">
    var jsVar = "hello world";
</script>

An HTML script tag must enclose the JavaScript code. The cfoutput tag does not need to be inside the script block; it can also surround the block.

WDDX-style output generates JavaScript code that creates a WDDXRecordset object, where the key of each record set entry is a column name, and the value of the recordlist entry is an array of the corresponding query column entries, as follows:

WDDXQuery = new WddxRecordset();
col0 = new Array();
col0[0] = "John";
col0[1] = "John";
WDDXQuery["firstname"] = col0;
col0 = null;
col1 = new Array();
col1[0] = "Lund";
col1[1] = "Allen";
WDDXQuery["lastname"] = col1;
col1 = null;

To use WDDX-style output, you must first load the cf_webroot/CFIDE/scripts/wddx.js script, which defines JavaScript WDDX objects, as in the following line:

<script type="text/javascript" src="/CFIDE/scripts/wddx.js script"> </script>

For more information on WDDX in JavaScript, see WDDX JavaScript Objects.

ActionScript-style output generates code that creates an array of objects, where the array is indexed by row number, and the objects consist of column name - column value pairs, as follows:

    ActionScriptQuery = new Array();
ActionScriptQuery[0] = new Object();
ActionScriptQuery[0]['firstname'] = "John";
ActionScriptQuery[0]['lastname'] = "Lund";
ActionScriptQuery[1] = new Object();
ActionScriptQuery[1]['firstname'] = "John";
ActionScriptQuery[1]['lastname'] = "Allen";

An ActionScript-style array does not require you to include the wddx.js file, and creates a variable that you can use in ActionScript on a Flash format form, for example, in an onChange attribute.

If the outputformat parameter is False, setting ASFormat to True causes ToScript to use the ActionScript shortcut [] in place of New Array() and the shortcut {} in place of New Object(). Using these shortcuts allows you to pass ActionScript into cfform attributes without triggering ActionScript validation. If ASFormat is False, ToScript generates New Array() and New Object() in the script.

Example

The following example shows the results of converting a ColdFusion string, array, and query object to JavaScript variables. It also uses the string and array in JavaScript code.

<h2>ToScript</h2>

<h3>Converting a string variable</h3>
<cfset thisString = "This is a string">
<cfoutput>
    <b>The thisString variable in ColdFusion</b><br>
    #thisString#<br>
    <br>
    <strong>The output of ToScript(thisString, "jsVar")</strong><br>
    #ToScript(thisString, "jsVar")#<br>
    <br>
    <strong>In a JavaScript script, convert thisString Variable to JavaScript
     and output the resulting variable:</strong><br>
    <script type="text/javascript" language="JavaScript">
        var #ToScript(thisString, "jsVar")#;
        document.write("jsVar in JavaScript is: " + jsVar);
    </script>
</cfoutput>

<h3>Converting an array</h3>
<!--- Create and populate a one-dimensional array --->
<cfset myArray=ArrayNew(1)>
<cfloop index="i" from="1" to="4">
            <cfset myArray[i]="This is array element" & i>
</cfloop>

<cfoutput>
<b>The ColdFusion myArray Array</b><br>
<!--- Write the contents of the myArray variable in ColdFusion --->
    <cfloop index="i" from="1" to="#arrayLen(myArray)#">
        myArry[#i#]: #myArray[i]#<br>
    </cfloop>
    <br>
    <strong>The output of ToScript(myArray, "jsArray")</strong><br>
    #toScript(myArray, "jsArray")#<br>
    <br>
    <strong>In JavaScript, convert myArray to a JavaScript variable and write it's contents</strong><br>
    <script type="text/javascript" language="JavaScript">
        var #ToScript(myArray, "jsArray")#;
        for (i in jsArray)
        {
            document.write("myArray[" + i + "]: " + jsArray[i] + "<br>");
        }
    </script>
<br>
<h3>Converting a query</h3>
This section converts the following query object to both WDDX format
and ActionScript type Javascript objects.<br>

<!--- Query a database --->
<cfquery name="thisQuery" datasource="cfdocexamples">
    SELECT FirstName,LastName
    FROM employee
    WHERE FirstName = 'John'
</cfquery>
<br>
The Query in ColdFusion
<cftable query="thisQuery" headerlines="1" colheaders>
    <cfcol align="left" width="9" header="<b>FirstName</b>" text="#FirstName#">
    <cfcol align="left" width="9" header="<b>LastName</b>" text="#LastName#">
</cftable>

<strong>JavaScript generated by ToScript(thisQuery, "WDDXQuery"):</strong><br>
    #toScript(thisQuery, "WDDXQuery")#;<br>
    <br>
<strong>JavaScript generated by ToScript(thisQuery, "ActionScriptQuery",
        False):</strong><br>
    #toScript(thisQuery, "ActionScriptQuery", False)#<br>
    <br>
<!--- Convert to both WDDX format and ActionScript format --->
<script type="text/javascript" language="JavaScript">
    #ToScript(thisQuery, "WDDXQuery")#;
    #ToScript(thisQuery, "ActionScriptQuery", False)#;
</script>
<!--- For brevity, this example does not use JavaScript query variables --->
</cfoutput>


ToString

Description

Converts a value to a string.

Returns

A string.

Category

Conversion functions, String functions

Function syntax

ToString(value[, encoding])

See also

ToBase64, ToBinary, CharsetEncode; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX:

  • Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535. (ColdFusion 5 and earlier releases supported ASCII values 1–255.)
  • Added the encoding parameter.
  • Added ability to convert an XML document object to a string.

Parameters

Parameter

Description

value

Value to convert to a string; can be a simple value such as an integer, a binary object, or an XML document object.

encoding

The character encoding (character set) of the string. Optional for binary data, Generates an error if used for a simple value or XML document object.

The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information on character encoding, see:
www.w3.org/International/O-charset.html.

The default value is the encoding of the page on which the function is called. See cfcontent.

Usage

This function can convert simple values and binary values that do not contain Byte zero. If this function cannot convert a value, it throws an exception. This function can also convert an XML document object to a string XML representation.

Macromedia recommends that you use the CharsetEncode function to convert binary data to a string.

Example

<h3>ToString Example</h3>
<!---- Initialize data. ------>
<cfset charData = "">
<!----- Create string of ASCII characters (32-255) and concatenate them. ---->
<cfloop index = "data" from = "32" to = "255">
    <cfset ch = chr(data)>
    <cfset charData = charData & ch>
</cfloop>
<p>The following string is the concatenation of characters (32 to 255)
from the ASCII table.<br>
<cfoutput>#charData#</cfoutput></p>

<!------ Create a Base64 representation of this string. ---->
<cfset data64 = toBase64(#charData#)>
<p>
The following string is the Base64 representation of the string.<br>
<cfoutput>#data64#</cfoutput></p>
<!---- Create a binary representation of Base64 data. --->
<cfset dataBinary = toBinary(data64)>

<!---- Create the string representation of the binary data. ----->
<cfset dataString = ToString(dataBinary)>
<p>The following is the string representation of the binary data.<br>
<cfoutput>#dataString#</cfoutput></p>


Trim

Description

Removes leading and trailing spaces from a string.

Returns

A copy of string, after removing leading and trailing spaces.

Category

String functions

Function syntax

Trim(string)

See also

LTrim, RTrim

Parameters

Parameter | Description
string | A string or a variable that contains one

Example

<h3>Trim Example</h3>
<cfif IsDefined("FORM.myText")>
    <cfoutput>
        <pre>
            Your string:	"#FORM.myText#"
            Your string:	"#Trim(FORM.myText)#"
            (trimmed on both sides)
        </pre>
    </cfoutput>
</cfif>
<form method = "post" action = "trim.cfm">
<p>Type in some text, and it will be modified by trim to remove leading
spaces from the left and right
<p><input type = "Text" name = "myText" value = "   TEST   ">
<p><input type = "Submit" name = "">
</form>


UCase

Description

Converts the alphabetic characters in a string to uppercase.

Returns

A copy of a string, converted to uppercase.

Category

String functions

Function syntax

UCase(string)

See also

LCase

Parameters

Parameter | Description
string | A string or a variable that contains one

Example

<h3>UCase Example</h3>

<cfif IsDefined("FORM.sampleText")>
    <cfif FORM.sampleText is not "">
        <p>Your text, <cfoutput>#FORM.sampleText#</cfoutput>,
returned in uppercase is <cfoutput>#UCase(FORM.sampleText)#</cfoutput>.
    <cfelse>
        <p>Please enter some text.
    </cfif>
</cfif>

<form action = "ucase.cfm">
<p>Enter your sample text, and press "submit" to see the text returned in
uppercase:
<p><input type = "Text" name = "SampleText" value = "sample">

<input type = "Submit" name = "" value = "submit">
</form>


URLDecode

Description

Decodes a URL-encoded string.

Returns

A copy of a string, decoded.

Category

Conversion functions, Other functions, String functions

Function syntax

URLDecode(urlEncodedString[, charset])

See also

URLEncodedFormat; Tags and functions for globalizing in Developing Globalized Applications in ColdFusion MX Developer’s Guide

ColdFusion MX 6.1: Changed the default charset: the default charset is the character encoding of the URL scope.

ColdFusion MX:

  • Changed Unicode support: ColdFusion supports the Java UCS-2 representation of Unicode character values 0–65535. (Earlier releases supported ASCII values.)
  • Added the charset parameter.

Parameters

Parameter

Description

urlEncodedString

URL-encoded string or a variable that contains one.

charset

The character encoding in which the URL is encoded. Optional.

The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information on character encoding, see:
www.w3.org/International/O-charset.html.

The default value is the character encoding of the URL scope. See SetEncoding.

Usage

URL encoding formats some characters with a percent sign and the two-character hexadecimal representation of the character. For example, a character whose code is 129 is encoded as %81. A space is encoded with a plus sign.

Query strings in HTTP are always URL-encoded.

Example

This example creates, encodes, and decodes a string that contains ASCII character codes:

<cfscript>
    // Build string
    s = "";
    for (c = 1; c lte 256; c = c + 1)
    {
        s = s & chr(c);
    }
    // Encode string and display result
    enc = URLEncodedFormat(s);
    WriteOutput("Encoded string is: '#enc#'.<br>");
    // Decode and compare result with original
    dec = URLDecode(enc);
    if (dec neq s)
    {
        WriteOutput("Decoded is not the same as encoded.");
    }
    else
    {
        WriteOutput("All's quiet on the Western front.");
    }
</cfscript>


URLEncodedFormat

Description

Generates a URL-encoded string. For example, it replaces spaces with %20, and non-alphanumeric characters with equivalent hexadecimal escape sequences. Passes arbitrary strings within a URL (ColdFusion automatically decodes URL parameters that are passed to a page).

Returns

A copy of a string, URL-encoded.

Category

Conversion functions, Other functions, String functions

Function syntax

URLEncodedFormat(string [, charset ])

See also

URLDecode; Tags and functions for globalizing in Developing Globalized Applications in ColdFusion MX Developer’s Guide

History

ColdFusion MX 6.1: Changed the default encoding to be the response character encoding.

ColdFusion MX: Added the charset parameter.

Parameters

Parameter

Description

string

A string or a variable that contains one

charset

The character encoding in which the string is encoded. Optional.

The following list includes commonly used values:

  • utf-8
  • iso-8859-1
  • windows-1252
  • us-ascii
  • shift_jis
  • iso-2022-jp
  • euc-jp
  • euc-kr
  • big5
  • euc-cn
  • utf-16

For more information on character encoding, see:
www.w3.org/International/O-charset.html.

The default value is the character encoding of the response. See cfcontent.

Usage

URL encoding formats some characters with a percent sign and the two-character hexadecimal representation of the character. For example, a character whose code is 129 is encoded as %81. A space is encoded with a plus sign.

Query strings in HTTP are always URL-encoded.

Example

<h3>URLEncodedFormat Example</h3>
<cfif IsDefined("url.myExample")>
    <p>The url variable url.myExample was passed from the previous link ...
    its value is:
    <br><b>"<cfoutput>#url.myExample#</cfoutput>"</b>
</cfif>
<p>This function returns a URL encoded string.
<cfset s = "My url-encoded string has special characters & other stuff">
<p> <A HREF = "urlencodedformat.cfm?myExample=<cfoutput>#URLEncodedFormat(s)#
</cfoutput>">Click me</A>


URLSessionFormat

Description

Depending on whether a client computer accepts cookies, this function does the following:

  • If the client does not accept cookies: automatically appends all required client identification information to a URL
  • If the client accepts cookies: does not append information

This function automatically determines which identifiers are required, and sends only the required information. It provides a more secure and robust method for supporting client identification than manually encoding the information in each URL, because it sends only required information, when it is required, and it is easier to code.

Returns

A URL; if cookies are disabled for the browser, client and session data are appended.

Category

Other functions; Maintaining client identity in Using Persistent Data and Locking in ColdFusion MX Developer’s Guide

Function syntax

URLSessionFormat(request_URL)

Parameters

Parameter | Description
request_URL | URL of a ColdFusion page

Usage

In the following example, the cfform tag posts a request to another page and sends the client identification, if required. If cookie support is detected, the function returns the following:

myactionpage.cfm

If the detected cookie is not turned on, or cookie support cannot be reliably detected, the function return value is as follows:

myactionpage.cfm?jsessionid=xxxx;cfid=xxxx&cftoken=xxxxxxxx

Example

<cfform
method="Post"
action="#URLSessionFormat("MyActionPage.cfm")#">
</cfform>


Val

Description

Converts numeric characters that occur at the beginning of a string to a number.

Returns

A number. If conversion fails, returns zero.

Category

Conversion functions, String functions

Function syntax

Val(string)

See also

IsNumeric

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

This function works as follows:

  • If TestValue = "234A56?7'", Val(TestValue) returns 234.
  • If TestValue = "234'5678'9?'", Val(TestValue) returns 234.
  • If TestValue = "BG234", Val(TestValue) returns the value 0, (not an error).
  • If TestValue = "0", Val(TestValue) returns the value 0, (not an error).

Example

<h3>Val Example</h3>
<cfif IsDefined("FORM.theTestValue")>
    <cfif Val(FORM.theTestValue) is not 0>
        <h3>The string <cfoutput>#DE(FORM.theTestValue)#</cfoutput>
can be converted to a number:
        <cfoutput>#Val(FORM.theTestValue)#</cfoutput></h3>
    <cfelse>
        <h3>The beginning of the string <cfoutput>#DE(FORM.theTestValue)#
         </cfoutput> cannot be converted to a number</h3>
    </cfif>
</cfif>
<form action = "val.cfm">
<p>Enter a string, and determine whether its beginning can be evaluated
to a numeric value.
<p>
<input type = "Text"
    name = "TheTestValue"
    value = "123Boy">
<input type = "Submit"
    value = "Is the beginning numeric?"
    name = "">
</form>


ValueList

Description

Inserts a delimiter between each value in an executed query. ColdFusion does not evaluate the arguments.

Returns

A delimited list of the values of each record returned from an executed query.

Category

List functions, Query functions

Function syntax

ValueList(query.column [, delimiter ])

See also

QuotedValueList

Parameters

Parameter | Description
query.column | Name of an executed query and column. Separate query name and column name with a period.
delimiter | A delimiter character to separate column data items. The default value is comma (,).

Example

<h3>ValueList Example</h3>

<!--- use the contents of a query to create another dynamically --->
<cfquery name = "GetDepartments" datasource = "cfdocexamples">
SELECT Dept_ID FROM Departments
WHERE Dept_ID IN ('BIOL')
</cfquery>

<cfquery name = "GetCourseList" datasource = "cfdocexamples">
SELECT *
FROM CourseList
WHERE Dept_ID IN ('#GetDepartments.Dept_ID#')
</cfquery>

Value list of all BIOL Course ID's using (--) as the delimiter:<br>
<cfoutput>
#ValueList(GetCourseList.Course_ID,"--")#<br>
</cfoutput>

Value list of all BIOL Course Numbers using (;) as the delimiter:<br>
<cfoutput>
#ValueList(GetCourseList.CorNumber,";")#<br>
</cfoutput>


Week

Description

From a date/time object, determines the week number within the year.

Returns

An integer in the range 1–53; the ordinal of the week, within the year.

Category

Date and time functions

Function syntax

Week(date)

See also

DatePart

Parameters

Parameter | Description
date | A date/time object in the range 100 AD–9999 AD.

Usage

When passing date as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date.

Example

<h3>Week Example</h3>
<cfif IsDefined("FORM.year")>
More information about your date:
<cfset yourDate = CreateDate(FORM.year, FORM.month, FORM.day)>
<cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayOfWeekAsString(DayOfWeek(yourDate))#, day
         #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(YourDate)# in the month of
         #MonthAsString(Month(yourDate))#, which has #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(yourDate)# (day
         #DayOfYear(yourDate)# of #DaysInYear(yourDate)#). <br>
    <cfif IsLeapYear(Year(yourDate))>This is a leap year
        <cfelse>This is not a leap year
    </cfif>
</cfoutput>
</cfif>


Wrap

Description

Wraps text so that each line has a specified maximum number of characters.

Returns

String containing the wrapped text.

Category

String functions

Function syntax

Wrap(string, limit[, strip])

See also

cfmail

History

ColdFusion MX 6.1: Added this function

Parameters

Parameter | Description
string | String or variable that contains one. The text to wrap.
limit | Positive integer maximum number of characters to allow on a line.
strip | Boolean specifying whether to remove all existing newline and carriage return characters in the input string with spaces before wrapping the text. The default value is False.

Usage

Inserts line break at the location of the first white space character (such as a space, tab, or new line) before the specified limit on a line. If a line has no whitespace characters before the limit, inserts a line break at the limit. Uses the operating-system specific line break: newline for UNIX, carriage return and newline on Windows.

If you specify the strip parameter, all existing line breaks are removed, so any paragraph formatting is lost.

Use this function to limit the length of text lines, such as text to be included in a mail message. The cfmail and cfmailpart tag wraptext attributes use this function

Example

<h3>Wrap Example</h3>
<cfset inputText="This is an example of a text message that we want to wrap. It is rather long and needs to be broken into shorter lines.">
<cfoutput>#Wrap(inputText, 59)#</cfoutput>


WriteOutput

Description

Appends text to the page-output stream.

This function writes to the page-output stream regardless of conditions established by the cfsetting tag.

Category

Other functions, System functions

Function syntax

WriteOutput(string)

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

Within the cfquery and cfmail tags, this function does not output to the current page; it writes to the current SQL statement or mail text. Do not use WriteOutput within cfquery and cfmail.

Although you can call this function anywhere within a page, it is most useful inside a cfscript block.

Example

...
<cfscript>
  employee = StructNew();
  StructInsert(employee, "firstname", FORM.firstname);
  StructInsert(employee, "lastname", FORM.lastname);
  StructInsert(employee, "email", FORM.email);
  StructInsert(employee, "phone", FORM.phone);
  StructInsert(employee, "department", FORM.department);
  WriteOutput("About to add " & FORM.firstname & " " & FORM.lastname);
</cfscript>


XmlChildPos

Description

Gets the position of a child element within an XML document object.

Returns

The position, in an XmlChildren array, of the Nth child that has the specified name.

Category

XML functions

Function syntax

XmlChildPos(elem, childName, N)

See also

IsXmlElem, XmlElemNew, XmlSearch, XmlTransform; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
elem | XML element within which to search.
childName | XML child element for which to search. Must be an immediate child of the elem parameter.
N | Index of XMLchild element for which to search.

Usage

You can use the returned index in the ArrayInsertAt and ArrayDeleteAt functions to change XML document objects. If the specified child is not found, the function returns -1.

Example

The following example searches XML document element, xmlobject.employee.name[1], for its second Status element child and uses the position in an ArrayDeleteAt function to remove the element:

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<employee>
    <!-- A list of employees -->
    <name EmpType="Regular">
        <first>Almanzo</first>
        <last>Wilder</last>
        <Status>Medical Absence</Status>
        <Status>Extended Leave</Status>
    </name>
    <name EmpType="Contract">
        <first>Laura</first>
        <last>Ingalls</last>
    </name>
</employee>
</cfxml>

<!--- Find the second Status child of the first employee.name element --->
<cfscript>
elempos=XMLChildPos(xmlobject.employee.name[1], "Status", 2);
ArrayDeleteAt(xmlobject.employee.name[1].XmlChildren, elempos);
</cfscript>

<!--- Dump the resulting document object to confirm the deletion --->
<cfdump var="#xmlobject#">


XmlElemNew

Description

Creates an XML document object element.

Returns

An XML document object element.

Category

XML functions

Function syntax

XmlElemNew(xmlObj[, namespace], childName)

See also

cfxml, IsXmlElem, XmlChildPos, XmlFormat, XmlNew, XmlParse; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the namespace parameter.

ColdFusion MX: Added this function.

Parameters

Parameter | Description
xmlObj | Name of the XML document object in which you are creating the element
namespace | (Optional) URI of the namespace to which this element belongs
childName | Name of the element to create

Usage

The function’s return variable specifies the location of the new element in the document object. It must specify a valid location in the document object identified by the xmlObj parameter. The following statements show this use:

MyDoc.MyRoot.XmlChildren[2] = XmlElemNew(MyDoc,"childNode");
ArrayAppend(MyDoc.MyRoot.XmlChildren, XmlElemNew(MyDoc,"childNode"));

If you do not specify a namespace URI and use a namespace prefix in the childName parameter, ColdFusion checks to see if a namespace URI has already been specified for the prefix, and if so, uses that namespace.

Example

The following example creates and displays a ColdFusion document object:

<cfscript>
    MyDoc = XmlNew();
    MyDoc.xmlRoot = XmlElemNew(MyDoc,"MyRoot");
    if (testVar IS TRUE)
        MyDoc.MyRoot.XmlText = "The value of testVar is True.";
    else
        MyDoc.MyRoot.XmlText = "The value of testVar is False.";
    for (i = 1; i LTE 4; i = i + 1)
        {
        MyDoc.MyRoot.XmlChildren[i] = XmlElemNew(MyDoc,"childNode");
        MyDoc.MyRoot.XmlChildren[i].XmlText = "This is Child node " & i &".";
        }
</cfscript>
<cfdump var=#MyDoc#>


XmlFormat

Description

Escapes special XML characters in a string so that the string can be used as text in XML.

Returns

A copy of the string parameter that is safe to use as text in XML.

Category

String functions, XML functions

Function syntax

XmlFormat(string)

See also

cfxml, XmlNew, XmlParse, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter | Description
string | A string or a variable that contains one

Usage

This function escapes characters as follows:

Text character | Escaped representation
Greater than symbol (>) | &gt;
Less than symbol (<) | &lt;
Single-quotation mark (') | &apos;
Double-quotation mark (") | &quot;
Ampersand symbol (&) | &amp;
Carriage return (but not line feed) | Removed from the text.
High ASCII characters in the range 128-255. | Replaced by unicode escape sequence; for example, É (capital E with an Acute symbol) is replaced by &#xc9;.

Example

The following example shows how XmlFormat escapes special XML characters. Use the View Source command in the browser to see the results. ColdFusion interprets the "" in the second text string as representing a single-quotation mark in text before it applies the XmlFormat function.

<?xml version = "1.0"?>
<cfoutput>
<someXML>
    <someElement someAttribute="#XmlFormat("'a quoted value'")#">
        #XmlFormat("Body of element with <, >, "" and & goes here.")#
    </someElement>
</someXML>
</cfoutput>


XmlGetNodeType

Description

Determines the type of an XML document object node.

Returns

A string identifying the XML node type. The following values are valid:

ATTRIBUTE_NODE | CDATA_SECTION_NODE
COMMENT_NODE | DOCUMENT_FRAGMENT_NODE
DOCUMENT_NODE | DOCUMENT_TYPE_NODE
ELEMENT_NODE | ENTITY_NODE
ENTITY_REFERENCE_NODE | NOTATION_NODE
PROCESSING_INSTRUCTION_NODE | TEXT_NODE

If the argument is not a document object node, the function generates an error.

Category

XML functions

Function syntax

XmlGetNodeType(xmlNode)

See also

IsXmlAttribute, IsXmlDoc, IsXmlElem, IsXmlNode, IsXmlRoot, XmlChildPos, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter | Description
xmlNode | An XML DOM object node

Usage

The XmlGetNodeType function can determine the types of the nodes returned by the XmlSearch function, or the types of the entries in an element’s XmlNodes array.

Example

The following example checks the node types of various parts of an XML document object:

<!--- Create an XML document object --->
<cfxml variable="xmlobject">
<?xml version="1.0" encoding="UTF-8"?>
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <!-- This item is coded to show several node types -->
            <![CDATA["Our Best" hammer & chisel set!!!]]> Imported from France
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
    </items>
</order>
</cfxml>

<!--- Display the node types --->
<cfoutput>
  <h3>Node Types</h3>
  xmlobject: #XMLGetNodeType(xmlobject)#<br>
  xmlobject.order: #XMLGetNodeType(xmlobject.order)#<br>
  <br>
  Now check the types of all the nodes in the xmlobject.order.items.item
    element’s XmlNodes array.<br>
    Note the many apparently empty Text nodes generated by whitespace characters in the XML text source.<br><br>
  <cfset descnodes=xmlobject.order.items.item.XmlNodes>
<cfloop from="1" to="#ArrayLen(descnodes)#" index="i">
    #i# Node type is: #XMLGetNodeType(descnodes[i])#<br>
    #i# Node name is: #descnodes[i].XmlName#<br>
    <cfif (descnodes[#i#].XmlValue NEQ "")>
        #i# Node value is: #descnodes[i].XmlValue#<br>
    </cfif>
    <br>
  </cfloop>
</cfoutput>


XmlNew

Description

Creates an XML document object.

Returns

An empty XML document object.

Category

XML functions

Function syntax

XmlNew([caseSensitive])

See also

cfxml, IsXmlDoc, ToString, XmlFormat, XmlParse, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX: Added this function.

Parameters

Parameter

Description

caseSensitive

Determines how ColdFusion processes the case of XML document object component identifiers:

  • True: maintains case
  • False: ColdFusion ignores case. Default.

Usage

An XML document object is represented in ColdFusion as a structure.

The caseSensitive parameter value determines whether identifiers whose characters are of varying case, but are otherwise the same, refer to different components; for example:

  • If True, the element or attribute names "name" and "NAME" refer to different elements or attributes.
  • If False, these names refer to the same elements or attributes.

If your XML object is case sensitive, you cannot use dot notation to reference an element or attribute name. Use the name in associative array (bracket) notation, or a reference that does not use the case-sensitive name (such as xmlChildren[1]) instead. In the following code, the first line will work with a case-sensitive XML object. The second and third lines cause errors:

MyDoc.xmlRoot.XmlAttributes["Version"] = "12b";
MyDoc.xmlRoot.XmlAttributes.Version = "12b";
MyDoc.MyRoot.XmlAttributes["Version"] = "12b";

To convert an XML document object into a string, use the ToString function.

Example

The following example creates and displays a ColdFusion document object:

<cfset testVar = True>
<cfscript>
    MyDoc = XmlNew();
    MyDoc.xmlRoot = XmlElemNew(MyDoc,"MyRoot");
    if (testVar IS TRUE)
        MyDoc.MyRoot.XmlText = "The value of testVar is True.";
    else
        MyDoc.MyRoot.XmlText = "The value of testVar is False.";
    for (i = 1; i LTE 4; i = i + 1)	{
        MyDoc.MyRoot.XmlChildren[i] = XmlElemNew(MyDoc,"childNode");
        MyDoc.MyRoot.XmlChildren[i].XmlText = "This is Child node " & i &".";
        }
</cfscript>
<cfdump var=#MyDoc#>


XmlParse

Description

Converts XML text into an XML document object.

Returns

An XML document object.

Category

Conversion functions, XML functions

Function syntax

XmlParse(xmlText [[, caseSensitive ], validator])

See also

cfxml, IsXML, ToString, XmlFormat, XmlNew, XmlSearch, XmlTransform, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7:

  • Added the validator parameter.
  • Added support for filenames and URLs in the xmlText parameter.
  • Added support for relative URLs and path names.

ColdFusion MX: Added this function.

Parameters

Parameter

Description

xmlText

Any of the following:

  • A string containing XML text.
  • The name of an XML file.
  • The URL of an XML file; valid protocol identifiers include http, https, ftp, and file.

caseSensitive
  • Yes: maintains the case of document elements and attributes.
  • No: Default

validator

Any of the following:

  • The name of a Document Type Definition (DTD) or XML Schema file.
  • The URL of a DTD or Schema file; valid protocol identifiers include http, https, ftp, and file.
  • A string representation of a DTD or Schema.
  • An empty string; in this case, the XML file must contain an embedded DTD or Schema identifier, which is used to validate the document.

Usage

If you specify a relative URL or path name in a parameter, ColdFusion uses the directory (or, for URLs, the logical directory) that contains the current ColdFusion page as the path root.

The caseSensitive parameter value determines whether identifiers whose characters are of varying case, but are otherwise the same, refer to different components; for example:

  • If true, the element or attribute names "name" and "NAME" refer to different elements or attributes.
  • If false, these names refer to the same elements or attributes.

If your XML object is case sensitive, you cannot use dot notation to reference an element or attribute name. Use the name in associative array (bracket) notation, or a reference that does not use the case-sensitive name (such as xmlChildren[1]) instead. In the following code, the first line will work with a case-sensitive XML object. The second and third lines cause errors:

MyDoc.xmlRoot.XmlAttributes["Version"] = "12b";
MyDoc.xmlRoot.XmlAttributes.Version = "12b";
MyDoc.MyRoot.XmlAttributes["Version"] = "12b";

The optional validator parameter specifies a DTD or Schema to use to validate the document. If the parser encounters a validation error, ColdFusion generates an error and stops parsing the document. You must specify a validator parameter to make the XmlParse function validate your document. If you do not specify a validator parameter, and the XML file specifies a DTD or Schema, ColdFusion ignores the DTD or Schema. If you specify a validator parameter, you must also specify a caseSensitive parameter.

If you do not specify a validator parameter, the xmlText parameter can specify a well-formed XML fragment, and does not have to specify a complete document.

Note: To convert an XML document object back into a string, use the ToString function.

Example

The following example has three parts: an XML file, a DTD file, and a CFML page that parses the XML file and uses the DTD for validation. The CFML file displays the returned XML document object. To show the results of invalid XML, modify the bmenuD.xml.

Note: The DTD used in the following example represents the same XML structure as the Schema used in the XmlValidate example.

The custorder.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE order SYSTEM "C:\CFusionMX7\wwwroot\examples\custorder.dtd">
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <name>	Deluxe Carpenter&apos;s Hammer</name>
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
        <item id="54">
            <name>	36&quot; Plastic Rake</name>
            <quantity>2</quantity>
            <unitprice>6.95</unitprice>
        </item>
        <item id="68">
            <name>	Standard paint thinner</name>
            <quantity>3</quantity>
            <unitprice>8.95</unitprice>
        </item>
    </items>
</order>

The custorder.dtd file is as follows:

<!ELEMENT order (customer, items)>
<!ATTLIST order
    id CDATA #REQUIRED>
<!ELEMENT customer EMPTY>
<!ATTLIST customer
    firstname CDATA #REQUIRED
    lastname CDATA #REQUIRED
    accountNum CDATA #REQUIRED>
<!ELEMENT items (item+)>
<!ELEMENT item (name, quantity, unitprice)>
<!ATTLIST item
    id CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT quantity (#PCDATA)>
<!ELEMENT unitprice (#PCDATA)>

The CFML file is as follows. It uses a filename for the XML file and a URL for the DTD. Note that the XML and URL paths must be absolute.

<cfset
myDoc=XMLParse("C:\CFusionMX7\wwwroot\examples\custorder.xml",
false, "http://localhost:8500/examples/custorder.dtd")>
Dump of myDoc XML document object<br>
<cfdump var="#myDoc#">


XmlSearch

Description

Uses an XPath language expression to search an XML document object.

Returns

An array of XML object nodes that match the search criteria.

Category

XML functions

Function syntax

XmlSearch(xmlDoc, xPathString)

See also

cfxml, IsXML, XmlChildPos, XmlParse, XmlTransform; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added support for attribute searches.

ColdFusion MX: Added this function.

Parameters

Parameter | Description
xmlDoc | XML document object
xPathString | XPath expression

Usage

The XmlSearch function does not support complete XPath syntax. It only supports XPath expressions that return one or more XML nodes and attribute searches. XPath expressions that return any other type of value, such as a string, number, or Boolean, generate errors.

XPath is specified by the World Wide Web Consortium (W3C). For detailed information on XPath, including XPath expression syntax, see the W3C website at www.w3.org/TR/xpath.

Example

The following example extracts the elements named last, which contain employee last names, from an XML file, and displays the names.

The employeesimple.xml file contains the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<employee>
<!-- A list of employees -->
 <name EmpType="Regular">
  <first>Almanzo</first>
  <last>Wilder</last>
 </name>
 <name EmpType="Contract">
  <first>Laura</first>
  <last>Ingalls</last>
 </name>
</employee>

The CFML file contains the following lines:

<cfscript>
    myxmldoc = XmlParse("C:\CFusionMX7\wwwroot\examples\employeesimple.xml");
    selectedElements = XmlSearch(myxmldoc, "/employee/name/last");
    for (i = 1; i LTE ArrayLen(selectedElements); i = i + 1)
        writeoutput(selectedElements[i].XmlText & "<br>");
</cfscript>


XmlTransform

Description

Applies an Extensible Stylesheet Language Transformation (XSLT) to XML. The XML can be in string format or an XML document object.

Returns

A string containing the results of applying the XSLT to the XML.

Category

Conversion functions, XML functions

Function syntax

XmlTransform(xml, xsl[, parameters])

See also

cfxml, XmlFormat, XmlNew, XmlParse, XmlSearch, XmlValidate; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added the parameters parameter and the ability to use a file for the XSL.

ColdFusion MX: Added this function.

Parameters

Parameter

Description

xml

An XML document in string format, or an XML document object

xsl

XSLT transformation to apply; can be any of the following:

Any of the following:

  • A string containing XSL text.
  • The name of an XSTLT file. Relative paths start at the directory containing the current CFML page.
  • The URL of an XSLT file; valid protocol identifiers include http, https, ftp, and file. Relative paths start at the directory containing the current CFML page.

parameters

A structure containing XSL template parameter name-value pairs to use in transforming the document. The XSL transform defined in the xslString parameter uses these parameter values in processing the XML.

Usage

An XSLT converts an XML document to another format or representation by applying an Extensible Stylesheet Language (XSL) stylesheet to it. XSL, including XSLT syntax is specified by the World Wide Web Consortium (W3C). For detailed information on XSL and XSLT, see the W3C website at www.w3.org/Style/XSL/.

If the XSLT code contains include statements with relative paths, ColdFusion resolves them relative to the location of the XSLT file, or for an XSL string, the location of the current ColdFusion page.

Example

The following example converts an XML document that represents a customer order into an HTML document with the customer name and a table with the order items and quantities:

The custorder.xml file that represents a customer order has the following lines:

<?xml version="1.0" encoding="UTF-8"?>
<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <name>Deluxe Carpenter&apos;s Hammer</name>
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
        <item id="54">
            <name>36&quot; Plastic Rake</name>
            <quantity>2</quantity>
            <unitprice>6.95</unitprice>
        </item>
        <item id="68">
            <name>Standard paint thinner</name>
            <quantity>3</quantity>
            <unitprice>8.95</unitprice>
        </item>
    </items>
</order>

The custorder.xsd XSLT file that transforms the XML to HTML that displays the customer’s name, and the items and quantities ordered has the following lines:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" doctype-public="-//W3C//DTD HTML 4.0 Transitional//EN" />
    <xsl:template match="/">
        <html>
            <body>
                <table border="2" bgcolor="yellow">
                    <tr>
                        <th>Name</th>
                        <th>Price</th>
                    </tr>
                    <xsl:for-each select="breakfast_menu/food">
                        <tr>
                            <td>
                                <xsl:value-of select="name"/>
                            </td>
                            <td>
                                <xsl:value-of select="price"/>
                            </td>
                        </tr>
                    </xsl:for-each>
                </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

The CFML file has the following lines:

<cffile action="read" file="C:\CFusionMX7\wwwroot\examples\custorder.xsl" variable="xmltrans">
<cfset xmldoc = XmlParse("C:\CFusionMX7\wwwroot\examples\custorder.xml")>
<cfoutput>#XmlTransform(xmldoc, xmltrans)#</cfoutput>


XmlValidate

Description

Uses a Document Type Definition (DTD) or XML Schema to validate an XML text document or an XML document object.

Returns

The following validation structure:

Field

Description

Errors

An array containing any validator error messages. These messages indicate that the document does not conform to the DTD or Schema (is not valid).

FatalErrors

An array containing any validator fatal error messages. Fatal errors indicate that the document contains XML formatting errors (is not well-formed XML).

Status

A Boolean value:

  • True if the document is valid.
  • False if the validation check failed.

Warning

An array containing any validator warnings. A well-formed and valid document can produce warning messages.

Category

XML functions

Function syntax

XmlValidate(xmlDoc[, validator])

See also

cfxml, IsXmlDoc, IsXML, XmlFormat, XmlNew, XmlParse, XmlSearch, XmlTransform; Using XML and WDDX in ColdFusion MX Developer’s Guide

History

ColdFusion MX 7: Added this function.

Parameters

Parameter

Description

xmlDoc

Any of the following:

  • A string containing an XML document.
  • The name of an XML file.
  • The URL of an XML file; valid protocol identifiers include http, https, ftp, and file.
  • An XML document object, such as one generated by the XmlParse function.

validator

Any of the following:

  • A string containing a DTD or Schema.
  • The name of a DTD or Schema file.
  • The URL of a DTD or Schema file; valid protocol identifiers include http, https, ftp, and file.

Usage

If you specify a relative URL or filename in a parameter, ColdFusion uses the directory (or, for URLs, the virtual directory) that contains the current ColdFusion page as the path root.

The validato r parameter specifies a DTD or Schema to use to validate the document. If you omit the parameter, the XML document must contain one of the following:

  • A !DOCTYPE tag to specify the DTD or its location
  • An xsi:schemaLocation or xsi:noNamespaceSchemaLocation tag to specify the Schema location

If you use a validator parameter and the XML document specifies a DTD or Schema, the XmlValidate function uses the validator parameter, and ignores the specification in the XML document.

If you do not use a validator parameter, and the XML document does not specify a DTD or Schema, the function returns a structure with an error message in the Errors field.

This function attempts to process the complete XML document, and reports all errors found during the processing. As a result, the returned structure can have a combination of Warning, Error, and FatalError fields, and each field can contain multiple error messages.

Example

The following example has three parts: an XML file, an XSD Schema file, and a CFML page that parses the XML file and uses the Schema for validation. The CFML file displays the value of the returned structure’s Status field and displays the returned structure. To show the results of invalid XML, modify the custorder.xml file.

Note: The Schema used in the following example represents the same XML structure as the DTD used in the XmlParse example.

The custorder.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:8500/something.xsd" id="4323251" >
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <name>	Deluxe Carpenter&apos;s Hammer</name>
            <quantity>1</quantity>
            <unitprice>15.95</unitprice>
        </item>
        <item id="54">
            <name>	36&quot; Plastic Rake</name>
            <quantity>2</quantity>
            <unitprice>6.95</unitprice>
        </item>
        <item id="68">
            <name>	Standard paint thinner</name>
            <quantity>3</quantity>
            <unitprice>8.95</unitprice>
        </item>
    </items>
</order>

The custorder.xsd file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
    <xs:element name="customer">
        <xs:complexType>
            <xs:attribute name="firstname" type="xs:string" use="required"/>
            <xs:attribute name="lastname" type="xs:string" use="required"/>
            <xs:attribute name="accountNum" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="name" type="xs:string"/>
    <xs:element name="quantity" type="xs:string"/>
    <xs:element name="unitprice" type="xs:string"/>
    <xs:element name="item">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="name"/>
                <xs:element ref="quantity"/>
                <xs:element ref="unitprice"/>
            </xs:sequence>
            <xs:attribute name="id" type="xs:integer" use="required">
            </xs:attribute>
        </xs:complexType>
    </xs:element>
    <xs:element name="items">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="item" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="order">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="customer"/>
                <xs:element ref="items"/>
            </xs:sequence>
            <xs:attribute name="id" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

The CFML file is as follows. It uses a filename for the XML file and a URL for the Schema. The XML and URL paths must be absolute.

<cfset
myResults=XMLValidate("C:\CFusionMX7\wwwroot\examples\custorder.xml",
"http://localhost:8500/examples/custorder.xsd")>
<cfoutput>
Did custorder.xml validate against custorder.xsd? #results.status#<br><br>
</cfoutput>
Dump of myResults structure returned by XMLValidate<br>
<cfdump var="#myResults#">


Year

Description

From a date/time object, gets the year value.

Returns

The year value of date.

Category

Date and time functions

Function syntax

Year(date)

See also

DatePart, IsLeapYear

Parameters

Parameter | Description
date | A date/time object in the range 100 AD–9999 AD.

Usage

When passing a date as a string, enclose it in quotation marks. Otherwise, it is interpreted as a number representation of a date.

Example

<h3>Year Example</h3>
<cfif IsDefined("FORM.year")>
    More information about your date:
    <cfset yourDate = CreateDate(FORM.year,FORM.month,FORM.day)>
    <cfoutput>
    <p>Your date, #DateFormat(yourDate)#.
    <br>It is #DayOfWeekAsString(DayOfWeek(yourDate))#,
day #DayOfWeek(yourDate)# in the week.
    <br>This is day #Day(yourDate)#
in the month of #MonthAsString(Month(yourDate))#,
which has #DaysInMonth(yourDate)# days.
    <br>We are in week #Week(yourDate)# of #Year(YourDate)#
(day #DayOfYear(yourDate)# of #DaysInYear(yourDate)#). <br>
    <cfif IsLeapYear(Year(yourDate))>
        This is a leap year
        <cfelse>This is not a leap year
    </cfif>
    </cfoutput>
</cfif>


YesNoFormat

Description

Evaluates a number or Boolean value.

Returns

Yes, for a nonzero value; No for zero, false, and no Boolean values, and an empty string ("").

Category

Decision functions, Display and formatting functions

Function syntax

YesNoFormat(value)

See also

IsBinary, IsNumeric

Parameters

Parameter | Description
value | A number or Boolean value

Example

<h3>YesNoFormat Example</h3>
<p>The YesNoFormat function returns non-zero values as "Yes"; zero, false and no Boolean values, and empty strings ("") as "No".

<cfoutput>
<ul>
    <li>YesNoFormat(1):	#YesNoFormat(1)#
    <li>YesNoFormat(0):	#YesNoFormat(0)#
    <li>YesNoFormat("1123"):	#YesNoFormat("1123")#
    <li>YesNoFormat("No"):	#YesNoFormat("No")#
    <li>YesNoFormat(True):	#YesNoFormat(True)#
</ul>
</cfoutput>

Previous


ColdFusion MX Flash Form Style Reference

This chapter describes the styles that you can specify in Macromedia ColdFusion MX 7 forms tags when you display the form or form element in Flash format.

Contents

Styles valid for all controls

Styles for cfform

Styles for cfformgroup with horizontal or vertical type atributes

Styles for box-style cfformgroup elements

Styles for cfformgroup with accordion type attribute

Styles for cfformgroup with tabnavigator type attribute

Styles for cfformitem with hrule or vrule type attributes

Styles for cfinput with radioButton, checkbox, button, image, or submit type attributes

Styles for cftextarea tag and cfinput with text, password, or hidden type attributes

Styles for cfselect with size attribute value of 1

Styles for cfselect with size attribute value greater than 1

Styles for cfcalendar tag and cfinput with dateField type attribute

Styles for the cfgrid tag

Styles for the cftree tag

Note: The column labeled Inh indicates whether a style is inherited by child controls, such as the form controls in a vbox.
Next


Styles valid for all controls

The following styles are valid for all ColdFusion Flash format form tags except for cfformitem tags with the following type attributes, which do not take style attributes:

  • html
  • space
  • text

These styles do not cause errors when used in all other tags. However, many styles do not have any effect when used in some tags.

Style

Inh

Description

backgroundAlpha

N

Alpha (transparency) level of the SWF file or image defined by backgroundImage. Valid values range from 0 (transparent) to 100 (opaque). The default value is 100.

backgroundColor

Y

Format: color; background color of the control. Has no effect if specified in a cfform control tag, which uses the background-color style to control the color. Also ignored by cfinput tags of type button, img, submit, radiobutton, and checkbox, because they are completely filled with the button face or other graphics.

backgroundDisabled
Color

Y

Format: color; background color of components when disabled. The default value is ##EFEEEF (light gray).

backgroundSize

N

Scales the image specified by backgroundImage to different percentage sizes. By default, the value is auto, which maintains the original size of the image. A value of 100% stretches the image to fit the entire screen. You must include the percent sign with the value.

barColor

Y

Format: color; color of the outer bar.

borderCapColor

Y

Format: color; outside left and outside right color for skins.

borderColor

Y

Format: color; black section of a three-dimensional border or the color section of a two-dimensional border.

borderSides

N

Bounding box sides. Only used when borderStyle="solid". Space-delimited string containing the sides of the border to show. Order is not important. The default value is "left top right bottom".

borderStyle

Y

Bounding box style. The possible values are:

  • inset (default)
  • none
  • outset
  • solid

borderThickness

N

Bounding box thickness. Only used when borderStyle="solid". The default value is 1.

color

Y

Format: color; text color of a component’s label.

cornerRadius

N

Radius of component corners. The default value is 0.

disabledColor

Y

Format: color; color of the component if it is disabled.

dropShadow

N

Format: Boolean; controls the visibility of the component's drop shadow. The default value is false. This style must be used with borderStyle="solid". For drop shadows to appear on containers, set backgroundColor or backgroundImage. Otherwise, since the default background of a container is transparent, the shadow appears behind the container.

errorColor

Y

Format: color; color of the error text.

fillColors

N

Format: color; colors used to tint the background of the control. Pass the same color for both values for "flat" looking control. The default value is ##E6EEEE,##FFFFFF.

fontFamily

Y

Comma-separated list of fonts to use, in descending order of desirability. You can use any font family name. If you specify a generic font name, it is converted to an appropriate device font. Flash can only use fonts that are installed on the client system.

fontSize

Y

Format: length; size of the text.

fontStyle

Y

Determines whether the text is italic. Recognized values are normal and italic. The default value is normal.

fontWeight

Y

Determines whether the text is bold. Recognized values are normal and bold. The default value is normal.

highlightColor

Y

Format: color; color of the control when it is in focus.

horizontalGap

N

Format: length; number of pixels between children in the horizontal direction.

leading

N

Additional vertical space between lines of text. The default value is no leading.

marginLeft

N

Format: length; number of pixels between the container’s left border and its content area.

marginRight

N

Format: length; number of pixels between the container’s right border and its content area.

scrollTrackColor

Y

Format: color; scroll track for a scroll bar. The default value is ##EFEEEF (light gray).

selectedFillColors

N

Format: colors; two colors used to tint the background of the control when in its selected state. Pass the same color for both values for "flat" looking control. The default value is undefined, which means the colors will be derived from themeColor.

textAlign

Y

Aligns text in a container. Recognized values are left, right, and center. The default value is right.

textDecoration

N

Determines whether the text is underlined or not. Recognized values are none and underline. The default value is none.

textIndent

Y

Format: length; offset of first line of text from the left side of the container. The default value is 0.

themeColor

Y

Format: color; background color of a component. The possible values are:

  • haloGreen
  • haloBlue
  • haloOrange
  • haloSilver

verticalGap

N

Format: length; number of pixels between children in the vertical direction.


Styles for cfform

The following styles apply to the cfform tag:

Style | Inh | Description
background-color |  | Format: color; background color of the form.
indicatorGap | Y | Format: length; number of pixels between the label and child components. The default value is 14.
labelWidth | Y | Format: length; width of the form labels. The default value is the length of the longest label in the form.
marginBottom | N | Format: length; number of pixels between the container’s bottom border and its content area. The default value is 16.
marginTop | N | Format: length; number of pixels between the container’s top border and its content area. The default value is 16.
verticalGap | N | Format: length; number of pixels between children in the vertical direction. The default value is 8.


Styles for cfformgroup with horizontal or vertical type atributes

The following styles apply to the cfformgroup tag with type attributes horizontal or vertical:

Style | Inh | Description
horizontalAlign | N | Horizontal alignment of children. Possible values are left, center, and right. The default value is left.
horizontalGap | N | Format: length; number of pixels between children in the horizontal direction. The default value is 6.
indicatorGap | Y | Format: length; number of pixels between the label and child components. The default value is 14.
labelWidth | Y | Format: length; width of the form labels. The default value is the length of the longest label in the form.
marginBottom | N | Format: length; number of pixels between the container`s bottom border and its content area. The default value is 0.
marginTop | N | Format: length; number of pixels between the container`s top border and its content area. The default value is 0.
verticalGap | N | Format: length; number of pixels between children in the vertical direction. The default value is 6.


Styles for box-style cfformgroup elements

The following styles apply to the cfformgroup tag with the following type attributes. Some types have additional attributes, which are listed in the following sections.

  • hbox
  • vbox
  • hdividedbox
  • vdividedbox
  • panel
  • tile
  • page

    Style

    Inh

    Description

    horizontalAlign

    N

    Horizontal alignment of children in the container. The default value is left. Possible values are left, center, and right.

    horizontalGap

    N

    Format: length; number of pixels between children in the horizontal direction. The default value is 8 (6 for a tile container).

    marginBottom

    N

    Format: length; number of pixels between the container’s bottom border and its content area. The default value is 0.

    marginTop

    N

    Format: length; number of pixels between the container’s top border and its content area. The default value is 0.

    verticalAlign

    N

    Vertical alignment of children in the container. The default value is top. Possible values are top, middle, and bottom.

    verticalGap

    N

    Format: length; number of pixels between children in the vertical direction. The default value is 8 (6 for a tile container).

Styles specific to cfformgroup with hdividedbox or vdividedbox type attributes

The following additional styles apply to the cfformgroup tag with type="hdividedbox", or type="vdividedbox":

Style | Inh | Description
dividerAffordance | N | Format: length; width (hdividedbox) or height (vdividedbox) in pixels of the area of the divider that the user can select with the mouse pointer. The default value is 6.
dividerColor | Y | Format: color; color of the dividers in their up state. The default value is ##AAAAAA.
dividerThickness | N | Format: length; thickness in pixels of the dividers. The default value is 4.

Styles specific to cfformgroup with panel type attribute

The following additional styles apply to the cfformgroup tag with type="panel":

Style | Inh | Description
cornerRadius | N | Format: length; radius of corners of the window frame. The default value is 8.
dropShadow | N | Boolean value specifying whether the panel has a drop shadow. The default value is true.
footerColors | Y | Format: color; comma-delimited list of two colors used to draw the footer (ControlBar) background. The first color is the top color. The second color is the bottom color. The default value is ##F4F5F7, ##E1E5EB.
headerColors | Y | Format: color; comma-delimited list of two colors used to draw the header. The first color is the top color. The second color is the bottom color. The default value is ##E1E5EB, ##F4F5F7.
headerHeight | N | Format: length; height of the header. The default value is 28.
panelBorderStyle | N | Border style for the bottom two corners of the container. The top two corners are always round. Possible values are default, which configures the container to have square corners, and roundCorners, which defines rounded corners. To configure the top corners to be square, set cornerRadius to 0. The default value is default.
shadowDirection | N | Direction of drop shadow. Possible values are "left", "center", and "right". The default value is "center".
shadowDistance | N | Distance of drop shadow. Negative values move shadow above the panel. The default value is 2.


Styles for cfformgroup with accordion type attribute

The following styles apply to the cfformgroup tag with type="accordion":

Style | Inh | Description
headerHeight | N | Format: length; height of the accordion container buttons, in pixels. The default value is 22.
marginBottom | N | Format: length; number of pixels between the container`s bottom border and its content area. The default value is -1.
marginTop | N | Format: length; number of pixels between the container`s top border and its content area. The default value is -1.
openDuration | N | Format: time; duration, in milliseconds, of the transition from one child panel to another. The default value is 250.
verticalGap | N | Format: length; number of pixels between children in the vertical direction. The default value is -1.


Styles for cfformgroup with tabnavigator type attribute

The following styles apply to the cfformgroup tag with the type="tabnavigator":

Style | Inh | Description
horizontalAlign | N | Horizontal alignment of children. The default value is left. Possible values are left, center, and right. Because the preferred width of each tab in the tab navigator container is the size of the label text, you must use the tabWidth style to increase the width of the tab to a size larger than its preferred width to see different alignments.
horizontalGap | N | Format: length; number of pixels between children in the horizontal direction. The default value is 6.
tabHeight | N | Format: length; default tab height, in pixels. The default value is 22.
tabWidth | N | Format: length; width of the tabs, in pixels. If undefined, the default tab widths are automatically calculated from the label text. If the width of the container is smaller than the width of the label text, the labels are truncated. If a tab label is truncated, Flash displays a tooltip with the full label text when a user moves the mouse pointer over the tab. If you specify an explicit tab width, labels do not automatically shrink to fit if they do not fit in the available space.


Styles for cfformitem with hrule or vrule type attributes

The following styles apply to the formitem tag with type="hrule" or type="vrule":

Style

Inh

Description

color

Y

Format: color; color of the line. according to the following rules:

  • If strokeWidth is 1, the color of the entire line.
  • If strokeWidth is 2 (default), the color of the top line.
  • If strokeWidth is greater than 2, the color of the top and left edges of the rectangle.

The default value is ##C4CCCC.

shadowColor

Y

Format: color; shadow color of the line, as follows:.

  • If strokeWidth is 1, does nothing.
  • If strokeWidth is 2 (default), the color of the bottom line.
  • If strokeWidth is greater than 2, the color of the bottom and right edges of the rectangle.

The default value is ##D4D0C8.

strokeWidth

Y

Thickness of the rule in pixels, as follows:

  • If strokeWidth is 1, the rule is a 1-pixel-wide line.
  • If strokeWidth is 2 (default), the rule is two adjacent 1-pixel-wide horizontal lines.
  • If strokeWidth is greater than 2, the rule is a hollow rectangle with 1-pixel-wide edges.

The default value is 2.


Styles for cfinput with radioButton, checkbox, button, image, or submit type attributes

The following styles apply cfinput tags with the following type attribute values:

  • button
  • checkbox
  • image
  • radiobutton
  • submit

In some cases, a style applies only to the subset of these input types, as specified in the description.

Style | Inh | Description
borderThickness | N | Thickness of border "ring". A value of 0 means no border. Any value greater than 2 creates a glowing "ring" around the button. The default value is 3.
cornerRadius | N | Radius of corners. The default value is 5.
horizontalGap | N | Gap between the label and the image in an img input when labelPlacement = "left" or "right". The default value is 2.
repeatDelay | N | Format: time; number of milliseconds to wait after the first buttonDown event before repeating buttonDown events at the repeatInterval. The default value is 500.
repeatInterval | N | Format: time; number of milliseconds between buttonDown events if you press and hold a button. The default value is 35.
symbolBackgroundColor | Y | Format: color; background color of check boxes and radio buttons. The default value is ##FFFFFF (white).
symbolBackground DisabledColor | Y | Format: color; background color of check boxes and radio buttons when disabled. The default value is ##EFEEEF (light gray).
symbolBackground PressedColor | Y | Format: color; background color of check boxes and radio buttons when pressed. The default value is ##FFFFFF (white).
symbolColor | Y | Format: color; the check mark of a check box or the dot of a radio button. The default value is ##000000 (black).
symbolDisabledColor | Y | Format: color; check mark or radio button dot color if the control is disabled. The default value is ##848384 (dark gray).
texRollOverColor | Y | Format: color; text color of the label as you move the mouse pointer over the control. The default value is ##2B333C.
textSelectColor | Y | Format: color; text color of the label as you select the control. The default value is ##000000.
verticalGap | N | Gap between the label and the image in an img input when labelPlacement = "top" or "bottom". The default value is 2.


Styles for cftextarea tag and cfinput with text, password, or hidden type attributes

The following style applies to the following tags and tag-attribute combinations:

  • textarea
  • cfinput type="hidden"
  • cfinput type="password"
  • cfinput type="text"

    Style

    Inh

    Description

    disabledColor

    Y

    Format: color; disabled color of the Text Area.


Styles for cfselect with size attribute value of 1

The following styles apply to the cfselect tag when the size attribute is 1; that is, if the control displays one option at a time, with a drop-down list (also known as a combobox):

Style | Inh | Description
alternatingRowColors | Y | Format: comma delimited list of colors for rows in an alternating pattern. Value can be a list of two or more colors. Use only if you do not specify a backgroundColor style.
closeDuration | N | Time to close the drop-down list, in milliseconds. The default value is 250.
openDuration | N | Time to close the drop-down list, in milliseconds. The default value is 250.
rollOverColor | Y | Format: color; color of the background when the user rolls over an item. The default value is ##0EFFD6.
selectionColor | Y | Format: color; color of the background when the user selects an item. The default value is ##0DFFC1.


Styles for cfselect with size attribute value greater than 1

The following styles apply to the cfselect tag when the size attribute is greater than 1; that is, if the control is a list box that displays two or more options at a time:

Style | Inh | Description
alternatingRowColors | Y | Type: comma-delimited list of colors for rows in an alternating pattern. Value can be a list of two or more colors.
marginBottom | N | Format: length; number of pixels between the bottom of the row and the bottom of the text in the row. The default value is 0.
marginTop | N | Format: length; number of pixels between the top of the row and the top of the text in the row. The default value is 0.
rollOverColor | Y | Format: color; color of the background when the user moves the mouse pointer over the link. The default value is ##0EFFD6.
selectionColor | Y | Format: color; color of the background when the user selects the link. The default value is ##0DFFC1.
selectionDuration | N | The duration of the selection animation, in milliseconds. The default value is 250. Set to 0 to disable animation.
textRollOverColor | Y | Format: color; text color when the user moves the mouse pointer over the selection. The default value is ##02B33C.
textSelectedColor | Y | Format: color; text color when selected. The default value is ##005F33.


Styles for cfcalendar tag and cfinput with dateField type attribute

The following styles apply to the cfcalendar tag and dateField type of the cfinput tag:

Style | Inh | Description
headerColors | Y | Format: color; colors of the band at the top of the DateChooser control. Specify two values, separated by a comma. For a solid band, use the same color for both values. The default value is ##E6EEEE,##FFFFFF.
rollOverColor | Y | Format: color; color of the background when the user moves the mouse pointer over the DateField. The default value is ##E3FFD6.
selectionColor | Y | Format: color; color of the background when the user selects the DateField. The default value is ##CDFFC1.
todayColor | Y | Format: color; color of today’s date. The default value is ##2B333C.


Styles for the cfgrid tag

The following styles apply to the cfgrid tag:

Style | Inh | Description
horizontalAlign | N | Horizontal alignment of children in the container. The default value is left. Possible values are left, center, and right.
horizontalGap | N | Number of pixels between children in the horizontal direction. The default value is 8.
marginBottom | N | Number of pixels between the container’s bottom border and its content area. The default value is 0.
marginTop | N | Number of pixels between the container’s top border and its content area. The default value is 0.
verticalAlign | N | Vertical alignment of children in the container. The default value is top. Possible values are top, middle, and bottom.
verticalGap | N | Number of pixels between children in the vertical direction. The default value is 8.


Styles for the cftree tag

The following styles apply to the cftree tag:

Style | Inh | Description
alternatingRowColors | Y | Type: Array; colors for rows in an alternating pattern. Value can be an Array of two or more colors.
depthColors | Y | Type: Array; array of colors used in the Tree control, in descending order.
indentation | N | Indentation for each tree level, in pixels. The default value is 8.
openDuration | N | Format: time; length of an open or close transition, in milliseconds. The default value is 250.
rollOverColor | Y | Format: color; color of the background when the user moves the mouse pointer over the link. The default value is ##E3FFD6.
selectionColor | Y | Format: color; color of the background when the user selects the link. The default value is ##CDFFC1.
selectionDuration | N | The duration of the selection animation, in milliseconds. The default value is 250. Set to 0 to disable animation.
textRollOverColor | Y | Format: color; color of the text when the user moves the mouse pointer over the entry. The default value is ##02B33C.
textSelectedColor | Y | Format: color; color of the text when the user selects the entry. The default value is ##005F33.
Previous


Application.CFC Reference

This chapter describes the methods that you implement in Application.cfc to handle Macromedia ColdFusion MX 7 application events. It also describes the variables that you set in the CFC to configure application characteristics.

Contents

Application variables

Method summary

Tag descriptions

Note: Although Windows is case-insensitive, Macromedia recommends that you always start the Application.cfc filename with an uppoercase A. Both application.cfc and Application.cfc are reserved words.

Note: If your application has an Application.cfc, and an Application.cfm or onRequestend.cfm page, ColdFusion MX ignores the CFM pages.
Next


Application variables

The This scope for the Application.cfc contains several built-in variables which correspond to the attributes that you set in the cfapplication tag. You set the values of these variables in the CFC initialization code, before you define the CFC methods. You can access the variables in any method.

The following table briefly describes the variables that you can set to control the application behavior. For more details, see the cfapplication tag.

Variable | Default | Description
name | no name | The application name. If you do not set this variable, or set it to the empty string, your CFC applies to the unnamed application scope, which is the ColdFusion MX J2EE servlet context. For more information on unnamed scopes see Sharing data between ColdFusion pages and JSP pages or servlets in ColdFusion MX Developer’s Guide.
applicationTimeout | Administrator value | Life span, as a real number of days, of the application, including all Application scope variables. Use the CFML CreateTimeSpan function to generate this variable’s value.
clientManagement | Administrator value | Whether the application supports Client scope variables.
clientStorage | Administrator value | Where Client variables are stored; can be cookie, registry, or the name of a data source.
loginStorage | cookie | Whether to store login information in the Cookie scope or the Session scope.
sessionManagement | no | Whether the application supports Session scope variables.
sessionTimeout | Administrator value | Life span, as a real number of days, of the user session, including all Session variables. Use the CFML CreateTimeSpan function to generate this variable’s value.
setClientCookies | True | Whether to send CFID and CFTOKEN cookies to the client browser.
setDomainCookies | False | Whether to set CFID and CFTOKEN cookies for a domain (not just a host).
scriptProtect | Administrator value | Whether to protect variables from cross-site scripting attacks.


Method summary

The following table briefly describes the application event methods that you can implement in Application.CFC:

Method name | Method runs when
onApplicationEnd | The application ends: the application times out, or the server is stopped
onApplicationStart | The application first starts: the first request for a page is processed or the first CFC method is invoked by an event gateway instance, or a web services or Macromedia Flash Remoting CFC.
onError | An exception occurs that is not caught by a try/catch block.
onRequest | The onRequestStart method finishes. (This method can filter request contents.)
onRequestEnd | All pages in the request have been processed:
onRequestStart | A request starts
onSessionEnd | A session ends
onSessionStart | A session starts

All parameters to these methods are positional. You can use any names for these parameters.

When a request executes, ColdFusion MX runs the CFC methods in the following order:

  1. onApplicationStart (if not run before for this application)
  2. onSessionStart (if not run before for this session)
  3. onRequestStart
  4. onRequest
  5. onRequestEnd

The onApplicationEnd, onSessionEnd, and onError CFCs are triggered by specific events.


onApplicationEnd

Description

Runs when an application times out or the server is shutting down.

Syntax

<cffunction name="onApplicationEnd" returnType="void">
    <cfargument name="ApplicationScope" required=true/>
    ...
</cffunction>

See also

onApplicationStart, Method summary, Managing the application with Application.cfc in Designing and Optimizing a ColdFusion Application in ColdFusion MX Developer’s Guide

Parameters

ColdFusion MX passes the following parameters to the method:

Parameters | Description
ApplicationScope | The application scope.

Returns

This method does not return a value; do not use the cfreturn tag.

Usage

Use this method for any clean-up activities that your application requires when it shuts down, such as saving data in memory to a database, or to log the application end to a file. You cannot use this method to display data on a user page, because it is not associated with a request. The application ends, even if this method throws an exception.

If you call this method explicitly, ColdFusion does not end the application; it does execute the method code, but does not lock the Application scope while the method executes.

You must use the ApplicationScope parameter to access the application scope; you cannot reference the scope directly; for example, use Arguments.ApplicationScope.myVariable, not Application.myVariable. This method can access the Server scope directly, but it does not have access to Session or Request scopes.

Note: The application times out only if it is inactive for the time-out period. Sessions do not end, and the onSessionEnd method is not called when an application ends. For more information, see onSessionEnd.

Example

<cffunction name="onApplicationEnd">
    <cfargument name="ApplicationScope" required=true/>
    <cflog file="#This.Name#" type="Information"
        text="Application #Arguments.ApplicationScope.applicationname# Ended" >
</cffunction>


onApplicationStart

Description

Runs when ColdFusion MX receives the first request for a page in the application.

Syntax

<cffunction name="onApplicationStart" returnType="boolean">
    ...
    <cfreturn Boolean>
</cffunction>

See also

onApplicationEnd, Method summary, Managing the application with Application.cfc in Designing and Optimizing a ColdFusion Application in Application.CFC Reference in ColdFusion MX Developer’s Guide

Returns

A Boolean value: True if the application startup code ran successfully; False, otherwise. You do not need to explicitly return a True value if you omit the cffunction tag returntype attribute.

Usage

Use this method for application initialization code; for example, use it to set Application scope variables, to determine whether a required data source or other resource is available, or to log the application start. You do not have to lock the Application scope if you set Application variables in this method, and you can reference Application scope variables as you normally do; for example, as Application.myVariable.

This method can access the requested page’s Variables scope only if the Application.cfc file includes an onRequest method that calls the page.

If you call this method explicitly, ColdFusion does not start the application; it does execute the method code, but does not lock the Application scope while the method executes.

If this method throws an uncaught exception or returns False, the application does not start and ColdFusion MX does not process any pages in the application. In this case, ColdFusion will run the onApplicationStart method the next time a user requests a page in the application.

Example

The following example tests for the availability of a database. If the database is not available it reports and logs the error, and does not start the application; if it is available, the method initializes two Application scope variables.

<cffunction name="onApplicationStart">
    <cftry>
        <!--- Test whether the DB is accessible by selecting some data. --->
        <cfquery name="testDB" dataSource="cfdocexamples" maxrows="2">
            SELECT Emp_ID FROM employee
        </cfquery>
        <!--- If we get a database error, report an error to the user, log the
                error information, and do not start the application. --->
        <cfcatch type="database">
            <cfoutput>
                This application encountered an error<br>
                Please contact support.
            </cfoutput>
            <cflog file="#This.Name#" type="error"
                text="cfdocexamples DB not available. message: #cfcatch.message#
Detail: #cfcatch.detail# Native Error: #cfcatch.NativeErrorCode#" >
            <cfreturn False>
        </cfcatch>
    </cftry>
    <cflog file="#This.Name#" type="Information" text="Application Started">
    <!--- You do not have to lock code in the onApplicationStart method that sets
            Application scope variables. --->
    <cfscript>
        Application.availableResources=0;
        Application.counter1=1;
    </cfscript>
    <cfreturn True>
</cffunction>


onError

Description

Runs when an uncaught exception occurs in the application.

Syntax

<cffunction name="onError" returnType="void">
    <cfargument name="Exception" required=true/>
    <cfargument name="EventName" type="String" required=true/>
    ...
</cffunction>

See also

Method summary, Handling errors in Application.cfc in ColdFusion MX Developer’s Guide

Parameters

ColdFusion MX passes the following parameters to the method:

Parameter | Description
Exception | The ColdFusion MX Exception object. For information on the structure of this object, see the description of the cfcatch variable in the cfcatch description.
EventName | The name of the event handler that generated the exception. If the error occurs during request processing and you do not implement an onRequest method, this is the empty string.

Returns

This method does not return a value; do not use the cfreturn tag.

Usage

Use this method to handle errors in an application-specific manner. This method overrides any error handlers that you set in the ColdFusion MX Administrator or in cferror tags. It does not override try/catch blocks.

Whether the onError method can display output depends on where the error takes place, as follows:

  • The onError method can display a message to the user if an error occurs during an onApplicationStart, onSessionStart, onRequestStart, onRequest, or onRequestEnd event method, or while processing a request.
  • The onError method cannot display output to the user if the error occurs during an onApplicationEnd or onSessionEnd event method, because there is no available page context; however, it can log an error message.

If the onError event handler is triggered by a scope-specific event method, such as onSessionStart, the error prevents further processing at the level of that scope and any lower scopes. An onError event triggered by an onSessionStart method, for example, prevents further processing in the session, but not in the application.

If an exception occurs while processing the onError method, or if the onError method uses a cfthrow tag, the ColdFusion MX standard error handling mechanisms handle the exception. These mechanisms include: any error handlers specified by cferror tags in the Application.cfc initialization code, the site-wide error handler specified in the ColdFusion MX Administrator, and ColdFusion MX default error page. Therefore, you can use the onError method as a filter to handle selected errors, and use other ColdFusion error-handling techniques for the remaining errors.

Example

<cffunction name="onError">
    <cfargument name="Exception" required=true/>
    <cfargument type="String" name="EventName" required=true/>
    <!--- Log all errors. --->
    <cflog file="#This.Name#" type="error"
            text="Event Name: #Arguments.Eventname#" >
    <cflog file="#This.Name#" type="error"
            text="Message: #Arguments.Exception.message#">
    <cflog file="#This.Name#" type="error"
        text="Root Cause Message: #Arguments.Exception.rootcause.message#">
    <!--- Display an error message if there is a page context. --->
    <cfif NOT (Arguments.EventName IS "onSessionEnd") OR
            (Arguments.EventName IS "onApplicationEnd")>
        <cfoutput>
            <h2>An unexpected error occurred.</h2>
            <p>Please provide the following information to technical support:</p>
            <p>Error Event: #Arguments.EventName#</p>
            <p>Error details:<br>
            <cfdump var=#Arguments.Exception#></p>
        </cfoutput>
    </cfif>
</cffunction>


onRequest

Description

Runs when a request starts, after the onRequestStart event handler. If you implement this method, it must explicitly call the requested page to process it.

Syntax

<cffunction name="onRequest" returnType="void">
    <cfargument name="targetPage" type="String" required=true/>
    ...
    <cfinclude template="#Arguments.targetPage#">
    ...
</cffunction>

See also

onRequestStart, onRequestEnd, Method summary, Managing requests in Application.cfc in ColdFusion MX Developer’s Guide

Parameters

ColdFusion MX passes the following parameters to the method:

Parameter | Description
targetPage | Path from the web root to the requested page.

Returns

This method does not return a value; do not use the cfreturn tag.

Usage

This event handler provides an optional request filter mechanism for CFML page requests (that is, .cfm pages requested using a browser). Use it to intercept requests to target pages and override the default behavior of running the requested pages. The following rules specify where and how you use the onRequest method.

  • Implement this method only if the following are true:
    • The directory, and any subdirectories affected by this Application.cfc contain CFM files and do not contain any CFC files that are intended to be accessed as web services, using Flash Remoting, or using an event gateway.
    • You want to intercept the request and process it in a special way.
  • If you do not implement this method, ColdFusion automatically calls the target page (or the CFC for a web service, Flash Remoting, or event gateway event).
  • If you implement this method, it must explicitly call the target page, normally by using a cfinclude tag.
  • Do not implement the onRequest method in any Application.cfc file that affects .cfc files that implement web services, process Flash Remoting or event gateway requests; ColdFusion MX will not execute the requests if you implement this method.
  • Code in this method that precedes the call to the target page can perform the same functions as the onRequestStart method, and shares the Variables scope with the target page.
  • Code in this method that follows the call to the target page can perform the same functions as the onRequestEnd method, and shares the Variables scope with the target page.
  • If you implement this method, you can also implement the onRequestStart and onRequestEnd methods.

You can use this method to do preprocessing that is required for all requests. Typical uses include filtering and modifying request page contents (such as removing extraneous white space), or creating a switching mechanism that determines the exact page to display based on available parameters.

Example

<cffunction name="onRequest">
    <cfargument name="targetPage" type="String" required=true/>
    <cfset var content="">
    <cfsavecontent variable="content">
        <cfinclude template="#Arguments.targetPage#">
    </cfsavecontent>
    <cfoutput>
        #replace(content, "report", "MyCompany Quarterly Report", "all")#
    </cfoutput>
</cffunction>


onRequestEnd

Description

Runs at the end of a request, after all other CFML code.

Syntax

<cffunction name="onRequestEnd" returnType="void">
    <cfargument type="String" name="targetPage" required=true/>
    ...
</cffunction>

See also

onRequestStart, onRequest, Method summary, Managing requests in Application.cfc in ColdFusion MX Developer’s Guide

Parameters

ColdFusion MX passes the following parameters to the method:

Parameter | Description
targetPage | Path from the web root to the requested page.

Returns

This method does not return a value; do not use the cfreturn tag.

Usage

This method has the same purpose as the onRequestEnd.cfm page. (You cannot use an onRequestEnd.cfm page if you have an Application.cfc file for your application.) This method runs before the request terminates; therefore, it can access the page context, and can generate output.

This method can be useful for gathering performance metrics, or for displaying dynamic footer information.

This method can access the requested page’s Variables scope only if the Application.cfc file includes an onRequest method that calls the page. You can use Request scope variables to share data with the requested page, even if the Application.cfc file does not have an onRequest method.

If you call this method explicitly, ColdFusion does not end the request, but does execute the method code.

Example

The following example displays one of two footer pages depending on whether the user has logged in:

The onRequestEnd method in Application.cfc contains the following code:

<cffunction name="onRequestEnd">
    <cfargument type="String" name="targetPage" required=true/>
    <cfset theAuthuser=getauthuser()>
    <cfif theAuthUser NEQ "">
        <cfinclude template="authuserfooter.cfm">
    <cfelse>
        <cfinclude template="noauthuserfooter.cfm">
    </cfif>
</cffunction>

A very simple authuserfooter.cfm page consists of the following code:

<cfoutput>
    <h3>Thank you for shopping at our store, #theAuthUser#!</h3>
</cfoutput>

A very simple noauthuserfooter.cfm page consists of the following code:

<cfoutput>
    <h3>Remember, only registered users get all our benefits!</h3>
</cfoutput>

To test this example, implement code for logging in a user, or try the example with and without the following line in the onRequestStart Application.cfc method:

<cfloginuser name="Robert Smith" password="secret" roles="customer">


onRequestStart

Description

Runs when a request starts.

Syntax

<cffunction name="onRequestStart" returnType="boolean">
    <cfargument type="String" name="targetPage" required=true/>
    ...
    <cfreturn Boolean>
</cffunction>

See also

onRequest, onRequestEnd, Method summary, Managing requests in Application.cfc in ColdFusion MX Developer’s Guide

Parameters

ColdFusion MX passes the following parameters to the method:

Parameters | Description
targetPage | Path from the web root to the requested page.

Returns

A Boolean value. Return False to prevent ColdFusion from processing the request. You do not need to explicitly return a True value if you omit the cffunction tag returntype attribute.

Usage

This method runs at the beginning of the request. It is useful for user authorization (login handling), and for request-specific variable initialization, such as gathering performance statistics.

If this method throws an exception (for example, if it uses the cfthrow tag), ColdFusion handles the error and does not process the request further.

If you call this method explicitly, ColdFusion does not start a request, but does execute the method code.

This method can access the requested page’s Variables scope only if the Application.cfc file includes an onRequest method that calls the page. You can use Request scope variables to share data with the requested page even if Application.cfc does not have an onRequest method.

Example

This example uses the authentication code generated by the ColdFusion MX Dreamweaver Login wizard to ensure that the user is logged in. For Beta 2, the wizard generates code that is appropriate for Application.cfm only. To use this code with the Application.CFC, delete the generated Application.CFM

<cffunction name="onRequestStart">
    <cfargument name="requestname" required=true/>
    <!--- Authentication code, generated by the Dreamweaver Login wizard.
    <cfinclude template="mm_wizard_application_include.cfm">
    <!--- Regular maintenance is done late at night. During those hours, tell
             people to come back later, and do not process the request further. --->
    <cfscript>
        if ((Hour(now()) gt 1) and (Hour(now()) lt 3)) {
            WriteOutput("The system is undergoing periodic maintenance.
                Please return after 3:00 AM Eastern time.");
            return false;
        } else {
            this.start=now();
            return true;
        }
    </cfscript>
</cffunction>


onSessionEnd

Description

Runs when a session ends.

Syntax

<cffunction name="onSessionEnd" returnType="void">
    <cfargument name="SessionScope" required=True/>
    <cfargument name="ApplicationScope" required=False/>
    ...
</cffunction>

See also

onSessionStart, Method summary, Managing sessions in Application.cfc in ColdFusion MX Developer’s Guide

Parameters

ColdFusion MX passes the following parameters to the method:

Parameter | Description
SessionScope | The Session scope
ApplicationScope | The Application scope;

Returns

This method does not return a value; do not use the cfreturn tag.

Usage

Use this method for any clean-up activities when the session ends. A session ends when the session is inactive for the session time-out period or, if using J2EE sessions, the user closes the browser. You can, for example, save session-related data, such as shopping cart contents or whether the user has not completed an order, in a database, or do any other required processing based on the user’s status. You might also want to log the end of the session, or other session related information, to a file for diagnostic use.

If you call this method explicitly, ColdFusion does not end the session; it does execute the method code, but does not lock the Session.

You cannot use this method to display data on a user page, because it is not associated with a request.

You can access shared scope variables as follows:

  • You must use the SessionScope parameter to access the Session scope. You cannot reference the Session scope directly; for example, use Arguments.SessionScope.myVariable, not Session.myVariable.
  • You must use the ApplicationScope parameter to access the Application scope. You cannot reference the Application scope directly; for example, use Arguments.ApplicationScope.myVariable, not Application.myVariable. Use a named lock when you reference variables in the Application scope, as shown in the example.
  • You can access the Server scope directly; for example, Server.myVariable.
  • You cannot access the Request scope.

Sessions do not end, and the onSessionEnd method is not called when an application ends. The onSessionEnd does not execute if there is no active application, however.

Example

The following method decrements an Application scope session count variable and logs the session length.

<cffunction name="onSessionEnd">
    <cfargument name = "SessionScope" required=true/>
    <cfargument name = "AppScope" required=true/>
    <cfset var sessionLength = TimeFormat(Now() - SessionScope.started,
        "H:mm:ss")>
    <cflock name="AppLock" timeout="5" type="Exclusive">
        <cfset Arguments.AppScope.sessions = Arguments.AppScope.sessions - 1>
    </cflock>
    <cflog file="#This.Name#" type="Information"
        text="Session #Arguments.SessionScope.sessionid# ended. Length: #sessionLength# Active sessions: #Arguments.AppScope.sessions#>
</cffunction>


onSessionStart

Description

Runs when a session starts.

Syntax

<cffunction name="onSessionStart" returnType="void">
    ...
</cffunction>

See also

onSessionEnd, Method summary, Managing sessions in Application.cfc in ColdFusion MX Developer’s Guide

Returns

This method does not return a value; do not use the cfreturn tag.

Usage

This method is useful for initializing Session scope data, such as a shopping cart, or setting session-specific Application scope variables, such as for tracking the number of active sessions. You never need to lock the Session scope to set its variables using this method.

If you call this method explicitly, ColdFusion does not start a session; it does execute the method code, but does not lock the Session scope.

This method can access the requested page’s Variables scope only if the Application.cfc file includes an onRequest method that calls the page.

Example

The following onSessionStart example initializes some Session scope variables and increments and Application scope counter of active sessions.

<cffunction name="onSessionStart">
    <cfscript>
        Session.started = now();
        Session.shoppingCart = StructNew();
        Session.shoppingCart.items =0;
    </cfscript>
        <cflock scope="Application" timeout="5" type="Exclusive">
            <cfset Application.sessions = Application.sessions + 1>
    </cflock>
</cffunction>
Previous


ColdFusion MX Event Gateway Reference

This chapter describes the Java interfaces available for building Macromedia ColdFusion MX 7 custom CFXs in Java.

Contents

Gateway development interfaces and classes

CFML CFEvent structure

IM gateway methods and commands

SMS Gateway CFEvent structure and commands

CFML event gateway SendGatewayMessage data parameter

Note: The following CFML functions also apply to gateway application development: GetGatewayHelper, SendGatewayMessage.
Next


Gateway development interfaces and classes

The ColdFusion MX event gateway system is defined in the coldfusion.eventgateway package. Gateway developers implement two interfaces and use several classes, as follows:

  • Gateway interface
  • GatewayHelper interface
  • GatewayServices class
  • CFEvent class
  • Logger class


Gateway interface

coldfusion.eventgateway.Gateway

Interface for implementing ColdFusion MX event gateways.

A class that implements this interface defines a ColdFusion MX event gateway type that you can use in ColdFusion MX applications. The class must implement the following methods:

Signature

Description

GatewayName([String id[, String
configFile]])

The gateway constructor.

String getGatewayID()

Returns the gateway ID.

GatewayHelper getHelper()

Returns an instance of the GatewayHelper class for this gateway type. instance, or null if the gateway does not have a GatewayHelper class.

int getStatus()

Gets the event gateway status.

String outgoingMessage(coldfusion.
eventgateway.CFEvent cfmessage)

Handles a message sent by ColdFusion and processes it to send to a message receiver.

void restart()

Restarts a running event gateway.

void setCFCListeners(String[]
listeners)

Identifies the CFCs that listen for incoming messages from the event gateway.

void setGatewayID(String id)

Sets the gateway ID that uniquely identifies the Gateway instance.

void start()

Starts the event gateway.

void stop()

Stops the event gateway.


Constructor

Description

Instantiates a gateway.

Category

Event Gateway Development

Syntax

public void gatewayName()
public void gatewayName(String id)
public void gatewayName(String id, String configFile)

See also

setGatewayID, Class constructor in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
id | The identifier for the gateway instance
configFile | The absolute path to the gateway configuration file.

Usage

If your gateway requires a configuration file, use the constructor with two parameters. Otherwise, you can use either the default constructor or the single parameter version; ColdFusion always uses the setGatewayID method to set the ID.

Example

The following example shows the two argument constructor implemented in the ColdFusion MX SocketGateway class:

public SocketGateway(String id, String configpath) {
        propsFilePath=configpath;
        try {
            FileInputStream propsFile = new FileInputStream(propsFilePath);
            properties.load(propsFile);
            propsFile.close();
            this.loadProperties();
        }
        catch (FileNotFoundException f) {
            // do nothing. use default value for port.
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        gatewayID = id;
        gatewayService = GatewayServices.getGatewayServices();
    }


getGatewayID

Description

Returns the gateway ID that identifies the Gateway instance.

Category

Event Gateway Development

Syntax

public String getGatewayID()

See also

setGatewayID, Providing Gateway class service and information routines in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Usage

This method returns a string value that is set by the setGatewayID method.

Example

The following example is the ColdFusion MX SocketGateway class getGatewayID method:

public String getGatewayID()
    {
        return gatewayID;
    }


getHelper

Description

Returns an instance of the gatewayHelper class, if any for the gateway type.

Category

Event Gateway Development

Syntax

public GatewayHelper getHelper()

See also

GatewayHelper interface; Providing Gateway class service and information routines in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

A coldfusion.eventgateway.GatewayHelper class instance, or null if the gateway does not have a GatewayHelper class.

Usage

ColdFusion calls this method when a ColdFusion MX application calls the CFML GetGatewayHelper function. The application then uses the gatewayHelper object methods to call gateway-specific utility methods, such as instant message buddy management methods.

Example

The following example is the ColdFusion MX SocketGateway class getHelper method:

public GatewayHelper getHelper()
    {
        // SocketHelper class implements the GatewayHelper interface
        return new SocketHelper();
    }


getStatus

Description

Returns the gateway status.

Category

Event Gateway Development

Syntax

public int getStatus()

See also

Providing Gateway class service and information routines in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

An integer status value. The Gateway interface defines the following status constants:

  • STARTING
  • RUNNING
  • STOPPING
  • STOPPED
  • FAILED

Example

The following example is the ColdFusion MX SocketGateway class getStatus method:

public int getStatus()
    {
        return status;
    }


outgoingMessage

Description

Sends a message from ColdFusion to a message receiver.

Category

Event Gateway Development

Syntax

public String outgoingMessage(coldfusion.eventgateway.CFEvent message)

See also

Responding to a ColdFusion function or listener CFC in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
message | A coldfusion.eventgateway.CFEvent instance containing the message to be sent.

Returns

A gateway-specific string, such as a message ID or a status indicator.

Usage

This method handles a message sent by ColdFusion MX and processes it as needed by the gateway type to send a message to the (usually external) message receiver. ColdFusion MX calls this method when the listener method of a listener CFC returns a message or when a ColdFusion application calls the SendGatewayMessage function. ColdFusion MX passes the String returned by this method back as the return value of a CFML SendGatewayMessage function.

Example

The following example is the ColdFusion MX SocketGateway class outgoingMessage method:

public String outgoingMessage(coldfusion.eventgateway.CFEvent cfmsg)
{
    String retcode="ok";
    // Get the table of data returned from the event handler
    Map data = cfmsg.getData();
    String message = (String) data.get("MESSAGE");
    // find the right socket to write to from the socketRegistry hashtable
    if (cfmsg.getOriginatorID() != null && message != null)
    {
        SocketServerThread st =
            ((SocketServerThread)socketRegistry.get(cfmsg.getOriginatorID()));
        if(st != null)
            st.writeOutput(message);
        else
        {
            log.error("Cannot send outgoing message. OriginatorID '" +
                cfmsg.getOriginatorID() + "' is not a valid socket id.");
            retcode="failed";
        }
    }
    else if (data.get("OriginatorID") != null && message != null)
    {
        SocketServerThread st =
            ((SocketServerThread)socketRegistry.get(data.get("OriginatorID")));
        if(st != null)
            st.writeOutput(message);
        else
        {
            log.error("Cannot send outgoing message. OriginatorID '" +
                data.get("OriginatorID") + "' is not a valid socket id.");
            retcode="failed";
        }
    }
    else
    {
        log.error("Cannot send outgoing message. OriginatorID/MESSAGE is not
            available.");
        retcode="failed";
    }
    return retcode;
}


restart

Description

Stops a gateway if it is running and starts it up.

Category

Event Gateway Development

Syntax

public void restart()

See also

start, stop

Usage

In most cases, you implement this method as a call to the stop method followed by a start method, but you may be able to optimize the restart method based on the type of gateway.

Example

The following example is the ColdFusion MX SocketGateway class restart method:

public void restart()
{
    stop();
    start();
}


setCFCListeners

Description

Sets the array of listener CFCs that the gateway sends messages to.

Category

Event Gateway Development

Syntax

public void setCFCListeners(String[] listeners)

See also

Constructor, getGatewayID, setCFCPath, Providing Gateway class service and information routines in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
listeners | Array of absolute file paths to CFCs to which the gateway forwards messages when it gets events.

Usage

When ColdFusion MX starts a gateway instance, it calls this method with the names in the instance’s listener list in the ColdFusion MX Administrator. ColdFusion MX can also call this method if the ColdFusion MX Administrator listener list changes while the gateway is running.

Example

The following example is the ColdFusion MX SocketGateway class setCFCListeners method:

public void setCFCListeners(String[] listeners)
{
    ArrayList aListeners = new ArrayList();
    for(int i = 0; i<listeners.length; i++)
    {
        aListeners.add(listeners[i]);
    }
        // Try not to pull the rug out from underneath a running message
    synchronized (cfcListeners)
    {
        cfcListeners = aListeners;
    }
}


setGatewayID

Description

Sets the gateway ID that uniquely identifies the Gateway instance.

Category

Event Gateway Development

Syntax

public void setGatewayID(String id)

See also

Constructor, getGatewayID, Providing Gateway class service and information routines in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
id | The identifier for this gateway instance.

Usage

This method sets a string value that is returned by the getGatewayID method. ColdFusion MX calls this method to set the gateway ID with the value specified in the gateway instance configuration in the ColdFusion MX Administrator before it starts the event gateway, even if the Gateway constructor also sets the ID.

Example

The following example is the ColdFusion MX SocketGateway class setGatewayID method:

public void setGatewayID(String id)
    {
        gatewayID = id;
    }


start

Description

starts a gateway running.

Category

Event Gateway Development

Syntax

public void start()

See also

restart, stop, The start method in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Usage

Start a gateway by performing any required initialization. This method starts any listener thread or threads that monitor the gateway’s event source. The ColdFusion MX Administrator calls this function when it starts a gateway instance.

This method should update the status information that is returned by the getStatus method to indicate when the gateway is starting and when the gateway is running.

The ColdFusion MX Administrator Gateway Types page lets you specify a time-out for the gateway startup, and whether to kill the gateway on startup time-out. If you enable the kill option and the start method does not return in the time-out period, ColdFusion MX will kill the thread that called this function.

Example

The following example is the ColdFusion MX SocketGateway class restart method:

public void start()
    {
        status = STARTING;
        listening=true;
        // Start up event generator thread
        Runnable r = new Runnable()
        {
            public void run()
            {
                socketServer();
            }
        };
        Thread t = new Thread(r);
        t.start();
        status = RUNNING;
    }


stop

Description

Stops a gateway if it is running.

Category

Event Gateway Development

Syntax

public void stop()

See also

restart, start, The stop method in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Usage

Stops a gateway by performing any required clean-up operations. This method stops any listener thread or threads that monitor the gateway’s event source and releases any other resources. The ColdFusion MX Administrator calls this function when it stops a gateway instance.

This method should update the status information that is returned by the getStatus method to indicate when the gateway is stopping and when the gateway is stopped.

Example

The following example is the ColdFusion MX SocketGateway class stop method:

public void stop()
    {
        status = STOPPING;
        listening=false;
        Enumeration e = socketRegistry.elements();
        while (e.hasMoreElements()) {
            try
            {
                ((SocketServerThread)e.nextElement()).socket.close();
            }
            catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (serverSocket != null) {
            try
            {
                serverSocket.close();
            }
            catch (IOException e1) {
            }
            serverSocket = null;
        }
        status = STOPPED;
    }


GatewayHelper interface

coldfusion.eventgateway.GatewayHelper

ColdFusion MX includes a coldfusion.eventgateway.GatewayHelper Java marker interface, with no methods. Implement this interface to define a class that provides gateway-specific utility methods to the ColdFusion application or listener CFC. For example, an instant messaging event gateway might use a helper class to provide buddy list management methods to the application. The Gateway class must implement a getHelper method that returns the helper class, or null if you do not implement the interface.

For information on GatewayHelper classes, see GatewayHelper class.


GatewayServices class

coldfusion.eventgateway.GatewayServices

The Gateway class uses the coldfusion.eventgateway.GatewayServices class to interact with the ColdFusion event gateway services. This class has the following methods:

Signature

Description

GatewayServices getGatewayServices()

Static method that returns the GatewayServices object.

boolean addEvent (CFEvent msg)

Sends a CFEvent instance to ColdFusion for dispatching to a listener CFC.

coldfusion.eventgateway.Logger
getLogger([String logfile])

Returns a ColdFusion logger object that the event gateway can use to log information in a file.

int getMaxQueueSize()

Returns the maximum size of the ColdFusion event queue, as set in the ColdFusion MX Administrator.

int getMaxQueueSize()

Returns the current size of the ColdFusion event queue that handles all messages for all gateways.


getGatewayServices

Description

Static method that returns the GatewayServices object. Gateway code can call this method at any time, if required.

Category

Event Gateway Development

Syntax

GatewayServices getGatewayServices()

See also

GatewayServices class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

The GatewayServices object.

Usage

Gateway constructors can call this method to get a convenient reference to the GatewayServices class and its methods.

Example

The following Socket gateway constructor code sets the GatewayServices variable:

public SocketGateway(String id)
    {
        gatewayID = id;
        gatewayService = GatewayServices.getGatewayServices();
    }

Calls to GatewayServices methods, such as the following, use the returned value.

boolean sent = gatewayService.addEvent(event);


addEvent

Description

Sends a CFEvent instance to ColdFusion for dispatching to a listener CFC.

Category

Event Gateway Development

Syntax

boolean addEvent(CFEvent msg)

See also

getMaxQueueSize, getMaxQueueSize, Responding to incoming messages in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
msg | The CFEvent object containing the message to be queued for delivery to the listener CFC.

Returns

True if the event was added to the gateway services queue for delivery, false, otherwise. Therefore, a true response does not indicate that the message was delivered.

Usage

The event gateway must use this method to send incoming messages to the application for processing.

Example

The following example from the ColdFusion MX SocketGateway code sends an event to all listener CFCs:

for (int i = 0; i < listeners.length; i++) {
    String path = listeners[i];
    CFEvent event = new CFEvent(gatewayID);
    Hashtable mydata = new Hashtable();
    mydata.put("MESSAGE", theInput);
    event.setData(mydata);
    event.setGatewayType("SocketGateway");
    event.setOriginatorID(theKey);
    event.setCfcMethod(cfcEntryPoint);
    event.setCfcTimeOut(10);
    if (path != null)
        event.setCfcPath(path);
    boolean sent = gatewayService.addEvent(event);
    if (!sent)
        log.error("SocketGateway(" + gatewayID + ") Unable to put message on
            event queue. Message not sent from " + gatewayID + ", thread " +
            theKey + ".  Message was " + theInput);
}


getLogger

Description

Returns a ColdFusion Logger object that the event gateway can use to log information in a file.

Category

Event Gateway Development

Syntax

coldfusion.eventgateway.Logger getLogger([String logfile])

See also

Logger class, Logging events and using log files in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
logfile | The name, without an extension, of a log file in the ColdFusion MX logs directory. ColdFusion MX automatically appends a .log extension to the name. If the file does not exist, ColdFusion MX creates it when it logs the first message. By default, ColdFusion logs to the eventgateway.log file.

Returns

A ColdFusion MX logger object to use in

Usage

The Logger class has five methods: debug, info, warn, error, and fatal, that correspond to the severity level that is set in the log message. Each method takes a message string, a Throwable class object, or both.

If you pass a Throwable object to these methods, ColdFusion MX writes the exception information in the exceptions.log file.

Example

The ColdFusion MX example DirectoryWatcherGateway includes the following line in the constructor to get a logger object:

// We create our own log file, which will be named "watcher.log"
logger = gatewayService.getLogger("watcher");

The following code, from the start of the routine that loads information from the configuration file, uses this object to log the initialization.

// Load the properties file to get our settings
protected void loadconfig() throws ServiceRuntimeException
{
    // load config
    logger.info("DirectoryWatcher (" + gatewayID + ") Initializing
        DirectoryWatcher gateway with configuration file " + config);
.
.
.


getMaxQueueSize

Description

Returns the maximum size of the ColdFusion event queue, as set in the ColdFusion MX Administrator.

Category

Event Gateway Development

Syntax

int getMaxQueueSize()

See also

addEvent, getQueueSize

Returns

The integer maximum number of messages that the gateway services queue can hold.

Usage

If the queue length reaches this value, the addEvent method will not add its message to the processing queue. You can use this method and the getQueueSize method to control the rate of event queuing and to help diagnose any throughput problems in your gateways.

Example

The following example logs the queue size, maximum queue size, and other information if a gatewayService.addEvent method fails to queue a message for delivery to a listener CFC. (It uses an internal method to construct the error message string.)

boolean sent = gatewayService.addEvent(cfmsg);
if (!sent)
{
    logger.error(RB.getString(this, "IMGateway.cantAddToQueue",
        gatewayType, gatewayID, ((path != null) ? path : "default"),
        Integer.ToString(gatewayService.getQueueSize()),
        Integer.ToString(gatewayService.getMaxQueueSize())));
}


getQueueSize

Description

Returns the current size of the ColdFusion event queue that handles all messages for all gateways.

Category

Event Gateway Development

Syntax

int getQueueSize()

See also

addEvent, getMaxQueueSize

Returns

The integer number of messages in the gateway message queue that are waiting to be delivered to CFCs.

Usage

You can use this method and the getMaxQueueSize method to control the rate of event queuing and to help diagnose any throughput problems in your gateways.

Example

The following example logs the queue size, maximum queue size, and other information if a gatewayService.addEvent method fails to queue a message for delivery to a listener CFC. (It uses an internal method to construct the error message string.)

boolean sent = gatewayService.addEvent(cfmsg);
if (!sent)
{
    logger.error(RB.getString(this, "IMGateway.cantAddToQueue",
        gatewayType, gatewayID, ((path != null) ? path : "default"),
        Integer.ToString(gatewayService.getQueueSize()),
        Integer.ToString(gatewayService.getMaxQueueSize())));
}


CFEvent class

coldfusion.gateway.CFEvent

The Gateway class sends and receives CFEvent instances to communicate with the ColdFusion listener CFC or application. The CFEvent instances correspond to CFML CFEvent structures that ColdFusion application listener CFC methods receive and contain the message structures that ColdFusion application code sends to the gateway.

  • The Gateway notifies ColdFusion of a message by sending a CFEvent instance in GatewayServices. addEvent method.
  • The Gateway receives a CFEvent instance when ColdFusion calls the gateway’s outgoingMessage method.

The CFEvent Class extends the java.util.Hashtable class and has the following methods:

Methods

Description

CFEvent(String gatewayID)

CFEvent constructor.

String getGatewayID()

Returns the gateway ID (set in the CFEvent constructor).

void setCFCMethod(String method)
String getCFCMethod()

Sets or gets the name of the CFC method that receives an incoming message.

void setCFCPath(String path)
String getCFCPath()

Sets or gets the path to the application listener CFC that processes the event.

void setCFCTimeout(String seconds)
String getCFCTimeout()

Sets or gets the time-out, in seconds, for the listener CFC to process the event request.

void setData(Map data)
Map getData()

Sets or gets the event data structure, which contains the message contents and any other gateway-specific information.

void setGatewayType(String type)
String getGatewayType()

Sets or gets the event gateway type identifier, such as SMS.

void setOriginatorID(String id)
String getOriginatorID()

Sets or gets the gateway- or protocol-specific Identity of the originator of a message.


CFEvent

Description

CFEvent constructor.

Category

Event Gateway Development

Syntax

CFEvent(String gatewayID)

See also

getGatewayID, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
gatewayID | The ID of the gateway. This parameter indicates the source of the message and must be the value that is passed in the Gateway constructor or set using the Gateway setGatewayID method.

Usage

This method creates a container for an event gateway message that you send to ColdFusion MX gateway services in a gatewayServices.addEvent method for delivery to a CFC listener method.

Example

The following example, based on code for the ColdFusion asynchronous CFML gateway, sends a message to that the gateway has received to a CFC:

public String outgoingMessage(coldfusion.eventgateway.CFEvent cfmsg)
{
    // Get the data
    Map data = cfmsg.getData();
    boolean status = true;
    if (data != null)
    {
        // create an event
        CFEvent event = new coldfusion.eventgateway.CFEvent(gatewayID);
        //set the event field values
        event.setGatewayType("CFMLGateway");
        event.setOriginatorID("CFMLGateway");
        event.setData(data);
        // send it to the event service
        status = gatewayService.addEvent(event);
    }
        return new Boolean(status).ToString();
}


getCFCMethod

Description

Gets the name of the CFC method that processes the message.

Category

Event Gateway Development

Syntax

String getCFCMethod()

See also

getCFCPath, getCFCTimeout, setCFCMethod, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

For incoming messages, the name of the method that gateway services will call in the listener CFC, as set by the setCFCMethod method. If setCFCMethod has not been called, returns null, and not onIncomingMessge, which ColdFusion gateway services uses by default. Outgoing messages that are returned by a CFC in response to an incoming message also have the CFC method name in this field if the gateway set the field on the incoming message.

Usage

Most event gateways do not need to use this method. This method could be useful if a gateway sends messages to multiple CFC Methods and must determine which method is responding.


getCFCPath

Description

Gets the path to the listener CFC that processes this message.

Category

Event Gateway Development

Syntax

String getCFCPath()

See also

getCFCMethod, getCFCTimeout, setCFCPath, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

An absolute path to the application listener CFC that will process the event, as set by the setCFCPath method. If the setCFCPath method has not been called, returns null, not the path specified in the ColdFusion Administrator and used by default by gateway services. Outgoing messages that are returned by a CFC in response to an incoming message also have the CFC method name in this field if the gateway set the field on the incoming message.

Usage

Most event gateways do not need to use this method. This method could be useful if a gateway sends messages to multiple CFCs and must determine which CFC is responding.


getCFCTimeout

Description

Gets the time-out, in seconds, for the listener CFC to process the event request.

Category

Event Gateway Development

Syntax

String getCFCTimeout()

See also

getCFCMethod, getCFCPath, setCFCTimeout, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

The listener CFC time-out, in seconds, as set by the setCFCTimeout method, or null.

Usage

Most gateways do not need to use this function.

When ColdFusion calls a listener CFC method to process the event, and the CFC does not process the event in the specified time-out period, ColdFusion terminates the request and logs an error in application.log file. By default ColdFusion uses the Timeout Request value set on the Server Settings page in the ColdFusion MX Administrator.


getData

Description

Returns the data Map that contains the message contents and other gateway-specific information.

Category

Event Gateway Development

Syntax

Map getData()

See also

setData, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

The event data structure, or null. This structure includes the message contents being passed by the gateway and any other gateway-specific information.

Usage

The contents of the data Map depends on the event gateway type. Typical fields include the message contents, originator ID, destination ID, and if a gateway (such as the ColdFusion MX SMS gateway) supports multiple commands, the command.

Note: The returned Map object has case-insensitive keys.

Example

The following outgoingMessage method from the SocketGateway example gateway gets the message contents from the CFEvent data field of an outgoing message. If the CFEvent object does not include an OriginatorID field, it also tries to get the originator ID from the data field.

public String outgoingMessage(coldfusion.eventgateway.CFEvent cfmsg)
{
    String retcode="ok";
    // Get the table of data returned from the event handler
    Map data = cfmsg.getData();
    String message = (String) data.get("MESSAGE");
    // find the right socket to write to from the socketRegistry hashtable
    if (cfmsg.getOriginatorID() != null)
        ((SocketServerThread)socketRegistry.get(cfmsg.getOriginatorID())).
            writeOutput(message);
    else if (data.get("OriginatorID") != null)
        ((SocketServerThread)socketRegistry.get(data.get("OriginatorID"))).
            writeOutput(message);
    else {
        System.out.println("cannot send outgoing message. OriginatorID is not
            available.");
            retcode="failed";
    }
    return retcode;
}


getGatewayID

Description

Returns the gateway ID field of the CFEvent object.

Category

Event Gateway Development

Syntax

String getGatewayID(CFEvent event)

See also

CFEvent, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

The gateway ID of the CFEvent object, or null.

Usage

Most gateways do not need to use this method. The gateway ID is set in the CFEvent constructor and normally corresponds to the gateway that is handling the event.


getGatewayType

Description

Returns the gateway type field of the CFEvent object.

Category

Event Gateway Development

Syntax

String getGatewayType()

See also

setGatewayType, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

The gateway type of the CFEvent object, or null.

Usage

Most gateways do not need to use this method.


getOriginatorID

Description

Identifies the originator of an incoming message. Some gateway types also use this field for the destination of an outgoing message.

Category

Event Gateway Development

Syntax

String getOriginatorID()

See also

setOriginatorID, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Returns

The protocol-specific identifier of the message originator, or null.

Example

The outgoingMessage method of the SocketGateway example gateway uses the getOriginatorID method to determine the destination of an outgoing message. This way, a listener CFC that sends a response back to the originator does not have to explicitly set a destination in the return variable. If the field is empty, (as it is in messages sent by the CFML SendGatewayMessage function) the gateway tries to get the destination from the CFevent data field.

public String outgoingMessage(coldfusion.eventgateway.CFEvent cfmsg)
{
    String retcode="ok";
    // Get the table of data returned from the event handler
    Map data = cfmsg.getData();
    String message = (String) data.get("MESSAGE");
    // find the right socket to write to from the socketRegistry hashtable
    if (cfmsg.getOriginatorID() != null)
        ((SocketServerThread)socketRegistry.get(cfmsg.getOriginatorID())).
            writeOutput(message);
    else if (data.get("OriginatorID") != null)
        ((SocketServerThread)socketRegistry.get(data.get("OriginatorID"))).
            writeOutput(message);
    else
    {
        System.out.println("cannot send outgoing message. OriginatorID is not
                available.");
        retcode="failed";
    }
    return retcode;
}


setCFCMethod

Description

Sets the name of the CFC method that will processes an incoming message.

Category

Event Gateway Development

Syntax

void setCFCMethod(String method)

See also

getCFCMethod, setCFCPath, setCFCTimeout, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
method | The method in the listener CFC that ColdFusion will call to process this event. If you do not use this method in your gateway, ColdFusion invokes the onIncomingMessage method,

Usage

Gateways that use a single CFC listener method do not need to use this method if the listener CFC method is named onIncomingMessage. For the sake of consistency, Macromedia recommends that any event gateway with a single listener not override this default.

A gateway, such as the ColdFusion MX XMPP gateway, that uses different listener methods for different message types uses this method to identify the destination method.

Example

The following example code comes from the ColdFusion XMPP gateway incoming message handler. It creates a CFEvent object and sets the method that will handle tests based on the message type.

CFEvent cfmsg = new CFEvent(gatewayID);
cfmsg.setOriginatorID(sender);
cfmsg.setGatewayType(gatewayType);
if(messageType == IMessage.IM)
    {
    // default for normal messages
    cfmsg.setCfcMethod(onIncomingMessageFunction);
    }
    //if the message is an authorization request
else if(messageType == IMessage.AUTH_REQUEST)
    {
    cfmsg.setCfcMethod(onAddBuddyRequestFunction);
    message = "Requesting authorization to add '" + recipient + "' to '"
    + sender + "' buddy list and view '" + recipient + "' presence.";
    } // Code snipped here for brevity.


setCFCPath

Description

Specifies the listener CFC that will process this event.

Category

Event Gateway Development

Syntax

void setCFCPath(String path)

See also

getCFCPath, setCFCMethod, setCFCTimeout, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
path | An absolute path to the application listener CFC that will process the event. If you do not call this method in your gateway, ColdFusion uses the first path configured for the event gateway instance on the Event Gateways page in the ColdFusion MX Administrator.

Usage

By default, ColdFusion delivers messages to the CFC in the first path configured for the event gateway instance on the Event Gateways page in the ColdFusion MX Administrator.

If your application supports multiple listener CFCs, use this method to set each listener CFC and then call the gatewayService.addEvent method to send the event to the CFC.

Example

The following example code is based on the Socket gateway processInput method that takes input from the socket and sends it to the CFC listener methods. The listeners variable contains an array of listener CFCS and is set by the gateway’s setCFCListeners method, which ColdFusion calls when it starts the gateway.

for (int i = 0; i < listeners.length; i++)
{
    String path = listeners[i];
    CFEvent event = new CFEvent(gatewayID);
    Hashtable mydata = new Hashtable();
    mydata.put("MESSAGE", theInput);
    event.setData(mydata);
    event.setGatewayType("SocketGateway");
    event.setOriginatorID(theKey);
    event.setCFCMethod(cfcEntryPoint);
    event.setCFCTimeout(10);
    if (path != null)
        event.setCFCPath(path);	boolean sent = gatewayService.addEvent(event);
}


setCFCTimeout

Description

Sets the time-out, in seconds, during which the listener CFC must process the event request and return before ColdFusion gateway services terminates the request.

Category

Event Gateway Development

Syntax

void setCFTimeout(String timeout)

See also

getCFCTimeout, setCFCMethod, setCFCPath, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
timeout | The CFC time-out period, in seconds.

Usage

When ColdFusion calls a listener CFC method to process the event, and the CFC does not return in the specified time-out period, ColdFusion terminates the request and logs an error in the application.log file.

If you do not use this method, ColdFusion uses the Timeout Request value set on the Server Settings page in the ColdFusion MX Administrator.

Use this method if your messages require a longer or shorter time-out period than standard ColdFusion MX HTML requests.

Example

The following example code is based on the Socket gateway processInput method that takes input from the socket and sends it to the CFC listener methods. It sets the CFC time-out to 10 seconds.

for (int i = 0; i < listeners.length; i++)
{
    String path = listeners[i];
    CFEvent event = new CFEvent(gatewayID);
    Hashtable mydata = new Hashtable();
    mydata.put("MESSAGE", theInput);
    event.setData(mydata);
    event.setGatewayType("SocketGateway");
    event.setOriginatorID(theKey);
    event.setCfcMethod(cfcEntryPoint);
    event.setCfcTimeOut(10);
    if (path != null)
         event.setCfcPath(path);
    boolean sent = gatewayService.addEvent(event);
}


setData

Description

Adds the gateway-specific data, including any message contents, as a Java Map to the CFEvent object

Category

Event Gateway Development

Syntax

void setData(Map data)

See also

getData, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
data | The incoming message and any additional gateway-specific event data.

Usage

The number of fields and their contents depend on the event gateway type. The Map keys must be strings.

Because Coldfusion is not case sensitive, it converts the Map passed in the setData method to a case insensitive Map. As a result, do not create entries in the data with names that differ only in case.

Example

The following code shows the routine from the example JMS gateway that handles incoming messages. It puts the JMS message ID and contents in a data HashMap, and uses it in the setData method:

public void handleMessage(String msg, String topicName, String msgID) {
    coldfusion.eventgateway.Logger log = getGatewayServices().getLogger();
    Map data = new HashMap();
    CFEvent cfMsg = new CFEvent(getGatewayID());
    data.put("msg", msg);
    data.put("id", msgID);
    cfMsg.setData(data);
    cfMsg.setOriginatorID(topicName);
    cfMsg.setGatewayType("JMS");
    if (sendMessage(cfMsg)) {
            log.info("Added message '" + msgID + "' to queue.");
    } else {
            log.error("Failed to add message '" + msgID + "' to queue.");
    }
}


setGatewayType

Description

Identifies the type of event gateway.

Category

Event Gateway Development

Syntax

void setGatewayType(String gatewayType)

See also

Parameters

Parameter | Description
gatewayType | A gateway type identifier.

getGatewayType, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Usage

For the sake of consistency, use the same name in this method and in the Type Name field when you add the event gateway type in the ColdFusion MX Administrator. Gateway application CFCs that handle multiple gateway types, such as those in an instant messaging application that handles multiple instant messaging providers, could use this field to determine the protocol type and any gateway type-specific actions.

Example

The following code shows the routine from the example JMS gateway that handles incoming messages. It sets the gateway type to JMS:

public void handleMessage(String msg, String topicName, String msgID) {
    coldfusion.eventgateway.Logger log = getGatewayServices().getLogger();
    Map data = new HashMap();
    CFEvent cfMsg = new CFEvent(getGatewayID());
    data.put("msg", msg);
    data.put("id", msgID);
    cfMsg.setData(data);
    cfMsg.setOriginatorID(topicName);
    cfMsg.setGatewayType("JMS");
    if (sendMessage(cfMsg)) {
            log.info("Added message '" + msgID + "' to queue.");
    } else {
            log.error("Failed to add message '" + msgID + "' to queue.");
    }
}


setOriginatorID

Description

Identifies the originator of an incoming message.

Category

Event Gateway Development

Syntax

void setOriginatorID(String originatorID)

See also

getOriginatorID, CFML CFEvent structure, CFEvent class in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
originatorID | The gateway or protocol-specific ID of the message originator.

Example

The following code shows the routine from the example JMS gateway that handles incoming messages. It sets the originator ID to the name of the JMS topic that the gateway handles:

public void handleMessage(String msg, String topicName, String msgID) {
    coldfusion.eventgateway.Logger log = getGatewayServices().getLogger();
    Map data = new HashMap();
    CFEvent cfMsg = new CFEvent(getGatewayID());
    data.put("msg", msg);
    data.put("id", msgID);
    cfMsg.setData(data);
    cfMsg.setOriginatorID(topicName);
    cfMsg.setGatewayType("JMS");
    if (sendMessage(cfMsg)) {
            log.info("Added message '" + msgID + "' to queue.");
    } else {
            log.error("Failed to add message '" + msgID + "' to queue.");
    }
}


Logger class

coldfusion.eventgateway.Logger

Note: This class is in the coldfusion.log package, not the coldfusion.eventgateway package, which contains all other event gateway-related interfaces and classes.

The Logger class logs messages to a file in the ColdFusion logs directory. (You set this directory on the ColdFusion MX Administrator Logging Settings page.) The coldfusion.eventgateway.GatewayServices. getLogger () method returns an instance of the Logger class. The Logger class has the following methods:

Signature

Description

debug

Writes a debugging message to the log file.

error

Writes an error message to the log file.

fatal

Writes a fatal error to the log file.

info

Writes an informational message to the log file.

warn

Writes a warning message to the log file.


debug

Description

Writes a log entry with a debugging severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message.

Category

Event Gateway Development

Syntax

debug(String message)
debug(Throwable th)
debug(String message, Throwable th)

See also

error, fatal, info, warn, getLogger, Logging events and using log files in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
message | The message to include in the log entry.
th | A throwable object, normally an exception. ColdFusion MX logs the exception information in the exception.log file in the ColdFusion MX logs directory.

Usage

Use this method to send a debugging message to the ColdFusion MX logging subsystem.

By default, ColdFusion does not write debugging messages to the log file. To have debug messages appear in the log file, change the priority entry in cf_root\lib\neo-logging.xml (in the server configuration) or cf_root/WEB-INF\cfusion\lib\neo-logging.xml (in the J2EE configuration. Change the following entry:

<var name='priority'>
    <string>information</string>
</var>

to the following:

<var name='priority'>
    <string>debug</string>
</var>

With debug priority, ColdFusion MX writes messages with a severity of "debug" to the log file specified in the getLogger method that returned the Logger instance (or the default log file).

Example

The ColdFusion MX instant messaging gateways use the following line to log information about incoming administrative messages or errors only when debugging priority is on.

// code to process incoming administrative messages or errors
logger.debug(gatewayType + "Gateway (" + gatewayID + ") admin message: " +
        msg.getMessage());


error

Description

Writes a log entry with an error severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message.

Category

Event Gateway Development

Syntax

error(String message)
error(Throwable th)
error(String message, Throwable th)

See also

debug, fatal, info, warn, getLogger, Logging events and using log files in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
message | The message to include in the log entry.
th | A throwable object, normally an exception. ColdFusion MX logs the exception information in the exception.log file in the ColdFusion MX logs directory.

Usage

Use this method to send an error message to the ColdFusion MX logging subsystem. ColdFusion MX will write a messages with a severity of "error" to the log file specified in the getLogger method that returned the Logger instance (or the default log file).

Example

The ColdFusion MX example SocketGateway class includes the following code in the outgoingMessage method. It writes an error message if the message’s originator ID does not correspond to an open socket.

SocketServerThread st =
        ((SocketServerThread)socketRegistry.get(cfmsg.getOriginatorID()));
    if(st != null)
        st.writeOutput(message);
    else {
        log.error("Cannot send outgoing message. OriginatorID '" +
            cfmsg.getOriginatorID() + "' is not a valid socket id.");
        retcode="failed";
    }


fatal

Description

Writes a log entry with a fatal severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message.

Category

Event Gateway Development

Syntax

fatal(String message)
fatal(Throwable th)
fatal(String message, Throwable th)

See also

debug, error, info, warn, getLogger, Logging events and using log files in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
message | The message to include in the log entry.
th | A throwable object, normally an exception. ColdFusion MX logs the exception information in the exception.log file in the ColdFusion MX logs directory.

Usage

Use this method to send a fatal error message to the ColdFusion MX logging subsystem. ColdFusion MX will write a messages with a severity of "fatal" to the log file specified in the getLogger method that returned the Logger instance (or the default log file).


info

Description

Writes a log entry with an information severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message.

Category

Event Gateway Development

Syntax

info(String message)
info(Throwable th)
info(String message, Throwable th)

See also

debug, error, fatal, warn, getLogger, Logging events and using log files in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
message | The message to include in the log entry.
th | A throwable object, normally an exception. ColdFusion MX logs the exception information in the exception.log file in the ColdFusion MX logs directory. Not normally used with this method.

Usage

Use this method to send an informational message to the ColdFusion MX logging subsystem. ColdFusion MX will write a messages with a severity of "information" to the log file specified in the getLogger method that returned the Logger instance (or the default log file).

ColdFusion normally logs all information severity messages, so you should not use this severity for debugging messages or for events that happen frequently.

Example

The ColdFusion MX example DirectoryWatcherGateway class includes the following line at the top of its loadconfig method that loads the gateway’s configuration file. It writes a message including the gateway ID and configuration file.

logger.info("DirectoryWatcher (" + gatewayID + ") Initializing
        DirectoryWatcher gateway with configuration file " + config);


warn

Description

Writes a log entry with a warning severity to the ColdFusion MX logger. The entry includes the severity, thread ID, date, time, and a text message.

Category

Event Gateway Development

Syntax

warn(String message)
warn(Throwable th)
warn(String message, Throwable th)

See also

debug, error, fatal, info, getLogger, Logging events and using log files in Creating Custom Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
message | The message to include in the log entry.
th | A throwable object, normally an exception. ColdFusion MX logs the exception information in the exception.log file in the ColdFusion MX logs directory.

Usage

Use this method to send a warning message to the ColdFusion MX logging subsystem. ColdFusion MX will write a messages with a severity of "warning" to the log file specified in the getLogger method that returned the Logger instance (or the default log file).

Example

The ColdFusion MX example SocketWatcherGateway class includes the following code in its constructor to load a configuration file. If it cannot load the file, it converts the exception information to a string and logs a warning that includes the gateway ID, and the exception information. It also passes the exception to the warn method

propsFilePath=configpath;
try {
    FileInputStream propsFile = new FileInputStream(propsFilePath);
    properties.load(propsFile);
    propsFile.close();
    this.loadProperties();
    }
catch (IOException e) {
    // do nothing. use default value for port.
    log.warn("SocketGateway(" + gatewayID + ") Unable to read configuration file
        " + propsFilePath + ": " + e.ToString() + ".  Using default port.", e);
    }


CFML CFEvent structure

The CFML listener CFC methods receive messages in the form of a CFEvent structure that corresponds to the CFEvent class that gateway developers use. This structure has the following fields. Some of the fields might not be used by all gateways. All fields contain text or numeric values except the Data field, which contains a structure.

Field | Description
GatewayID | The event gateway that sent the event or will handle the outgoing message. The value is the ID of an event gateway instance configured on the ColdFusion MX Administrator Gateways page. If the application calls the SendGatewayMessage function to respond to the event gateway, it uses this ID as the function’s first parameter.
Data | A structure containing the event data, including the message. The Data structure contents depend on the event gateway type. This field corresponds to the SendGatewayMessage function’s second parameter.
OriginatorID | The originator of the message. The value depends on the protocol or event gateway type. Some event gateways might require this value in response messages to identify the destination of the response. Identifies the sender of the message.
GatewayType | The type of event gateway, such as SMS. An application that can process messages from multiple event gateway types can use this field. This value is the gateway type name that is specified by the event Gateway class. It is not necessarily the same as the gateway type name in the ColdFusion MX Administrator.
CFCPath | The location of the listener CFC. The listener CFC does not need to use this field.
CFCMethod | The listener method that ColdFusion invokes to process the event. The listener CFC does not need to use this field.
CFCTimeout | The time-out, in seconds, for the listener CFC to process the event request. The listener CFC does not need to use this field.


IM gateway methods and commands

The XMPP and IBM Sametime gateways implement CFC methods to receive messages, use the gatewayHelper object methods to manage the gateway, and use outgoing message commands to send messages. The following sections describe these methods and commands:

  • IM Gateway CFC incoming message methods
  • IM gateway message sending commands
  • IM Gateway GatewayHelper class methods


IM Gateway CFC incoming message methods

You write the following CFC methods to handle incoming messages from an XMPP or Lotus Sametime instant messaging gateway.

Note: The method names assume a default gateway configuration. ColdFusion lets you change the method names and disable event types in the gateway configuration file.

Method | Message type
onAddBuddyRequest | Requests from other IM users to add the gateway ID as their buddy
onAddBuddyResponse | Responses from others to requests from your gateway to add them to your buddy lists. Also used by buddies to ask to be removed from your list.
onBuddyStatus | Online status information messages
onIMServerMessage | Error and administrative messages from the IM server
onIncomingMessage | Instant messages


onAddBuddyRequest

Description

Handles incoming requests for users to add the gateway user name as one of their buddies.

Syntax

onAddBuddyRequest(CFEvent)

See also

onIncomingMessage, onAddBuddyResponse, onBuddyStatus, onIMServerMessage

Parameters

The method must take one parameter, a CFEvent structure with the following fields:

Field | Description
gatewayType | Gateway type, either XMPP or SAMETIME
gatewayID | The ID of the gateway instance, as configured in ColdFusion MX Administrator
originatorID | The IM ID of the message originator
cfcMethod | This CFC method; by default, onAddBuddyRequest.
data.MESSAGE | The message that was sent with the request
data.SENDER | The sender’s ID; identical to the originatorID field value
data.RECIPIENT | The recipient’s ID, as specified in the gateway’s configuration file
data.TIMESTAMP | The date and time when the message was sent

Returns

The function can optionally return a value to send a response message. The return structure must contain the following fields:

Field

Description

command

One of the following:

  • accept Accept the request to add you as a buddy. ColdFusion adds the user to the permit list of users that can get status information.
  • decline Deny request to add you as a buddy. ColdFusion adds the user to the deny list of users that can get status information.
  • noact Take no action. ColdFusion does not respond to the requestor.

buddyID

ID to which to send the message. Normally, the value of the CFEvent.data.SENDER field. Not used with the noact command.

reason

A text message describing the reason for the action. Not used with the noact command.

Example

The following example searches for the requested buddy’s name in a data source and, if it finds a unique entry, adds the buddy and updates the buddy’s status information in an Application scope buddyStatus structure. If it doesn’t find the name, it declines the buddy. If there are multiple entries for the buddy name in the database, it tells the gateway not to respond. It logs all actions.

<cffunction name="onAddBuddyRequest">
    <cfargument name="CFEvent" type="struct" required="YES">
    <cfquery name="buddysearch" datasource="cfdocexamples">
        select IM_ID
        from Employees
        where IM_ID = '#CFEvent.Data.SENDER#'
    </cfquery>
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE">
        <cfscript>
            // If the name is in the DB once, accept; if it is missing, decline.
            // If it is in the DB multiple times, take no action.
            if (buddysearch.RecordCount IS 0) {
                action="decline";
                reason="Invalid ID";
            }
            else if (buddysearch.RecordCount IS 1) {
                action="accept";
                reason="Valid ID";
                //Add the buddy to the buddy status structure only if accepted.
                if (NOT StructKeyExists(Application,
                        "buddyStatus")) {
                    Application.buddyStatus=StructNew();
                }
                if (NOT StructKeyExists(Application.buddyStatus,
                        CFEvent.Data.SENDER)) {
                    Application.buddyStatus[#CFEvent.Data.SENDER#]=StructNew();
                }
                Application.buddyStatus[#CFEvent.Data.SENDER#].status=
                    "Accepted Buddy Request";
                Application.buddyStatus[#CFEvent.Data.SENDER#].timeStamp=
                    CFEvent.Data.TIMESTAMP;
                Application.buddyStatus[#CFEvent.Data.SENDER#].message=
                    CFEvent.Data.MESSAGE;
            }
            else {
                action="noact";
            }
        </cfscript>
    </cflock>
    <!--- Log the request and decision information. --->
    <cflog file="#CFEvent.GatewayID#Status"
            text="onAddBuddyRequest; SENDER: #CFEvent.Data.SENDER# MESSAGE:
#CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP# ACTION: #action#">
    <!--- Return the action decision. --->
    <cfset retValue = structNew()>
    <cfset retValue.command = action>
    <cfset retValue.BuddyID = CFEvent.DATA.SENDER>
    <cfset retValue.Reason = reason>
    <cfreturn retValue>
</cffunction>


onAddBuddyResponse

Description

Handles incoming responses from other users to requests from the gateway to be added to their buddy lists. Also receives requests from buddies to have you remove them from your buddy list.

Syntax

onAddBuddyResponse(CFEvent)

See also

onIncomingMessage, onAddBuddyRequest, onBuddyStatus, onIMServerMessage

Parameters

The method must take one parameter, a CFEvent structure with the following fields:

Field

Description

gatewayType

Gateway type, either XMPP or SAMETIME.

gatewayID

The ID of the gateway instance, as configured in ColdFusion MX Administrator.

originatorID

The IM ID of the message originator.

cfcMethod

This CFC method; by default, onAddBuddyResponse.

data.MESSAGE

One of the following:

  • accept The request was accepted.
  • decline The request was declined, or the buddy is asking you to remove them from your list.

data.SENDER

The sender’s ID; identical to the originatorID.

data.RECIPIENT

The recipient’s ID, as specified in the gateway’s configuration file.

data.TIMESTAMP

The date and time when the message was sent.

Returns

The function does not return a value.

Example

The following example adds the buddy’s status to the Application scope buddyStatus structure if the message sender accepted an add buddy request. It logs all responses.

<cffunction name="onAddBuddyResponse">
    <cfargument name="CFEvent" type="struct" required="YES">
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE">
        <cfscript>
            //Do the following only if the buddy accepted the request.
            if (NOT StructKeyExists(Application, "buddyStatus")) {
                Application.buddyStatus=StructNew();
                }
            if (#CFEVENT.Data.MESSAGE# IS "accept") {
                //Create a new entry in the buddyStatus record for the buddy.
                if (NOT StructKeyExists(Application.buddyStatus,
                        CFEvent.Data.SENDER)) {
                    Application.buddyStatus[#CFEvent.Data.SENDER#]=StructNew();
                }
                //Set the buddy status information to indicate buddy was added.
                Application.buddyStatus[#CFEvent.Data.SENDER#].status=
                    "Buddy accepted us";
                Application.buddyStatus[#CFEvent.Data.SENDER#].timeStamp=
                    CFEvent.Data.TIMESTAMP;
                Application.buddyStatus[#CFEvent.Data.SENDER#].message=
                    CFEvent.Data.MESSAGE;
            }
        </cfscript>
    </cflock>
    <!--- Log the information for all responses. --->
    <cflog file="#CFEvent.GatewayID#Status"
        text="onAddBuddyResponse; BUDDY: #CFEvent.Data.SENDER# RESPONSE:
#CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP#">
</cffunction>


onBuddyStatus

Description

Handles incoming messages indicating online status (presence) changes of users on the gateway’s buddy list.

Syntax

onBuddyStatus(CFEvent)

See also

onIncomingMessage, onAddBuddyRequest, onAddBuddyResponse, onIMServerMessage

Parameters

The method must take one parameter, a CFEvent structure with the following fields:

Field

Description

gatewayType

Gateway type, either XMPP or SAMETIME.

gatewayID

The ID of the Gateway instance, as configured in ColdFusion MX Administrator.

originatorID

The IM ID (buddy name) of the message originator.

cfcMethod

This CFC method; by default, onIMServerMessage.

data.BUDDYNAME

The sender’s buddy name, or ID; identical to the originatorID.

data.BUDDYNICK
NAME

The buddy’s display name or nickname.

data.BUDDYSTATUS

The buddy’s status; one of the following:

  • ONLINE
  • OFFLINE
  • AWAY
  • DO NOT DISTURB

XMPP only

  • NOT AVAILABLE
  • FREE TO CHAT

Sametime only

  • IDLE

Use the IMGatewayHelper getCustomAwayMessage method to get any custom message that the buddy sent when changing status.

data.BUDDYGROUP

The group that the buddy belongs to.

data.RECIPIENT

The recipient’s ID, as specified in the gateway’s configuration file.

data.TIMESTAMP

The date and time when the message was sent.

Note: You configure the buddy’s nickname and group when you use the gatewayHelper object addBuddy method to add a buddy.

Returns

The function does not return a value.

Example

The following example keeps an Application scope structure up-to-date with a buddy’s status. It also uses the gatewayhelper object getBuddyStatus method to get the buddy’s custom away message, if any.

<cffunction name="onBuddyStatus">
    <cfargument name="CFEvent" type="struct" required="YES">
    <!--- Get the gatewayhelper object and to get the info for this buddy. --->
    <!--- This is used to get the buddy's custom away message. --->
    <cfset helper = getGatewayHelper("MYIM")>
    <cfset mybuddyinfo=helper.getBuddyInfo(CFEvent.Data.BUDDYNAME)>

    <cflog file="#CFEvent.GatewayID#Status" type="Information"
        text="in OnbuddyStatus, sender is #CFEvent.OriginatorID#">
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE">
        <cfscript>
        // Create the status structures if they don’t exist.
            if (NOT StructKeyExists(Application, "buddyStatus")) {
                Application.buddyStatus=StructNew();
            }
            if (NOT StructKeyExists(Application.buddyStatus,
                    CFEvent.Data.BUDDYNAME)) {
                Application.buddyStatus[#CFEvent.Data.BUDDYNAME#]=StructNew();
            }
            // Save the buddy status, timestamp, and custom away message
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].status=
                CFEvent.Data.BUDDYSTATUS;
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].timeStamp=
                CFEvent.Data.TIMESTAMP;
            // The following assumes that the buddy is in only one group.
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].customAway=
                mybuddyinfo[1].BUDDYCUSTOMAWAYMESSAGE;
        </cfscript>
    </cflock>
    <!--- log the info, for debugging purposes only --->
    <cfset temp=Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].status>
    <cflog file="#CFEvent.GatewayID#Status" type="Information" text=
        "Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].status is #temp#">
    <cfset temp=Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].timeStamp>
        <cflog file="#CFEvent.GatewayID#Status" type="Information" text=
         "Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].timestamp is #temp#">
        <cflog file="#CFEvent.GatewayID#Status" type="Information" text=
            "Buddy Custom Away Message is mybuddyinfo[1].BUDDYCUSTOMAWAYMESSAGE#">
</cffunchtion>


onIMServerMessage

Description

Handles incoming error and status messages from the IM server.

Syntax

onIMServerMessage(CFEvent)

See also

onIncomingMessage, onAddBuddyRequest, onAddBuddyResponse, onBuddyStatus

Parameters

This method must take one parameter, a CFEvent structure with the following fields:

Field | Description
gatewayType | Gateway type, either XMPP or SAMETIME
gatewayID | The ID of the gateway instance, as configured in ColdFusion MX Administrator
originatorID | The IM ID (buddy name) of the message originator
cfcMethod | This CFC method; by default, onIMServerMessage
data.MESSAGE | The message sent by the server
data.SENDER | The sender’s ID; identical to the originatorID
data.RECIPIENT | The recipient’s ID, as specified in the gateway’s configuration file
data.TIMESTAMP | The date and time when the message was sent

Example

The following example logs the sender, message, and a timestamp when an IM server sends an error or status message:

<cffunction name="onIMServerMessage">
    <!--- This function just logs the message. --->
    <cfargument name="CFEvent" type="struct" required="YES">
    <cflog file="#CFEvent.GatewayID#Status"
        text="onIMServerMEssage; SENDER: #CFEvent.OriginatorID#  MESSAGE:
#CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP#">
</cffunction>


onIncomingMessage

Description

Handles incoming instant messages from other users. Optionally returns a response to the message sender.

Syntax

onIncomingMessage(CFEvent)

See also

onAddBuddyRequest, onAddBuddyResponse, onBuddyStatus, onIMServerMessage, Handling incoming messages and Sample IM message handling application in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

The method must take one parameter, a CFEvent structure with the following fields:

Field | Description
gatewayType | Gateway type, either XMPP or SAMETIME.
gatewayID | The ID of the Gateway instance as configured in ColdFusion MX Administrator.
originatorID | The IM ID of the message originator.
cfcMethod | This CFC method; by default, onIncomingMessage.
data.MESSAGE | The message that was received.
data.SENDER | The sender’s ID; identical to the originatorID
data.RECIPIENT | The recipient’s ID, as specified in the gateway’s configuration file
data.TIMESTAMP | The date and time when the message was sent

Returns

The function can optionally return a value to send a response message. The return structure must contain the following fields:

Field | Description
command | Normally omitted. You can also specify submit.
buddyID | ID to which to send the message. Normally, the value of the input parameter’s Data.SENDER field.
message | The message contents.

Example

The following example shows a simple onIncomingMessage method that echoes a message back to the sender.

<cffunction name="onIncomingMessage">
    <cfargument name="CFEvent" type="struct" required="YES">
    <cfset input_mesg = CFEvent.data.MESSAGE>
    <cfset retValue = structNew()>
    <cfset retValue.command = "submit">
    <cfset retValue.buddyID = CFEvent.originatorID>
    <cfset retValue.message = "Message Received:" & input_mesg>
    <cfreturn retValue>
</cffunction>


IM gateway message sending commands

You use the SendGatewayMessage CFML function or the return value of a CFC listener method to send outgoing messages. The ColdFusion MX 7 IM gateway accepts the following outgoing message commands:

Command | Description
submit | (Default) Sends a normal message to another IM user.
accept | Accepts an add buddy request. Adds the buddy to the list of IDs that get your presence information and sends an acceptance message to the buddy ID.
decline | Declines an add buddy request and sends a rejection message to the buddy ID.
noact | Tells the gateway to take no action. The gateway logs a message that indicates that it took no action, and contains the gateway type, gateway ID, and buddy ID.

The message structure that you return in the gateway listener CFC function or use as the second parameter in the CFML SendGatewayMessage function can have the following fields. The table lists the fields and the commands in which they are used, and describes the field’s use.

Field | Commands | Description
buddyID | All | The destination user ID
command | All | The command; defaults to submit if omitted
message | submit | A text message to send to the destination user
reason | accept, decline | A text description of the reason for the action or other message to send to the add buddy requestor

In typical use, a ColdFusion application uses the accept, decline, and noact commands in the return value of the onAddBuddyRequest method, and uses the submit command (or no command, because submit is the default command) in SendGatewayMessage CFML functions and the return value of the onIncomingMessage CFC method.


IM Gateway GatewayHelper class methods

The GatewayHelper class returned by the CFML GetGatewayHelper function includes the following methods:

addBuddy

getDenyList

getStatusAsString

removeDeny

addDeny

getName

getStatusTimeStamp

removePermit

addPermit

getNickName

isOnline

setNickName

getBuddyInfo

getPermitList

numberOfMessagesReceived

setPermitMode

getBuddyList

getPermitMode

numberOfMessagesSent

setStatus

getCustomAwayMessage

getProtocolName

removeBuddy


addBuddy

Description

Adds a buddy to the buddy list for the gateway user ID and asks to have the IM server send messages with the buddy’s online presence state to the gateway.

Syntax

Boolean = addBuddy(name, nickname, group)

See also

getBuddyInfo, getBuddyList, removeBuddy, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person about whom you want to receive periodic status messages.
nickname | The nickname that the application can use to refer to the user.
group | The name of the group you wish to add the user to in your Buddy List. If the group specified does not exist, it will be created. If the group parameter is the empty string, the gateway uses the General group.

Returns

True if the ID was added to the gateway’s buddy list; False, otherwise.

Usage

This method adds the buddy to the buddy list for the gateway’s ID and sends a subscription request (to automatically get presence information about the buddy’s online status) to the remote buddy. It does not wait for a response from the buddy, so it returns True (and the gateway adds the buddy to the list) even if the buddy denies the subscription request. Use the listener CFC onAddBuddyResponse method to monitor the buddy’s response. If the CFEvent.data.MESSAGE field value is decline, the listener method can call the gatewayHelper object removeBuddy method to remove the buddy from the buddy list.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


addDeny

Description

Tells the IM server to add the specified user to the deny list for the gateway’s user ID. If the gateway’s permit mode value is DENY_SOME, the specified user cannot receive messages on the gateway’s presence state.

Syntax

Boolean = addDeny(name, nickname, group)

See also

addPermit, getDenyList, getPermitList, getPermitMode, removeDeny, removePermit, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person about whom you want to deny access to status messages.
nickname | The nickname that the application can use to refer to the user. Can be the empty string.
group | The name of the group that you want to add the user to in your buddy list. If the group specified does not exist, it is created. If the group parameter is the empty string, the gateway uses the General group.

Returns

True if the ID was added to the deny list; False, otherwise.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns False.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


addPermit

Description

Tells the IM server to add the specified user to the permit list for the gateway’s user ID. If the gateway’s permit mode is PERMIT_SOME, the specified user receive messages on the gateway’s presence state.

Syntax

Boolean = addPermit(name, nickname, group)

See also

addDeny, getDenyList, getPermitList, getPermitMode, removeDeny, removePermit, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person about whom you want to deny access to status messages.
nickname | The nickname that the application can use to refer to the user. Can be the empty string.
group | The name of the group you want to add the user to in your Buddy List. If the group specified does not exist, it is created. If the group parameter is the empty string, the gateway uses the General group.

Returns

True if the ID was added to the permit list; false, otherwise.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns False.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getBuddyInfo

Description

Gets information about the specified user from the buddy list, deny list, and permit list.

Syntax

array = getBuddyInfo(name)

See also

addBuddy, getBuddyList, removeBuddy, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person about whom you want to get information.

Returns

An array of structures, with one structure for each information record found. The method finds one record for each group that the user belongs to in each of the lists (buddy, permit, deny) that contains the specified name. Each structure has the following fields. Some fields might not be meaningful for some IM protocols. If there is no information for a field, it is blank.

Field

Description

BUDDYNAME

The user’s unique ID.

BUDDYGROUP

The group to which the user belongs.

BUDDYNICKNAME

The nickname that you have assigned to the user.

BUDDYPROTOCOL

The instant messaging protocol. JABBER (for XMPP) or SAMETIME, or an empty string (if the server did not return a value).

BUDDYSTATUS

The user’s presence state, can by any of the following:

  • ONLINE
  • OFFLINE
  • AWAY
  • DND (displays as DO NOT DISTURB)

XMPP only

  • NA (displays as NOT AVAILABLE)
  • FREE_TO_CHAT (displays as FREE TO CHAT)

Sametime only

  • IDLE

BUDDYSIGNONTIME

The date and time when the user signed onto the IM server. Empty if the user is not currently signed on. Always an empty string for XMPP and Sametime.

BUDDYSTATUSTIME

The date and time when the user’s status most recently changed.

BUDDYCUSTOM
AWAYMESSAGE

The custom away message that the user has set to explain the current status, if any.

BUDDYOWNER

A string representing the client and protocol associated with this ID, in the format client@protocol.

BUDDYLISTTIYPE

The type of list that this buddy record is in; one of the following:

  • BUDDY_LIST The list of users whose presence status information the gateway can receive.
  • DENY_LIST The list of users who cannot get presence information about the gateway ID.
  • PERMIT_LIST The list of users who can send presence information messages to the gateway ID.
  • REVERSE_LIST The list of users who do not allow messages to us.

BUDDYIDLETIME

If the buddy status is IDLE, how long the buddy has been idle. Always 0 for XMPP or SameTime.

BUDDYISMOBILE

True or False, indicating whether the user is on a mobile device. Always False for XMPP or SameTime.

BUDDYWARNING
PERCENT

The user’s warning percentage value. Always 0 for XMPP or SameTime.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods. For an example of using this method to get the buddy custom away message, see onBuddyStatus.


getBuddyList

Description

Gets the buddy list for the gateway’s user ID.

Syntax

array = getBuddyList()

See also

addBuddy, getBuddyInfo, removeBuddy, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

An array of IDs (buddy names) of the users on the gateway’s buddy list, a list of instant messaging IDs that this gateway normally communicates with.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getCustomAwayMessage

Description

Returns the gateway’s custom away message if it has been set by the gatewayHelper object setStatus method.

Syntax

string = getCustomAwayMessage()

See also

getStatusAsString, getStatusTimeStamp, isOnline, setStatus, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Returns

The gateway’s custom away message if it has been set by the GatewayHelper object setStatus method.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getDenyList

Description

Returns the list of users that the IM server has been told not to send state information about the gateway, if the permit mode is set to DENY_SOME.

Syntax

array = getDenyList()

See also

addDeny, addPermit, getPermitList, getPermitMode, removeDeny, removePermit, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Returns

An array of IDs (buddy names) of the users on the gateway’s deny list, the list of IDs to which the IM server does not send presence status information.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns False.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getName

Description

Returns the gateway's user name.

Syntax

string = getName()

See also

getProtocolName, numberOfMessagesReceived, numberOfMessagesSent, setNickName, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Returns

The gateway’s user name, as specified in gateway configuration file.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getNickName

Description

Returns the gateway’s nickname (display name), if it has been set using the gatewayHelper object setNickName method.

Syntax

string = getNickName()

See also

getName, getProtocolName, numberOfMessagesReceived, numberOfMessagesSent, setNickName, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Returns

The gateway’s nickname, if any; empty string, otherwise.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getPermitList

Description

Returns the list of users that the IM server has been told to send state information about the gateway.

Syntax

array = getPermitList()

See also

addDeny, addPermit, getDenyList, getPermitMode, removeDeny, removePermit, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways of ColdFusion MX Developer’s Guide

Returns

An array of IDs (buddy names) of the users on the gateway’s permit list, the list of IDs to which the IM server sends presence status information if the permit mode is set to PERMIT_SOME.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns False.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getPermitMode

Description

Gets the gateway’s permit mode from the IM server. The permit mode determines whether all users can get the gateway’s online state information, or whether the server uses a permit list or a deny list to control which users get state information.

Syntax

string = getPermitMode()

See also

addDeny, addPermit, getDenyList, getPermitList, removeDeny, removePermit, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

The gateway’s permit mode; one of the following values:

Mode | Description
PERMIT_ALL | (Default) Permits all users to be aware of the gateway’s online presence and state.
PERMIT_SOME | Permits only users in the permit list to be aware of the gateway’s online presence and state.
DENY_SOME | Prevents the users in the deny list from being aware of the gateway’s online presence and state.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns PERMIT_ALL.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getProtocolName

Description

Gets the name of the gateway’s instant messaging protocol.

Syntax

string = getProtocolName()

See also

getName, getNickName, numberOfMessagesReceived, numberOfMessagesSent, setNickName, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

The gateway’s protocol, as determined by the gateway type; one of the following values:

  • JABBER (for XMPP)
  • SAMETIME

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getStatusAsString

Description

Gets the online status of the gateway as a text string.

Syntax

string = getStatusAsString()

See also

getCustomAwayMessage, getStatusTimeStamp, isOnline, setStatus, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

The gateway’s online status; one of the following:

  • ONLINE
  • OFFLINE
  • AWAY
  • DO NOT DISTURB

XMPP only

  • NOT AVAILABLE
  • FREE TO CHAT

Sametime only

  • IDLE

Usage

The DO NOT DISTURB, NOT AVAILABLE, and FREE TO CHAT strings differ from the status values that you use in the setStatus method, which does not allow spaces in the status names.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


getStatusTimeStamp

Description

Gets the date and time that the gateway changed its online status.

Syntax

date-time object = getStatusTimeStamp()

See also

getCustomAwayMessage, getStatusAsString, isOnline, setStatus, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

The date and time that the gateway changed its online status, normally by calling the setStatus gatewayHelper object method.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


isOnline

Description

Determines whether the gateway is connected to the instant messaging server.

Syntax

Boolean = isOnline()

See also

getCustomAwayMessage, getStatusAsString, getStatusTimeStamp, setStatus, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

True, if the gateway is connected to the IM server; False, otherwise.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


numberOfMessagesReceived

Description

Gets the number of messages received by the gateway since it was started.

Syntax

integer = numberOfMessagesReceived()

See also

getName, getNickName, getProtocolName, numberOfMessagesSent, setNickName, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

The number of messages received by the gateway since it was started.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


numberOfMessagesSent

Description

Gets the number of messages sent by the gateway since it was started.

Syntax

integer = numberOfMessagesSent()

See also

getName, getNickName, getProtocolName, numberOfMessagesReceived, setNickName, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Returns

The number of messages sent by the gateway since it was started.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


removeBuddy

Description

Removes an ID from a group in the buddy list for the gateway and tells the IM server not to send the gateway messages with the buddy’s online presence state.

Syntax

Boolean = removeBuddy(name, group)

See also

addBuddy, getBuddyInfo, getBuddyList, removeDeny, removePermit, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person to remove from the buddy list.
group | The name of the group from which you want to remove the user. If the parameter is the empty string, the gateway uses the General group.

Returns

True if the ID was removed from the group; False, otherwise.

Usage

If the user is in multiple groups in your buddy list, you remove the buddy separately from each group. The IM server does not stop sending status updates until you remove the name from all groups.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


removeDeny

Description

Removes an ID from a group in the deny list for the gateway. If the gateway’s permit mode is DENY_SOME, the specified user can receive messages on the gateway’s presence state.

Syntax

Boolean = removeDeny(name, group)

See also

addDeny, addPermit, getDenyList, getPermitList, getPermitMode, removeBuddy, removePermit, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person to remove from the deny list.
group | The name of the group from which you want to remove the user. If the parameter is the empty string, the gateway uses the General group.

Returns

True if the ID was removed from the group; False, otherwise.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns False.

Usage

If the user is in multiple groups in your deny list, you remove the user separately from each group. The IM server enables sending status updates if you remove the name any group.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


removePermit

Description

Removes an ID from a group in the permit list for the gateway. If the gateway’s permit mode is PERMIT_SOME, the specified user cannot receive messages on the gateway's presence state.

Syntax

Boolean = removePermit(name, group)

See also

addDeny, addPermit, getDenyList, getPermitList, getPermitMode, removeBuddy, removeDeny, setPermitMode, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The unique instant messaging user name for the person to remove from the permit list.
group | The name of the group from which you want to remove the user. If the parameter is the empty string, the gateway uses the General group.

Returns

True if the ID was removed from the group; False, otherwise.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function always returns False.

Usage

If the user is in multiple groups in your permit list, you remove the user separately from each group. However, the IM server stops sending status updates when you remove the user from the first group.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


setNickName

Description

Sets the gateway’s nickname (display name).

Syntax

Boolean = setNickName(name)

See also

getName, getNickName, getProtocolName, numberOfMessagesReceived, numberOfMessagesSent, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter | Description
name | The display name that you want to associate with this gateway. This name is not guaranteed to be unique for the protocol.

Returns

True if the nickname got set; false, otherwise.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


setPermitMode

Description

Sets the gateway’s permit mode on the IM server. The permit mode determines whether all users can get the gateway's online state information, or whether the server uses a permit list or a deny list to control which users get state information.

Syntax

Boolean = setPermitMode(permitMode)

See also

addDeny, addPermit, getDenyList, getPermitList, getPermitMode, removeDeny, removePermit, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

permitMode

The permission mode, one of the following:

  • PERMIT_ALL Permits all users to be aware of the gateway’s online presence and state. This is the default mode if you do not call this function.
  • PERMIT_SOME Permits only users in the permit list to be aware of the gateway’s online presence and state.
  • DENY_SOME Prevents all users in the deny list from being aware of the gateway’s online presence and state.

Returns

True if the permit mode was set; False otherwise.

Note: XMPP permission management is included in the XMPP 1.0 draft specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management. If the server does not support permission management, this function returns False to all values except PERMIT_ALL.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


setStatus

Description

Sets the online presence status of the gateway, including any custom away message.

Syntax

Boolean = setStatus(status, customAwayMsg)

See also

getCustomAwayMessage, getStatusAsString, getStatusTimeStamp, isOnline, Using the GatewayHelper object in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide

Parameters

Parameter

Description

status

The gateway’s online presence status; one of the following:

  • ONLINE
  • AWAY
  • DND (Do Not Disturb)

XMPP only

  • NA (Not Available)
  • FREE_TO_CHAT

Sametime only:

  • IDLE

customAwayMsg

A text string containing a custom message for the status. Can be the empty string if you do not need a custom away message.

Returns

True, if the operation was successful; False. otherwise. Passing an invalid status for the protocol causes this method to return False.

Usage

Do not use the setStatus method to go offline. Although the method accepts a parameter of OFFLINE, the gateway immediately resets itself to be online. To set the gateway offline, stop the gateway instance in the ColdFusion MX Administrator, or use the stopGatewayInstance method in the CFIDE.adminapi.eventgateway CFC.

Example

See GatewayHelper example, in Using the Instant Messaging Event Gateways in ColdFusion MX Developer’s Guide, which uses all GatewayHelper class methods.


SMS Gateway CFEvent structure and commands

This section describes the detailed contents of the following structures that you use in the SMS Gateway listener CFCs and CFML SendGatewayMessage functions:

  • SMS Gateway incoming message CFEvent structure
  • SMS gateway message sending commands


SMS Gateway incoming message CFEvent structure

The SMS gateway puts the following information in a CFEvent instance that it sends to the CFC listener method:

Field

Value

OriginatorID

Contents of the PDU source_addr field, the address of the device that sent the message.

CfcMethod

Listener CFC method name. Value of the configuration file cfc-method entry, or onIncomingMessage if the configuration file does not have this entry.

Data.MESSAGE

Contents of the short_message field of the PDU.

Data.sourceAddress

The address of the device that sent this message.

Data.destAddress

The address to which the message was sent; an address in the range specified by the gateway configuration file address-range setting.

Data.esmClass

Contents of the PDU esm_class field. Identifies the message type. A number in the range 0-255 representing a Byte value, where bits 2-5 (0-indexed) indicate the message type, and therefore the contents of the data.MESSAGE field, as follows. (Reserved values are omitted.)

xx0000xx Normal message

xx0001xx SMSC delivery receipt

xx0010xx SME Delivery Acknowledgement

xx0100xx SME Manual/User Acknowledgement

xx0110xx Conversation abort (Korean CDMA only)

xx1000xx Intermediate Delivery Notification

For more information on this field, see the SMPP specification.

Data.protocol

Contents of the PDU protocol_id field. Meaningful for messages sent from GSM networks only. For more information, see the GSM 03.40 specification.

Data.priority

Contents of the PDU priority_flag field. A message priority level set by the originating SME, in the range 0-3; 0 is the lowest priority and 3 is the highest priority. The specific priority level meaning depends on the originating network. For more details, see the SMPP specification.

Data.registeredDelivery

Contents of the PDU registered_delivery field, indicating the type of delivery receipt or acknowledgement that the sender requested. A number in the range 0-32, representing the sum of the following values:

0 No SMS delivery receipt requested or
1 SMSC delivery receipt requested on delivery success or failure or
2 SMSC delivery receipt requested on delivery failure only

Plus

0 No SME acknowledgement requested or
4 SME Delivery Acknowledgement requested or
8 SME Manual/User Acknowledgement requested or
12 Both Delivery and Manual/User Acknowledgements requested

Plus

0 No Intermediate notification requested or
16 Intermediate notification requested

Data.DataCoding

Contents of the PDU data_coding field. Indicates the character set or the noncharacter data type of the message contents, as follows:

00000000 SMSC Default Alphabet

00000001 IA5 (CCITT T.50)/ASCII (ANSI X3.4)

00000010 Octet unspecified (8-bit binary)

00000011 Latin 1 (ISO-8859-1)

00000100 Octet unspecified (8-bit binary)

00000101 JIS (X 0208-1990)

00000110 Cyrillic (ISO-8859-5)

00000111 Latin/Hebrew (ISO-8859-8)

00001000 UCS2 (ISO/IEC-10646)

00001001 Pictogram Encoding

00001010 ISO-2022-JP (Music Codes)

00001101 Extended Kanji JIS(X 0212-1990)

00001110 KS C 5601

11xxxxxx GSM control use only; see the GSM 03.38 specification

For more details, see the SMPP specification.

data.messageLength

The length of the short_message field.

GatewayType

Always SMS.

For more information on the meanings of some of these fields and how to handle incoming SMS messages an SMS gateway listener CFC method, see Handling incoming messages in Using the SMS Event Gateway in ColdFusion MX Developer’s Guide.


SMS gateway message sending commands

ColdFusion applications that use gateways of the Short Message Service (SMS) type can send the following commands to the event gateway in an outgoing message:

  • submit command
  • submitMulti command
  • data command


submit command

To send a message to a single destination address in an SMPP SUBMIT_SM PDU, the structure that you used in the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method has the following fields. For more information about these fields, see the documentation for the SUBMIT_MULTI PDU in the SMPP3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

Required fields

Field | Contents
command | If present, the value must be submit. If you omit this field, the event gateway sends a submit message.
shortMessage or messagePayload | The message contents. You must specify one of these fields, but not both. The SMPP specification imposes a maximum size of 254 bytes on the shortMessage field, and some carriers might limit its size further. The messagePayload field can contain up to 64K bytes; it must start with 0x0424, followed by two bytes specifying the payload length, followed by the message contents.
destAddress | Required. The address to which to send the message.
sourceAddress | The address of this application. You can omit this field; the configuration file specifies the application address.

Optional fields

You can set default values for the following optional fields in the SMS event gateway configuration file. For information on the default values, see Configuring an SMS event gateway in Using the SMS Event Gateway in ColdFusion MX Developer’s Guide.

destAddress_npi

destAddress_ton

serviceType

The following optional fields do not have default values:

alertOnMsgDelivery | EsmClass | priorityFlag | smDefaultMsgId
callbackNum | ItsReplyType | PrivacyIndicator | SmsSignal
callbackNumAtag | ItsSessionInfo | protocolId | SourceAddrSubunit
callbackNumPresInd | LanguageIndicator | registeredDelivery | SourcePort
dataCoding | MoreMsgsToSend | replaceIfPresent | SourceSubaddress
DestAddrSubunit | MsMsgWaitFacilities | SarMsgRefNum | UserMessageReference
DestinationPort | MsValidity | SarSegmentSeqnum | UserResponseCode
DestSubaddress | NumberOfMessages | SarTotalSegments | UssdServiceOp
DisplayTime | PayloadType | scheduleDeliveryTime | validityPeriod

Example

The following example onIncomingMessage method of a listener CFC uses the submit command to echo incoming SMS messages to the message originator:

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Create a return structure that contains the message. --->
    <cfset retValue = structNew()>
    <cfset retValue.command = "submit">
    <cfset retValue.destAddress = arguments.CFEvent.originatorid>
    <cfset retValue.shortMessage = "Echo: " & CFEvent.Data.MESSAGE>
    <!--- Send the message back. --->
    <cfreturn retValue>
</cffunction>


submitMulti command

To send a single text message to multiple recipients using an SMPP SUBMIT_MULTI PDU, the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method usually has the following fields. For more information about these fields, see the documentation for the SUBMIT_MULTI PDU in the SMPP3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

Required fields

Field | Contents
command | Must be submitMulti.
shortMessage or messagePayload | The message contents. You must specify one of these fields, but not both. The SMPP specification imposes a maximum size of 254 bytes on the shortMessage field, and some carriers might limit its size further. The messagePayload field can contain up to 64K bytes; it must start with 0x0424, followed by two bytes specifying the payload length, followed by the message contents.
destAddress | A ColdFusion array of destination addresses (required). You cannot specify individual TON and NPI values for these addresses; all must conform to a single setting.
sourceAddress | The address of this application. You can omit this field; the configuration file specifies the application address.

Optional fields

The following optional fields can have default values set in the SMS event gateway configuration file. For information on the default values see Configuring an SMS event gateway in Using the SMS Event Gateway in ColdFusion MX Developer’s Guide.

destAddress_npi

destAddress_ton

serviceType

The following optional fields do not have default values:

alertOnMsgDelivery | DisplayTime | protocolId | SmsSignal
callbackNum | EsmClass | registeredDelivery | SourceAddrSubunit
callbackNumAtag | LanguageIndicator | replaceIfPresent | SourcePort
callbackNumPresInd | MsMsgWaitFacilities | SarMsgRefNum | SourceSubaddress
dataCoding | MsValidity | SarSegmentSeqnum | UserMessageReference
DestAddrSubunit | PayloadType | SarTotalSegments | validityPeriod
DestinationPort | priorityFlag | scheduleDeliveryTime |
DestSubaddress | PrivacyIndicator | smDefaultMsgId |

Example

The following example onIncomingMessage method sends a response that echoes an incoming message to the originator address, and sends a copy of the response to a second address:

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Get the message. --->
    <cfset data=cfevent.DATA>
    <cfset message="#data.message#">
    <!--- Create the return structure. --->
    <cfset retValue = structNew()>
    <cfset retValue.command = "submitmulti">
    <cfset retValue.destAddresses=arraynew(1)>
    <!--- One destination is incoming message originator;
                    get the address from CFEvent originator ID. --->
    <cfset retValue.destAddresses[1] = arguments.CFEvent.originatorid>
    <cfset retValue.destAddresses[2] = "12345">
    <cfset retValue.shortMessage = "echo: " & message>
<cfreturn retValue>
</cffunction>


data command

To send binary data to a single destination address in an SMPP DATA_SM PDU, the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method must have the following fields. For more information about these fields, see the documentation for the SUBMIT_MULTI PDU in the SMPP3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

Required fields

Field | Contents
command | Must be data.
messagePayload | The message data. To convert data to binary format, use the ColdFusion MX ToBinary function.
destAddress | The address to which to send the message.
sourceAddress | The address of this application. You can omit this field; the configuration file specifies the application address.

Optional fields

The following optional fields can have default values set in the SMS event gateway configuration file. For information on the default values see Configuring an SMS event gateway in Using the SMS Event Gateway in ColdFusion MX Developer’s Guide.

destAddress_npi

destAddress_ton

serviceType

The following optional fields do not have default values:

alertOnMsgDelivery | DestTelematicsId | NetworkErrorCode | SetDpf
callbackNum | DisplayTime | NumberOfMessages | SmsSignal
callbackNumAtag | EsmClass | PayloadType | SourceAddrSubunit
callbackNumPresInd | ItsReplyType | PrivacyIndicator | SourceBearerType
dataCoding | ItsSessionInfo | QosTimeToLive | SourceNetworkType
DestAddrSubunit | LanguageIndicator | ReceiptedMessgeId | SourcePort
DestBearerType | MessageState | registeredDelivery | SourceSubaddress
DestNetworkType | MoreMsgsToSend | SarMsgRefNum | SourceTelematicsId
DestinationPort | MsMsgWaitFacilities | SarSegmentSeqnum | UserMessageReference
DestSubaddress | MsValidity | SarTotalSegments | UserResponseCode

Example

The following example onIncomingMessage method converts an incoming message to binary data, and sends the binary version of the message back to the originator address:

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Get the message --->
    <cfset data=CFEvent.DATA>
    <cfset message="#data.message#">
    <!--- Create the return structure --->
    <cfset retValue = structNew()>
    <cfset retValue.command = "data">
    <!--- Sending to incoming message originator; get value from CFEvent. --->
    <cfset retValue.destAddress = arguments.CFEvent.originatorid>
    <cfset retValue.messagePayload = tobinary(tobase64("echo: " & message))>
    <cfreturn retValue>
</cffunction>


CFML event gateway SendGatewayMessage data parameter

The ColdFusion CFML gateway type enables you to invoke CFC methods asynchronously. The structure that you use in the SendGatewayMessage function data parameter can include two types of fields:

  • Any number of fields can contain arbitrary contents for use in by the CFC.
  • Several optional fields can configure how the gateway delivers the information to the CFC.

The CFML gateway looks for the following optional fields, and, if they exist, uses them to determine how it delivers the message. Do not use these field names for data that you send to your CFC method.

Field | Use
cfcpath | Overrides the CFC path specified in the ColdFusion MX Administrator. This field lets you use a single gateway configuration in the ColdFusion MX Administrator multiple CFCs. This field sets the CFEvent object CFCPath variable.
method | Specifies the name of the method to invoke in the CFC. The default method is onIncomingMessage. This field lets you use a single gateway configuration in the ColdFusion MX Administrator for a CFC that has several methods. This field sets the CFEvent object CFCMethod variable.
originatorID | Sets the originatorID field of the CFEvent object that ColdFusion MX delivers to the CFC. The default value is CFMLGateway.
timeout | Sets the time-out, in seconds, during which the listener CFC must process the event request and return before ColdFusion gateway services terminates the request. The default value is the Timeout Request value set on the Server Settings page in the ColdFusion MX Administrator. Set this value if a request might validly take longer to process than the default time-out; for example, if the request involves a very long processing time. This field sets the CFEvent object CFCTimeout variable.

Example

The following example consists of a CFML page that sends a message to a logevent method in the file logger.CFC. The CFML page specifies the CFC and method to call, and sets the OriginatorID.

<h3>Sending an event using a generic CFML event gateway and specifying the CFC and method.</h3>
<cfscript>
    status = False;
    props = structNew();
    props.cfcpath="C:\CFusionMX7\gateway\cfc\MyCFCs\logger.cfc";
    props.method="logEvent";
    props.OriginatorID=CGI.SCRIPT_NAME;
    props.Message="Replace me with a variable with data to log";
    props.file="GenericCFCtest";
    props.type="warning";
    status = SendGatewayMessage("DefaultCFC", props);
    if (status IS True)
        WriteOutput('Event Message "#props.Message#" has been sent.');
</cfscript>

The CFC method uses the OriginatorID and the message, file, and type fields of the CFEvent parameter’s data field to specify the log file and message.

<cfcomponent>
    <cffunction name="logEvent" output="no">
        <cfargument name="CFEvent" type="struct" required="yes">
         <cfscript>
            if (NOT IsDefined("CFEvent.Data.file")) {
                CFEvent.Data.file="defaultEventLog"; }
            if (NOT IsDefined("CFEvent.Data.type")) {
                CFEvent.Data.type="information"; }
        </cfscript>
        <cflog text="Message from #CFEvent.originatorID#: #CFEvent.Data.message#"
            file="#CFEvent.data.file#" type="#CFEvent.Data.type#" >
    </cffunction>
</cfcomponent>

Previous


ColdFusion C++ CFX Reference

This chapter describes the Macromedia ColdFusion MX 7 CFXAPI classes and methods.

Contents

C++ class overview

Deprecated class methods

CCFXException class

CCFXQuery class

CCFXRequest class

CCFXStringSet class
Next


C++ class overview

The following table lists the CFXAPI classes and methods:

Class | Methods
CCFXException class | CCFXException::GetError CCFXException::GetDiagnostics
CCFXQuery class | CCFXQuery::AddRow CCFXQuery::GetColumns CCFXQuery::GetData CCFXQuery::GetName CCFXQuery::GetRowCount CCFXQuery::SetData
CCFXRequest class | CCFXRequest::AddQuery CCFXRequest::AttributeExists CCFXRequest::CreateStringSet CCFXRequest::Debug CCFXRequest::GetAttribute CCFXRequest::GetAttributeList CCFXRequest::GetCustomData CCFXRequest::GetQuery CCFXRequest::ReThrowException CCFXRequest::SetCustomData CCFXRequest::SetVariable CCFXRequest::ThrowException CCFXRequest::Write CCFXRequest::WriteDebug
CCFXStringSet class | CCFXStringSet::AddString CCFXStringSet::GetCount CCFXStringSet::GetIndexForString CCFXStringSet::GetString


Deprecated class methods

The following CFXAPI classes and methods are deprecated. They do not work, and might cause an error, in later releases.

Class | Deprecated member | Deprecated as of this ColdFusion release
CCFXQuery Class | CCFXQuery::SetQueryString CCFXQuery::SetTotalTime | ColdFusion MX ColdFusion MX
CCFXRequest Class | CCFXRequest::GetSetting | ColdFusion MX


CCFXException class

An abstract class that represents an exception thrown during processing of a ColdFusion Extension (CFX) procedure.

Exceptions of this type can be thrown by CCFXRequest class, CCFXQuery class, and CCFXStringSet class. Your ColdFusion Extension code must be written to handle exceptions of this type. For more information, see CCFXRequest::ThrowException and CCFXRequest::ReThrowException.

Class methods

virtual LPCSTR GetError()

The CCFXException::GetError function returns a general error message.

virtual LPCSTR GetDiagnostics()

The CCFXException::GetDiagnostics function returns detailed error information.

CCFXException::GetError

Description

Provides basic user output for exceptions that occur during processing.

CCFXException::GetDiagnostics

Description

Provides detailed user output for exception that occur during processing.

Example

This code block shows how GetError and GetDiagnostics work with ThrowException and ReThrowException.

// Write output back to the user here...
pRequest->Write( "Hello from CFX_FOO2!" ) ;
pRequest->ThrowException("User Error", "You goof'd...");

// Output optional debug info
if ( pRequest->Debug() )
{
                    pRequest->WriteDebug( "Debug info..." ) ;
}

// Catch ColdFusion exceptions & re-raise them
catch( CCFXException* e )
{
                    // This is how you would pull the error information
                    LPCTSTR strError = e->GetError();
                    LPCTSTR strDiagnostic = e->GetDiagnostics();

                    pRequest->ReThrowException( e ) ;
}

// Catch ALL other exceptions and throw them as
// ColdFusion exceptions (DO NOT REMOVE! --
// this prevents the server from crashing in
// case of an unexpected exception)
catch( ... )
{
                    pRequest->ThrowException(
                    "Error occurred in tag CFX_FOO2",
                    "Unexpected error occurred while processing tag." ) ;
}


CCFXQuery class

An abstract class that represents a query used or created by a ColdFusion Extension (CFX). Queries contain one or more columns of data that extend over a varying number of rows.

Class methods

virtual int AddRow()

CCFXQuery::AddRow adds a row to a query.

virtual CCFXStringSet* GetColumns

CCFXQuery::GetColumns retrieves a list of a query's column names.

virtual LPCSTR GetData( int iRow, int iColumn )

CCFXQuery::GetData retrieves a data element from a row and column of a query.

virtual LPCSTR GetName()

CCFXQuery::GetName retrieves the name of a query.

virtual int GetRowCount()

CCFXQuery::GetRowCount retrieves the number of rows in a query.

virtual void SetData( int iRow, int iColumn, LPCSTR lpszData )

CCFXQuery::SetData sets a data element within a row and column of a query.

virtual void SetQueryString( LPCSTR lpszQuery )

This function is deprecated. It might not work, and might cause an error, in later releases.

virtual void SetTotalTime( DWORD dwMilliseconds )

This function is deprecated. It might not work, and might cause an error, in later releases.


CCFXQuery::AddRow

Syntax

int CCFXQuery::AddRow(void)

Description

Add a row to the query. Call this function to append a row to a query.

Returns

Returns the index of the row that was appended to a query.

Example

The following example shows the addition of two rows to a three-column ('City', 'State', and 'Zip') query:

// First row
int iRow ;
iRow = pQuery->AddRow() ;
pQuery->SetData( iRow, iCity, "Minneapolis" ) ;
pQuery->SetData( iRow, iState, "MN" ) ;
pQuery->SetData( iRow, iZip, "55345" ) ;

// Second row
iRow = pQuery->AddRow() ;
pQuery->SetData( iRow, iCity, "St. Paul" ) ;
pQuery->SetData( iRow, iState, "MN" ) ;
pQuery->SetData( iRow, iZip, "55105" ) ;


CCFXQuery::GetColumns

Syntax

CCFXStringSet* CCFXQuery::GetColumns(void)

Description

Retrieves a list of the column names contained in a query.

Returns

Returns an object of CCFXStringSet class that contains a list of the columns in the query. ColdFusion automatically frees the memory that is allocated for the returned string set, after the request is completed.

Example

The following example gets the list of columns, then iterates over the list, writing each column name back to the user:

// Get the list of columns from the query
CCFXStringSet* pColumns = pQuery->GetColumns() ;
int nNumColumns = pColumns->GetCount() ;

// Print the list of columns to the user
pRequest->Write( "Columns in query: " ) ;
for( int i=1; i<=nNumColumns; i++ )
{
    pRequest->Write( pColumns->GetString( i ) ) ;
    pRequest->Write( " " ) ;
}


CCFXQuery::GetData

Syntax

LPCSTR CCFXQuery::GetData(int iRow, int iColumn)

Description

Gets a data element from a row and column of a query. Row and column indexes begin with 1. You can determine the number of rows in a query by calling CCFXQuery::GetRowCount. You can determine the number of columns in a query by retrieving the list of columns using CCFXQuery::GetColumns, and then calling CCFXStringSet::GetCount on the returned string set.

Returns

Returns the value of the requested data element.

Parameters

Parameter | Description
iRow | Row to retrieve data from (1-based)
iColumn | Column to retrieve data from (1-based)

Example

The following example iterates over the elements of a query and writes the data in the query back to the user in a simple, space-delimited format:

int iRow, iCol ;
int nNumCols = pQuery->GetColumns()->GetCount() ;
int nNumRows = pQuery->GetRowCount() ;
for ( iRow=1; iRow<=nNumRows; iRow++ )
{
    for ( iCol=1; iCol<=nNumCols; iCol++ )
    {
    pRequest->Write( pQuery->GetData( iRow, iCol ) ) ;
    pRequest->Write( " " ) ;
    }
    pRequest->Write( "<BR>" ) ;
}


CCFXQuery::GetName

Syntax

LPCSTR CCFXQuery::GetName(void)

Description

Returns the name of a query.

Example

The following example retrieves the name of a query and writes it back to the user:

CCFXQuery* pQuery = pRequest->GetQuery() ;
pRequest->Write( "The query name is: " ) ;
pRequest->Write( pQuery->GetName() ) ;


CCFXQuery::GetRowCount

Syntax

int CCFXQuery::GetRowCount(void)

Description

Returns the number of rows contained in a query.

Example

The following example retrieves the number of rows in a query and writes it back to the user:

CCFXQuery* pQuery = pRequest->GetQuery() ;
char buffOutput[256] ;
wsprintf( buffOutput,
    "The number of rows in the query is %ld.",
    pQuery->GetRowCount() ) ;
pRequest->Write( buffOutput ) ;


CCFXQuery::SetData

Syntax

void CCFXQuery::SetData(int iRow, int iColumn, LPCSTR lpszData)

Description

Sets a data element within a row and column of a query. Row and column indexes begin with 1. Before calling SetData for a given row, call CCFXQuery::AddRow and use the return value as the row index for your call to SetData.

Parameters

Parameter | Description
iRow | Row of data element to set (1-based)
iColumn | Column of data element to set (1-based)
lpszData | New value for data element

Example

The following example shows the addition of two rows to a three-column ('City', 'State', and 'Zip') query:

// First row
int iRow ;
iRow = pQuery->AddRow() ;
pQuery->SetData( iCity, iRow, "Minneapolis" ) ;
pQuery->SetData( iState, iRow, "MN" ) ;
pQuery->SetData( iZip, iRow, "55345" ) ;

// Second row
iRow = pQuery->AddRow() ;
pQuery->SetData( iCity, iRow, "St. Paul" ) ;
pQuery->SetData( iState, iRow, "MN" ) ;
pQuery->SetData( iZip, iRow, "55105" ) ;


CCFXRequest class

Abstract class that represents a request made to a ColdFusion Extension (CFX). An instance of this class is passed to the main function of your extension DLL. The class provides interfaces that can be used by the custom extension for the following actions:

  • Reading and writing variables
  • Returning output
  • Creating and using queries
  • Throwing exceptions

Class methods

virtual BOOL AttributeExists
( LPCSTR lpszName )

CCFXRequest::AttributeExists checks whether the attribute was passed to the tag.

virtual LPCSTR GetAttribute
( LPCSTR lpszName )

CCFXRequest::GetAttribute gets the value of the passed attribute.

virtual CCFXStringSet* GetAttributeList()

CCFXRequest::GetAttributeList gets an array of attribute names passed to the tag.

virtual CCFXQuery* GetQuery()

CCFXRequest::GetQuery gets the query that was passed to the tag.

virtual LPCSTR GetSetting( LPCSTR lpszSettingName )

CCFXRequest::GetSetting

This method is deprecated. It might not work, and might cause an error, in later releases.

virtual void Write( LPCSTR lpszOutput )

CCFXRequest::Write writes text output back to the user.

virtual void SetVariable( LPCSTR lpszName, LPCSTR lpszValue )

CCFXRequest::SetVariable sets a variable in the template that contains this tag.

virtual CCFXQuery* AddQuery( LPCSTR lpszName, CCFXStringSet* pColumns )

CCFXRequest::AddQuery adds a query to the template that contains this tag.

virtual BOOL Debug()

CCFXRequest::Debug checks whether the tag contains the Debug attribute.

virtual void WriteDebug( LPCSTR lpszOutput )

CCFXRequest::WriteDebug writes text output into the debug stream.

virtual CCFXStringSet* CreateStringSet()

CCFXRequest::CreateStringSet allocates and returns a CCFXStringSet instance.

virtual void ThrowException( LPCSTR lpszError, LPCSTR lpszDiagnostics )

CCFXRequest::ThrowException throws an exception and ends processing of this request.

virtual void ReThrowException
( CCFXException* e )

CCFXRequest::ReThrowException re-throws an exception that has been caught.

virtual void SetCustomData( LPVOID lpvData )

CCFXRequest::SetCustomData sets custom (tag specific) data to carry with a request.

virtual LPVOID GetCustomData()

CCFXRequest::GetCustomData gets custom (tag specific) data for a request.


CCFXRequest::AddQuery

Syntax

CCFXQuery* CCFXRequest::AddQuery(LPCSTR lpszName,
CCFXStringSet* pColumns)

Description

Adds a query to the calling template. The query can be accessed by CFML tags (for example, CFOUTPUT or CFTABLE) within the template. After calling AddQuery, the query is empty (it has 0 rows). To populate the query with data, call the CCFXQuery::AddRow and CCFXQuery::SetData functions.

Returns

Returns a pointer to the query that was added to the template (an object of class CCFXQuery). The memory allocated for the returned query is freed automatically by ColdFusion after the request is completed.

Parameters

Parameter | Description
lpszName | Name of query to add to the template (must be unique)
pColumns | List of column names to be used in the query

Example

The following example adds a query named 'People' to the calling template. The query has two columns ('FirstName' and 'LastName') and two rows:

// Create a string set and add the column names to it
CCFXStringSet* pColumns = pRequest->CreateStringSet() ;
int iFirstName = pColumns->AddString( "FirstName" ) ;
int iLastName = pColumns->AddString( "LastName" ) ;

// Create a query that contains these columns
CCFXQuery* pQuery = pRequest->AddQuery( "People", pColumns ) ;

// Add data to the query
int iRow ;
iRow = pQuery->AddRow() ;
pQuery->SetData( iRow, iFirstName, "John" ) ;
pQuery->SetData( iRow, iLastName, "Smith" ) ;
iRow = pQuery->AddRow() ;
pQuery->SetData( iRow, iFirstName, "Jane" ) ;
pQuery->SetData( iRow, iLastName, "Doe" ) ;


CCFXRequest::AttributeExists

Syntax

BOOL CCFXRequest::AttributeExists(LPCSTR lpszName)

Description

Checks whether the parameter was passed to the tag. Returns True if the parameter is available; False, otherwise.

Parameters

Parameter | Description
lpszName | Name of the parameter to check (case insensitive)

Example

The following example checks whether the user passed an attribute named DESTINATION to the tag, and throws an exception if the attribute was not passed:

if ( pRequest->AttributeExists("DESTINATION")==FALSE )
{
    pRequest->ThrowException(
        "Missing DESTINATION parameter",
        "You must pass a DESTINATION parameter in "
        "order for this tag to work correctly." ) ;
}


CCFXRequest::CreateStringSet

Syntax

CCFXStringSet* CCFXRequest::CreateStringSet(void)

Description

Allocates and returns an instance. Always use this function to create string sets, as opposed to directly using the new operator.

Returns

Returns an object of CCFXStringSet class. The memory allocated for the returned string set is freed automatically by ColdFusion after the request is completed

Example

The following example creates a string set and adds three strings to it:

CCFXStringSet* pColors = pRequest->CreateStringSet() ;
pColors->AddString( "Red" ) ;
pColors->AddString( "Green" ) ;
pColors->AddString( "Blue" ) ;


CCFXRequest::Debug

Syntax

BOOL CCFXRequest::Debug(void)

Description

Checks whether the tag contains the Debug attribute. Use this function to determine whether to write debug information for a request. For more information, see CCFXRequest::WriteDebug.

Returns

Returns True if the tag contains the Debug attribute; False, otherwise.

Example

The following example checks whether the Debug attribute is present, and if it is, it writes a brief debug message:

if ( pRequest->Debug() )
{
                    pRequest->WriteDebug( "Top secret debug info" ) ;
}


CCFXRequest::GetAttribute

Syntax

LPCSTR CCFXRequest::GetAttribute(LPCSTR lpszName)

Description

Retrieves the value of the passed attribute. Returns an empty string if the attribute does not exist. (To test whether an attribute was passed to the tag, use CCFXRequest::AttributeExists.)

Returns

Returns the value of the attribute passed to the tag. If no attribute of that name was passed to the tag, an empty string is returned.

Parameters

Parameter | Description
lpszName | Name of the attribute to retrieve (case insensitive)

Example

The following example retrieves an attribute named DESTINATION and writes its value back to the user:

LPCSTR lpszDestination = pRequest->GetAttribute("DESTINATION") ;
pRequest->Write( "The destination is: " ) ;
pRequest->Write( lpszDestination ) ;


CCFXRequest::GetAttributeList

Syntax

CCFXStringSet* CCFXRequest::GetAttributeList(void)

Description

Gets an array of attribute names passed to the tag. To get the value of one attribute, use CCFXRequest::GetAttribute.

Returns

Returns an object of class CCFXStringSet class that contains a list of attributes passed to the tag. The memory allocated for the returned string set is freed automatically by ColdFusion after the request is completed.

Example

The following example gets the list of attributes and iterates over the list, writing each attribute and its value back to the user.

LPCSTR lpszName, lpszValue ;
CCFXStringSet* pAttribs = pRequest->GetAttributeList() ;
int nNumAttribs = pAttribs->GetCount() ;

for( int i=1; i<=nNumAttribs; i++ )
{
                    lpszName = pAttribs->GetString( i ) ;
                    lpszValue = pRequest->GetAttribute( lpszName ) ;
                    pRequest->Write( lpszName ) ;
                    pRequest->Write( " = " ) ;
                    pRequest->Write( lpszValue ) ;
                    pRequest->Write( "<BR>" ) ;
}


CCFXRequest::GetCustomData

Syntax

LPVOID CCFXRequest::GetCustomData(void)

Description

Gets the custom (tag specific) data for the request. This method is typically used from within subroutines of a tag implementation to extract tag data from a request.

Returns

Returns a pointer to the custom data, or NULL if no custom data has been set during this request using CCFXRequest::SetCustomData.

Example

The following example retrieves a pointer to a request specific data structure of hypothetical type MYTAGDATA:

void DoSomeGruntWork( CCFXRequest* pRequest )
{
        MYTAGDATA* pTagData =
            (MYTAGDATA*)pRequest->GetCustomData() ;

        ... remainder of procedure ...
}


CCFXRequest::GetQuery

Syntax

CCFXQuery* CCFXRequest::GetQuery(void)

Description

Retrieves a query that was passed to a tag. To pass a query to a custom tag, you use the QUERY attribute. This attribute should be set to the name of a query (created using the cfquery tag or another custom tag). The QUERY attribute is optional and should be used only by tags that process an existing data set.

Returns

Returns an object of the CCFXQuery class that represents the query passed to the tag. If no query was passed to the tag, NULL is returned. The memory allocated for the returned query is freed automatically by ColdFusion after the request is completed.

Example

The following example retrieves the query that was passed to the tag. If no query was passed, an exception is thrown:

CCFXQuery* pQuery = pRequest->GetQuery() ;
if ( pQuery == NULL )
{
                    pRequest->ThrowException(
                        "Missing QUERY parameter",
                        "You must pass a QUERY parameter in "
                        "order for this tag to work correctly." ) ;
}


CCFXRequest::ReThrowException

Syntax

void CCFXRequest::ReThrowException(CCFXException* e)

Description

Re-throws an exception that has been caught within an extension procedure. This function is used to avoid having C++ exceptions that are thrown by DLL extension code propagate back into ColdFusion. Catch ALL C++ exceptions that occur in extension code, and either re-throw them (if they are of the CCFXException class) or create and throw a new exception pointer using CCFXRequest::ThrowException.

Parameters

Parameter | Description
e | A CCFXException that has been caught

Example

The following code demonstrates how to handle exceptions in ColdFusion Extension DLL procedures:

try
{
                    ...Code that could throw an exception...
}
catch( CCFXException* e )
{
                    ...Do appropriate resource cleanup here...
                    // Re-throw the exception
                    pRequest->ReThrowException( e ) ;
}
catch( ... )
{
                    // Something nasty happened

                    pRequest->ThrowException(
                    "Unexpected error occurred in CFX tag", "" ) ;
}


CCFXRequest::SetCustomData

Syntax

void CCFXRequest::SetCustomData(LPVOID lpvData)

Description

Sets custom (tag specific) data to carry with the request. Use this function to store request specific data to pass to procedures within your custom tag implementation.

Parameters

Parameter | Description
lpvData | Pointer to custom data

Example

The following example creates a request-specific data structure of hypothetical type MYTAGDATA and stores a pointer to the structure in the request for future use:

void ProcessTagRequest( CCFXRequest* pRequest )
        try
        {
                    MYTAGDATA tagData ;
                    pRequest->SetCustomData( (LPVOID)&tagData ) ;

                    ... remainder of procedure ...
}


CCFXRequest::SetVariable

Syntax

void CCFXRequest::SetVariable(LPCSTR lpszName, LPCSTR lpszValue)

Description

Sets a variable in the calling template. If the variable name already exists in the template, its value is replaced. If it does not exist, a variable is created. The values of variables created using SetVariable can be accessed in the same manner as other template variables (for example, #MessageSent#).

Parameters

Parameter | Description
lpszName | Name of variable
lpszValue | Value of variable

Example

The following example sets the value of a variable named 'MessageSent' based on the success of an operation performed by the custom tag:

BOOL bMessageSent;
...attempt to send the message...
if ( bMessageSent == TRUE )
{
                    pRequest->SetVariable( "MessageSent", "Yes" ) ;
}
else
{
                    pRequest->SetVariable( "MessageSent", "No" ) ;
}


CCFXRequest::ThrowException

Syntax

void CCFXRequest::ThrowException(LPCSTR lpszError,
LPCSTR lpszDiagnostics)

Description

Throws an exception and ends processing of a request. Call this function when you encounter an error that does not allow you to continue processing the request. This function is almost always combined with the CCFXRequest::ReThrowException to protect against resource leaks in extension code.

Parameters

Parameter | Description
lpszError | Short identifier for error
lpszDiagnostics | Error diagnostic information

Example

The following example throws an exception indicating that an unexpected error occurred while processing a request:

char buffError[512] ;
wsprintf( buffError,
        "Unexpected Windows NT error number %ld "
        "occurred while processing request.", GetLastError() ) ;

pRequest->ThrowException( "Error occurred", buffError ) ;


CCFXRequest::Write

Syntax

void CCFXRequest::Write(LPCSTR lpszOutput)

Description

Writes text output back to the user.

Parameters

Parameter | Description
lpszOutput | Text to output

Example

The following example creates a buffer to hold an output string, fills the buffer with data, and writes the output back to the user:

CHAR buffOutput[1024] ;
wsprintf( buffOutput, "The destination is: %s",
        pRequest->GetAttribute("DESTINATION") ) ;
pRequest->Write( buffOutput ) ;


CCFXRequest::WriteDebug

Syntax

void CCFXRequest::WriteDebug(LPCSTR lpszOutput)

Description

Writes text output into the debug stream. The text is only displayed to the end-user if the tag contains the Debug attribute. (For more information, see CCFXRequest::Debug.)

Parameters

Parameter | Description
lpszOutput | Text to output

Example

The following example checks whether the Debug attribute is present; if so, it writes a brief debug message:

if ( pRequest->Debug() )
{
                    pRequest->WriteDebug( "Top secret debug info" ) ;
}


CCFXStringSet class

Abstract class that represents a set of ordered strings. Strings can be added to a set and can be retrieved by a numeric index (index values for strings are 1-based). To create a string set, use CCFXRequest::CreateStringSet.

Class methods

virtual int AddString( LPCSTR lpszString )

CCFXStringSet::AddString adds a string to the end of a list.

virtual int GetCount()

CCFXStringSet::GetCount gets the number of strings contained in a list.

virtual LPCSTR GetString( int iIndex )

CCFXStringSet::GetString gets the string located at the passed index.

virtual int GetIndexForString
( LPCSTR lpszString )

CCFXStringSet::GetIndexForString gets the index for the passed string.


CCFXStringSet::AddString

Syntax

int CCFXStringSet::AddString(LPCSTR lpszString)

Description

Adds a string to the end of the list.

Returns

The index of the string that was added.

Parameters

Parameter | Description
lpszString | String to add to the list

Example

The following example demonstrates adding three strings to a string set and saving the indexes of the items that are added:

CCFXStringSet* pSet = pRequest->CreateStringSet() ;
int iRed = pSet->AddString( "Red" ) ;
int iGreen = pSet->AddString( "Green" ) ;
int iBlue = pSet->AddString( "Blue" ) ;


CCFXStringSet::GetCount

Syntax

int CCFXStringSet::GetCount(void)

Description

Gets the number of strings in a string set. The value can be used with CCFXStringSet::GetString to iterate over the strings in the set (recall that the index values for strings in the list begin at 1).

Returns

Returns the number of strings contained in the string set.

Example

The following example demonstrates using GetCount with CCFXStringSet::GetString to iterate over a string set and write the contents of the list back to the user:

int nNumItems = pStringSet->GetCount() ;
for ( int i=1; i<=nNumItems; i++ )
{
                    pRequest->Write( pStringSet->GetString( i ) ) ;
                    pRequest->Write( "<BR>" ) ;
}


CCFXStringSet::GetIndexForString

Syntax

int CCFXStringSet::GetIndexForString(LPCSTR lpszString)

Description

Searches for a passed string. The search is case-insensitive.

Returns

If the string is found, its index within the string set is returned. If it is not found, the constant CFX_STRING_NOT_FOUND is returned.

Parameters

Parameter | Description
lpszString | String to search for

Example

The following example demonstrates a search for a string and throwing an exception if it is not found:

CCFXStringSet* pAttribs = pRequest->GetAttributeList() ;

int iDestination =
        pAttribs->GetIndexForString("DESTINATION") ;
if ( iDestination == CFX_STRING_NOT_FOUND )
{
                    pRequest->ThrowException(
                    "DESTINATION attribute not found."
                    "The DESTINATION attribute is required "
                    "by this tag." ) ;
}


CCFXStringSet::GetString

Syntax

LPCSTR CCFXStringSet::GetString(int iIndex)

Description

Retrieves the string located at the passed index (index values are 1-based).

Returns

Returns the string located at the passed index.

Parameters

Parameter | Description
iIndex | Index of string to retrieve

Example

The following example demonstrates GetString with CCFXStringSet::GetCount to iterate over a string set and write the contents of a list back to the user:

int nNumItems = pStringSet->GetCount() ;
for ( int i=1; i<=nNumItems; i++ )
{
                    pRequest->Write( pStringSet->GetString( i ) ) ;
                    pRequest->Write( "<BR>" ) ;
}

Previous


ColdFusion Java CFX Reference

This chapter describes the Java interfaces available for building Macromedia ColdFusion MX 7 custom CFXs in Java.

Contents

Class libraries overview

Custom tag interface

Query interface

Request interface

Response interface

Debugging classes reference
Next


Class libraries overview

The following Java interfaces are available for building ColdFusion custom CFXs in Java:

Interface | Methods
Custom tag interface | processRequest
Query interface | addRow getColumnIndex getColumns getData getName getRowCount setData
Request interface | attributeExists debug getAttribute getAttributeList getIntAttribute getQuery getSetting
Response interface | addQuery setVariable write writeDebug


Custom tag interface

public abstract interface CustomTag

Interface for implementing custom tags.

Classes that implement this interface can be specified in the CLASS attribute of the Java CFX tag. For example, in a class MyCustomTag, which implements this interface, the following CFML code calls the MyCustomTag.processRequest method:

<CFX_MyCustomTag>

Other attributes can be passed to the Java CFX tag. Their values are available using the Request object passed to the processRequest method.

Methods

Returns | Syntax | Description
void | processRequest(Request request, Response response) | Processes a request originating from the CFX_mycustomtag tag


processRequest

Description

Processes a request originating from the Java CFX tag.

Category

Custom tag interface

Syntax

public void processRequest(Request request, Response response)

Throws

Exception If an unexpected error occurs while processing the request.

Parameters

Parameter | Description
request | Parameters (attributes, query, and so on.) for this request
response | Interface for generating response to request (output, variables, queries, and so on)


Query interface

public abstract interface Query

Interface to a query used or created by a custom tag. A query contains tabular data organized by named columns and rows.

Methods

Returns

Method

Description

int

addRow ()

Adds a row to the query

int

getColumnIndex (String name)

Gets the index of a column given its name

String[]

getColumns ()

Gets a list of the column names in a query

String

getData (int iRow, int iCol)

Gets a data element from a row and column of a query

String

getName ()

Gets the name of a query

int

getRowCount ()

Gets the number of rows in a query

void

setData (int iRow, int iCol,
String data)

Sets a data element in a row and column of a query


addRow

Description

Adds a row to a query. Call this method to append a row to a query.

Returns the index of the row that was appended to the query.

Category

Query interface

Syntax

public int addRow()

See also

setData, getData

Example

The following example demonstrates the addition of two rows to a query that has three columns, City, State, and Zip:

// Define column indexes
int iCity = 1, iState = 2, iZip = 3 ;

// First row
int iRow = query.addRow() ;
query.setData( iRow, iCity, "Minneapolis" ) ;
query.setData( iRow, iState, "MN" ) ;
query.setData( iRow, iZip, "55345" ) ;
// Second row
iRow = query.addRow() ;
query.setData( iRow, iCity, "St. Paul" ) ;
query.setData( iRow, iState, "MN" ) ;
query.setData( iRow, iZip, "55105" ) ;


getColumnIndex

Description

Returns the index of the column, or 0 if no such column exists.

Category

Query interface

Syntax

public int getColumnIndex(String name)

See also

getColumns, getData

Parameters

Parameter | Description
name | Name of column to get index of (lookup is case-insensitive)

Example

The following example retrieves the index of the EMAIL column and uses it to output a list of the addresses contained in the column:

// Get the index of the EMAIL column
int iEMail = query.getColumnIndex( "EMAIL" ) ;

// Iterate over the query and output list of addresses
int nRows = query.getRowCount() ;
for( int iRow = 1; iRow <= nRows; iRow++ )
{
    response.write( query.getData( iRow, iEMail ) + "<BR>" ) ;
}


getColumns

Description

Returns an array of strings containing the names of the columns in the query.

Category

Query interface

Syntax

public String[] getColumns()

Example

The following example retrieves the array of columns, then iterates over the list, writing each column name back to the user:

// Get the list of columns from the query
String[] columns = query.getColumns() ;
int nNumColumns = columns.length ;

// Print the list of columns to the user
response.write( "Columns in query: " ) ;
for( int i=0; i<nNumColumns; i++ )
{
    response.write( columns[i] + " " ) ;
}


getData

Description

Retrieves a data element from a row and column of a query. Row and column indexes begin with 1. You can find the number of rows in a query by calling getRowCount. You can find the number of columns in a query by calling getColumns.

Returns the value of the requested data element.

Category

Query interface

Syntax

public String getData(int iRow, int iCol)

Throws

IndexOutOfBoundsException If an invalid index is passed to the method.

See also

setData, addRow

Parameters

Parameter | Description
iRow | Row to retrieve data from (1-based)
iCol | Column to retrieve data from (1-based)

Example

The following example iterates over the rows of a query and writes the data back to the user in a simple, space-delimited format:

int iRow, iCol ;
int nNumCols = query.getColumns().length ;
int nNumRows = query.getRowCount() ;
for ( iRow = 1; iRow <= nNumRows; iRow++ )
{
    for ( iCol = 1; iCol <= nNumCols; iCol++ )
    {
        response.write( query.getData( iRow, iCol ) + " " ) ;
    }
    response.write( "<BR>" ) ;
}


getName

Description

Returns the name of a query.

Category

Query interface

Syntax

public String getName()

Example

The following example retrieves the name of a query and writes it back to the user:

Query query = request.getQuery() ;
    response.write( "The query name is: " + query.getName() ) ;


getRowCount

Description

Retrieves the number of rows in a query.

Returns the number of rows contained in a query.

Category

Query interface

Syntax

public int getRowCount()

Example

The following example retrieves the number of rows in a query and writes it back to the user:

Query query = request.getQuery() ;
    int rows = query.getRowCount() ;
    response.write( "The number of rows in the query is "
    + Integer.ToString(rows) ) ;


setData

Description

Sets a data element in a row and column of a query. Row and column indexes begin with 1. Before calling setData for a given row, call addRow and use the return value as the row index for your call to setData.

Category

Query interface

Syntax

public void setData(int iRow, int iCol, String data)

Throws

IndexOutOfBoundsException If an invalid index is passed to the method.

See also

getData, addRow

Parameters

Parameter | Description
iRow | Row of data element to set (1-based)
iCol | Column of data element to set (1-based)
data | New value for data element

Example

The following example demonstrates the addition of two rows to a query that has three columns, City, State, and Zip:

// Define column indexes
int iCity = 1, iState = 2, iZip = 3 ;

// First row
int iRow = query.addRow() ;
query.setData( iRow, iCity, "Minneapolis" ) ;
query.setData( iRow, iState, "MN" ) ;
query.setData( iRow, iZip, "55345" ) ;

// Second row
iRow = query.addRow() ;
query.setData( iRow, iCity, "St. Paul" ) ;
query.setData( iRow, iState, "MN" ) ;
query.setData( iRow, iZip, "55105" ) ;


Request interface

public abstract interface Request

Interface to a request made to a CustomTag. The interface includes methods for retrieving attributes passed to the tag (including queries) and reading global tag settings.

Methods

Returns

Syntax

Description

boolean

attributeExists(String name)

Checks whether the attribute was passed to this tag.

boolean

debug()

Checks whether the tag contains the debug attribute.

String

getAttribute(String name)

Retrieves the value of the passed attribute.

String[]

getAttributeList()

Retrieves a list of attributes passed to the tag.

int

getIntAttribute(String name)

Retrieves the value of the passed attribute as an integer.

int

getIntAttribute(String name,
int def)

Retrieves the value of the passed attribute as an integer (returns default if the attribute does not exist or is not a valid number).

Query

getQuery()

Retrieves the query that was passed to this tag.


attributeExists

Description

Checks whether the attribute was passed to this tag.

Returns True if the attribute is available; otherwise returns False.

Category

Request interface

Syntax

public boolean attributeExists(String name)

See also

getAttribute, getAttributeList

Parameters

Parameter | Description
name | Name of the attribute to check (case-insensitive)

Example

The following example checks whether the user passed an attribute named DESTINATION to the tag; if not, it throws an exception:

if ( ! request.attributeExists("DESTINATION") )
{
    throw new Exception(
    "Missing DESTINATION parameter",
    "You must pass a DESTINATION parameter in "
    "order for this tag to work correctly." ) ;
} ;


debug

Description

Checks whether the tag contains the debug attribute. Use this method to determine whether to write debug information for this request. For more information, see writeDebug.

Returns True if the tag contains the debug attribute; False, otherwise.

Category

Request interface

Syntax

public boolean debug()

See also

writeDebug

Example

The following example checks whether the debug attribute is present, and if so, it writes a brief debug message:

if ( request.debug() )
{
    response.writeDebug( "debug info" ) ;
}


getAttribute

Description

Retrieves the value of a passed attribute. Returns an empty string if the attribute does not exist (use attributeExists to test whether an attribute was passed to the tag). Use getAttribute(String,String) to return a default value rather than an empty string.

Returns the value of the attribute passed to the tag. If no attribute of that name was passed to the tag, an empty string is returned.

Category

Request interface

Syntax

public String getAttribute(String name)

See also

attributeExists, getAttributeList, getIntAttribute, getAttribute

Parameters

Parameter | Description
name | The attribute to retrieve (case-insensitive)

Example

The following example retrieves an attribute named DESTINATION and writes its value back to the user:

String strDestination = request.getAttribute("DESTINATION") ;
response.write( "The destination is: " + strDestination ) ;


getAttributeList

Description

Retrieves a list of attributes passed to the tag. To retrieve the value of one attribute, use the getAttribute method.

Returns an array of strings containing the names of the attributes passed to the tag.

Category

Request interface

Syntax

public String[] getAttributeList()

See also

attributeExists, getAttributeList

Example

The following example retrieves the list of attributes, then iterates over the list, writing each attribute and its value back to the user:

String[] attribs = request.getAttributeList() ;
int nNumAttribs = attribs.length ;

for( int i = 0; i < nNumAttribs; i++ )
{
    String strName = attribs[i] ;
    String strValue = request.getAttribute( strName ) ;
    response.write( strName + "=" + strValue + "<BR>" ) ;
}


getIntAttribute

Description

Retrieves the value of the passed attribute as an integer. Returns -1 if the attribute does not exist. Use attributeExists to test whether an attribute was passed to the tag. Use getIntAttribute(String,int) to return a default value rather than throwing an exception or returning -1.

Returns the value of the attribute passed to the tag. If no attribute of that name was passed to the tag, -1 is returned.

Category

Request interface

Syntax

public int getIntAttribute(String name)

Throws

NumberFormatException If the attribute is not a valid number.

See also

attributeExists, getAttributeList, getIntAttribute

Parameters

Parameter | Description
name | The attribute to retrieve (case-insensitive)

Example

The following example retrieves an attribute named PORT and writes its value back to the user:

int nPort = request.getIntAttribute("PORT") ;
if ( nPort != -1 )
    response.write( "The port is: " + String.valueOf(nPort) ) ;


getQuery

Description

Retrieves the query that was passed to this tag.

To pass a query to a custom tag, you use the query attribute. It should be set to the name of a query (created using the cfquery tag). The query attribute is optional and should be used only by tags that process an existing dataset.

Returns the Query that was passed to the tag. If no query was passed, returns null.

Category

Request interface

Syntax

public Query getQuery()

Example

The following example retrieves a query that was passed to a tag. If no query was passed, an exception is thrown:

Query query = request.getQuery() ;
if ( query == null )
{
    throw new Exception(
    "Missing QUERY parameter. " +
    "You must pass a QUERY parameter in "
    "order for this tag to work correctly." ) ;
}


getSetting

Description

Retrieves the value of a global custom tag setting. Custom tag settings are stored in the CustomTags section of the ColdFusion Registry key.

Returns the value of the custom tag setting. If no setting of that name exists, an empty string is returned.

Category

Request interface

Syntax

public String getSetting(String name)

Parameters

Parameter | Description
name | The name of the setting to retrieve (case-insensitive)

Usage

All custom tags implemented in Java share a registry key for storing settings. To avoid name conflicts, preface the names of settings with the name of your custom tag class. For example, the code below retrieves the value of a setting named VerifyAddress for a custom tag class named MyCustomTag:

String strVerify = request.getSetting("MyCustomTag.VerifyAddress") ;
if ( Boolean.valueOf(strVerify) )
{
    // Do address verification...
}


Response interface

public abstract interface Response

Interface to response generated from a custom tag. This interface includes methods for writing output, generating queries, and setting variables in the calling page.

Methods

Returns | Syntax | Description
Query | addQuery (String name, String[] columns) | Adds a query to the calling template.
void | setVariable (String name, String value) | Sets a variable in the calling template.
void | write (String output) | Outputs text back to the user.
void | writeDebug (String output) | Writes text output into the debug stream.


addQuery

Description

Adds a query to the calling template. The query can be accessed by CFML tags in the template. After calling addQuery, the query is empty (it has 0 rows). To populate the query with data, call the Query methods addRow and setData.

Returns the Query that was added to the template.

Category

Response interface

Syntax

public Query addQuery(String name, String[] columns)

Throws

IllegalArgumentException If the name parameter is not a valid CFML variable name.

See also

addRow, setData

Parameters

Parameter | Description
name | The name of the query to add to the template
columns | The column names to use in the query

Example

The following example adds a query named People to the calling template. The query has two columns (FirstName and LastName) and two rows:

// Create string array with column names (also track columns indexes)
String[] columns = { "FirstName", "LastName" } ;
int iFirstName = 1, iLastName = 2 ;

// Create a query which contains these columns
Query query = response.addQuery( "People", columns ) ;

// Add data to the query
int iRow = query.addRow() ;
query.setData( iRow, iFirstName, "John" ) ;
query.setData( iRow, iLastName, "Smith" ) ;
iRow = query.addRow() ;
query.setData( iRow, iFirstName, "Jane" ) ;
query.setData( iRow, iLastName, "Doe" ) ;


setVariable

Description

Sets a variable in the calling template. If the variable name specified exists in the template, its value is replaced. If it does not exist, a new variable is created.

Category

Response interface

Syntax

public void setVariable(String name, String value)

Throws

IllegalArgumentException If the name parameter is not a valid CFML variable name.

Parameters

Parameter | Description
name | The name of the variable to set
value | The value to set the variable to

Example

For example, this code sets the value of a variable named MessageSent based on the success of an operation performed by the custom tag:

boolean bMessageSent ;

    ...attempt to send the message...

    if ( bMessageSent == true )
    {
        response.setVariable( "MessageSent", "Yes" ) ;
    }
    else
    {
        response.setVariable( "MessageSent", "No" ) ;
    }


write

Description

Outputs text back to the user.

Category

Response interface

Syntax

public void write(String output)

Parameters

Parameter | Description
output | Text to output

Example

The following example outputs the value of the DESTINATION attribute:

response.write( "DESTINATION = " +
    request.getAttribute("DESTINATION") ) ;


writeDebug

Description

Writes text output into the debug stream. This text is displayed to the end-user only if the tag contains the debug attribute (check for this attribute using the Request.debug method).

Category

Response interface

Syntax

public void writeDebug(String output)

See also

debug

Parameters

Parameter | Description
output | The text to output

Example

The following example checks whether the debug attribute is present; if so, it writes a brief debug message:

if ( request.debug() )
{
    response.writeDebug( "debug info" ) ;
}


Debugging classes reference

The constructors and methods supported by the DebugRequest, DebugResponse, and DebugQuery classes are as follows. These classes also support the other methods of the Request, Response, and Query interfaces, respectively.

DebugRequest

// initialize a debug request with attributes
public DebugRequest( Hashtable attributes ) ;

// initialize a debug request with attributes and a query
public DebugRequest( Hashtable attributes, Query query ) ;

// initialize a debug request with attributes, a query, and settings
public DebugRequest( Hashtable attributes, Query query,
                     Hashtable settings ) ;


DebugResponse

// initialize a debug response
public DebugResponse() ;

// print the results of processing
public void printResults() ;

DebugQuery

// initialize a query with name and columns
public DebugQuery( String name, String[] columns )
   throws IllegalArgumentException ;

// initialize a query with name, columns, and data
public DebugQuery( String name, String[] columns, String[][] data )
    throws IllegalArgumentException ;

Previous


WDDX JavaScript Objects

This chapter provides information about JavaScript objects and functions used to WDDX in a Macromedia ColdFusion MX 7 application.

Contents

JavaScript object overview

WddxSerializer object

WddxRecordset object
Next


JavaScript object overview

These are the JavaScript objects and functions:

Class | Functions
WddxSerializer object | serialize serializeVariable serializeValue write
WddxRecordset object | addColumn addRows getField getRowCount setField wddxSerialize

WDDX JavaScript objects are defined in the wddx.js file; this file is installed in the CFIDE/scripts directory.

To use these objects, you must put a JavaScript tag before the code that refers to the objects; for example:

<script type="text/javascript" src="/CFIDE/scripts/wddx.js"></script>


WddxSerializer object

The WddxSerializer object includes functions that serialize any JavaScript data structure. For more information on using this object, see Using WDDX in Using XML and WDDX in ColdFusion MX Developer’s Guide.

Functions

The only function that developers typically call is serialize.

Function syntax | Description
object. serialize (rootobj) | Creates a WDDX packet for a passed WddxRecordset instance.
object. serializeVariable (name, obj) | Serializes a property of a structure. If an object is not a string, number, array, Boolean, or a date, WddxSerializer treats it as a structure.
object. serializeValue (obj) | Recursively serializes eligible data in a passed instance.
object. write (str) | Appends data to the serialized data stream.


serialize

Description

Creates a WDDX packet for a passed WddxRecordset instance.

Syntax

object.serialize( rootobj )

Parameters

Parameter | Description
object | Instance name of the WddxSerializer object
rootobj | JavaScript data structure to serialize

Return value

Returns a serialized WDDX packet as a string if the function succeeds, or a null value if an error occurs.

Usage

Call this function to serialize the data in a WddxRecordset instance.

Example

This example shows a JavaScript function that you can call to serialize a WddxRecordset instance. It copies serialized data to a form field for display:

function serializeData(data, formField)
{
    wddxSerializer = new WddxSerializer();
    wddxPacket = wddxSerializer.serialize(data);
    if (wddxPacket != null)
    {
        formField.value = wddxPacket;
    }
    else
    {
        alert("Couldn't serialize data");
    }
}


serializeVariable

Description

Serializes a property of a structure. If an object is not a string, number, array, Boolean, or date, WddxSerializer treats it as a structure.

Syntax

object.serializeVariable( name, obj )

Parameters

Parameter | Description
object | Instance name of a WddxSerializer object
name | Property to serialize
obj | Instance name of the value to serialize

Return value

Returns a Boolean True if serialization was successful; False, otherwise.

This is an internal function; you do not typically call it.

Example

This example is from the WddxSerializer serializeValue function:

...
// Some generic object; treat it as a structure
    this.write("<struct>");
    for (prop in obj)
    {
        bSuccess = this.serializeVariable(prop, obj[prop]);
        if (! bSuccess)
        {
            break;
        }
    }
    this.write("</struct>");
...


serializeValue

Description

Recursively serializes eligible data in a passed instance. Eligible data includes:

  • String
  • Number
  • Boolean
  • Date
  • Array
  • Recordset
  • Any JavaScript object

This function serializes null values as empty strings.

Syntax

object.serializeValue( obj )

Parameters

Parameter | Description
object | Instance name of the WddxSerializer object
obj | Instance name of the WddxRecordset object to serialize

Return value

Returns a Boolean True if obj was serialized successfully; False, otherwise.

Usage

This is an internal function; you do not typically call it.

Example

This example is from the WddxSerializer serialize function:

...
this.wddxPacket = "";
this.write("<wddxPacket version='1.0'><header/><data>");
bSuccess = this.serializeValue(rootObj);
this.write("</data></wddxPacket>");
if (bSuccess)
{
    return this.wddxPacket;
}
else
{
    return null;
}
...


write

Description

Appends data to a serialized data stream.

Syntax

object.write( str )

Parameters

Parameter | Description
object | Instance name of the WddxSerializer object
str | String to be copied to the serialized data stream

Return value

Returns an updated serialized data stream as a String.

Usage

This is an internal function; you do not typically call it.

Example

This example is from the WddxSerializer serializeValue function:

...
else if (typeof(obj) == "number")
{
    // Number value
    this.write("<number>" + obj + "</number>");
}
else if (typeof(obj) == "boolean")
{
    // Boolean value
    this.write("<boolean value='" + obj + "'/>");
}
...


WddxRecordset object

Includes functions that you call as needed when constructing a WDDX record set. For more information on using this object, see Using WDDX in Using XML and WDDX in ColdFusion MX Developer’s Guide.

Functions

Function syntax | Description
object. addColumn (name) | Adds a column to all rows in a WddxRecordset instance.
object. addRows (n) | Adds rows to all columns in a WddxRecordset instance.
object.dump(escapeStrings) | Displays WddxRecordset object data.
object. getField (row, col) | Returns the element in a row/column position.
object. getRowCount () | Indicates the number of rows in a WddxRecordset instance.
object. setField (row, col, value) | Sets the element in a row/column position.
object. wddxSerialize (serializer) | Serializes a record set.
:

Returns

HTML table of the WddxRecordset object data.

Usage

Convenient for debugging and testing record sets. The boolean parameter escapeStrings determines whether <>& characters in string values are escaped as &lt;&gt;&amp; in HTML.

Example

<!--- Create a simple query --->
<cfquery name = "q" datasource ="cfdocexamples">
SELECT Message_Id, Thread_id, Username, Posted
FROM messages
</cfquery>
<!--- Load the wddx.js file, which includes the dump function --->
<script type="text/javascript" src="/CFIDE/scripts/wddx.js"></script>
<script>
// Use WDDX to move from CFML data to JS
<cfwddx action="cfml2js" input="#q#" topLevelVariable="qj">
// Dump the record set
document.write(qj.dump(true));
</script>


addColumn

Description

Adds a column to all rows in a WddxRecordset instance.

Syntax

object.addColumn( name )

Parameters

Parameter | Description
object | Instance name of the WddxRecordset object
name | Name of the column to add

Return value

None.

Usage

Adds a column to every row of the WDDX record set. Initially the new column’s values are set to NULL.

Example

This example calls the addColumn function:

// Create a new record set
rs = new WddxRecordset();

// Add a new column
rs.addColumn("NewColumn");

// Extend the record set by 3 rows
rs.addRows(3);

// Set an element in the first row
// newValue is a previously defined variable
rs.setField(0, "NewColumn", newValue);


addRows

Description

Adds rows to all columns in a WddxRecordset instance.

Syntax

object.addRows( n )

Parameters

Parameter | Description
object | Instance name of the WddxRecordset object
n | Integer; number of rows to add

Return value

None.

Usage

This function adds the specified number of rows to every column of a WDDX record set. Initially, the row/column values are set to NULL.

Example

This example calls the addRows function:

// Create a new record set
rs = new WddxRecordset();

// Add a new column
rs.addColumn("NewColumn");

// Extend the record set by 3 rows
rs.addRows(3);

// Set an element in the first row
// newValue is a previously defined variable
rs.setField(0, "NewColumn", newValue);


getField

Description

Returns the element in the specified row/column position.

Syntax

object.getField( row, col )

Parameters

Parameter | Description
object | Instance name of the WddxRecordset object
row | Integer; zero-based row number of the value to return
col | Integer or string; column of the value to be returned.

Return value

Returns the value in the specified row/column position.

Usage

Call this function to access a value in a WDDX record set.

Example

This example calls the getField function (the variable r is a reference to a WddxRecordset instance):

for (row = 0; row < nRows; ++row)
{
    o += "<tr>";
    for (i = 0; i < colNames.length; ++i)
    {
        o += "<td>" + r.getField(row, colNames[i]) + "</td>";
    }
    o += "</tr>";
}


getRowCount

Description

Indicates the number of rows in a WddxRecordset instance.

Syntax

object.getRowCount( )

Parameters

Parameter | Description
object | Instance name of a WddxRecordset object

Return value

Integer. Returns the number of rows in the WddxRecordset instance.

Usage

Call this function before a looping construct to determine the number of rows in a record set.

Example

This example calls the getRowCount function:

function dumpWddxRecordset(r)
{
// Get row count
    nRows = r.getRowCount();
...
    for (row = 0; row < nRows; ++row)
...


setField

Description

Sets the element in the specified row/column position.

Syntax

object.setField( row, col, value )

Parameters

Parameter | Description
object | Instance name of a WddxRecordset object
row | Integer; row that contains the element to set
col | Integer or string; the column containing the element to set
value | Value to set

Return value

None.

Usage

Call this function to set a value in a WddxRecordset instance.

Example

This example calls the setField function:

// Create a new recordset
rs = new WddxRecordset();

// Add a new column
rs.addColumn("NewColumn");

// Extend the record set by 3 rows
rs.addRows(3);

// Set an element in the first row
// newValue is a previously defined variable
rs.setField(0, "NewColumn", newValue);


wddxSerialize

Description

Serializes a record set.

Syntax

object.wddxSerialize( serializer )

Parameters

Parameter | Description
object | Instance name of the WddxRecordset object
serializer | WddxSerializer instance

Return value

Returns a Boolean True if serialization was successful; False, otherwise.

Usage

This is an internal function; you do not typically call it.

Example

This example is from the WddxSerializer serializeValue function:

...
else if (typeof(obj) == "object")
{
if (obj == null)
{
// Null values become empty strings
this.write("<string></string>");
}
else if (typeof(obj.wddxSerialize) == "function")
{
// Object knows how to serialize itself
bSuccess = obj.wddxSerialize(this);
}
...

Previous


ColdFusion ActionScript Functions

This chapter explains the syntax and usage of the two Macromedia ColdFusion MX 7 server-side ActionScript functions, CF.query and CF.http.

Contents

CF.query

CF.http
Next


CF.query

Description

Performs queries against ColdFusion data sources.

Return value

Returns a RecordSet object.

Syntax

CF.query
    ({
        datasource:"data source name",
        sql:"SQL stmts",
        username:"username",
        password:"password",
        maxrows:number,
        timeout:milliseconds
    })

Arguments

Arguments | Req/Opt | Description
datasource | Required | Name of the data source from which the query retrieves data.
sql | Required | SQL statement.
username | Optional | Username. Overrides the username specified in the data source setup.
password | Optional | Password. Overrides the password specified in the data source setup.
maxrows | Optional | Maximum number of rows to return in the record set.
timeout | Optional | Maximum number of seconds for the query to execute before returning an error indicating that the query has timed out. Can only be used in named arguments.

Usage

You can code the CF.query function using named or positional arguments. You can invoke all supported arguments using the named argument style, as follows:

CF.query({datasource:"datasource", sql:"sql stmt",
    username:"username", password:"password", maxrows:"maxrows",
    timeout:"timeout"});

Note: The named argument style uses curly braces {} to surround the function arguments.

Positional argument style, which is a shorthand coding style, does not support all arguments. Use the following syntax to code the CF.query function using positional arguments:

CF.query(datasource, sql);
CF.query(datasource, sql, maxrows);
CF.query(datasource, sql, username, password);
CF.query(datasource, sql, username, password, maxrows);

Note: Do not use curly braces {} with positional arguments.

You can manipulate the record set returned by the CF.query function using methods in the RecordSet ActionScript class. The following are some of the methods available in the RecordSet class:

  • RecordSet.getColumnnames
  • RecordSet.getLength
  • RecordSet.getItemAt
  • RecordSet.getItemID
  • RecordSet.sortItemsBy
  • RecordSet.getNumberAvailable
  • RecordSet.filter
  • RecordSet.sort

For more information on using server-side ActionScript, see Using Server-Side ActionScript in ColdFusion MX Developer’s Guide. For more detailed information about the RecordSet ActionScript class, see Using Flash Remoting.

Example

// Define a function to do a basic query
// Note use of positional arguments
function basicQuery()
{
    result = CF.query("myquery", "cust_data", "SELECT * from tblParks");
    return result;
}

// Example function declaration using named arguments
function basicQuery()
{
    result = CF.query({datasource:"cust_data", sql:"SELECT * from tblParks"});
    return result;
}

// Example of the CF.query function using maxrows argument
function basicQueryWithMaxRows()
{
    result = CF.query("cust_data", "SELECT * from tblParks", 25);
    return result;
}

// Example of the CF.query function with username and password
function basicQueryWithUser()
{
    result = CF.query("cust_data", "SELECT * from tblParks",
        "wsburroughs", "migraine1");
    return result;
}


CF.http

Description

Executes HTTP POST and GET operations on files. (POST operations upload MIME file types to a server, or post cookie, formfield, URL, file, or CGI variables directly to a server.)

Return value

Returns an object containing properties that you reference to access data.

Syntax

CF.http
    ({
        method:"get or post",
        url:"URL",
        username:"username",
        password:"password",
        resolveurl:"yes or no",
        params:arrayvar,
        path:"path",
        file:"filename"
    })

Arguments

Arguments

Req/Opt

Description

method

Required

One of two arguments:

  • get: downloads a text or binary file or creates a query from the contents of a text file.
  • post: sends information to the server page or CGI program for processing. Requires the params argument.

url

Required

The absolute URL of the host name or IP address of the server on which the file resides. The URL must include the protocol (http or https) and host name.

username

Optional

When required by a server, a username.

password

Optional

When required by a server, a password.

resolveurl

Optional

For Get and Post methods.

  • Yes or No. Default is No.

For GET and POST operations, if Yes, the page reference that is returned into the Filecontent property has its internal URLs fully resolved, including port number, so that links remain intact. The following HTML tags, which can contain links, are resolved:

- img src

- a href

- form action

- applet code

- script src

- embed src

- embed pluginspace

- body background

- frame src

- bgsound src

- object data

- object classid

- object codebase

- object usemap

params

Optional

HTTP parameters passed as an array of objects. Supports the following parameter types:

  • name
  • type
  • value

CF.http params are passed as an array of objects. The params argument is required for POST operations.

path

Optional

The path to the directory in which to store files. When using the path argument, the file argument is required.

file

Optional

Name of the file that is accessed. For GET operations, defaults to the name specified in the url argument. Enter path information in the path argument. This argument is required if you are using the path argument.

Usage

You can write the CF.http function using named arguments or positional arguments. You can invoke all supported arguments using the named argument style, as follows:

CF.http({method:"method", url:"URL", username:"username", password:"password",
    resolveurl:"yes or no", params:arrayvar,
    path:"path", file:"filename"});

Note: The named argument style uses curly braces {} to surround the function arguments.

Positional arguments let you use a shorthand coding style. However, not all arguments are supported for the positional argument style. Use the following syntax to code the CF.http function using positional arguments:

CF.http(url);
CF.http(method, url);
CF.http(method, url, username, password);
CF.http(method, url, params, username, password);

Note: Do not use curly braces {} with positional arguments.

The following parameters can only be passed as an array of objects in the params argument in the CF.http function:

Parameter

Description

name

The variable name for data that is passed

type

The transaction type:

  • URL
  • FormField
  • Cookie
  • CGI
  • File

value

Value of URL, FormField, Cookie, File, or CGI variables that are passed

The CF.http function returns data as a set of object properties, as described in the following table:

Property

Description

Text

A Boolean value that indicates whether the specified URL location contains text data.

Charset

The charset used by the document specified in the URL.

HTTP servers normally provide this information, or the charset is specified in the charset parameter of the Content-Type header field of the HTTP protocol. For example, the following HTTP header announces that the character encoding is EUC-JP:

Content-Type: text/html; charset=EUC-JP

Header

Raw response header. For example, macromedia.com returns the following header:

HTTP/1.1 200 OK

Date: Mon, 04 Mar 2002 17:27:44 GMT

Server: Apache/1.3.22 (Unix) mod_perl/1.26

Set-Cookie: MM_cookie=207.22.48.162.4731015262864476;
path=/; expires=Wed, 03-Mar-04 17:27:44 GMT;
domain=.macromedia.com

Connection: close

Content-Type: text/html

Filecontent

File contents, for text and MIME files.

Mimetype

MIME type. Examples of MIME types include text/html, image/png, image/gif,video/mpeg, text/css, and audio/basic.

responseHeader

Response header. If there is only one header key, its value can be accessed as simple type. If there are multiple header keys, the values are put in an array in a responseHeader structure.

Statuscode

HTTP error code and associated error string. Common HTTP status codes returned in the response header include:

400: Bad Request

401: Unauthorized

403: Forbidden

404: Not Found

405: Method Not Allowed

You access these attributes using the get function:

function basicGet()
{
    url = "http://localhost:8100/";

    // Invoke with just the url. This is an HTTP GET.
    result = CF.http(url);
    return result.get("Filecontent");
}

Note: For more information on using server-side ActionScript, see Using Server-Side ActionScript in ColdFusion MX Developer’s Guide.

Example

The following examples show a number of the ways to use the CF.http function:

function postWithNamedArgs()
{
    // Set up the array of Post parameters.
    params = new Array();
    params[1] = {name:"arg1", type:"FormField", value:"value1"};
    params[2] = {name:"arg2", type:"URL", value:"value2"};
    params[3] = {name:"arg3", type:"CGI", value:"value3"};

    url = "http://localhost:8100/";

    path = application.getContext("/").getRealPath("/");
    file = "foo.txt";

    result = CF.http({method:"post", url:url, username:"karl", password:"salsa",
resolveurl:true, params:params, path:path, file:file});

    if (result)
        return result.get("Statuscode");
    return null;
}

// Example of a basic HTTP GET operation
// Shows that HTTP GET is the default
function basicGet()
{
    url = "http://localhost:8100/";

    // Invoke with just the url. This is an HTTP GET.
    result = CF.http(url);
    return result.get("Filecontent");
}

// Example showing simple array created to pass params arguments
function postWithParams()
{
    // Set up the array of Post parameters. These are just like cfhttpparam tags.
    params = new Array();
    params[1] = {name:"arg2", type:"URL", value:"value2"};

    url = "http://localhost:8100/";

    // Invoke with the method, url, and params
    result = CF.http("post", url, params);
    return result.get("Filecontent");
}

// Example with username and params arguments
function postWithParamsAndUser()
{
    // Set up the array of Post parameters. These are just like cfhttpparam tags.
    params = new Array();
    params[1] = {name:"arg2", type:"URL", value:"value2"};

    url = "http://localhost:8100/";

    // Invoke with the method, url, params, username, and password
    result = CF.http("post", url, params, "karl", "salsa");
    return result.get("Filecontent");
}

Previous


Developing ColdFusion MX Applications

Developing ColdFusion MX 7 Applications provides the tools needed to develop Internet applications using Macromedia ColdFusion MX 7. This book is intended for web application programmers who are learning ColdFusion MX 7 or wish to extended their ColdFusion MX 7 programming knowledge. It provides a solid grounding in the tools that ColdFusion MX 7 provides to develop web applications.

Because of the power and flexibility of ColdFusion MX 7, you can create many different types of web applications of varying complexity. As you become more familiar with the material presented in this manual, and begin to develop your own applications, you will want to refer to CFML Reference for details about various tags and functions.

This book contains the following chapters:

  • About ColdFusion MX Documentation
  • Introducing ColdFusion MX
  • Elements of CFML
  • Using ColdFusion Variables
  • Using Expressions and Number Signs
  • Using Arrays and Structures
  • Extending ColdFusion Pages with CFML Scripting
  • Using Regular Expressions in Functions
  • Creating ColdFusion Elements
  • Writing and Calling User-Defined Functions
  • Building and Using ColdFusion Components
  • Creating and Using Custom CFML Tags
  • Building Custom CFXAPI Tags
  • Designing and Optimizing a ColdFusion Application
  • Handling Errors
  • Using Persistent Data and Locking
  • Securing Applications
  • Developing Globalized Applications
  • Debugging and Troubleshooting Applications
  • Introduction to Databases and SQL
  • Accessing and Retrieving Data
  • Updating Your Database
  • Using Query of Queries
  • Managing LDAP Directories
  • Building a Search Interface
  • Using Verity Search Expressions
  • Introduction to Retrieving and Formatting Data
  • Building Dynamic Forms with cfform Tags
  • Validating Data
  • Creating Forms in Macromedia Flash
  • Creating Skinnable XML Forms
  • Creating Charts and Graphs
  • Creating Reports for Printing
  • Using the Flash Remoting Service
  • Using Server-Side ActionScript
  • Using XML and WDDX
  • Using Web Services
  • Integrating J2EE and Java Elements in CFML Applications
  • Integrating COM and CORBA Objects in CFML Applications
  • Sending and Receiving E-Mail
  • Interacting with Remote Servers
  • Managing Files on the Server
  • Using Event Gateways
  • Using the Instant Messaging Event Gateways
  • Using the SMS Event Gateway
  • Creating Custom Event Gateways


About ColdFusion MX Documentation

ColdFusion MX Developer’s Guide provides the tools needed to develop Internet applications using Macromedia ColdFusion MX. This manual is intended for web application programmers who are learning ColdFusion MX or wish to extended their ColdFusion MX programming knowledge. It provides a solid grounding in the tools that ColdFusion MX provides to develop web applications.

Because of the power and flexibility of ColdFusion MX, you can create many different types of web applications of varying complexity. As you become more familiar with the material presented in this manual, and begin to develop your own applications, you will want to refer to CFML Reference for details about various tags and functions.

Contents

Using this manual

Accessing the ColdFusion MX documentation
Next


Using this manual

This manual can to help anyone with a basic understanding of HTML learn to develop ColdFusion MX applications. However, this manual is most useful if you have basic ColdFusion experience, or have read Getting Started Building ColdFusion MX Applications. The Getting Started Building ColdFusion MX Applications manual provides an introduction to ColdFusion and helps you develop the basic knowledge that will make using this manual easier.

Approaches to using this manual

This section describes approaches to using this manual for beginning ColdFusion developers, developers with some experience who want to develop expertise, and advanced developers who want to learn about the new and enhanced features of ColdFusion MX.

Beginning with ColdFusion

If you are learning ColdFusion, it might be most effective to read this manual in the following order:

  1. Introducing ColdFusion MX through Using Expressions and Number Signs to learn the basics of CFML.
  2. Introduction to Databases and SQL through Updating Your Database to learn about using databases.
  3. Introduction to Retrieving and Formatting Data and Building Dynamic Forms with cfform Tags to learn about requesting data from users.

    After you read these chapters, you should have a basic understanding of the basic elements of ColdFusion, and be able to create simple ColdFusion applications. To learn to produce more complete and robust applications, you could proceed with the following chapters:

  4. Designing and Optimizing a ColdFusion Application through Debugging and Troubleshooting Applications to learn how to build a complete ColdFusion application.
  5. Using Query of Queries to learn how to use queries effectively.
  6. Using Arrays and Structures through Building and Using ColdFusion Components to learn to use more advanced features of CFML, including ways to reuse code.

You can then read the remaining chapters as you add new features to your ColdFusion application.

Developing an in-depth knowledge of ColdFusion

If you have a basic understanding of ColdFusion as presented in Getting Started Building ColdFusion MX Applications or the Fast Track to ColdFusion course, you might want to start at Chapter 1 and work through to the end of the book, skipping any specialized chapters that you are unlikely to need.

Learning about new and modified ColdFusion features

If you are an advanced ColdFusion developer, you might want to learn about new or changed ColdFusion features. The following chapters document features that are new or substantially enhanced in ColdFusion MX 7:

  • Building a Search Interface
  • Using Verity Search Expressions
  • Building Dynamic Forms with cfform Tags
  • Validating Data
  • Creating Forms in Macromedia Flash
  • Creating Skinnable XML Forms
  • Creating Reports for Printing
  • Using Event Gateways
  • Using the Instant Messaging Event Gateways
  • Using the SMS Event Gateway
  • Creating Custom Event Gateways

Nearly all chapters contain information that is new in ColdFusion MX 7, so you should also review all other chapters for useful information. The index and the table of contents are useful tools for finding new features or changed documentation.

Note: If you are moving from ColdFusion 4.5 or 5, start by reading Migrating ColdFusion 5 Applications, available on the Macromedia website.


ColdFusion features described in this manual

ColdFusion provides a comprehensive set of features for developing and managing Internet applications. These features enhance speed and ease-of-development, and let you dynamically deploy your applications, integrate new and legacy technologies, and build secure applications.

The following table describes the primary ColdFusion features that are discussed in this manual, and lists the chapters that describe them. This table is only a summary of major CFML features; this manual also includes information about other features. Also, this table does not include features that are described in other manuals.

Feature | Description | Chapters
CFML | CFML is a fully featured tag-oriented Internet application language. It includes a wide range of tags, functions, variables, and expressions. | 2–5
CFScript | CFScript is a server-side scripting language that provides a subset of ColdFusion functionality in script syntax. | 6
Regular expressions | ColdFusion provides several functions that use regular expressions for string manipulation. It also lets you use regular expressions in text input tags. | 7, 28
Reusable elements | ColdFusion lets you create several types of elements, such as user-defined functions and ColdFusion components, that you write once and can use many times. | 8–12
User-defined functions (UDFs) | You can use CFScript or the cffunction tag to create your own functions. These functions can incorporate all of the built-in ColdFusion tags and functions, plus other extensions. | 9
ColdFusion components | ColdFusion components encapsulate multiple functions and related data in a single logical unit. ColdFusion components can have many uses, and are particularly useful in creating web services and Flash interfaces for your application. | 10
Custom CFML tags | You can create custom ColdFusion tags using CFML. These tags can have bodies and can call other custom tags. | 11
ColdFusion extension (CFX) tags | You can create custom tags in Java or C++. These tags can use features that are only available when using programming languages. However, CFX tags cannot have tag bodies. | 12
ColdFusion application structure | ColdFusion supports many ways of building an application, and includes specific features, such as the Application.cfc file or Application.cfm page, built-in security features, and shared scopes, that help you optimize your application structure. | 13–17
Error handling mechanisms | ColdFusion provides several mechanisms for handling data, including custom error pages and exception-handling tags and functions, such as cftry and cfcatch. | 14
Shared and persistent variable scopes | Using shared and persistent scopes, you can make data available to a single user over one or many browser sessions, or to multiple users of an application or server. | 15
Code locking | You lock sections of code that access in-memory shared scopes or use external resources that are not safe for multiple simultaneous access. | 15
Application security | ColdFusion provides mechanisms, including the cflogin tag, for authenticating users and authorizing them to access specific sections of your application. You can also use resource security, which secures access to ColdFusion resources based on the ColdFusion page location. | 16
Application globalization | ColdFusion supports global applications that use different character sets and locales, and provides tags and functions designed to support globalizing your applications. | 17
Debugging tools | Using debugging output, the cftrace tag, logging features, and the Code Analyzer, you can locate and fix coding errors. | 18
Database access and management | ColdFusion can access SQL databases to retrieve, add, and modify data. This feature is one of the core functions of many dynamic applications. | 19–21
Queries of Queries | You can use a subset of standard SQL within ColdFusion to manipulate any data that is represented as a record set, including database query results, LDAP (Lightweight Directory Access Protocol) directory information, and other data. | 22
LDAP directory access and management | ColdFusion applications can access and manipulate data in LDAP directory services. These directories are often used for security validation data and other directory-like information. | 23
Indexing and searching data | ColdFusion applications can provide full-text search capabilities for documents and data sources using the Verity search engine. | 24–25
Dynamic forms | With ColdFusion, you can use HTML and forms to control the data displayed by a dynamic web page. You can also use the cfform tag to enrich your forms with sophisticated graphical controls, and perform input data validation. | 26–30
Validating data | ColdFusion provides several ways to validate data in forms and in CFML variables. | 28
Flash forms | ColdFusion can display forms using Macromedia Flash, which presents a pleasing appearance and includes features such as accordion and tab navigators. | 29
XML skinnable forms | ColdFusion can convert your CFML forms into XML and format the XML using XSLT skins and style sheets. | 30
Data graphing | You can use the cfchart tag to display your data graphically. | 31
Reports and printable output | You can create output that is formatted for print as PDF or FlashPaper documents. You can also use ColdFusion reporting to create banded reports for display or printing. | 32
Macromedia Flash integration | You can use native Flash connectivity built into ColdFusion to help build dynamic Flash user interfaces for ColdFusion applications. | 33
Server-side ActionScript | Macromedia Flash Remoting lets Macromedia Flash MX developers create server-side ActionScript. ActionScript files can directly access ColdFusion query and HTTP features through two functions: CF.query and CF.http. | 34
XML document processing and creation | ColdFusion applications can create, use, and manipulate XML (Extensible Markup Language) documents. ColdFusion also provides tools to use WDDX (Web Distributed Data Exchange), an XML dialect for transmitting structured data. | 35
Web services | ColdFusion applications can use available SOAP (Simple Object Access Protocol)-based web services, including Microsoft .NET services. ColdFusion applications can also use ColdFusion components to provide web services to other applications over the Internet. | 36
Java and J2EE integration | You can integrate J2EE elements, including JSP (JavaServer Pages) pages, JSP tag libraries, and Java objects, including EJBs (Enterprise JavaBeans), into your ColdFusion application. | 37
COM and CORBA objects | The cfobject tag lets you use COM (Component Object Model) or DCOM (Distributed Component Object Model) and CORBA (Common Object Request Broker) objects in your ColdFusion applications. | 38
E-mail messages | You can add interactive e-mail features to your ColdFusion applications using the cfmail and cfpop tags. | 39
HTTP and FTP | The cfhttp and cfftp tags provide simple methods of using HTTP (Hypertext Transfer Protocol) and FTP (File Transfer Protocol) communications in your application. | 40
File and directory access | You can use the cffile, cfdirectory, and cfcontent tags to read, write, and manage files and directories on the server. | 41
Event gateways | ColdFusion event gateways let ColdFusion applications asynchronously react to or generate external events or messages. | 42–45
Instant messaging event gateways | Your ColdFusion application can communicate with XMPP (Jabber) or IBM Sametime instant messaging clients using the ColdFusion IM gateways. | 43
SMS event gateway | Your ColdFusion MX application can communicate with short message service (SMS) devices, such as mobile phones, using the ColdFusion SMS event gateway. | 44
Creating gateways | You can write your own event gateways in Java and integrate them into ColdFusion MX. | 45

Accessing the ColdFusion MX documentation

The ColdFusion MX documentation is designed to provide support for the complete spectrum of participants.

Documentation set

The ColdFusion MX 7 documentation set includes the following titles:

Book | Description
Installing and Using ColdFusion MX | Describes system installation and basic configuration for Windows, Solaris, and Linux. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_installing.
Configuring and Administering ColdFusion MX | Part I describes how to manage the ColdFusion environment, including connecting to your data sources and configuring security for your applications. Part II describes Verity search tools and utilities that you can use for configuring the Verity Search Server engine, as well as creating, managing, and troubleshooting Verity collections. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_configadmin.
ColdFusion MX Developer’s Guide | Describes how to develop your dynamic web applications, including retrieving and updating your data, using structures, and forms. This manual includes two volumes. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_dev.
Getting Started Building ColdFusion MX Applications | Contains an overview of ColdFusion features and application development procedures. Includes a tutorial that guides you through the process of developing an example ColdFusion application. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_gs.
CFML Reference | Provides descriptions, syntax, usage, and code examples for all ColdFusion tags, functions, and variables. This manual includes two volumes. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs__cfml_reference.
CFML Quick Reference | Provides a brief guide that shows the syntax of ColdFusion tags, functions, and variables.

Viewing online documentation

All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com.
Previous


Introducing ColdFusion MX

This chapter describes Macromedia ColdFusion MX and the role it plays in developing dynamic Internet applications. This chapter also introduces the topics discussed in this manual.

Contents

About Internet applications and web application servers

About ColdFusion MX

About J2EE and the ColdFusion architecture
Next


About Internet applications and web application servers

With ColdFusion MX, you develop Internet applications that run on web application servers. The following sections introduce Internet applications and web application servers. Later sections explain the specific role that ColdFusion MX plays in this environment.

About web pages and Internet applications

The Internet has evolved from a collection of static HTML pages to an application deployment platform. First, the Internet changed from consisting of static web pages to providing dynamic, interactive content. Rather than providing unchanging content where organizations merely advertise goods and services, dynamic pages enable companies to conduct business ranging from e-commerce to managing internal business processes. For example, a static HTML page lets a bookstore publish its location, list services such as the ability to place special orders, and advertise upcoming events like book signings. A dynamic website for the same bookstore lets customers order books online, write reviews of books they read, and even get suggestions for purchasing books based on their reading preferences.

More recently, the Internet has become the underlying infrastructure for a wide variety of applications. With the arrival of technologies such as XML, web services, J2EE (Java 2 Platform, Enterprise Edition), and Microsoft .NET, the Internet has become a multifaceted tool for integrating business activities. Now, enterprises can use the Internet to integrate distributed activities, such as customer service, order entry, order fulfillment, and billing.

ColdFusion MX is a rapid application development environment that lets you build dynamic websites and Internet applications quickly and easily. It lets you develop sophisticated websites and Internet applications without knowing the details of many complex technologies, yet it lets advanced developers take advantage of the full capabilities of many of the latest Internet technologies.

About web application servers

To understand ColdFusion, you must first understand the role of web application servers. Typically, web browsers make requests, and web servers, such as Microsoft Internet Information Server (IIS) and the Apache web server, fulfill those requests by returning the requested information to the browser. This information includes, but is not limited to, HTML and Macromedia Flash files.

A web server’s capabilities are limited because all it does is wait for requests to arrive and attempt to fulfill those requests as soon as possible. A web server does not let you do the following tasks:

  • Interact with a database, other resource, or other application.
  • Serve customized information based on user preferences or requests.
  • Validate user input.

A web server, basically, locates information and returns it to a web browser.

To extend the capabilities of a web server, you use a web application server, a software program that extends the web server’s capabilities to do tasks such as those in the preceding list.

How a web server and web application server work together

The following steps explain how a web server and web application server work together to process a page request:

  1. The user requests a page by typing a URL in a browser, and the web server receives the request.
  2. The web server looks at the file extension to determine whether a web application server must process the page. Then, one of the following actions occur:
    • If the user requests a file that is a simple web page (often one with an HTM or HTML extension), the web server fulfills the request and sends the file to the browser.
    • If the user requests a file that is a page that a web application server must process (one with a CFM, CFML, or CFC extension for ColdFusion requests), the web server passes the request to the web application server. The web application server processes the page and sends the results to the web server, which returns those results to the browser. The following figure shows this process:

      Web server passing a request to ColdFusion

Because web application servers interpret programming instructions and generate output that a web browser can interpret, they let web developers build highly interactive and data-rich websites, which can do tasks such as the following:

  • Query other database applications for data.
  • Dynamically populate form elements.
  • Dynamically generate Flash application data.
  • Provide application security.
  • Integrate with other systems using standard protocols such as HTTP, FTP, LDAP, POP, and SMTP.
  • Create shopping carts and e-commerce websites.
  • Respond with an e-mail message immediately after a user submits a form.
  • Return the results of keyword searches.


About ColdFusion MX

ColdFusion MX is a rapid scripting environment server for creating dynamic Internet Applications. ColdFusion Markup Language (CFML) is an easy-to-learn tag-based scripting language, with connectivity to enterprise data and powerful built-in search and charting capabilities. ColdFusion MX enables developers to easily build and deploy dynamic websites, content publishing systems, self-service applications, commerce sites, and more.

ColdFusion MX consists of the following core components:

  • ColdFusion scripting environment
  • CFML
  • ColdFusion MX Administrator
  • Verity Search Server

The following sections describe these core components in more detail.

The ColdFusion scripting environment

The ColdFusion scripting environment provides an efficient development model for Internet applications. At the heart of the ColdFusion scripting environment is the ColdFusion Markup Language (CFML), a tag-based programming language that encapsulates many of the low-level details of web programming in high-level tags and functions.

ColdFusion Markup Language

ColdFusion Markup Language (CFML) is a tag-based language, similar to HTML, that uses special tags and functions. With CFML, you can enhance standard HTML files with database commands, conditional operators, high-level formatting functions, and other elements to rapidly produce easy-to-maintain web applications. However, CFML is not limited to enhancing HTML. For example, you can create Macromedia Flash MX applications that consist entirely of Flash elements and CFML. Similarly, you can use CFML to create web services for use by other applications.

The following sections briefly describe basic CFML elements. For more information, see Elements of CFML.

CFML tags

CFML looks similar to HTML--it includes starting and, in most cases, ending tags, and each tag is enclosed in angle brackets. All ending tags are preceded with a forward slash (/) and all tag names are preceded with cf; for example:

<cftagname>
    tag body text and CFML
</cftagname>

CFML increases productivity by providing a layer of abstraction that hides many low-level details involved with Internet application programming. At the same time, CFML is extremely powerful and flexible. ColdFusion lets you easily build applications that integrate files, databases, legacy systems, mail servers, FTP servers, objects, and components.

CFML includes approximately 110 tags. ColdFusion tags serve many functions. They provide programming constructs, such as conditional processing and loop structures. They also provide services, such as charting and graphing, full-text search, access to protocols such as FTP, SMTP/POP, and HTTP, and much more. The following table lists a few examples of commonly used ColdFusion tags:

Tag

Purpose

cfquery

Establishes a connection to a database (if one does not exist), executes a query, and returns results to the ColdFusion environment.

cfoutput

Displays output that can contain the results of processing ColdFusion functions, variables, and expressions.

cfset

Sets the value of a ColdFusion variable.

cfmail

Lets an application send SMTP mail messages using application variables, query results, or server files. (Another tag, cfpop, gets mail.)

cfchart

Converts application data or query results into graphs, such as bar charts or pie charts, in Flash, JPG, or PNG format.

cfobject

Invokes objects written in other programming languages, including COM (Component Object Model) components, Java objects such as Enterprise JavaBeans, or Common CORBA (Object Request Broker Architecture) objects.

CFML Reference describes the CFML tags in detail.

CFML functions and CFScript

CFML includes approximately 280 built-in functions. These functions perform a variety of roles, including string manipulation, data management, and system functions. CFML also includes a built-in scripting language, CFScript, that lets you write code in a manner that is familiar to programmers and JavaScript writers.

CFML extensions

You can extend CFML further by creating custom tags or user-defined functions (UDFs), or by integrating COM, C++, and Java components (such as JSP tag libraries). You can also create ColdFusion components (CFCs), which encapsulate related functions and properties and provide a consistent interface for accessing them.

All these features let you easily create reusable functionality that is customized to the types of applications or websites that you are building.

CFML development tools

Macromedia Dreamweaver MX 2004 helps you develop ColdFusion applications efficiently. It includes many features that simplify and enhance ColdFusion development, including tools for debugging CFML. Because CFML is written in an HTML-like text format, and you often use HTML in ColdFusion pages, you can also use an HTML editor or a text editor, such as Notepad, to write ColdFusion applications.

Verity Search Server

The Verity Search Server (also called the Verity search engine) provides full text search capability for documents and data on a ColdFusion MX site.

ColdFusion MX Administrator

ColdFusion MX Administrator configures and manages the ColdFusion application server. It is a secure web-based application that you can access using any web browser, from any computer with an Internet connection.

For more information about ColdFusion MX Administrator, see Configuring and Administering ColdFusion MX.


About J2EE and the ColdFusion architecture

As the Internet software market has matured, the infrastructure services required by distributed Internet applications, including ColdFusion applications, have become increasingly standardized. The most widely adopted standard today is the Java 2 Platform, Enterprise Edition (J2EE) specification. J2EE provides a common set of infrastructure services for accessing databases, protocols, and operating system functionality, across multiple operating systems.

About ColdFusion MX and the J2EE platform

ColdFusion MX is implemented on the Java technology platform and uses a J2EE application server for many of its base services, including database connectivity, naming and directory services, and other runtime services. ColdFusion MX can be configured to use an embedded J2EE server (in the server configuration) or it can be deployed as a J2EE application on an independent J2EE application server (in the multiserver configuration or the J2EE configuration). ColdFusion MX Enterprise includes a fully featured version of the Macromedia JRun J2EE application server, or can be deployed on third-party J2EE servers such as IBM WebSphere and BEA WebLogic.

For more information on ColdFusion MX configurations, see Installing and Using ColdFusion MX.

By implementing the ColdFusion scripting environment on top of the J2EE platform, ColdFusion MX takes advantage of the power of the J2EE platform while also providing an easy-to-use scripting environment and built-in services. Moreover, because ColdFusion is built on a J2EE platform, you can easily integrate J2EE and Java functionality into your ColdFusion application. As a result, ColdFusion pages can do any of the following:

  • Share session data with JSPs (Java Server Pages) and Java servlets.
  • Import custom JSP tag libraries and use them like ColdFusion custom tags.
  • Integrate with Java objects, including the J2EE Java API, JavaBeans, and Enterprise JavaBeans.

For more information on using J2EE features in ColdFusion, see Integrating J2EE and Java Elements in CFML Applications.
Previous


Elements of CFML

This chapter provides an overview of the basic elements of CFML, including tags, functions, constants, variables, expressions, and CFScript. The chapters in Part I of this manual describe these topics in detail.

Contents

CFML Basics

Comments

Tags

Functions

ColdFusion components

Constants

Variables

Expressions

Data types

Flow control

Character case

Special characters

Reserved words

CFScript
Next


CFML Basics

This chapter introduces and describes the basic elements of CFML. These elements make CFML a powerful tool for developing interactive web applications. Because CFML is a dynamic application development tool, it has many of the features of a programming language, including the following:

  • Functions
  • Expressions
  • Variables and constants
  • Flow-control constructs such as if-then and loops

CFML also has a "language within a language," CFScript, which enables you to use a syntax similar to JavaScript for many operations.

This chapter introduces these elements and other basic CFML entities such as comments, data types, escape characters, and reserved words.

The remainder of Part I of this manual provides more detailed information on many of the basic CFML elements. The rest of this manual helps you use these elements effectively in your applications.


Comments

ColdFusion comments have a similar format to HTML comments. However, they use three dash characters instead of two; for example:

<!--- This is a ColdFusion Comment. Browsers do not receive it. --->

The ColdFusion server removes all ColdFusion comments from the page before returning it to the web server. As a result, the page that a user browser receives does not include the comment, and users cannot see it even if they view the page source.

You can embed CFML comments in begin tags (not just tag bodies), functions calls, and variable text in number signs. ColdFusion ignores the text in comments such as the following:

<cfset MyVar = var1 <!--- & var2 --->>
<cfoutput>#Dateformat(now() <!---, "dddd, mmmm yyyy" --->)#</cfoutput>

This technique can be useful if you want to temporarily comment out parts of expressions or optional attributes or arguments.

You can also nest comments, as the following example shows:

<!--- disable this code
<!--- display error message --->
<cfset errormessage1="Oops!">
<cfoutput>
#errormessage1#
</cfoutput>
--->

This is useful if you want to temporarily disable a section of code while you test your application.

You can embed comments within comments, however, you should use this technique carefully.

Note: You cannot embed comments inside a tag name or function name, such as
<cf_My<!--- New --->CustomTag>. You also cannot embed comments inside strings, as in the following example: IsDefined("My<!--- New --->Variable").


Tags

ColdFusion tags tell the ColdFusion server that it must process information. The ColdFusion server only processes tag contents; it returns text outside of ColdFusion to the web server unchanged. Macromedia ColdFusion MX provides a wide variety of built-in tags and lets you create custom tags.

Tag syntax

ColdFusion tags have the same format as HTML tags. They are enclosed in angle brackets (< and >) and can have zero or more named attributes. Many ColdFusion tags have bodies; that is, they have beginning and end tags with text to be processed between them. For example:

<cfoutput>
    Hello #YourName#! <br>
</cfoutput>

Other tags, such as cfset and cfftp, never have bodies; all the required information goes between the beginning (<) character and the ending (>) character, as in the following example:

<cfset YourName="Bob">

Sometimes, although the tag can have a body, you do not need to put anything in it because the attributes specify all the required information. You can omit the end tag and put a forward slash character before the closing (>) character, as in the following example:

<cfexecute name="C:\winNT\System32\netstat.exe" arguments = "-e"
outputfile="C:\Temp\out.txt" timeout = "1" />

Note: The cfset tag differs from other tags in that it has neither a body nor arguments. Instead, the tag encloses an assignment statement that assigns a value to a variable. The cfset tag can also call a function without assigning a value to a result variable.

Built-in tags

Over 110 built-in tags make up the heart of ColdFusion. These tags have many uses, including the following:

  • Manipulating variables
  • Creating interactive forms
  • Accessing and manipulating databases
  • Displaying data
  • Controlling the flow of execution on the ColdFusion page
  • Handling errors
  • Processing ColdFusion pages
  • Managing the CFML application framework
  • Manipulating files and directories
  • Using external tools and objects, including Verity collections, COM, Java, and CORBA objects, and executable programs
  • Using protocols, such as mail, http, ftp, and pop

Much of this document describes how to use these tags effectively. CFML Reference documents each tag in detail.

Custom tags

ColdFusion lets you create custom tags. You can create two types of custom tags:

  • CFML custom tags that are ColdFusion pages
  • CFX tags that you write in a programing language such as Java or C++

Custom tags can encapsulate frequently used business logic or display code. These tags enable you to place frequently used code in one place and call it from many places. Custom tags also let you abstract complex logic into a single, simple interface. They provide an easy way to distribute your code to others; you can even distribute encrypted versions of the tags to prevent access to the tag logic.

You can access a variety of free and commercial custom tags on the Macromedia developer’s exchange (www.macromedia.com/cfusion/exchange/index.cfm). They perform tasks ranging from checking if Cookies and JavaScript are enabled on the client's browser to moving items from one list box to another. Many of these tags are free and include source code.

CFML custom tags

When you write a custom tag in CFML, you can take advantage of all the features of the ColdFusion language, including all built-in tags and even other custom tags. CFML custom tags can include body sections and end tags. Because they are written in CFML, you do not need to know a programming language such as Java. CFML custom tags provide more capabilities than user-defined functions, but are less efficient.

For more information on CFML custom tags, see Creating and Using Custom CFML Tags. For information about, and comparisons among, ways to reuse ColdFusion code, including CFML custom tags, user-defined functions, and CFX tags, see Creating ColdFusion Elements.

CFX Tags

CFX tags are ColdFusion custom tags that you write in a programming language such as Java or C++. These tags can take full advantage of all the tools and resources provided by these languages, including their access to runtime environments. CFX tags also generally execute faster than CFML custom tags because they are compiled. CFX tags can be cross-platform, but are often platform-specific, for example if they take advantage of COM objects or the Windows API.

For more information on CFX tags, see Building Custom CFXAPI Tags.


Functions

Functions typically manipulate data and return a result. CFML includes over 280 built-in functions. You can also create user-defined functions (UDFs), sometimes referred to as custom functions.

Functions have the following general form:

functionName([argument1[, argument2]]...)

Some functions, such as the Now function take no arguments. Other functions require one or more comma-separated arguments and can have additional optional arguments. All ColdFusion functions return a value. For example, Round(3.14159) returns the value 3.

Built-in functions

ColdFusion built-in functions perform a variety of tasks, including, but not limited to, the following:

  • Creating and manipulating complex data variables, such as arrays, lists, and structures
  • Creating and manipulating queries
  • Creating, analyzing, manipulating, and formatting strings and date and time values
  • Evaluating the values of dynamic data
  • Determining the type of a variable value
  • Converting data between formats
  • Performing mathematical operations
  • Getting system information and resources

For alphabetical and categorized lists of ColdFusion functions, see ColdFusion Functions in CFML Reference.

You use built-in functions throughout ColdFusion pages. Built-in functions are frequently used in a cfset or cfoutput tag to prepare data for display or further use. For example, the following line displays today’s date in the format October 12, 2001:

<cfoutput>#DateFormat(Now(), "mmmm d, yyyy")#</cfoutput>

Note that this code uses two nested functions. The Now function returns a ColdFusion date-time value representing the current date and time. The DateFormat function takes the value returned by the Now function and converts it to the desired string representation.

Functions are also valuable in CFScript scripts. ColdFusion does not support ColdFusion tags in CFScript, so you must use functions to access ColdFusion functionality in scripts.

User-defined functions

You can write your own functions, user-defined functions (UDFs). You can use these functions in ColdFusion expressions or in CFScript. You can call a user-defined function anywhere you can use a built-in CFML function. You create UDFs using the cffunction tag or the CFScript function statement. UDFs that you create using the cffunction tag can include ColdFusion tags and functions. UDFs that you create in CFScript can only include functions. You can create stand-alone UDFs or encapsulate them in a ColdFusion component.

User-defined functions let you encapsulate logic and operations that you use frequently in a single unit. This way, you can write the code once and use it multiple times. UDFs ensure consistency of coding and enable you to structure your CFML more efficiently.

Typical user-defined functions include mathematical routines, such as a function to calculate the logarithm of a number; string manipulation routines, such as a function to convert a numeric monetary value to a string such as "two dollars and three cents"; and can even include encryption and decryption routines.

Note: The Common Function Library Project at www.cflib.org includes a number of free libraries of user-defined functions.

For more information on user-defined functions, see Writing and Calling User-Defined Functions.


ColdFusion components

ColdFusion components encapsulate multiple, related, functions. A ColdFusion component is essentially a set of related user-defined functions and variables, with additional functionality to provide and control access to the component contents. ColdFusion components can make their data private, so that it is available to all functions (also called methods) in the component, but not to any application that uses the component.

ColdFusion components have the following features:

  • They are designed to provide related services in a single unit.
  • They can provide web services and make them available over the Internet.
  • They can provide ColdFusion services that Flash clients can call directly.
  • They have several features that are familiar to object-oriented programmers, including data hiding, inheritance, packages, and introspection.

For more information on ColdFusion components, see Building and Using ColdFusion Components.


Constants

The value of a constant does not change during program execution. Constants are simple scalar values that you can use within expressions and functions, such as "Robert Trent Jones" and 123.45. Constants can be integers, real numbers, time and date values, Boolean values, or text strings. ColdFusion does not allow you to give names to constants.


Variables

Variables are the most frequently used operands in ColdFusion expressions. Variable values can be set and reset, and can be passed as attributes to CFML tags. Variables can be passed as parameters to functions, and can replace most constants.

ColdFusion has a number of built-in variables that provide information about the server and are returned by ColdFusion tags. For a list of the ColdFusion built-in variables, see Reserved Words and Variables in CFML Reference.

The following two characteristics classify a variable:

  • The scope of the variable, which indicates where the information is available and how long the variable persists
  • The data type of the variable’s value, which indicates the kind of information a variable represents, such as number, string, or date

The following section lists and briefly describes the variable scopes. Data types lists data types (which also apply to constant values). For detailed information on ColdFusion variables, including data types, scopes, and their use, see Using ColdFusion Variables.

Variable scopes

The following table describes ColdFusion variable scopes:

Scope | Description
Variables (local) | The default scope for variables of any type that are created with the cfset and cfparam tags. A local variable is available only on the page on which it is created and any included pages.
Form | The variables passed from a form page to its action page as the result of submitting the form.
URL | The parameters passed to the current page in the URL that is used to call it.
Attributes | The values passed by a calling page to a custom tag in the custom tag’s attributes. Used only in custom tag pages.
Caller | A reference, available in a custom tag, to the Variables scope of the page that calls the tag. Used only in custom tag pages.
ThisTag | Variables that are specific to a custom tag, including built-in variables that provide information about the tag. Used only in custom tag pages. A nested custom tag can use the cfassociate tag to return values to the calling tag’s ThisTag scope.
Request | Variables that are available to all pages, including custom tags and nested custom tags, that are processed in response to an HTTP request. Used to hold data that must be available for the duration of one HTTP request.
CGI | Environment variables identifying the context in which a page was requested. The variables available depend on the browser and server software.
Cookie | Variables maintained in a user’s browser as cookies.
Client | Variables that are associated with one client. Client variables let you maintain state as a user moves from page to page in an application and are available across browser sessions.
Session | Variables that are associated with one client and persist only as long as the client maintains a session.
Application | Variables that are associated with one, named, application on a server. The Application.cfc initialization code or the cfapplication tag name attribute specifies the application name.
Server | Variables that are associated with the current ColdFusion server. This scope lets you define variables that are available to all your ColdFusion pages, across multiple applications.
Flash | Variables sent by a Macromedia Flash movie to ColdFusion and returned by ColdFusion to the movie.
Arguments | Variables passed in a call to a user-defined function or ColdFusion component method.
This | Variables that are declared inside a ColdFusion component or in a cffunction tag that is not part of a ColdFusion component.
function local | Variables that are declared in a user-defined function and exist only while the function executes.


Expressions

ColdFusion expressions consist of operands and operators. Operands are comprised of constants and variables, such as "Hello" or MyVariable. Operators, such as the string concatenation operator (&) or the division operator (/) are the verbs that act on the operands. ColdFusion functions also act as operators.

The simplest expression consists of a single operand with no operators. Complex expressions consist of multiple operands and operators. For example, the following statements are all ColdFusion expressions:

12
MyVariable
(1 + 1)/2
"father" & "Mother"
Form.divisor/Form.dividend
Round(3.14159)

For detailed information on using variables, see Using ColdFusion Variables. For detailed information on expressions and operators, see Using Expressions and Number Signs.


Data types

ColdFusion is considered typeless because you do not explicitly specify variable data types.

However, ColdFusion data, the constants and the data that variables represent, do have data types, which correspond to the ways the data is stored on the computer.

ColdFusion data belongs to the following type categories:

Category

Description and types

Simple

Represents one value. You can use simple data types directly in ColdFusion expressions. ColdFusion simple data types are:

  • strings A sequence of alphanumeric characters enclosed in single or double quotation marks, such as "This is a test."
  • integers A sequence of numbers written without quotation marks, such as 356.
  • real numbers, such as -3.14159
  • Boolean values Use True, Yes, or 1 for true and False, No, or 0 for false. Boolean values are not case-sensitive.
  • date-time values ColdFusion supports a variety of data formats. For more information, see Date-Time values.

Complex

A container for data. Complex variables generally represent more than one value. ColdFusion built-in complex data types are:

  • arrays
  • structures
  • queries

Binary

Raw data, such as the contents of a GIF file or an executable program file

Object

COM, CORBA, Java, web services, and ColdFusion Component objects: Complex objects that you create and access using the cfobject tag and other specialized tags.

For more information on ColdFusion data types, see Using ColdFusion Variables.


Flow control

ColdFusion provides several tags that let you control how a page gets executed. These tags generally correspond to programming language flow control statements, such as if, then, and else. The following tags provide ColdFusion flow control:

Tags | Purpose
cfif, cfelseif, cfelse | Select sections of code based on whether expressions are True or False.
cfswitch, cfcase, cfdefaultcase | Select among sections of code based on the value of an expression. Case processing is not limited to True and False conditions.
cfloop, cfbreak | Loop through code based on any of the following values: entries in a list, keys in a structure or external object, entries in a query column, an index, or the value of a conditional expression.
cfabort, cfexit | End processing of a ColdFusion page or custom tag.

This section provides a basic introduction to using flow-control tags. CFScript also provides a set of flow-control statements. For information on using flow-control statements in CFScript, see Extending ColdFusion Pages with CFML Scripting. For more details on using flow-control tags, see the reference pages for these tags in CFML Reference.

This section describes the following topics:

  • cfif, cfelseif, and cfelse
  • cfswitch, cfcase, and cfdefaultcase
  • cfloop and cfbreak
  • cfabort and cfexit

cfif, cfelseif, and cfelse

The cfif, cfelseif, and cfelse tags provide if-then-else conditional processing, as follows:

  1. The cfif tag tests a condition and executes its body if the condition is True.
  2. If the preceding cfif (or cfelseif) test condition is False, the cfelseif tag tests another condition and executes its body if that condition is True.
  3. The cfelse tag can optionally follow a cfif tag and zero or more cfelseif tags. Its body executes if all the preceding tags’ test conditions are False.

The following example shows the use of the cfif, cfelseif, and cfelse tags. If the value of the type variable is "Date," the date displays; if the value is "Time," the time displays; otherwise, both the time and date display.

<cfif type IS "Date">
    <cfoutput>#DateFormat(Now())#</cfoutput>
<cfelseif type IS "Time">
    <cfoutput>#TimeFormat(Now())#</cfoutput>
<cfelse>
    <cfoutput>#TimeFormat(Now())#, #DateFormat(Now())#</cfoutput>
</cfif>

cfswitch, cfcase, and cfdefaultcase

The cfswitch, cfcase, and cfdefaultcase tags let you select among different code blocks based on the value of an expression. ColdFusion processes these tags as follows:

  1. The cfswitch tag evaluates an expression. The cfswitch tag body contains one or more cfcase tags and optionally includes cfdefaultcase tag.
  2. Each cfcase tag in the cfswitch tag body specifies a value or set of values. If a value matches the value determined by the expression in the cfswitch tag, ColdFusion runs the code in the body of the cfcase tag and then exits the cfswitch tag. If two cfcase tags have the same condition, ColdFusion generates an error.
  3. If none of the cfcase tags match the value determined by the cfswitch tag, and the cfswitch tag body includes a cfdefaultcase tag, ColdFusion runs the code in the cfdefaultcase tag body.

Note: Although the cfdefaultcase tag does not have to follow all cfcase tags, it is good programming practice to put it at the end of the cfswitch statement.

The cfswitch tag provides better performance than a cfif tag with multiple cfelseif tags, and is easier to read. Switch processing is commonly used when different actions are required based on a a string variable such as a month or request identifier.

The following example shows switch processing:

<cfoutput query = "GetEmployees">
<cfswitch expression = #Department#>
    <cfcase value = "Sales">
        #FirstName# #LastName# is in <b>Sales</b><br><br>
    </cfcase>
    <cfcase value = "Accounting">
        #FirstName# #LastName# is in <b>Accounting</b><br><br>
    </cfcase>
    <cfcase value = "Administration">
        #FirstName# #LastName# is in <b>Administration</b><br><br>
    </cfcase>
    <cfdefaultcase>#FirstName# #LastName# is not in Sales,
        Accounting, or Administration.<br>
    </cfdefaultcase>
</cfswitch>
</cfoutput>

cfloop and cfbreak

The cfloop tag loops through the tag body zero or more times based on a condition specified by the tag attributes. The cfbreak tag exits a cfloop tag.

cfloop

The cfloop tag provides five types of loops:

Loop type | Description
Index | Loops through the body of the tag and increments a counter variable by a specified amount after each loop until the counter reaches a specified value.
Conditional | Checks a condition and runs the body of the tag if the condition is True.
Query | Loops through the body of the tag once for each row in a query.
List | Loops through the body of the tag once for each entry in a list.
Collection | Loops through the body of the tag once for each key in a ColdFusion structure or item in a COM/DCOM object.

The following example shows a simple index loop:

<cfloop index = "LoopCount" from = 1 to = 5>
The loop index is <cfoutput>#LoopCount#</cfoutput>.<br>
</cfloop>

The following example shows a simple conditional loop. The code does the following:

  1. Sets up a ten-element array with the word "kumquats" in the fourth entry.
  2. Loops through the array until it encounters an array element containing "kumquats" or it reaches the end of the array.
  3. Prints out the value of the Boolean variable that indicates whether it found the word kumquats and the array index at which it exited the loop.
<cfset myArray = ArrayNew(1)>
<!--- Use ArraySet to initialize the first ten elements to 123 --->
<cfset ArraySet(myArray, 1, 10, 123)>
<cfset myArray[4] = "kumquats">

<cfset foundit = False>
<cfset i = 0>
<cfloop condition = "(NOT foundit) AND (i LT ArrayLen(myArray))">
    <cfset i = i + 1>
    <cfif myArray[i] IS "kumquats">
        <cfset foundit = True>
    </cfif>
</cfloop>
<cfoutput>
i is #i#<br>
foundit is #foundit#<br>
</cfoutput>

Note: You can get an infinite conditional loop if you do not force an end condition. In this example, the loop is infinite if you omit the <cfset i = i + 1> statement. To end an infinite loop, stop the ColdFusion application server.

cfbreak

The cfbreak tag exits the cfloop tag. You typically use it in a cfif tag to exit the loop if a particular condition occurs. The following example shows the use of a cfbreak tag in a query loop:

<cfloop query="fruitOrder">
    <cfif fruit IS "kumquat">
        <cfoutput>You cannot order kumquats!<br></cfoutput>
        <cfbreak>
    </cfif>
    <cfoutput>You have ordered #quantity# #fruit#.<br></cfoutput>
</cfloop>

cfabort and cfexit

The cfabort tag stops processing of the current page at the location of the cfabort tag. ColdFusion returns to the user or calling tag everything that was processed before the cfabort tag. You can optionally specify an error message to display. You can use the cfabort tag as the body of a cfif tag to stop processing a page when a condition, typically an error, occurs.

The cfexit tag controls the processing of a custom tag, and can only be used in ColdFusion custom tags. For more information see, Terminating tag execution and CFML Reference.


Character case

ColdFusion is case-insensitive. For example, the following all represent the cfset tag: cfset, CFSET, CFSet, and even cfsEt. However, you should get in the habit of consistently using the same case rules in your programs; for example:

  • Develop consistent rules for case use, and stick to them. If you use lowercase characters for some tag names, use them for all tag names.
  • Always use the same case for a variable. For example, do not use both myvariable and MyVariable to represent the same variable on a page.

Follow these rules to prevent errors on application pages where you use both CFML and case-sensitive languages, such as JavaScript.


Special characters

The double-quotation marks ("), single-quotation mark ('), and number sign (#) characters have special meaning to ColdFusion. To include any of them in a string, double the character; for example, use ## to represent a single # character.

The need to escape the single- and double-quotation marks is context-sensitive. Inside a double-quoted string, you do not need to escape single-quotation mark (apostrophe) characters. Inside a single-quoted string, you do not escape double-quotation mark characters.

The following example illustrates escaping special characters, including the use of mixed single- and double-quotation marks:

<cfset mystring = "We all said ""For He's a jolly good fellow.""">
<cfset mystring2 = 'Then we said "For She''s a jolly good fellow".'>
<cfoutput>
    #mystring#<br>
    #mystring2#<br>
    Here is a number sign: ##
</cfoutput>

The output looks like this:

We all said "For He's a jolly good fellow."
Then we said "For She's a jolly good fellow."
Here is a number sign: #


Reserved words

As with any programming tool, you cannot use just any word or name for ColdFusion variables, UDFs and custom tags. You must avoid using any name that can be confused with a ColdFusion element. In some cases, if you use a word that ColdFusion uses--for example, a built-in structure name--you can overwrite the ColdFusion data.

The following list indicates words you must not use for ColdFusion variables, user-defined function names, or custom tag names. While some of these words can be used safely in some situations, you can prevent errors by avoiding them entirely. For a complete list of reserved words, see CFML Reference.

  • Built-in function names, such as Now or Hash
  • Scope names, such as Form or Session
  • Any name starting with cf. However, when you call a CFML custom tag directly, you prefix the custom tag page name with cf_.
  • Operators, such as NE or IS
  • The names of any built-in data structures, such as Error or File
  • The names of any built-in variables, such as RecordCount or CGI variable names
  • CFScript language element names such as for, default, or continue

You must also not create form field names ending in any of the following, except to specify a form field validation rule using a hidden form field name. (For more information on form field validation, see Introduction to Retrieving and Formatting Data.)

  • _integer
  • _float
  • _range
  • _date
  • _time
  • _eurodate

Remember that ColdFusion is not case-sensitive. For example, all of the following are reserved words: IS, Is, iS, and is.


CFScript

CFScript is a language within a language. CFScript is a scripting language that is similar to JavaScript but is simpler to use. Also, unlike JavaScript, CFScript only runs on the ColdFusion server; it does not run on the client system. A CFScript script can use all ColdFusion functions and all ColdFusion variables that are available in the script’s scope.

CFScript provides a compact and efficient way to write ColdFusion logic. Typical uses of CFScript include:

  • Simplifying and speeding variable setting
  • Building compact flow control structures
  • Encapsulating business logic in user-defined functions

The following sample script populates an array and locates the first array entry that starts with the word "key". It shows several of the elements of CFScript, including setting variables, loop structures, script code blocks, and function calls. Also, the code uses a cfoutput tag to display its results. Although you can use CFScript for output, the cfoutput tag is usually easier to use.

<cfscript>
strings = ArrayNew(1);
strings[1]="the";
strings[2]="key to our";
strings[4]="idea";
for( i=1 ; i LE 4 ; i = i+1 )
{
    if(Find("key",strings[i],1))
        break; }
</cfscript>
<cfoutput>Entry #i# starts with "key"</cfoutput><br>

You use CFScript to create user-defined functions.

For more information on CFScript, see Extending ColdFusion Pages with CFML Scripting. For more information on user-defined functions, see Writing and Calling User-Defined Functions.
Previous


Using ColdFusion Variables

Macromedia ColdFusion variables are the most frequently used operands in ColdFusion expressions. Variable values can be set and reset, and can be passed as attributes to CFML tags. Variables can be passed as parameters to functions, and can replace most constants.

This chapter describes how to create and use ColdFusion variables. It includes the following information:

  • How variables can represent different types of data
  • How the data types get converted
  • How variables exist in different scopes
  • How the scopes are used
  • How to use variables correctly

Contents

Creating variables

Variable characteristics

Data types

Using periods in variable references

Data type conversion

About scopes

Ensuring variable existence

Validating data

Passing variables to custom tags and UDFs
Next


Creating variables

You create most ColdFusion variables by assigning them values. (You must use the ArrayNew function to create arrays.) Most commonly, you create variables by using the cfset tag. You can also use the cfparam tag, and assignment statements in CFScript. Tags that create data objects also create variables. For example, the cfquery tag creates a query object variable.

ColdFusion automatically creates some variables that provide information about the results of certain tags or operations. ColdFusion also automatically generates variables in certain scopes, such as Client and Server. For information on these special variables, see Reserved Words and Variables in CFML Reference and the documentation of the CFML tags that create these variables.

ColdFusion generates an error when it tries to use a variable before it is created. This can happen, for example, when processing data from an incompletely filled form. To prevent such errors, test for the variable’s existence before you use it. For more information on testing for variable existence, see Ensuring variable existence.

For more information on how to create variables, see Creating and using variables in scopes.


Variable naming rules

ColdFusion variable names, including form field names and custom function and ColdFusion component argument names, must conform to Java naming rules and the following guidelines:

  • A variable name must begin with a letter, underscore, or Unicode currency symbol.
  • The initial character can by followed by any number of letters, numbers, underscore characters, and Unicode currency symbols.
  • A variable name cannot contain spaces.
  • A query result is a type of variable, so it overwrites a local variable with the same name.
  • ColdFusion variables are not case-sensitive. However, consistent capitalization makes the code easier to read.
  • When creating a form with fields that are used in a query, match form field names with the corresponding database field names.
  • Periods separate the components of structure or object names. They also separate a variable scope from the variable name. You cannot use periods in simple variable names, with the exception of variables in the Cookie and Client scopes. For more information on using periods, see Using periods in variable references.

The following rule applies to variable names, but does not apply to form field and argument names:

  • Prefix each variable’s name with its scope. Although some ColdFusion programmers do not use the Variables prefix for local variable names, you should use prefixes for all other scopes. Using scope prefixes makes variable names clearer and increases code efficiency. In many cases, you must prefix the scope. For more information, see About scopes.

Note: In some cases, when you use an existing variable name, you must enclose it with number signs (#) to allow ColdFusion to distinguish it from string or HTML text, and to insert its value, as opposed to its name. For more information, see Using number signs.


Variable characteristics

You can classify a variable using the following characteristics:

  • The data type of the variable value, which indicates the kind of information a variable represents, such as number, string, or date
  • The scope of the variable, which indicates where the information is available and how long the variable persists

The following sections provide detailed information on Data types and scopes.


Data types

ColdFusion is often referred to as typeless because you do not assign types to variables and ColdFusion does not associate a type with the variable name. However, the data that a variable represents does have a type, and the data type affects how ColdFusion evaluates an expression or function argument. ColdFusion can automatically convert many data types into others when it evaluates expressions. For simple data, such as numbers and strings, the data type is unimportant until the variable is used in an expression or as a function argument.

ColdFusion variable data belongs to one of the following type categories:

  • Simple One value. Can use directly in ColdFusion expressions. Include numbers, strings, Boolean values, and date-time values.
  • Complex A container for data. Generally represent more than one value. ColdFusion built-in complex data types include arrays, structures, queries, and XML document objects.

    You cannot use a complex variable, such as an array, directly in a ColdFusion expression, but you can use simple data type elements of a complex variable in an expression.

    For example, with a one-dimensional array of numbers called myArray, you cannot use the expression myArray * 5. However, you could use an expression myArray[3] * 5 to multiply the third element in the array by five.

  • Binary Raw data, such as the contents of a GIF file or an executable program file.
  • Objects Complex constructs. Often encapsulate both data and functional operations. The following table lists the types of objects that ColdFusion can use, and identifies the chapters that describe how to use them:

    Object type

    See

    Component Object Model (COM)

    Integrating COM and CORBA Objects in CFML Applications

    Common Object Request Broker Architecture (CORBA)

    Integrating COM and CORBA Objects in CFML Applications

    Java

    Integrating J2EE and Java Elements in CFML Applications

    ColdFusion component

    Building and Using ColdFusion Components

    Web service

    Using Web Services

Data type notes

Although ColdFusion variables do not have types, it is often convenient to use "variable type" as a shorthand for the type of data that the variable represents.

ColdFusion can validate the type of data contained in form fields and query parameters. For more information, see SELECT * FROM Departmt WHERE Dept_Name IN ('Marketing','Sales') and Using cfqueryparam.

The cfdump tag displays the entire contents of a variable, including ColdFusion complex data structures. It is an excellent tool for debugging complex data and the code that handles it.

ColdFusion provides the following functions for identifying the data type of a variable:

  • IsArray
  • IsBinary
  • IsBoolean
  • IsObject
  • IsQuery
  • IsSimpleValue
  • IsStruct
  • IsXmlDoc

ColdFusion also includes the following functions for determining whether a string can be represented as or converted to another data type:

  • IsDate
  • IsNumeric
  • IsXML

ColdFusion does not use a null data type. However, if ColdFusion receives a null value from an external source such as a database, a Java object, or some other mechanism, it maintains the null value until you use it as a simple value. At that time, ColdFusion converts the null to an empty string (""). Also, you can use the JavaCast function in a call to a Java object to convert a ColdFusion empty string to a Java null.


Numbers

ColdFusion supports integers and real numbers. You can intermix integers and real numbers in expressions; for example, 1.2 + 3 evaluates to 4.2.


Integers

ColdFusion supports integers between -2,147,483,648 and 2,147,483,647 (32-bit signed integers). You can assign a value outside this range to a variable, but ColdFusion initially stores the number as a string. If you use it in an arithmetic expression, ColdFusion converts it into a floating point value, preserving its value, but losing precision as the following example shows:

<cfset mybignum=12345678901234567890>
<cfset mybignumtimes10=(mybignum * 10)>
<cfoutput>mybignum is: #mybignum#</cfoutput><br>
<cfoutput>mybignumtimes10 is: #mybignumtimes10# </cfoutput><br>

This example generates the following output:

mybignum is: 12345678901234567890
mybignumtimes10 is: 1.23456789012E+020


Real numbers

Real numbers, numbers with a decimal part, are also known as floating point numbers. ColdFusion real numbers can range from approximately -10300 to approximately 10300. A real number can have up to 12 significant digits. As with integers, you can assign a variable a value with more digits, but the data is stored as a string. The string is converted to a real number, and can lose precision, when you use it in an arithmetic expression.

You can represent real numbers in scientific notation. This format is xEy, where x is a positive or negative real number in the range 1.0 (inclusive) to 10 (exclusive), and y is an integer. The value of a number in scientific notation is x times 10y. For example, 4.0E2 is 4.0 times 102, which equals 400. Similarly, 2.5E-2 is 2.5 times 10-2, which equals 0.025. Scientific notation is useful for writing very large and very small numbers.


Strings

In ColdFusion, text values are stored in strings. You specify strings by enclosing them in either single- or double-quotation marks. For example, the following two strings are equivalent:

"This is a string"
'This is a string'

You can write an empty string in the following ways:

  • "" (a pair of double-quotation marks with nothing in between)
  • '' (a pair of single-quotation marks with nothing in between)

Strings can be any length, limited by the amount of available memory on the ColdFusion server. However, the default size limit for long text retrieval (CLOB) is 64K. The ColdFusion MX Administrator lets you increase the limit for database string transfers, but doing so can reduce server performance. To change the limit, select the Enable retrieval of long text option on the Advanced Settings page for the data source.

Escaping quotation marks and number signs

To include a single-quotation character in a string that is single-quoted, use two single-quotation marks (known as escaping the single-quotation mark). The following example uses escaped single-quotation marks:

<cfset myString='This is a single-quotation mark: '' This is a double-quotation mark: "'>
<cfoutput>#mystring#</cfoutput><br>

To include a double-quotation mark in a double-quoted string, use two double-quotation marks (known as escaping the double-quotation mark). The following example uses escaped double-quotation marks:

<cfset myString="This is a single-quotation mark: ' This is a double-quotation mark: """>
<cfoutput>#mystring#</cfoutput><br>

Because strings can be in either double-quotation marks or single-quotation marks, both of the preceding examples display the same text:

This is a single-quotation mark: ' This is a double-quotation mark: "

To insert a number sign (#) in a string, you must escape the number sign, as follows:

"This is a number sign ##"

Lists

ColdFusion includes functions that operate on lists, but it does not have a list data type. In ColdFusion, a list is just a string that consists of multiple entries separated by delimiter characters.

The default delimiter for lists is the comma. If you use any other character to separate list elements, you must specify the delimiter in the list function. You can also specify multiple delimiter characters. For example, you can tell ColdFusion to interpret a comma or a semicolon as a delimiter, as the following example shows:

<cfset MyList="1,2;3,4;5">
<cfoutput>
List length using ; and , as delimiters: #listlen(Mylist, ";,")#<br>
List length using only , as a delimiter: #listlen(Mylist)#<br>
</cfoutput>

This example displays the following output:

List length using ; and , as delimiters: 5
List length using only , as a delimiter: 3

Each delimiter must be a single character. For example, you cannot tell ColdFusion to require two hyphens in a row as a delimiter.

If a list has two delimiters in a row, ColdFusion ignores the empty element. For example, if MyList is "1,2,,3,,4,,,5" and the delimiter is the comma, the list has five elements and list functions treat it the same as "1,2,3,4,5".


Boolean values

A Boolean value represents whether something is true or false. ColdFusion has two special constants--True and False--to represent these values. For example, the Boolean expression 1 IS 1 evaluates to True. The expression "Monkey" CONTAINS "Money" evaluates to False.

You can use Boolean constants directly in expressions, as in the following example:

<cfset UserHasBeenHere = True>

In Boolean expressions, True, nonzero numbers, and the string "Yes" are equivalent, and False, 0, and the string "No" are equivalent.

In Boolean expressions, True, nonzero numbers, and the strings "Yes", "1|", "True" are equivalent; and False, 0, and the strings "No", "0", and "False" are equivalent.

Boolean evaluation is not case-sensitive. For example, True, TRUE, and true are equivalent.


Date-Time values

ColdFusion can perform operations on date and time values. Date-time values identify a date and time in the range 100 AD to 9999 AD. Although you can specify just a date or a time, ColdFusion uses one data type representation, called a date-time object, for date, time, and date and time values.

ColdFusion provides many functions to create and manipulate date-time values and to return all or part of the value in several different formats.

You can enter date and time values directly in a cfset tag with a constant, as follows:

<cfset myDate = "October 30, 2001">

When you do this, ColdFusion stores the information as a string. If you use a date-time function, ColdFusion stores the value as a date-time object, which is a separate simple data type. When possible, use date-time functions such as CreateDate and CreateTime to specify dates and times, because these functions can prevent you from specifying the date or time in an invalid format and they create a date-time object immediately.


Date and time formats

You can directly enter a date, time, or date and time, using standard U.S. date formats. ColdFusion processes the two-digit-year values 0 to 29 as twenty-first century dates; it processes the two-digit-year values 30 to 99 as twentieth century dates. Time values can include units down to seconds. The following table lists valid date and time formats:

To specify | Use these formats
Date | October 30, 2003 Oct 30, 2003 Oct. 30, 2003 10/30/03 2003-10-30 10-30-2003
Time | 02:34:12 2:34a 2:34am 02:34am 2am
Date and Time | Any combination of valid date and time formats, such as these: October 30, 2003 02:34:12 Oct 30, 2003 2:34a Oct. 30, 2001 2:34am 10/30/03 02:34am 2003-10-30 2am 10-30-2003 2am


Locale-specific dates and times

ColdFusion provides several functions that let you input and output dates and times (and numbers and currency values) in formats that are specific to the current locale. A locale identifies a language and locality, such as English (US) or French (Swiss). Use these functions to input or output dates and times in formats other than the U.S. standard formats. (Use the SetLocale function to specify the locale.) The following example shows how to do this:

<cfset oldlocale = SetLocale("French (Standard)")>
<cfoutput>#LSDateFormat(Now(), "ddd, dd mmmm, yyyy")#</cfoutput>

This example outputs a line like the following:

mar., 03 juin, 2003

For more information on international functions, see Developing Globalized Applications and CFML Reference.


How ColdFusion stores dates and times

ColdFusion stores and manipulates dates and times as date-time objects. Date-time objects store data on a time line as real numbers. This storage method increases processing efficiency and directly mimics the method used by many popular database systems. In date-time objects, one day is equal to the difference between two successive integers. The time portion of the date-and-time value is stored in the fractional part of the real number. The value 0 represents 12:00 AM 12/30/1899.

Although you can use arithmetic operations to manipulate date-and-time values directly, this method can result in code that is difficult to understand and maintain. Use the ColdFusion date-time manipulation functions instead. For information on these functions, see the CFML Reference.


Binary data type and binary encoding

Binary data (also referred to as a binary object) is raw data, such as the contents of a GIF file or an executable program file. You do not normally use binary data directly, but you can use the cffile tag to read a binary file into a variable, typically for conversion to a string binary encoding before transmitting the file using e-mail.

A string binary encoding represents a binary value in a string format that can be transmitted over the web. ColdFusion MX supports three binary encoding formats:

Encoding | Format
Base64 | Encodes the binary data in the lowest six bits of each byte. It ensures that binary data and non-ANSI character data can be transmitted using e-mail without corruption. The Base64 algorithm is specified by IETF RFC 2045, at www.ietf.org/rfc/rfc2045.txt.
Hex | Uses two characters in the range 0-9 and A-F represent the hexadecimal value of each byte; for example, 3A.
UU | Uses the UNIX UUencode algorithm to convert the data.

ColdFusion provides the following functions that convert among string data, binary data, and string encoded binary data:

Function | Description
BinaryDecode | Converts a string that contains encoded binary data to a binary object.
BinaryEncode | Converts binary data to an encoded string.
CharsetDecode | Converts a string to binary data in a specified character encoding.
CharsetEncode | Converts a binary object to a string in a specified character encoding.
ToBase64 | Converts string and binary data to Base64 encoded data Macromedia recommends using the BinaryEncode function, instead of this function, to convert binary data to Base64 in new applications.
ToBinary | Converts Base64 encoded data to binary data. Macromedia recommends using the BinaryDecode function, instead of this function, in new applications.
ToString | Converts most simple data types to string data. It can convert numbers, date-time objects, and boolean values. (It converts date-time objects to ODBC timestamp strings.) Macromedia recommends that you use the CharsetEncode function to convert binary data to a string in new applications.


Complex data types

Arrays, structures, and queries are ColdFusion built-in complex data types. Structures and queries are sometimes referred to as objects, because they are containers for data, not individual data values.

For details on using arrays and structures, see Using Arrays and Structures.

Complex data type topics are as follows:

  • Arrays
  • Structures
  • Queries
  • Working with structures and queries


Arrays

Arrays are a way of storing multiple values in a table-like format that can have one or more dimensions. To create an array and specify its initial dimensions, use the ColdFusion ArrayNew function. For example, the following line creates an empty two-dimensional array:

<cfset myarray=ArrayNew(2)>

You reference elements using numeric indexes, with one index for each dimension. For example, the following line sets one element of a two-dimensional array to the current date and time:

<cfset myarray[1][2]=Now()>

The ArrayNew function can create arrays with up to three dimensions. However, there is no limit on array size or maximum dimension. To create arrays with more than three dimensions, create arrays of arrays.

After you create an array, you can use functions or direct references to manipulate its contents.

When you assign an existing array to a new variable, ColdFusion creates a new array and copies the old array’s contents to the new array. The following example creates a copy of the original array:

<cfset newArray=myArray>

For more information on using arrays, see Using Arrays and Structures.


Structures

ColdFusion structures consist of key-value pairs, where the keys are text strings and the values can be any ColdFusion data type, including other structures. Structures let you build a collection of related variables that are grouped under a single name. To create a structure, use the ColdFusion StructNew function. For example, the following line creates a new, empty, structure called depts:

<cfset depts=StructNew()>

You can also create a structure by assigning a value in the structure. For example, the following line creates a new structure called MyStruct with a key named MyValue, equal to 2:

<cfset MyStruct.MyValue=2>

Note: In previous ColdFusion versions, this line created a Variables scope variable named "MyStruct.MyValue" with the value 2.

After you create a structure, you can use functions or direct references to manipulate its contents, including adding key-value pairs.

You can use either of the following methods to reference elements stored in a structure:

  • StructureName.KeyName
  • StructureName["KeyName"]

The following examples show these methods:

depts.John="Sales"
depts["John"]="Sales"

When you assign an existing structure to a new variable, ColdFusion does not create a new structure. Instead, the new variable accesses the same data (location) in memory as the original structure variable. In other words, both variables are references to the same object.

For example, the following line creates a new variable, myStructure2, that is a reference to the same structure as the myStructure variable:

<cfset myStructure2=myStructure>

When you change the contents of myStructure2, you also change the contents of myStructure. To copy the contents of a structure, use the ColdFusion Duplicate function, which copies the contents of structures and other complex data types.

Structure key names can be the names of complex data objects, including structures or arrays. This lets you create arbitrarily complex structures.

For more information on using structures, see Using Arrays and Structures.


Queries

A query object, sometimes referred to as a query, query result, or record set, is a complex ColdFusion data type that represents data in a set of named columns, similar to the columns of a database table. The following ColdFusion tags can create query objects:

  • cfquery
  • cfdirectory
  • cfhttp
  • cfldap
  • cfpop
  • cfprocresult

In these tags, the name attribute specifies the query object’s variable name. The QueryNew function also creates query objects.

When you assign a query to a new variable, ColdFusion does not copy the query object. Instead, both names point to the same record set data. For example, the following line creates a new variable, myQuery2, that references the same record set as the myQuery variable:

<cfset myQuery2 = myQuery>

If you make changes to data in myQuery, myQuery2 also shows those changes.

You reference query columns by specifying the query name, a period, and the column name; for example:

myQuery.Dept_ID

When you reference query columns inside tags, such as cfoutput and cfloop, in which you specify the query name in a tag attribute, you do not have to specify the query name.

You can access query columns as if they are one-dimensional arrays. For example, the following line assigns the contents of the Employee column in the second row of the myQuery query to the variable myVar:

<cfset myVar = myQuery.Employee[2]>

Note: You cannot use array notation to refer to a row (of all columns) of a query. For example, myQuery[2] does not refer to the second row of the myQuery query object.


Working with structures and queries

Because structure variables and query variables are references to objects, the rules in the following sections apply to both types of data.

Multiple references to an object

When multiple variables refer to a structure or query object, the object continues to exist as long as at least one reference to the object exists. The following example shows how this works:

<cfscript> depts = structnew();</cfscript>
<cfset newStructure=depts>
<cfset depts.John="Sales">
<cfset depts=0>
<cfoutput>
    #newStructure.John#<br>
    #depts#
</cfoutput>

This example displays the following output:

Sales
0

After the <cfset depts=0> tag executes, the depts variable does not refer to a structure; it is a simple variable with the value 0. However, the variable newStructure still refers to the original structure object.

Assigning objects to scopes

You can give a query or structure a different scope by assigning it to a new variable in the other scope. For example, the following line creates a server variable, Server.SScopeQuery, using the local myquery variable:

<cfset Server.SScopeQuery = myquery>

To clear the server scope query variable, reassign the query object, as follows:

<cfset Server.SScopeQuery = 0>

This deletes the reference to the object from the server scope, but does not remove any other references that might exist.

Copying and duplicating objects

You can use the Duplicate function to make a true copy of a structure or query object. Changes to the copy do not affect the original.

Using a query column

When you are not inside a cfloop, cfoutput, or cfmail tag that has a query attribute, you can treat a query column as an array. However, query column references do not always behave as you might expect. This section explains the behavior of references to query columns using the results of the following cfquery tag in its examples:

<cfquery dataSource="cfdocexamples" name="myQuery">
    SELECT FirstName, LastName
    FROM Employee
</cfquery>

To reference elements in a query column, use the row number as an array index. For example, both of the following lines display the word "ben":

<cfoutput> #myQuery.Firstname[1]# </cfoutput><br>
<cfoutput> #myQuery["Firstname"][1]# </cfoutput><br>

ColdFusion behavior is less straightforward, however, when you use the query column references myQuery.Firstname and myQuery["Firstname"] without using an array index. The two reference formats produce different results.

If you refer to myQuery.Firstname, ColdFusion automatically converts it to the first row in the column. For example, the following lines print the word "ben":

<cfset myCol = myQuery.Firstname >
<cfoutput>#mycol#</cfoutput>

But the following lines display an error message:

<cfset myCol = myQuery.Firstname >
<cfoutput>#mycol[1]#</cfoutput><br>

If you refer to Query["Firstname"], ColdFusion does not automatically convert it to the first row of the column. For example, the following line results in an error message indicating that ColdFusion cannot convert a complex type to a simple value:

<cfoutput> #myQuery['Firstname']# </cfoutput><br>

Similarly, the following lines print the name "marjorie", the value of the second row in the column:

<cfset myCol = myQuery["Firstname"]>
<cfoutput>#mycol[2]#</cfoutput><br>

However, when you make an assignment that requires a simple value, ColdFusion automatically converts the query column to the value of the first row. For example, the following lines display the name "ben" twice:

<cfoutput> #myQuery.Firstname# </cfoutput><br>
<cfset myVar= myQuery['Firstname']>
<cfoutput> #myVar# </cfoutput><br>


Using periods in variable references

ColdFusion uses the period (.) to separate elements of a complex variable such as a structure, query, XML document object, or external object, as in MyStruct.KeyName. A period also separates a variable scope identifier from the variable name, as in Variables.myVariable or CGI.HTTP_COOKIE.

With the exception of Cookie and Client scope variables, which must always be simple variable types, you cannot normally include periods in simple variable names. However, ColdFusion makes some exceptions that accommodate legacy and third-party code that does not conform to this requirement.

For more information, see About scopes, Using Arrays and Structures, and Using XML and WDDX.


Understanding variables and periods

The following descriptions use a sample variable named MyVar.a.b to explain how ColdFusion uses periods when getting and setting the variable value.


Getting a variable

ColdFusion can correctly get variable values even if the variable name includes a period. For example, the following set of steps shows how ColdFusion gets MyVar.a.b, as in <cfset Var2 = myVar.a.b> or IsDefined(myVar.a.b):

  1. Looks for myVar in an internal table of names (the symbol table).
  2. If myVar is the name of a complex object, including a scope, looks for an element named a in the object.

    If myVar is not the name of a complex object, checks whether myVar.a is the name of a complex object and skips step 3.

  3. If myVar is the name of a complex object, checks whether a is a complex object.
  4. If a or myVar.a is the name of a complex object, checks whether b is the name of a simple variable, and returns the value of b.

    If myVar is a complex object but a is not a complex object, checks whether a.b is the name of a simple variable and returns its value.

    If myVar.a is not a complex object, checks whether myVar.a.b is the name of a simple variable and returns its value.

This way, ColdFusion correctly resolves the variable name and can get its value.

You can also use array notation to get a simple variable with a name that includes periods. In this form of array notation, you use the scope name (or the complex variable that contains the simple variable) as the "array" name. You put the simple variable name, in single- or double-quotation marks, inside the square brackets.

Using array notation is more efficient than using plain dot notation because ColdFusion does not have to analyze and look up all the possible key combinations. For example, both of the following lines write the value of myVar.a.b, but the second line is more efficient than the first:

<cfoutput>myVar.a.b is: #myVar.a.b#<br></cfoutput>
<cfoutput>myVar.a.b is: #Variables["myVar.a.b"]#<br></cfoutput>


Setting a variable

ColdFusion cannot be as flexible when it sets a variable value as when it gets a variable, because it must determine the type of variable to create or set. Therefore, the rules for variable names that you set are stricter. Also, the rules vary depending on whether the first part of the variable name is the Cookie or Client scope identifier.

For example, assume you have the following code:

<cfset myVar.a.b = "This is a test">

If a variable myVar does not exist, it does the following:

  1. Creates a structure named myVar.
  2. Creates a structure named a in the structure myVar.
  3. Creates a key named b in myVar.a.
  4. Gives it the value "This is a test".

If either myVar or myVar.a exist and neither one is a structure, ColdFusion generates an error.

In other words, ColdFusion uses the same rules as for getting a variable to resolve the variable name until it finds a name that does not exist yet. It then creates any structures that are needed to create a key named b inside a structure, and assigns the value to the key.

However, if the name before the first period is either Cookie or Client, ColdFusion uses a different rule. It treats all the text (including any periods) that follow the scope name as the name of a simple variable, because Cookie and Client scope variables must be simple. If you have the following code, you see that ColdFusion creates a single, simple Client scope variable named myVar.a.b:

<cfset Client.myVar.a.b = "This is a test">
<cfdump var=#Client.myVar.a.b#>


Creating variables with periods

You should avoid creating the names of variables (except for dot notation in structures) that include periods. However, ColdFusion provides mechanisms for handling cases where you must do so, for example, to maintain compatibility with names of variables in external data sources or to integrate your application with existing code that uses periods in variable names. The following sections describe how to create simple variable names that include periods.

Using brackets to create variables with periods

You can create a variable name that includes periods by using associative array structure notation, as described in Structure notation. To do so, you must do the following:

  • Refer to the variable as part of a structure. You can always do this, because ColdFusion considers all scopes to be structures. For more information on scopes, see About scopes.
  • Put the variable name that must include a period inside square brackets and single- or double-quotation marks.

The following example shows this technique:

<cfset Variables['My.Variable.With.Periods'] = 12>
<cfset Request["Another.Variable.With.Periods"] = "Test variable">
<cfoutput>
    My.Variable.With.Periods is: #My.Variable.With.Periods#<br>
    Request.Another.Variable.With.Periods is:
        #Request.Another.Variable.With.Periods#<br>
</cfoutput>

Creating Client and Cookie variables with periods

To create a Client or Cookie variable with a name that includes one or more periods, simply assign the variable a value. For example, the following line creates a Cookie named User.Preferences.CreditCard:

<cfset Cookie.User.Preferences.CreditCard="Discover">


Data type conversion

ColdFusion automatically converts between data types to satisfy the requirements of an expression’s operations, including a function’s argument requirements. As a result, you generally don’t need to be concerned about compatibility between data types and the conversions from one data type to another. However, understanding how ColdFusion evaluates data values and converts data between types can help you prevent errors and create code more effectively.

This discussion contains the following topics:

  • Operation-driven evaluation
  • Conversion between types
  • Evaluation and type conversion issues
  • Examples of type conversion in expression evaluation


Operation-driven evaluation

Conventional programming languages enforce strict rules about mixing objects of different types in expressions. For example, in a language such as C++ or Basic, the expression ("8" * 10) produces an error because the multiplication operator requires two numerical operands and "8" is a string. When you program in such languages, you must convert between data types to ensure error-free program execution. For example, the previous expression might have to be written as (ToNumber("8") * 10).

In ColdFusion, however, the expression ("8" * 10) evaluates to the number 80 without generating an error. When ColdFusion processes the multiplication operator, it automatically attempts to convert its operands to numbers. Since "8" can be successfully converted to the number 8, the expression evaluates to 80.

ColdFusion processes expressions and functions in the following sequence:

  1. For each operator in an expression, it determines the required operands. (For example, the multiplication operator requires numeric operands and the CONTAINS operator requires string operands.)

    For functions, it determines the type required for each function argument. (For example, the Min function requires two numbers as arguments and the Len function requires a string.)

  2. It evaluates all operands or function arguments.
  3. It converts all operands or arguments whose types differ from the required type. If a conversion fails, it reports an error.


Conversion between types

Although the expression evaluation mechanism in ColdFusion is very powerful, it cannot automatically convert all data. For example, the expression "eight" * 10 produces an error because ColdFusion cannot convert the string "eight" to the number 8. Therefore, you must understand the rules for conversion between data types.

The following table explains how conversions are performed. The first column shows values to convert. The remaining columns show the result of conversion to the listed data type.

Value | As Boolean | As number | As date-time | As string
"Yes" | True | 1 | Error | "Yes"
"No" | False | 0 | Error | "No"
True | True | 1 | Error | "Yes"
False | False | 0 | Error | "No"
Number | True if Number is not 0; False otherwise. | Number | See "Date-time values" earlier in this chapter. | String representation of the number (for example, "8").
String | If "Yes", True If "No", False If it can be converted to 0, False If it can be converted to any other number, True | If it represents a number (for example, "1,000" or "12.36E-12"), it is converted to the corresponding number. If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. | If it is an ODBC date, time, or timestamp (for example "{ts '2001-06-14 11:30:13'}", or if it is expressed in a standard U.S. date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value. Days of the week or unusual punctuation result in an error. Dashes, forward-slashes, and spaces are generally allowed. | String
Date | Error | The numeric value of the date-time object. | Date | An ODBC timestamp.

ColdFusion cannot convert complex types, such as arrays, queries, and COM objects, to other types. However, it can convert simple data elements of complex types to other simple data types.

Type conversion considerations

The following sections detail specific rules and considerations for converting between types.

The cfoutput tag

The cfoutput tag always displays data as a string. As a result, when you display a variable using the cfoutput tag, ColdFusion applies the type conversion rules to any non-string data before displaying it. For example, the cfoutput tag displays a date-time value as an ODBC timestamp.

Case-insensitivity and Boolean conversion

Because ColdFusion expression evaluation is not case-sensitive, Yes, YES, and yes are equivalent; False, FALSE, and false are equivalent; No, NO, and no are equivalent; and True, TRUE, and true are equivalent.

Converting binary data

ColdFusion cannot automatically convert binary data to other data types. To convert binary data, use the ToBase64 and ToString functions. For more information, see Binary data type and binary encoding.

Converting date and time data

To ensure that a date and time value is expressed as a real number, add zero to the variable. The following example shows this:

<cfset mynow = now()>
Use cfoutput to display the result of the now function:<br>
<cfoutput>#mynow#</cfoutput><br>
Now add 0 to the result and display it again:<br>
<cfset mynow = mynow + 0>
<cfoutput>#mynow#</cfoutput>

At 1:06 PM on June 6, 2003, its output looked like this:

Use cfoutput to display the result of the now function:
{ts '2003-06-03 13:06:44'}
Now add 0 to the result and display it again:
37775.5463426

Converting numeric values

When ColdFusion evaluates an expression that includes both integers and real numbers, the result is a real number. To convert a real number to an integer, use a ColdFusion function. The Int, Round, Fix, and Ceiling functions convert real numbers to integers, and differ in their treatment of the fractional part of the number.

If you use a hidden form field with a name that has the suffix _integer or _range to validate a form input field, ColdFusion truncates real numbers entered into the field and passes the resulting integer to the action page.

If you use a hidden form field with a name that has the suffix _integer, _float, or _range to validate a form input field, and the entered data contains a dollar amount (including a dollar sign) or a numeric value with commas, ColdFusion considers the input to be valid, removes the dollar sign or commas from the value, and passes the resulting integer or real number to the action page.


Evaluation and type conversion issues

The following sections explain several issues that you might encounter with type evaluation and conversion.

Comparing variables to True or False

You might expect the following two cfif tag examples to produce the same results:

<cfif myVariable>
    <cfoutput>myVariable equals #myVariable# and is True
    </cfoutput>
</cfif>
<cfif myVariable IS True>
    <cfoutput>myVariable equals #myVariable# and is True
    </cfoutput>
</cfif>

However, if myVariable has a numeric value such as 12, only the first example produces a result. In the second case, the value of myVariable is not converted to a Boolean data type, because the IS operator does not require a specific data type and just tests the two values for identity. Therefore, ColdFusion compares the value 12 with the constant True. The two are not equal, so nothing is printed. If myVariable is 1, "Yes", or True, however, both examples print the same result, because ColdFusion considers these to be identical to Boolean True.

If you use the following code, the output statement does display, because the value of the variable, 12, is not equal to the Boolean value False:

<cfif myVariable IS NOT False>
<cfoutput>myVariable equals #myVariable# and IS NOT False
</cfoutput>
</cfif>

As a result, you should use the test <cfif testvariable>, and not use the IS comparison operator when testing whether a variable is True or False. This issue is a case of the more general problem of ambiguous type expression evaluation, described in the following section.

Ambiguous type expressions and strings

When ColdFusion evaluates an expression that does not require strings, including all comparison operations, such as IS or GT, it checks whether it can convert each string value to a number or date-time object. If so, ColdFusion converts it to the corresponding number or date-time value (which is stored as a number). It then uses the number in the expression.

Short strings, such as 1a and 2P, can produce unexpected results. ColdFusion can interpret a single "a" as AM and a single "P" as PM. This can cause ColdFusion to interpret strings as date-time values in cases where this was not intended.

Similarly, if the strings can be interpreted as numbers, you might get unexpected results.

For example, ColdFusion interprets the following expressions as shown:

Expression

Interpretation

<cfif "1a" EQ "01:00">

If 1:00am is 1:00am.

<cfif "1P" GT "2A">

If 1:00pm is later than 2:00am.

<cfset age="4a">
<cfset age=age + 7>

Treat the variable age as 4:00 am, convert it to the date-time value 0.16666666667, and add 7 to make it 7.16666666667.

<cfif "0.0" is "0">

If 0 is 0.

To prevent such ambiguities when you compare strings, use the ColdFusion string comparison functions Compare and CompareNoCase, instead of the comparison operators.

You can also use the IsDate function to determine whether a string can be interpreted as a date-time value, or to add characters to a string before comparison to avoid incorrect interpretation.

Date-time functions and queries when ODBC is not supported

Many CFML functions, including the Now, CreateDate, CreateTime, and CreateDateTime functions, return date-time objects. ColdFusion creates Open Database Connectivity (ODBC) timestamp values when it converts date-time objects to strings. As a result, you might get unexpected results when using dates with a database driver that does not support ODBC escape sequences, or when you use SQL in a query of queries.

If you use SQL to insert data into a database or in a WHERE clause to select data from a database, and the database driver does not support ODBC-formatted dates, use the DateFormat function to convert the date-time value to a valid format for the driver. This rule also applies to queries of queries.

For example, the following SQL statement uses the DateFormat function in a query of queries to select rows that have MyDate values in the future:

<cfquery name="MyQofQQ" dbtype="query">
SELECT *
FROM DateQuery
WHERE MyDate >= '#DateFormat(Now())#'
</cfquery>

The following query of queries fails with the error message "Error: {ts is not a valid date," because the ColdFusion Now function returns an ODBC timestamp:

<cfquery name="MyQofQQ" dbtype="query">
SELECT *
FROM DateQuery
WHERE MyDate >= '#now()#'
</cfquery>

Using JavaCast with overloaded Java methods

You can overload Java methods so a class can have several identically named methods that differ only in parameter data types. At runtime, the Java virtual machine attempts to resolve the specific method to use, based on the types of the parameters passed in the call. Because ColdFusion does not use explicit types, you cannot predict which version of the method the virtual machine will use.

The ColdFusion JavaCast function helps you ensure that the right method executes by specifying the Java type of a variable, as in the following example:

<cfset emp.SetJobGrade(JavaCast("int", JobGrade))>

The JavaCast function takes two parameters: a string representing the Java data type and the variable whose type you are setting. You can specify the following Java data types: bool, int, long, float, double, and String.

For more information on the JavaCast function, see CFML Reference.

Using quotation marks

To ensure that ColdFusion properly interprets string data, surround strings in single- or double-quotation marks. For example, ColdFusion evaluates "10/2/2001" as a string that can be converted into a date-time object. However, it evaluates 10/2/2001 as a mathematical expression, 5/2001, which evaluates to 0.00249875062469.


Examples of type conversion in expression evaluation

The following examples demonstrate ColdFusion expression evaluation.

Example 1

2 * True + "YES" - ('y' & "es")

Result value as string: "2"

Explanation: (2*True) is equal to 2; ("YES"- "yes") is equal to 0; 2 + 0 equals 2.

Example 2

"Five is " & 5

Result value as string: "Five is 5"

Explanation: 5 is converted to the string "5".

Example 3

DateFormat("October 30, 2001" + 1)

Result value as string: "31-Oct-01"

Explanation: The addition operator forces the string "October 30, 2001" to be converted to a date-time object, and then to a number. The number is incremented by one. The DateFormat function requires its argument to be a date-time object; thus, the result of the addition is converted to a date-time object. One is added to the date-time object, moving it ahead by one day to October 31, 2001.


About scopes

Variables differ in how they are set (by your code or by ColdFusion), the places in your code where they are meaningful, and how long their values persist. These considerations are generally referred to as a variable’s scope. Commonly used scopes include the Variables scope, the default scope for variables that you create, and the Request scope, which is available for the duration of an HTTP request.

Note: User-defined functions also belong to scopes. For more information, see Specifying the scope of a function.

This section includes the following topics:

  • Scope types
  • Creating and using variables in scopes
  • Using scopes


Scope types

The following table describes ColdFusion scopes:

Scope

Description

Variables (local)

The default scope for variables of any type that are created with the cfset and cfparam tags. A local variable is available only on the page on which it is created and any included pages (see also the Caller scope).

Form

Contains variables passed from a Form page to its action page as the result of submitting the form. (If you use the HTML form tag, you must use method="post".) For more information, see Introduction to Retrieving and Formatting Data.

URL

Contains parameters passed to the current page in the URL that is used to call it. The parameters are appended to the URL in the format ?variablename = value[&variablename=value...]; for example www.MyCompany.com/inputpage.cfm?productCode=A12CD1510&quantity=3.

Note: If a URL includes multiple parameters with the same name, the resulting variable in the ColdFusion URL scope consists of all parameter values separated by commas. For example, a URL of the form http://localhost/urlparamtest.cfm? param=1&param=2&param=3 results in a URL.param variable value of 1,2,3 on the ColdFusion page.

Attributes

Used only in custom tag pages. Contains the values passed by the calling page in the custom tag’s attributes. For more information, see Creating and Using Custom CFML Tags.

Caller

Used only in custom tag pages. The custom tag’s Caller scope is a reference to the calling page’s Variables scope. Any variables that you create or change in the custom tag page using the Caller scope are visible in the calling page’s Variables scope. For more information, see Creating and Using Custom CFML Tags.

ThisTag

Used only in custom tag pages. The ThisTag scope is active for the current invocation of the tag. If a custom tag contains a nested tag, any ThisTag scope values you set before calling the nested tag are preserved when the nested tag returns to the calling tag.

The ThisTag scope includes three built-in variables that identify the tag’s execution mode, contain the tag’s generated contents, and indicate whether the tag has an end tag.

A nested custom tag can use the cfassociate tag to return values to the calling tag’s ThisTag scope. For more information, see Accessing tag instance data.

Request

Used to hold data that must be available for the duration of one HTTP request. The Request scope is available to all pages, including custom tags and nested custom tags, that are processed in response to the request.

This scope is useful for nested (child/parent) tags. This scope can often be used in place of the Application scope, to avoid the need for locking variables. Several chapters discuss using the Request scope.

CGI

Contains environment variables identifying the context in which a page was requested. The variables available depend on the browser and server software. For a list of the commonly used CGI variables, see Reserved Words and Variables in CFML Reference.

Cookie

Contains variables maintained in a user’s browser as cookies. Cookies are typically stored in a file on the browser, so they are available across browser sessions and applications. You can create memory-only Cookie variables, which are not available after the user closes the browser. Cookie scope variable names can include periods.

Client

Contains variables that are associated with one client. Client variables let you maintain state as a user moves from page to page in an application, and are available across browser sessions. By default, Client variables are stored in the system registry, but you can store them in a cookie or a database. Client variables cannot be complex data types and can include periods in their names. For more information, see Using Persistent Data and Locking.

Session

Contains variables that are associated with one client and persist only as long as the client maintains a session. They are stored in the server’s memory and can be set to time out after a period of inactivity. For more information, see Using Persistent Data and Locking.

Application

Contains variables that are associated with one, named application on a server. The cfapplication tag name attribute or the Application.cfc This.name variable setting specifies the application name. For more information, see Using Persistent Data and Locking.

Server

Contains variables that are associated with the current ColdFusion server. This scope lets you define variables that are available to all your ColdFusion pages, across multiple applications. For more information, see Using Persistent Data and Locking.

Flash

Variables sent by a Macromedia Flash movie to ColdFusion and returned by ColdFusion to the movie. For more information, see Using the Flash Remoting Service.

Arguments

Variables passed in a call to a user-defined function or ColdFusion component method. For more information, see About the Arguments scope.

This

Exists only in ColdFusion components or cffunction tags that are part of a containing object such as a ColdFusion Struct. Exists for the duration of the component instance or containing object. Data in the This scope is accessible from outside the component or container by using the instance or object name as a prefix.

function local

Contains variables that are declared inside a user-defined function or ColdFusion component method and exist only while a function executes. For more information, see Writing and Calling User-Defined Functions.

Caution: To prevent data corruption, you lock code that uses Session, Application, or Server scope variables. For more information, see Using Persistent Data and Locking.


Creating and using variables in scopes

The following table shows how you create and refer to variables in different scopes in your code. For more information on the mechanisms for creating variables in most scopes, see Creating variables.

Scope prefix (type) | Prefix required to reference | Where available | Created by
Variables (Local) | No | On the current page. Cannot be accessed by a form’s action page (unless the form page is also the action page). Variables in this scope used on a page that calls a custom tag can be accessed in the custom tag by using its Caller scope; however, they are not available to any nested custom tags. | Specifying the prefix Variables, or using no prefix, when you create the variable.
Form | No | On the action page of a form and in custom tags called by the action page; cannot be used on a form page that is not also the action page. | A form or cfform tag. Contains the values of form field tags (such as input) in the form body when the form is submitted. The variable name is the name of the form field.
URL | No | On the target page of the URL. | The system. Contains the parameters passed in the URL query string used to access the page.
Attributes | Yes | On the custom tag page. | The calling page passing the values to a custom tag page in the custom tag’s attributes.
Caller | On the custom tag page, Yes. On the calling page, No (Variables prefix is optional). | On the custom tag page, by using the Caller scope prefix. On the page that calls the custom tag, as local variables (Variables scope). | On the custom tag page, by specifying the prefix Caller when you create the variable. On the calling page, by specifying the prefix Variables, or using no prefix, when you create the variable.
ThisTag | Yes | On the custom tag page. | Specifying the prefix ThisTag when you create the variable in the tag or using the cfassociate tag in a nested custom tag.
Request | Yes | On the creating page and in any pages invoked during the current HTTP request after the variable is created, including in custom tags and nested custom tags. | Specifying the prefix Request when you create the variable.
CGI | No | On any page. Values are specific to the latest browser request. | The web server. Contains the server environment variables that result from the browser request.
Cffile | Yes | Following an invocation of cffile. | A cffile tag.
Cookie | No | For one client in one or more applications and pages, over multiple browser sessions. | A cfcookie tag. You can also set memory-only cookies by specifying the prefix Cookie when you create the variable.
Client | No | For one client in one application, over multiple browser sessions. | Specifying the prefix Client when you create the variable.
Session | Yes | For one client in one application and one browser session. Surround code that uses Session scope variables in cflock blocks. | Specifying the prefix Session when you create the variable.
Application | Yes | For multiple clients in one application over multiple browser sessions. Surround code that uses application variables in cflock blocks. | Specifying the prefix Application when you create the variable.
Server | Yes | To any page on the ColdFusion server. Surround all code that uses server variables in cflock blocks. | Specifying the prefix Server when you create the variable.
Flash | Yes | A ColdFusion page or ColdFusion component called by a Flash client. | The ColdFusion Client access. You assign a value to Flash.You can assign values to the Flash.result and Flash.pagesize variables.
Arguments | No | Within the body of a user-defined function or ColdFusion component method. | The calling page passing an argument in the function call.
This | Yes | Within a ColdFusion component or the body of a user-defined function that was created using the cffunction tag and put in an object, structure, or scope. In the containing page, through the component instance or containing object. | Within the component or function by specifying the prefix This when you create the variable. In the containing page, by specifying the component instance or object that contains the function as a prefix when you create the variable.
(function local, no prefix) | Prohibited | Within the body of a user-defined function or ColdFusion component method, only while the function executes. | In the function or method definition, a var keyword in a cfset tag or a CFScript var statement.


Using scopes

The following sections provide details on how you can create and use variables in different scopes.

Evaluating unscoped variables

If you use a variable name without a scope prefix, ColdFusion checks the scopes in the following order to find the variable:

  1. Function local (UDFs and CFCs only)
  2. Arguments
  3. Variables (local scope)
  4. CGI
  5. Cffile
  6. URL
  7. Form
  8. Cookie
  9. Client

Because ColdFusion must search for variables when you do not specify the scope, you can improve performance by specifying the scope for all variables.

To access variables in all other scopes, you must prefix the variable name with the scope identifier.

Scopes and CFX tags

ColdFusion scopes do not apply to ColdFusion Extension (CFX) tags, custom tags that you write in a programming language such as C++ or Java. The ColdFusion page that calls a CFX tag must use tag attributes to pass data to the CFX tag. The CFX tag must use the Java Request and Response interfaces or the C++ Request class to get and return data.

The Java setVariable Response interface method and C++ CCFX::SetVariable method return data to the Variables scope of the calling page. Therefore, they are equivalent to setting a Caller scope variable in a custom ColdFusion tag.

Using scopes as structures

ColdFusion makes all named scopes available as structures. You cannot access the function-local scope for user defined functions (UDFs) that you define using CFScript as a structure. (In ColdFusion 4.5 and 5, the following scopes are not available as structures: Variables, Caller, Client, and Server.)

You can reference the variables in named scopes as elements of a structure. To do so, specify the scope name as the structure name and the variable name as the key. For example, if you have a MyVar variable in the Request scope, you can refer to it in either of the following ways:

Request.MyVar
Request["MyVar"]

Similarly, you can use CFML structure functions to manipulate the contents of the scope. For more information on using structures, see Using Arrays and Structures.

Caution: Do not call StructClear (Session) to clear session variables. This deletes the SessionID, CFID, and CFtoken built-in variables, effectively ending the session. If you want to use StructClear to delete your application variables, put those variables in a structure in the Session scope, and then clear that structure. For example, put all your application variables in Session.MyVars and then call StructClear(Session.MyVars) to clear the variables.


Ensuring variable existence

ColdFusion generates an error if you try to use a variable value that does not exist. Therefore, before you use any variable whose value is assigned dynamically, you must ensure that a variable value exists. For example, if your application has a form, it must use some combination of requiring users to submit data in fields, providing default values for fields, and checking for the existence of field variable values before they are used.

There are several ways to ensure that a variable exists before you use it, including the following:

  • You can use the IsDefined function to test for the variable’s existence.
  • You can use the cfparam tag to test for a variable and set it to a default value if it does not exist.
  • You can use a cfform input tag with a hidden attribute to tell ColdFusion to display a helpful message to any user who does not enter data in a required field. For more information on this technique, see Requiring users to enter values in form fields.


Testing for a variable’s existence

Before relying on a variable’s existence in an application page, you can test to see if it exists by using the IsDefined function. To check whether a specific key exists in a structure, use the StructKeyExists function.

For example, if you submit a form with an unsettled check box, the action page does not get a variable for the check box. The following example from a form action page makes sure the Contractor check box Form variable exists before using it:

<cfif IsDefined("Form.Contractor")>
    <cfoutput>Contractor: #Form.Contractor#</cfoutput>
    </cfif>

You must always enclose the argument passed to the IsDefined function in double-quotation marks. For more information on the IsDefined function, see CFML Reference.

If you attempt to evaluate a variable that you did not define, ColdFusion cannot process the page and displays an error message. To help diagnose such problems, turn on debugging in the ColdFusion MX Administrator or use the debugger in your editor. The Administrator debugging information shows which variables are being passed to your application pages.

Variable existence considerations

If a variable is part of a scope that is available as a structure, you might get a minor performance increase by testing the variable’s existence using the StructKeyExists function instead of the IsDefined function.

You can also determine which Form variables exist by inspecting the contents of the Form.fieldnames built-in variable. This variable contains a list of all the fields submitted by the form. Remember, however, that form text fields are always submitted to the action page, and might contain an empty string if the user did not enter data.

The IsDefined function always returns False if you specify an array or structure element using bracket notation. For example, IsDefined("myArray[3]") always returns False, even if the array element myArray[3] has a value. To check for the existence of an array element, use cftry, as in the following example:

<cfset items=ArrayNew(2)>
<cfset items[1][1] = "Dog">
<cfset items[2][2] = "Cat">
<cftry>
  <cfset temp=items[1][2]>
<cfcatch type="any">
<  cfoutput>Items[1][2] does not exist</cfoutput>
</cfcatch>
</cftry>


Using the cfparam tag

You can ensure that a variable exists by using the cfparam tag, which tests for the variable’s existence and optionally supplies a default value if the variable does not exist. The cfparam tag has the following syntax:

<cfparam name="VariableName"
    type="data_type"
    default="DefaultValue">

Note: For information on using the type attribute to validate the parameter data type, see CFML Reference.

There are two ways to use the cfparam tag to test for variable existence, depending on how you want the validation test to proceed:

  • With only the name attribute to test that a required variable exists. If it does not exist, the ColdFusion server stops processing the page and displays an error message.
  • With the name and default attributes to test for the existence of an optional variable. If the variable exists, processing continues and the value is not changed. If the variable does not exist, it is created and set to the value of the default attribute, and processing continues.

The following example shows how to use the cfparam tag to check for the existence of an optional variable and to set a default value if the variable does not already exist:

<cfparam name="Form.Contract" default="Yes">


Example: testing for variables

Using the cfparam tag with the name attribute is one way to clearly define the variables that a page or a custom tag expects to receive before processing can proceed. This can make your code more readable, as well as easier to maintain and debug.

For example, the following cfparam tags indicate that this page expects two form variables named StartRow and RowsToFetch:

<cfparam name="Form.StartRow">
    <cfparam name="Form.RowsToFetch">

If the page with these tags is called without either one of the form variables, an error occurs and the page stops processing. By default, ColdFusion displays an error message; you can also handle the error as described in Handling Errors.


Example: setting default values

The following example uses the cfparam tag to see if optional variables exist. If they do exist, processing continues. If they do not exist, the ColdFusion server creates them and sets them to the default values.

<cfparam name="Cookie.SearchString" default="temple">
<cfparam name="Client.Color" default="Grey">
<cfparam name="ShowExtraInfo" default="No">

You can use the cfparam tag to set default values for URL and Form variables, instead of using conditional logic. For example, you could include the following code on the action page to ensure that a SelectedDepts variable exists:

<cfparam name="Form.SelectedDepts" default="Marketing,Sales">


Validating data

It is often not sufficient that input data merely exists; it must also have the right format. For example, a date field must have data in a date format. A salary field must have data in a numeric or currency format. There are many ways to ensure the validity of data, including the following methods:

  • Use the cfparam tag with the type attribute to validate a variable.
  • Use the IsValid function to validate a variable.
  • Use the cfqueryparam tag in a SQL WHERE clause to validate query parameters.
  • Use cfform controls that have validation attributes.
  • Use a form input tag with a hidden attribute to validate the contents of a form input field.

Note: Data validation using the cfparam, cfqueryparam, and form tags is done by the server. Validation using cfform tags and hidden fields is done using JavaScript in the user’s browser, before any data is sent to the server.

For detailed information on validating data in forms and variables, see Validating Data. For detailed information on validating query parameters, see Using cfqueryparam.


Passing variables to custom tags and UDFs

The following sections describe rules for how data gets passed to custom tags and user-defined functions that are written in CFML, and to CFX custom tags that are written in Java or C++.


Passing variables to CFML tags and UDFs

When you pass a variable to a CFML custom tag as an attribute, or to a user-defined function as an argument, the following rules determine whether the custom tag or function receives its own private copy of the variable or only gets a reference to the calling page’s variable:

  • Simple variables and arrays are passed as copies of the data. If your argument is an expression that contains multiple simple variables, the result of the expression evaluation is copied to the function or tag.
  • Structures, queries, and cfobject objects are passed as references to the object.

If the tag or function gets a copy of the calling page’s data, changes to the variable in the custom tag or function do not change the value of the variable on the calling page. If the variable is passed by reference, changes to the variable in the custom tag or function also change the value of the variable in the calling page.

To pass a variable to a custom tag, you must enclose the variable name in number signs. To pass a variable to a function, do not enclose the variable name in number signs. For example, the following code calls a user-defined function using three Form variables:

<cfoutput>
TOTAL INTEREST: #TotalInterest(Form.Principal, Form.AnnualPercent,
Form.Months)#<br>
</cfoutput>

The following example calls a custom tag using two variables, MyString and MyArray:

<cf_testTag stringval=#MyString# arrayval=#MyArray#>


Passing variables to CFX tags

You cannot pass arrays, structures, or cfobject objects to CFX tags. You can pass a query to a CFX tag by using the query attribute when calling the tag. ColdFusion normally converts simple data types to strings when passing them to CFX tags; however, the Java Request Interface getIntAttribute method lets you get a passed integer value.
Previous


Using Expressions and Number Signs

This chapter discusses how to use expressions in CFML. It discusses the elements of Macromedia ColdFusion expressions and how to create expressions. It also describes the correct use of number signs to indicate expressions in ColdFusion tags such as cfoutput, in strings, and in expressions. Finally, it describes how to use variables in variable names and strings to create dynamic expressions, and dynamic variables.

Contents

Expressions

Using number signs

Dynamic expressions and dynamic variables
Next


Expressions

ColdFusion expressions consist of operands and operators. Operands are comprised of constants and variables. Operators, such as the multiplication symbol, are the verbs that act on the operands; functions are a form of operator.

The simplest expression consists of a single operand with no operators. Complex expressions have multiple operators and operands. The following are all ColdFusion expressions:

12
MyVariable
(1 + 1)/2
"father" & "Mother"
Form.divisor/Form.dividend
Round(3.14159)

Operators act on the operands. Some operators, such as functions with a single argument, take a single operand. Many operators, including most arithmetic and logical operators, take two operands. The following is the general form of a two-operand expression:

Expression Operator Expression

Note that the operator is surrounded by expressions. Each expression can be a simple operand (variable or constant) or a subexpression consisting of more operators and expressions. Complex expressions are built up using subexpressions. For example, in the expression (1 + 1)/2, 1 + 1 is a subexpression consisting of an operator and two operands.

This section describes the following topics:

  • Operator types
  • Operator precedence and evaluation ordering
  • Using functions as operators


Operator types

ColdFusion has four types of operators:

  • Arithmetic operators
  • Boolean operators
  • Decision operators (or comparison operators)
  • String operators

Functions also can be viewed as operators because they act on operands.

Arithmetic operators

The following table describes the arithmetic operators:

Operator | Description
+ - * / | Basic arithmetic: Addition, subtraction, multiplication, and division. In division, the right operand cannot be zero.
+ - | Unary arithmetic: Set the sign of a number.
MOD | Modulus: Return the remainder after a number is divided by a divisor. The result has the same sign as the divisor. The right should be an integer; using a non-numeric value causes an error, and if you specify a real number, ColdFusion ignores the fractional part (for example, 11 MOD 4 is 3).
\ | Integer division: Divide an integer by another integer. Use the backslash character (\) to separate the integers. The right operand cannot be zero. For example, 9\4 is 2.
^ | Exponentiation: Return the result of a number raised to a power (exponent). Use the caret character (^) to separate the number from the power; for example, 2^3 is 8. Real and negative numbers are allowed for both the base and the exponent. However, any expression that equates to an imaginary number, such -1^.5 results in the string "-1.#IND. ColdFusion does not support imaginary or complex numbers.


Boolean operators

Boolean, or logical, operators perform logical connective and negation operations. The operands of Boolean operators are Boolean (True/False) values. The following table describes the Boolean operators:

Operator | Description
NOT | Reverse the value of an argument. For example, NOT True is False and vice versa.
AND | Return True if both arguments are True; return False otherwise. For example, True AND True is True, but True AND False is False.
OR | Return True if any of the arguments is True; return False otherwise. For example, True OR False is True, but False OR False is False.
XOR | Exclusive or: Return True if one of the values is True and the other is False. Return False if both arguments are True or both are False. For example, True XOR True is False, but True XOR False is True.
EQV | Equivalence: Return True if both operands are True or both are False. The EQV operator is the opposite of the XOR operator. For example, True EQV True is True, but True EQV False is False.
IMP | Implication: The statement A IMP B is the equivalent of the logical statement "If A Then B." A IMP B is False only if A is True and B is False. It is True in all other cases.


Decision operators

The ColdFusion decision, or comparison, operators produce a Boolean True/False result. The following table describes the decision operators:

Operator | Description
IS | Perform a case-insensitive comparison of two values. Return True if the values are identical.
IS NOT | Opposite of IS. Perform a case-insensitive comparison of two values. Return True if the values are not identical.
CONTAINS | Return True if the value on the left contains the value on the right.
DOES NOT CONTAIN | Opposite of CONTAINS. Return True if the value on the left does not contain the value on the right.
GREATER THAN | Return True if the value on the left is greater than the value on the right.
LESS THAN | Opposite of GREATER THAN. Return True if the value on the left is smaller than the value on the right.
GREATER THAN OR EQUAL TO | Return True if the value on the left is greater than or equal to the value on the right.
LESS THAN OR EQUAL TO | Return True if the value on the left is less than or equal to the value on the right.

Alternative notation for decision operators

You can replace some decision operators with alternative notations to make your CFML more compact, as shown in the following table:

Operator | Alternative name(s)
IS | EQUAL, EQ
IS NOT | NOT EQUAL, NEQ
GREATER THAN | GT
LESS THAN | LT
GREATER THAN OR EQUAL TO | GTE, GE
LESS THAN OR EQUAL TO | LTE, LE

Decision operator rules

The following rules apply to decision operators:

  • When ColdFusion evaluates an expression that contains a decision operator other than CONTAINS or DOES NOT CONTAIN, it first determines if the data can be converted to numeric values. If they can be converted, it performs a numeric comparison on the data. If they cannot be converted, it performs a string comparison. This can sometimes result in unexpected results. For more information on this behavior, see Evaluation and type conversion issues.
  • When ColdFusion evaluates an expression with CONTAINS or DOES NOT CONTAIN it does a string comparison. The expression A CONTAINS B evaluates to True if B is a substring of A. Therefore an expression such as the following evaluates as True:
    123.45 CONTAINS 3.4
  • When a ColdFusion decision operator compares strings, it ignores the case. As a result, the following expression is True:
    "a" IS "A"
  • When a ColdFusion decision operator compares strings, it evaluates the strings from left to right, comparing the characters in each position according to their sorting order. The first position where the characters differ determines the relative values of the strings. As a result, the following expressions are True:
    "ab" LT "aba"
"abde" LT "ac"


String operators

There is one string operator, which is the concatenation operator.

Operator | Description
& | Concatenates strings.

Note: In a Query of Queries, you use || as the concatenation operator.


Operator precedence and evaluation ordering

The order of precedence controls the order in which operators in an expression are evaluated. The order of precedence is as follows:

Unary +, Unary -
^
*, /
\
MOD
+, -
&
EQ, NEQ, LT, LTE, GT, GTE, CONTAINS, DOES NOT CONTAIN
NOT
AND
OR
XOR
EQV
IMP

To enforce a non-standard order of evaluation, you must parenthesize expressions. For example:

  • 6 - 3 * 2 is equal to 0
  • (6 - 3) * 2 is equal to 6

You can nest parenthesized expressions. When in doubt about the order in which operators in an expression will be evaluated, use parentheses to force the order of evaluation.


Using functions as operators

Functions are a form of operator. Because ColdFusion functions return values, you can use function results as operands. Function arguments are expressions. For example, the following are valid expressions:

  • Rand()
  • UCase("This is a text: ") & ToString(123 + 456)

Function syntax

The following table shows function syntax and usage guidelines:

Usage

Example

No arguments

Function()

Basic format

Function(Data)

Nested functions

Function1(Function2(Data))

Multiple arguments

Function(Data1, Data2, Data3)

String arguments

Function('This is a demo')
Function("This is a demo")

Arguments that are expressions

Function1(X*Y, Function2("Text"))

All functions return values. In the following example, the cfset tag sets a variable to the value returned by the Now function:

<cfset myDate = DateFormat(Now(), "mmmm d, yyyy")>

You can use the values returned by functions directly to create more complex expressions, as in the following example:

Abs(Myvar)/Round(3.14159)

For more information on how to insert functions in expressions, see Using number signs.

Optional function arguments

Some functions take optional arguments after their required arguments. If omitted, all optional arguments default to a predefined value. For example:

  • Replace("Eat and Eat", "Eat", "Drink") returns "Drink and Eat"
  • Replace("Eat and Eat", "Eat", "Drink", "All") returns "Drink and Drink"

The difference in the results is because the Replace function takes an optional fourth argument that specifies the scope of replacement. The default value is "One," which explains why only the first occurrence of "Eat" was replaced with "Drink" in the first example. In the second example, a fourth argument causes the function to replace all occurrences of "Eat" with "Drink".

Expression evaluation and functions

It is important to remember that ColdFusion evaluates function attributes as expressions before it executes the function. As a result, you can use any ColdFusion expression as a function attribute. For example, consider the following lines:

<cfset firstVariable = "we all need">
<cfset myStringVar = UCase(firstVariable & " more sleep!")>

When ColdFusion server executes the second line, it does the following:

  1. Determines that there is an expression with a string concatenation.
  2. Evaluates the firstVariable variable as the string "we all need".
  3. Concatenates "we all need" with the string " more sleep!" to get "we all need more sleep!".
  4. Passes the string "we all need more sleep!" to the UCase function.
  5. Executes the UCase function on the string argument "we all need more sleep!" to get "WE ALL NEED MORE SLEEP!".
  6. Assigns the string value "WE ALL NEED MORE SLEEP!" to the variable myStringVar.

ColdFusion completes steps 1-3 before invoking the function.


Using number signs

Number signs (#) have a special meaning in CFML. When the ColdFusion server encounters number signs in CFML text, such as the text in a cfoutput tag body, it checks to see if the text between the number signs is either a variable or a function.

Tip: Number signs are also called pound signs.

Is so, it replaces the text and surrounding number signs with the variable value or the result of the function. Otherwise, ColdFusion generates an error.

For example, to output the current value of a variable named Form.MyFormVariable, you delimit (surround) the variable name with number signs:

<cfoutput>Value is #Form.MyFormVariable#</cfoutput>

In this example, the variable Form.MyFormVariable is replaced with the value assigned to it.

Follow these guidelines when using number signs:

  • Use number signs to distinguish variables or functions from plain text.
  • Surround only a single variable or function in number signs; for example, #Variables.myVar# or #Left(myString, position)#. (However, a function in number signs can contain nested functions, such as #Left(trim(myString), position)#.
  • Do not put complex expressions, such as 1 + 2 in number signs. Although this is allowed in a cfoutput block, such as <cfoutput>One plus one is #1 + 1#</cfoutput>, doing so mixes logic and presentation.
  • Use number signs only where necessary, because unneeded number signs slow processing.

The following sections provide more details on how to use number signs in CFML. For a description of using number signs to create variable names, see Using number signs to construct a variable name in assignments.

  • Using number signs in ColdFusion tag attribute values
  • Using number signs in tag bodies
  • Using number signs in strings
  • Nested number signs
  • Using number signs in expressions


Using number signs in ColdFusion tag attribute values

You can put variables, functions, or expressions inside tag attributes by enclosing the variable or expression with number signs. For example, if the variable CookieValue has the value "MyCookie", the following line sets the cfcookie value attribute to "The value is MyCookie":

<cfcookie name="TestCookie" value="The value is #CookieValue#">

You can optionally omit quotation marks around variables used as attribute values as shown in the following example:

<cfcookie name = TestCookie value = #CookieValue#>

However, surrounding all attribute values in quotation marks is more consistent with HTML coding style.

If you use string expressions to construct an attribute value, as shown in the following example, the strings inside the expression use single quotation marks (') to differentiate the quotation marks from the quotation marks that surround the attribute value.

<cfcookie name="TestCookie2" value="The #CookieValue & 'ate the cookie!'#">

Note: You do not need to use number signs when you use the cfset tag to assign one variable’s value to another value. For example, the following tag assigns the value of the oldVar variable to the new variable, newVar: <cfset newVar = oldVar>.


Using number signs in tag bodies

You can put variables or functions freely inside the bodies of the following tags by enclosing each variable or expression with number signs:

  • cfoutput
  • cfquery
  • cfmail

For example:

<cfoutput>
    Value is #Form.MyTextField#
</cfoutput>

<cfoutput>
    The name is #FirstName# #LastName#.
</cfoutput>

<cfoutput>
    The value of Cos(0) is #Cos(0)#
</cfoutput>

If you omit the number signs, the text, rather than the value, appears in the output generated by the cfoutput statement.

Two expressions inside number signs can be adjacent to one another, as in the following example:

<cfoutput>
    "Mo" and "nk" is #Left("Moon", 2)##Mid("Monkey", 3, 2)#
</cfoutput>

This code displays the following text:

"Mo" and "nk" is Monk

ColdFusion does not interpret the double number sign as an escaped # character.


Using number signs in strings

You can put variables or functions freely inside strings by enclosing each variable or expression with number signs; for example:

<cfset TheString = "Value is #Form.MyTextField#">
<cfset TheString = "The name is #FirstName# #LastName#.">
<cfset TheString = "Cos(0) is #Cos(0)#">

ColdFusion automatically replaces the text with the value of the variable or the value returned by the function. For example, the following pairs of cfset statements produce the same result:

<cfset TheString = "Hello, #FirstName#!">
<cfset TheString = "Hello, " & FirstName & "!">

If number signs are omitted inside the string, the text, rather than the value, appears in the string. For example, the following pairs of cfset statements produce the same result:

<cfset TheString = "Hello, FirstName!">
<cfset TheString = "Hello, " & "First" & "Name!">

As with the cfoutput statement, two expressions can be adjacent to each other in strings, as in the following example:

<cfset TheString = "Monk is #Left("Moon", 2)##Mid("Monkey", 3, 2)#">

The double-quotation marks around "Moon" and "Monkey" do not need to be escaped (as in ""Moon"" and ""Monkey""). This is because the text between the number signs is treated as an expression; it is evaluated before its value is inserted inside the string.


Nested number signs

In a few cases, you can nest number signs in an expression. The following example uses nested number signs:

<cfset Sentence = "The length of the full name is
#Len("#FirstName# #LastName#")#">

In this example, number signs are nested so that the values of the variables FirstName and LastName are inserted in the string whose length the Len function calculates.

Nested number signs imply a complex expression that can typically be written more clearly and efficiently without the nesting. For example, you can rewrite the preceding code example without the nested number signs, as follows:

<cfset Sentence2 = "The length of the full name is #Len(FirstName & " "
& LastName)#">

The following achieves the same results and can further improve readability:

<cfset FullName = "#FirstName# #LastName#">
<cfset Sentence = "The length of the full name
    is #Len(FullName)#">

A common mistake is to put number signs around the arguments of functions, as in:

<cfset ResultText = "#Len(#TheText#)#">
<cfset ResultText = "#Min(#ThisVariable#, 5 + #ThatVariable#)#">
<cfset ResultText = "#Len(#Left("Some text", 4)#)#">

These statements result in errors. As a general rule, never put number signs around function arguments.


Using number signs in expressions

Use number signs in expressions only when necessary, because unneeded number signs reduce clarity and can increase processing time. The following example shows the preferred method for referencing variables:

<cfset SomeVar = Var1 + Max(Var2, 10 * Var3) + Var4>

In contrast, the following example uses number signs unnecessarily and is less efficient than the previous statement:

<cfset #SomeVar# = #Var1# + #Max(Var2, 10 * Var3)# + #Var4#>


Dynamic expressions and dynamic variables

This section discusses the advanced topics of dynamic expressions, dynamic evaluation, and dynamic variable naming. Many ColdFusion programmers never encounter or need to use dynamic expressions. However, dynamic variable naming is important in situations where the variable names are not known in advance, such as in shopping cart applications.

This section also discusses the use of the IIf function, which is most often used without dynamic expressions. This function dynamically evaluates its arguments, and you must often use the DE function to prevent the evaluation. For more information on using the IIF function, see Using the IIF function .

Note: This section uses several tools and techniques that are documented in later chapters. If you are unfamiliar with using ColdFusion forms, structures, and arrays, you should learn about these tools before reading this section.

This section describes the following topics:

  • About dynamic variables
  • About dynamic expressions and dynamic evaluation
  • Dynamic variable naming without dynamic evaluation
  • Using dynamic evaluation
  • Using the IIF function
  • Example: a dynamic shopping cart


About dynamic variables

Dynamic variables are variables that are named dynamically, typically by creating a variable name from a static part and a variable part. For example, the following example dynamically constructs the variable name from a variable prefix and a static suffix:

<cfset "#flavor#_availability" = "out of stock">

Using dynamic variables in this manner does not require dynamic evaluation.


About dynamic expressions and dynamic evaluation

In a dynamic expression, the actual expression, not just its variable values, is determined at execution time. In other words, in a dynamic expression the structure of the expression, such as the names of the variables, not just the values of the variables, gets built at runtime.

You create dynamic expressions using string expressions, which are expressions contained in strings, (that is, surrounded with quotation marks). Dynamic evaluation is the process of evaluating a string expression. The Evaluate and IIf functions, and only these functions, perform dynamic evaluation.

When ColdFusion performs dynamic evaluation it does the following:

  1. Takes a string expression and treats it as a standard expression, as if the expression was not a string.
  2. Parses the expression to determine the elements of the expression and validate the expression syntax.
  3. Evaluates the expression, looking up any variables and replacing them with their values, calling any functions, and performing any required operations.

This process enables ColdFusion to interpret dynamic expressions with variable parts. However, it incurs a substantial processing overhead.

Dynamic expressions were important in early versions of ColdFusion, before it supported arrays and structures, and they still can be useful in limited circumstances. However, the ability to use structures and the ability to use associative array notation to access structure elements provide more efficient and easier methods for dynamically managing data. For information on using arrays and structures, see Using Arrays and Structures.

Selecting how to create variable names

The following two examples describes cases when you need dynamic variable names:

  • Form applications where the number and names of fields on the form vary dynamically. In this case, the form posts only the names and values of its fields to the action page. The action page does not know all the names of the fields, although it does know how the field names (that is, the variable names) are constructed.
  • If the following are true:
    • ColdFusion calls a custom tag multiple times.
    • The custom tag result must be returned to different variables each time.
    • The calling code can specify the variable in which to return the custom tag result.

    In this case, the custom tag does not know the return variable name in advance, and gets it as an attribute value.

In both cases, it might appear that dynamic expressions using the Evaluate function are needed to construct the variable names. However, you can achieve the same ends more efficiently by using dynamic variable naming, as shown in Example: a dynamic shopping cart.

This does not mean that you must always avoid dynamic evaluation. However, given the substantial performance costs of dynamic evaluation, you should first ensure that one of the following techniques cannot serve your purpose:

  • An array (using index variables)
  • Associative array references containing expressions to access structure elements
  • Dynamically generated variable names


Dynamic variable naming without dynamic evaluation

While ColdFusion does not always allow you to construct a variable name in-line from variable pieces, it does let you to do so in the most common uses, as described in the following sections.

Using number signs to construct a variable name in assignments

You can combine text and variable names to construct a variable name on the left side of a cfset assignment. For example, the following code sets the value of the variable Product12 to the string "Widget":

<cfset ProdNo = 12>
<cfset "Product#ProdNo#" = "Widget">

To construct a variable name this way, all the text on the left side of the equal sign must be in quotation marks.

This usage is less efficient than using arrays. The following example has the same purpose as the previous one, but requires less processing:

<cfset MyArray=ArrayNew(1)>
<cfset prodNo = 12>
<cfset myArray[prodNo] = "Widget">

Dynamic variable limitation

When you use a dynamic variable name in quotation marks on the left side of an assignment, the name must be either a simple variable name or a complex name that uses object.property notation (such as MyStruct.#KeyName#). You cannot use an array as part of a dynamic variable name. For example, the following code generates an error:

<cfset MyArray=ArrayNew(1)>
<cfset productClassNo = 1>
<cfset productItemNo = 9>
<cfset "myArray[#productClassNo##productItemNo#]" = "Widget">

However, you can construct an array index value dynamically from variables without using quotation marks on the left side of an assignment. For example, the preceding sample code works if you replace the final line with the following line:

<cfset myArray[#productClassNo# & #productItemNo#] = "Widget">

Dynamically constructing structure references

The ability to use associative array notation to reference structures provides a way for you to use variables to dynamically create structure references. (For a description of associative array notation, see Structure notation.) Associative array structure notation allows you to use a ColdFusion expression inside the index brackets. For example, if you have a productName structure with keys of the form product_1, product_2 and so on, you can use the following code to display the value of productName.product_3:

<cfset prodNo = 3>
<cfoutput>
    Product_3 Name: #ProductName["product_" & prodNo]#
<cfoutput>

For an example of using this format to manage a shopping cart, see Example: a dynamic shopping cart.


Using dynamic evaluation

The following sections describe how to use dynamic evaluation and create dynamic expressions.

  • ColdFusion dynamic evaluation functions
  • Function argument evaluation considerations
  • About the Evaluate function
  • Avoiding the Evaluate function
  • SetVariable function considerations


ColdFusion dynamic evaluation functions

The following table describes the functions that perform dynamic evaluation and are useful in evaluating dynamic expressions:

Function | Purpose
DE | Escapes any double-quotation marks in the argument and wraps the result in double-quotation marks. The DE function is particularly useful with the IIF function, to prevent the function from evaluating a string to be output. For an example of using the DE function with the IIF function, see Using the IIF function.
Evaluate | Takes one or more string expressions and dynamically evaluates their contents as expressions from left to right. (The results of an evaluation to the left can have meaning in an expression to the right.) Returns the result of evaluating the rightmost argument. For more information on this function see About the Evaluate function.
IIf | Evaluates a boolean condition expression. Depending on whether this expression is True or False, dynamically evaluates one of two string expressions and returns the result of the evaluation. The IIF function is convenient for incorporating a cfif tag in-line in HTML. For an example of using this function, see Using the IIF function.
SetVariable | Sets a variable identified by the first argument to the value specified by the second argument. This function is no longer required in well-formed ColdFusion pages; see SetVariable function considerations.


Function argument evaluation considerations

It is important to remember that ColdFusion always evaluates function arguments before the argument values are passed to a function:

For example, consider the following DE function:

<cfoutput>#DE("1" & "2")#</cfoutput>

You might expect this line to display """1"" & ""2""". Instead, it displays "12", because ColdFusion processes the line as follows:

  1. Evaluates the expression "1" & "2" as the string "12".
  2. Passes the string "12" (without the quotation marks) to the DE function.
  3. Calls the DE function, which adds literal quotation marks around the 12.

Similarly, if you use the expression DE(1 + 2), ColdFusion evaluates 1 + 2 as the integer 3 and passes it to the function. The function converts it to a string and surrounds the string in literal quotation marks: "3".


About the Evaluate function

The Evaluate function takes one or more string expressions, dynamically evaluates their contents as expressions from left to right, and returns the result of evaluating the rightmost argument.

The following example shows the Evaluate function and how it works with ColdFusion variable processing:

<cfset myVar2="myVar">
<cfset myVar="27/9">
<cfoutput>
    #myVar2#<br>
    #myVar#<br>
    #Evaluate("myVar2")#<br>
    #Evaluate("myVar")#<br>
    #Evaluate(myVar2)#<br>
    #Evaluate(myVar)#<br>
</cfoutput>

Reviewing the code

The following table describes how ColdFusion processes this code:

Code

Description

<cfset myVar2="myVar">
<cfset myVar="27/9">

Sets the two variables to the following strings:

myVar

27/9

<cfoutput>
    #myVar2#<br>
    #myVar#<br>

Displays the values assigned to the variables, myVar and 27/9, respectively.

#Evaluate("myVar2")#<br>

Passes the string "myvar2" (without the quotation marks) to the Evaluate function, which does the following:

1 Evaluates it as the variable myVar2.

2 Returns the value of the myVar2 variable, the string "myvar"
(without the quotation marks).

#Evaluate("myVar")#<br>

Passes the string "myvar" (without the quotation marks) to the Evaluate function, which does the following:

1 Evaluates it as the variable myVar.

2 Returns the value of the myVar variable, the string "27/9"
(without the quotation marks).

#Evaluate(myVar2)#<br>

Evaluates the variable myVar2 as the string "myVar" and passes the string (without the quotation marks) to the Evaluate function. The rest of the processing is the same as in the previous line.

#Evaluate(myVar)#<br>
</cfoutput>

Evaluates the variable myVar as the string "27/9" (without the quotation marks), and passes it to the Evaluate function, which does the following:

1 Evaluates the string as the expression 27/9

2 Performs the division.

3 Returns the resulting value, 3

As you can see, using dynamic expressions can result in substantial expression evaluation overhead, and the code can be confusing. Therefore, you should avoid using dynamic expressions wherever a simpler technique, such as using indexed arrays or structures can serve your purposes.


Avoiding the Evaluate function

Using the Evaluate function increases processing overhead, and in most cases it is not necessary. The following sections provide examples of cases where you might consider using the Evaluate function.

Example 1

You might be inclined to use the Evaluate function in code such as the following:

<cfoutput>1 + 1 is #Evaluate(1 + 1)#</cfoutput>

Although this code works, it is not as efficient as the following code:

<cfset Result = 1 + 1>
<cfoutput>1 + 1 is #Result#</cfoutput>

Example 2

This example shows how you can use an associative array reference in place of an Evaluate function. This technique is powerful because:

  • Most ColdFusion scopes are accessible as structures.
  • You can use ColdFusion expressions in the indexes of associative array structure references. (For more information on using associative array references for structures, see Structure notation.)

The following example uses the Evaluate function to construct a variable name:

<cfoutput>
Product Name: #Evaluate("Form.product_#i#")#
</cfoutput>

This code comes from an example where a form has entries for an indeterminate number of items in a shopping cart. For each item in the shopping cart there is a product name field. The field name is of the form product_1, product_2, and so on, where the number corresponds to the product’s entry in the shopping cart. In this example, ColdFusion does the following:

  1. Replaces the variable i with its value, for example 1.
  2. concatenates the variable value with "Form.product_", and passes the result (for Form.product_1) to the Evaluate function, which does the remaining steps.
  3. Parses the variable product_1 and generates an executable representation of the variable. Because ColdFusion must invoke its parser, this step requires substantial processing, even for a simple variable.
  4. Evaluates the representation of the variable, for example as "Air popper".
  5. Returns the value of the variable.

The following example has the same result as the preceding example and is more efficient:

<cfoutput>
ProductName: #Form["product_" & i]#
</cfoutput>

In this code, ColdFusion does the following:

  1. Evaluates the expression in the associative array index brackets as the string "product_" concatenated with the value of the variable i.
  2. Determines the value of the variable i; 1.
  3. Concatenates the string and the variable value to get product_1.
  4. Uses the result as the key value in the Form structure to get Form[product_1]. This associative array reference accesses the same value as the object.attribute format reference Form.product_1; in this case, Air popper.

This code format does not use any dynamic evaluation, but it achieves the same effect, of dynamically creating a structure reference by using a string and a variable.


SetVariable function considerations

You can avoid using the SetVariable function by using a format such as the following to set a dynamically named variable. For example, the following lines are equivalent:

<cfset SetVariable("myVar" & i, myVal)>
<cfset "myVar#i#" = myVal>

In the second line, enclosing the myVar#i# variable name in quotation marks tells ColdFusion to evaluate the name and process any text in number signs as a variable or function. ColdFusion replaces the #i# with the value of the variable i, so that if the value of i is 12, this code is equivalent to the line

<cfset myVar12 = myVal>

For more information on this usage, see Using number signs to construct a variable name in assignments.


Using the IIF function

The IIf function is a shorthand for the following code:

<cfif argument1>
    <cfset result = Evaluate(argument1)>
<cfelse>
    <cfset result = Evaluate(argument2)>
</cfif>

The function returns the value of the result variable. It is comparable to the use of the JavaScript and Java ? : operator, and can result in more compact code. As a result, the IIF function can be convenient even if you are not using dynamic expressions.

The IIF function requires the DE function to prevent ColdFusion from evaluating literal strings, as the following example shows:

<cfoutput>
#IIf(IsDefined("LocalVar"), "LocalVar", DE("The variable is not
defined."))#
</cfoutput>

If you do not enclose the string "The variable is not defined." in a DE function, the IIF function tries to evaluate the contents of the string as an expression and generates an error (in this case, an invalid parser construct error).

The IIF function is useful for incorporating ColdFusion logic in-line in HTML code, but it entails a processing time penalty in cases where you do not otherwise need dynamic expression evaluation.

The following example shows using IIF to alternate table row background color between white and gray. It also shows the use of the DE function to prevent ColdFusion from evaluating the color strings.

<cfoutput>
<table border="1" cellpadding="3">
<cfloop index="i" from="1" to="10">
    <tr bgcolor="#IIF( i mod 2 eq 0, DE("white"), DE("gray") )#">
        <td>
            hello #i#
        </td>
    </tr>
</cfloop>
</table>
</cfoutput>

This code is more compact than the following example, which does not use IIF or DE:

<cfoutput>
<table border="1" cellpadding="3">
<cfloop index="i" from="1" to="10">
    <cfif i mod 2 EQ 0>
        <cfset Color = "white">
    <cfelse>
        <cfset Color = "gray">
    </cfif>
    <tr bgcolor="#color#">
        <td>
            hello #i#
        </td>
    </tr>
</cfloop>
</table>
</cfoutput>


Example: a dynamic shopping cart

The following example dynamically creates and manipulates variable names without using dynamic expression evaluation by using associative array notation.

You need to dynamically generate variable names in applications such as shopping carts, where the required output is dynamically generated and variable. In a shopping cart, you do not know in advance the number of cart entries or their contents. Also, because you are using a form, the action page only receives Form variables with the names and values of the form fields.

The following example shows the shopping cart contents and lets you edit your order and submit it. To simplify things, the example automatically generates the shopping cart contents using CFScript instead of having the user fill the cart. A more complete example would populate a shopping cart as the user selected items. Similarly, the example omits all business logic for committing and making the order.

To create the form:

  1. Create a file in your editor.
    <html>
<head>
    <title>Shopping Cart</title>
</head>
<cfscript>
CartItems=4;
Cart = ArrayNew(1);
for ( i=1; i LE cartItems; i=i+1)
{
    Cart[i]=StructNew();
    Cart[i].ID=i;
    Cart[i].Name="Product " & i;
    Cart[i].SKU=i*100+(2*i*10)+(3*i);
    Cart[i].Qty=3*i-2;
}
</cfscript>

<body>
Your shopping cart has the following items.<br>
You can change your order quantities.<br>
If you don't want any item, clear the item's check box.<br>
When you are ready to order, click submit.<br>
<br>
<cfform name="ShoppingCart" action="ShoppingCartAction.cfm" method="post">
  <table>
    <tr>
      <td>Order?</td>
      <td>Product</td>
      <td>Code</td>
      <td>Quantity</td>
    </tr>
    <cfloop index="i" from="1" to="#cartItems#">
        <tr>
          <cfset productName= "product_" & Cart[i].ID>
          <cfset skuName= "sku_" & Cart[i].ID>
          <cfset qtyname= "qty_" & Cart[i].ID>
          <td><cfinput type="checkbox" name="itemID" value="#Cart[i].ID#" checked>
             </td>
          <td><cfinput type="text" name="#productName#" value="#Cart[i].Name#"
             passThrough = "readonly = 'True'"></td>
          <td><cfinput type="text" name="#skuName#" value="#Cart[i].SKU#"
             passThrough = "readonly = 'True'"></td>
          <td><cfinput type="text" name="#qtyName#" value="#Cart[i].Qty#">
             </td>
        </tr>
    </cfloop>
  </table>
  <input type="submit" name="submit" value="submit">
</cfform>

</body>
</html>
  2. Save the page as ShoppingCartForm.cfm.

Reviewing the code

The following table describes the code:

Code

Description

<cfscript>
CartItems=4;
Cart = ArrayNew(1);
for ( i=1; i LE #cartItems#; i=i+1)
{
    Cart[i]=StructNew();
    Cart[i].ID=i;
    Cart[i].Name="Product " & i;
    Cart[i].SKU=i*100+(2*i*10)+(3*i);
    Cart[i].Qty=3*i-2;
}
</cfscript>

Create a shopping cart as an array of structures, with each structure containing the cart item ID, product name, SKU number, and quantity ordered for one item in the cart. Populate the shopping cart by looping CartItems times and setting the structure variables to arbitrary values based on the loop counter. A real application would set the Name, SKU, and Quantity values on other pages.

<cfform name="ShoppingCart"
        action="ShoppingCartAction.cfm"
        method="post">
  <table>
    <tr>
        <td>Order?</td>
        <td>Product</td>
        <td>Code</td>
        <td>Quantity</td>
    </tr>

Start the form and its embedded table. When the user clicks the submit button, post the form data to the ShoppingCartAction.cfm page.

The table formats the form neatly. The first table row contains the column headers. Each following row has the data for one cart item.

<cfloop index="i" from="1" to="#cartItems#">
    <tr>
        <cfset productName= "product_" &
            Cart[i].ID>
        <cfset skuName= "sku_" & Cart[i].ID>
        <cfset qtyname= "qty_" & Cart[i].ID>
        <td><cfinput type="checkbox"
            name="itemID" value="#Cart[i].ID#"
            checked>
        </td>
        <td><cfinput type="text"
            name="#productName#"
            value="#Cart[i].Name#"
            passThrough = "readonly = 'True'">
        </td>
        <td><cfinput type="text"
            name="#skuName#"
            value="#Cart[i].SKU#"
            passThrough = "readonly = 'True'">
        </td>
      <td><cfinput type="text"
            name="#qtyName#"
            value="#Cart[i].Qty#">
        </td>
    </tr>
</cfloop>
</table>

Loop through the shopping cart entries to generate the cart form dynamically. For each loop, generate variables used for the form field name attributes by appending the cart item ID (Cart[i].ID) to a field type identifier, such as "sku_".

Use a single name, "itemID", for all check boxes. This way, the itemID value posted to the action page is a list of all the check box field values. The check box field value for each item is the cart item ID.

Each column in a row contains a field for a cart item structure entry. The passthrough attribute sets the product name and SKU fields to read-only; note the use of single-quotation marks. (For more information on the cfinput tag passthrough attribute, see CFML Reference.) The check boxes are selected by default.

<input type="submit" name="submit"
    value="Submit">
</form>

Create the Submit button and end the form.

To create the Action page:

  1. Create a file in your editor.
  2. Enter the following text:
    <html>
<head>
    <title>Your Order</title>
</head>
<body>
<cfif isDefined("Form.submit")>
    <cfparam name="Form.itemID" default="">
    <cfoutput>
        You have ordered the following items:<br>
        <br>
        <cfloop index="i" list="#Form.itemID#">
            ProductName: #Form["product_" & i]#<br>
            Product Code: #Form["sku_" & i]#<br>
            Quantity: #Form["qty_" & i]#<br>
            <br>
        </cfloop>
    </cfoutput>
</cfif>
</body>
</html>
  3. Save the file as ShoppingCartAction.cfm
  4. Open ShoppingCartform.cfm in your browser, change the check box and quantity values, and click Submit.

Reviewing the code

The following table describes the code:

Code

Description

<cfif isDefined("Form.submit")>

Run the CFML on this page only if it is called by submitting a form. This is not needed if there are separate form and action pages, but is required if the form and action page were one ColdFusion page.

<cfparam name="Form.itemID"
    default="">

Set the default Form.itemID to the empty string. This prevents ColdFusion from displaying an error if the user clears all check boxes before submitting the form (so no product IDs are submitted).

<cfoutput>
You have ordered the following
        items:<br>
<br>
<cfloop index="i" list=
        "#Form.itemID#">
    ProductName:
        #Form["product_" & i]#<br>
    Product Code:
        #Form["sku_" & i]#<br>
    Quantity:
        #Form["qty_" & i]#<br>
    <br>
</cfloop>
</cfoutput>
</cfif>

Display the name, SKU number, and quantity for each ordered item.

The form page posts Form.itemID as a list containing the value attributes of all the check boxes. These attributes contain the shopping cart item IDs for the selected cart items. Use the list values to index a loop that outputs each ordered item.

Use associative array notation to access the Form scope as a structure and use expressions in the array indexes to construct the form variable names. The expressions consist of a string containing the field name’s field type prefix (for example, "sku_"), concatenated with the variable i, which contains the shopping cart ItemID number (which is also the loop index variable).

Previous


Using Arrays and Structures

Macromedia ColdFusion supports dynamic multidimensional arrays. This chapter explains the basics of creating and handling arrays. It also provides several examples showing how arrays can enhance your ColdFusion application code.

ColdFusion also supports structures for managing lists of key-value pairs. Because structures can contain other structures or complex data types as it values, they provide a flexible and powerful tool for managing complex data. This chapter explains the basics of creating and working with structures.

Contents

About arrays

Basic array techniques

Populating arrays with data

Array functions

About structures

Creating and using structures

Structure examples

Structure functions
Next


About arrays

Traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions.

In ColdFusion, you typically use arrays to temporarily store data. For example, if your site lets users order goods online, you can store their shopping cart contents in an array. This lets you make changes easily without committing the information, which the user can change before completing the transaction, to a database.

Basic array concepts

The following terms will help you understand subsequent discussions of ColdFusion arrays:

  • Array dimension The relative complexity of the array structure.
  • Index The position of an element in a dimension, ordinarily surrounded by square brackets: my1Darray[1], my2Darray[1][1], my3Darray[1][1][1].
  • Array element Data stored at an array index.

The simplest array is a one-dimensional array, similar to a row in a table. A one-dimensional array has a name (the variable name) and a numerical index. The index number references a single entry, or cell, in the array, as the following figure shows:

A one-dimensional array showing the index for each entry

Thus, the following statement sets the value of the fifth entry in the one-dimensional array MyArray to "Robert":

<cfset MyArray[5] = "Robert">

A basic two-dimensional (2D) array is like a simple table. A three-dimensional (3D) array is like a cube of data, and so on. ColdFusion lets you directly create arrays with up to three dimensions. You can use multiple statements to create arrays with more than three dimensions.

The syntax my2darray[1][3]="Paul" is the same as saying 'My2dArray is a two-dimensional array and the value of the array element index [1][3] is "Paul"'.

About ColdFusion arrays

ColdFusion arrays differ from traditional arrays, because they are dynamic. For example, in a conventional array, array size is constant and symmetrical, whereas in a ColdFusion array, you can have rows of differing lengths based on the data that has been added or removed.

The following figures show the differences between traditional arrays and ColdFusion arrays using 2D arrays. The differences between traditional and ColdFusion 3D arrays are similar, but much harder to show on a page.

A conventional 2D array is like a fixed-size table made up of individual cells, as the following figure shows:

A two-dimensional array showing the index for each entry

The following figure represents a ColdFusion 2D array:

A ColdFusion two-dimensional array contains a series of one-dimensional arrays.

A ColdFusion 2D array is actually a one-dimensional array that contains a series of additional 1D arrays. Each of the arrays that make up a row can expand and contract independently of any other column. Similarly, a ColdFusion 3D array is essentially three nested sets of 1D arrays.

Dynamic arrays expand to accept data you add to them and contract as you remove data from them.


Basic array techniques

This section describes the following topics:

  • Referencing array elements
  • Creating arrays
  • Adding elements to an array
  • Deleting elements from an array
  • Copying arrays

Referencing array elements

You reference array elements by enclosing the index with brackets: arrayName[x] where x is the index that you want to reference. In ColdFusion, array indexes are counted starting with position 1, which means that position 1 in the firstname array is referenced as firstname[1]. For 2D arrays, you reference an index by specifying two coordinates: myarray[1][1].

You can use ColdFusion variables and expressions inside the square brackets to reference an index, as the following example shows:

<cfset myArray=ArrayNew(1)>
<cfset myArray[1]="First Array Element">
<cfset myArray[1 + 1]="Second Array" & "Element">
<cfset arrayIndex=3>
<cfset arrayElement="Third Array Element">
<cfset myArray[arrayIndex]=arrayElement>
<cfset myArray[arrayIndex + 1]="Fourth Array Element">
<cfdump var=#myArray#>

Note: The IsDefined function does not test the existence of array elements. Instead, put any code that might try to access an undefined array element in a try block and use a catch block to handle exceptions that arise if elements do not exist.

Creating arrays

In ColdFusion, you declare an array by assigning a variable name to the new array and specifying its dimensions, as follows:

<cfset mynewarray=ArrayNew(x)>

where x is the number of dimensions (from 1 to 3) in the array that you want to create.

Once you declare an array, you can add array elements, which you can then reference using the elements’ indexes.

For example, suppose you declare a 1D array called firstname:

<cfset firstname=ArrayNew(1)>

The array firstname holds no data and is of an unspecified length. Next you add data to the array:

<cfset firstname[1]="Coleman">
<cfset firstname[2]="Charlie">
<cfset firstname[3]="Dexter">

After you add these names to the array, it has a length of 3.

Creating complex multidimensional arrays

ColdFusion supports dynamic multidimensional arrays. When you declare an array with the ArrayNew function, you specify the number of dimensions. You can create an asymmetrical array or increase an existing array’s dimensions by nesting arrays as array elements.

It is important to know that when you assign one array (array1) to an element of another array (array2), array1 is copied into array2. The original copy of array1 still exists, independent of array2. You can then change the contents of the two arrays independently.

The best way to understand an asymmetrical array is by looking at it. The following example creates an asymmetric, multidimensional array and the cfdump tag displays the resulting array structure. Several array elements do not yet contain data.

<cfset myarray=ArrayNew(1)>
<cfset myotherarray=ArrayNew(2)>
<cfset biggerarray=ArrayNew(3)>

<cfset biggerarray[1][1][1]=myarray>
<cfset biggerarray[1][1][1][10]=3>
<cfset biggerarray[2][1][1]=myotherarray>
<cfset biggerarray[2][1][1][4][2]="five deep">

<cfset biggestarray=ArrayNew(3)>
<cfset biggestarray[3][1][1]=biggerarray>
<cfset biggestarray[3][1][1][2][3][1]="This is complex">
<cfset myarray[3]="Can you see me">

<cfdump var=#biggestarray#><br>
<cfdump var=#myarray#>

Note: The cfdump tag displays the entire contents of an array. It is an excellent tool for debugging arrays and array-handling code.

Reviewing the code

The following table describes the code:

Code

Description

<cfset myarray=ArrayNew(1)>
<cfset myotherarray=ArrayNew(2)>
<cfset biggerarray=ArrayNew(3)>

Create three empty arrays, a 1D array, a 2D array, and a 3D array.

<cfset biggerarray[1][1][1]=myarray>
<cfset biggerarray[1][1][1][10]=3>

Make element [1][1][1] of the 3D biggerarray array be a copy of the 1D array. Assign 3 to the [1][1][1][10] element of the resulting array.

The biggerarray array is now asymmetric. For example, it does not have a [1][1][2][1] element.

<cfset biggerarray[2][1][1]=
    myotherarray>
<cfset biggerarray[2][1][1][4][2]=
    "five deep">

Make element [2][1][1] of the 3D array be the 2D array, and assign the [2][1][1][4][2] element the value "five deep".

The biggerarray array is now even more asymmetric.

<cfset biggestarray=ArrayNew(3)>
<cfset biggestarray[3][1][1]
    =biggerarray>
<cfset biggestarray[3][1][1][2][3][1]
    ="This is complex">

Create a second 3D array. Make the [3][1][1] element of this array be a copy of the bigerarray array, and assign element [3][1][1][2][3][1].

The resulting array is very complex and asymmetric.

<cfset myarray[3]="Can you see me">

Assign a value to element [3] of myarray.

<cfdump var=#biggestarray#><br>
<cfdump var=#myarray#>

Use cfdump to view the structure of biggestarray and myarray.

Notice that the "Can you see me" entry appears in myarray, but not in biggestarray, because biggestarray has a copy of the original myarray values and is not affected by the change to myarray.


Adding elements to an array

You can add an element to an array by assigning the element a value or by using a ColdFusion function.

Adding an array element by assignment

You can add elements to an array by defining the value of an array element, as shown in the following cfset tag:

<cfset myarray[5]="Test Message">

If an element does not exist at the specified index, ColdFusion creates it. If an element already exists at the specified index, ColdFusion replaces it with the new value. To prevent existing data from being overwritten, use the ArrayInsertAt function, as described in the next section.

If elements with lower-number indexes do not exist, they remain undefined. You must assign values to undefined array elements before you can use them. For example, the following code creates an array and an element at index 4. It outputs the contents of element 4, but generates an error when it tries to output the (nonexistent) element 3.

<cfset myarray=ArrayNew(1)>
<cfset myarray[4]=4>
<cfoutput>
    myarray4: #myarray[4]#<br>
    myarray3: #myarray[3]#<br>
</cfoutput>

Adding an array element with a function

You can use the following array functions to add data to an array:

Function | Description
ArrayAppend | Creates a new array element at the end of the array.
ArrayPrepend | Creates a new array element at the beginning of the array.
ArrayInsertAt | Inserts an array element at the specified index position.

Because ColdFusion arrays are dynamic, if you add or delete an element from the array, any higher-numbered index values all change. For example, the following code creates a two element array and displays the array contents. It then uses ArrayPrepend to insert a new element at the beginning of the array and displays the result. The data that was originally in indexes 1 and 2 is now in indexes 2 and 3.

<!--- Create an array with three elements --->
<cfset myarray=ArrayNew(1)>
<cfset myarray[1]="Original First Element">
<cfset myarray[2]="Original Second Element">
<!--- Use cfdump to display the array structure --->
<cfdump var=#myarray#>
<br>
<!--- Add a new element at the beginning of the array --->
<cfscript>
    ArrayPrepend(myarray, "New First Element");
</cfscript>
<!--- Use cfdump to display the new array structure --->
<cfdump var=#myarray#>

For more information about these array functions, see CFML Reference.


Deleting elements from an array

Use the ArrayDeleteAt function to delete data from the array at a particular index, instead of setting the data value to zero or an empty string. If you remove data from an array, the array resizes dynamically, as the following example shows:

<!--- Create an array with three elements --->
<cfset firstname=ArrayNew(1)>
<cfset firstname[1]="Robert">
<cfset firstname[2]="Wanda">
<cfset firstname[3]="Jane">
<!--- Delete the second element from the array --->
<cfset temp=ArrayDeleteAt(firstname, 2)>
<!--- Display the array length (2) and its two entries,
which are now "Robert" and "Jane" --->
<cfoutput>
    The array now has #ArrayLen(firstname)# indexes<br>
    The first entry is #firstname[1]#<br>
    The second entry is #firstname[2]#<br>
</cfoutput>

The ArrayDeleteAt function removed the original second element and resized the array so that it has two entries, with the second element now being the original third element.


Copying arrays

You can copy arrays of simple variables (numbers, strings, Boolean values, and date-time values) by assigning the original array to a new variable name. You do not have to use ArrayNew to create the new array first. When you assign the existing array to a new variable, ColdFusion creates a new array and copies the old array’s contents to the new array. The following example creates and populates a two-element array. It then copies the original array, changes one element of the copied array and dumps both arrays. As you can see, the original array is unchanged and the copy has a new second element.

<cfset myArray=ArrayNew(1)>
<cfset myArray[1]="First Array Element">
<cfset myArray[2]="Second Array Element">
<cfset newArray=myArray>
<cfset newArray[2]="New Array Element 2">
<cfdump var=#myArray#><br>
<cfdump var=#newArray#>

If your array contains complex variables (structures, query objects, or external objects such as COM objects) assigning the original array to a new variable does not make a complete copy of the original array. The array structure is copied; however, the new array does not get its own copy of the complex data, only references to it. To demonstrate this behavior, run the following code:

Create an array that contains a structure.<br>
<cfset myStruct=StructNew()>
<cfset myStruct.key1="Structure key 1">
<cfset myStruct.key2="Structure key 2">
<cfset myArray=ArrayNew(1)>
<cfset myArray[1]=myStruct>
<cfset myArray[2]="Second array element">
<cfdump var=#myArray#><br>
<br>
Copy the array and dump it.<br>
<cfset myNewArray=myArray>
<cfdump var=#myNewArray#><br>
<br>
Change the values in the new array.<br>
<cfset myNewArray[1].key1="New first array element">
<cfset myNewArray[2]="New second array element">
<br>
Contents of the original array after the changes:<br>
<cfdump var=#myArray#><br>
Contents of the new array after the changes:<br>
<cfdump var=#myNewArray#>

The change to the new array also changes the contents of the structure in the original array.

To make a complete copy of an array that contains complex variables, use the Duplicate function.


Populating arrays with data

Array elements can store any values, including queries, structures, and other arrays. You can use a number of functions to populate an array with data, including ArraySet, ArrayAppend, ArrayInsertAt, and ArrayPrepend. These functions are useful for adding data to an existing array.

In particular, you should master the following basic techniques:

  • Populating an array with the ArraySet function
  • Populating an array with the cfloop tag
  • Populating an array from a query

The following sections describe these techniques:

  • Populating an array with the ArraySet function
  • Populating an array with the cfloop tag
  • Populating an array from a query

Populating an array with the ArraySet function

You can use the ArraySet function to populate a 1D array, or one dimension of a multidimensional array, with some initial value, such as an empty string or zero. This can be useful if you need to create an array of a certain size, but do not need to add data to it right away. One reason to do this is so that you can refer to all the array indexes. If you refer to an array index that does not contain some value, such as an empty string, you get an error.

The ArraySet function has the following form:

ArraySet (arrayname, startrow, endrow, value)

The following example initializes the array myarray, indexes 1 to 100, with an empty string:

ArraySet (myarray, 1, 100, "")

Populating an array with the cfloop tag

The cfloop tag provides a common and very efficient method for populating an array. The following example uses a cfloop tag and the MonthAsString function to populate a simple 1D array with the names of the months. A second cfloop outputs data in the array to the browser.

<cfset months=arraynew(1)>

<cfloop index="loopcount" from=1 to=12>
    <cfset months[loopcount]=MonthAsString(loopcount)>
</cfloop>

<cfloop index="loopcount" from=1 to=12>
        <cfoutput>
            #months[loopcount]#<br>
        </cfoutput>
</cfloop>

Using nested loops for 2D and 3D arrays

To output values from 2D and 3D arrays, you must employ nested loops to return array data. With a one-dimensional (1D) array, a single cfloop is sufficient to output data, as in the previous example. With arrays of dimension greater than one, you need to maintain separate loop counters for each array level.

Nesting cfloop tags for a 2D array

The following example shows how to handle nested cfloop tags to output data from a 2D array. It also uses nested cfloop tags to populate the array:

<cfset my2darray=arraynew(2)>
<cfloop index="loopcount" from=1 to=12>
    <cfloop index="loopcount2" from=1 to=2>
        <cfset my2darray[loopcount][loopcount2]=(loopcount * loopcount2)>
    </cfloop>
</cfloop>

<p>The values in my2darray are currently:</p>

<cfloop index="OuterCounter" from="1" to="#ArrayLen(my2darray)#">
    <cfloop index="InnerCounter" from="1"
            to="#ArrayLen(my2darray[OuterCounter])#">
        <cfoutput>
            <b>[#OuterCounter#][#InnerCounter#]</b>:
            #my2darray[OuterCounter][InnerCounter]#<br>
        </cfoutput>
    </cfloop>
</cfloop>

Nesting cfloop tags for a 3D array

For 3D arrays, you simply nest an additional cfloop tag. (This example does not set the array values first to keep the code short.)

<cfloop index="Dim1" from="1" to="#ArrayLen(my3darray)#">
    <cfloop index="Dim2" from="1" to="#ArrayLen(my3darray[Dim1])#">
        <cfloop index="Dim3" from="1"
                to="#ArrayLen(my3darray[Dim1][Dim2])#">
            <cfoutput>
                <b>[#Dim1#][#Dim2#][#Dim3#]</b>:
                #my3darray[Dim1][Dim2][Dim3]#<br>
            </cfoutput>
        </cfloop>
    </cfloop>
</cfloop>


Populating an array from a query

When populating an array from a query, keep the following things in mind:

  • You cannot add query data to an array all at once. A looping structure is generally required to populate an array from a query.
  • You can reference query column data using array-like syntax. For example, myquery.col_name[1] references data in the first row in the col_name column of the myquery query.
  • Inside a cfloop query= loop, you do not have to specify the query name to reference the query’s variables.

You can use a cfset tag with the following syntax to define values for array indexes:

<cfset arrayName[index]=queryColumn[row]>

In the following example, a cfloop tag places four columns of data from a sample data source into an array, myarray.

<!--- Do the query --->
<cfquery name="test" datasource="cfdocexamples">
    SELECT Emp_ID, LastName, FirstName, Email
    FROM Employees
</cfquery>

<!--- Declare the array --->
<cfset myarray=arraynew(2)>

<!--- Populate the array row by row --->
<cfloop query="test">
    <cfset myarray[CurrentRow][1]=Emp_ID>
    <cfset myarray[CurrentRow][2]=LastName>
    <cfset myarray[CurrentRow][3]=FirstName>
    <cfset myarray[CurrentRow][4]=Email>
</cfloop>

<!--- Now, create a loop to output the array contents --->
<cfset total_records=test.recordcount>
<cfloop index="Counter" from=1 to="#Total_Records#">
    <cfoutput>
        ID: #MyArray[Counter][1]#,
        LASTNAME: #MyArray[Counter][2]#,
        FIRSTNAME: #MyArray[Counter][3]#,
        EMAIL: #MyArray[Counter][4]# <br>
    </cfoutput>
</cfloop>

This example uses the query object built-in variable CurrentRow to index the first dimension of the array.


Array functions

The following functions are available for creating, editing, and handling arrays:

Function | Description
ArrayAppend | Appends an array element to the end of a specified array.
ArrayAvg | Returns the average of the values in the specified array.
ArrayClear | Deletes all data in a specified array.
ArrayDeleteAt | Deletes an element from a specified array at the specified index and resizes the array.
ArrayInsertAt | Inserts an element (with data) in a specified array at the specified index and resizes the array.
ArrayIsEmpty | Returns True if the specified array is empty of data.
ArrayLen | Returns the length of the specified array.
ArrayMax | Returns the largest numeric value in the specified array.
ArrayMin | Returns the smallest numeric value in the specified array.
ArrayNew | Creates a new array of specified dimension.
ArrayPrepend | Adds an array element to the beginning of the specified array.
ArrayResize | Resets an array to a specified minimum number of elements.
ArraySet | Sets the elements in a 1D array in a specified range to a specified value.
ArraySort | Returns the specified array with elements sorted numerically or alphanumerically.
ArraySum | Returns the sum of values in the specified array.
ArraySwap | Swaps array values in the specified indexes.
ArrayToList | Converts the specified 1D array to a list, delimited with the character you specify.
IsArray | Returns True if the value is an array.
ListToArray | Converts the specified list, delimited with the character you specify, to an array.

For more information about each of these functions, see CFML Reference.


About structures

ColdFusion structures consist of key-value pairs. Structures let you build a collection of related variables that are grouped under a single name. You can define ColdFusion structures dynamically.

You can use structures to refer to related values as a unit, rather than individually. To maintain employee lists, for example, you can create a structure that holds personnel information such as name, address, phone number, ID numbers, and so on. Then you can refer to this collection of information as a structure called employee rather than as a collection of individual variables.

A structure’s key must be a string. The values associated with the key can be any valid ColdFusion value or object. It can be a string or integer, or a complex object such as an array or another structure. Because structures can contain any kind of data they provide a very powerful and flexible mechanism for representing complex data.

This section describes the following topics:

  • Structure notation
  • Referencing complex structures

Structure notation

ColdFusion supports two types of notation for referencing structure contents. The notation that you use depends on your requirements.

Notation

Description

Object.property

You can refer to a property, prop, of an object, obj, as obj.prop. This notation, also called dot notation, is useful for simple assignments, as in this example:

depts.John="Sales"

Use this notation only when you know the property names (keys) in advance and they are strings, with no special characters, numbers, or spaces. You cannot use the dot notation when the property, or key, is dynamic.

Associative arrays

If you do not know the key name in advance, or it contains spaces, numbers, or special characters, you can use associative array notation. This notation uses structures as arrays with string indexes; for example:

depts["John"]="Sales"
depts[employeeName]="Sales"

You can use a variable (such as employeeName) as an associative array index. Therefore, you must enclose any literal key names in quotation marks.

For information on using associative array references containing variables, see Dynamically constructing structure references.


Referencing complex structures

When a structure contains another structure, you reference the data in the nested structure by extending either object.property or associative array notation. You can even use a mixture of both notations.

For example, if structure1 has a key key1 whose value is a structure that has keys struct2key1, struct2key2, and so on, you can use any of the following references to access the data in the first key of the embedded structure:

Structure1.key1.Struct2key1
Structure1["key1"].Struct2key1
Structure1.key1["Struct2key1"]
Structure1["key1"]["Struct2key1"]

The following example shows various ways you can reference the contents of a complex structure:

<cfset myArray=ArrayNew(1)>
<cfset myArray[1]="2">
<cfset myArray[2]="3">
<cfset myStruct2=StructNew()>
<cfset myStruct2.struct2key1="4">
<cfset myStruct2.struct2key2="5">
<cfset myStruct=StructNew()>
<cfset myStruct.key1="1">
<cfset myStruct.key2=myArray>
<cfset myStruct.key3=myStruct2>
<cfdump var=#myStruct#><br>

<cfset key1Var="key1">
<cfset key2Var="key2">
<cfset key3Var="key3">
<cfset var2="2">

<cfoutput>
Value of the first key<br>
#mystruct.key1#<br>
#mystruct["key1"]#<br>
#mystruct[key1Var]#<br>
<br>
Value of the second entry in the key2 array<br>
#myStruct.key2[2]#<br>
#myStruct["key2"][2]#<br>
#myStruct[key2Var][2]#<br>
#myStruct[key2Var][var2]#<br>
<br>
Value of the struct2key2 entry in the key3 structure<br>
#myStruct.key3.struct2key2#<br>
#myStruct["key3"]["struct2key2"]#<br>
#myStruct[key3Var]["struct2key2"]#<br>
#myStruct.key3["struct2key2"]#<br>
#myStruct["key3"].struct2key2#<br>
<br>
</cfoutput>

Reviewing the code

The following table describes the code:

Code

Description

<cfset myArray=ArrayNew(1)>
<cfset myArray[1]="2">
<cfset myArray[2]="3">
<cfset myStruct2=StructNew()>
<cfset myStruct2.struct2key1="4">
<cfset myStruct2.struct2key2="5">
<cfset myStruct=StructNew()>
<cfset myStruct.key1="1">
<cfset myStruct.key2=myArray>
<cfset myStruct.key3=myStruct2>

Create a structure with three entries: a string, an array, and an embedded structure.

<cfdump var=#myStruct#><br>

Display the complete structure.

<cfset key1Var="key1">
<cfset key2Var="key2">
<cfset key3Var="key3">
<cfset var2="2">

Create variables containing the names of the myStruct keys and the number 2.

<cfoutput>
Value of the first key<br>
#mystruct.key1#<br>
#mystruct["key1"]#<br>
#mystruct[key1Var]#<br>
<br>

Output the value of the structure’s key1 (string) entry using the following notation:

  • object.property notation
  • associative array notation with a constant
  • associative array notation with a variable

Value of the second entry in the
key2 array<br>
#myStruct.key2[2]#<br>
#myStruct["key2"][2]#<br>
#myStruct[key2Var][2]#<br>
#myStruct[key2Var][var2]#<br>
<br>

Output the value of the second entry in the structure’s key2 array using the following notation:

  • object.property notation
  • associative array notation with a constant
  • associative array notation with a variable
  • associative array notation with variables for both the array and the array index

Value of the struct2key2 entry in
the key3 structure<br>
#myStruct.key3.struct2key2#<br>
#myStruct["key3"]["struct2key2"]#<br>
#myStruct[key3Var]["struct2key2"]#<br>
#myStruct.key3["struct2key2"]#<br>
#myStruct["key3"].struct2key2#<br>
<br>
</cfoutput>

Output the value of second entry in the structure’s key3 embedded structure using the following notation:

  • object.property notation
  • associative array notation with two constants
  • associative array notation with a variable and a constant
  • object.property notation followed by associative array notation
  • associative array notation followed by object.property notation


Creating and using structures

This section explains how to create and use structures in ColdFusion. The sample code in this section uses a structure called employee, which is used to add new employees to a corporate information system.

This section describes the following topics:

  • Creating structures
  • Adding data elements to structures
  • Updating values in structures
  • Getting information about structures and keys
  • Copying structures
  • Deleting structure elements and structures
  • Looping through structures

Creating structures

You can create a structure by creating a first key-pair or by using the ColdFusion StructNew function.

Creating structures by assigning values

You can create a structure by assigning a key-value pair. For example, the following line creates a structure named myStruct with one element, name, that has the value Macromedia.

<cfset myStruct.name="Macromedia">

Note: You can also create a structure using the structname["keyname"] format; for example, <cfset myStruct["name"] ="Macromedia">.

Creating structures using a function

You can create structures by assigning a variable name to the structure with the StructNew function as follows:

<cfset mystructure=StructNew()>

For example, to create a structure named departments, use the following syntax:

<cfset departments=StructNew()>

This creates an empty structure to which you can add data.

Use this technique to create structures if your application must run on ColdFusion server versions 5 and earlier.

Adding data elements to structures

You add an element to a structure by assigning the element a value or by using a ColdFusion function. It is cleaner and more efficient to use direct assignment, so only this technique is described.

You add structure key-value pairs by defining the value of the structure key, as shown in the following example:

<cfset myNewStructure.key1="A new structure with a new key">
<cfdump var=#myNewStructure#>
<cfset myNewStructure.key2="Now I’ve added a second key">
<cfdump var=#myNewStructure#>

Updating values in structures

You can update structure element values by assignment or by using the StructUpdate function. Direct assignment results in simpler code than using a function, so only the assignment technique is described.

To update a structure value, assign the key a new value. For example, the following code uses cfset and object.property notation to create a new structure element called departments.John, and changes John’s department from Sales to Marketing. It then uses associative array notation to change his department to Facilities. Each time the department changes, it displays the results:

<cfset departments=structnew()>
<cfset departments.John = "Sales">
<cfoutput>
    Before the first change, John was in the #departments.John# Department<br>
</cfoutput>
<cfset Departments.John = "Marketing">
<cfoutput>
    After the first change, John is in the #departments.John# Department<br>
</cfoutput>
<cfset Departments["John"] = "Facilities">
<cfoutput>
    After the second change, John is in the #departments.John# Department<br>
</cfoutput>


Getting information about structures and keys

The following sections describe how to use ColdFusion functions to find information about structures and their keys.

Getting information about structures

To find out if a given value represents a structure, use the IsStruct function, as follows:

IsStruct(variable)

This function returns True if variable is a ColdFusion structure. (It also returns True if variable is a Java object that implements the java.util.Map interface.)

Structures are not indexed numerically, so to find out how many name-value pairs exist in a structure, use the StructCount function, as in the following example:

StructCount(employee)

To discover whether a specific Structure contains data, use the StructIsEmpty function, as follows:

StructIsEmpty(structure_name)

This function returns True if the structure is empty, and False if it contains data.

Finding a specific key and its value

To determine whether a specific key exists in a structure, use the StructKeyExists function, as follows:

StructKeyExists(structure_name, "key_name")

Do not put the name of the structure in quotation marks, but you do put the key name in quotation marks. For example, the following code displays the value of the MyStruct.MyKey only if it exists:

<cfif StructKeyExists(myStruct, "myKey")>
<cfoutput> #mystruct.myKey#</cfoutput><br>
</cfif>

You can use the StructKeyExists function to dynamically test for keys by using a variable to represent the key name. In this case, you do not put the variable in quotation marks. For example, the following code loops through the records of the GetEmployees query and tests the myStruct structure for a key that matches the query’s LastName field. If ColdFusion finds a matching key, it displays the Last Name from the query and the corresponding entry in the structure.

<cfloop query="GetEmployees">
<cfif StructKeyExists(myStruct, LastName)>
<cfoutput>#LastName#: #mystruct[LastName]#</cfoutput><br>
</cfif>
</cfloop>

If the name of the key is known in advance, you can also use the ColdFusion IsDefined function, as follows:

IsDefined("structure_name.key")>

However, if the key is dynamic, or contains special characters, you must use the StructKeyExists function.

Note: Using StructKeyExists to test for the existence of a structure entry is more efficient than using IsDefined. ColdFusion scopes are available as structures and you can improve efficiency by using StructKeyExists to test for the existence of variables.

Getting a list of keys in a structure

To get a list of the keys in a CFML structure, you use the StructKeyList function, as follows:

<cfset temp=StructKeyList(structure_name, [delimiter] )>

You can specify any character as the delimiter; the default is a comma.

Use the StructKeyArray function to returns an array of keys in a structure, as follows:

<cfset temp=StructKeyArray(structure_name)>

Note: The StructKeyList and StructKeyArray functions do not return keys in any particular order. Use the ListSort or ArraySort functions to sort the results.


Copying structures

ColdFusion provides several ways to copy structures and create structure references. The following table lists these methods and describes their uses:

Technique

Use

Duplicate function

Makes a complete copy of the structure. All data is copied from the original structure to the new structure, including the contents of structures, queries, and other objects. As a result changes to one copy of the structure have no effect on the other structure.

This function is useful when you want to move a structure completely into a new scope. In particular, if a structure is created in a scope that requires locking (for example, Application), you can duplicate it into a scope that does not require locking (for example, Request), and then delete it in the scope that requires locking.

StructCopy function

Makes a shallow copy of a structure. It creates a new structure and copies all simple variable and array values at the top level of the original structure to the new structure. However, it does not make copies of any structures, queries, or other objects that the original structure contains, or of any data inside these objects. Instead, it creates a reference in the new structure to the objects in the original structure. As a result, any change to these objects in one structure also changes the corresponding objects in the copied structure.

The Duplicate replaces this function for most, if not all, purposes.

Variable assignment

Creates an additional reference, or alias, to the structure. Any change to the data using one variable name changes the structure that you access using the other variable name.

This technique is useful when you want to add a local variable to another scope or otherwise change a variable’s scope without deleting the variable from the original scope.

The following example shows the different effects of copying, duplicating, and assigning structure variables:

Create a new structure<br>
<cfset myNewStructure=StructNew()>
<cfset myNewStructure.key1="1">
<cfset myNewStructure.key2="2">
<cfset myArray=ArrayNew(1)>
<cfset myArray[1]="3">
<cfset myArray[2]="4">
<cfset myNewStructure.key3=myArray>
<cfset myNewStructure2=StructNew()>
<cfset myNewStructure2.Struct2key1="5">
<cfset myNewStructure2.Struct2key2="6">
<cfset myNewStructure.key4=myNewStructure2>
<cfdump var=#myNewStructure#><br>
<br>
A StructCopy copied structure<br>
<cfset CopiedStruct=StructCopy(myNewStructure)>
<cfdump var=#CopiedStruct#><br>
<br>
A Duplicated structure<br>
<cfset dupStruct=Duplicate(myNewStructure)>
<cfdump var=#dupStruct#><br>
<br>
A new reference to a structure<br>
<cfset structRef=myNewStructure>
<cfdump var=#structRef#><br>

<br>
Change a string, array element, and structure value in the StructCopy copy.<br>
<br>
<cfset CopiedStruct.key1="1A">
<cfset CopiedStruct.key3[2]="4A">
<cfset CopiedStruct.key4.Struct2key2="6A">
Original structure<br>
<cfdump var=#myNewStructure#><br>
Copied structure<br>
<cfdump var=#CopiedStruct#><br>
Duplicated structure<br>
<cfdump var=#DupStruct#><br>
Structure reference
<cfdump var=#structRef#><br>
<br>
Change a string, array element, and structure value in the Duplicate<br>
<br>
<cfset DupStruct.key1="1B">
<cfset DupStruct.key3[2]="4B">
<cfset DupStruct.key4.Struct2key2="6B">
Original structure<br>
<cfdump var=#myNewStructure#><br>
Copied structure<br>
<cfdump var=#CopiedStruct#><br>
Duplicated structure<br>
<cfdump var=#DupStruct#><br>
Structure reference
<cfdump var=#structRef#><br>
<br>
Change a string, array element, and structure value in the reference<br>
<br>
<cfset structRef.key1="1C">
<cfset structRef.key3[2]="4C">
<cfset structRef.key4.Struct2key2="6C">
Original structure<br>
<cfdump var=#myNewStructure#><br>
Copied structure<br>
<cfdump var=#CopiedStruct#><br>
Duplicated structure<br>
<cfdump var=#DupStruct#><br>
Structure reference
<cfdump var=#structRef#><br>
<br>
Clear the original structure<br>
<cfset foo=structclear(myNewStructure)>
Original structure:<br>
<cfdump var=#myNewStructure#><br>
Copied structure<br>
<cfdump var=#CopiedStruct#><br>
Duplicated structure<br>
<cfdump var=#DupStruct#><br>
Structure reference:<br>
<cfdump var=#structRef#><br>


Deleting structure elements and structures

To delete a key and its value from a structure, use the StructDelete function, as follows:

StructDelete(structure_name, key [, indicateNotExisting ])

The indicateNotExisting argument tells the function what to do if the specified key does not exist. By default, the function always returns True. However, if you specify True for the indicateNotExisting argument, the function returns True if the key exists and False if it does not.

You can also use the StructClear function to delete all the data in a structure but keep the structure instance itself, as follows:

StructClear(structure_name)

If you use StructClear to delete a structure that you have copied using the StructCopy function, the specified structure is deleted, but the copy is unaffected.

If you use StructClear to delete a structure that has a multiple references, the function deletes the contents of the structure and all references point to the empty structure, as shown in the following example:

<cfset myStruct.Key1="Macromedia">
Structure before StructClear<br>
<cfdump var="#myStruct#">
<cfset myCopy=myStruct>
<cfset StructClear(myCopy)>
After Clear:<br>
myStruct: <cfdump var="#myStruct#"><br>
myCopy: <cfdump var="#myCopy#">


Looping through structures

You can loop through a structure to output its contents, as shown in the following example:

<!--- Create a structure and set its contents --->
<cfset departments=structnew()>

<cfset val=StructInsert(departments, "John", "Sales")>
<cfset val=StructInsert(departments, "Tom", "Finance")>
<cfset val=StructInsert(departments, "Mike", "Education")>

<!--- Build a table to display the contents --->
<cfoutput>
<table cellpadding="2" cellspacing="2">
    <tr>
        <td><b>Employee</b></td>
        <td><b>Department</b></td>
    </tr>
    <!--- Use cfloop to loop through the departments structure.
    The item attribute specifies a name for the structure key. --->
    <cfloop collection=#departments# item="person">
        <tr>
            <td>#person#</td>
            <td>#Departments[person]#</td>
        </tr>
    </cfloop>
</table>
</cfoutput>


Structure examples

Structures are particularly useful for grouping together a set of variables under a single name. The example in this section uses structures to collect information from a form, and to submit that information to a custom tag, named cf_addemployee. For information on creating and using custom tags, see Creating and Using Custom CFML Tags.

Example file newemployee.cfm

The following ColdFusion page shows how to create structures and use them to add data to a database. It calls the cf_addemployee custom tag, which is defined in the addemployee.cfm file.

<html>
<head>
<title>Add New Employees</title>
</head>

<body>
<h1>Add New Employees</h1>
<!--- Action page code for the form at the bottom of this page --->

<!--- Establish parameters for first time through --->
<cfparam name="Form.firstname" default="">
<cfparam name="Form.lastname" default="">
<cfparam name="Form.email" default="">
<cfparam name="Form.phone" default="">
<cfparam name="Form.department" default="">

<!--- If at least the firstname form field is passed, create
     a structure named employee and add values --->
<cfif #Form.firstname# eq "">
    <p>Please fill out the form.</p>
<cfelse>
  <cfoutput>
     <cfscript>
        employee=StructNew();
        employee.firstname = Form.firstname;
        employee.lastname = Form.lastname;
        employee.email = Form.email;
        employee.phone = Form.phone;
        employee.department = Form.department;
     </cfscript>

<!--- Display results of creating the structure --->
     First name is #StructFind(employee, "firstname")#<br>
     Last name is #StructFind(employee, "lastname")#<br>
     EMail is #StructFind(employee, "email")#<br>
     Phone is #StructFind(employee, "phone")#<br>
     Department is #StructFind(employee, "department")#<br>
    </cfoutput>

  <!--- Call the custom tag that adds employees --->
    <cf_addemployee empinfo="#employee#">
</cfif>

<!--- The form for adding the new employee information --->
<hr>
<form action="newemployee.cfm" method="Post">
First Name:&nbsp;
<input name="firstname" type="text" hspace="30" maxlength="30"><br>
Last Name:&nbsp;
<input name="lastname" type="text" hspace="30" maxlength="30"><br>
EMail:&nbsp;
<input name="email" type="text" hspace="30" maxlength="30"><br>
Phone:&nbsp;
<input name="phone" type="text" hspace="20" maxlength="20"><br>
Department:&nbsp;
<input name="department" type="text" hspace="30" maxlength="30"><br>

<input type="Submit" value="OK">
</form>
<br>
</body>
</html>

Reviewing the code

The following table describes the code:

Code

Description

<cfparam name="Form.firstname" default="">
<cfparam name="Form.lastname" default="">
<cfparam name="Form.email" default="">
<cfparam name="Form.phone" default="">
<cfparam name="Form.department" default="">

Set default values of all form fields so that they exist the first time this page is displayed and can be tested.

<cfif #form.firstname# eq "">
 Please fill out the form.<br>

Test the value of the form’s firstname field. This field is required. The test is False the first time the page displays.

If there is no data in the Form.firstname variable, display a message requesting the user to fill the form.

<cfelse>
 <cfoutput>
  <cfscript>
   employee=StructNew();
   employee.firstname = Form.firstname;
   employee.lastname = Form.lastname;
   employee.email = Form.email;
   employee.phone = Form.phone;
   employee.department = Form.department;
  </cfscript>

  First name is #employee.firstname#<br>
  Last name is #employee.lastname#<br>
  EMail is #employee.email#<br>
  Phone is #employee.phone#<br>
  Department is #employee.department#<br>
 </cfoutput>

If Form.firstname contains text, the user submitted the form.

Use CFScript to create a new structure named employee and fill it with the form field data.

Then display the contents of the structure

<cf_addemployee empinfo="#duplicate(employee)#">
</cfif>

Call the cf_addemployee custom tag and pass it a copy of the employee structure in the empinfo attribute.

The duplicate function ensures that the custom tag gets a copy of the employee structure, not the original. While this is not necessary in this example, it is good practice because it prevents the custom tag from modifying the calling page’s structure contents.

<form action="newemployee.cfm" method="Post">
First Name:&nbsp;
<input name="firstname" type="text" hspace="30"
   maxlength="30"><br>
Last Name:&nbsp;
<input name="lastname" type="text" hspace="30"
   maxlength="30"><br>
EMail:&nbsp;
<input name="email" type="text" hspace="30"
   maxlength="30"><br>
Phone:&nbsp;
<input name="phone" type="text" hspace="20"
   maxlength="20"><br>
<p>Department:&nbsp;
<input name="department" type="text" hspace="30"
   maxlength="30"><br>
<br>
<input type="Submit" value="OK">
</form>

The data form. When the user clicks Submit, the form posts the data to this ColdFusion page.

Example file addemployee.cfm

The following file is an example of a custom tag used to add employees. Employee information is passed through the employee structure (the empinfo attribute). For databases that do not support automatic key generation, you must also add the Emp_ID.

<cfif StructIsEmpty(attributes.empinfo)>
    <cfoutput>
        Error. No employee data was passed.<br>
    </cfoutput>
    <cfexit method="ExitTag">
<cfelse>
    <!--- Add the employee --->
    <cfquery name="AddEmployee" datasource="cfdocexamples">
        INSERT INTO Employees
            (FirstName, LastName, Email, Phone, Department)
        VALUES (
        '#attributes.empinfo.firstname#' ,
        '#attributes.empinfo.lastname#' ,
        '#attributes.empinfo.email#' ,
        '#attributes.empinfo.phone#' ,
        '#attributes.empinfo.department#' )
    </cfquery>
</cfif>
<cfoutput>
    <hr>Employee Add Complete
</cfoutput>

Reviewing the code

The following table describes the code:

Code

Description

<cfif StructIsEmpty(Attributes.empinfo)>
  <cfoutput>
    Error. No employee data was passed.
  </cfoutput>
  <cfexit method="ExitTag">

If the custom tag was called without an empinfo attribute, display an error message and exit the tag.

<cfelse>
  <cfquery name="AddEmployee" datasource=
      "cfdocexamples">
    INSERT INTO Employees
      (FirstName, LastName, Email, Phone,
        Department)
    VALUES (
      '#attributes.empinfo.firstname#' ,
      '#attributes.empinfo.lastname#' ,
      '#attributes.empinfo.email#' ,
      '#attributes.empinfo.phone#' ,
      '#attributes.empinfo.department#' )
    </cfquery>
</cfif>

Add the employee data passed in the empinfo structure to the Employees table of the cfdocexamples database.

Use direct references to the structure entries, not StructFind functions.

If the database does not support automatic generation of the Emp_ID key, you must add an Emp_ID entry to the form and add it to the query.

<cfoutput>
    <hr>Employee Add Complete
</cfoutput>

Display a completion message. This code does not have to be inside the cfelse block because the cfexit tag prevents it from being run if the empinfo structure is empty.


Structure functions

You can use the following functions to create and manage structures in ColdFusion applications. The table describes each function’s purpose and provides specific, but limited, information that can assist you in determining whether to use the function instead of other techniques:

Function | Description
Duplicate | Returns a complete copy of the structure.
IsStruct | Returns True if the specified variable is a ColdFusion structure or a Java object that implements the java.util.Map interface.
StructAppend | Appends one structure to another.
StructClear | Removes all data from the specified structure.
StructCopy | Returns a "shallow" copy of the structure. All embedded objects are references to the objects in the original structure. The Duplicate function has replaced this function for most purposes.
StructCount | Returns the number of keys in the specified structure.
StructDelete | Removes the specified item from the specified structure.
StructFind | Returns the value associated with the specified key in the specified structure. This function is redundant with accessing structure elements using associative array notation.
StructFindKey | Searches through a structure for the specified key name and returns an array containing data on the found key or keys.
StructFindValue | Searches through a structure for the specified simple data value (for example, a string or number) and returns an array containing information on the value location in the structure.
StructGet | Returns a reference to a substructure contained in a structure at the specified path. This function is redundant with using direct reference to a structure. If you accidentally use this function on a variable that is not a structure, it replaces the value with an empty structure.
StructInsert | Inserts the specified key-value pair into the specified structure. Unlike a direct assignment statement, this function generates an error by default if the specified key exists in the structure.
StructIsEmpty | Indicates whether the specified structure contains data. Returns True if the structure contains no data, and False if it does contain data.
StructKeyArray | Returns an array of keys in the specified structure.
StructKeyExists | Returns True if the specified key is in the specified structure. You can use this function in place of the IsDefined function to check for the existence of variables in scopes that are available as structures.
StructKeyList | Returns a list of keys in the specified structure.
StructNew | Returns a new structure.
StructSort | Returns an array containing the key names of a structure in the order determined by the sort criteria.
StructUpdate | Updates the specified key with the specified value. Unlike a direct assignment statement, this function generates an error if the structure or key does not exist.

All functions except StructDelete throw an exception if a referenced key or structure does not exist.

For more information on these functions, see CFML Reference.
Previous


Extending ColdFusion Pages with CFML Scripting

Macromedia ColdFusion MX offers a server-side scripting language, CFScript, that provides ColdFusion functionality in script syntax. This JavaScript-like language gives developers the same control flow as ColdFusion, but without tags. You can also use CFScript to write user-defined functions that you can use anywhere that a ColdFusion expression is allowed.

This chapter describes the CFScript language’s functionality and syntax, and provides information on using CFScript effectively in ColdFusion pages.

Contents

About CFScript

The CFScript language

Using CFScript statements

Handling exceptions

CFScript example
Next


About CFScript

CFScript is a language within a language. It is a scripting language that is similar to JavaScript but is simpler to use. Also, unlike JavaScript, CFScript only runs on the ColdFusion server; it does not run on the client system. CFScript code can use all the ColdFusion functions and expressions, and has access to all ColdFusion variables that are available in the script’s scope.

CFScript provides a compact and efficient way to write ColdFusion logic. Typical uses of CFScript include the following:

  • Simplifying and speeding variable setting
  • Building compact JavaScript-like flow control structures
  • Creating user-defined functions

Because you use functions and expressions directly in CFScript, you do not have to surround each assignment or function in a cfset tag. Also, CFScript assignments are often faster than cfset tags.

CFScript provides a set of decision and flow-control structures that are more familiar than ColdFusion tags to most programmers.

In addition to variable setting, other operations tend to be slightly faster in CFScript than in tags.

ColdFusion 5 and later releases let you use CFScript to create user-defined functions, or UDFs (also known as custom functions). You call UDFs in the same manner that you call standard ColdFusion functions. UDFs are to ColdFusion built-in functions what custom tags are to ColdFusion built-in tags. Typical uses of UDFs include data manipulation and mathematical calculation routines.

You cannot include ColdFusion tags in CFScript. However, a number of functions and CFScript statements are equivalent to commonly used tags. For more information, see CFScript functional equivalents to ColdFusion tags.

Comparing tags and CFScript

The following examples show how you can use CFML tags and CFScript to do the same thing. Each example takes data submitted from a form and puts it in a structure; if the form does not have a last name and department field, it displays a message.

Using CFML tags

<cfif IsDefined("Form.submit")>
      <cfif (Form.lastname NEQ "") AND (Form.department NEQ "")>
        <cfset employee=structnew()>
        <cfset employee.firstname=Form.firstname>
        <cfset employee.lastname=Form.lastname>
        <cfset employee.email=Form.email>
        <cfset employee.phone=Form.phone>
        <cfset employee.department=Form.department>
        <cfoutput>
            Adding #Form.firstname# #Form.lastname#<br>
        </cfoutput>
    <cfelse>
        <cfoutput>
            You must enter a Last Name and Department.<br>
        </cfoutput>
     </cfif>
</cfif>

Using CFScript

<cfscript>
    if (IsDefined("Form.submit")) {
        if ((Form.lastname NEQ "") AND (Form.department NEQ "")) {
            employee=StructNew();
            employee.firstname=Form.firstname;
            employee.lastname=Form.lastname;
            employee.email=Form.email;
            employee.phone=Form.phone;
            employee.department=Form.department;
            WriteOutput("Adding #Form.firstname# #Form.lastname# <br>");
            }
        else
            WriteOutput("You must enter a Last Name and Department.<br>");
        }
</cfscript>


The CFScript language

This section explains the syntax of the CFScript language.

Identifying CFScript

You enclose CFScript regions inside < cfscript > and </cfscript> tags. No other CFML tags are allowed inside a cfscript region. The following lines show a minimal script:

<cfscript>
a = 2;
</cfscript>

Variables

CFScript variables can be of any ColdFusion type, such as numbers, strings, arrays, queries, and objects. The CFScript code can read and write any variables that are available in the page that contains the script. This includes all common scope variables, such as session, application, and server variables.

Expressions and operators

CFScript supports all CFML expressions. CFML expressions include operators (such as +, -, EQ, and so on), as well as all CFML functions. As in all ColdFusion expressions, you must use CFML operators, such as LT, GT, and EQ. You cannot use JavaScript operators, such as <, >, ==, or ++.

For information about CFML expressions, operators, and functions, see Using Expressions and Number Signs.

Statements

CFScript supports the following statements:

assignment | for-in | try-catch
function call | while | function (function definition)
if-else | do-while | var (in custom functions only)
switch-case-default | break | return (in custom functions only)
for | continue |

The following rules apply to statements:

  • You must put a semicolon at the end of a statement.
  • Line breaks are ignored. A single statement can cross multiple lines.
  • White space is ignored. For example, it does not matter whether you precede a semicolon with a space character.
  • Use curly braces to group multiple statements together into one logical statement unit.
  • Unless otherwise indicated, you can use any ColdFusion expression in the body of a statement.

Note: This chapter documents all statements except function, var, and return. For information on these statements, see Defining functions in CFScript.

Statement blocks

Curly brace characters ({ and }) group multiple CFScript statements together so that they are treated as a single unit or statement. This enables you to create code blocks in conditional statements, such as the following:

if(score GT 0) {
    result = "positive";
    Positives = Positives + 1;
}

In this example, both assignment statements are executed if the score is greater than 0. If they were not in the code block, only the first line would execute.

You do not have to put brace characters on their own lines in the code. For example, you could put the open brace in the preceding example on the same line as the if statement, and some programmers use this style. However, putting at least the ending brace on its own line makes it easier to read the code and separate out code blocks.

Comments

CFScript has two forms of comments: single line and multiline.

A single line comment begins with two forward slashes (//) and ends at the line end; for example:

//This is a single-line comment.
//This is a second single-line comment.

A multiline comment starts with a /* marker and continues until it reaches a */ marker; for example:

/*This is a multiline comment.
  You do not need to start each line with a comment indicator.
  This is the last line in the comment. */

The following rules apply to comments:

  • Comments do not have to start at the beginning of a line. They can follow active code on a line. For example, the following line is valid:
    MyVariable = 12; // Set MyVariable to the default value.
  • The end of a multiline comment can be followed on the same line by active code. For example, the following line is valid, although it is poor coding practice:
    End of my long comment */ foo = "bar";
  • You can use multiline format for a comment on a single line, for example:
    /*This is a single line comment using multiline format. */
  • You cannot nest /* and */ markers inside other comment lines.
  • CFML comments (<!--- and --->) do not work in CFScript.

Reserved words

In addition to the names of ColdFusion functions and words reserved by ColdFusion expressions (such as NOT, AND, IS, and so on), the following words are reserved in CFScript. Do not use these words as variables or identifiers in your scripting code:

break | default | function | switch
case | do | if | try
catch | else | in | var
continue | for | return | while

Differences from JavaScript

Although CFScript and JavaScript are similar, they have several key differences. The following list identifies CFScript features that differ from JavaScript:

  • CFScript uses ColdFusion expressions, which are neither a subset nor a superset of JavaScript expressions. For example, there is no < operator in CFScript; you use the LT operator instead.
  • Variable declarations are only used in user-defined functions.
  • CFScript is case-insensitive.
  • All statements end with a semicolon and line breaks in the code are ignored.
  • Assignments are statements, not expressions.
  • JavaScript objects, such as Window and Document, are not available.
  • Only the ColdFusion server processes CFScript. There is no client-side CFScript.

CFScript limitation

You cannot include ColdFusion tags in CFScript. However, you can include cfscript blocks inside other ColdFusion tags, such as cfoutput.

CFScript functional equivalents to ColdFusion tags

Tag | CFScript equivalent
cfset | Direct assignment, such as Myvar=1;
cfoutput | WriteOutput function
cfif, cfelseif, cfelse | if and else statements
cfswitch, cfcase, cfdefaultcase | switch, case, and default statements
Indexed cfloop | for loops
Conditional cfloop | while loops and do while loops
Structure cfloop | for in loop. (There is no equivalent for queries, lists, or objects.)
cfbreak | break statement. CFScript also has a continue statement that has no equivalent CFML tag.
cftry, cfcatch | try and catch statements
cfcookie | Direct assignment of Cookie scope memory-only variables. You cannot use direct assignment to set persistent cookies that are stored on the user’s system.
cfobject | CreateObject function

For example, the following example loops through a query in CFScript:

...
<cfscript>
// Loop through the qGetEmails RecordSet
for (x = 1; x LTE qGetEmails.RecordCount; x=x+1) {
  This_id = qGetEmails.Emails_id[x];
  This_Subject = qGetEmails.Subject[x];
  This_RecFrom = qGetEmails.RecFrom[x];
  This_SentTo = qGetEmails.SentTo[x];
  This_dReceived = qGetEmails.dReceived[x];
   This_Body = qGetEmails.Body[x];
... // More code goes here.
}
</cfscript>


Using CFScript statements

The following sections describe how to use these CFScript statements:

  • Using assignment statements and functions
  • Using conditional processing statements
  • Using looping statements

Using assignment statements and functions

CFScript assignment statements are the equivalent of the cfset tag. These statements have the following form:

lval = expression;

lval is any ColdFusion variable reference; for example:

x = "positive";
y = x;
a[3]=5;
structure.member=10;
ArrayCopy=myArray;

You can use ColdFusion function calls, including UDFs, directly in CFScript. For example, the following line is a valid CFScript statement:

StructInsert(employee,"lastname",FORM.lastname);

Using conditional processing statements

CFScript includes the following conditional processing statements:

  • if and else statements, which serve the same purpose as the cfif, cfelseif, and cfelse tags
  • switch, case, and default statements, which are the equivalents of the cfswitch, cfcase, and cfdefaultcase tags

Using if and else statements

The if and else statements have the following syntax:

if(expr) statement [else statement]

In its simplest form, an if statement looks like this:

if(value EQ 2700)
    message = "You’ve reached the maximum";

A simple if-else statement looks like the following:

if(score GT 1)
    result = "positive";
else
    result = "negative";

CFScript does not include an elseif statement. However, you can use an if statement immediately after an else statement to create the equivalent of a cfelseif tag, as the following example shows:

if(score GT 1)
    result = "positive";
else if(score EQ 0)
    result = "zero";
else
    result = "negative";

As with all conditional processing statements, you can use curly braces to enclose multiple statements for each condition, as follows:

if(score GT 1) {
    result = "positive";
    message = "The result was positive.";
    }
else {
    result = "negative";
    message = "The result was negative.";
    }

Note: Often, you can make your code clearer by using braces even where they are not required.

Using switch and case statements

The switch statement and its dependent case and default statements have the following syntax:

switch (expression) {
    case constant: [case constant:]... statement(s) break;
    [case constant: [case constant:]... statement(s) break;]...
    [default: statement(s)] }

Use the following rules and recommendations for switch statements:

  • You cannot mix Boolean and numeric constant values in a switch statement.
  • Each constant value must be a constant (that is, not a variable, a function, or other expression).
  • Multiple case constant: statements can precede the statement or statements to execute if any of the cases are true. This lets you specify several matches for one code block.
  • No two constant values can be the same.
  • The statements following the colon in a case statement block do not have to be in braces. If a constant value equals the switch expression, ColdFusion executes all statements through the break statement.
  • The break statement at the end of the case statement tells ColdFusion to exit the switch statement. ColdFusion does not generate an error message if you omit a break statement. However, if you omit it, ColdFusion executes all the statements in the following case statement, even if that case is false. In nearly all circumstances, this is not what you want to do.
  • You can have only one default statement in a switch statement block. ColdFusion executes the statements in the default block if none of the case statement constants equals the expression value.
  • The default statement does not have to follow all switch statements, but it is good programming practice to do so. If any switch statements follow the default statement you must end the default block code with a break statement.
  • The default statement is not required. However, you should use one if the case constants do not include all possible values of the expression.
  • The default statement does not have to follow all the case statements; however, it is good programming practice to put it there.

The following switch statement takes the value of a name variable:

  1. If the name is John or Robert, it sets both the male variable and the found variable to True.
  2. If the name is Mary, it sets the male variable to False and the found variable to True.
  3. Otherwise, it sets the found variable to False.
switch(name) {
    case "John": case "Robert":
        male=True;
        found=True;
        break;
    case "Mary":
        male=False;
        found=True;
        break;
    default:
        found=False;
} //end switch


Using looping statements

CFScript provides a richer selection of looping constructs than those supplied by CFML tags. It enables you to create efficient looping constructs similar to those in most programming and scripting languages. CFScript provides the following looping constructs:

  • For
  • While
  • Do-while
  • For-in

CFScript also includes the continue and break statements that control loop processing.

The following sections describe these types of loops and their uses.

  • Using for loops
  • Using while loops
  • Using do-while loops
  • Using for-in loops
  • Using continue and break statements


Using for loops

The for loop has the following format:

for (initial-expression; test-expression; final-expression) statement

The initial-expression and final-expression can be one of the following:

  • A single assignment expression; for example, x=5 or loop=loop+1
  • Any ColdFusion expression; for example, SetVariable("a",a+1)
  • Empty

The test-expression can be one of the following:

  • Any ColdFusion expression; for example:
    A LT 5
index LE x
status EQ "not found" AND index LT end
  • Empty

Note: The test expression is re-evaluated before each repeat of the loop. If code inside the loop changes any part of the test expression, it can affect the number of iterations in the loop.

The statement can be a single semicolon terminated statement or a statement block in curly braces.

When ColdFusion executes a for loop, it does the following:

  1. Evaluates the initial expression.
  2. Evaluates the test-expression.
  3. If the test-expression is False, exits the loop and processing continues following the statement.

    If the test-expression is True:

    1. Executes the statement (or statement block).
    2. Evaluates the final-expression.
    3. Returns to Step 2.

For loops are most commonly used for processing in which an index variable is incremented each time through the loop, but it is not limited to this use.

The following simple for loop sets each element in a 10-element array with its index number.

for(index=1;
    index LT 10;
    index = index + 1)
    a[index]=index;

The following, more complex, example demonstrates two features:

  • The use of curly braces to group multiple statements into a single block.
  • An empty condition statement. All loop control logic is in the statement block.
<cfscript>
strings=ArrayNew(1);
ArraySet(strings, 1, 10, "lock");
strings[5]="key";
indx=0;
for( ; ; ) {
    indx=indx+1;
    if(Find("key",strings[indx],1)) {
        WriteOutput("Found key at " & indx & ".<br>");
        break;
        }
    else if (indx IS ArrayLen(strings)) {
        WriteOutput("Exited at " & indx & ".<br>");
        break;
        }
}
</cfscript>

This example shows one important issue that you must remember when creating loops: you must always ensure that the loop ends. If this example lacked the else if statement, and there was no "key" in the array, ColdFusion would loop forever or until a system error occurred; you would have to stop the server to end the loop.

The example also shows two issues with index arithmetic: in this form of loop you must make sure to initialize the index, and you must keep track of where the index is incremented. In this case, because the index is incremented at the top of the loop, you must initialize it to 0 so it becomes 1 in the first loop.


Using while loops

The while loop has the following format:

while (expression) statement

The while statement does the following:

  1. Evaluates the expression.
  2. If the expression is True, it does the following:
    1. Executes the statement, which can be a single semicolon-terminated statement or a statement block in curly braces.
    2. Returns to step 1.

If the expression is False, processing continues with the next statement.

The following example uses a while loop to populate a 10-element array with multiples of five.

a = ArrayNew(1);
loop = 1;
while (loop LE 10) {
    a[loop] = loop * 5;
    loop = loop + 1;
    }

As with other loops, you must make sure that at some point the while expression is False and you must be careful to check your index arithmetic.


Using do-while loops

The do-while loop is like a while loop, except that it tests the loop condition after executing the loop statement block. The do-while loop has the following format:

do statement while (expression);

The do while statement does the following:

  1. Executes the statement, which can be a single semicolon-terminated statement or a statement block in curly braces.
  2. Evaluates the expression.
  3. If the expression is true, it returns to step 1.

If the expression is False, processing continues with the next statement.

The following example, like the while loop example, populates a 10-element array with multiples of 5:

a = ArrayNew(1);
loop = 1;
do {
  a[loop] = loop * 5;
  loop = loop + 1;
}
while (loop LE 10);

Because the loop index increment follows the array value assignment, the example initializes the loop variable to 1 and tests to make sure that it is less than or equal to 10.

The following example generates the same results as the previous two examples, but it increments the index before assigning the array value. As a result, it initializes the index to 0, and the end condition tests that the index is less than 10.

a = ArrayNew(1);
loop = 0;
do {
    loop = loop + 1;
    a[loop] = loop * 5;
}
while (loop LT 10);

The following example loops through a query:

<cfquery ... name="myQuery">
... sql goes here...
</cfquery>
<cfscript>
if (myQuery.RecordCount gt 0) {
  currRow=1;
  do {
    theValue=myQuery.myField[CurrRow];
    currRow=currRow+1;
  } while (currRow LTE myQuery.RecordCount);
}
</cfscript>


Using for-in loops

The for-in loop loops over the elements in a ColdFusion structure. It has the following format:

for (variable in structure) statement

The variable can be any ColdFusion identifier; it holds each structure key name as ColdFusion loops through the structure. The structure must be the name of an existing ColdFusion structure. The statement can be a single semicolon terminated statement or a statement block in curly braces.

The following example creates a structure with three elements. It then loops through the structure and displays the name and value of each key. Although the curly braces are not required here, they make it easier to determine the contents of the relatively long WriteOutput function. In general, you can make structured control flow, especially loops, clearer by using curly braces.

myStruct=StructNew();
myStruct.productName="kumquat";
mystruct.quality="fine";
myStruct.quantity=25;
for (keyName in myStruct) {
    WriteOutput("myStruct." & Keyname & " has the value: " &
        myStruct[keyName] &"<br>");
}

Note: Unlike the cfloop tag, CFScript for-in loops do not provide built-in support for looping over queries and lists.


Using continue and break statements

The continue and break statements enable you to control the processing inside loops:

  • The continue statement tells ColdFusion to skip to the beginning of the next loop iteration.
  • The break statement exits the current loop or case statement.

Using continue

The continue statement ends the current loop iteration, skips any code following it in the loop, and jumps to the beginning of the next loop iteration. For example, the following code loops through an array and display’s each value that is not an empty string:

for ( loop=1; loop LE 10; loop = loop+1) {
    if(a[loop] EQ "") continue;
    WriteOutput(loop);
}

(To test this code snippet, you must first create an array, a, with 10 or more elements, some of which are not empty strings.)

In general, the continue statement is particularly useful if you loop over arrays or structures and you want to skip processing for array elements or structure members with specific values, such as the empty string.

Using break

The break statement exits the current loop or case statement. Processing continues at the next CFScript statement. You end case statement processing blocks with a break statement. You can also use a test case with a break statement to prevent infinite loops, as shown in the following example. This script loops through an array and prints out the array indexes that contain the value key. It uses a conditional test and a break statement to make sure that the loop ends when at the end of the array.

strings=ArrayNew(1);
ArraySet(strings, 1, 10, "lock");
strings[5]="key";
strings[9]="key";
indx=0;
for( ; ; ) {
    indx=indx+1;
    if(Find("key",strings[indx],1)) {
        WriteOutput("Found a key at " & indx & ".<br>");
        }
    else if (indx IS ArrayLen(strings)) {
        WriteOutput("Array ends at index " & indx & ".<br>");
        break;
    }
}


Handling exceptions

ColdFusion provides two statements for exception handling in CFScript: try and catch. These statements are equivalent to the CFML cftry and cfcatch tags.

Note: This section does not explain exception-handling concepts. For a discussion of exception handling in ColdFusion, see Handling Errors.

Exception handling syntax and rules

Exception-handling code in CFScript has the following format:

try {
    Code where exceptions will be caught
}
catch(exceptionType exceptionVariable) {
    Code to handle exceptions of type exceptionType
    that occur in the try block
}
...
catch(exceptionTypeN exceptionVariableN) {
    Code to handle exceptions of type
    exceptionTypeN that occur in the try block
}

Note: In CFScript, catch statements follow the try block; you do not put them inside the try block. This structure differs from that of the cftry tag, which must include the cfcatch tags in its body.

When you have a try statement, you must have a catch statement. In the catch block, the exceptionVariable variable contains the exception type. This variable is the equivalent of the cfcatch tag cfcatch.Type built-in variable.

Exception handling example

The following code shows exception handling in CFScript. It uses a CreateObject function to create a Java object. The catch statement executes only if the CreateObject function generates an exception. The displayed information includes the exception message; the except.Message variable is the equivalent of calling the Java getMessage method on the returned Java exception object.

<cfscript>
    try {
        emp = CreateObject("Java", "Employees");
    }
    catch(Any excpt) {
        WriteOutput("The application was unable to perform a required operation.<br>
Please try again later.<br>If this problem persists, contact
Customer Service and include the following information:<br>
            #excpt.Message#<br>");
    }
</cfscript>


CFScript example

The example in this section uses the following CFScript features:

  • Variable assignment
  • Function calls
  • For loops
  • If-else statements
  • WriteOutput functions
  • Switch statements

The example uses CFScript without any other ColdFusion tags. It creates a structure of course applicants. This structure contains two arrays; the first has accepted students, the second has rejected students. The script also creates a structure with rejection reasons for some (but not all) rejected students. It then displays the accepted applicants followed by the rejected students and their rejection reasons.

<html>
<head>
    <title>CFScript Example</title>
</head>
<body>
<cfscript>

    //Set the variables

    acceptedApplicants[1] = "Cora Cardozo";
    acceptedApplicants[2] = "Betty Bethone";
    acceptedApplicants[3] = "Albert Albertson";
    rejectedApplicants[1] = "Erma Erp";
    rejectedApplicants[2] = "David Dalhousie";
    rejectedApplicants[3] = "Franny Farkle";
    applicants.accepted=acceptedApplicants;
    applicants.rejected=rejectedApplicants;

    rejectCode=StructNew();
    rejectCode["David Dalhousie"] = "score";
    rejectCode["Franny Farkle"] = "too late";

    //Sort and display accepted applicants

    ArraySort(applicants.accepted,"text","asc");
    WriteOutput("The following applicants were accepted:<hr>");
    for (j=1;j lte ArrayLen(applicants.accepted);j=j+1) {
        WriteOutput(applicants.accepted[j] & "<br>");
    }
    WriteOutput("<br>");

    //sort and display rejected applicants with reasons information

    ArraySort(applicants.rejected,"text","asc");
    WriteOutput("The following applicants were rejected:<hr>");
    for (j=1;j lte ArrayLen(applicants.rejected);j=j+1) {
        applicant=applicants.rejected[j];
        WriteOutput(applicant & "<br>");
        if (StructKeyExists(rejectCode,applicant)) {
            switch(rejectCode[applicant]) {
                case "score":
                    WriteOutput("Reject reason: Score was too low.<br>");
                    break;
                case "late":
                    WriteOutput("Reject reason: Application was late.<br>");
                    break;
                default:
                    WriteOutput("Rejected with invalid reason code.<br>");
            } //end switch
        } //end if
        else {
            WriteOutput("Reject reason was not defined.<br>");
        } //end else
        WriteOutput("<br>");
    } //end for
</cfscript>

Reviewing the code

The following table describes the code:

Code

Description

<cfscript>
acceptedApplicants[1] = "Cora Cardozo";
acceptedApplicants[2] = "Betty Bethone";
acceptedApplicants[3] = "Albert Albertson";
rejectedApplicants[1] = "Erma Erp";
rejectedApplicants[2] = "David Dalhousie";
rejectedApplicants[3] = "Franny Farkle";
applicants.accepted=acceptedApplicants;
applicants.rejected=rejectedApplicants;

rejectCode=StructNew();
rejectCode["David Dalhousie"] = "score";
rejectCode["Franny Farkle"] = "too late";

Creates two one-dimensional arrays, one with the accepted applicants and another with the rejected applicants. The entries in each array are in random order.

Creates a structure and assign each array to an element of the structure.

Creates a structure with rejection codes for rejected applicants. The rejectedCode structure does not have entries for all rejected applicants, and one of its values does not match a valid code. The structure element references use associative array notation in order to use key names that contain spaces.

ArraySort(applicants.accepted,"text","asc");
WriteOutput("The following applicants were accepted:<hr>");
for (j=1;j lte ArrayLen(applicants.accepted);j=j+1) {
  WriteOutput(applicants.accepted[j] & "<br>");
}
WriteOutput("<br>");

Sorts the accepted applicants alphabetically.

Displays a heading.

Loops through the accepted applicants and writes their names. Braces enhance clarity, although they are not needed for a single statement loop.

Writes an additional line break at the end of the list of accepted applicants.

ArraySort(applicants.rejected,"text","asc");
WriteOutput("The following applicants were rejected:<hr>");

Sorts rejectedApplicants array alphabetically and writes a heading.

for (j=1;j lte ArrayLen(applicants.rejected);j=j+1) {
  applicant=applicants.rejected[j];
  WriteOutput(applicant & "<br>");

Loops through the rejected applicants.

Sets the applicant variable to the applicant name. This makes the code clearer and enables you to easily reference the rejectCode array later in the block.

Writes the applicant name.

if (StructKeyExists(rejectCode,applicant)) {
  switch(rejectcode[applicant]) {
    case "score":
      WriteOutput("Reject reason: Score was too low.<br>");
      break;
    case "late":
      WriteOutput("Reject reason: Application was
            late.<br>");
      break;
    default:
      WriteOutput("Rejected with invalid reason code.<br>");
  } //end switch
} //end if

Checks the rejectCode structure for a rejection code for the applicant.

If a code exists, enters a switch statement that examines the rejection code value.

If the rejection code value matches one of the known codes, displays an expanded explanation of the meaning. Otherwise (the default case), displays an indication that the rejection code is not valid.

Comments at the end of blocks help clarify the control flow.

else {
  WriteOutput("Reject reason was not defined. <br>");
{

If there is no entry for the applicant in the rejectCode structure, displays a message indicating that the reason was not defined.

        WriteOutput("<br>");
} //end for
</cfscript>

Displays a blank line after each rejected applicant.

Ends the for loop that handles each rejected applicant.

Ends the CFScript.
Previous


Using Regular Expressions in Functions

Regular expressions let you perform string matching operations using ColdFusion functions. This chapter describes how regular expressions work with the following functions:

  • REFind
  • REFindNoCase
  • REReplace
  • REReplaceNoCase

This chapter does not apply to regular expressions used in the cfinput and cftextinput tags. These tags use JavaScript regular expressions, which have a slightly different syntax than ColdFusion regular expressions. For information on JavaScript regular expressions, see Building Dynamic Forms with cfform Tags.

Contents

About regular expressions

Regular expression syntax

Using backreferences

Returning matched subexpressions

Regular expression examples

Types of regular expression technologies
Next


About regular expressions

In traditional string matching, as used by the ColdFusion Find and Replace functions, you provide the string pattern to search for and the string to search. The following example searches a string for the pattern " BIG " and returns a string index if found. The string index is the location in the search string where the string pattern begins.

<cfset IndexOfOccurrence=Find(" BIG ", "Some BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

You must provide the exact string pattern to match. If the exact pattern is not found, Find returns an index of 0. Because you must specify the exact string pattern to match, matches for dynamic data can be very difficult, if not impossible, to construct.

The next example uses a regular expression to perform the same search. This example searches for the first occurrence in the search string of any string pattern that consists entirely of uppercase letters enclosed by spaces:

<cfset IndexOfOccurrence=REFind(" [A-Z]+ ", "Some BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

The regular expression " [A-Z]+ " matches any string pattern consisting of a leading space, followed by any number of uppercase letters, followed by a trailing space. Therefore, this regular expression matches the string " BIG " and any string of uppercase letters enclosed in spaces.

By default, the matching of regular expressions is case-sensitive. You can use the case-insensitive functions, REFindNoCase and REReplaceNoCase, for case-insensitive matching.

Because you often process large amounts of dynamic textual data, regular expressions are invaluable in writing complex ColdFusion applications.

Using ColdFusion regular expression functions

ColdFusion supplies four functions that work with regular expressions:

  • REFind
  • REFindNoCase
  • REReplace
  • REReplaceNoCase

REFind and REFindNoCase use a regular expression to search a string for a pattern and return the string index where it finds the pattern. For example, the following function returns the index of the first instance of the string " BIG ":

<cfset IndexOfOccurrence=REFind(" BIG ", "Some BIG BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

To find the next occurrence of the string " BIG ", you must call the REFind function a second time. For an example of iterating over a search string to find all occurrences of the regular expression, see Returning matched subexpressions.

REReplace and REReplaceNoCase use regular expressions to search through a string and replace the string pattern that matches the regular expression with another string. You can use these functions to replace the first match, or to replace all matches.

For detailed descriptions of the ColdFusion functions that use regular expressions, see CFML Reference.

Basic regular expression syntax

The simplest regular expression contains only a literal characters. The literal characters must match exactly the text being searched. For example, you can use the regular expression function REFind to find the string pattern " BIG ", just as you can with the Find function:

<cfset IndexOfOccurrence=REFind(" BIG ", "Some BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

In this example, REFind must match the exact string pattern " BIG ".

To use the full power of regular expressions, combine literal characters with character sets and special characters, as in the following example:

<cfset IndexOfOccurrence=REFind(" [A-Z]+ ", "Some BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

The literal characters of the regular expression consists of the space characters at the beginning and end of the regular expression. The character set consists of that part of the regular expression in square brackets. This character set specifies to find a single uppercase letter from A to Z, inclusive. The plus sign (+) after the square brackets is a special character specifying to find one or more occurrences of the character set.

If you removed the + from the regular expression in the previous example, " [A-Z] " matches a literal space, followed by any single uppercase letter, followed by a single space. This regular expression matches " B " but not " BIG ". The REFind function returns 0 for the regular expression, meaning that it did not find a match.

You can construct very complicated regular expressions containing literal characters, character sets, and special characters. Like any programming language, the more you work with regular expressions, the more you can accomplish with them. The examples in this section are fairly basic. For more examples, see Regular expression examples.


Regular expression syntax

This section describes the basic rules for creating regular expressions.

  • Using character sets
  • Finding repeating characters
  • Case sensitivity in regular expressions
  • Using subexpressions
  • Using special characters
  • Using escape sequences
  • Using character classes

Using character sets

The pattern within the square brackets of a regular expression defines a character set that is used to match a single character. For example, the regular expression " [A-Za-z] " specifies to match any single uppercase or lowercase letter enclosed by spaces. In the character set, a hyphen indicates a range of characters.

The regular expression " B[IAU]G " matches the strings " BIG ", " BAG ", and " BUG ", but does not match the string " BOG ".

If you specified the regular expression as " B[IA][GN] ", the concatenation of character sets creates a regular expression that matches the corresponding concatenation of characters in the search string. This regular expression matches a space, followed by "B", followed by an "I" or "A", followed by a "G" or "N", followed by a trailing space. The regular expression matches " BIG ", " BAG ", "BIN ", and "BAN ".

The regular expression [A-Z][a-z]* matches any word that starts with an uppercase letter and is followed by zero or more lowercase letters. The special character * after the closing square bracket specifies to match zero or more occurrences of the character set.

Note: The * only applies to the character set that immediately precedes it, not to the entire regular expression.

A + after the closing square bracket specifies to find one or more occurrences of the character set. You interpret the regular expression " [A-Z]+ " as matching one or more uppercase letters enclosed by spaces. Therefore, this regular expression matches " BIG " and also matches " LARGE ", " HUGE ", " ENORMOUS ", and any other string of uppercase letters surrounded by spaces.

Considerations when using special characters

Since a regular expression followed by an * can match zero instances of the regular expression, it can also match the empty string. For example,

<cfoutput>REReplace("Hello","[T]*","7","ALL") -
#REReplace("Hello","[T]*","7","ALL")#<BR>
</cfoutput>

results in the following output:

REReplace("Hello","[T]*","7","ALL") - 7H7e7l7l7o

The regular expression [T]* can match empty strings. It first matches the empty string before "H" in "Hello". The "ALL" argument tells REReplace to replace all instances of an expression. The empty string before "e" is matched and so on until the empty string before "o" is matched.

This result might be unexpected. The workarounds for these types of problems are specific to each case. In some cases you can use [T]+, which requires at least one "T", instead of [T]*. Alternatively, you can specify an additional pattern after [T]*.

In the following examples the regular expression has a "W" at the end:

<cfoutput>REReplace("Hello World","[T]*W","7","ALL") –
#REReplace("Hello World","[T]*W","7","ALL")#<BR></cfoutput>

This expression results in the following more predictable output:

REReplace("Hello World","[T]*W","7","ALL") - Hello 7orld


Finding repeating characters

In some cases, you might want to find a repeating pattern of characters in a search string. For example, the regular expression "a{2,4}" specifies to match two to four occurrences of "a". Therefore, it would match: "aa", "aaa", "aaaa", but not "a" or "aaaaa". In the following example, the REFind function returns an index of 6:

<cfset IndexOfOccurrence=REFind("a{2,4}", "hahahaaahaaaahaaaaahhh")>
<!--- The value of IndexOfOccurrence is 6--->

The regular expression "[0-9]{3,}" specifies to match any integer number containing three or more digits: "123", "45678", etc. However, this regular expression does not match a one-digit or two-digit number.

You use the following syntax to find repeating characters:

  • {m,n}

    Where m is 0 or greater and n is greater than or equal to m. Match m through n (inclusive) occurrences.

    The expression {0,1} is equivalent to the special character ?.

  • {m,}

    Where m is 0 or greater. Match at least m occurrences. The syntax {,n} is not allowed.

    The expression {1,} is equivalent to the special character +, and {0,} is equivalent to *.

  • {m}

    Where m is 0 or greater. Match exactly m occurrences.


Case sensitivity in regular expressions

ColdFusion supplies case-sensitive and case-insensitive functions for working with regular expressions. REFind and REReplace perform case-sensitive matching and REFindNoCase and REReplaceNoCase perform case-insensitive matching.

You can build a regular expression that models case-insensitive behavior, even when used with a case-sensitive function. To make a regular expression case insensitive, substitute individual characters with character sets. For example, the regular expression [Jj][Aa][Vv][Aa], when used with the case-sensitive functions REFind or REReplace, matches all of the following string patterns:

  • JAVA
  • java
  • Java
  • jAva
  • All other combinations of case


Using subexpressions

Parentheses group parts of regular expressions together into grouped subexpressions that you can treat as a single unit. For example, the regular expression "ha" specifies to match a single occurrence of the string. The regular expression "(ha)+" matches one or more instances of "ha".

In the following example, you use the regular expression "B(ha)+" to match the letter "B" followed by one or more occurrences of the string "ha":

<cfset IndexOfOccurrence=REFind("B(ha)+", "hahaBhahahaha")>
<!--- The value of IndexOfOccurrence is 5 --->

You can use the special character | in a subexpression to create a logical "OR". You can use the following regular expression to search for the word "jelly" or "jellies":

<cfset IndexOfOccurrence=REFind("jell(y|ies)", "I like peanut butter and jelly">
<!--- The value of IndexOfOccurrence is 26--->


Using special characters

Regular expressions define the following list of special characters:

+ * ? . [ ^ $ ( ) { | \

In some cases, you use a special character as a literal character. For example, if you want to search for the plus sign in a string, you have to escape the plus sign by preceding it with a backslash:

"\+"

The following table describes the special characters for regular expressions:

Special Character

Description

\

A backslash followed by any special character matches the literal character itself, that is, the backslash escapes the special character.

For example, "\+" matches the plus sign, and "\\" matches a backslash.

.

A period matches any character, including newline.

To match any character except a newline, use [^#chr(13)##chr(10)#], which excludes the ASCII carriage return and line feed codes. The corresponding escape codes are \r and \n.

[ ]

A one-character character set that matches any of the characters in that set.

For example, "[akm]" matches an "a", "k", or "m". A hyphen in a character set indicates a range of characters; for example, [a-z] matches any single lowercase letter.

If the first character of a character set is the caret (^), the regular expression matches any character except those in the set. It does not match the empty string.

For example, [^akm] matches any character except "a", "k", or "m". The caret loses its special meaning if it is not the first character of the set.

^

If the caret is at the beginning of a regular expression, the matched string must be at the beginning of the string being searched.

For example, the regular expression "^ColdFusion" matches the string "ColdFusion lets you use regular expressions" but not the string "In ColdFusion, you can use regular expressions."

$

If the dollar sign is at the end of a regular expression, the matched string must be at the end of the string being searched.

For example, the regular expression "ColdFusion$" matches the string "I like ColdFusion" but not the string "ColdFusion is fun."

?

A character set or subexpression followed by a question mark matches zero or one occurrences of the character set or subexpression.

For example, xy?z matches either "xyz" or "xz".

|

The OR character allows a choice between two regular expressions.

For example, jell(y|ies) matches either "jelly" or "jellies".

+

A character set or subexpression followed by a plus sign matches one or more occurrences of the character set or subexpression.

For example, [a-z]+ matches one or more lowercase characters.

*

A character set or subexpression followed by an asterisk matches zero or more occurrences of the character set or subexpression.

For example, [a-z]* matches zero or more lowercase characters.

()

Parentheses group parts of a regular expression into subexpressions that you can treat as a single unit.

For example, (ha)+ matches one or more instances of "ha".

(?x)

If at the beginning of a regular expression, it specifies to ignore whitespace in the regular expression and lets you use ## for end-of-line comments. You can match a space by escaping it with a backslash.

For example, the following regular expression includes comments, preceded by ##, that are ignored by ColdFusion:

reFind("(?x)
    one                  ##first option
    |two                 ##second option
    |three\ point\ five  ## note escaped spaces
    ", "three point five")

(?m)

If at the beginning of a regular expression, it specifies the multiline mode for the special characters ^ and $.

When used with ^, the matched string can be at the start of the of entire search string or at the start of new lines, denoted by a linefeed character or chr(10), within the search string. For $, the matched string can be at the end the search string or at the end of new lines.

Multiline mode does not recognize a carriage return, or chr(13), as a new line character.

The following example searches for the string "two" across multiple lines:

#reFind("(?m)^two", "one#chr(10)#two")#

This example returns 4 to indicate that it matched "two" after the chr(10) linefeed. Without (?m), the regular expression would not match anything, because ^ only matches the start of the string.

The character (?m) does not affect \A or \Z, which always match the start or end of the string, respectively. For information on \A and \Z, see Using escape sequences.

(?i)

If at the beginning of a regular expression for REFind(), it specifies to perform a case-insensitive compare.

For example, the following line would return an index of 1:

    #reFind("(?i)hi", "HI")#

If you omit the (?i), the line would return an index of zero to signify that it did not find the regular expression.

(?=...)

If at the beginning of a regular expression, it specifies to use positive lookahead when searching for the regular expression.

Positive lookahead tests for the parenthesized subexpression like regular parenthesis, but does not include the contents in the match - it merely tests to see if it is there in proximity to the rest of the expression.

For example, consider the expression to extract the protocol from a URL:

<cfset regex = "http(?=://)">
<cfset string = "http://">
<cfset result = reFind(regex, string, 1, "yes")>
mid(string, result.pos[1], result.len[1])

This example results in the string "http". The lookahead parentheses ensure that the "://" is there, but does not include it in the result. If you did not use lookahead, the result would include the extraneous "://".

Lookahead parentheses do not capture text, so backreference numbering will skip over these groups. For more information on backreferencing, see Using backreferences.

(?!...)

If at the beginning of a regular expression, it specifies to use negative lookahead. Negative is just like positive lookahead, as specified by (?=...), except that it tests for the absence of a match.

Lookahead parentheses do not capture text, so backreference numbering will skip over these groups. For more information on backreferencing, see Using backreferences.

(?:...)

If you prefix a subexpression with "?:", ColdFusion performs all operations on the subexpression except that it will not capture the corresponding text for use with a back reference.

You must be aware of the following considerations when using special characters in character sets, such as [a-z]:

  • To include a hyphen (-) in the square brackets of a character set as a literal character, you cannot escape it as you can other special characters because ColdFusion always interprets a hyphen as a range indicator. Therefore, if you use a literal hyphen in a character set, make it the last character in the set.
  • To include a closing square bracket (]) in the character set, escape it with a backslash, as in [1-3\]A-z]. You do not have to escape the ] character outside of the character set designator.


Using escape sequences

Escape sequences are special characters in regular expressions preceded by a backslash (\). You typically use escape sequences to represent special characters within a regular expression. For example, the escape sequence \t represents a tab character within the regular expression, and the \d escape sequence specifies any digit, similar to [0-9]. In ColdFusion the escape sequences are case-sensitive.

The following table lists the escape sequences that ColdFusion supports:

Escape Sequence

Description

\b

Specifies a boundary defined by a transition from an alphanumeric character to a nonalphanumeric character, or from a nonalphanumeric character to an alphanumeric character.

For example, the string " Big" contains boundary defined by the space (nonalphanumeric character) and the "B" (alphanumeric character).

The following example uses the \b escape sequence in a regular expression to locate the string "Big" at the end of the search string and not the fragment "big" inside the word "ambiguous".

reFindNoCase("\bBig\b", "Don’t be ambiguous about Big.")

<!--- The value of IndexOfOccurrence is 26 --->

When used inside of a character set (e.g. [\b]), it specifies a backspace

\B

Specifies a boundary defined by no transition of character type. For example, two alphanumeric character in a row or two nonalphanumeric character in a row; opposite of \b.

\A

Specifies a beginning of string anchor, much like the ^ special character.

However, unlike ^, you cannot combine \A with (?m) to specify the start of newlines in the search string.

\Z

Specifies an end of string anchor, much like the $ special character.

However, unlike $, you cannot combine \Z with (?m) to specify the end of newlines in the search string.

\n

Newline character

\r

Carriage return

\t

Tab

\f

Form feed

\d

Any digit, similar to [0-9]

\D

Any nondigit character, similar to [^0-9]

\w

Any alphanumeric character, similar to [[:alnum:]]

\W

Any nonalphanumeric character, similar to [^[:alnum:]]

\s

Any whitespace character including tab, space, newline, carriage return, and form feed. Similar to [ \t\n\r\f].

\S

Any nonwhitespace character, similar to [^ \t\n\r\f]

\xdd

A hexadecimal representation of character, where d is a hexadecimal digit

\ddd

An octal representation of a character, where d is an octal digit, in the form \000 to \377


Using character classes

In character sets within regular expressions, you can include a character class. You enclose the character class inside square brackets, as the following example shows:

REReplace ("Macromedia Web Site","[[:space:]]","*","ALL")

This code replaces all the spaces with *, producing this string:

Macromedia*Web*Site

You can combine character classes with other expressions within a character set. For example, the regular expression [[:space:]123] searches for a space, 1, 2, or 3. The following example also uses a character class in a regular expression:

<cfset IndexOfOccurrence=REFind("[[:space:]][A-Z]+[[:space:]]",
    "Some BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

The following table shows the character classes that ColdFusion supports. Regular expressions using these classes match any Unicode character in the class, not just ASCII or ISO-8859 characters.

Character class | Matches
:alpha: | Any alphabetic character.
:upper: | Any uppercase alphabetic character.
:lower: | Any lowercase alphabetic character
:digit: | Any digit. Same as \d.
:alnum: | Any alphanumeric character. Same as \w.
:xdigit: | Any hexadecimal digit. Same as [0-9A-Fa-f].
:blank: | Space or a tab.
:space: | Any whitespace character. Same as \s.
:print: | Any alphanumeric, punctuation, or space character.
:punct: | Any punctuation character
:graph: | Any alphanumeric or punctuation character.
:cntrl: | Any character not part of the character classes [:upper:], [:lower:], [:alpha:], [:digit:], [:punct:], [:graph:], [:print:], or [:xdigit:].
:word: | Any alphanumeric character, plus the underscore (_)
:ascii: | The ASCII characters, in the Hexadecimal range 0 - 7F


Using backreferences

You use parenthesis to group components of a regular expression into subexpressions. For example, the regular expression "(ha)+" matches one or more occurrences of the string "ha".

ColdFusion performs an additional operation when using subexpressions; it automatically saves the characters in the search string matched by a subexpression for later use within the regular expression. Referencing the saved subexpression text is called backreferencing.

You can use backreferencing when searching for repeated words in a string, such as "the the" or "is is". The following example uses backreferencing to find all repeated words in the search string and replace them with an asterisk:

REReplace("There is is coffee in the the kitchen",
"[ ]+([A-Za-z]+)[ ]+\1"," * ","ALL")

Using this regular expression, ColdFusion detects the two occurrences of "is" as well as the two occurrences of "the", replaces them with an asterisk enclosed in spaces, and returns the following string:

There * coffee in * kitchen

You interpret the regular expression [ ]+([A-Za-z]+)[ ]+\1 as follows:

Use the subexpression ([A-Za-z]+) to search for character strings consisting of one or more letters, enclosed by one or more spaces, [ ]+, followed by the same character string that matched the first subexpression, \1.

You reference the matched characters of a subexpression using a slash followed by a digit n (\n) where the first subexpression in a regular expression is referenced as \1, the second as \2, etc. The next section includes an example using multiple backreferences.

Using backreferences in replacement strings

You can use backreferences in the replacement string of both the REReplace and REReplaceNoCase functions. For example, to replace the first repeated word in a text string with a single word, use the following syntax:

REReplace("There is is a cat in in the kitchen",
"([A-Za-z ]+)\1","\1")

This results in the sentence:

"There is a cat in in the kitchen"

You can use the optional fourth parameter to REReplace, scope, to replace all repeated words, as in the following code:

REReplace("There is is a cat in in the kitchen",
"([A-Za-z ]+)\1","\1","ALL")

This results in the following string:

"There is a cat in the kitchen"

The next example uses two backreferences to reverse the order of the words "apples" and "pears" in a sentence:

<cfset astring = "apples and pears, apples and pears, apples and pears">
<cfset newString = REReplace("#astring#", "(apples) and (pears)",
"\2 and \1","ALL")>

In this example, you reference the subexpression (apples) as \1 and the subexpression (pears) as \2. The REReplace function returns the string:

"pears and apples, pears and apples, pears and apples"

Note: To use backreferences in either the search string or the replace string, you must use parentheses within the regular expression to create the corresponding subexpression. Otherwise, ColdFusion throws an exception.

Using backreferences to perform case conversions in replacement strings

The REReplace and REReplaceNoCase functions support special characters in replacement strings to convert replacement characters to uppercase or lowercase. The following table describes these special characters:

Special character | Description
\u | Converts the next character to uppercase.
\l | Converts the next character to lowercase.
\U | Converts all characters to uppercase until encountering \E.
\L | Converts all characters to lowercase until encountering \E.
\E | End \U or \L.

To include a literal \u, or other code, in a replacement string, escape it with another backslash; for example \\u .

For example, the following statement replaces the uppercase string "HELLO" with a lowercase "hello". This example uses backreferences to perform the replacement. For more information on using backreferences, see Using backreferences in replacement strings.

reReplace("HELLO", "([[:upper:]]*)", "Don't shout\scream \L\1")

The result of this example is the string "Don't shout\scream hello".

Escaping special characters in replacement strings

You use the backslash character, \, to escape backreference and case-conversion characters in replacement strings. For example, to include a literal "\u" in a replacement string, escape it, as in "\\u".

Omitting subexpressions from backreferences

By default, a set of parentheses will both group the subexpression and capture its matched text for later referral by backreferences. However, if you insert "?:" as the first characters of the subexpression, ColdFusion performs all operations on the subexpression except that it will not capture the corresponding text for use with a back reference.

This is useful when alternating over subexpressions containing differing numbers of groups would complicate backreference numbering. For example, consider an expression to insert a "Mr." in between Bonjour|Hi|Hello and Bond, using a nested group for alternating between Hi & Hello:

<cfset regex = "(Bonjour|H(?:i|ello))( Bond)">
<cfset replaceString = "\1 Mr.\2">
<cfset string = "Hello Bond">
#reReplace(string, regex, replaceString)#

This example returns "Hello Mr. Bond". If you did not prohibit the capturing of the Hi/Hello group, the \2 backreference would end up referring to that group instead of " Bond", and the result would be "Hello Mr.ello".


Returning matched subexpressions

The REFind and REFindNoCase functions return the location in the search string of the first match of the regular expression. Even though the search string in the next example contains two matches of the regular expression, the function only returns the index of the first:

<cfset IndexOfOccurrence=REFind(" BIG ", "Some BIG BIG string")>
<!--- The value of IndexOfOccurrence is 5 --->

To find all instances of the regular expression, you must call the REFind and REFindNoCase functions multiple times.

Both the REFind and REFindNoCase functions take an optional third parameter that specifies the starting index in the search string for the search. By default, the starting location is index 1, the beginning of the string.

To find the second instance of the regular expression in this example, you call REFind with a starting index of 8:

<cfset IndexOfOccurrence=REFind(" BIG ", "Some BIG BIG string", 8)>
<!--- The value of IndexOfOccurrence is 9 --->

In this case, the function returns an index of 9, the starting index of the second string " BIG ".

To find the second occurrence of the string, you must know that the first string occurred at index 5 and that the string’s length was 5. However, REFind only returns starting index of the string, not its length. So, you either must know the length of the matched string to call REFind the second time, or you must use subexpressions in the regular expression.

The REFind and REFindNoCase functions let you get information about matched subexpressions. If you set these functions’ fourth parameter, ReturnSubExpression, to True, the functions return a CFML structure with two arrays, pos and len, containing the positions and lengths of text strings that match the subexpressions of a regular expression, as the following example shows:

<cfset sLenPos=REFind(" BIG ", "Some BIG BIG string", 1, "True")>
<cfoutput>
    <cfdump var="#sLenPos#">
</cfoutput><br>

The following figure shows the output of the cfdump tag:

Output of the cfdump tag

Element one of the pos array contains the starting index in the search string of the string that matched the regular expression. Element one of the len array contains length of the matched string. For this example, the index of the first " BIG " string is 5 and its length is also 5. If there are no occurrences of the regular expression, the pos and len arrays each contain one element with a value of 0.

You can use the returned information with other string functions, such as mid. The following example returns that part of the search string matching the regular expression:

<cfset myString="Some BIG BIG string">
<cfset sLenPos=REFind(" BIG ", myString, 1, "True")>
<cfoutput>
    #mid(myString, sLenPos.pos[1], sLenPos.len[1])#
</cfoutput>

Each additional element in the pos array contains the position of the first match of each subexpression in the search string. Each additional element in len contains the length of the subexpression’s match.

In the previous example, the regular expression " BIG " contained no subexpressions. Therefore, each array in the structure returned by REFind contains a single element.

After executing the previous example, you can call REFind a second time to find the second occurrence of the regular expression. This time, you use the information returned by the first call to make the second:

<cfset newstart = sLenPos.pos[1] + sLenPos.len[1] - 1>
<!--- subtract 1 because you need to start at the first space --->
<cfset sLenPos2=REFind(" BIG ", "Some BIG BIG string", newstart, "True")>
<cfoutput>
    <cfdump var="#sLenPos2#">
</cfoutput><br>

The following figure shows the output of the cfdump tag:

Output of the cfdump tag

If you include subexpressions in your regular expression, each element of pos and len after element one contains the position and length of the first occurrence of each subexpression in the search string.

In the following example, the expression [A-Za-z]+ is a subexpression of a regular expression. The first match for the expression ([A-Za-z]+)[ ]+, is "is is".

<cfset sLenPos=REFind("([A-Za-z]+)[ ]+\1",
"There is is a cat in in the kitchen", 1, "True")>
<cfoutput>
    <cfdump var="#sLenPos#">
</cfoutput><br>

The following figure shows the output of the cfdump tag:

Output of the cfdump tag

The entries sLenPos.pos[1] and sLenPos.len[1] contain information about the match of the entire regular expression. The array elements sLenPos.pos[2] and sLenPos.len[2] contain information about the first subexpression ("is"). Because REFind returns information on the first regular expression match only, the sLenPos structure does not contain information about the second match to the regular expression, "in in".

The regular expression in the following example uses two subexpressions. Therefore, each array in the output structure contains the position and length of the first match of the entire regular expression, the first match of the first subexpression, and the first match of the second subexpression.

<cfset sString = "apples and pears, apples and pears, apples and pears">
<cfset regex = "(apples) and (pears)">
<cfset sLenPos = REFind(regex, sString, 1, "True")>
<cfoutput>
    <cfdump var="#sLenPos#">
</cfoutput><br><br>

The following figure shows the output of the cfdump tag:

Output of the cfdump tag

For a full discussion of subexpression usage, see the sections on REFind and REFindNoCase in the ColdFusion functions chapter in CFML Reference.

Specifying minimal matching

The regular expression quantifiers ?, *, +, {min,} and {min,max} specify a minimum and/or maximum number of instances of a given expression to match. By default, ColdFusion locates the greatest number characters in the search string that match the regular expression. This behavior is called maximal matching.

For example, you use the regular expression "<b>(.*)</b>" to search the string "<b>one</b> <b>two</b>". The regular expression "<b>(.*)</b>", matches both of the following:

  • <b>one</b>
  • <b>one</b> <b>two</b>

By default, ColdFusion always tries to match the regular expression to the largest string in the search string. The following code shows the results of this example:

<cfset sLenPos=REFind("<b>(.*)</b>", "<b>one</b> <b>two</b>", 1, "True")>
<cfoutput>
    <cfdump var="#sLenPos#">
</cfoutput><br>

The following figure shows the output of the cfdump tag:

Output of the cfdump tag

Thus, the starting position of the string is 1 and its length is 21, which corresponds to the largest of the two possible matches.

However, sometimes you might want to override this default behavior to find the shortest string that matches the regular expression. ColdFusion includes minimal-matching quantifiers that let you specify to match on the smallest string. The following table describes these expressions:

Expression | Description
*? | minimal-matching version of *
+? | minimal-matching version of +
?? | minimal-matching version of ?
{min,}? | minimal-matching version of {min,}
{min,max}? | minimal-matching version of {min,max}
{n}? | (no different from {n}, supported for notational consistency)

If you modify the previous example to use the minimal-matching syntax, the code is as follows:

<cfset sLenPos=REFind("<b>(.*?)</b>", "<b>one</b> <b>two</b>", 1, "True")>
<cfoutput>
    <cfdump var="#sLenPos#">
</cfoutput><br>

The following figure shows the output of the cfdump tag:

Output of the cfdump tag

Thus, the length of the string found by the regular expression is 10, corresponding to the string "<b>one</b>".


Regular expression examples

The following examples show some regular expressions and describe what they match:

Expression

Description

[\?&]value=

A URL parameter value in a URL.

[A-Z]:(\\[A-Z0-9_]+)+

An uppercase DOS/Windows path in which (a) is not the root of a drive, and (b) has only letters, numbers, and underscores in its text.

^[A-Za-z][A-Za-z0-9_]*

A ColdFusion variable with no qualifier.

([A-Za-z][A-Za-z0-9_]*)(\.[A-Za-z]
[A-Za-z0-9_]*)?

A ColdFusion variable with no more than one qualifier; for example, Form.VarName, but not Form.Image.VarName.

(\+|-)?[1-9][0-9]*

An integer that does not begin with a zero and has an optional sign.

(\+|-)?[0-9]+(\.[0-9]*)?

A real number.

(\+|-)?[1-9]\.[0-9]*E(\+|-)?[0-9]+

A real number in engineering notation.

a{2,4}

Two to four occurrences of "a": aa, aaa, aaaa.

(ba){3,}

At least three "ba" pairs: bababa, babababa, and so on.

Regular expressions in CFML

The following examples of CFML show some common uses of regular expression functions:

Expression

Returns

REReplace (CGI.Query_String, "CFID=[0-9]+[&]*", "")

The query string with parameter CFID and its numeric value stripped out.

REReplace("I Love Jellies", "[[:lower:]]","x","ALL"

I Lxxx Jxxxxxx

REReplaceNoCase("cabaret","[A-Z]", "G","ALL")

GGGGGGG

REReplace (Report,"\$[0-9,]*\.[0-9]*",
"$***.**")", "")

The string value of the variable Report with all positive numbers in the dollar format changed to "$***.**".

REFind ("[Uu]\.?[Ss]\.?[Aa}\.?", Report )

The position in the variable Report of the first occurrence of the abbreviation USA. The letters can be in either case and the abbreviation can have a period after any letter.

REFindNoCase("a+c","ABCAACCDD")

4

REReplace("There is is coffee in the the kitchen",
"([A-Za-z]+)[ ]+\1","*","ALL")

There * coffee in * kitchen

REReplace(report, "<[^>]*>", "", "All")

Removes all HTML tags from a string value of the report variable.


Types of regular expression technologies

Many types of regular expression technologies are available to programmers. JavaScript, Perl, and POSIX are all examples of different regular expression technologies. Each technology has its own syntax specifications and is not necessarily compatible with other technologies.

ColdFusion supports regular expressions that are Perl compliant with a few exceptions:

  • A period, ., always matches newlines.
  • In replacement strings, use \n instead of $n for backreference variables. ColdFusion escapes all $ in the replacement string.
  • You do not have to escape backslashes in replacement strings. ColdFusion escapes them, with the exception of case conversion sequences or escaped versions (e.g. \u or \\u).
  • Embedded modifiers ( (?i), etc. ) always affect the entire expression, even if they are inside a group.
  • \Q and the combinations \u\L and \l\U are not supported in replacement strings.

The following Perl statements are not supported:

  • Lookbehind (?<=) (<?!)
  • \x{hhhh}
  • \N
  • \p
  • \C

An excellent reference on regular expressions is Mastering Regular Expressions, by Jeffrey E. F. Friedl, O'Reilly & Associates, Inc., 1997, ISBN: 1-56592-257-3, available at www.oreilly.com.
Previous


Creating ColdFusion Elements

This chapter describes ColdFusion elements that you create. These elements let you to organize your code. When you create any of these elements, you write your code once and use it, without copying it, in many places. This chapter describes the elements that you can create and their features, and provides advice on selecting among the elements.

Contents

About CFML elements you create

Including pages with the cfinclude tag

About user-defined functions

Using ColdFusion components

Using custom CFML tags

Using CFX tags

Selecting among ColdFusion code reuse methods
Next


About CFML elements you create

ColdFusion provides you with several techniques and elements to create sections of code that you can use multiple times in an application. Many of the elements also let you extend the built-in capabilities of ColdFusion. ColdFusion provides the following techniques and elements:

  • ColdFusion pages you include using the cfinclude tag
  • User-defined functions (UDFs)
  • ColdFusion components
  • Custom CFML tags
  • CFX (ColdFusion Extension) tags

The following sections describe the features of each of these elements and provide guidelines for determining which to use in your application. Other chapters describe the elements in detail. The last section in this chapter includes a table to help you choose among these techniques and elements for different purposes.

ColdFusion can also use elements developed using other technologies, including the following:

  • JSP tags from JSP tag libraries

    For information on using JSP tags, see Integrating J2EE and Java Elements in CFML Applications.

  • Java objects, including objects in the Java runtime environment and JavaBeans

    For information on using Java objects, see Integrating J2EE and Java Elements in CFML Applications.

  • Microsoft COM (Component Object Model) objects

    For information on using COM objects, see Integrating COM and CORBA Objects in CFML Applications.

  • CORBA (Common Object Request Broker Architecture) objects

    For information on using CORBA objects, see Integrating COM and CORBA Objects in CFML Applications.

  • Web services

    For information on using web services, see Using Web Services


Including pages with the cfinclude tag

The cfinclude tag adds the contents of a ColdFusion page to another ColdFusion page, as if the code on the included page were part of the page that uses the cfinclude tag. It lets you pursue a "write once use multiple times" strategy for ColdFusion elements that you incorporate in multiple pages. Instead of copying and maintaining the same code on multiple pages, you can store the code in one page and then refer to it in many pages. For example, the cfinclude tag is commonly used to put a header and footer on multiple pages. This way, if you change the header or footer design, you only change the contents of a single file.

The model of an included page is that it is part of your page; it just resides in a separate file. The cfinclude tag cannot pass parameters to the included page, but the included page has access to all the variables on the page that includes it. The following figure shows this model:

Including a page using cfinclude

Using the cfinclude tag

When you use the cfinclude tag to include one ColdFusion page in another ColdFusion page, the page that includes another page is referred to as the calling page. When ColdFusion encounters a cfinclude tag it replaces the tag on the calling page with the output from processing the included page. The included page can also set variables in the calling page.

The following line shows a sample cfinclude tag:

<cfinclude template = "header.cfm">

Note: You cannot break CFML code blocks across pages. For example, if you open a cfoutput block in a ColdFusion page, you must close the block on the same page; you cannot include the closing portion of the block in an included page.

ColdFusion searches for included files as follows:

  • The template attribute specifies a path relative to the directory of the calling page.
  • If the template value is prefixed with a forward slash (/), ColdFusion MX searches for the included file in directories that you specify on the Mappings page of the ColdFusion MX Administrator.

Caution: A page must not include itself. Doing so causes an infinite processing loop, and you must stop the ColdFusion server to resolve the problem.

To include code in a calling page:

  1. Create a ColdFusion page named header.cfm that displays your company’s logo. Your page can consist of just the following lines, or it can include many lines to define an entire header:
    <img src="mylogo.gif">
<br>

    (For this example to work, you must also put your company’s logo as a GIF file in the same directory as the header.cfm file.)

  2. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Test for Include</title>
</head>
<body>
    <cfinclude template="header.cfm">
</body>
</html>
  3. Save the file as includeheader.cfm and view it in a browser.

The header should appear along with the logo.

Recommended uses

Consider using the cfinclude tag in the following cases:

  • For page headers and footers
  • To divide a large page into multiple logical chunks that are easier to understand and manage
  • For large "snippets" of code that are used in many places but do not require parameters or fit into the model of a function or tag


About user-defined functions

User-defined functions (UDFs) let you create application elements in a format in which you pass in arguments and get a return a value. You can define UDFs using CFScript or the cffunction tag. The two techniques have several differences, of which the following are the most important:

  • If you use the cffunction tag, your function can include CFML tags.
  • If you write your function using CFScript, you cannot include CFML tags.

You can use UDFs in your application pages just as you use standard ColdFusion functions. When you create a function for an algorithm or procedure that you use frequently, you can then use the function wherever you need the procedure, just as you would use a ColdFusion built-in function. For example, the following line calls the function MyFunct and passes it two arguments:

<cfset returnValue=MyFunct(Arg1, Arg2)>

You can group related functions in a ColdFusion component. For more information, see Using ColdFusion components.

As with custom tags, you can easily distribute UDFs to others. For example, the Common Function Library Project at www.cflib.org is an open-source collection of CFML user-defined functions.

Recommended uses

Typical uses of UDFs include, but are not limited to, the following:

  • Data manipulation routines, such as a function to reverse an array
  • String and date and time routines, such as a function to determine whether a string is a valid IP address
  • Mathematical calculation routines, including standard trigonometric and statistical operations or calculating loan amortization
  • Routines that call functions externally, for example using COM or CORBA, such as routines to determine the space available on a Windows file system drive

Consider using UDFs in the following circumstances:

  • You must pass in a number of arguments, process the results, and return a value. UDFs can return complex values, including structures that contain multiple simple values.
  • You want to provide logical units, such as data manipulation functions.
  • Your code must be recursive.
  • You distribute your code to others.

If you can create either a UDF or a custom CFML tag for a particular purpose, first consider creating a UDF because invoking it requires less system overhead than using a custom tag.

For more information

For more information on user-defined functions, see Writing and Calling User-Defined Functions.


Using ColdFusion components

ColdFusion components (CFCs) are ColdFusion templates that contain related functions and arguments that each function accepts. The CFC contains the CFML tags necessary to define its functions and arguments and return a value. ColdFusion components are saved with a .cfc extension.

CFCs combine the power of objects with the simplicity of CFML. By packaging related functionality into a single unit, they provide an object or class shell from which functions can be called.

ColdFusion components can make their data private, so that it is available to all functions (also called methods) in the component, but not to any application that uses the component.

ColdFusion components have the following features:

  • They are designed to provide related services in a single unit.
  • They can provide web services and make them available over the Internet.
  • They can provide ColdFusion services that Macromedia Flash clients can call directly.
  • They have several features that are familiar to object-oriented programmers, including data hiding, inheritance, packages, and introspection.

Recommended uses

Consider using ColdFusion components when doing the following:

  • Creating web services. (To create web services in ColdFusion, you must use components.)
  • Creating services that are callable by Flash clients.
  • Creating libraries of related functions, particularly if they must share data.
  • Using integrated application security mechanisms based on roles and the requestor location.
  • Developing code in an object-oriented manner, in which you use methods on objects and can create objects that extend the features of existing objects.

For more information

For more information on using ColdFusion components, see Building and Using ColdFusion Components.


Using custom CFML tags

Custom tags written in CFML behave like ColdFusion tags. They can do all of the following:

  • Take arguments.
  • Have tag bodies with beginning and ending tags.
  • Do specific processing when ColdFusion encounters the beginning tag.
  • Do processing that is different from the beginning tag processing when ColdFusion encounters the ending tag.
  • Have any valid ColdFusion page content in their bodies, including both ColdFusion built-in tags and custom tags (referred to as nested tags), or even JSP tags or JavaScript.
  • Be called recursively; that is, a custom tag can, if designed properly, call itself in the tag body.
  • Return values to the calling page in a common scope or the calling page’s Variables scope, but custom tags do not return values directly, the way functions do.

Although a custom tag and a ColdFusion page that you include using the cfinclude tag are both ColdFusion pages, they differ in how they are processed. When a page calls a custom tag, it hands processing off to the custom tag page and waits until the custom tag page completes. When the custom tag finishes, it returns processing (and possibly data) to the calling page; the calling page can then complete its processing. The following figure shows how this works. The arrows indicate the flow of ColdFusion processing the pages.

Flow control processing in a ColdFusion page

Calling custom CFML tags

Unlike built-in tags, you can invoke custom CFML tags in the following three ways:

  • Call a tag directly.
  • Call a tag using the cfmodule tag.
  • Use the cfimport tag to import a custom tag library directory.

To call a CFML custom tag directly, precede the file name with cf_, omit the .cfm extension, and put the name in angle brackets (<>). For example, use the following line to call the custom tag defined by the file mytag.cfm:

<cf_myTag>

If your tag takes a body, end it with the same tag name preceded with a forward slash (/), as follows:

</cf_myTag>

For information on using the cfmodule and cfimport tags to call custom CFML tags, see Creating and Using Custom CFML Tags.

Recommended uses

ColdFusion custom tags let you abstract complex code and programming logic into simple units. These tags let you maintain a CFML-like design scheme for your code. You can easily distribute your custom tags and share tags with others. For example, the Macromedia ColdFusion Developer’s Exchange includes a library of custom tags that perform a wide variety of often-complex jobs; see http://devex.macromedia.com/developer/gallery/index.cfm.

Consider using CFML custom tags in the following circumstances:

  • You need a tag-like structure, which has a body and an end tag, with the body contents changing from invocation to invocation.
  • You want to associate specific processing with the beginning tag, the ending tag, or both tags.
  • To use a logical structure in which the tag body uses "child" tags or subtags. This structure is similar to the cfform tag, which uses subtags for the individual form fields.
  • You do not need a function format in which the calling code uses a direct return value.
  • Your code must be recursive.
  • Your functionality is complex.
  • To distribute your code in a convenient form to others.

If you can create either a UDF or a custom CFML tag for a purpose, first consider creating a UDF because invoking it requires less system overhead than using a custom tag.

For more information

For more information on custom CFML tags, see Creating and Using Custom CFML Tags.


Using CFX tags

ColdFusion Extension (CFX) tags are custom tags that you write in Java or C++. Generally, you create a CFX tag to do something that is not possible in CFML. CFX tags also let you use existing Java or C++ code in your ColdFusion application. Unlike CFML custom tags, CFX tags cannot have bodies or ending tags.

CFX tags can return information to the calling page in a page variable or by writing text to the calling page.

CFX tags can do the following:

  • Have any number of custom attributes.
  • Create and manipulate ColdFusion queries.
  • Dynamically generate HTML to be returned to the client.
  • Set variables within the ColdFusion page from which they are called.
  • Throw exceptions that result in standard ColdFusion error messages.

Calling CFX tags

To use a CFX tag, precede the class name with cfx_ and put the name in angle brackets. For example, use the following line to call the CFX tag defined by the MyCFXClass class and pass it one attribute.

<cfx_MyCFXClass myArgument="arg1">

Recommended uses

CFX tags provide one way of using C++ or Java code. However, you can also create Java classes and COM objects and access them using the cfobject tag. CFX tags, however, provide some built-in features that the cfobject tag does not have:

  • CFX tags are easier to call in CFML code. You use CFX tags directly in CFML code as you would any other tag, and you can pass arguments using a standard tag format.
  • ColdFusion provides predefined classes for use in your Java or C++ code that facilitate CFX tag development. These classes include support for request handling, error reporting, and query management.

You should consider using CFX tags in the following circumstances:

  • You already have existing application functionality written in C++ or Java that you want to incorporate into your ColdFusion application.
  • You cannot build the functionality you need using ColdFusion elements.
  • You want to provide the new functionality in a tag format, as opposed to using the cfobject tag to import native Java or COM objects.
  • You want use the Java and C++ classes provided by ColdFusion for developing your CFX code.

For more information

For more information on CFX tags, see Building Custom CFXAPI Tags.


Selecting among ColdFusion code reuse methods

The following table lists common reasons to employ code reuse methods and indicates the techniques to consider for each purpose. The letter P indicates that the method is preferred. (There can be more than one preferred method.) The letter A means that the method provides an alternative that might be useful in some circumstances.

This table does not include CFX tags. You use CFX tags only when you should code your functionality in C++ or Java. For more information about using CFX tags, see Using CFX tags.

Purpose | cfinclude tag | Custom tag | UDF | Component
Provide code, including CFML, HTML, and static text, that must be used in multiple pages. | P |  |  |
Deploy headers and footers. | P |  |  |
Include one page in another page. | P |  |  |
Divide pages into smaller units. | P |  |  |
Use variables from a calling page. | A | P | P |
Implement code that uses recursion. |  | P | P | P
Distribute your code to others. |  | P | P | P
Operate on a body of HTML or CFML text. |  | P |  |
Use subtags. |  | P |  |
Provide a computation, data manipulation, or other procedure. |  | A | P |
Provide a single functional element that takes any number of input values and returns a (possibly complex) result. |  | A | P |
Use variables, whose variable names might change from use to use. |  | A | P | P
Provide accessibility from Flash clients. |  | A | A | P
Use built-in user security features. |  |  | A | P
Encapsulate multiple related functions and properties. |  |  |  | P
Create web services. |  |  |  | P
Implement object-oriented coding methodologies. |  |  |  | P
Previous


Writing and Calling User-Defined Functions

This chapter describes how to create and call user-defined functions (UDFs).

Contents

About user-defined functions

Creating user-defined functions

Calling user-defined functions

Working with arguments and variables in functions

Handling errors in UDFs

A user-defined function example

Using UDFs effectively
Next


About user-defined functions

You can create your own custom functions, known as user-defined functions, or UDFs. You then use them in your application pages the same way you use standard ColdFusion functions. You can also organize functions you create by grouping related functions into ColdFusion components. For more information, see Building and Using ColdFusion Components.

When you create a function for an algorithm or procedure that you use frequently, you can then use the function wherever you need the procedure. If you must change the procedure, you change only one piece of code. You can use your function anywhere that you can use a ColdFusion expression: in tag attributes, between number (#) signs in output, and in CFScript code. Typical uses of UDFs include, but are not limited to the following:

  • Data manipulation routines, such as a function to reverse an array
  • String and date/time routines, such as a function to determine whether a string is a valid IP address
  • Mathematical calculation routines, including standard trigonometric and statistical operations or calculating loan amortization
  • Routines that call functions externally, for example using COM or CORBA, including routines to determine the space available on a Windows file system drive

For information about selecting among User-defined functions, ColdFusion components, and custom tags, see Creating ColdFusion Elements.

Note: The Common Function Library Project at www.cflib.org is an open source collection of CFML user-defined functions.

To use a user-defined function, you define the function and then call it.


Creating user-defined functions

Before you create a UDF, you must determine where you want to define it, and whether you want to use CFML or CFScript to create it.

This section describes the following topics:

  • Determining where to create a user-defined function
  • About creating functions using CFScript
  • Defining functions in CFScript
  • About creating functions using tags
  • Defining functions using the cffunction tag
  • Rules for function definitions

Determining where to create a user-defined function

You can define a function in the following places:

  • In a ColdFusion component. If you organize your functions in ColdFusion components, you use the functions as described in Using ColdFusion components.
  • On the page where it is called. You can even define it below the place on the page where it is called, but this poor coding practice can result in confusing code.
  • On a page that you include using a cfinclude tag. The cfinclude tag must be executed before the function gets called. For example, you can define all your application’s functions on a single page and place a cfinclude tag at the top of pages that use the functions.
  • On any page that puts the function name in a scope common with the page on which you call the function. For more information on UDF scoping, see Specifying the scope of a function.
  • On the Application.cfc or Application.cfm page. For more information, see Designing and Optimizing a ColdFusion Application

For recommendations on selecting where you define functions, see the sections Using Application.cfm and function include files and Specifying the scope of a function.

About creating functions using CFScript

You use the function statement to define the function in CFScript. CFScript function definitions have the following features and limitations:

  • The function definition syntax is familiar to anyone who uses JavaScript or most programming languages.
  • CFScript is efficient for writing business logic, such as expressions and conditional operations.
  • CFScript function definitions cannot include CFML tags.

The following is a CFScript definition for a function that returns a power of 2:

<cfscript>
function twoPower(exponent) {
        return 2^exponent;
}
</cfscript>

For more information on how to use CFScript to define a function, see Defining functions in CFScript.

Defining functions in CFScript

You define functions using CFScript in a manner similar to defining JavaScript functions. You can define multiple functions in a single CFScript block.

Note: For more information on using CFScript, see Extending ColdFusion Pages with CFML Scripting.

CFScript function definition syntax

A CFScript function definition has the following syntax:

function functionName( [argName1[, argName2...]] )
{
        CFScript Statements
}

The following table describes the function variables:

Function variable | Description
functionName | The name of the function. You cannot use the name of a standard ColdFusion function or any name that starts with "cf". You cannot use the same name for two different function definitions. Function names cannot include periods.
argName1... | Names of the arguments required by the function. The number of arguments passed into the function must equal or exceed the number of arguments in the parentheses at the start of the function definition. If the calling page omits any of the required arguments, ColdFusion generates a mismatched argument count error.

The body of the function definition must be in curly braces, even if it is a empty.

The following two statements are allowed only in function definitions:

Statement

Description

var variableName = expression;

Creates and initializes a variable that is local to the function (function variable). This variable has meaning only inside the function and is not saved between calls to the function. It has precedence in the function body over any variables with the same name that exist in any other scopes. You never prefix a function variable with a scope identifier, and the name cannot include periods. The initial value of the variable is the result of evaluating the expression. The expression can be any valid ColdFusion expression, including a constant or even another UDF.

All var statements must be at the top of the function declaration, before any other statements. You must initialize all variables when you declare them. You cannot use the same name for a function variable and an argument.

Each var statement can initialize only one variable.

You should use the var statement to initialize all function-only variables, including loop counters and temporary variables.

return expression;

Evaluates expression (which can be a variable), returns its value to the page that called the function, and exits the function. You can return any ColdFusion variable type.

A simple CFScript example

The following example function adds the two arguments and returns the result:

<cfscript>
function Sum(a,b) {
        var sum = a + b;
        return sum;
}
</cfscript>

In this example, a single line declares the function variable and uses an expression to set it to the value to be returned. This function can be simplified so that it does not use a function variable, as follows:

function MySum(a,b) {Return a + b;}

You must always use curly braces around the function definition body, even if it is a single statement.


About creating functions using tags

You use the cffunction tag to define a UDF in CFML. The cffunction tag syntax has the following features and limitations:

  • Developers who have a background in CFML or HTML, but no scripting or programming experience will be more familiar with the syntax.
  • You can include any ColdFusion tag in your function definition. Therefore, you can create a function, for example, that accesses a database.
  • You can embed CFScript code inside the function definition.
  • The cffunction tag provides attributes that enable you to easily limit the execution of the tag to authorized users or specify how the function can be accessed.

The following code uses the cffunction tag to define the exponentiation function:

<cffunction name="twoPower" output=True>
    <cfargument name="exponent">
    <cfreturn 2^exponent>
</cffunction>

For more information on how to use the cffunction tag to define a function, see Defining functions using the cffunction tag.


Defining functions using the cffunction tag

The cffunction and cfargument tags let you define functions in CFML without using CFScript.

Note: This chapter describes how to use the cffunction tag to define a function that is not part of a ColdFusion component. For information on ColdFusion components, see Building and Using ColdFusion Components. For more information on the cffunction tag, see CFML Reference.

The cffunction tag function definition format

A cffunction tag function definition has the following format:

<cffunction name="functionName" [returnType="type" roles="roleList"
        access="accessType" output="Boolean"]>
    <cfargument name="argumentName" [Type="type" required="Boolean"
        default="defaultValue">]
    <!--- Function body code goes here. --->
    <cfreturn expression>
</cffunction>

where square brackets ([]) indicate optional arguments. You can have any number of cfargument tags.

The cffunction tag specifies the name you use when you call the function. You can optionally specify other function characteristics, as described in the following table:

Attribute

Description

name

The function name.

returnType

(Optional) The type of data that the function returns. The valid standard type names are: any, array, binary, boolean, date, guid, numeric, query, string, struct, uuid, variableName, xml, and void. If you specify any other name, ColdFusion requires the argument to be a ColdFusion component with that name.

ColdFusion throws an error if you specify this attribute and the function tries to return data with a type that ColdFusion cannot automatically convert to the one you specified. For example, if the function returns the result of a numeric calculation, a returnType attribute of string or numeric is valid, but array is not.

roles

(Optional) A comma-delimited list of security roles that can invoke this method. If you omit this attribute, ColdFusion does not restrict user access to the function.

If you use this attribute, the function executes only if the current user is logged in using the cfloginuser tag and is a member of one or more of the roles specified in the attribute. Otherwise, ColdFusion throws an unauthorized access exception. For more information on user security, see Securing Applications.

output

(Optional) Determines how ColdFusion processes displayable output in the function body.

If you do not specify this option, ColdFusion treats the body of the function as normal CFML. As a result, text and the result of any cfoutput tags in the function definition body are displayed each time the function executes.

If you specify True or "yes", the body of the function is processed as if it were in a cfoutput tag. ColdFusion displays variable values and expression results if you surround the variables and expressions with number signs (#).

If you specify False or "no", the function is processed as if it were in a cfsilent tag. The function does not display any output. The code that calls the function is responsible for displaying any function results.

You must use cfargument tags for required function arguments. All cfargument tags must precede any other CFML code in a cffunction tag body. Therefore, put the cfargument tags immediately following the cffunction opening tag. The cfargument tag takes the following attributes:

Attribute

Description

name

The argument name.

type

(Optional) The data type of the argument. The type of data that is passed to the function. The valid standard type names are any, array, binary, boolean, date, guid, numeric, query, string, struct, uuid, and variableName. If you specify any other name, ColdFusion requires the argument to be a ColdFusion component with that name.

ColdFusion throws an error if you specify this attribute and the function is called with data of a type that ColdFusion cannot automatically convert to the one you specified. For example, if the argument type attribute is numeric, you cannot call the function with an array.

required

(Optional) A Boolean value specifying whether the argument is required, If set to True and the argument is omitted from the function call, ColdFusion throws an error. The default is False. The required attribute is not required if you specify a default attribute.

Because you do not identify arguments when you call a function, all cfargument tags that specify required arguments must precede any cfargument tags that specify optional arguments in the cffunction definition.

default

(Optional) The default value for an optional argument if no argument value is passed. If you specify this attribute, ColdFusion ignores the required attribute.

Note: The cfargument tag is not required for optional arguments. This feature is useful if a function can take an indeterminate number of arguments. If you do not use the cfargument tag for an optional argument, reference it using its position in the Arguments scope array. For more information see Using the Arguments scope as an array.

Using a CFML tag in a user-defined function

The most important advantage of using the cffunction tag over defining a function in CFScript is that you can include CFML tags in the function. Thus, UDFs can encapsulate activities, such as database lookups, that require ColdFusion tags. Also, you can use the cfoutput tag to display output on the calling page with minimal coding.

Tip: To improve performance, avoid using the cfparam tag in ColdFusion functions. Instead, use the cfset tag.

The following example function looks up and returns an employee’s department ID. It takes one argument, the employee ID, and looks up the corresponding department ID in the cfdocexamples Employee table:

<cffunction name="getDeptID" >
    <cfargument name="empID" required="true" type="numeric">
    <cfset var cfdocexamples="">
    <cfquery dataSource="cfdocexamples" name="deptID">
        SELECT Dept_ID
        FROM Employee
        WHERE Emp_ID = #empID#
    </cfquery>
    <cfreturn deptID.Dept_ID>
</cffunction>


Rules for function definitions

The following rules apply to functions that you define using CFScript or the cffunction tag:

  • The function name must be unique. It must be different from any existing variable, UDF, or built-in function name, except you can use the ColdFusion advanced security function names.
  • The function name must not start with the letters cf in any form. (For example, CF_MyFunction, cfmyFunction, and cfxMyFunction are not valid UDF names.)
  • You cannot redefine or overload a function. If a function definition is active, ColdFusion generates an error if you define a second function with the same name.
  • You cannot nest function definitions; that is, you cannot define one function inside another function definition.
  • The function can be recursive, that is, the function definition body can call the function.
  • The function does not have to return a value.

You can use tags or CFScript to create a UDF. Each technique has advantages and disadvantages.


Calling user-defined functions

You can call a function anywhere that you can use an expression, including in number signs (#) in a cfoutput tag, in a CFScript, or in a tag attribute value. One function can call another function, and you can use a function as an argument to another function.

You can call a UDF in two ways:

  • With unnamed, positional arguments, as you would call a built-in function
  • With named arguments, as you would use attributes in a tag

You can use either technique for any function. However, if you use named arguments, you must use the same argument names to call the function as you use to define the function. You cannot call a function with a mixture of named and unnamed arguments.

One example of a user-defined function is a TotalInterest function that calculates loan payments based on a principal amount, annual percentage, and loan duration in months. (For this function’s definition, see A user-defined function example). You might call the function without argument names on a form’s action page, as follows:

<cfoutput>
Interest: #TotalInterest(Form.Principal, Form.Percent, Form.Months)#
</cfoutput>

You might call the function with argument names, as follows:

<cfoutput>
Interest: #TotalInterest(principal=Form.Principal, annualPercent=Form.Percent,
        months=Form.Months)#
</cfoutput>


Working with arguments and variables in functions

This section describes the following topics:

  • Good argument naming practice
  • Passing arguments
  • Passing complex data
  • About the Arguments scope
  • Function-only variables
  • Referencing caller variables
  • Using arguments

Good argument naming practice

An argument’s name should represent its use. For example, the following code is unlikely to result in confusion:

<cfscript>
    function SumN(Addend1,Addend2)
    { return Addend1 + Addend2; }
</cfscript>
<cfset x = 10>
<cfset y = 12>
<cfoutput>#SumN(x,y)#</cfoutput>

The following, similar code is more likely to result in programming errors:

<cfscript>
    function SumN(x,y)
    { return x + y; }
</cfscript>
<cfset x = 10>
<cfset y = 12>
<cfoutput>#SumN(x,y)#<cfoutput>

Passing arguments

ColdFusion passes the following data types to the function by value:

  • Integers
  • Real numbers
  • Strings (including lists)
  • Date-time objects
  • Arrays

As a result, any changes that you make in the function to these arguments do not affect the variable that was used to call the function, even if the calling code is on the same ColdFusion page as the function definition.

ColdFusion passes queries, structures, and external objects such as COM objects into the function by reference. As a result, any changes to these arguments in the function also change the value of the variable in the calling code.

For an example of the effects of passing arguments, see Passing complex data.

Passing complex data

Structures, queries, and complex objects such as COM objects are passed to UDFs by reference, so the function uses the same copy of the data as the caller. Arrays are passed to user-defined functions by value, so the function gets a new copy of the array data and the array in the calling page is unchanged by the function. As a result, you must handle arrays differently from all other complex data types.

Passing structures, queries, and objects

For your function to modify the caller’s copy of a structure, query, or object, you must pass the variable as an argument. Because the function gets a reference to the caller’s structure, the caller variable reflects all changes in the function. You do not have to return the structure to the caller. After the function returns, the calling page accesses the changed data by using the structure variable that it passed to the function.

If you do not want a function to modify the caller’s copy of a structure, query, or object, use the Duplicate function to make a copy and pass the copy to the function.

Passing arrays

If you want your function to modify the caller’s copy of the array, the simplest solution is to pass the array to the function and return the changed array to the caller in the function return statement. In the caller, use the same variable name in the function argument and return variable.

The following example shows how to directly pass and return arrays. In this example, the doubleOneDArray function doubles the value of each element in a one-dimensional array.

<cfscript>
//Initialize some variables
//This creates a simple array.
a=ArrayNew(1);
a[1]=2;
a[2]=22;
//Define the function.
function doubleOneDArray(OneDArray) {
    var i = 0;
    for ( i = 1; i LE arrayLen(OneDArray); i = i + 1)
        { OneDArray[i] = OneDArray[i] * 2; }
    return OneDArray;
}
//Call the function.
a = doubleOneDArray(a);
</cfscript>
<cfdump var="#a#">

This solution is simple, but it is not always optimal:

  • This technique requires ColdFusion to copy the entire array twice, once when you call the function and once when the function returns. This is inefficient for large arrays and can reduce performance, particularly if the function is called frequently.
  • You can use the return value for other purposes, such as a status variable.

If you do not use the return statement to return the array to the caller, you can pass the array as an element in a structure and change the array values inside the structure. Then the calling page can access the changed data by using the structure variable it passed to the UDF.

The following code shows how to rewrite the previous example using an array in a structure. It returns True as a status indicator to the calling page and uses the structure to pass the array data back to the calling page.

<cfscript>
//Initialize some variables.
//This creates an simple array as an element in a structure.
arrayStruct=StructNew();
arrayStruct.Array=ArrayNew(1);
arrayStruct.Array[1]=2;
arrayStruct.Array[2]=22;
//Define the function.
function doubleOneDArrayS(OneDArrayStruct) {
    var i = 0;
    for ( i = 1; i LE arrayLen(OneDArrayStruct.Array); i = i + 1)
        { OneDArrayStruct.Array[i] = OneDArrayStruct.Array[i] * 2; }
    return True;
}
//Call the function.
Status = doubleOneDArrayS(arrayStruct);
WriteOutput("Status: " & Status);
</cfscript>
</br>
<cfdump var="#arrayStruct#">

You must use the same structure element name for the array (in this case Array) in the calling page and the function.

About the Arguments scope

All function arguments exist in their own scope, the Arguments scope.

The Arguments scope exists for the life of a function call. When the function returns, the scope and its variables are destroyed.

However, destroying the Argument scope does not destroy variables, such as structures or query objects, that ColdFusion passes to the function by reference. The variables on the calling page that you use as function arguments continue to exist; if the function changes the argument value, the variable in the calling page reflects the changed value.

The Arguments scope is special, in that you can treat the scope as either an array or a structure. This dual nature of the Arguments scope is useful because it makes it easy to use arguments in any of the following circumstances:

  • You define the function using CFScript.
  • You define the function using the cffunction tag.
  • You pass arguments using argument name=value format.
  • You pass arguments as values only.
  • The function takes optional, undeclared arguments.

The following sections describe the general rules for using the Arguments scope as an array and a structure. For more information on using the Arguments scope in functions defined using CFScript, see Using the Arguments scope in CFScript. For more information on using the Arguments scope in functions defined using the cffunction tag, see Using the Arguments scope in cffunction definitions.

The contents of the Arguments scope

The following rules apply to the Arguments scope and its contents:

  • The scope contains all the arguments passed into a function.
  • If you use cffunction to define the function, the scope always contains an entry "slot" for each declared argument, even if you do not pass the argument to the function when you call it. If you do not pass a declared (optional) argument, the scope entry for that argument is empty.

    When you call a function that you defined using CFScript, you must pass the function a value for each argument declared in the function definition. Therefore, the Arguments scope for a CFScript call does not have empty slots.

The following example shows these rules. Assume that you have a function declared, as follows:

<cffunction name="TestFunction">
    <cfargument name="Arg1" >
    <cfargument name="Arg2">
</cffunction>

You can call this function with a single argument, as in the following line:

<cfset TestFunction(1)>

The resulting Arguments scope looks like the following:

As an array |  | As a structure
Entry | Value | Entry | Value
1 | 1 | Arg1 | 1
2 | undefined | Arg2 | undefined

In this example, the following functions return the value 2 because there are two defined arguments:

ArrayLen(Arguments)
StructCount(Arguments)

However, the following tests return the value False, because the contents of the second element in the Arguments scope is undefined.

Isdefined("Arguments.Arg2")
testArg2 = Arguments[2]>
Isdefined("testArg2")

Note: The IsDefined function does not test the existence of array elements. Instead, put any code that might try to access an undefined array element in a try block and use a catch block to handle exceptions that arise if elements do not exist.

Using the Arguments scope as an array

The following rules apply to referencing Arguments scope as an array:

  • If you call the function using unnamed arguments, the array index is the position of the argument in the function call.
  • If you use names to pass the arguments, the array indexes correspond to the order in which the arguments are declared in the function definition.
  • If you use names to pass arguments, and do not pass all the arguments defined in the function, the Arguments array has an empty entry at the index corresponding to the argument that was not passed. This rule applies only to functions created using the cffunction tag.
  • If you use a name to pass an optional argument that is not declared in the function definition, the array index of the argument is the sum of the following:
    1. The number of arguments defined with names in the function.
    2. The position of the optional argument among the arguments passed in that do not have names defined in the function.

    However, using argument names in this manner is not good programming practice because you cannot ensure that you always use the same optional argument names when calling the function.

To demonstrate these rules, define a simple function that displays the contents of its Arguments array and call the function with various argument combinations, as shown in the following example:

<cffunction name="TestFunction" >
    <cfargument name="Arg1">
    <cfargument name="Arg2">
    <cfloop index="i" from="1" to="#ArrayLen(Arguments)#">
        <cfoutput>Argument #i#: #Arguments[i]#<br></cfoutput>
    </cfloop>
</cffunction>

<strong>One Unnamed argument</strong><br>
<cfset TestFunction(1)>
<strong>Two Unnamed arguments</strong><br>
<cfset TestFunction(1, 2)>
<strong>Three Unnamed arguments</strong><br>
<cfset TestFunction(1, 2, 3)>
<strong>Arg1:</strong><br>
<cfset TestFunction(Arg1=8)>
<strong>Arg2:</strong><br>
<cfset TestFunction(Arg2=9)>
<strong>Arg1=8, Arg2=9:</strong><br>
<cfset TestFunction(Arg1=8, Arg2=9)>
<strong>Arg2=6, Arg1=7</strong><br>
<cfset TestFunction(Arg2=6, Arg1=7)>
<strong>Arg1=8, Arg2=9, Arg3=10:</strong><br>
<cfset TestFunction(Arg1=8, Arg2=9, Arg3=10)>
<strong>Arg2=6, Arg3=99, Arg1=7</strong><br>
<cfset TestFunction(Arg2=6, Arg3=99, Arg1=7)>

Note: Although you can use the Arguments scope as an array, the IsArray(Arguments) function always returns false and the cfdump tag displays the scope as a structure.

Using the Arguments scope as a structure

The following rule applies when referencing Arguments scope as a structure:

  • Use the argument names as structure keys. For example, if your function definition includes a Principal argument, refer to the argument as Arguments.Principal.

The following rules are also true, but avoid writing code that uses them. To ensure program clarity, only use the Arguments structure for arguments that you name in the function definition. Use the Arguments scope as an array for optional arguments that you do not declare in the function definition.

  • If the function can take unnamed optional arguments, use array notation to reference the unnamed arguments. For example, if the function declaration includes two named arguments and you call the function with three arguments, refer to the third argument as Arguments[3]. To determine if an unnamed optional argument exists, use the StructKeyExists function; for example, structKeyExists(Arguments,"3").
  • If you do not name an optional argument in the function definition, but do use a name for it in the function call, use the name specified in the function call For example, if you have an unnamed optional argument and call the function using the name myOptArg for the argument, you can refer to the argument as Arguments.myOptArg in the function body. This usage, however, is poor programming practice, as it makes the function definition contents depend on variable names in the code that calls the function.

Using the Arguments scope in CFScript

A function can have optional arguments that you do not have to specify when you call the function. To determine the number of arguments passed to the function, use the following function:

ArrayLen(Arguments)

When you define a function using CFScript, the function must use the Arguments scope to retrieve the optional arguments. For example, the following SumN function adds two or more numbers together. It requires two arguments and supports any number of additional optional arguments. You can refer to the first two, required, arguments as Arg1 and Arg2 or as Arguments[1] and Arguments[2]. You must refer to the third, fourth, and any additional optional arguments as Arguments[3], Arguments[4], and so on.

function SumN(Arg1,Arg2) {
    var arg_count = ArrayLen(Arguments);
    var sum = 0;
    var i = 0;
    for( i = 1 ; i LTE arg_count; i = i + 1 )
    {
        sum = sum + Arguments[i];
    }
    return sum;
}

With this function, any of the following function calls are valid:

SumN(Value1, Value2)
SumN(Value1, Value2, Value3)
SumN(Value1, Value2, Value3, Value4)

and so on.

The code never uses the Arg1 and Arg2 argument variables directly, because their values are always the first two elements in the Arguments array and it is simpler to step through the array. Specifying Arg1 and Arg2 in the function definition ensures that ColdFusion generates an error if you pass the function one or no arguments.

Note: Avoid referring to a required argument in the body of a function by both the argument name and its place in the Arguments scope array or structure, as this can be confusing and makes it easier to introduce errors.

For more information on the Arguments scope, see About the Arguments scope.

Using the Arguments scope in cffunction definitions

When you define a function using the cffunction tag, you generally refer to the arguments directly by name if all arguments are named in the cfargument tags. If you do use the Arguments scope identifier, follow the rules listed in About the Arguments scope.


Function-only variables

In addition to the Arguments scope, each function can have a number of variables that exist only inside the function, and are not saved between times the function gets called. As soon as the function exits, all the variables in this scope are removed.

In CFScript, you create function-only variables with the var statement. Unlike other variables, you never prefix function-only variables with a scope name.

Using function-only variables

Make sure to use the var statement in CFScript UDFs to declare all function-specific variables, such as loop indexes and temporary variables that are required only for the duration of the function call. Doing this ensures that these variables are available inside the function only, and makes sure that the variable names do not conflict with the names of variables in other scopes. If the calling page has variables of the same name, the two variables are independent and do not affect each other.

For example, if a ColdFusion page has a cfloop tag with an index variable i, and the tag body calls a CFScript UDF that also has a loop with a function-only index variable i, the UDF does not change the value of the calling page loop index, and the calling page does not change the UDF index. So you can safely call the function inside the cfloop tag body.

In general, use the var statement to declare all UDF variables, other than the function arguments or shared-scope variables, that you use only inside CFScript functions. Use another scope, however, if the value of the variable must persist between function calls; for example, for a counter that the function increments each time it is called.


Referencing caller variables

A function can use and change any variable that is available in the calling page, including variables in the caller’s Variables (local) scope, as if the function was part of the calling page. For example, if you know that the calling page has a local variable called Customer_name (and there is no function scope variable named Customer_name) the function can read and change the variable by referring to it as Customer_name or (using better coding practice) Variables.Customer_name. Similarly, you can create a local variable inside a function and then refer to it anywhere in the calling page after the function call. You cannot refer to the variable before you call the function.

However, you should generally avoid using the caller’s variables directly inside a function. Using the caller’s variables creates a dependency on the caller. You must always ensure that the code outside the function uses the same variable names as the function. This can become difficult if you call the function from many pages.

You can avoid these problems by using only the function arguments and the return value to pass data between the caller and the function. Do not reference calling page variables directly in the function. As a result, you can use the function anywhere in an application (or even in multiple applications), without concern for the calling code’s variables.

As with many programming practice, there are valid exceptions to this recommendation. For example you might do any of the following:

  • Use a shared scope variable, such as an Application or Session scope counter variable.
  • Use the Request scope to store variables used in the function, as shown in Using the Request scope for static variables and constants.).
  • Create context-specific functions that work directly with caller data if you always synchronize variable names.

Note: If your function must directly change a simple variable in the caller (one that is not passed to the function by reference), you can place the variable inside a structure argument.


Using arguments

Function arguments can have the same names, but different values, as variables in the caller. Avoid such uses for clarity, however.

The following rules apply to argument persistence:

  • Because simple variable and array arguments are passed by value, their names and values exist only while the function executes.
  • Because structures, queries, and objects such as COM objects are passed by reference, the argument name exists only while the function executes, but the underlying data persists after the function returns and can be accessed by using the caller’s variable name. The caller’s variable name and the argument name can, and should, be different.

Note: If a function must use a variable from another scope that has the same name as a function-only variable, prefix the external variable with its scope identifier, such as Variables or Form. (However, remember that using variables from other scopes directly in your code is often poor practice.)


Handling errors in UDFs

This section discusses the following topics:

  • Displaying error messages directly in the function
  • Returning function status information to the calling page
  • Using try/catch or cftry/cfcatch blocks and the cfthrow and cfrethrow tags to handle and generate exceptions

The technique you use depends on the circumstances of your function and application and on your preferred programming style. However, most functions should use the second or third technique, or a combination of the two. The following sections discuss the uses, advantages, and disadvantages of each technique, and provide examples of their use.

  • Displaying error messages
  • Providing status information
  • Using exceptions

Displaying error messages

Your function can test for errors and use the WriteOutput function to display an error message directly to the user. This method is particularly useful for providing immediate feedback to users for simple input errors. You can use it independently or in conjunction with either of the other two error-handling methods.

For example, the following variation on a "Hello world" function displays an error message if you do not enter a name in the form:

<cfform method="POST" action="#CGI.script_name#">
    <p>Enter your Name:&nbsp;
    <input name="name" type="text" hspace="30" maxlength="30">
    <input type="Submit" name="submit" value="OK">
</cfform>
<cfscript>
    function HelloFriend(Name) {
        if (Name is "") WriteOutput("You forgot your name!");
        else WriteOutput("Hello " & name &"!");
        return "";
    }
    if (IsDefined("Form.submit")) HelloFriend(Form.name);
</cfscript>

Reviewing the code

The following table describes the code:

Code

Description

<cfform method="POST" action="#CGI.script_name#">
    <p>Enter your Name:&nbsp;
    <input name="name" type="text" hspace="30"
        maxlength="30">
    <input type="Submit" name="submit" value="OK">
</cfform>

Creates a simple form requesting you to enter your name.

Uses the script_name CGI variable to post to this page without specifying a URL.

If you do not enter a name, the form posts an empty string as the name field.

<cfscript>
    function HelloFriend(Name) {
        if (Name is "") WriteOutput("You forgot your
            name!");
        else WriteOutput("Hello " & name &"!");
        return "";
    }
    if (IsDefined("Form.submit"))
        HelloFriend(Form.name);
</cfscript>

Defines a function to display "Hello name!" First, checks whether the argument is an empty string. If so, displays an error message.

Otherwise displays the hello message.

Returns the empty string. (The caller does not use the return value). It is not necessary to use curly braces around the if or else statement bodies because they are single statements.

If this page has been called by submitting the form, calls the HelloFriend function. Otherwise, the page just displays the form.

Providing status information

In some cases, such as those where the function cannot provide a corrective action, the function cannot, or should not, handle the error directly. In these cases, your function can return information to the calling page. The calling page must handle the error information and act appropriately.

Consider the following mechanisms for providing status information:

  • Use the return value to indicate the function status only. The return value can be a Boolean success/failure indicator. The return value can also be a status code, for example where 1 indicates success, and various failure types are assigned known numbers. With this method, the function must set a variable in the caller to the value of a successful result.
  • Set a status variable that is available to the caller (not the return variable) to indicate success or failure and any information about the failure. With this method, the function can return the result directly to the caller. In this method, the function should use only the return value and structure arguments to pass the status back to the caller.

Each of these methods can have variants, and each has advantages and disadvantages. The technique that you use should depend on the type of function, the application in which you use it, and your coding style.

The following example, which modifies the function used in A user-defined function example, uses one version of the status variable method. It provides two forms of error information:

  • It returns -1, instead of an interest value, if it encounters an error. This value can serve as an error indicator because you never pay negative interest on a loan.
  • It also writes an error message to a structure that contains an error description variable. Because the message is in a structure, it is available to both the calling page and the function.

The TotalInterest function

After changes to handle errors, the TotalInterest function looks like the following. Code that is changed from the example in A user-defined function example is in bold.

<cfscript>
function TotalInterest(principal, annualPercent, months, status) {
    Var years = 0;
    Var interestRate = 0;
    Var totalInterest = 0;
    principal = trim(principal);
    principal = REReplace(principal,"[\$,]","","ALL");
    annualPercent = Replace(annualPercent,"%","","ALL");
    if ((principal LE 0) OR (annualPercent LE 0) OR (months LE 0)) {
        Status.errorMsg = "All values must be greater than 0";
        Return -1;
    }
    interestRate = annualPercent / 100;
    years = months / 12;
    totalInterest = principal*(((1+ interestRate)^years)-1);
    Return DollarFormat(totalInterest);
}
</cfscript>

Reviewing the code

The following table describes the code that has been changed or added to the previous version of this example. For a description of the initial code, see A user-defined function example.

Code

Description

function TotalInterest(principal,
    annualPercent, months, status)

The function now takes an additional argument, a status structure. Uses a structure for the status variable so that changes that the function makes affect the status structure in the caller.

if ((principal LE 0) OR
    (annualPercent LE 0) OR
    (months LE 0)) {
    Status.errorMsg = "All values
        must be greater than 0";
    Return -1;
}

Checks to make sure the principal, percent rate, and duration are all greater than zero.

If any is not, sets the errorMsg key (the only key) in the Status structure to a descriptive string. Also, returns -1 to the caller and exits the function without processing further.

Calling the function

The code that calls the function now looks like the following. Code that is changed from the example in A user-defined function example is in bold.

<cfset status = StructNew()>
<cfset myInterest = TotalInterest(Form.Principal,
    Form.AnnualPercent,Form.Months, status)>
<cfif myInterest EQ -1>
    <cfoutput>
        ERROR: #status.errorMsg#<br>
    </cfoutput>
<cfelse>
    <cfoutput>
        Loan amount: #Form.Principal#<br>
        Annual percentage rate:
            #Form.AnnualPercent#<br>
        Loan duration: #Form.Months# months<br>
        TOTAL INTEREST: #myInterest#<br>
    </cfoutput>
</cfif>

Reviewing the code

The following table describes the code that has been changed or added:

Code

Description

<cfset status = StructNew()>

Creates a structure to hold the function status.

<cfset myInterest = TotalInterest
    (Form.Principal, Form.AnnualPercent,
    Form.Months, status)>

Calls the function. This time, the function requires four arguments, including the status variable.

<cfif myInterest EQ -1>
    <cfoutput>
        ERROR: #status.errorMsg#<br>
    </cfoutput>

If the function returns -1, there must be an error. Displays the message that the function placed in the status.errorMsg structure key.

<cfelse>
    <cfoutput>
        Loan amount: #Form.Principal#<br>
        Annual percentage rate:
            #Form.AnnualPercent#<br>
        Loan duration: #Form.Months# months<br>
        TOTAL INTEREST: #myInterst#<br>
    </cfoutput>
</cfif>

If the function does not return -1, it returns an interest value. Displays the input values and the function return value.


Using exceptions

UDFs written in CFScript can handle exceptions using the try and catch statements. UDFs written using the cffunction tag can use the cftry, cfcatch, cfthrow, and cfrethrow tags. Using exceptions corresponds to the way many functions in other programming languages handle errors, and can be an effective way to handle errors. In particular, it separates the functional code from the error-handling code, and it can be more efficient than other methods at runtime, because it does not require testing and branching.

Exceptions in UDFs have the following two dimensions:

  • Handling exceptions generated by running the UDF code
  • Generating exceptions when the UDF identifies invalid data or other conditions that would cause errors if processing continued

Handling exceptions in UDFs

A UDF should use try/catch blocks to handle exceptions in the same conditions that any other ColdFusion application uses try/catch blocks. These are typically circumstances where the function uses an external resource, such as a Java, COM, or CORBA object, a database, or a file. When possible, your application should prevent, rather than catch, exceptions caused by invalid application data. For example, the application should prevent users from entering a zero value for a form field that is used to divide another number, rather than handling exceptions generated by dividing by zero.

When ColdFusion catches an exception, the function can use any of the following methods to handle the exception:

  • If the error is recoverable (for example, if the problem is a database timeout where a retry might resolve the issue), try to recover from the problem.
  • Display a message, as described in Displaying error messages.
  • Return an error status, as described in Providing status information.
  • If the UDF is defined using the cffunction tag, throw a custom exception, or rethrow the exception so that it will be caught by the calling ColdFusion page. For more information on throwing and rethrowing exceptions, see Handling runtime exceptions with ColdFusion tags.

Generating exceptions in UDFs

If you define your function using the cffunction tag, you can use the cfthrow and cfrethrow tags to throw errors to the page that called the function. You can use this technique whenever your UDF identifies an error, instead of displaying a message or returning an error status. For example, the following code rewrites the example from Providing status information to use the cffunction tag and CFML, and to throw and handle an exception if any of the form values are not positive numbers.

The lines that identify invalid data and throw the exception are in bold. The remaining lines are equivalent to the CFScript code in the previous example. However, the code that removes unwanted characters must precede the error checking code.

<cffunction name="TotalInterest">
    <cfargument name="principal" required="Yes">
    <cfargument name="annualPercent" required="Yes">
    <cfargument name="months" required="Yes">
    <cfset var years = 0>
    <cfset var interestRate = 0>
    <cfset var totalInterest = 0>

    <cfset principal = trim(principal)>
    <cfset principal = REReplace(principal,"[\$,]","","ALL")>
    <cfset annualPercent = Replace(annualPercent,"%","","ALL")>

    <cfif ((principal LE 0) OR (annualPercent LE 0) OR (months LE 0))>
        <cfthrow type="InvalidData" message="All values must be greater than 0.">
    </cfif>

    <cfset interestRate = annualPercent / 100>
    <cfset years = months / 12>
    <cfset totalInterest = principal*
            (((1+ interestRate)^years)-1)>
    <cfreturn DollarFormat(totalInterest)>
</cffunction>

The code that calls the function and handles the exception looks like the following. The changed lines are in bold.

<cftry>
    <cfset status = StructNew()>
    <cfset myInterest = TotalInterest(Form.Principal, Form.AnnualPercent,
        Form.Months, status)>
    <cfoutput>
        Loan amount: #Form.Principal#<br>
        Annual percentage rate: #Form.AnnualPercent#<br>
        Loan duration: #Form.Months# months<br>
        TOTAL INTEREST: #myInterest#<br>
    </cfoutput>
<cfcatch type="InvalidData">
    <cfoutput>
        #cfcatch.message#<br>
    </cfoutput>
</cfcatch>

</cftry>


A user-defined function example

The following simple function takes a principal amount, an annual percentage rate, and a loan duration in months and returns the total amount of interest to be paid over the period. You can optionally use the percent sign for the percentage rate, and include the dollar sign and comma separators for the principal amount.

You could use the TotalInterest function in a cfoutput tag of a form’s action page, as follows:

<cfoutput>
    Loan amount: #Form.Principal#<br>
    Annual percentage rate: #Form.AnnualPercent#<br>
    Loan duration: #Form.Months# months<br>
    TOTAL INTEREST: #TotalInterest(Form.Principal, Form.AnnualPercent,
        Form.Months)#<br>
</cfoutput>

Defining the function using CFScript

<cfscript>
function TotalInterest(principal, annualPercent, months) {
    Var years = 0;
    Var interestRate = 0;
    Var totalInterest = 0;
    principal = trim(principal);
    principal = REReplace(principal,"[\$,]","","ALL");
    annualPercent = Replace(annualPercent,"%","","ALL");
    interestRate = annualPercent / 100;
    years = months / 12;
    totalInterest = principal*(((1+ interestRate)^years)-1);
    Return DollarFormat(totalInterest);
}
</cfscript>

Reviewing the code

The following table describes the code:

Code

Description

function TotalInterest(principal, annualPercent,
    months) {

Starts the TotalInterest function definition. Requires three variables: the principal amount, the annual percentage rate, and the loan duration in months.

Var years = 0;
Var interestRate = 0;
Var totalInterest = 0;

Declares intermediate variables used in the function and initializes them to 0. All var statements must precede the rest of the function code.

principal = trim(principal);
principal = REReplace(principal,"[\$,]","","ALL");
annualPercent =
    Replace(annualPercent,"%","","ALL");
interestRate = annualPercent / 100;
years = months / 12;

Removes any leading or trailing spaces from the principal argument. Removes any dollar sign ($) and comma (,) characters from the principal argument to get a numeric value.

Removes any percent (%) character from the annualPercent argument to get a numeric value, then divides the percentage value by 100 to get the interest rate.

Converts the loan from months to years.

    totalInterest = principal*(((1+ interestRate)^years)-1);
    Return DollarFormat(totalInterest);
}

Calculates the total amount of interest due. It is possible to calculate the value in the Return statement, but this example uses an intermediate totalInterest variable to make the code easier to read. Returns the result formatted as a US currency string.

Ends the function definition.

Defining the function using the cffunction tag

The following code replaces CFScript statements with their equivalent CFML tags.

<cffunction name="TotalInterest">
    <cfargument name="principal" required="Yes">
    <cfargument name="annualPercent" required="Yes">
    <cfargument name="months" required="Yes">
    <cfset var years = 0>
    <cfset var interestRate = 0>
    <cfset var totalInterest = 0>
    <cfset principal = trim(principal)>
    <cfset principal = REReplace(principal,"[\$,]","","ALL")>
    <cfset annualPercent = Replace(annualPercent,"%","","ALL")>
    <cfset interestRate = annualPercent / 100>
    <cfset years = months / 12>
    <cfset totalInterest = principal*
            (((1+ interestRate)^years)-1)>
    <cfreturn DollarFormat(totalInterest)>
</cffunction>


Using UDFs effectively

This section provides information that will help you use user-defined functions more effectively.

Using functions in ColdFusion component

In many cases, the most effective use of UDFs is within a CFC. For more information on CFCs, see Building and Using ColdFusion Components.

  • Using Application.cfm and function include files
  • Specifying the scope of a function
  • Using function names as function arguments
  • Handling query results using UDFs
  • Identifying and checking for UDFs
  • Using the Evaluate function
  • Using recursion

Using Application.cfm and function include files

Consider the following techniques for making your functions available to your ColdFusion pages:

  • If you consistently call a small number of UDFs, consider putting their definitions on the Application.cfm page.
  • If you call UDFs in only a few of your application pages, do not include their definitions in Application.cfm.
  • If you use many UDFs, put their definitions on one or more ColdFusion pages that contain only UDFs. You can include the UDF definition page in any page that calls the UDFs.

The next section describes other techniques for making UDFs available to your ColdFusion pages.


Specifying the scope of a function

User-defined function names are essentially ColdFusion variables. ColdFusion variables are names for data. Function names are names (references) for segments of CFML code. Therefore, like variables, functions belong to scopes.

About functions and scopes

Like ColdFusion variables, UDFs exist in a scope:

  • When you define a UDF, ColdFusion puts it in the Variables scope.
  • You can assign a UDF to a scope the same way you assign a variable to a scope, by assigning the function to a name in the new scope. For example, the following line assigns the MyFunc UDF to the Request scope:
    <cfset Request.MyFunc = Variables.MyFunc>

    You can now use the function from any page in the Request scope by calling Request.MyFunc.

Selecting a function scope

The following table describes the advantages and disadvantages of scopes that you might considering using for your functions:

Scope | Considerations
Application | Makes the function available across all invocations of the application. Access to UDFs in Application scope is multithreaded and you can execute multiple copies of the UDF at one time.
Request | Makes the function available for the life of the current HTTP request, including in all custom tags and nested custom tags. This scope is useful if a function is used in a page and in the custom tags it calls, or in nested custom tags.
Server | Makes the function available to all pages on a single server. In most cases, this scope is not a good choice because in clustered systems, it only makes the function available on a single server, and all code that uses the function must be inside a cflock block.
Session | Makes the function available to all pages during the current user session. This scope has no significant advantages over the Application scope.

Using the Request scope

You can effectively manage functions that are used in application pages and custom tags by doing the following:

  1. Define the functions on a function definitions page.
  2. On the functions page, assign the functions to the request scope.
  3. Use a cfinclude tag to include the function definition page on the application page, but do not include it on any custom tag pages.
  4. Always call the functions using the request scope.

This way you only need to include the functions once per request and they are available throughout the life of the request. For example, create a myFuncs.cfm page that defines your functions and assigns them to the Request scope using syntax such as the following:

function MyFunc1(Argument1, Argument2)
{ Function definition goes here }
Request.MyFunc1 = MyFunc1

The application page includes the myFuncs.cfm page:

<cfinclude template="myfuncs.cfm">

The application page and all custom tags (and nested custom tags) call the functions as follows:

Request.MyFunc1(Value1, Value2)

Using the Request scope for static variables and constants

This section describes how to partially break the rule described in the section Referencing caller variables. Here, the function defines variables in the Request scope. However, it is a specific solution to a specific issue, where the following circumstances exist:

  • Your function initializes a large number of variables.
  • The variables have either of the following characteristics:
    • They must be static: they are used only in the function, the function can change their values, and their values must persist from one invocation of the function to the next.
    • They are named constants; that is the variable value never changes.
  • Your application page (and any custom tags) calls the function multiple times.
  • You can assure that the variable names are used only by the function.

In these circumstances, you can improve efficiency and save processing time by defining your function’s variables in the Request scope, rather than the Function scope. The function tests for the Request scope variables and initializes them if they do not exist. In subsequent calls, the variables exist and the function does not reset them.

The NumberAsString function, written by Ben Forta and available from www.cflib.org, takes advantage of this technique.


Using function names as function arguments

Because function names are ColdFusion variables, you can pass a function’s name as an argument to another function. This technique allows a function to use another function as a component. For example, a calling page can call a calculation function, and pass it the name of a function that does some subroutine of the overall function.

This way, the calling page could use a single function for different specific calculations, such as calculating different forms of interest. The initial function provides the framework, while the function whose name is passed to it can implement a specific algorithm that is required by the calling page.

The following simple example shows this use. The binop function is a generalized function that takes the name of a function that performs a specific binary operation and two operands. The binop function simply calls the specified function and passes it the operands. This code defines a single operation function, the sum function. A more complete implementation would define multiple binary operations.

<cfscript>
function binop(operation, operand1, operand2)
{ return (operation(operand1, operand2)); }
function sum(addend1, addend2)
{ return addend1 + addend2;}
x = binop(sum, 3, 5);
writeoutput(x);
</cfscript>


Handling query results using UDFs

When you call a UDF in the body of a tag that has a query attribute, such as a cfloop query=... tag, any function argument that is a query column name passes a single element of the column, not the entire column. Therefore, the function must manipulate a single query element.

For example, the following code defines a function to combine a single first name and last name to make a full name. It queries the cfdocexamples database to get the first and last names of all employees, and then it uses a cfoutput tag to loop through the query and call the function on each row in the query.

<cfscript>
function FullName(aFirstName, aLastName)
 { return aFirstName & " " & aLastName; }
</cfscript>

<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT FirstName, LastName
    FROM Employee
</cfquery>

<cfoutput query="GetEmployees">
#FullName(FirstName, LastName)#<br>
</cfoutput>

You generally use functions that manipulate many rows of a query outside tags that loop over queries. Pass the query to the function and loop over it inside the function. For example, the following function changes text in a query column to uppercase. It takes a query name as an argument.

function UCaseColumn(myquery, colName) {
    var currentRow = 1;
    for (; currentRow lte myquery.RecordCount;
        currentRow = currentRow + 1)
    {
        myquery[colName][currentRow] =
            UCase(myquery[colName][currentRow]);
    }
    Return "";
}

The following code uses a script that calls the UCaseColumn function to convert all the last names in the GetEmployees query to uppercase. It then uses cfoutput to loop over the query and display the contents of the column.

<cfscript>
    UCaseColumn(GetEmployees, "LastName");
</cfscript>
<cfoutput query="GetEmployees">
    #LastName#<br>
</cfoutput>


Identifying and checking for UDFs

You can use the IsCustomFunction function to determine whether a name represents a UDF. The IsCustomFunction function generates an error if its argument does not exist. As a result, you must ensure that the name exists before calling the function, for example, by calling the IsDefined function. The following code shows this use:

<cfscript>
if(IsDefined("MyFunc"))
    if(IsCustomFunction(MyFunc))
        WriteOutput("MyFunc is a user-defined function");
    else
        WriteOutput("Myfunc is defined but is NOT a user-defined function");
else
    WriteOutput("MyFunc is not defined");
</cfscript>

You do not surround the argument to IsCustomFunction in quotation marks, so you can use this function to determine if function arguments are themselves functions.


Using the Evaluate function

If your user-defined function uses the Evaluate function on arguments that contain strings, you must make sure that all variable names you use as arguments include the scope identifier. Doing so avoids conflicts with function-only variables.

The following example returns the result of evaluating its argument. It produces the expected results, the value of the argument, if you pass the argument using its fully scoped name, Variables.myname. However, the function returns the value of the function local variable if you pass the argument as myname, without the Variables scope identifier.

<cfscript>
    myname = "globalName";
    function readname(name) {
        var myname = "localName";
        return (Evaluate(name));
    }
</cfscript>

<cfoutput>
<!--- This one collides with local variable name. --->
    The result of calling readname with myname is:
            #readname("myname")# <br>
<!--- This one finds the name passed in. --->
    The result of calling readname with Variables.myname is:
        #readname("Variables.myname")#
</cfoutput>


Using recursion

A recursive function is a function that calls itself. Recursive functions are useful when a problem can be solved by an algorithm that repeats the same operation multiple times using the results of the preceding repetition. Factorial calculation, used in the following example, is one case where recursion is useful. The Towers of Hanoi game is also solved using a recursive algorithm.

A recursive function, like looping code, must have an end condition that always stops the function. Otherwise, the function will continue until a system error occurs or you stop the ColdFusion server.

The following example calculates the factorial of a number, that is, the product of all the integers from 1 through the number; for example, 4 factorial is 4 X 3 X 2 X 1 = 24.

function Factorial(factor) {
    If (factor LTE 1)
        return 1;
    else
        return factor * Factorial(factor -1);
}

If the function is called with a number greater than 1, it calls itself using an argument one less than it received. It multiplies that result by the original argument, and returns the result. Therefore, the function keeps calling itself until the factor is reduced to 1. The final recursive call returns 1, and the preceding call returns 2 * 1, and so on until all the initial call returns the end result.

Caution: If a recursive function calls itself too many times, it causes a stack overflow. Always test any recursive functions under conditions that are likely to cause the maximum number of recursions to ensure that they do not cause a stack overflow.
Previous


Building and Using ColdFusion Components

This chapter describes Macromedia ColdFusion component (CFC) concepts and elements and tells you how to create and use CFCs. It provides you with all the tools to create and use CFCs; however, it does not discuss CFC methodologies or provide information on designing applications for CFC use. For more information on creating applications that use CFCs, see the Macromedia website: www.macromedia.com.

Contents

About ColdFusion components

Creating ColdFusion components

Using ColdFusion components

Passing parameters to methods

Using CFCs effectively

ColdFusion component example
Next


About ColdFusion components

A ColdFusion component (CFC) is a file saved with the extension .cfc. A CFC can contain data and functions. Within a CFC, data is referred to as properties. Although you use the cffunction tag to define functions within a CFC, they are typically referred to as methods instead of functions.

The page on which you define a CFC is also known as a component page. Component pages use the same tags and functions that regular CFML pages do, plus a small number of special tags (in particular, the cfcomponent tag) and tag attributes.

You define related methods in a CFC. Unlike ColdFusion custom tags, a single CFC can perform many related actions, defined in multiple methods. The methods may share a data context, such as metadata and scoping, or manage a particular database or set of tables. For example, you can define the methods to insert, update, delete, and retrieve records from a particular database or table in one CFC.

This section describes the following topics:

  • CFCs and object-oriented programming
  • When to use CFCs


CFCs and object-oriented programming

CFCs are building blocks that let you develop ColdFusion code in an object-oriented manner, although CFCs do not require you to do object-oriented programming. Some of the object-oriented features of CFCs include encapsulation, inheritance, and introspection. CFC object-oriented features are similar to the object-oriented elements in other languages, like JavaScript.

The technique of incorporating both code and data into one object such as a CFC is known as encapsulation. Encapsulation lets users pass data to and get a result from your CFC without having to understand the underlying code. When you use encapsulation, you can validate data that is passed to the CFC. CFCs can also enforce data types, check for required parameters, and optionally assign default values.

One CFC can inherit the methods and properties of another CFC. Inheritance lets you build multiple specific components without rewriting the code for the basic building blocks of the components. For more information, see Using inheritance and the Super keyword.

CFCs support introspection; that is, they can provide information about themselves. If you display a component page directly in an HTML browser, inspect it in the ColdFusion and Macromedia Dreamweaver MX component browsers, or use the CFML GetMetadata function, you see information about the component. This information includes its path, property, methods, and additional information that you can specify using special documentation attributes and tags. For more information, see Using introspection to get information about components

When you use a ColdFusion component, you can simply invoke a method in the CFC. However, typically, you create an instance of the CFC, and then invoke methods and refer to properties of the CFC.


When to use CFCs

This section describes the ways in which you can use CFCs:

  • Developing structured, reusable code
  • Creating web services
  • Creating Macromedia Flash Remoting elements
  • Using asynchronous CFCs

Developing structured, reusable code

CFCs provide an excellent method for developing structured applications that separate display elements from logical elements and encapsulate database queries. You can use CFCs to create application functionality that you (and others) can reuse wherever needed, similar to user-defined functions (UDFs) and custom tags. If you want to modify, add, or remove component functionality, you make changes in only one component file.

CFCs have several advantages over UDFs and custom tags. These advantages, which CFCs automatically provide, include all of the following:

  • The ability to group related methods into a single component, and to group related components into a package
  • Properties that multiple methods can share
  • The This scope, a component-specific scope
  • Inheritance of component methods and properties from a base component, including the use of the Super keyword
  • Access control
  • Introspection for CFC methods, properties, and metadata

CFCs have one characteristic that prevents them from being the automatic choice for all code reuse. It takes relatively more processing time to instantiate a CFC than to process a custom tag. In turn, it takes substantially more time to process a custom tag than to execute a user-defined function (UDF). However, after a CFC is instantiated, calling a CFC method has about the same processing overhead as an equivalent UDF. As a result, you should not use CFCs in place of independent, single-purpose custom tags or UDFs. Instead, you should use CFCs to create bodies of related methods, particularly methods that share properties.

For more information about UDFs, custom tags, and other ColdFusion code reuse techniques, see Creating ColdFusion Elements.

Creating web services

ColdFusion MX 7 can automatically publish CFC methods as web services. To publish a CFC method as a web service, you specify the access="remote" attribute in the method’s cffunction tag. ColdFusion generates all the required Web Services Description Language (WSDL) code and exports the CFC methods. For more information on creating web services in ColdFusion, see Using Web Services.

Creating Macromedia Flash Remoting elements

Flash applications that use Flash Remoting MX can easily take advantage of ColdFusion components for business logic. In a CFC, the cffunction tag names the function and contains the application logic, and the cfreturn tag returns the result to Flash.

Note: For ColdFusion component methods to communicate with Flash applications, you must set the access attribute of the cffunction tag to remote.

For more information on creating CFCs for Flash Remoting MX, see Using Flash with CFCs.

Using asynchronous CFCs

ColdFusion MX 7 provides an event gateway that lets you send a message to a CFC asynchronously. This gateway lets you initialize processing by a CFC without waiting for the CFC to complete or return a value. You can use asynchronous CFCs that use this gateway for the following:

  • Reindexing a Verity collection
  • Logging information
  • Running batch processes

For more information on using asynchronous CFCs, see About event gateways.


Creating ColdFusion components

When you create CFCs, you create methods, which are ColdFusion user-defined functions, in the component page. You pass data to a method by using parameters. The method then performs the function and, if specified in the cfreturn tag, returns data.

You can also define variables in a CFC. Within a CFC, these variables are known as properties.

The following sections describe how to create CFCs:

  • Tags for creating CFCs
  • Elements of a CFC
  • Building ColdFusion components
  • Providing results
  • Tags for creating CFCs
  • Elements of a CFC
  • Building ColdFusion components
  • Providing results

Tags for creating CFCs

The following table lists the tags that you use to create a CFC. You use these tags on the CFML page that defines the CFC.

Tag | Description
cfcomponent | Contains a component definition; includes attributes for introspection. For more information, see Building ColdFusion components.
cffunction | Defines a component method (function); includes attributes for introspection. For more information, see Defining component methods.
cfargument | Defines a parameter (argument) to a method; includes attributes for introspection. For more information, see Defining and using method parameters.
cfproperty | Defines variables for CFCs that provide web services; also use to document component properties. For more information, see The cfproperty tag.

Elements of a CFC

A CFC has the following characteristics:

  • It is a single CFML page with a .cfc filename extension. The component name is the same as the filename. For example, if the file is myComponent.cfc, the component name is myComponent.
  • The page is surrounded by a cfcomponent tag. No code can be outside this tag.
  • The component page defines methods (functions), properties (data), or both. Most CFCs have methods, or methods and properties, but you can also have a CFC that contains only properties.
  • You use the cffunction tag to define CFC methods. The CFScript function statement can create simple methods, but it does not provide options to control access to the method, provide metadata, specify a return type, or control generated output.
  • You can write code on the component page that is outside of cffunction definitions. This code executes when the CFC is instantiated or whenever you invoke a method of the CFC.

Building ColdFusion components

You use the cfcomponent and cffunction tags to create ColdFusion components. By itself, the cffunction tag does not provide functionality. The cfcomponent tag provides an envelope that describes the functionality that you build in CFML and enclose in cffunction tags. The following example shows the skeleton of a component with two methods:

<cfcomponent>
    <cffunction name="firstMethod">
         <!--- CFML code for this method goes here. --->
    </cffunction>
    <cffunction name="secondMethod">
         <!--- CFML code for this method goes here. --->
    </cffunction>
</cfcomponent>

This section describes the following topics:

  • Defining component methods
  • Defining CFCs with related methods
  • Putting executable code in a separate file
  • Initializing instance data
  • Defining and using method parameters


Defining component methods

You define component methods using cffunction tags. The following example defines a CFC that contains two methods, getall and getsalary:

<cfcomponent>
    <cffunction name="getall" output="false" returntype="query">
        <cfset var queryall="">
        <cfquery name="queryall" datasource="cfdocexamples">
            SELECT * FROM EMPLOYEE
        </cfquery>
        <cfreturn queryall>
    </cffunction>
    <cffunction name="getsalary" output="false">
        <cfset var getNamesandSalary="">
            <cfquery name="getNamesandSalary" datasource="cfdocexamples">
                SELECT FirstName, LastName, Salary FROM EMPLOYEE
            </cfquery>
        <cfreturn getNamesandSalary>
    </cffunction>
</cfcomponent>

Because component methods are ColdFusion functions, most of their features and coding techniques are identical to those of user-defined functions. For more information on using the cffunction tag to create functions, see Writing and Calling User-Defined Functions. Like other ColdFusion functions, CFC methods can display information directly by generating output, or can return a value to the code or client that invoked the method.

You use the following cffunction tag attributes only for CFCs:

  • The displayname and hint attributes, which document the CFC; for more information, see Documenting CFCs.
  • The access attribute, which controls access to the CFC; for more information, see Using access security.

For detailed reference information on the cffunction tag, see CFML Reference.


Defining CFCs with related methods

When defining CFCs, it is good programming practice to organize related methods in one CFC. For example, you could put all methods that perform operations related to a user, such as addUser, editUser, and storeUserPreferences, in one CFC. You can group related mathematical functions into one CFC. A CFC can also contain all the methods and properties necessary for a shopping cart. The following CFC contains two cffunction tags that define two component methods, getEmp and getDept. When invoked, the component methods query the ExampleApps database. The cfreturn tag returns the query results to the client, or page, where the method was invoked.

<cfcomponent>
    <cffunction name="getEmp">
        <cfset var empQuery="">
         <cfquery name="empQuery" datasource="cfdocexamples" dbtype="ODBC" >
             SELECT FIRSTNAME, LASTNAME, EMAIL
             FROM tblEmployees
         </cfquery>
         <cfreturn empQuery>
    </cffunction>
    <cffunction name="getDept">
        <cfset var deptQuery="">
        <cfquery name="deptQuery" datasource="cfdocexamples" dbtype="ODBC" >
             SELECT *
             FROM tblDepartments
         </cfquery>
         <cfreturn deptQuery>
    </cffunction>
</cfcomponent>


Putting executable code in a separate file

You can put executable code in a separate file from the main component definition page. By placing the method execution code in a separate file, you can separate property initialization code, meta information, and the method definition shell from the executable method definition code. This technique lets you modularize your code and helps prevent CFML pages from getting too long and complex.

To separate the component method code, use a cfinclude tag on the component definition page to call the page that contains the component method code.

Note: If your method takes arguments or returns data to the page that invokes it, the cfargument tag and the cfreturn tag must be on the component definition page, not on the included page.

To create a component method using the cfinclude tag:

  1. Create a tellTime.cfc file with the following code:
    <cfcomponent>
    <cffunction name="getUTCTime">
        <cfinclude template="getUTCTime.cfm">
    <cfreturn utcStruct.Hour & ":" & utcStruct.Minute>
    </cffunction>
</cfcomponent>
  2. Create a ColdFusion page with the following code, and save it as getUTCTime.cfm in the same directory as tellTime.cfc:
    <cfscript>
    serverTime=now();
    utcTime=GetTimeZoneInfo();
    utcStruct=structNew();
    utcStruct.Hour=DatePart("h", serverTime);
    utcStruct.Minute=DatePart("n", serverTime);
    utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet;
    utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet;
    if (utcStruct.Minute LT 10)
        utcStruct.Minute = "0" & utcStruct.Minute;
</cfscript>

    In the example, the getUTCTime method definition calls the getUTCTime.cfm file with the cfinclude tag. The getUTCTime.cfm code calculates the UTC time representation of the current time and populates a structure with hour and minute values. The method in tellTime.cfc then uses the information in the structure to return the current UTC time as a string to the calling page. The included page must not include a cfreturn statement.


Initializing instance data

Some components have instance data, which is data that persists as long as the component instance exists. For example, a shopping cart component might have instance data that includes the IDs and quantities of items that the user puts in the shopping cart. Instance data is often shared by several methods that can create, delete, or modify the data.

You can refer to instance data of a CFC only if you create an instance of the CFC. From inside the CFC, you refer to instance data of the CFC using the this prefix, for example this.firstvariable. From the calling page, you refer to instance data using dot notation, including the name of the instance of the component and the name of the instance data, as in objectname.ivarname. Components whose methods you invoke without first instantiating the component do not typically have instance data.

You initialize instance data at the top of the component definition, before the method definitions. ColdFusion executes this code when it instantiates the component; for example, when a cfobject tag creates the component instance. Because this code executes only when the instance is created and it typically "constructs" properties of the component, instance data initialization code is sometimes called constructor code.

You can use any CFML tag or function in constructor code, and the code can perform any ColdFusion processing, such as querying a database or data validation and manipulation. If one component extends another, the parent component’s constructor code executes before the child component’s constructor code.

Note: ColdFusion does not require you to put the initialization code at the top of the component definition; however, it is good programming practice to do so.

The following example shows constructor code for a shopping cart CFC:

<cfcomponent>
    <!--- Initialize the array for the cart item IDs and quantities. --->
    <cfset This.CartData = ArrayNew(2)>
    <!--- The following variable has the ID of the "Special Deal" product for
            this session. --->
    <cfset This.Special_ID = RandRange(1, 999)>

For information on scopes, see The This scope and The Variables scope.

A useful technique is to define a method named init(), which initializes an instance of a CFC, acting as a constructor. The init() method can initialize constants and return an instance of the component to the calling page. The following code illustrates an example of an init() method:

<cfcomponent displayname="shoppingCart">
    <cffunction name="init" access="public" output="no" returntype="shoppingCart">
        <cfargument name="shoppingCartID" type="UUID" required="yes">
        <cfset variables.shoppingCartID = arguments.shoppingCartID>
        <cfreturn this>
    </cffunction>

    <!--- Additional methods go here. --->
</cfcomponent>

In this example, the init() method uses the variables scope to make the shopping cart ID available anywhere in the CFC. For more information about scope, see CFC variables and scope.


Defining and using method parameters

You pass data to a method by using parameters. To define a component method parameter, use the cfargument tag in the cffunction tag body. To define multiple parameters, use multiple cfargument tags. The tag names a parameter and lets you specify the following:

  • Whether the parameter is required
  • The type of data that is required
  • A default argument value
  • Display name and hint metadata for CFC introspection

Note: You can create CFC methods that do not use cfargument tags, for example, if you use positional parameters in your methods. However, most CFC methods use the cfargument tag.

Example: convertTemp.cfc

The convertTemp.cfc file consists of the following:

<cfcomponent>
    <!--- Celsius to Fahrenheit conversion method. --->
    <cffunction name="ctof" output="false">
        <cfargument name="temp" required="yes" type="numeric">
        <cfreturn ((temp*9)/5)+32>
    </cffunction>

    <!--- Fahrenheit to Celsius conversion method. --->
    <cffunction name="ftoc" output="false">
        <cfargument name="temp" required="yes" type="numeric">
        <cfreturn ((temp-32)*5/9)>
    </cffunction>
</cfcomponent>

Reviewing the code

The convertTemp CFC contains two methods that convert temperature. The following table describes the code and its function:

Code

Description

<cfcomponent>

Defines the component.

<cffunction name="ctof" output="false">

Defines the ctof method.

Indicates that this method does not display output.

<cfargument name="temp" required="yes" type="numeric">

Creates the temp parameter of the ctof method. Indicates that it is required and that the expected value is numeric.

<cfreturn ((temp*9)/5)+32>

Defines the value that the method returns.

</cffunction>

Ends the method definition.

<cffunction name="ftoc" output="false">

Defines the ftoc method.

Indicates that this method does not display output.

<cfargument name="temp" required="yes" type="numeric">

Creates the temp parameter of the ftoc method. Indicates that it is required and that the expected value is numeric.

<cfreturn ((temp-32)*5/9)>

Defines the value that the method returns.

</cffunction>

Ends the method definition.

</cfcomponent>

Ends the component definition.

Example: tempConversion.cfm

The ColdFusion page tempConversion.cfm is an HTML form in which the user enters the temperature to convert, and selects the type of conversion to perform. When the user clicks the Submit button, ColdFusion performs the actions on the processForm.cfm page. The file tempConversion.cfm, which should be in the same directory as convertTemp.cfc, consists of the following:

<cfform action="processForm.cfm" method="POST">
    Enter the temperature:
        <input name="temperature" type="text"><br><br>
    Select the type of conversion:<br>
        <select name="conversionType">
            <option value="CtoF">Celsius to Farenheit</option>
            <option value="FtoC">Farenheit to Celsius</option>
        </select><br><br>
    <input name="submitform" type="submit" value="Submit">
</cfform>

Example: processForm.cfm

The ColdFusion page processForm.cfm calls the appropriate component method, based on what the user entered in the form on the tempConversion.cfm page. It should be in the same directory as convertTemp.cfc.

<cfif #form.conversionType# is "CtoF">
    <cfinvoke component="convertTemp" method="ctof" returnvariable="newtemp"
        temp=#form.temperature#>
    <cfoutput>#form.temperature# degrees Celsius is #newtemp# degrees
        Farenheit.</cfoutput>
    <cfelseif #form.conversionType# is "FtoC">
        <cfinvoke component="convertTemp" method="ftoc"
            returnvariable="newtemp" temp=#form.temperature#>
        <cfoutput>#form.temperature# degrees Fahrenheit is #newtemp# degrees
            Celsius.</cfoutput>
</cfif>

Reviewing the code

The file processForm.cfm invokes the appropriate component method. The following table describes the code and its function:

Code

Description

<cfif form.conversionType is "CtoF">

Executes the code in the cfif block if the user selected Celsius to Fahrenheit as the conversion type in the form on the tempConversion.cfm page.

<cfinvoke component="convertTemp" method="ctof" returnvariable="newtemp" arguments.temp="#form.temperature#">

Invokes the ctof method of the convertTemp component, without creating an instance of the convertTemp component. Specifies newtemp as the result variable for the method. Assigns the temperature value that the user entered in the form to the variable temp, which is specified in the cfargument tag of the ctof method. When invoking the ctof method, the temp variable is assigned to the Arguments scope. For more information about variables and scope, see CFC variables and scope.

<cfoutput>#form.temperature# degrees Celsius is #newtemp# degrees Fahrenheit.</cfoutput>

Displays the temperature that the user entered in the form, the text "degrees Celsius is," the new temperature value that results from the ctof method, and the text "degrees Fahrenheit."

<cfelseif #form.conversionType# is "FtoC">

Executes the code in the cfelseif block if the user selected Fahrenheit to Celsius as the conversion type in the form on the tempConversion.cfm page.

<cfinvoke component="converttemp" method="ftoc" returnvariable="newtemp" temp=#form.temperature#>

Invokes the ftoc method of the convertTemp component, without creating an instance of the convertTemp component. Specifies newtemp as the result variable for the method. Assigns the temperature value that the user entered in the form to the variable temp, which is specified in the cfargument tag of the ftoc method. When invoking the ftoc method, the temp variable is assigned to the Arguments scope. For more information about variables and scope, see CFC variables and scope

<cfoutput>#form.temperature# degrees Fahrenheit is #newtemp# degrees Celsius.</cfoutput>

Displays the temperature that the user entered in the form, the text "degrees Fahrenheit is," the new temperature value that results from the ftoc method, and the text "degrees Celsius."

</cfif>

Closes the cfif block.

To run the example, display the tempConversion.cfm page in your browser. When you enter a value in the text box of the form, the value is stored in the form.temperature variable. Processing is then performed on the processForm.cfm page, which refers to the value as form.temperature. When you invoke either method, the cfinvoke tag assigns the value form.temperature to temp; temp is the argument specified in the cfargument tag of the appropriate method. The appropriate method in the convertTemp component performs the necessary calculations and returns the new value as newtemp.

For detailed reference information on the cfargument tag, see CFML Reference.

To access the parameter values in the component method definition, use structure- or array-like notation with the Arguments scope. The following example refers to the lastName argument as Arguments.lastname; it could also refer to it as Arguments[1]. In addition, you can access arguments directly using number (#) signs, such as #lastname#; however, it is better programming practice to identify the scope (for example, #Arguments.lastname#). Also, you can use Array- or structure-like notation, which lets you loop over multiple parameters.

For more information on the Arguments scope, see The Arguments scope.

To define parameters in the component method definition:

  • Create a new component with the following contents, and save it as corpQuery.cfc in a directory under your web root directory:
    <cfcomponent>
    <cffunction name="getEmp">
        <cfargument name="lastName" type="string" required="true"
                hint="Employee last name">
        <cfset var empQuery="">
         <cfquery name="empQuery" datasource="cfdocexamples">
             SELECT LASTNAME, FIRSTNAME, EMAIL
             FROM tblEmployees
            WHERE LASTNAME LIKE '#Arguments.lastName#'
         </cfquery>
            <!--- Use cfdump for debugging purposes. --->
         <cfdump var=#empQuery#>
    </cffunction>
    <cffunction name="getCat" hint="Get items below specified cost">
    <cfargument name="cost" type="numeric" required="true">
        <cfset var catQuery="">
        <cfquery name="catQuery" datasource="cfdocexamples">
             SELECT ItemName, ItemDescription, ItemCost
             FROM tblItems
            WHERE ItemCost <= #Arguments.cost#
         </cfquery>
            <!--- Use cfdump for debugging purposes. --->
         <cfdump var=#catQuery#>
    </cffunction>
</cfcomponent>

In the example, the cfargument attributes specify the following:

  • The name attributes define the parameter names.
  • The type attribute for the lastName argument specifies that the parameter must be a text string. The type attribute for the cost argument specifies that the parameter must be a numeric value. These attributes validate the data before it is submitted to the database.
  • The required attributes indicate that the parameters are required or an exception will be thrown.
  • The Arguments scope provides access to the parameter values.


Providing results

ColdFusion components can provide information in the following ways:

  • They can generate output that is displayed on the calling page.
  • They can return a variable.

You can use either technique, or a combination of both, in your applications. The technique that you use should depend on your application’s needs and your coding methodologies. For example, many CFC methods that perform business logic return the results as a variable, and many CFC methods that display output directly are designed as modular units for generating output, and do not do business logic.

This section describes the following topics:

  • Displaying output
  • Returning a results variable
  • Documenting CFCs
  • Saving and naming ColdFusion components


Displaying output

If you do not specifically suppress output, any text, HTML code, or output that CFML tags generate inside your method gets returned as generated output to the client that calls the component method. If the client is a web browser, it displays these results. For example, the following getLocalTime1 component method shows the local time directly on the page that invokes the method:

<cfcomponent>
    <cffunction name="getLocalTime1">
        <cfoutput>#TimeFormat(now())#</cfoutput>
    </cffunction>
</cfcomponent>

Component methods that are called using Flash Remoting or as web services cannot use this method to provide results.


Returning a results variable

In the component method definition, you use the cfreturn tag to return the results to the client as variable data. For example, the following getLocalTime2 component method returns the local time as a variable to the ColdFusion page or other client that invokes the method:

<cfcomponent>
    <cffunction name="getLocalTime">
        <cfreturn TimeFormat(now())>
    </cffunction>
</cfcomponent>

The ColdFusion page or other client, such as a Flash application, that receives the result then uses the variable data as appropriate.

Note: If a CFC is invoked using a URL or by submitting a form, ColdFusion MX returns the variable as a WDDX packet. A CFC that is invoked by Flash Remoting MX, or any other instance of a CFC, must not return the This scope.

You can return values of all data types, including strings, integers, arrays, structures, and instances of CFCs. The cfreturn tag returns a single variable, as does the return CFScript statement. Therefore, if you want to return more than one result value at a time, use a structure. If you do not want to display output in a method, use output="false" in the cffunction tag.

For more information on using the cfreturn tag, see CFML Reference.


Documenting CFCs

ColdFusion provides several ways to include documentation about your CFCs in your component definitions. The documentation is available when you use introspection to display information about the CFC or call the GetMetadata function to get the component’s metadata. You can use the following tools for documenting CFCs:

  • The displayname and hint attributes
  • User-defined metadata attributes
  • The cfproperty tag

The following sections describe these tools. For information on displaying the information, see Using introspection to get information about components.

The displayname and hint attributes

The cfcomponent, cffunction, cfargument, and cfproperty tags have displayname and hint attributes.

The displayname attribute lets you provide a more descriptive name for a component, attribute, method, or property. When you use introspection, this attribute appears in parentheses next to the component or method name, or on the parameter information line.

You use the hint attribute for longer descriptions of the component, method, or argument. In the introspection display, this attribute appears on a separate line or on several lines of the component or method description, and at the end of the argument description.

Metadata attributes

You can include arbitrary metadata information as attributes of the cfcomponent, cffunction, cfargument, and cfproperty tags. To create a metadata attribute, specify the metadata attribute name and its value. For example, in the following cfcomponent tag, the Author attribute is a metadata attribute. This attribute is not used as a function parameter; instead, it indicates who wrote this CFC.

<cfcomponent name="makeForm" Author="Bean Lapin">

Metadata attributes are not used by ColdFusion MX for processing; they also do not appear in standard ColdFusion introspection displays; however, you can access and display them by using the GetMetaData function to get the metadata. Each attribute name is a key in the metadata structure of the CFC element.

Metadata attributes are used for more than documentation. Your application can use the GetMetadata function to get the metadata attributes and act based on the values. For example, a mathCFC component might have the following cfcomponent tag:

<cfcomponent displayname="Math Functions" MetaType="Float">

In this case, a ColdFusion page with the following code sets the MetaTypeInfo variable to Float:

<cfobject component="mathCFC" name="MathFuncs">
<cfset MetaTypeInfo=GetMetadata(MathFuncs).MetaType>

Note: All metadata values are replaced by strings in the metadata structure returned from the GetMetadata function. Because of this, you should not use expressions in custom metadata attributes.

The cfproperty tag

The cfproperty tag is used to create complex data types with WSDL descriptors and for component property documentation, as follows:

  • It can create complex data types with WSDL descriptions for ColdFusion web services. For more information, see Using ColdFusion components to define data types for web services.
  • It can provide documentation of component properties in the ColdFusion introspection output. The introspection information includes the values of the standard cfproperty tag attributes.

Note: The cfproperty tag does not create a variable or assign it a value. It is used for information purposes only. You use a cfset tag, or CFScript assignment statement, to create the property and set its value.


Saving and naming ColdFusion components

The following table lists the locations in which you can save component files and how they can be accessed from each location:

 | URL | Form | Flash Remoting | Web services | ColdFusion page
Current directory | N/A | Yes | N/A | N/A | Yes
Web root | Yes | Yes | Yes | Yes | Yes
ColdFusion mappings | No | No | No | No | Yes
Custom tag roots | No | No | No | No | Yes

Note: ColdFusion MX mappings and custom tag roots can exist within the web root. If so, they are accessible to remote requests, including URL, form, Flash Remoting, and web services invocation.

When you store components in the same directory, they are members of a component package. You can group related CFCs into packages. Your application can refer to any component in a directory specifically by using a qualified component name that starts with a subdirectory of one of the accessible directories and uses a period to delimit each directory in the path to the directory that contains the component. For example, the following example is a qualified name of a component named price:

catalog.product.price

In this example, the price.cfc file must be in the catalog\product subdirectory of a directory that ColdFusion searches for components, as listed in the preceding table. When you refer to a component using the qualified name, ColdFusion looks for the component in the order described in Specifying the CFC location.

Establishing a descriptive naming convention is a good practice, especially if you plan to install the components as part of a packaged application.


Using ColdFusion components

There are two ways to use a CFC:

  • You can instantiate a CFC object, which creates a CFC instance. You then invoke the methods of the instance. You can access the CFC methods and data as instance elements. You can also use the instance in the cfinvoke tag to invoke the CFC methods. When you instantiate a CFC, data in the CFC is preserved as long as the CFC instance exists, and ColdFusion does not incur the overhead of creating the instance each time you call a method.

    Instantiate CFCs to preserve data in the CFC. To ensure processing efficiency if you use the CFC more than once on a page, instantiate the CFC before you invoke its methods.

    Methods that are executed remotely through Flash Remoting and web services always create a new instance of the CFC before executing the method.

  • You can invoke (call) a method of the CFC without creating an instance of the CFC, which is referred to as transiently invoking a method. In this case, ColdFusion creates an instance of the CFC that exists only from the time you invoke the method until the method returns a result. No data is preserved between invocations and there is no instance of the CFC that you can reuse elsewhere in your CFML. It is considered a best practice to create an instance of a CFC before invoking any of its methods, unless your CFML request uses the CFC only once. If you transiently invoke a method frequently, consider creating a user-defined function to replace the CFC method.

You can create persistent CFCs by assigning the CFC instance to a persistent scope, such as the Session or Application scope. This way, you can create CFCs for objects, such as shopping carts or logged-in users, that must persist for sessions. You can also create CFCs that provide application-specific data and methods.

This section describes how to use CFCs, including the following topics:

  • Tags for using CFCs
  • CFC invocation techniques
  • Instantiating CFCs
  • Invoking CFC methods with the cfinvoke tag
  • Using components directly in CFScript and CFML
  • Invoking CFC methods using forms and URLs
  • Accessing CFCs from outside ColdFusion and basic HTML
  • Specifying the CFC location


Tags for using CFCs

The following table lists the tags that you use to instantiate or invoke a CFC. You use these tags on the CFML page on which you instantiate or invoke the CFC.

Tag | Description
cfinvoke | Invokes a method of a CFC.
cfinvokeargument | Passes the name and value of a parameter to a component method.
cfobject | Creates a CFC instance.
CreateObject | Creates a CFC instance.


CFC invocation techniques

ColdFusion provides many ways to instantiate CFCs and invoke CFC methods. The following table lists the techniques, including the ColdFusion tags and functions that you use:

Invocation | Description | For more information
cfinvoke tag | Invokes a component method. Can invoke methods of a CFC instance or invoke the methods transiently. | See Invoking CFC methods with the cfinvoke tag.
cfset tag and assignment statements | Invoke methods and access properties of a component instance. | See Using components directly in CFScript and CFML.
URL (HTTP GET) | Transiently invokes a component method by specifying the component and method names in the URL string. | See Invoking component methods using a URL.
Form control (HTTP POST) | Transiently invokes a component method using the HTML form and input tags and their attributes. | See Invoking component methods using a form.
Flash Remoting | ActionScript can transiently invoke component methods. | See Using the Flash Remoting Service.
Web services | The cfinvoke tag and CFScript consume web services in ColdFusion MX 7. External applications can also consume CFC methods as web services. | See Using Web Services.


Instantiating CFCs

If you use a CFC multiple times in a ColdFusion request, or if you use a CFC with persistent properties, use the cfobject tag or CreateObject function to instantiate the CFC before you call its methods.

The following example uses the cfobject tag to create an instance of the tellTime CFC.

<cfobject component="tellTime" name="tellTimeObj">

The following example uses the CreateObject function to instantiate the same component in CFScript:

tellTimeObj = CreateObject("component", "tellTime");


Invoking CFC methods with the cfinvoke tag

The cfinvoke tag can invoke methods on a CFC instance or invoke CFC methods transiently. You can also use the cfinvoke tag to invoke CFC methods from within a CFC.

This section describes the following topics:

  • Invoking methods of a CFC instance
  • Invoking component methods transiently using the cfinvoke tag
  • Using the cfinvoke tag within the CFC definition
  • Invoking methods using dynamic method names

Invoking methods of a CFC instance

To invoke a component method of a CFC instance, use the cfinvoke tag and specify the following:

  • The CFC instance name, enclosed in number signs (#), in the component attribute.
  • The method name, in the method attribute.
  • Any parameters. For information on passing parameters, see Passing parameters to methods using the cfinvoke tag.
  • If the component method returns a result, the name of the variable that will contain the result in the returnVariable attribute.

To invoke a method of a component instance using the cfinvoke tag:

  1. Create a file named tellTime2.cfc with the following code:
    <cfcomponent>
    <cffunction name="getLocalTime" access="remote">
        <cfreturn TimeFormat(now())>
    </cffunction>
    <cffunction name="getUTCTime" access="remote">
        <cfscript>
            serverTime=now();
            utcTime=GetTimeZoneInfo();
            utcStruct=structNew();
            utcStruct.Hour=DatePart("h", serverTime);
            utcStruct.Minute=DatePart("n", serverTime);
            utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet;
            utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet;
            if (utcStruct.Minute LT 10)
                utcStruct.Minute = "0" & utcStruct.Minute;
        </cfscript>
        <cfreturn utcStruct.Hour & ":" & utcStruct.Minute>
    </cffunction>
</cfcomponent>

    The example defines two component methods: getLocalTime and getUTCTime.

  2. Create a new ColdFusion page, with the following code and save it in the same directory as the tellTime component:
    <!--- Create the component instance. --->
<cfobject component="tellTime2" name="tellTimeObj">
<!--- Invoke the methods. --->
<cfinvoke component="#tellTimeObj#" method="getLocalTime"
    returnvariable="localTime" >
<cfinvoke component="#tellTimeObj#" method="getUTCTime"
    returnvariable="UTCTime" >
<!--- Display the results. --->
<h3>Time Display Page</h3>
<cfoutput>
    Server's Local Time: #localTime#<br>
    Calculated UTC Time: #UTCTime#
</cfoutput>

This example uses the cfobject tag to create an instance of the tellTime component and the cfinvoke tag to invoke the instance’s getLocalTime and getUTCTime methods. In this example, the CFC contains the functional logic in the methods, which return a result to the calling page, and the calling page displays the results. This structure separates the logic from the display functions, which usually results in more reusable code.


Invoking component methods transiently using the cfinvoke tag

In ColdFusion pages or components, the cfinvoke tag can invoke component methods without creating a persistent CFC instance.

To invoke a component method transiently, use the cfinvoke tag and specify the following:

  • The name or path of the component, in the component attribute.
  • The method name, in the method attribute.
  • Any parameters. For information on passing parameters, see Passing parameters to methods using the cfinvoke tag.
  • If the component method returns a result, the name of the variable that will contain the result, in the returnVariable attribute.

To invoke a component method using the cfinvoke tag:

  1. Create the following component and save it as tellTime.cfc:
    <cfcomponent>
    <cffunction name="getLocalTime">
        <cfoutput>#TimeFormat(now())#</cfoutput>
    </cffunction>
</cfcomponent>

    The example defines a component with one method, getLocalTime, that displays the current time.

  2. Create a ColdFusion page, with the following code, and save it in the same directory as the tellTime component:
    <h3>Time Display Page</h3>
<b>Server's Local Time:</b>
<cfinvoke component="tellTime" method="getLocalTime">

    Using the cfinvoke tag, the example invokes the getLocalTime component method without creating a persistent CFC instance.


Using the cfinvoke tag within the CFC definition

You can use the cfinvoke tag to invoke a component method within the component definition; for example, to call a utility method that provides a service to other methods in the component. To use the cfinvoke tag in this instance, do not create an instance or specify the component name in the cfinvoke tag, as the following example shows:

<cfcomponent>
    <cffunction name="servicemethod" access="public">
        <cfoutput>At your service...<br></cfoutput>
    </cffunction>
    <cffunction name="mymethod" access="public">
        <cfoutput>We're in mymethod.<br></cfoutput>
        <!--- Invoke a method in this CFC. --->
        <cfinvoke method="servicemethod">
    </cffunction>
</cfcomponent>

Note: When you invoke a method from within the component definition in which you define the method, do not use the This scope, because this resets the access privileges.


Invoking methods using dynamic method names

The cfinvoke tag is the only way to efficiently invoke different component methods based on variable data (for example, form input). In this case, you use a variable name, such as Form.method, as the value of the method attribute. In the following example, the user selects a report from a form:

<select name="whichreport">
    <option value="all">Complete Report</option>
    <option value="salary">Salary Information</option>
</select>

The cfinvoke tag then invokes the appropriate method, based on what the user selected:

<cfinvoke component="getdata" method="#form.whichreport#" returnvariable="queryall">


Using components directly in CFScript and CFML

You can invoke methods of a component instance directly using CFScript or in CFML tags. To invoke component methods directly, use the CreateObject function or cfobject tag to instantiate the component. Thereafter, use the instance name followed by a period and the method that you are calling to invoke an instance of the method. You must always use parentheses after the method name, even if the method does not take any parameters.

You can use this syntax anywhere that you can use a ColdFusion function, such as in cfset tags or surrounded by number signs in the body of a cfoutput tag.

Invoking component methods in CFScript

The following example shows how to invoke component methods in CFScript:

<!--- Instantiate once and reuse the instance.--->
<cfscript>
    tellTimeObj=CreateObject("component","tellTime");
    WriteOutput("Server's Local Time: " & tellTimeObj.getLocalTime());
    WriteOutput("<br> Calculated UTC Time: " & tellTimeObj.getUTCTime());
</cfscript>

In the example, the three CFScript statements do the following:

  1. The CreateObject function instantiates the tellTime CFC as tellTimeObj.
  2. The first WriteOutput function displays text followed by the results returned by the getLocalTime method of the tellTimeObj instance.
  3. The second WriteOutput function displays text followed by the results returned by the getUTCTime method of the tellTimeObj instance.

In CFScript, you use the method name in standard function syntax, such as methodName().

Invoking component methods in CFML

The following example uses CFML tags to produce the same results as the CFScript example:

<cfobject name="tellTimeObj" component="tellTime">
<cfoutput>
    Server's Local Time: #tellTimeObj.getLocalTime()#<br>
    Calculated UTC Time: #tellTimeObj.getUTCTime()#
</cfoutput>

Accessing component data directly

You can access data in the component’s This scope directly in CFScript and cfset assignment statements. For example, if a user data CFC has a This.lastUpdated property, you could have code such as the following:

<cfobject name="userDataCFC" component="userData">
<cfif DateDiff("d", userDataCFC.lastUpdated, Now()) GT 30>
    <!--- Code to deal with older data goes here. --->
</cfif>

For more information, see The This scope.


Invoking CFC methods using forms and URLs

You can invoke CFC methods directly by specifying the CFC in a URL, or using HTML and CFML form tags. Because all HTTP requests are transient, these methods only let you transiently invoke methods. They do not let you create persistent CFC instances.

This section describes the following topics:

  • Invoking component methods using a URL
  • Invoking component methods using a form

Invoking component methods using a URL

To invoke a component method using a URL, you must append the method name to the URL in standard URL query-string, name-value syntax. You can invoke only one component method per URL request; for example:

http://localhost:8500/tellTime.cfc?method=getLocalTime

Note: To use URL invocation, you must set the access attribute of the cffunction tag to remote.

To pass parameters to component methods using a URL, append the parameters to the URL in standard URL query-string, name-value pair syntax; for example:

http://localhost:8500/corpQuery.cfc?method=getEmp&lastName=camden

To pass multiple parameters within a URL, use the ampersand character (&) to delimit the name-value pairs; for example:

http://localhost:8500/corpQuerySecure.cfc?method=getAuth&store=women&dept=shoes

Note: To ensure data security, Macromedia strongly recommends that you not pass sensitive information over the web using URL strings. Potentially sensitive information includes all personal user information, including passwords, addresses, telephone numbers, and so on.

If a CFC method that you access using the URL displays output directly, the user’s browser shows the output. You can suppress output by specifying output="No" in the cffunction tag. If the CFC returns a result using the cfreturn tag, ColdFusion converts the text to HTML edit format (with special characters replaced by their HTML escape sequences), puts the result in a WDDX packet, and includes the packet in the HTML that it returns to the client.


Invoking component methods using a form

To invoke a method using a ColdFusion or HTML form, the following must be true:

  • The form or cfform tag action attribute must specify the CFC filename or path followed by ?method=methodname, where methodname is the name of the method; for example, <form action="myComponent.cfc?method=myMethod" method="POST">.
  • The form must have an input tag for each component method parameter. The name attribute of the tag must be the method parameter name and the field value is the parameter value.
  • The cffunction tag that defines the CFC method being invoked must specify the access="remote" attribute.

If the CFC method that you invoke from the form displays output directly, the user’s browser shows the output. (You can use the cffunction tag output attribute to disable displaying output.) If the CFC returns a result using the cfreturn tag, ColdFusion converts the text to HTML edit format, puts it in a WDDX packet, and includes the packet in the HTML that it returns to the client.

To invoke component methods using a form:

  1. Create a corpFind.cfm file with the following contents:
    <h2>Find People</h2>
<form action="components/corpQuery.cfc?method="getEmp" method="post">
    <p>Enter employee's last Name:</p>
    <input type="Text" name="lastName">
    <input type="Hidden" name="method" value="getEmp">
    <input type="Submit" title="Submit Query"><br>
</form>

    In the example, the form tag’s action attribute points to the corpQuery component and invokes the getEmp method.

  2. Create a corpQuery.cfc file, specifying access="remote" for each cffunction tag, as the following example shows:
    <cfcomponent>
    <cffunction name="getEmp" access="remote">
        <cfargument name="lastName" required="true">
        <cfset var empQuery="">
         <cfquery name="empQuery" datasource="cfdocexamples">
             SELECT LASTNAME, FIRSTNAME, EMAIL
             FROM tblEmployees
            WHERE LASTNAME LIKE '#arguments.lastName#'
         </cfquery>
         <cfoutput>Results filtered by #arguments.lastName#:</cfoutput><br>
         <cfdump var=#empQuery#>
    </cffunction>
</cfcomponent>
  3. Open a web browser and enter the following URL:
    http://localhost/corpFind.cfm

    ColdFusion displays the search form. After you enter values and click the Submit Query button, the browser displays the results.


Accessing CFCs from outside ColdFusion and basic HTML

Flash applications that use Flash Remoting MX can easily take advantage of ColdFusion components for business logic. Similarly, you can export CFCs so that any application can access CFC methods as web services.

Using Flash Remoting MX

For ColdFusion component methods to communicate with Flash Remoting MX applications, you must set the access attribute of the cffunction tag to remote.

For more information on creating CFCs for Flash Remoting MX, see Using the Flash Remoting Service.

Invoking components as web services

Any application, whether it is a ColdFusion application, a Java application, JSP page, or a .Net application, can access well-formed ColdFusion components as web services by referencing the WSDL file that ColdFusion automatically generates.

To see a component’s WSDL definition, specify the component web address in a URL, followed by ?wsdl; for example:

http://localhost:8500/MyComponents/arithCFC.cfc?wsdl

For more information on using CFCs as web services, see Using Web Services.


Specifying the CFC location

When you instantiate or invoke a component, you can specify the component name only, or you can specify a qualified path. To specify a qualified path, separate the directory names with periods, not backslashes. For example, myApp.cfcs.myComponent specifies the component defined in myApp\cfcs\myComponent.cfc. For additional information, see Saving and naming ColdFusion components.

ColdFusion uses the following rules to find the specified CFC:

  • If you use a cfinvoke or cfobject tag, or the CreateObject function, to access the CFC from a CFML page, ColdFusion searches directories in the following order:
    1. Local directory of the calling CFML page
    2. Web root
    3. Directories specified on the Custom Tag Paths page of ColdFusion MX Administrator
  • If you specify only a component name, ColdFusion searches each of these directories, in turn, for the component.
  • If you specify a qualified path, such as myApp.cfcs.myComponent, ColdFusion MX looks for a directory matching the first element of the path in each of these directories (in this example, myApp). If ColdFusion MX finds a matching directory, it looks for a file in the specified path beneath that directory, such as myApp\cfcs\myComponent.cfc, relative to each of these directories.

    Note: If ColdFusion finds a directory that matches the first path element, but does not find a CFC under that directory, ColdFusion returns a not found error and does not search for another directory.

  • If you invoke a CFC method remotely, using a specific URL, a form field, Flash Remoting MX, or a web service invocation, ColdFusion looks in the specified path relative to the web root. For form fields and URLs that are specified directly on local web pages, ColdFusion also searches relative to the page directory.

Note: On UNIX and Linux systems, ColdFusion MX attempts to match a CFC name or Custom tag name with a filename, as follows: First, it attempts to find a file with the name that is all lowercase. If it fails, it tries to find a file whose case matches the CFML case. For example, if you specify <cfobject name="myObject" Component="myComponent">, ColdFusion first looks for mycomponent.cfc and, if it doesn't find it, ColdFusion looks for myComponent.cfc.


Passing parameters to methods

This section describes how to pass parameters to a method in a CFC, including:

  • Passing parameters to methods using the cfinvoke tag
  • Passing parameters in direct method invocations
  • Passing parameters in a URL


Passing parameters to methods using the cfinvoke tag

When you use the cfinvoke tag, ColdFusion MX provides several methods for passing parameters to CFC methods:

  • As cfinvoke tag attributes, in name="value" format
  • In the cfinvoke tag argumentcollection attribute
  • In the cfinvoke tag body, using the cfinvokeargument tag

You can use any combination of these methods in a single invocation. If you use the same name in two or three of these methods, ColdFusion uses the value based on the following order of precedence:

  1. cfinvokeargument tags
  2. cfinvoke attribute name-value pairs
  3. argumentcollection arguments

Passing parameters using attribute format

You can pass parameters in the cfinvoke tag as tag attribute name-value pairs, as the following example shows:

<cfinvoke component="authQuery" method="getAuthSecure"
lastName="#session.username#" password="#url.password#">

In the example, the parameters are passed as the lastName and password attributes.

Note: The cfinvoke tag attribute names are reserved and cannot be used for parameter names. The reserved attribute names are: component, method, argumentCollection, and returnVariable. For more information, see CFML Reference.

Passing parameters in the argumentCollection attribute

If you save attributes to a structure, you can pass the structure directly using the cfinvoke tag’s argumentCollection attribute. This technique is useful if an existing structure or scope (such as the Forms scope) contains values that you want to pass to a CFC as parameters, and for using conditional or looping code to create parameters.

When you pass an argumentCollection structure, each structure key is the name of a parameter inside the structure.

The following example passes the Form scope to the addUser method of the UserDataCFC component. In the method, each form field name is a parameter name; the method can use the contents of the form fields to add a user to a database.

<cfinvoke component="UserDataCFC" method="addUser" argumentCollection="#Form#">

Passing parameters using the cfinvokeargument tag

To pass parameters in the cfinvoke tag body, use the cfinvokeargument tag. Using the cfinvokeargument tag, for example, you can build conditional processing that passes a different parameter based on user input.

The following example invokes the corpQuery component:

<cfinvoke component="corpQuery" method="getEmp">
    <cfinvokeargument name="lastName" value="Wilder">
</cfinvoke>

The cfinvokeargument tag passes the lastName parameter to the component method.

In the following example, a form already let the user select the report to generate. After instantiating the getdata and reports components, the action page invokes the doquery component instance, which returns the query results in queryall. The action page then invokes the doreport component instance and uses the cfinvokeargument tag to pass the query results to the doreport instance, where the output is generated.

<cfobject component="getdata" name="doquery">
<cfobject component="reports" name="doreport">
    <cfinvoke component="#doquery#" method="#form.whichreport#" returnvariable="queryall">
    <cfinvoke component="#doreport#"method="#form.whichreport#">
        <cfinvokeargument name="queryall" value="#queryall#">
    </cfinvoke>


Passing parameters in direct method invocations

ColdFusion provides three methods for passing parameters to CFC methods in direct method invocations:

  • You can pass the parameters the form of comma-separated name="value" entries, as in the following CFScript example:
    authorized = securityCFC.getAuth(name="Almonzo", Password="LauRa123");
  • You can pass the parameters in an argumentCollection structure. The following code is equivalent to the previous example:
    argsColl = structNew();
argsColl.username = "Amonzo";
argsColl.password = "LauRa123;
authorized = securityCFC.getAuth(argumentCollection = argsColl);
  • You can pass positional parameters to a method by separating them with commas. The following example calls the getAuth method, and passes the name and password as positional parameters:
    authorized = securityCFC.getAuth("Almonzo", "LauRa123");

    Note: For more information on using positional parameters and component methods in ColdFusion functions, see Creating user-defined functions.


Passing parameters in a URL

ColdFusion lets you pass parameters to CFC methods in a URL. To do so, you append the URL in standard URL query-string, name-value pair syntax; for example:

http://localhost:8500/CompanyQuery.cfc?method=getEmp&lastName=Adams


CFC variables and scope

This section describes how CFCs interact with ColdFusion scopes and use local variables, including the following topics:

  • The This scope
  • The Variables scope
  • The Arguments scope
  • Other variable scopes
  • Function local variables

Note: Components also have a Super keyword that is sometimes called a scope. For information on the Super keyword, see Using the Super keyword.

The This scope

The This scope is available within the CFC and is shared by all CFC methods. It is also available in the base component (if the CFC is a child component), on the page that instantiates the CFC, and all CFML pages included by the CFC.

Inside the CFC, you define and access This scope variables by using the prefix This, as in the following line:

<cfset This.color="green">

In the calling page, you can define and access CFC This scope variables by using the CFC instance name as the prefix. For example, if you create a CFC instance named car and, within the car CFC specify <cfset This.color="green">, a ColdFusion page that instantiates the CFC could refer to the component’s color property as #car.color#.

Variable values in the This scope last as long as the CFC instance exists and, therefore, can persist between calls to methods of a CFC instance.

Note: The This scope identifier works like the This keyword of JavaScript and ActionScript. CFCs do not follow the Java class model, and the This keyword behaves differently in ColdFusion MX than in Java. In Java, This is a private scope, whereas in ColdFusion, it is a public scope.


The Variables scope

The Variables scope in a CFC is private to the CFC. It includes variables defined in the CFC body (initialization or constructor code) and in the CFC methods. When you set Variables scope variables in the CFC, they cannot be seen by pages that invoke the CFC.

The CFC Variables scope does not include any of the Variables scope variables that are declared or available in the page that instantiates or invokes the CFC. However, you can make the Variables scope of the page that invokes a CFC accessible to the CFC by passing Variables as an argument to the CFC method.

You set a Variables scope variable by assigning a value to a name that has the Variables prefix or no prefix.

Values in the Variables scope last as long as the CFC instance exists, and therefore can last between calls to CFC instance methods.

The Variables scope is available to included pages, and Variables scope variables that are declared in the included page are available in the component page.

Note: The Variables scope is not the same as the var keyword, which makes variables private within a function. You should always define function-local variables using the var keyword.

Example: sharing the Variables scope

The following example shows how to make the Variables scope of the page that invokes a CFC accessible to the CFC by passing Variables as an argument to the CFC method. It also illustrates that the Variables scope is private to the CFC.

The following code is for the callGreetMe.cfm page:

<cfset Variables.MyName="Wilson">
<cfobject component="greetMe" name="myGreetings">
<cfoutput>
    Before invoking the CFC, Variables.Myname is: #Variables.MyName#.<br>
    Passing Variables scope to hello method. It returns: #myGreetings.hello(Variables.MyName)#.<br>
    After invoking the CFC, Variables.Myname is: #Variables.MyName#.<br>
</cfoutput>
<cfinvoke component="greetMe" method="VarScopeInCfc">

The following code is for the greetMe CFC:

<cfcomponent>
<cfset Variables.MyName="Tuckerman">
    <cffunction name="hello">
        <cfargument name="Name" Required=true>
        <cfset Variables.MyName="Hello " & Arguments.Name>
        <cfreturn Variables.MyName>
    </cffunction>
    <cffunction name="VarScopeInCfc">
        <cfoutput>Within the VarScopeInCfc method, Variables.MyName is: #variables.MyName#<br></cfoutput>
    </cffunction>
</cfcomponent>

In this example, the callGreetMe.cfm page does the following:

  1. Sets the MyName variable in its Variables scope to Wilson.
  2. Displays the Variables.MyName value.
  3. Calls the greetMe CFC and passes its Variables scope as a parameter.
  4. Displays the value returned by the greetMe CFC.
  5. Displays the Variables.MyName value.
  6. Invokes the VarScopeInCfc method, which displays the value of Variables.MyName within the CFC.

When you browse the callGreetMe.cfm page, the following appears:

Before invoking the CFC, Variables.Myname is: Wilson.
Passing Variables scope to hello method. It returns: Hello Wilson.
After invoking the CFC, Variables.Myname is: Wilson.
Within the VarScopeInCfc method, Variables.MyName is: Tuckerman


The Arguments scope

The Arguments scope exists only in a method, and is not available outside the method. The scope contains the variables that you passed into the method, including variables that you passed in the following ways:

  • As named attributes to the cfinvoke tag
  • In the cfargumentcollection attribute of the cfinvoke tag
  • In cfinvokeargument tags
  • As attributes or parameters passed into the method when the method is invoked as a web service, by Flash Remoting, as a direct URL, or by submitting a form

You can access variables in the Arguments scope using structure notation (Arguments.variablename), or array notation (Arguments[1] or Arguments["variablename"]).

The Arguments scope does not persist between calls to CFC methods.

Variables in the Arguments scope are available to pages included by the method.


Other variable scopes

A CFC shares the Form, URL, Request, CGI, Cookie, Client, Session, Application, Server, and Flash scopes with the calling page. Variables in these scopes are also available to all pages that are included by a CFC. These variables do not have any behavior that is specific to CFCs.


Function local variables

Variables that you declare with the Var keyword inside a cffunction tag or CFScript function definition are available only in the method in which they are defined, and only last from the time the method is invoked until it returns the result. You cannot use the Var keyword outside of function definitions.

Tip: You should always use the Var keyword on variables that are only used inside of the function in which they are declared.

You must define all function local variables at the top of the function definition, before any other CFML code; for example:

<cffunction ...>
    <cfset Var testVariable = "this is a local variable">
        <!--- Function code goes here. --->
    <cfreturn myresult>
</cffunction>

Any arguments declared with the cfargument tag must appear before any variables defined with the cfset tag. You can also put any cfscript tag first and define variables that you declare with the Var keyword in the script.

Use function local variables if you put the CFC in a persistent scope such as the Session scope, and the function has data that must be freed when the function exits.

Local variables do not persist between calls to CFC methods.

Local variables are available to pages included by the method.


Using CFCs effectively

This section describes the following techniques:

  • Structuring and reusing code
  • Building secure ColdFusion components
  • Using introspection to get information about components

Structuring and reusing code

The following sections provide information about the techniques that ColdFusion MX provides for structuring and reusing component code:

  • Using inheritance and the Super keyword
  • Using component packages
  • Using CFCs in persistent scopes


Using inheritance and the Super keyword

Component inheritance and the Super keyword are two important tools for creating structured, object-oriented ColdFusion components.

Component inheritance lets you create a single base component and reuse this code in multiple subclasses that are derived from the base component. Typically a base component is more general, and subcomponents are typically more specific. Each subclass does not have to redefine the code in the base component, but can override it if necessary.

The Super keyword lets a component that overrides a base component method execute the original base component method. This technique lets your subclassed component override a method without losing the ability to call the original version of the method.

Using component inheritance

Component inheritance lets you import component methods and properties from one component to another component. Inherited components share any component methods or properties that they inherit from other components, and ColdFusion MX initializes instance data in the parent CFC when you instantiate the CFC that extends it.

When using component inheritance, inheritance should define an is a relationship between components. For example, a component named president.cfc inherits its methods and properties from manager.cfc, which inherits its methods and properties from employee.cfc. In other words, president.cfc is a manager.cfc; manager.cfc is an employee.cfc; and president.cfc is an employee.cfc.

In this example, employee.cfc is the base component; it’s the component upon which the others are based. The manager component extends the employee component; it has all the methods and properties of the employee component, and some additional ones. The president component extends the manager component. The president component is called a subcomponent or child component of the manager component, which, in turn, is a child component of the employee component.

To use component inheritance:

  1. Create the employee.cfc file with the following content:
    <cfcomponent>
    <cfset This.basesalary=40*20>
</cfcomponent>
  2. Create the manager.cfc file with the following content:
    <cfcomponent extends="employee">
    <cfset This.mgrBonus=40*10>
</cfcomponent>

    In the example, the cfcomponent tag’s extends attribute points to the employee component.

  3. Create the president.cfc file with the following content:
    <cfcomponent extends="manager">
    <cfset This.prezBonus=40*20>
</cfcomponent>

    In the example, the cfcomponent tag’s extends attribute points to the manager component.

  4. Create the inherit.cfm file with the following content, and save it in the same directory as the components you created in the previous steps:
    <cfobject name="empObj" component="employee">
<cfobject name="mgrObj" component="manager">
<cfobject name="prezObj" component="president">
<cfoutput>
    An employee's salary is #empObj.basesalary# per week.<br>
    A manager's salary is #mgrObj.basesalary + mgrObj.mgrBonus# per week.<br>
    A president's salalry is #prezObj.basesalary + prezObj.mgrBonus +
        prezObj.PrezBonus# per week.
</cfoutput>

When you browse the inherit.cfm file, the manager component refers to the basesalary defined in employee.cfc, which is the base component; the president component refers to both the basesalary defined in the employee component, and the mgrBonus defined in the manager component. The manager component is the parent class of the president component.

Using the component.cfc file

All CFCs automatically extend the ColdFusion WEB-INF/cftags/component.cfc component. (The WEB-INF directory is in the cf_root/wwwroot directory on ColdFusion configured with an embedded J2EE server. It is in the cf_root directory when you deploy ColdFusion on a J2EE server.) This CFC is distributed as a zero-length file. You can use it for any core methods or properties that you want all CFCs in your ColdFusion application server instance to inherit.

Note: If you install a newer version of ColdFusion, the installation procedure replaces the existing component.cfc file with a new version. Therefore, before upgrading to a new version of ColdFusion, you should save any code that you have added to the component.cfc file, and then copy the code into the new component.cfc file.

Using the Super keyword

You use the Super keyword only on CFCs that use the Extends attribute to extend another CFC. Unlike ColdFusion scopes, the Super keyword is not used for variables; it is only used for CFC methods, and it is not available on ColdFusion pages that invoke CFCs.

The Super keyword lets you refer to versions of methods that are defined in the CFC that the current component extends. For example, the employee, manager, and president CFCs each contain a getPaid method. The manager CFC extends the employee CFC. Therefore, the manager CFC can use the original versions of the overridden getPaid method, as defined in the employee CFC, by prefixing the method name with Super.

To use the Super keyword:

  1. Create the employee.cfc file with the following content:
    <cfcomponent>
    <cffunction name="getPaid" returntype="numeric">
        <cfset var salary=40*20>
        <cfreturn salary>
    </cffunction>
</cfcomponent>
  2. Create the manager.cfc file with the following content:
    <cfcomponent extends="employee">
    <cffunction name="getPaid" returntype="numeric">
        <cfset var salary=1.5 * Super.getPaid()>
        <cfreturn salary>
    </cffunction>
</cfcomponent>
  3. Create the president.cfc file with the following content:
    <cfcomponent extends="manager">
    <cffunction name="getPaid" returntype="numeric">
        <cfset var salary=1.5 * Super.getPaid()>
        <cfreturn salary>
    </cffunction>
</cfcomponent>
  4. Create the payday.cfm file with the following content, and save it in the same directory as the components that you created in the previous steps:
    <cfobject name="empObj" component="employee">
<cfobject name="mgrObj" component="manager">
<cfobject name="prezObj" component="president">
<cfoutput>
    <cfoutput>
        An employee earns #empObj.getPaid()#.<br>
        A manager earns #mgrObj.getPaid()#.<br>
        The president earns #prezObj.getPaid()#.
    </cfoutput>
</cfoutput>

In this example, each getPaid method in a child component invoked the getPaid method of its parent component. The child’s getPaid method then used the salary returned by the parent’s getPaid method to calculate the appropriate amount.

Included pages can use the Super keyword.

Note: The Super keyword supports only one level of inheritance. If you use multiple levels of inheritance, you can only use the Super keyword to access the current component’s immediate parent. The example in this section illustrates handling this limitation by invoking methods in a chain.


Using component packages

Components stored in the same directory are members of a component package. Component packages help prevent naming conflicts, and facilitate easy component deployment; for example:

  • ColdFusion searches the current directory first for a CFC. If you put two components in a single directory as a package, and one component refers to the other with only the component name, not a qualified path, ColdFusion always searches the package directory first for the component. As a result, if you structure each application’s components into a package, your applications can use the same component names without sharing the component code.
  • If you use the access="package" attribute in a method’s cffunction tag, access to the method is limited to components in the same package. Components in other packages cannot use this method, even if they specify it with a fully qualified component name. For more information on access security, see Using access security.

To invoke a packaged component method using the cfinvoke tag:

  1. In your web root directory, create a directory named appResources.
  2. In the appResources directory, create a directory named components.
  3. Copy the tellTime2.cfc file you created in Invoking methods of a CFC instance and the getUTCTime.cfm file that you created in Putting executable code in a separate file to the components directory.
  4. Create the timeDisplay.cfm file with the following content and save it in your web root directory:
    <!--- Create the component instance. --->
<cfobject component="appResources.components.tellTime2" name="tellTimeObj">
<!--- Invoke the methods. --->
<cfinvoke component="#tellTimeObj#" method="getLocalTime"
    returnvariable="localTime" >
<cfinvoke component="#tellTimeObj#" method="getUTCTime"
    returnvariable="UTCTime" >
<!--- Display the results. --->
<h3>Time Display Page</h3>
<cfoutput>
    Server's Local Time: #localTime#<br>
    Calculated UTC Time: #UTCTime#
</cfoutput>

    You use dot syntax to navigate directory structures. Place the directory name before the component name.

  5. Browse the timeDisplay.cfm file in your browser.

The following example shows a CFScript invocation:

<cfscript>
helloCFC = createObject("component", "appResources.components.catQuery");
helloCFC.getSaleItems();
</cfscript>

The following example shows a URL invocation:

http://localhost/appResources/components/catQuery.cfc?method=getSalesItems


Using CFCs in persistent scopes

You can put a CFC instance in the Session or Application scope. This way, the component properties continue to exist while the scope persists. For example, you might want to use a CFC for a shopping cart application, where the shopping cart contents must persist for the length of the user’s session. If you put the shopping cart CFC in the Session scope, you can use component properties to store the cart contents. For example, the following line creates an instance of the shoppingCart component in the Session scope:

<cfobject name="Session.myShoppingCart" component="shoppingCart">

Code that manipulates persistent scope CFC properties must be locked, just as all other code that manipulates persistent scope properties must be locked. Therefore, you must lock both of the following types of application code:

  • Code that directly manipulates properties of a persistent scope CFC instance
  • Code that calls methods of a persistent scope CFC instance that manipulate properties of the instance

If you put multiple CFC instances in a single persistent scope, you can create a named lock for each CFC instance. For more information on locking, see Using Persistent Data and Locking.

Note: Session scope CFCs cannot be serialized, so you cannot use them with clustered sessions; for example, if you want to support session failover among servers.


Building secure ColdFusion components

To restrict access to component methods, ColdFusion components use the following security features:

  • Access security
  • Role-based security
  • Programmatic security

Using access security

CFC access security lets you limit the code that can access the components. You specify the access to a CFC method by specifying the cffunction access attribute, as follows:

Type | Description
private | Available only to the component that declares the method and any components that extend the component in which it is defined. This usage is similar to the Java protected keyword, not the Java private keyword.
package | Available only to the component that declares the method, components that extend the component, or any other components in the package. A package consists of all components defined in a single directory. For more information on packages, see Using component packages.
public | Available to any locally executing ColdFusion page or component method.
remote | Available to a locally or remotely executing ColdFusion page or component method, or to a local or remote client through a URL, form submission, Flash Remoting MX, or as a web service.

Using role-based security

If you specify a roles attribute in a cffunction tag, only users who are logged in with one of the specified roles can execute the method. When a user tries to invoke a method that he or she is not authorized to invoke, an exception is returned.

The following example creates a component method that deletes files:

<cfcomponent>
    <cffunction
      name="deleteFile" access="remote" roles="admin,manager" output="no">
        <cfargument name="filepath" required="yes">
        <cffile action="DELETE" file=#arguments.filepath#>
    </cffunction>
</cfcomponent>

In the example, the cffunction tag includes the roles attribute to specify the user roles allowed to access it. In this example, only users in the role admin and manager can access the function. Notice that multiple roles are delimited by a comma.

For information on ColdFusion security, including the cflogin tag and role-based security in ColdFusion MX, see Securing Applications.

Using programmatic security

You can implement your own security within a method to protect resources. For example you can use the ColdFusion function IsUserInRole to determine if a user is in particular role, as the following example shows:

<cffunction name="foo">
    <cfif IsUserInRole("admin")>
        … do stuff allowed for admin
    <cfelseif IsUserInRole("user")>
        … do stuff allowed for user
    <cfelse>
        <cfoutput>unauthorized access</cfoutput>
        <cfabort>
    </cfif>
</cffunction>


Using introspection to get information about components

ColdFusion provides several ways for you to get information about components:

  • Requesting a component page from the browser
  • Using the ColdFusion component browser
  • Using the Dreamweaver MX 2004 component panel
  • Using the GetMetaData function

Development teams can use the information about components as up-to-date API reference information.

Note: For information about how to include documentation in CFCs for display using introspection, see Documenting CFCs.

Requesting a component page from the browser

When you access a CFC directly with a web browser without specifying a component method, the following chain of events occurs:

  1. The request is redirected to the cfcexplorer.cfc file, which is located in the cf_root/wwwroot/CFIDE/componentutils directory.
  2. The cfcexplorer component prompts users for the ColdFusion RDS or Administrator password, if necessary.
  3. The cfcexplorer component renders an HTML description and returns it to the browser.

The resulting display looks like the following example:

This is a picture of the feature being described.

tests.cfcs.arithCFC
Component arithCFC (Arithmetic Functions)

Miscellaneous functions for doing arithmetic

hierarchy: | WEB-INF.cftags.component tests.cfcs.arithCFC
path: | C:\cfmx\wwwroot\tests\cfcs\arithCFC.cfc
properties: | something
methods: | add, multiply *

* - private method

Property | Hint | Type | Req. | Implemented In | Default Value
Prop1 (display name here) | I just need this for an example | any |  | arithCFC | -

add (Addition Function)

remote numeric add ( numeric arg1, numeric arg2 )

Adds integers or floating point numbers

Output: enabled
Parameters:
arg1: numeric, optional, argument 1 - must be numeric
arg2: numeric, optional, arg2

multiply*

private numeric multiply ( numeric argA, numeric argB )

Output: enabled
Parameters:
argA: numeric, optional, argA
argB: numeric, optional, argB

This is a picture of the feature being described.


Using the ColdFusion component browser

You can also browse the components available in ColdFusion using the component browser, which is located at cf_root/wwwroot/CFIDE/componentutils/componentdoc.cfm.

The browser has three panes:

  • The upper-left pane lists all CFC packages that ColdFusion can access, and has all components and refresh links.
  • The lower-left pane lists CFC component names. When the browser first appears, or when you click the all components link in the upper pane, the lower pane lists all available components. If you click a package name in the upper left pane, the lower pane lists only the components in the package.
  • The right pane initially lists the paths of all components. When you click a component name in the lower-left pane, the right pane shows the ColdFusion introspection page, as described in Requesting a component page from the browser.


Using the Dreamweaver MX 2004 component panel

The Dreamweaver MX 2004 Components panel lists all available components, including their methods, method parameters, and properties. The panel’s context menu includes options to create a new component, edit the selected component, insert code to invoke the component, or show detailed information on the component or component element. The Get description option shows the ColdFusion introspection page, as described in Requesting a component page from the browser. For more information on viewing and editing CFCs in Dreamweaver MX 2004, see the Dreamweaver MX 2004 online help.


Using the GetMetaData function

The CFML GetMetaData function returns a structure that contains all the metadata of a CFC instance. This structure contains substantially more data about the CFC than the cfdump tag shows, and includes the following information:

  • All attributes to the component tag, including any metadata-only attributes, plus the component path.
  • An array of structures that contains complete information on each method (function) in the component. This information describes all attributes, including metadata-only function and parameter attributes.
  • Within each function structure, a Parameters element that contains an array of parameters specified by cfargument tags. Information on each parameter includes any metadata-only attributes.
  • Information about any properties that are specified using the cfproperty tag.

To display metadata for a CFC:

  1. Create the tellAboutCfcs.cfm file in the same directory as the telltime.cfc file, with the following code:
    <!--- Create an instance of the component. --->
<cfobject component="tellTime" name="tellTimeObj">
<!--- Create a new structure. --->
<cfset aboutcfc=structNew()>
<!--- Populate the structure with the metadata for the
            tellTimeObj instance of the tellTime CFC. --->
<cfset aboutcfc=GetMetaData(tellTimeObj)>
<cfdump var="aboutcfc">
  2. View the tellAboutCfcs.cfm file in a browser.

For information on how to specify CFC metadata, including how to use component tags and how to specify metadata-only attributes, see Documenting CFCs.


ColdFusion component example

A number of code examples in ColdFusion MX Developer’s Guide reuse code, particularly queries. To illustrate the advantages of CFCs, these examples invoke the appropriate method in the CFC that appears in the following example. Although Macromedia recommends using CFCs to create structured, reusable code, some code examples in this manual contain queries within a CFML page, rather than invoking a CFC, in order to clearly illustrate a particular element of ColdFusion.

<cfcomponent>
    <cffunction name="allemployees" access="public" output="false"
        returntype="query">
        <cfset var getNames="">
        <cfquery name="getNames" datasource="cfdocexamples">
            SELECT * FROM Employee
        </cfquery>
    </cffunction>

    <cffunction name="namesalarycontract" access="public" output="false"
        returntype="query">
        <cfset var EmpList="">
        <cfquery name="EmpList" datasource="cfdocexamples">
            SELECT Firstname, Lastname, Salary, Contract
            FROM Employee
        </cfquery>
    </cffunction>

    <cffunction name="fullname" access="public" output="false"
        returntype="query">
        <cfset var engquery="">
        <cfquery name="engquery" datasource="cfdocexamples">
            SELECT FirstName + ' ' + LastName AS FullName
            FROM Employee
        </cfquery>
    </cffunction>

    <cffunction name="bydept" access="public" output="false" returntype="query">
        <cfset var deptquery="">
        <cfquery name="deptquery" datasource="cfdocexamples">
            SELECT Dept_ID, FirstName + ' ' + LastName
            AS FullName
            FROM Employee
            ORDER BY Dept_ID
        </cfquery>
    </cffunction>

    <cffunction name="employeebyURLID" access="public" output="false"
        returntype="query">
        <cfset var GetRecordtoUpdate="">
        <cfquery name="GetRecordtoUpdate" datasource="cfdocexamples">
            SELECT * FROM Employee
            WHERE Emp_ID = #URL.Emp_ID#
        </cfquery>
    </cffunction>

    <cffunction name="deleteemployee" access="public" output="false"
        returntype="void">
        <cfset var DeleteEmployee="">
        <cfquery name="DeleteEmployee" datasource="cfdocexamples">
            DELETE FROM Employee
            WHERE Emp_ID = #Form.Emp_ID#
        </cfquery>
    </cffunction>

    <cffunction name="distinctlocs"  access="public" output="false"
        returntype="void">
        <cfset var GetDepartments="">
        <cfquery name="GetDepartments" datasource="cfdocexamples">
            SELECT DISTINCT Location
            FROM Departmt
        </cfquery>
    </cffunction>
</cfcomponent>
Previous


Creating and Using Custom CFML Tags

This chapter describes how to create and use custom CFML tags that encapsulate common code.

Contents

Creating custom tags

Passing data to custom tags

Managing custom tags

Executing custom tags

Nesting custom tags
Next


Creating custom tags

Custom tags let you extend CFML by adding your own tags to the ones supplied with ColdFusion. After you define a custom tag, you can use it on a ColdFusion page just as you would any of the standard CFML tags, such as cfquery and cfoutput.

You use custom tags to encapsulate your application logic so that it can be referenced from any ColdFusion page. Custom tags allow for rapid application development and code reuse while offering off-the-shelf solutions for many programming chores.

For example, you might create a custom tag, named cf_happybirthday, to generate a birthday message. You could then use that tag in a ColdFusion page, as follows:

<cf_happybirthday name="Ted Cantor" birthDate="December 5, 1987">

When ColdFusion processes the page containing this tag, it could output the message:

December 5, 1987 is Ted Cantor’s Birthday.
Please wish him well.

A custom tag can also have a body and end tag, for example:

<cf_happybirthdayMessge name="Ellen Smith" birthDate="June 8, 1993">
    <P> Happy Birthday Ellen!</P>
    <P> May you have many more!</P>
</cf_happybirthdayMessge>

This tag could output the message:

June 8, 1993 is Ellen Smith’s Birthday.
Happy Birthday Ellen!
May you have many more!

For more information about using end tags, see Handling end tags.

This section describes the following topics:

  • Creating and calling custom tags
  • Securing custom tags
  • Accessing existing custom tags


Creating and calling custom tags

You implement a custom tag with a single ColdFusion page. You then call the custom tag from a ColdFusion page by inserting the prefix cf_ before the page’s file name. The page referencing the custom tag is referred to as the calling page.

To create and call a custom tag:

  1. Create a ColdFusion page, the custom tag page, that shows the current date:
    <cfoutput>#DateFormat(Now())#</cfoutput>
  2. Save the file as date.cfm.
  3. Create a ColdFusion page, the calling page, with the following content:
    <html>
<head>
    <title>Date Custom Tag</title>
</head>
<body>

    <!--- Call the custom tag defined in date.cfm --->
    <cf_date>

</body>
</html>
  4. Save the file as callingdate.cfm.
  5. View callingdate.cfm in your browser.

    This custom tag returns the current date in the format DD-MMM-YY.

As you can see from this example, creating a custom tag in CFML is no different from writing any ColdFusion page. You can use all CFML constructs, as well as HTML. You are free to use any naming convention that fits your development practice. Unique descriptive names make it easy for you and others to find the right tag.

Note: Although tag names in ColdFusion pages are case-insensitive, custom tag filenames must be lowercase on UNIX.

Storing custom tag pages

You must store custom tag pages in any one of the following:

  • The same directory as the calling page
  • The cfusion\CustomTags directory
  • A subdirectory of the cfusion\CustomTags directory
  • A directory that you specify in the ColdFusion MX Administrator

To share a custom tag among applications in multiple directories, place it in the cfusion\CustomTags directory. You can create subdirectories to organize custom tags. ColdFusion searches recursively for the Custom Tags directory, stepping down through any existing subdirectories until the custom tag is found.

You might have a situation where you have multiple custom tags with the same name. To guarantee which tag ColdFusion calls, copy it to the same directory as the calling page. Or, use the cfmodule tag with the template attribute to specify the absolute path to the custom tag. For more information on cfmodule, see the next section.

Calling custom tags using the cfmodule tag

You can also use the cfmodule tag to call custom tags if you want to specify the location of the custom tag page. The cfmodule tag is useful if you are concerned about possible name conflicts when invoking a custom tag, or if the application must use a variable to dynamically call a custom tag at runtime.

You must use either a template or name attribute in the tag, but you cannot use both. The following table describes the basic cfmodule attributes:

Attribute

Description

template

Required if the name attribute is not used. Same as the template attribute in cfinclude. This attribute:

  • Specifies a path relative to the directory of the calling page.
  • If the path value is prefixed with "/", ColdFusion searches directories explicitly mapped in the ColdFusion MX Administrator for the included file.

Example: <cfmodule template="../MyTag.cfm"> identifies a custom tag file in the parent directory.

name

Required if the template attribute is not used. Use period-separated names to uniquely identify a subdirectory under the CustomTags root directory.

Example: <cfmodule name="MyApp.GetUserOptions"> identifies the file GetUserOptions.cfm in the CustomTags\MyApp directory under the ColdFusion root directory.

attributes

The custom tag's attributes.

For example, the following code specifies to execute the custom tag defined by the mytag.cfm page in the parent directory of the calling page:

<cfmodule template="../mytag.cfm">

For more information on using the cfmodule tag, see CFML Reference.

Calling custom tags using the cfimport tag

You can use the cfimport tag to import custom tags from a directory as a tag library. The following example imports the tags from the directory myCustomTags:

<cfimport prefix="mytags" taglib="myCustomTags">

Once imported, you call the custom tags using the prefix that you set when importing, as the following example shows:

<mytags:customTagName>

where customTagName corresponds to a ColdFusion application page named customTagName.cfm. If the tag takes attributes, you include them in the call:

<mytags:custom_tag_name attribute1=val_1 attribute2=val_2>

You can also include end tags when calling your custom tags, as the following example shows:

<mytags:custom_tag_name attribute1=val_1 attribute2=val_2>
...
</mytags:custom_tag_name>

ColdFusion calls the custom tag page twice for a tag that includes an end tag: once for the start tag and once for the end tag. For more information on how ColdFusion handles end tags, and how to write your custom tags to handle them, see Handling end tags.

One of the advantages to using the cfimport tag is that you can define a directory structure for your custom tags to organize them by category. For example, you can put all security tags in one directory, and all interface tags in another. You then import the tags from each directory and give them a different prefix:

<cfimport prefix="security" taglib="securityTags">
<cfimport prefix="ui" taglib="uiTags">
...
<security:validateUser name="Bob">
...
<ui:greeting name="Bob">
...

Reading your code becomes easier because you can identify the location of your custom tags from the prefix.


Securing custom tags

The ColdFusion security framework enables you to selectively restrict access to individual tag files and tag directories. This can be an important safeguard in team development. For details, see Configuring and Administering ColdFusion MX.


Accessing existing custom tags

Before creating a custom tag in CFML, you should review the Custom Tag section of the ColdFusion Developer Exchange at http://devex.macromedia.com/developer/gallery/index.cfm. You might find a tag here that does what you want.

Tags are grouped in several broad categories and are downloadable as freeware, shareware, or commercial software. You can view each tag’s syntax and usage information. The gallery contains a wealth of background information on custom tags and an online discussion forum for tag topics.

Tag names with the cf_ preface are CFML custom tags; those with the cfx_ preface are ColdFusion extensions written in C++. For more information about the CFX tags, see Building Custom CFXAPI Tags.

If you do not find a tag that meets your specific needs, you can create your own custom tags in CFML.


Passing data to custom tags

To make your custom tags flexible, you will often want to pass data to them for processing. This section describes how to write custom tags that take tag attributes and other data as input from a calling page.

  • Passing values to and from custom tags
  • Using tag attributes summary
  • Custom tag example with attributes
  • Passing custom tag attributes using CFML structures

Passing values to and from custom tags

Because custom tags are individual ColdFusion pages, variables and other data are not automatically shared between a custom tag and the calling page. To pass data from the calling page to the custom tag, you can specify attribute name/value pairs in the custom tag, just as you do for normal HTML and CFML tags.

For example, to pass the value of the NameYouEntered variable to the cf_getmd tag, you can call the custom tag as follows:

<cf_getmd Name=#NameYouEntered#>

To pass multiple attributes to a custom tag, separate them with a space in the tag as follows:

<cf_mytag Firstname="Thadeus" Lastname="Jones">

In the custom tag, you use the Attributes scope to access attributes passed to the tag. Therefore, in the getmd.cfm page, you refer to the passed attribute as Attributes.Name. The mytag.cfm custom tag page refers to the passed attributes as Attributes.Firstname and Attributes.Lastname.

The custom tag page can also access variables set in the calling page by prefixing the calling page’s local variable with Caller. However, this is not the best way to pass information to a custom tag, because each calling page would be required to create variables with the names required by the custom tag. You can create more flexible custom tags by passing parameters using attributes.

Variables created within a custom tag are deleted when the processing of the tag terminates. Therefore, if you want to pass information back to the calling page, you must write that information back to the Caller scope of the calling page. You cannot access the custom tag’s variables outside the custom tag itself.

For example, use the following code in the getmd.cfm page to set the variable Doctor on the calling page:

<cfset Caller.Doctor="Doctor " & Attributes.Name>

If the variable Doctor does not exist in the calling page, this statement creates it. If the variable exists, the custom tag overwrites it.

The following figure shows the relationship between the variables on the calling page and the custom tag:

The relationship between variables in the calling page and the custom tag

One common technique used by custom tags is for the custom tag to take as input an attribute containing the name of the variable to use to pass back results. For example, the calling page passes returnHere as the name of the variable to use to pass back results:

<cf_mytag resultName="returnHere">

In mytag.cfm, the custom tag passes back its results using the following code:

<cfset "Caller.#Attributes.resultName#" = result>

Tip: Be careful not to overwrite variables in the calling page from the custom tag. You should adopt a naming convention to minimize the chance of overwriting variables. For example, prefix the returned variable with customtagname_, where customtagname is the name of the custom tag.

Note: Data pertaining to the HTTP request or to the current application is visible in the custom tag page. This includes the variables in the Form, Url, Cgi, Request, Cookies, Server, Application, Session, and Client scopes.


Using tag attributes summary

Custom tag attribute values are passed from the calling page to the custom tag page as name-value pairs. CFML custom tags support required and optional attributes. Custom tag attributes conform to the following CFML coding standards:

  • ColdFusion passes any attributes in the Attributes scope.
  • Use the Attributes.attribute_name syntax when referring to passed attributes to distinguish them from custom tag page local variables.
  • Attributes are case-insensitive.
  • Attributes can be listed in any order within a tag.
  • Attribute name-value pairs for a tag must be separated by a space in the tag invocation.
  • Passed values that contain spaces must be enclosed in double-quotation marks.
  • Use the cfparam tag with a default attribute at the top of a custom tag to test for and assign defaults for optional attributes that are passed from a calling page. For example:
    <!--- The value of the variable Attributes.Name comes from the calling page. If
    the calling page does not set it, make it "Who". --->
<cfparam name="Attributes.Name" default="Who">
  • Use the cfparam tag or a cfif tag with an IsDefined function at the top of a custom tag to test for required attributes that must be passed from a calling page; for example, the following code issues an abort if the user does not specify the Name attribute to the custom tag:
    <cfif not IsDefined("Attributes.Name")>
    <cfabort showError="The Name attribute is required.">
</cfif>


Custom tag example with attributes

The example in this section creates a custom tag that uses an attribute that is passed to it to set the value of a variable called Doctor on the calling page.

To create a custom tag:

  1. Create a new ColdFusion page (the calling page) with the following content:
    <html>
<head>
    <title>Enter Name</title>
</head>
<body>
<!--- Enter a name, which could also be done in a form --->
<!--- This example simply uses a cfset --->
<cfset NameYouEntered="Smith">

<!--- Display the current name --->
<cfoutput>
Before you leave this page, you're #Variables.NameYouEntered#.<br>
</cfoutput>

<!--- go to the custom tag --->
<cf_getmd Name="#NameYouEntered#">
<!--- Come back from the Custom tag --->

<!--- display the results of the custom tag --->
<cfoutput>
You are now #Variables.Doctor#.<br>
</cfoutput>
</body>
</html>
  2. Save the page as callingpage.cfm.
  3. Create another new page (the custom tag) with the following content:
    <!--- The value of the variable Attributes.Name comes from the calling page.
      If the calling page does not set it, make it "Who". --->
<cfparam name="Attributes.Name" default="Who">

<!--- Create a variable called Doctor, make its value "Doctor "
         followed by the value of the variable Attributes.Name.
         Make its scope Caller so it is passed back to the calling page
--->
<cfset Caller.Doctor="Doctor " & Attributes.Name>
  4. Save the page as getmd.cfm.
  5. Open the file callingpage.cfm in your browser.

The calling page uses the getmd custom tag and displays the results.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfset NameYouEntered="Smith">

In the calling page, create a variable NameYouEntered and assign it the value "Smith."

<cfoutput>
Before you leave this page, you're
    #Variables.NameYouEntered#.<br>
</cfoutput>

In the calling page, display the value of the NameYouEntered variable before calling the custom tag.

<cf_getmd Name="#NameYouEntered#">

In the calling page, call the getmd custom tag and pass it the Name attribute whose value is the value of the local variable NameYouEntered.

<cfparam name="Attributes.Name" default="Who">

The custom tag page normally gets the Name variable in the Attributes scope from the calling page. Assign it the value "Who" if the calling page did not pass an attribute.

<cfset Caller.Doctor="Doctor " & Attributes.Name>

In the custom tag page, create a variable called Doctor in the Caller scope so it will exist in the calling page as a local variable.

Set its value to the concatenation of the string "Doctor" and the value of the Attributes.Name variable.

<cfoutput>
You are now #Variables.Doctor#.<br>
</cfoutput>

In the calling page, display the value of the Doctor variable returned by the custom tag page. (This example uses the Variables scope prefix to emphasize the fact that the variable is returned as a local variable.)


Passing custom tag attributes using CFML structures

You can use the reserved attribute attributecollection to pass attributes to custom tags using a structure. The attributecollection attribute must reference a structure containing the attribute names as the keys and the attribute values as the values. You can freely mix attributecollection with other attributes when you call a custom tag.

The key-value pairs in the structure specified by the attributecollection attribute get copied into the custom tag page’s Attributes scope. This has the same effect as specifying the attributecollection entries as individual attributes when you call the custom tag. The custom tag page refers to the attributes passed using attributecollection the same way as it does other attributes; for example, as Attributes.CustomerName or Attributes.Department_number.

Note: You can use both tag attributes and attributecollections. If you pass an attribute with the same name using both methods, ColdFusion passes only the tag attribute to the custom tag and ignores the corresponding attribute from the attribute collection.

Custom tag processing reserves the attributecollection attribute to refer to the structure holding a collection of custom tag attributes. If attributecollection does not refer to such a collection, ColdFusion generates a template exception.

The following example uses an attributecollection attribute to pass two of four attributes:

<cfset zort=StructNew()>
<cfset zort.x = "-X-">
<cfset zort.y = "-Y-">
<cf_testtwo a="blab" attributecollection=#zort# foo="16">

If testtwo.cfm contains the following code:

---custom tag ---<br>
<cfoutput>#attributes.a# #attributes.x# #attributes.y#
    #attributes.foo#</cfoutput><br>
--- end custom tag ---

its output is the following statement:

---custom tag ---
blab -X- -Y- 16
--- end custom tag ---

One use for attributecollection is to pass the entire Attributes scope of one custom tag to another. This often happens when you have one custom tag that calls a second custom tag and you want to pass all attributes from the first tag to the second.

For example, you call a custom tag with the following code:

<cf_first attr1="foo" attr2="bar">

To pass all the attributes of the first custom tag to the second, you include the following statement in first.cfm:

<cf_second attributecollection="#attributes#">

Within the body of second.cfm, you reference the parameters passed to it as follows:

<cfoutput>#attributes.attr1#</cfoutput>
<cfoutput>#attributes.attr2#</cfoutput>


Managing custom tags

If you deploy custom tags in a multideveloper environment or distribute your tags publicly, you can use the following additional ColdFusion capabilities:

  • Advanced security
  • Template encoding

Securing custom tags

The ColdFusion security framework enables you to selectively restrict access to individual tags or to tag directories. This can be an important safeguard in team development. For more information, see Securing Applications.

Compiling custom tags

You can use the command-line utility cfcompile to precompile your custom tag files into Java class files or byte code. For more information, see Using the cfcompile utility in Deploying ColdFusion Applications of Configuring and Administering ColdFusion MX.


Executing custom tags

The following sections provide information about executing custom tags, including information about handling end tags and processing body text.

  • Accessing tag instance data
  • Handling end tags
  • Processing body text
  • Terminating tag execution

Accessing tag instance data

When a custom tag page executes, ColdFusion keeps data related to the tag instance in the thisTag structure. You can access the thisTag structure from within your custom tag to control processing of the tag. The behavior is similar to the File tag-specific variable (sometimes called the File scope).

ColdFusion generates the variables in the following table and writes them to the thisTag structure:

Variable

Description

ExecutionMode

Contains the execution mode of the custom tag. Valid values are "start", "end", and "inactive".

HasEndTag

Distinguishes between custom tags that are called with and without end tags. Used for code validation. If the user specifies an end tag, HasEndTag is set to True; otherwise, it is set to False.

GeneratedContent

The content that has been generated by the tag. This includes anything in the body of the tag, including the results of any active content, such as ColdFusion variables and functions. You can process this content as a variable.

AssocAttribs

Contains the attributes of all nested tags if you use cfassociate to make them available to the parent tags. For more information, see High-level data exchange.

The following example accesses the ExecutionMode variable of the thisTag structure from within a custom tag:

<cfif thisTag.ExecutionMode is 'start'>


Handling end tags

The examples of custom tags shown so far in this chapter all reference a custom tag using just a start tag, as in:

<cf_date>

In this case, ColdFusion calls the custom tag page date.cfm to process the tag.

However, you can create custom tags that have both a start and an end tag. For example, the following tag has both a start and an end tag:

<cf_date>
    ...
</cf_date>

ColdFusion calls the custom tag page date.cfm twice for a tag that includes an end tag: once for the start tag and once for the end tag. As part of the date.cfm page, you can determine if the call is for the start or end tag, and perform the appropriate processing.

ColdFusion will also call the custom tag page twice if you use the shorthand form of an end tag:

<cf_date/>

You can also call a custom tag using the cfmodule tag, as shown in the following example:

<cfmodule ...>
    ...
</cfmodule>

If you specify an end tag to cfmodule, then ColdFusion calls your custom tag as if it had both a start and an end tag.

Determining if an end tag is specified

You can write a custom tag that requires users to include an end tag. If a tag must have an end tag provided, you can use thisTag.HasEndTag in the custom tag page to verify that the user included the end tag.

For example, in date.cfm, you could include the following code to determine whether the end tag is specified:

<cfif thisTag.HasEndTag is 'False'>
    <!--- Abort the tag--->
    <cfabort showError="An end tag is required.">
</cfif>

Determining the tag execution mode

The variable thisTag.ExecutionMode contains the mode of invocation of a custom tag page. The variable has one of the following values:

  • Start Mode for processing the start tag.
  • End Mode for processing the end tag.
  • Inactive Mode when the custom tag uses nested tags. For more information, see Nesting custom tags.

If an end tag is not explicitly provided, ColdFusion invokes the custom tag page only once, in Start mode.

A custom tag page named bold.cfm that makes text bold could be written as follows:

<cfif thisTag.ExecutionMode is 'start'>
    <!--- Start tag processing --->
    <B>
<cfelse>
    <!--- End tag processing --->
    </B>
</cfif>

You then use this tag to convert the text to bold:

<cf_bold>This is bold text</cf_bold>

You can also use cfswitch to determine the execution mode of a custom tag:

<cfswitch expression=#thisTag.ExecutionMode#>
    <cfcase value= 'start'>
        <!--- Start tag processing --->
    </cfcase>
    <cfcase value='end'>
        <!--- End tag processing --->
    </cfcase>
</cfswitch>

Considerations when using end tags

How you code your custom tag to divide processing between the start tag and end tag is greatly dependent on the function of the tag. However, you can use the following rules to help you make your decisions:

  • Use the start tag to validate input attributes, set default values, and validate the presence of the end tag if it is required by the custom tag.
  • Use the end tag to perform the actual processing of the tag, including any body text passed to the tag between the start and end tags. For more information on body text, see Processing body text.
  • Perform output in either the start or end tag; do not divide it between the two tags.


Processing body text

Body text is any text that you include between the start and end tags when you call a custom tag; for example:

<cf_happybirthdayMessge name="Ellen Smith" birthDate="June, 8, 1993">
    <P> Happy Birthday Ellen!</P>
    <P> May you have many more!</P>
</cf_happybirthdayMessge>

In this example, the two lines of code after the start tag are the body text.

You can access the body text within the custom tag using the thisTag.GeneratedContent variable. The variable contains all body text passed to the tag. You can modify this text during processing of the tag. The contents of the thisTag.GeneratedContent variable are returned to the browser as part of the tag’s output.

The thisTag.GeneratedContent variable is always empty during the processing of a start tag. Any output generated during start tag processing is not considered part of the tag’s generated content.

A custom tag can access and modify the generated content of any of its instances using the thisTag.GeneratedContent variable. In this context, the term generated content means the results of processing the body of a custom tag. This includes all text and HTML code in the body, the results of evaluating ColdFusion variables, expressions, and functions, and the results generated by descendant tags. Any changes to the value of this variable result in changes to the generated content.

As an example, consider a tag that comments out the HTML generated by its descendants. Its implementation could look like this:

<cfif thisTag.ExecutionMode is 'end'>
    <cfset thisTag.GeneratedContent ='<!--#thisTag.GeneratedContent#-->'>
</cfif>


Terminating tag execution

Within a custom tag, you typically perform error checking and parameter validation. As part of those checks, you can choose to abort the tag, using cfabort, if a required attribute is not specified or other severe error is detected.

The cfexit tag also terminates execution of a custom tag. However, the cfexit tag is designed to give you more flexibility when coding custom tags than cfabort. The cfexit tag’s method attribute specifies where execution continues. The cfexit tag can specify that processing continues from the first child of the tag or continues immediately after the end tag marker.

You can also use the method attribute to specify that the tag body executes again. This enables custom tags to act as high-level iterators, emulating cfloop behavior.

The following table summarizes cfexit behavior:

Method attribute value | Location of cfexit call | Behavior
ExitTag (default) | Base page | Acts like cfabort
 | ExecutionMode=start | Continue after end tag
 | ExecutionMode=end | Continue after end tag
ExitTemplate | Base page | Acts like cfabort
 | ExecutionMode=start | Continue from first child in body
 | ExecutionMode=end | Continue after end tag
Loop | Base page | Error
 | ExecutionMode=start | Error
 | ExecutionMode=end | Continue from first child in body


Nesting custom tags

A custom tag can call other custom tags from within it’s body text, thereby nesting tags. ColdFusion uses nested tags such as cfgraph and cfgraphdata, cfhttp and cfhttpparam, and cftree and cftreeitem. The ability to nest tags allows you to provide similar functionality.

The following example shows a cftreeitem tag nested within a cftree tag:

<cftree name="tree1"
    required="Yes"
    hscroll="No">
    <cftreeitem value=fullname
        query="engquery"
        queryasroot="Yes"
        img="folder,document">
</cftree>

The calling tag is known as an ancestor, parent, or base tag, while the tags that ancestor tags call are known as descendant, child, or sub tags. Together, the ancestor and all descendant tags are called collaborating tags.

In order to nest tags, the parent tag must have a closing tag.

The following table lists the terms that describe the relationships between nested tags:

Calling tag | Tag nested within the calling tag | Description
Ancestor | Descendant | An ancestor is any tag that contains other tags between its start and end tags. A descendant is any tag called by a tag.
Parent | Child | Parent and child are synonyms for ancestor and descendant.
Base tag | Sub tag | A base tag is an ancestor that you explicitly associate with a descendant, called a sub tag, with cfassociate.

You can create multiple levels of nested tags. In this case, the sub tag becomes the base tag for its own sub tags. Any tag with an end tag present can be an ancestor to another tag.

Nested custom tags operate through three modes of processing, which are exposed to the base tags through the variable thisTag.ExecutionMode:

  • The start mode, in which the base tag is processed for the first time.
  • The inactive mode, in which sub tags and other code contained within the base tag are processed. No processing occurs in the base tag during this phase.
  • The end mode, in which the base tag is processed a second time. The end mode occurs when ColdFusion reaches the custom tag’s end tag.

This section describes the following topics:

  • Passing data between nested custom tags
  • Variable scopes and special variables
  • High-level data exchange


Passing data between nested custom tags

A key custom tag feature is for collaborating custom tags to exchange complex data without user intervention, while encapsulating each tag’s implementation so that others cannot see it.

When you decide to you use nested tags, you must address the following issues:

  • What data should be accessible?
  • Which tags can communicate to which tags?
  • How are the source and targets of the data exchange identified?
  • What CFML mechanism is used for the data exchange?

What data is accessible?

To enable developers to obtain maximum productivity in an environment with few restrictions, CFML custom tags can expose all their data to collaborating tags.

When you develop custom tags, you should document all variables that collaborating tags can access and/or modify. When your custom tags collaborate with other custom tags, you should make sure that they do not modify any undocumented data.

To preserve encapsulation, put all tag data access and modification operations into custom tags. For example, rather than documenting that the variable MyQueryResults in a tag's implementation holds a query result and expecting users to manipulate MyQueryResults directly, create a nested custom tag that manipulates MyQueryResult. This protects the users of the custom tag from changes in the tag's implementation.


Variable scopes and special variables

Use the Request scope for variables in nested tags. The Request scope is available to the base page, all pages it includes, all custom tag pages it calls, and all custom tag pages called by the included pages and custom tag pages. Collaborating custom tags that are not nested in a single tag can exchange data using the request structure. The Request scope is represented as a structure named Request.

Where is data accessible?

Two custom tags can be related in a variety of ways in a page. Ancestor and descendant relationships are important because they relate to the order of tag nesting.

A tag’s descendants are inactive while the page is executed; that is, the descendent tags have no instance data. A tag, therefore, can only access data from its ancestors, not its descendants. Ancestor data is available from the current page and from the whole runtime tag context stack. The tag context stack is the path from the current tag element up the hierarchy of nested tags, including those in included pages and custom tag references, to the start of the base page for the request. Both cfinclude tags and custom tags appear on the tag context stack.


High-level data exchange

While the ability to create nested custom tags is a tremendous productivity gain, keeping track of complex nested tag hierarchies can become a chore. The cfassociate tag lets the parent know what the children are up to. By adding this tag to a sub tag, you enable communication of its attributes to the base tag.

In addition, there are many cases in which descendant tags are used only as a means for data validation and exchange with an ancestor tag, such as cfhttp/cfhttpparam and cftree / cftreeitem. You can use the cfassociate tag to encapsulate this processing.

The cfassociate tag has the following format:

<cfassociate baseTag="tagName" dataCollection="collectionName">

The baseTag attribute specifies the name of the base tag that gets access to this tag’s attributes. The dataCollection attribute specifies the name of the structure in which the base tag stores the sub-tag data. Its default value is AssocAttribs. You only need to specify a dataCollection attribute if the base tag can have more than one type of subtag. It is convenient for keeping separate collections of attributes, one per tag type.

Note: If the custom tag requires an end tag, the code processing the structure referenced by the dataCollection attribute must be part of end-tag code.

When cfassociate is encountered in a sub tag, the sub tag’s attributes are automatically saved in the base tag. The attributes are in a structure appended to the end of an array whose name is thisTag.collectionName.

The cfassociate tag performs the following operations:

<!--- Get base tag instance data --->
<cfset data = getBaseTagData(baseTag)>
<!--- Create a string with the attribute collection name --->
<cfset collection_Name = "data.#dataCollection#">
<!--- Create the attribute collection, if necessary --->
<cfif not isDefined(collectionName)>
    <cfset #collection_Name# = arrayNew(1)>
</cfif>
<!--- Append the current attributes to the array --->
<cfset temp=arrayAppend(evaluate(collectionName), attributes)>

The code accessing sub-tag attributes in the base tag could look like the following:

<!--- Protect against no sub-tags --->
<cfparam Name='thisTag.assocAttribs' default=#arrayNew(1)#>

<!--- Loop over the attribute sets of all sub tags --->
<cfloop index=i from=1 to=#arrayLen(thisTag.assocAttribs)#>

    <!--- Get the attributes structure --->
    <cfset subAttribs = thisTag.assocAttribs[i]>
    <!--- Perform other operations --->

</cfloop>

Ancestor data access

The ancestor’s data is represented by a structure object that contains all the ancestor’s data.

The following functions provide access to ancestral data:

  • GetBaseTagList () Returns a comma-delimited list of uppercase ancestor tag names, as a string. The first list element is the current tag, the next element is the parent tag name if the current tag is a nested tag. If the function is called for a top-level tag, it returns an empty string.
  • GetBaseTagData (TagName, InstanceNumber=1) Returns an object that contains all the variables (not just the local variables) of the nth ancestor with a given name. By default, the closest ancestor is returned. If there is no ancestor by the given name, or if the ancestor does not expose any data (such as cfif), an exception is thrown.

Example: ancestor data access

This example creates two custom tags and a simple page that calls each of the custom tags. The first custom tag calls the second. The second tag reports on its status and provides information about its ancestors.

To create the calling page:

  1. Create a ColdFusion page (the calling page) with the following content:
    Call cf_nesttag1 which calls cf_nesttag2<br>
<cf_nesttag1>
<hr>

Call cf_nesttag2 directly<br>
<cf_nesttag2>
<hr>
  2. Save the page as nesttest.cfm.

To create the first custom tag page:

  1. Create a ColdFusion page with the following content:
    <cf_nesttag2>
  2. Save the page as nesttag1.cfm.

To create the second custom tag page:

  1. Create a ColdFusion page with the following content:
    <cfif thisTag.executionmode is 'start'>
    <!--- Get the tag context stack. The list will look something like
    "MYTAGNAME, CALLINGTAGNAME, ..." --->
    <cfset ancestorlist = getbasetaglist()>

    <!--- Output your own name. You are the first entry in the context stack. --->
    <cfoutput>
    <p>I'm custom tag #ListGetAt(ancestorlist,1)#</p>

    <!--- output all the contents of the stack a line at a time --->
    <cfloop index="loopcount" from="1" to="#listlen(ancestorlist)#">
    Ancestorlist entry #loopcount# n is #ListGetAt(ancestorlist,loopcount)#<br>
    </cfloop><br>
    </cfoutput>

    <!--- Determine whether you are nested inside a custom tag. Skip the first
    element of the ancestor list, i.e., the name of the custom tag I'm in --->
    <cfset incustomtag = ''>
    <cfloop index="elem"
        list="#listrest(ancestorlist)#"
        <cfif (left(elem, 3) eq 'cf_')>
            <cfset incustomtag = elem>
            <cfbreak>
        </cfif>
    </cfloop>

    <cfif incustomtag neq ''>
        <!--- Say you are there --->
        <cfoutput>
            I'm running in the context of a custom
            tag named #inCustomTag#.<p>
        </cfoutput>

        <!--- Get the tag instance data --->
        <cfset tagdata = getbasetagdata(incustomtag)>

        <!--- Find out the tag's execution mode --->
        I'm located inside the
        <cfif tagdata.thisTag.executionmode neq 'inactive'>
            custom tag code either because it is in
            its start or end execution mode.
        <cfelse>
            body of the tag
        </cfif>
        <p>
    <cfelse>
        <!--- Say you are lonely --->
        I'm not nested inside any custom tags. :^( <p>
    </cfif>
</cfif>
  2. Save the page as nesttag2.cfm.
  3. Open the file nesttest.cfm in your browser.

Previous


Building Custom CFXAPI Tags

Sometimes, the best approach to application development is to develop elements of your application by building executables to run with Macromedia ColdFusion. Perhaps the application requirements go beyond what is currently feasible in CFML. Perhaps you can improve application performance for certain types of processing. Or, you have existing code that already solves an application problem and you want to incorporate it into your ColdFusion application.

To meet these types of requirements, you can use the ColdFusion Extension Application Programming Interface (CFX API) to develop custom ColdFusion tags. This chapter documents custom tag development using Java or C++.

Contents

What are CFX tags?

Before you begin developing CFX tags in Java

Writing a Java CFX tag

ZipBrowser example

Approaches to debugging Java CFX tags

Developing CFX tags in C++
Next


What are CFX tags?

ColdFusion Extension (CFX) tags are custom tags written against the ColdFusion Extension Application Programming Interface. Generally, you create a CFX tag if you want to do something that is not possible in CFML, or if you want to improve the performance of a repetitive task.

One common use of CFX tags is to incorporate existing application functionality into a ColdFusion application. That means if you already have the code available, CFX tags make it easy to use it in your application.

CFX tags can do the following:

  • Handle any number of custom attributes.
  • Use and manipulate ColdFusion queries for custom formatting.
  • Generate ColdFusion queries for interfacing with non-ODBC based information sources.
  • Dynamically generate HTML to be returned to the client.
  • Set variables within the ColdFusion application page from which they are called.
  • Throw exceptions that result in standard ColdFusion error messages.

You can build CFX tags using C++ or Java.

Note: ColdFusion MX provides several different techniques to create reusable code, including custom tags. For information on all of these techniques, see Creating ColdFusion Elements.


Before you begin developing CFX tags in Java

Before you begin developing CFX tags in Java, you must configure your Java development environment. Also, you might want to take a look at some examples before creating your own CFX tags. This section contains information about examples and how to configure your development environment.

This section describes the following topics:

  • Sample C++ CFX tags
  • Setting up your development environment to develop CFX tags in Java
  • Customizing and configuring Java

Sample Java CFX tags

Before you begin developing a CFX tag in Java, you might want to study sample CFX tags. You can find the Java source files for the examples on Windows in the cfx\java\distrib\examples subdirectory of the main installation directory. On UNIX systems, the files are located in the cfx/java/examples directory. The following table describes the example tags:

Example

Action

Demonstrates

HelloColdFusion

Prints a personalized greeting.

The minimal implementation required to create a CFX tag.

ZipBrowser

Retrieves the contents of a zip archive.

How to generate a ColdFusion query and return it to the calling page.

ServerDateTime

Retrieves the date and time from a network server.

Attribute validation, using numeric attributes, and setting variables within the calling page.

OutputQuery

Returns a ColdFusion query in an HTML table.

How to handle a ColdFusion query as input, throw exceptions, and generate dynamic output.

HelloWorldGraphic

Generates a "Hello World!" graphic in JPEG format.

How to dynamically create and return graphics from a Java CFX tag.


Setting up your development environment to develop CFX tags in Java

You can use a wide range of Java development environments, including the Java Development Kit (JDK) from Sun, to build Java CFX tags. You can download the JDK from Sun http://java.sun.com/j2se.

Macromedia recommends that you use one of the commercial Java IDEs, so you have an integrated environment for development, debugging, and project management.

Configuring the classpath

To configure your development environment to build Java CFX tags, you must ensure that the supporting classes are visible to your Java compiler. These classes are located in the cfx.jar archive, located in one of the following directories:

Server configuration cf_root/wwwroot/WEB-INF/lib

J2EE configuration cf_webapp_root/WEB-INF/lib

Consult your Java development tool documentation to determine how to configure the compiler classpath for your particular environment.

The cfx.jar archive contains the classes in the com.allaire.cfx package, which are required for developing and deploying Java CFX tags.

When you create new Java CFX tags, you should compile them into the WEB-INF/classes directory. Doing this simplifies your development, debugging, and testing processes.

After you finish with development and testing, you can deploy your Java CFX tag anywhere on the classpath visible to ColdFusion. For more details on customizing the classpath, see Customizing and configuring Java.


Customizing and configuring Java

Use the JVM and Java Settings page on the ColdFusion MX Administrator Server tab to customize your Java development environment, such as by customizing the classpath and Java system properties, or specifying an alternate JVM. For more information, see the ColdFusion MX Administrator online Help.


Writing a Java CFX tag

To create a Java CFX tag, create a class that implements the Custom tag interface. This interface contains one method, processRequest, which is passed Request and Response objects that are then used to do the work of the tag.

The example in the following procedure creates a very simple Java CFX tag named cfx_MyHelloColdFusion that writes a text string back to the calling page.

To create a Java CFX tag:

  1. Create a new source file in your editor with the following code:
    import com.allaire.cfx.* ;

public class MyHelloColdFusion implements CustomTag {
   public void processRequest( Request request, Response response )
        throws Exception {
        String strName = request.getAttribute( "NAME" ) ;
        response.write( "Hello, " + strName ) ;
   }
}
  2. Save the file as MyHelloColdFusion.java in the WEB_INF/classes directory.
  3. Compile the java source file into a class file using the Java compiler. If you are using the command-line tools bundled with the JDK, use the following command line, which you execute from within the classes directory:
    javac -classpath cf_root\WEB-INF\lib\cfx.jar MyHelloColdFusion.java

    Note: The previous command works only if the Java compiler (javac.exe) is in your path. If it is not in your path, specify the fully qualified path; for example, c:\jdk1.3.1_01\bin\javac on Windows or /usr/java/bin/javac on UNIX.

If you receive errors during compilation, check the source code to make sure you entered it correctly. If no errors occur, you successfully wrote your first Java CFX tag. For information on using your new tag in a ColdFusion page, see Calling the CFX tag from a ColdFusion page.

This section describes the following topics:

  • Calling the CFX tag from a ColdFusion page
  • Processing requests
  • Life cycle of Java CFX tags


Calling the CFX tag from a ColdFusion page

You call Java CFX tags from within ColdFusion pages by using the name of the CFX tag that is registered on the ColdFusion MX Administrator CFX tags page. This name should be the prefix cfx_ followed by the class name (without the .class extension).

To register a Java CFX tag in the ColdFusion MX Administrator:

  1. In the ColdFusion MX Administrator, select Extensions > CFX Tags to open the CFX Tags page.
  2. Click Register Java CFX.
  3. Enter the tag name (for example, cfx_MyHelloColdFusion).
  4. Enter the class name without the .class extension (for example, MyHelloColdFusion).
  5. (Optional) Enter a description.
  6. Click Submit.

You can now call the tag from a ColdFusion page.

To call a CFX tag from a ColdFusion page:

  1. Create a ColdFusion page (.cfm) in your editor with the following content to call the HelloColdFusion custom tag:
    <html>
<body>
    <cfx_MyHelloColdFusion NAME="Les">
</body>
</html>
  2. Save the file in a directory configured to serve ColdFusion pages. For example, you can save the file as C:\inetpub\wwwroot\cfdocs\testjavacfx.cfm on Windows or /home/docroot/cfdocs/testjavacfx.cfm on UNIX.
  3. If you have not already done so, register the CFX tag in the ColdFusion MX Administrator (see Registering CFX tags).
  4. Request the page from your browser using the appropriate URL; for example:

    http://localhost/cfdocs/testjavacfx.cfm

ColdFusion processes the page and returns a page that displays the text "Hello, Les." If an error is returned instead, check the source code to make sure you have entered it correctly.

To delete a CFX tag in the ColdFusion MX Administrator:

  1. In the ColdFusion MX Administrator, select Extensions > CFX Tags to open the CFX Tags page.
  2. For the tag you want to delete, click the Delete icon in the Controls column of the Registered CFX Tags list.


Processing requests

Implementing a Java CFX tag requires interaction with the Request and Response objects passed to the processRequest method. In addition, CFX tags that need to work with ColdFusion queries also interface with the Query object. The com.allaire.cfx package, located in the WEB-INF/lib/cfx.jar archive, contains the Request, Response, and Query objects.

This section provides an overview of these object types. For a complete description of these object types, see ColdFusion Java CFX Reference in CFML Reference.

For a complete example Java CFX tag that uses Request, Response, and Query objects, see ZipBrowser example.

Request object

The Request object is passed to the processRequest method of the CustomTag interface. The following table lists the methods of the Request object for retrieving attributes, including queries, passed to the tag and for reading global tag settings:

Method | Description
attributeExists | Checks whether the attribute was passed to this tag.
debug | Checks whether the tag contains the debug attribute.
getAttribute | Retrieves the value of the passed attribute.
getAttributeList | Retrieves a list of all attributes passed to the tag.
getIntAttribute | Retrieves the value of the passed attribute as an integer.
getQuery | Retrieves the query that was passed to this tag, if any.
getSetting | Retrieves the value of a global custom tag setting.

For detailed reference information on each of these interfaces, see CFML Reference.

Response object

The Response object is passed to the processRequest method of the CustomTag interface. The following table lists the methods of the Response object for writing output, generating queries, and setting variables within the calling page:

Method | Description
write | Outputs text to the calling page.
setVariable | Sets a variable in the calling page.
addQuery | Adds a query to the calling page.
writeDebug | Outputs text to the debug stream.

For detailed reference information on each of these interfaces, see CFML Reference.

Query object

The Query object provides an interface for working with ColdFusion queries. The following table lists the methods of the Query object for retrieving name, row count, and column names and methods for getting and setting data elements:

Method | Description
getName | Retrieves the name of the query.
getRowCount | Retrieves the number of rows in the query.
getColumnIndex | Retrieves the index of a query column.
getColumns | Retrieves the names of the query columns.
getData | Retrieves a data element from the query.
addRow | Adds a new row to the query.
setData | Sets a data element within the query.

For detailed reference information on each of these interfaces, see CFML Reference.


Life cycle of Java CFX tags

A new instance of the Java CFX object is created for each invocation of the Java CFX tag. This means that it is safe to store per-request instance data within the members of your CustomTag object. To store data and/or objects that are accessible to all instances of your CustomTag, use static data members. If you do so, you must ensure that all accesses to the data are thread-safe.


ZipBrowser example

The following example shows the use of the Request, Response, and Query objects. The example uses the java.util.zip package to implement a Java CFX tag called cfx_ZipBrowser, which is a zip file browsing tag.

Note: The Java source file that implements cfx_ZipBrowser, ZipBrowser.java, is included in the cf_root/cfx/java/distrib/examples (server configuration) or cf_webapp_root/WEB-INF/cfusion/cfx/java/distrib/examples (J2EE configuration) directory. Compile ZipBrowser.java to implement the tag.

The tag’s archive attribute specifies the fully qualified path of the zip archive to browse. The tag’s name attribute must specify the query to return to the calling page. The returned query contains three columns: Name, Size, and Compressed.

For example, to query an archive at the path C:\logfiles.zip for its contents and output the results, you use the following CFML code:

<cfx_ZipBrowser
    archive="C:\logfiles.zip"
    name="LogFiles" >

<cfoutput query="LogFiles">
#Name#,  #Size#, #Compressed# <BR>
</cfoutput>

The Java implementation of ZipBrowser is as follows:

import com.allaire.cfx.* ;
import java.util.Hashtable ;
import java.io.FileInputStream ;
import java.util.zip.* ;

public class ZipBrowser implements CustomTag {
   public void processRequest( Request request, Response response )
      throws Exception {
      // validate that required attributes were passed
      if (  !request.attributeExists( "ARCHIVE" ) ||
            !request.attributeExists( "NAME" ) ) {
         throw new Exception(
            "Missing attribute (ARCHIVE and NAME are both " +
            "required attributes for this tag)" ) ;
      }
     // get attribute values
      String strArchive = request.getAttribute( "ARCHIVE" ) ;
      String strName = request.getAttribute( "NAME" ) ;

    // create a query to use for returning the list of files
      String[] columns = { "Name", "Size", "Compressed" } ;
      int iName = 1, iSize = 2, iCompressed = 3 ;
      Query files = response.addQuery( strName, columns ) ;

    // read the zip file and build a query from its contents
      ZipInputStream zin =
         new ZipInputStream( new FileInputStream(strArchive) ) ;
      ZipEntry entry ;
      while ( ( entry = zin.getNextEntry()) != null ) {
         // add a row to the results
         int iRow = files.addRow() ;

         // populate the row with data
         files.setData( iRow, iName,
            entry.getName() ) ;
         files.setData( iRow, iSize,
            String.valueOf(entry.getSize()) ) ;
         files.setData( iRow, iCompressed,
            String.valueOf(entry.getCompressedSize()) ) ;

         // finish up with entry
         zin.closeEntry() ;
      }

      // close the archive
      zin.close() ;
   }
}


Approaches to debugging Java CFX tags

Java CFX tags are not stand-alone applications that run in their own process, like typical Java applications. Rather, they are created and invoked from an existing process. This makes debugging Java CFX tags more difficult, because you cannot use an interactive debugger to debug Java classes that have been loaded by another process.

To overcome this limitation, you can use one of the following techniques:

  • Debug the CFX tag while it is running within ColdFusion MX by outputting the debug information as needed.
  • Debug the CFX tag using a Java IDE (Integrated Development Environment) that supports debugging features, such as setting breakpoints, stepping through your code, and displaying variable values.
  • Debug the request in an interactive debugger offline from ColdFusion MX using the special com.allaire.cfx debugging classes.

This section describes the following topics:

  • Outputting debugging information
  • Debugging in a Java IDE
  • Using the debugging classes


Outputting debugging information

Before using interactive debuggers became the norm, programmers typically debugged their programs by inserting output statements in their programs to indicate information such as variable values and control paths taken. Often, when a new platform emerges, this technique comes back into vogue while programmers wait for more sophisticated debugging technology to develop for the platform.

If you need to debug a Java CFX tag while running against a live production server, this is the technique you must use. In addition to outputting debugging text using the Response.write method, you can also call your Java CFX tag with the debug="On" attribute. This attribute flags the CFX tag that the request is running in debug mode and therefore should output additional extended debugging information. For example, to call the HelloColdFusion CFX tag in debugging mode, use the following CFML code:

<cfx_HelloColdFusion name="Robert" debug="On">

To determine whether a CFX tag is invoked with the debug attribute, use the Request.debug method. To write debugging output in a special debugging block after the tag finishes executing, use the Response.writeDebug method. For information on using these methods, see ColdFusion Java CFX Reference in CFML Reference.


Debugging in a Java IDE

You can use a Java IDE to debug your Java CFX tags. This means you can develop your Java CFX tag and debug it in a single environment.

To use a Java IDE to debug your CFX tag:

  1. Start your IDE.
  2. In the project properties (or your IDE's project setting), make sure your CFX class is in the web_root\WEB-INF\classes directory or in the system classpath.
  3. Make sure the libraries cf_root/wwwroot/WEB-INF/lib/cfx.jar (cf_webapp_root/WEB-INF/lib/cfx.jar in the J2EE configuration) and cf_root/runtime/lib/jrun.jar (server configuration only) are included in your classpath.
  4. In your project settings, set your main class to jrunx.kernel.JRun and application parameters to -start default.
  5. Debug your application by setting breakpoints, single stepping, displaying variables, or by performing other debugging actions.


Using the debugging classes

To develop and debug Java CFX tags in isolation from the ColdFusion, you use three special debugging classes that are included in the com.allaire.cfx package. These classes lets you simulate a call to the processRequest method of your CFX tag within the context of the interactive debugger of a Java development environment. The three debugging classes are the following:

  • DebugRequest An implementation of the Request interface that lets you initialize the request with custom attributes, settings, and a query.
  • DebugResponse An implementation of the Response interface that lets you print the results of a request once it has completed.
  • DebugQuery An implementation of the Query interface that lets you initialize a query with a name, columns, and a data set.

To use the debugging classes:

  1. Create a main method for your Java CFX class.
  2. Within the main method, initialize a DebugRequest and DebugResponse, and a DebugQuery. Use the appropriate attributes and data for your test.
  3. Create an instance of your Java CFX tag and call its processRequest method, passing in the DebugRequest and DebugResponse objects.
  4. Call the DebugResponse.printResults method to output the results of the request, including content generated, variables set, queries created, and so on.

After you implement a main method as described previously, you can debug your Java CFX tag using an interactive, single-step debugger. Specify your Java CFX class as the main class, set breakpoints as appropriate, and begin debugging.

Debugging classes example

The following example demonstrates how to use the debugging classes:

import java.util.Hashtable ;
import com.allaire.cfx.* ;

public class OutputQuery implements CustomTag {
   // debugger testbed for OutputQuery
   public static void main(String[] argv) {
      try {
         // initialize attributes
         Hashtable attributes = new Hashtable() ;
         attributes.put( "HEADER", "Yes" ) ;
         attributes.put( "BORDER", "3" ) ;

         // initialize query

         String[] columns =
            { "FIRSTNAME", "LASTNAME", "TITLE" } ;

         String[][] data =  {
            { "Stephen", "Cheng", "Vice President" },
            { "Joe", "Berrey", "Intern" },
            { "Adam", "Lipinski", "Director" },
            { "Lynne", "Teague", "Developer" } }  ;

         DebugQuery query =
            new DebugQuery( "Employees", columns, data ) ;

         // create tag, process debugging request, and print results
         OutputQuery tag = new OutputQuery() ;
         DebugRequest request = new DebugRequest( attributes, query ) ;
         DebugResponse response = new DebugResponse() ;
         tag.processRequest( request, response ) ;
         response.printResults() ;
      }
      catch( Throwable e ) {
         e.printStackTrace() ;
      }
   }

   public void processRequest(Request request, Response response) throws Exception {
      // ...code for processing the request...
   }
}


Developing CFX tags in C++

The following sections provide information to help you develop CFX tags in C++.

Sample C++ CFX tags

Before you begin development of a CFX tag in C++, you might want to study the two CFX tags included with ColdFusion MX. These examples will help you get started working with the CFXAPI. The two example tags are as follows:

  • CFX_DIRECTORYLIST Queries a directory for the list of files it contains.
  • CFX_NTUSERDB (Windows only) Lets you add and delete Windows NT users.

On Windows, these tags are located in the cf_root\cfx\examples directory. On UNIX, these tags are in the cf_root/coldfusion/cfx/examples directory.

Setting up your C++ development environment

The following compliers generate valid CFX code for UNIX platforms:

Platform | Compiler
Solaris | Sun C++ compiler 5.0 or higher (gcc does not work)
Linux | RedHat 6.2 gcc/egcs 1.1.2 compiler

Before you can use your C++ compiler to build custom tags, you must enable the compiler to locate the CFX API header file, cfx.h. In Windows, you do this by adding the CFX API include directory to your list of global include paths. In Windows, this directory is cf_root\cfx\include. On UNIX this directory is cf_root/cfx/include. On UNIX, you will need -I <includepath> on your compile line (see the Makefile for the directory list example in the cfx/examples directory).

Compiling C++ CFX tags

CFX tags built in Windows and on UNIX must be thread-safe. Compile CFX tags for Solaris with the -mt switch on the Sun compiler.

Locating your C++ library files on UNIX

On UNIX systems, your C++ library files can be in any directory as long as the directory is included in LD_LIBRARY_PATH or SHLIB_PATH (HP-UX only).

Implementing C++ CFX tags

CFX tags built in C++ use the tag request object, represented by the C++ CCFXRequest class. This object represents a request made from an application page to a custom tag. A pointer to an instance of a request object is passed to the main procedure of a custom tag. The methods available from the request object let the custom tag accomplish its work. For information about the CFX API classes and members, see ColdFusion C++ CFX Reference in CFML Reference.

Note: Calling a non-existent C++ CFX procedure or entry point causes a JVM crash on UNIX.

Debugging C++ CFX tags

After you configure a debugging session, you can run your custom tag from within the debugger, set breakpoints, single-step, and so on.

Debugging in Windows

You can debug custom tags within the Visual C++ environment.

To debug C++ CFX tags in Windows:

  1. Build your C++ CFX tag using the debug option.
  2. Restart ColdFusion.
  3. Start Visual C++.
  4. Select Build > Start Debug > AttachProcess.
  5. Select jrunsvc.exe.

    Macromedia recommends that you shut down all other Java programs.

  6. Execute any ColdFusion page that calls the CFX tag.
  7. Select File > Open to open a file in VisualDev in which to set a breakpoint.
  8. Set a breakpoint in the CFX project.

    The best place is to put it in ProcessRequest(). Next time you execute the page you will hit the breakpoint.

Registering CFX tags

To use a CFX tag in your ColdFusion applications, first register it in the Extensions, CFX Tags page in the ColdFusion MX Administrator.

To register a C++ CFX tag:

  1. In the ColdFusion MX Administrator, select Extensions > CFX Tags to open the CFX Tags page.
  2. Click Register C++ CFX.
  3. Enter the Tag name (for example, cfx_MyNewTag).
  4. If the Server Library .dll field is empty, enter the filepath.
  5. Accept the default Procedure entry.
  6. Clear the Keep library loaded box while developing the tag.

    For improved performance, when the tag is ready for production use, you can select this option to keep the DLL in memory.

  7. (Optional) Enter a description.
  8. Click Submit.

You can now call the tag from a ColdFusion page.

To delete a CFX tag:

  1. In the ColdFusion MX Administrator, select Extensions > CFX Tags to open the CFX Tags page.
  2. For the tag you want to delete, click the Delete icon in the Controls column of the Registered CFX Tags list.
Previous


Designing and Optimizing a ColdFusion Application

This chapter describes the elements that make your ColdFusion pages into an effective Internet application. It provides an overview of application elements, describes how you can structure an application on your server, and provides detailed information on using the Application.cfc and Application.cfm files. It also describes coding methods for optimizing application efficiency.

Contents

About applications

Elements of a ColdFusion application

Structuring an application

Defining the application and its event handlers in Application.cfc

Migrating from Application.cfm to Application.cfc

Using an Application.cfm page

Optimizing ColdFusion applications
Next


About applications

The term application can mean many things. An application can be as simple as a guest book or as sophisticated as a full Internet commerce system with catalog pages, shopping carts, and reporting.

n application, however, has a specific meaning in Macromedia ColdFusion MX. A ColdFusion application has the following characteristics:

  • It consists of one or more ColdFusion pages that work together and share a common set of resources.
  • All pages in the application share an application name and configuration settings as specified in an Application.cfc file or a cfapplication tag.
  • All pages in the application share variables in the Application scope.
  • You can write application-wide event handlers for specific events, such as request start or session end.

What appears to a user to be a single application (for example, a company’s website), might consist of multiple ColdFusion MX applications.

ColdFusion MX applications are not J2EE applications. If you do not specify an application name in your Application.cfc file or cfapplication tag, however, the Application scope corresponds to the J2EE application servlet context.

ColdFusion MX applications end when the application has been inactive for the application time-out period or the server stops. When the application times out, ColdFusion MX releases all Application scope variables. You must, therefore, select a time-out period that balances the need for clearing Application scope memory and the overhead of recreating the scope. A typical application time-out is two days.

ColdFusion MX applications and sessions are independent of each other. For example, if an application times out while a user’s session is active, the session continues and the session context, including the user’s Session scope variables, is unaffected by the application ending and restarting.

Although there are no definite rules about how you represent your web application as a ColdFusion application or applications, the following guidelines are useful:

  • Application pages share a common general purpose. For example, a web storefront is typically a single ColdFusion application.
  • Many, but not necessarily all, pages in a ColdFusion application share data or common code elements, such as a single login mechanism.
  • Application pages share a common look and feel, often enforced by using common code elements, such as the same header and footer pages, and a common error message template.

This chapter describes the tools that ColdFusion MX provides to create an application, and presents information on how you can develop and optimize your application.


Elements of a ColdFusion application

Before you develop a ColdFusion application, you must determine how to structure the application and how to handle application-wide needs and issues. In particular, you must consider all of the following:

  • The overall application framework
  • Reusable application elements
  • Shared variables
  • Application events and the Application.cfc file
  • Application-level settings and functions
  • Application security and user identification

The following sections introduce these application elements and provide references to more detailed information:

  • The application framework
  • Reusable application elements
  • Shared variables
  • Application events and the Application.cfc file.
  • Other application-level settings and functions
  • Application security and user identification


The application framework

The application framework is the overall structure of the application and how your directory structure and application pages reflect that structure. You can use a single application framework to structure multiple ColdFusion applications into a single website or Internet application. You can structure a ColdFusion application by using many methodologies. For example, the Fusebox application development methodology is one popular framework for developing ColdFusion web applications. (For more information on Fusebox, see www.fusebox.org.)

This chapter does not provide information on how to use or develop a specific application framework. However, it does discuss the tools that ColdFusion MX provides for building your framework, including the Application.cfc file, how an application’s directory structure affects the application, and how you can map the directory structure. For more information on mapping the application framework, see Structuring an application.

Note: For one example of an application framework, see "ColdFusion Methodologies for Content Management," available at www.macromedia.com/devnet/server_archive/articles/cf_methodologies_for_content_mgmt.html.


Reusable application elements

ColdFusion provides a variety of reusable elements that you can use to provide commonly used functionality and extend CFML. These elements include the following:

  • User-defined functions (UDFs)
  • CFML custom tags
  • ColdFusion components (CFCs)
  • CFX (ColdFusion Extension) tags
  • Pages that you include using the cfinclude tag

For an overview of these elements, and information about how to choose among them, see Creating ColdFusion Elements.


Shared variables

The following ColdFusion variable scopes maintain data that lasts beyond the scope of the current HTTP request:

Variable scope | Variables available
Server | To all applications on a server and all clients
Application | To all pages in an application for all clients
Client | For a single client browser over multiple browser sessions in one application
Session | For a single client browser for a single browser session in one application

For more information on using these variables, including how to use locks to ensure that the data they contain remains accurate, see Using Persistent Data and Locking.


Application events and the Application.cfc file.

In ColdFusion MX 7, Macromedia introduced application events and the Application.cfc file, which defines application settings and implements methods to handle the application events. Application events are specific occurrences during the life cycle of an application. Each time one of these events occurs, ColdFusion MX runs the corresponding method in your Application.cfc file (also referred to as the application CFC). You can implement application CFC methods to handle the following events:

.
Event | Trigger
Application start | ColdFusion starts processing the first request for a page in an application that is not running.
Application end | An application time-out setting is reached or the server shuts down.
Session start | A new session is created as a result of a request that is not in an existing session.
Session end | A session time-out setting is reached or, if using J2EE sessions, the user closes the browser.
Request start | ColdFusion receives a request, including HTTP requests, messages to the event gateway, SOAP requests, or Flash Remoting requests.
Request | Immediately after ColdFusion finishes processing the request start event. The handler for this event is intended for use as a filter for the request contents. For more information on the differences between request start and request events, see Managing requests in Application.cfc.
Request end | ColdFusion finishes processing all pages and CFCs for the request.
Exceptions | An exception occurs that is not handled in a try/catch block.

The Application.cfc file can also define application-wide settings, including the application name and whether the application supports Session variables.

For more information on using application events and the Application.cfc file, see Defining the application and its event handlers in Application.cfc.


Other application-level settings and functions

This section describes the techniques used prior to ColdFusion MX 7 to define application-level settings, variables, and functions. Macromedia recommends that you do not use these techniques in new code that you write; instead, you should use the Application.cfc file and its variables and methods, which provide more features and include logical, hierarchical structure.

If you do not have an Application.cfc file, ColdFusion processes the following two pages, if they are available, every time it processes any page in the application:

  • The Application.cfm page is processed before each page in the application.
  • The OnRequestEnd.cfm page is processed after each page in the application.

Note: UNIX systems are case-sensitive. To ensure that your pages work on UNIX, always capitalize the A in Application.cfm and the O, R, and E in OnRequestEnd.cfm.

The Application.cfm page can define the application. It can contain the cfapplication tag that specifies the application name, and code on this page is processed for all pages in the application. This page can define application-level settings, functions, and features.

The OnRequestEnd.cfm page is used in fewer applications than the Application.cfm page. It lets you provide common clean-up code that gets processed after all application pages, or specify dynamic footer pages.

Tip: The OnRequestEnd.cfm page does not execute if the page invokes a cflocation tag.

For more information on the Application.cfm and OnRequestEnd.cfm pages, see Using an Application.cfm page. For information on placing these pages in the application directory structure, see Structuring an application.

Note: You can create a ColdFusion application without using an Application.cfc, Application.cfm, or OnRequestEnd.cfm page. However, it is much easier to use the Application.cfm page than to have each page in the application use a cfapplication tag and define common application elements.


Application security and user identification

All applications must ensure that malicious users cannot make improper use of their resources. Additionally, many applications require user identification, typically to control the portions of a site that the user can access, to control the operations that the user can perform, or to provide user-specific content. ColdFusion provides the following forms of application security to address these issues:

Resource (file and directory-based) security Limits the ColdFusion resources, such as tags, functions, and data sources that application pages in particular directories can access. You must consider the resource security needs of your application when you design the application directory structure.

User (programmatic) security Provides an authentication (login) mechanism and a role-based authorization mechanism to ensure that users can only access and use selected features of the application. User security also incorporates a user ID, which you can use to customize page content. To implement user security, you include security code, such as the cflogin and cfloginuser tags, in your application.

For more on implementing security, see Securing Applications.


Structuring an application

When you design a ColdFusion application, you must structure its contents into directories and files, also known as mapping the directory structure. This activity is an important step in designing a ColdFusion application. Before you start building the application, you must establish a root directory for the application. You can store application pages in subdirectories of the root directory.

The following sections describe how ColdFusion uses application-specific pages and how you can organize your application pages in a directory structure.

How ColdFusion MX finds and process application definition pages

ColdFusion MX uses the following rules to locate and process the Application.cfc, Application.cfm, and OnRequestEnd.cfm pages that define application-specific elements. The way ColdFusion MX locates these files helps determine how you structure an application.

Each time ColdFusion MX processes a page request it does the following:

  1. When ColdFusion starts processing the request, it does the following:
    • It searches the page’s directory for a file named Application.cfc. If one exists, it creates a new instance of the CFC, processes the initial events, and stops searching. (ColdFusion MX creates a new instance of the CFC and processes its initialization code for each request.)
    • If the requested page’s directory does not have an Application.cfc file, it checks the directory for an Application.cfm file. If one exists, ColdFusion MX logically includes the Application.cfm page at the beginning of the requested page and stops searching further.
    • If the requested page’s directory does not have an Application.cfc or Application.cfm file, ColdFusion MX searches up the directory tree and checks each directory first for an Application.cfc file and then, if one is not found, for an Application.cfm page, until it reaches the root directory (such as C:\). When it finds an Application.cfc or Application.cfm file, it processes the page and stops searching.
  2. ColdFusion MX processes the requested page’s contents.
  3. When the request ends, ColdFusion MX does the following:
    • If you have an Application.cfc, ColdFusion MX processes the CFC’s onRequestEnd method and releases the CFC instance.
    • If you do not have an Application.cfc, but do have an Application.cfm page, ColdFusion MX looks for an OnRequestEnd.cfm in the same directory as the Application.cfm page ColdFusion uses for the current page. ColdFusion does not search beyond that directory, so it does not run an OnRequestEnd.cfm page that resides in another directory. Also, the OnRequestEnd.cfm page does not run if there is an error or an exception on the application page, or if the application page executes the cfabort or cfexit tag.

The following rules determine how ColdFusion MX processes application pages and settings:

  • ColdFusion processes only one Application.cfc or Application.cfm page for each request. If a ColdFusion page has a cfinclude tag pointing to an additional ColdFusion page, ColdFusion MX does not search for an Application.cfc or Application.cfm page when it includes the additional page.
  • If a ColdFusion page has a cfapplication tag, it first processes any Application.cfc or Application.cfm, and then processes the cfapplication tag. The tag can override the settings from the application files, including the application name and the behaviors set by the cfapplication tag attributes.
  • You can have multiple Application.cfc files, Application.cfm files, and cfapplication tags that use the same application name. In this case, all pages that have the same name share the same application settings and Application scope and can set and get all the variables in this scope. ColdFusion uses the parameter settings of the cfapplication tag or the most recently processed file, if the settings, such as the session time-out, differ among the files.

Note: If your application runs on a UNIX platform, which is case-sensitive, you must spell Application.cfc, Application.cfm, and OnRequestEnd.cfm with capital letters, as shown.

Defining the directory structure

Defining an application directory structure with an application-specific root directory has the following advantages:

Development The application is easier to develop and maintain, because the application page files are well-organized.

Portability You can easily move the application to another server or another part of a server without changing any code in the application page files.

Application-level settings Application pages that are under the same directory can share application-level settings and functions.

Security Application pages that are under the same directory can share web server security settings.

When you put your application in an application-specific directory hierarchy, you can use a single application definition (Application.cfc or Application.cfm) page in the application root directory, or put different application definition pages that govern individual sections of the application in different directories.

You can divide your logical web application into multiple ColdFusion applications by using multiple application definition pages with different application names. Alternatively, you can use multiple application definition pages that specify the same application name, but have different code, for different subsections of your application.

The directory trees in the following figure show two approaches to implementing an application framework:

  • In the example on the left, a company named Web Wonders, Inc. uses a single Application.cfc file installed in the application root directory to process all application page requests.
  • In the example on the right, Bandwidth Associates uses the settings in individual Application.cfc files to create individual ColdFusion applications at the departmental level. Only the Products application pages are processed using the settings in the root Application.cfc file. The Consulting, Marketing, and Sales directories each have their own Application.cfc file.

    This is a picture of the feature being described.


Defining the application and its event handlers in Application.cfc

The Application.cfc file defines application-wide settings and variables, and application event handlers:

  • Application-wide settings and variables include page processing settings, default variables, data sources, style settings, and other application-level constants.
  • Application event handlers are CFC methods that ColdFusion MX automatically executes when specific events occur during the lifetime of an application: application start and end, session start and end, request start, execution, and end, and exceptions.


Defining application-level settings and variables

When you create an application, you can set a number of application-wide properties and characteristics, including the following items:

  • Application name
  • Application properties, including Client-, Application-, and Session-variable management options
  • Page processing options
  • Default variables, data sources, style settings, and other application-level constants

This section describes the following topics:

  • Naming the application
  • Setting application properties
  • Setting page processing options

For information on setting default variables, see You can set default variables and application-level constants in Application.cfc. For example, you can do the following:.


Naming the application

Define the application and give it a name by setting the This.name variable in the Application.cfc initialization section, before the method definitions. By using a specific application name, you define a set of pages as part of the same logical application.

ColdFusion supports unnamed applications, which are useful for ColdFusion applications that must interoperate with JSP tags and servlets. Consider creating an unnamed application only if your ColdFusion pages must share Application or Session scope data with existing JSP pages and servlets. You cannot have more than one unnamed application on a server instance. For more information on using unnamed applications, see Sharing data between ColdFusion pages and JSP pages or servlets.


Setting application properties

You can specify application properties by setting This scope variables in the Application.cfc initialization code. (These are the same properties that you can set in the cfapplication tag.) The following table lists the This scope variables that ColdFusion MX uses to set application properties and describes their uses.

Variable | Default | Description
applicationTimeout | Administrator value | Life span, as a real number of days, of the application, including all Application scope variables. Use the createTimeSpan function to generate this variable.
clientManagement | False | Whether the application supports Client scope variables.
clientStorage | Administrator value | Where Client variables are stored; can be cookie, registry, or the name of a data source.
loginStorage | Cookie | Whether to store login information in the Cookie scope or the Session scope.
scriptProtect | Administrator Value | Whether to protect variables from cross-site scripting attacks.
sessionManagement | False | Whether the application supports Session scope variables.
sessionTimeout | Administrator Value | Life span, as a real number of days, of the user session, including all Session variables. Use the createTimeSpan function to generate this variable.
setClientCookies | True | Whether to send CFID and CFTOKEN cookies to the client browser.
setDomainCookies | False | Whether to use domain cookies for the CFID and CFTOKEN values used for client identification, and for Client scope variables stored using cookies. If False, ColdFusion MX uses host-specific cookies. Set to True for applications running on clusters.

The following example code from the top of an Application.cfc sets the application name and properties:

<cfcomponent>
<cfset This.name = "TestApplication">
<cfset This.clientmanagement="True">
<cfset This.loginstorage="Session">
<cfset This.sessionmanagement="True">
<cfset This.sessiontimeout="#createtimespan(0,0,10,0)#">
<cfset This.applicationtimeout="#createtimespan(5,0,0,0)#">

For more information on these settings, see cfapplication in CFML Reference.


Setting page processing options

The cfsetting tag lets you specify the following page processing attributes that you might want to apply to all pages in your application:

Attribute | Use
showDebugOutput | Specifies whether to show debugging output. This setting cannot enable debugging if it is disabled in the ColdFusion MX Administrator. However, this option can ensure that debugging output is not displayed, even if the Administrator enables it.
requestTimeout | Specifies the page request time-out. If ColdFusion cannot complete processing a page within the time-out period, it generates an error. This setting overrides the setting in the ColdFusion MX Administrator. You can use this setting to increase the page time-out if your application or page frequently accesses external resources that might be particularly slow, such as external LDAP servers or web services providers.
enableCFOutputOnly | Disables output of text that is not included inside cfoutput tags. This setting can help ensure that extraneous text that might be in your ColdFusion pages does not get displayed.

Often, you use the cfsetting tag on individual pages, but you can also use it in your Application.cfc file. For example, you might use it in multi-application environment to override the ColdFusion MX Administrator settings in one application.

You can put an application-wide cfsetting tag in the component initialization code, normally following the This scope application property settings, as the following example shows:

<cfcomponent>
<cfscript>
    This.name="MyAppl";
    This.clientmanagement="True";
    This.loginstorage="Session" ;
    This.sessionmanagement="True" ;
    This.sessiontimeout=CreateTimeSpan(0,0,1,0);
</cfscript>
<cfsetting showdebugoutput="No" enablecfoutputonly="No">

The cfsetting tag in this example affects all pages in an application. You can override the application-wide settings in the event methods, such as onRequestStart, or on individual ColdFusion pages.


Using application event handlers

The following table briefly describes the application event CFC methods that you can implement, including when they are triggered. The following sections describe how to use these methods in more detail.

Method

When run

onApplicationStart

The application first starts: when the first request for a page is processed or the first CFC method is invoked by an event gateway instance, Flash Remoting request, or a web service invocation.

This method is useful for setting application-wide (Application scope) variables, such as the names of data sources.

onApplicationEnd

The application ends: when the application times out or the server shuts down.

onSessionStart

A new session is created as a result of a request that is not in an existing session, including ColdFusion event gateway sessions. The application must enable sessions for this event to happen.

onSessionEnd

A session time-out setting is reached or, if using J2EE sessions, the user closes the browser. This event is not triggered when the application ends or the server shuts down.

onRequestStart

ColdFusion receives any of the following: a request, an HTTP request (for example, from a browser), a message to an event gateway, a SOAP request, or a Flash Remoting request.

onRequest

The onRequestStart event has completed. This method can act as a filter for the requested page content.

onRequestEnd

All pages and CFCs in the request have been processed: equivalent to the OnRequestEnd.cfm page.

onError

When an exception occurs that is not caught by a try/catch block.

When ColdFusion MX receives a request, it instantiates the Application CFC and runs the Application.cfc code in the following order:

  • CFC initialization code at the top of the file
  • onApplicationStart, if not run before for this application
  • onSessionStart, if not run before for this session
  • onRequestStart
  • onRequest, or the requested page if there is no onRequest method
  • onRequestEnd

The following methods are triggered by specific events:

  • onApplicationEnd
  • onSessionEnd
  • onError

The onApplicationEnd and onSessionEnd methods do not execute in the context of a page request, so they cannot access request variables or display information to the user. The OnError method does not always execute in the context of a request; you can use its Event argument to determine the context.


Managing the application with Application.cfc

You use the onApplicationStart and onApplicationEnd methods to configure and manage the application; that is, to control resources that are used by multiple pages and requests and must be consistently available to all code in your application. Such resources can include data sources, application counters such as page hit variables, or style information for all pages.

The onApplicationStart method executes when ColdFusion MX gets the first request for a page in the application after the server starts. The onApplicationEnd method executes when the application server shuts down or if the application is inactive for the application time-out period.

The following sections describe some of the ways you can use these methods. For more information, see entries for onApplicationStart and onApplicationEnd in CFML Reference.

Defining application utility functions

Functions that you define in Application.cfc and do not put in a shared scope are, by default, available only to other methods in the CFC.

If your Application.cfc implements the onRequest method, any utility functions that you define in Application.cfc are also directly available in to the target page, because Application.cfc and the target page share the Variables scope.

If your application requires utility functions that are used by multiple pages, not just by the methods in Application.cfc, and you do not use an onRequest method, Macromedia recommends that you put them in a separate CFC and access them by invoking that CFC. As with other ColdFusion pages, Application.cfc can access any CFC in a directory path that is configured on the ColdFusion MX Administrator Mappings page. You can, therefore, use this technique to share utility functions across applications.

If your Application.cfc defines utility functions that you want available on request pages and does not use an onRequest method, you must explicitly put the functions in a ColdFusion MX scope, such as the Request scope, as the following code shows:

<cffunction name="theFunctionName" returntype="theReturnType">
    <!--- Function definition goes here. --->
</cffunction>

<cffunction name="OnRequestStart">
    <!--- OnRequestStart body goes here --->
        <cfset Request.theFunctionName=This.theFunctionName>
</cffunction>

On the request page, you would include the following code:

<cfset myVar=Request.theFunctionName(Argument1...)>

Functions that you define in this manner share the This scope and Variables scope with the Application.cfc file for the request.

Setting application default variables and constants in onApplicationStart

You can set default variables and application-level constants in Application.cfc. For example, you can do the following:

  • Specify a data source and ensure that it is available
  • Specify domain name
  • Set styles, such as fonts or colors
  • Set other application-level variables

You do not have to lock Application scope variables when you set them in the Application.cfc onApplicationStart method.

For details on implementing the onApplicationStart method, see onApplicationStart in CFML Reference.

Using the onApplicationEnd method

Use the onApplicationEnd method for any clean-up activities that your application requires when it shuts down, such as saving data in memory to a database, or to log the application end. You cannot use this method to display data on a user page, because it is not associated with any request. The application ends, even if this method throws an exception. An application that is used often is unlikely to execute this method, except when the server is shut down.

For details on implementing the onApplicationEnd method, see onApplicationEnd in CFML Reference.


Managing sessions in Application.cfc

You use the onSessionStart and onSessionEnd methods to configure and manage user sessions; that is, to control resources that are used by multiple pages while a user is accessing your site from during a single browser session. The session begins when a user first requests a page in your application, and ends either when the session times out or, if you are using J2EE session management, when the user closes the browser when the user closes the browser. For more information on Session scope and Session variables, see Using Persistent Data and Locking.

Session resources include variables that store data that is needed throughout the session, such as account numbers, shopping cart contents, or CFCs that contain methods and data that are used by multiple pages in a session.

Note: Do not put the cflogin tag or basic login processing in the onSessionStart method, as the code executes only at the start of the session; it cannot handle user logouts, and cannot fully ensure security.

The following sections describe some of the ways you can use the onSessionStart and onSessionEnd methods. For more information, see the onSessionStart and onSessionEnd entries in CFML Reference.

Using the onSessionStart method

This method is useful for initializing session data, such as user settings or shopping cart contents, or for tracking the number of active sessions. You do not need to lock the Session scope when you set session variables in this method.

Using the onSessionEnd method

Use this method for any clean-up activities when the session ends. (For information on ending sessions, see Ending a session.) You can, for example, save session-related data, such as shopping cart contents or information about whether the user has not completed an order, in a database, or you can log the end of the session to a file. You cannot use this method to display data on a user page, because it is not associated with a request.

Note: Sessions do not end, and the onSessionEnd method is not called when an application ends. For more information, see the onSessionEnd entry in CFML Reference.


Managing requests in Application.cfc

ColdFusion MX provides three methods for managing requests: onRequestStart, onRequest, and onRequestEnd. ColdFusion processes requests, including these methods, as follows:

  1. ColdFusion always processes onRequestStart at the start of the request.
  2. If you implement an onRequest method, ColdFusion processes it; otherwise, it processes the requested page. If you implement an onRequest method, you must explicitly call the requested page in your onRequest method.
  3. ColdFusion always processes onRequestEnd at the end of the request.

The following sections explain how you can use each of the Application.cfc request methods to manage requests. For more information, see entries for onRequestStart, onRequest, and onRequestEnd in CFML Reference.

Using the onRequestStart method

This method runs at the beginning of the request. It is useful for user authorization (login handling), and for request-specific variable initialization, such as gathering performance statistics.

If you use the onRequestStart method and do not use the onRequest method, ColdFusion MX automatically processes the request when it finishes processing the onRequestStart code.

Note: If you do not include an onRequest method in Application.cfm file, the onRequestStart method does not share a Variables scope with the requested page, but it does share Request scope variables.

User authentication

When an application requires a user to log in, put the authentication code, including the cflogin tag or code that calls this tag, in the onRequestStart method. Doing so ensures that the user is authenticated at the start of each request. For detailed information on security and creating logins, see Securing Applications. For an example that uses authentication code generated by the Macromedia Dreamweaver CF Login Wizard, see onRequestStart in CFML Reference.

Using the onRequest method

The onRequest method differs from the onRequestStart method in one major way: the onRequest method intercepts the user’s request. This difference has two implications:

  • ColdFusion does not process the request unless you explicitly call it, for example, by using a cfinclude tag. This behavior lets you use the onRequest method to filter requested page content or to implement a switch that determines the pages or page contents to be displayed.
  • When you use cfinclude to process request, the CFC instance shares the Variables scope with the requested page. As a result, any method in the CFC that executes can set the page’s Variables scope variables, and the onRequestEnd method can access any Variable scope values that the included page has set or changed. Therefore, for example, the onRequestStart or onRequest method can set variables that are used on the page.

To use this method as a filter, put the cfinclude tag inside a cfsavecontent tag, as the following example shows:

<cffunction name="onRequest">
    <cfargument name = "targetPage" type="String" required=true/>
    <cfsavecontent variable="content">
        <cfinclude template=#Arguments.targetPage#>
    </cfsavecontent>
    <cfoutput>
        #replace(content, "report", "MyCompany Quarterly Report", "all")#
    </cfoutput>
</cffunction>

Using the onRequestEnd method

You use the onRequestEnd method for code that should run at the end of each request. (In ColdFusion versions through ColdFusion MX 6.1, you would use the OnRequestEnd.cfm page for such code.) Typical uses include displaying dynamic footer pages. For an example, see onSessionEnd in CFML Reference.

Note: If you do not include an onRequest method in Application.cfm file, the onRequestEnd method does not share a Variables scope with the requested page, but it does share Request scope variables.


Handling errors in Application.cfc

The following sections briefly describe how you can handle errors in Application.cfc. For more information on error pages and error handling, see Handling Errors. For details on implementing the onError method, see onError in CFML Reference.

Application.cfc error handling techniques

Application.cfc can handle errors in any combination of the following ways:

  • You can use try/catch error handling in the event methods, such as onApplicationStart or onRequestStart, to handle exceptions that happen in the event methods.
  • You can implement the onError method. This method receives all exceptions that are not directly handled by try/catch handlers in CFML code. The method can use the cfthrow tag to pass any errors it does not handle to ColdFusion for handling.
  • You can use cferror tags in the application initialization code following the cfcomponent tag, typically following the code that sets the application’s This scope variables. These tags specify error processing if you do not implement an onError method, or if the onError method throws an error. You could implement an application-specific validation error handler, for example, by putting the following tag in the CFC initialization code:
    <cferror type="VALIDATION" template="validationerrorhandler.cfm">
  • The ColdFusion MX default error mechanisms handle any errors that are not handled by the preceding techniques. These mechanisms include the site-wide error handler that you can specify in the ColdFusion MX Administrator and the built-in default error pages.

These techniques let you include application-specific information, such as contact information or application or version identifiers, in the error message, and let you display all error messages in the application in a consistent manner. You can use Application.cfc to develop sophisticated application-wide error-handling techniques, including error-handling methods that provide specific messages, or use structured error-handling techniques.

Note: The onError method can catch errors that occur in the onSessionEnd and onApplicationEnd application event methods. It will not display messages to the user, however, because there is no request context. The onError function can log errors that occur when the session or application ends.

Handling server-side validation errors in the onError method

Server-side validation errors are actually ColdFusion exceptions; as a result, if your application uses an onError method, this method gets the error and must handle it or pass it on to ColdFusion for handling.

To identify a server-side validation error, search the Arguments.Exception.StackTrace field for coldfusion.filter.FormValidationException. You can then handle the error directly in your onError routine, or throw the error so that either the ColdFusion default validation error page or a page specified by an cferror tag in your Application.cfc initialization code handles it.

Example: error Handling with the onError method

The following Application.cfc file has an onError method that handles errors as follows:

  • If the error is a server-side validation error, the onError method throws the error for handling by ColdFusion MX, which displays its standard validation error message.
  • For any other type of exception, the onError method displays the name of the event method in which the error occurred and dumps the exception information. In this example, because you generate errors on the CFM page only, and not in a Application.cfc method, the event name is always the empty string.
<cfcomponent>
<cfset This.name = "BugTestApplication">
<cffunction name="onError">
    <!--- The onError method gets two arguments:
            An exception structure, which is identical to a cfcatch variable.
            The name of the Application.cfc method, if any, in which the error
            happened.
    <cfargument name="Except" required=true/>
    <cfargument type="String" name = "EventName" required=true/>
    <!--- Log all errors in an application-specific log file. --->
    <cflog file="#This.Name#" type="error" text="Event Name: #Eventname#" >
    <cflog file="#This.Name#" type="error" text="Message: #except.message#">
    <!--- Throw validation errors to ColdFusion for handling. --->
    <cfif Find("coldfusion.filter.FormValidationException",
                     Arguments.Except.StackTrace)>
        <cfthrow object="#except#">
    <cfelse>
        <!--- You can replace this cfoutput tag with application-specific
                error-handling code. --->
        <cfoutput>
            <p>Error Event: #EventName#</p>
            <p>Error details:<br>
            <cfdump var=#except#></p>
        </cfoutput>
    </cfif>
</cffunction>
</cfcomponent>

To test this example, put a CFML page with the following code in the same page as the Application.cfc file, and enter valid and invalid text in the text input field.

<cfform>
    This box does Integer validation:
    <cfinput name="intinput" type="Text" validate="integer" validateat="onServer"><br>
    Check this box to throw an error on the action page:
    <cfinput type="Checkbox" name="throwerror"><br>
    <cfinput type="submit" name="submitit">
 </cfform>

<cfif IsDefined("form.fieldnames")>
    <cfif IsDefined("form.throwerror")>
        <cfthrow type="ThrownError" message="This error was thrown from the bugTest action page.">
    <cfelseif form.intinput NEQ "">
        <h3>You entered the following valid data in the field</h3>
        <cfoutput>#form.intinput#</cfoutput>
    </cfif>
</cfif>

Note: For more information on server-side validation errors, see Validating Data.


Example: a complete Application.cfc

The following example is a simplified Application.cfc file that illustrates the basic use of all application event handlers:

<cfcomponent>
<cfset This.name = "TestApplication">
<cfset This.Sessionmanagement=true>
<cfset This.Sessiontimeout="#createtimespan(0,0,10,0)#">
<cfset This.applicationtimeout="#createtimespan(5,0,0,0)#">

<cffunction name="onApplicationStart">
    <cftry>
        <!--- Test whether the DB that this application uses is accessible
                by selecting some data. --->
        <cfquery name="testDB" dataSource="cfdocexamples" maxrows="2">
            SELECT Emp_ID FROM employee
        </cfquery>
        <!--- If we get database error, report it to the user, log the error
            information, and do not start the application. --->
        <cfcatch type="database">
            <cfoutput>
                This application encountered an error.<br>
                Please contact support.
            </cfoutput>
            <cflog file="#This.Name#" type="error"
                text="cfdocexamples DB not available. message: #cfcatch.message#
                Detail: #cfcatch.detail# Native Error: #cfcatch.NativeErrorCode#">
            <cfreturn False>
        </cfcatch>
    </cftry>
    <cflog file="#This.Name#" type="Information" text="Application Started">
    <!--- You do not have to lock code in the onApplicationStart method that sets Application scope variables. --->
    <cfscript>
        Application.availableResources=0;
        Application.counter1=1;
        Application.sessions=0;
    </cfscript>
    <!--- You do not need to return True if you don't set the cffunction returntype attribute. --->
 </cffunction>

<cffunction name="onApplicationEnd">
    <cfargument name="ApplicationScope" required=true/>
    <cflog file="#This.Name#" type="Information"
        text="Application #ApplicationScope.applicationname# Ended">
</cffunction>

<cffunction name="onRequestStart">
    <!--- Authentication code, generated by the Dreamweaver Login Wizard,
        makes sure that a user is logged in, and if not displays a login page. --->
    <cfinclude template="mm_wizard_application_include.cfm">
<!--- If it’s time for maintenance, tell users to come back later. --->
    <cfscript>
        if ((Hour(now()) gt 1) and (Hour(now()) lt 3)) {
            WriteOutput("The system is undergoing periodic maintenance.
                Please return after 3:00 AM Eastern time.");
            return false;
        } else {
            this.start=now();
        }
    </cfscript>
</cffunction>

<cffunction name="onRequest">
    <cfargument name = "targetPage" type="String" required=true/>
    <cfsavecontent variable="content">
        <cfinclude template=#Arguments.targetPage#>
    </cfsavecontent>
    <!--- This is a minimal example of an onRequest filter. --->
    <cfoutput>
        #replace(content, "report", "MyCompany Quarterly Report", "all")#
    </cfoutput>
</cffunction>

<!--- Display a different footer for logged in users than for guest users or
         users who have not logged in. --->

<cffunction name="onRequestEnd">
    <cfargument type="String" name = "targetTemplate" required=true/>
    <cfset theAuthuser=getauthuser()>
    <cfif ((theAuthUser EQ "guest") OR (theAuthUser EQ ""))>
        <cfinclude template="noauthuserfooter.cfm">
    <cfelse>
        <cfinclude template="authuserfooter.cfm">
    </cfif>
</cffunction>

<cffunction name="onSessionStart">
    <cfscript>
        Session.started = now();
        Session.shoppingCart = StructNew();
        Session.shoppingCart.items =0;
    </cfscript>
    <cflock timeout="5" throwontimeout="No" type="EXCLUSIVE" scope="SESSION">
        <cfset Application.sessions = Application.sessions + 1>
    </cflock>
    <cflog file="#This.Name#" type="Information" text="Session:
        #Session.sessionid# started">
</cffunction>

<cffunction name="onSessionEnd">
    <cfargument name = "SessionScope" required=true/>
    <cflog file="#This.Name#" type="Information" text="Session:
        #arguments.SessionScope.sessionid# ended">
</cffunction>

<cffunction name="onError">
    <cfargument name="Exception" required=true/>
    <cfargument type="String" name = "EventName" required=true/>
    <!--- Log all errors. --->
    <cflog file="#This.Name#" type="error" text="Event Name: #Eventname#">
    <cflog file="#This.Name#" type="error" text="Message: #exception.message#">
    <!--- Some exceptions, including server-side validation errors, do not
             generate a rootcause structure. --->
    <cfif isdefined("exception.rootcause")>
        <cflog file="#This.Name#" type="error"
            text="Root Cause Message: #exception.rootcause.message#">
    </cfif>
    <!--- Display an error message if there is a page context. --->
    <cfif NOT (Arguments.EventName IS onSessionEnd) OR
            (Arguments.EventName IS onApplicationEnd)>
        <cfoutput>
            <h2>An unexpected error occurred.</h2>
            <p>Please provide the following information to technical support:</p>
            <p>Error Event: #EventName#</p>
            <p>Error details:<br>
            <cfdump var=#exception#></p>
        </cfoutput>
    </cfif>
 </cffunction>

</cfcomponent>


Migrating from Application.cfm to Application.cfc

To migrate an existing application that uses Application.cfm to one that uses Application.cfc, do the following:

  • Replace the cfapplication tag with CFC initialization code that sets the Application.cfc This scope variables that correspond to the tag attributes.
  • Put in the onApplicationStart method any code that initializes Application scope variables, and any other application-specific code that executes only when the application starts. Often, such code in Application.cfm is inside a block that tests for the existence of an Application scope switch variable. Remove the variable test and the Application scope lock that surrounds the code that sets the Application scope variables.
  • Put in the onSessionStart method any code that initializes Session scope variables, and any other application-specific code that executes only when the session starts. Remove any code that tests for the existence of Session scope variables to be for initialized and the Session scope lock that surrounds the code that sets the Session scope variables.
  • Put in the onRequestStart method any cflogin tag and related authentication code.
  • Put in the onRequest method any code that sets Variables scope variables and add a cfinclude tag that includes the page specified by the method’s Arguments.Targetpage variable.
  • Put in the onRequestEnd method any code you have in an OnRequestEnd.cfm page.
  • Consider replacing cferror tags with an onError event method. If you do not do so, put the cferror tags in the CFC initialization code.


Using an Application.cfm page

If you do not use an Application.cfc file, you can use the Application.cfm page to define application-level settings and functions, as described in the following sections.

  • Naming the application
  • Setting the client, application, and session variables options
  • Defining page processing settings
  • Setting application default variables and constants
  • Processing logins
  • Handling errors
  • Example: an Application.cfm page

Naming the application

Use the cfapplication tag to specify the application name and define a set of pages as part of the same logical application. Although you can create an application by putting a cfapplication tag with the application name on each page, you normally put the tag in the Application.cfm file; for example:

<cfapplication name="SearchApp">

Note: The value that you set for the name attribute in the cfapplication tag is limited to 64 characters.

Setting the client, application, and session variables options

Use the cfapplication tag to specify client state and persistent variable use, as follows:

  • To use Client scope variables, you must specify clientManagement=True.
  • To use Session scope variables, you must specify sessionManagment=True.

You can also optionally do the following:

  • Set application-specific time-outs for Application and Session scope variables. These settings override the default values set in the ColdFusion MX Administrator.
  • Specify a storage method for Client scope variables. This setting overrides the method set in the ColdFusion MX Administrator.
  • Specify not to use cookies on the client browser.

For more information on configuring these options, see Using Persistent Data and Locking, and CFML Reference.

Defining page processing settings

The cfsetting tag lets you specify page processing attributes that you might want to apply to all pages in your application. For more information, see Setting page processing options.

Setting application default variables and constants

You can set default variables and application-level constants on the Application.cfm page. For example, you can specify the following values:

  • A data source
  • A domain name
  • Style settings, such as fonts or colors
  • Other important application-level variables

Often, an Application.cfm page uses one or more cfinclude tags to include libraries of commonly used code, such as user-defined functions, that are required on many of the application’s pages.

Processing logins

When an application requires a user to log in, you typically put the cflogin tag on the Application.cfm page. For detailed information on security and creating logins, including an Application.cfm page that manages user logins, see Securing Applications.

Handling errors

You can use the cferror tag on your Application.cfm page to specify application-specific error-handling pages for request, validation, or exception errors, as shown in the example in the following section. This way you can include application-specific information, such as contact information or application or version identifiers, in the error message, and you display all error messages in the application in a consistent manner.

For more information on error pages and error handling, see Handling Errors.

Example: an Application.cfm page

The following example shows a sample Application.cfm file that uses several of the techniques typically used in Application.cfm pages. For the sake of simplicity, it does not show login processing; for a login example, see Securing Applications.

<!--- Set application name and enable Client and Session variables. --->
<cfapplication name="Products"
    clientmanagement="Yes"
    clientstorage="myCompany"
    sessionmanagement="Yes">

<!--- Set page processing attributes. --->
<cfsetting showDebugOutput="No">

<!--- Set custom global error handling pages for this application.--->
<cferror type="request"
    template="requesterr.cfm"
    mailto="admin@company.com">
<cferror type="validation"
    template="validationerr.cfm">

<!--- Set the Application variables if they aren’t defined. --->
<!--- Initialize local app_is_initialized flag to false. --->
<cfset app_is_initialized = False>
<!--- Get a read-only lock. --->
<cflock scope="application" type="readonly" timeout=10>
<!--- Read init flag and store it in local variable. --->
    <cfset app_is_initialized = IsDefined("Application.initialized")>
</cflock>
<!--- Check the local flag. --->
<cfif not app_is_initialized>
<!--- Application variables are not initialized yet.
        Get an exclusive lock to write scope. --->
    <cflock scope="application" type="exclusive" timeout=10>
        <!--- Check the Application scope initialized flag since another request
            could have set the variables after this page released the read-only
            lock. --->
        <cfif not IsDefined("Application.initialized")>
            <!--- Do initializations --->
            <cfset Application.ReadOnlyData.Company = "MyCompany">
            <!--- and so on --->
            <!--- Set the Application scope initialization flag. --->
            <cfset Application.initialized = "yes">
        </cfif>
    </cflock>
</cfif>

<!--- Set a Session variable.--->
<cflock timeout="20" scope="Session" type="exclusive">
    <cfif not IsDefined("session.pagesHit")>
        <cfset session.pagesHit=1>
    <cfelse>
        <cfset session.pagesHit=session.pagesHit+1>
    </cfif>
</cflock>

<!--- Set Application-specific Variables scope variables. --->
<cfset mainpage = "default.cfm">
<cfset current_page = "#cgi.path_info#?#cgi.query_string#">

<!--- Include a file containing user-defined functions called throughout
        the application. --->
<cfinclude template="commonfiles/productudfs.cfm">

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfapplication name="Products"
    clientmanagement="Yes"
    clientstorage="myCompany"
    sessionmanagement="Yes">

Names the application, enables Client and Session scope variables, and sets the client variable store to the myCompany data source.

<cfsetting showDebugOutput="No">

Ensures that debugging output is not displayed, if the ColdFusion MX Administrator enables it.

<cferror type="request"
    template="requesterr.cfm"
    mailto="admin@company.com">
<cferror type="validation"
    template="validationerr.cfm">

Specifies custom error handlers for request and validation errors encountered in the application. Specifies the mailing address for use in the request error handler.

<cfset app_is_initialized = False>
.
.
.

Sets the Application scope variables, if they are not already set. For a detailed description of the technique used to set the Application scope variables, see Using Persistent Data and Locking.

<cflock timeout="20"
        scope="Session"
        type="exclusive">
    <cfif not IsDefined("session.pagesHit")>
        <cfset session.pagesHit=1>
    <cfelse>
        <cfset session.pagesHit=
            session.pagesHit+1>
    </cfif>
</cflock>

Sets the Session scope pagesHit variable, which counts the number of pages touched in this session. If the variable does not exist, creates it; otherwise, increments it.

<cfset mainpage = "default.cfm">
<cfset current_page =
    "#cgi.path_info#?#cgi.query_string#">

Sets two Variables scope variables that are used throughout the application. Creates the current_page variable dynamically; its value varies from request to request.

<cfinclude template=
    "commonfiles/productudfs.cfm">

Includes a library of user-defined functions that are used in most pages in the application.


Optimizing ColdFusion applications

You can optimize your ColdFusion application in many ways. Optimizing ColdFusion mostly involves good development and coding practices. For example, good database design and usage is a prime contributor to efficient ColdFusion applications.

In several places, this manual documents optimization techniques as part of the discussion of the related ColdFusion topic. This section provides information about general ColdFusion optimization tools and strategies, and particularly about using CFML caching tags for optimization. This section also contains information on optimizing database use, an important area for application optimization.

The ColdFusion MX Administrator provides caching options for ColdFusion pages and SQL queries. For information on these options, see the ColdFusion MX Administrator online Help and Configuring and Administering ColdFusion MX.

For information on debugging techniques that can help you identify slow pages, see Debugging and Troubleshooting Applications.

For additional information on optimizing ColdFusion, see the Macromedia ColdFusion support center at www.macromedia.com/support/coldfusion.

This section describes the following topics:

  • Caching ColdFusion pages that change infrequently
  • Caching parts of ColdFusion pages
  • Optimizing database use
  • Providing visual feedback to the user


Caching ColdFusion pages that change infrequently

Some ColdFusion pages produce output that changes infrequently. For example, you might have an application that extracts a vendor list from a database or produces a quarterly results summary. Normally, when ColdFusion gets a request for a page in the application, it does all the business logic and display processing that are required to produce the report or generate and display the list. If the results change infrequently, this can be an inefficient use of processor resources and bandwidth.

The cfcache tag tells ColdFusion to cache the HTML that results from processing a page request in a temporary file on the server. This HTML does not need to be generated each time the page is requested. When ColdFusion gets a request for a cached ColdFusion page, it retrieves the pregenerated HTML page without having to process the ColdFusion page. ColdFusion can also cache the page on the client. If the client browser has its own cached copy of the page from a previous viewing, ColdFusion instructs the browser to use the client’s page rather than resending the page.

Note: The cfcache tag caching mechanism considers that each URL is a separate page. Therefore, http://www.mySite.com/view.cfm?id=1 and http://www.mySite.com/view.cfm?id=2 result in two separate cached pages. Because ColdFusion caches a separate page for each unique set of URL parameters, the caching mechanism accommodates pages for which different parameters result in different output.

Using the cfcache tag

You tell ColdFusion to cache the page results by putting a cfcache tag on your ColdFusion page before code that outputs text. The tag lets you specify the following information:

  • Whether to cache the page results on the server, the client system, or both. The default is both. The default is optimal for pages that are identical for all users. If the pages contain client-specific information, or are secured with ColdFusion user security, set the action attribute in the cfcache tag to ClientCache.
  • The directory on the server in which to store the cached pages. The default directory is cf_root/cache. It is a good practice to create a separate cache directory for each application. Doing so can prevent the cfcache tag flush action from inappropriately flushing more than one application’s caches at a time.
  • The time span that indicates how long the page lasts in the cache from when it is stored until it is automatically flushed.

You can also specify several attributes for accessing a cached page on the web server, including a user name and password (if required by the web server), the port, and the protocol (HTTP or HTTPS) to use to access the page.

Place the cfcache tag before any code on your page that generates output, typically at the top of the page body. For example, the following tag tells ColdFusion to cache the page on both the client and the server. On the server, the page is cached in the e:/temp/page_cache directory. ColdFusion retains the cached page for one day.

<cfcache timespan="#CreateTimespan(1, 0, 0, 0)#" directory="e:/temp/page_cache">

Caution: If an Application.cfm or Application.cfc page displays text (for example, if it includes a header page), use the cfcache tag on the Application.cfm page, in addition to the pages that you cache. Otherwise, ColdFusion displays the Application.cfm page output twice on each cached page.

Flushing cached pages

ColdFusion automatically flushes any cached page if you change the code on the page. It also automatically flushes pages after the expiration timespan passes.

You can use the cfcache tag with the action="flush" attribute to immediately flush one or more cached pages. You can optionally specify the directory that contains the cached pages to be flushed and a URL pattern that identifies the pages to flush. If you do not specify a URL pattern, all pages in the directory are flushed. The URL pattern can include asterisk (*) wildcards to specify parts of the URL that can vary.

When you use the cfcache tag to flush cached pages, ColdFusion deletes the pages cached on the server. If a flushed page is cached on the client system, it is deleted, and a new copy gets cached the next time the client tries to access the ColdFusion page.

The following example flushes all the pages in the e:/temp/page_cache/monthly directory that start with HR:

<cfcache action="flush" directory="e:/temp/page_cache/monthly" expirURL="HR*">

If you have a ColdFusion page that updates data that you use in cached pages, the page that does the updating includes a cfcache tag that flushes all pages that use the data.

For more information on the cfcache tag, see CFML Reference.


Caching parts of ColdFusion pages

In some cases, your ColdFusion page might contain a combination of dynamic information that ColdFusion must generate each time it displays the page, and information that it generates dynamically, but that change less frequently. In this case, you cannot use the cfcache tag to cache the entire page. Instead, use the cfsavecontent tag to cache the infrequently changed content.

The cfsavecontent tag saves the results of processing the tag body in a variable. For example, if the body of the cfsavecontent tag contains a cfexecute tag that runs an executable program that displays data, the variable saves the output.

You can use the cfsavecontent tag to cache infrequently changing output in a shared scope variable. If the information is used throughout the application, save the output in the Application scope. If the information is client-specific, use the Session scope. Because of the overhead of locking shared scope variables, use this technique only if the processing overhead of generating the output is substantial.

Before you use this technique, also consider whether other techniques are more appropriate. For example, query caching eliminates the need to repeat a common query. However, if the effort of processing the data or formatting the output is substantial, using the cfsavecontent tag can save processing time.

Using this technique, if the variable exists, the page uses the cached output. If the variable does not exist, the page gets the data, generates the output, and saves the results to the shared scope variable.

The following example shows this technique. It has two parts. The first part welcomes the user and prints out a random lucky number. This part runs and produces a different number each time a user opens the page. The second part performs a database query to get information that changes infrequently; in this example, a listing of the current special sale items. It uses the cfsavecontent tag to get the data only when needed.

Tip: If you use this technique frequently, consider incorporating it in a custom CFML tag.

<!--- Greet the user. --->
<cfoutput>
    Welcome to our home page.<br>
    The time is #TimeFormat(Now())#.<br>
    Your lucky number is: #RandRange(1,1000)#<br>
    <hr><br>
</cfoutput>

<!--- Set a flag to indicate whether the Application scope variable exists.--->
<cflock scope="application" timeout="20" type="readonly">
    <cfset IsCached = Not IsDefined("Application.ProductCache")>
</cflock>

<!--- If the flag is false, query the DB, and save an image of
    the results output to a variable. --->
<cfif not IsCached>
    <cfsavecontent variable="ProductCache">
    <!--- Perform database query. --->
        <cfquery dataSource="ProductInfo" name="specialQuery">
            SELECT ItemName, Item_link, Description, BasePrice
            FROM SaleProducts
        </cfquery>
<!--- Calculate sale price and display the results. --->
        <h2>Check out the following specials</h2>
        <table>
        <cfoutput query="specialQuery">
            <cfset salePrice= BasePrice * .8>
            <tr>
                <td>#ItemNAme#</td>
                <td>#Item_Link#</td>
                <td>#Description#</td>
                <td>#salePrice#</td>
            </tr>
        </cfoutput>
        </table>
    </cfsavecontent>

<!--- Save the results in the Application scope. --->
    <cflock scope="Application" type="Exclusive" timeout=30>
        <cfset Application.productCache = ProductCache>
    </cflock>
</cfif>

<!--- Use the Application scope variable to display the sale items. --->
<cflock scope="application" timeout="20" type="readonly">
    <cfoutput>#Application.ProductCache#</cfoutput>
</cflock>

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfoutput>
    Welcome to our home page.<br>
    The time is #TimeFormat(Now())#.<br>
    Your lucky number is:
        #RandRange(1,1000)#<br>
    <hr><br>
</cfoutput>

Displays the part of the page that must change each time.

<cflock scope="application" timeout="20"
        type="readonly">
    <cfset IsCached = IsDefined
        ("Application.ProductCache")>
</cflock>

Inside a read-only lock, tests to see if the part of the page that changes infrequently is already cached in the Application scope, and sets a Boolean flag variable with the result.

<cfif not IsCached>
    <cfsavecontent variable="ProductCache">

If the flag is False, uses a cfsavecontent tag to save output in a Variables scope variable. Using the Variables scope eliminates the need to do a query (which can take a long time) in an Application scope lock.

<cfquery dataSource="ProductInfo"
        name="specialQuery">
    SELECT ItemName, Item_link,
        Description, BasePrice
    FROM SaleProducts
</cfquery>

Queries the database to get the necessary information.

<h2>Check out the following specials</h2>
<table>
    <cfoutput query="specialQuery">
        <cfset salePrice = BasePrice * .8>
        <tr>
            <td>#ItemNAme#</td>
            <td>#Item_Link#</td>
            <td>#Description#</td>
            <td>#salePrice#</td>
        </tr>
    </cfoutput>
    </table>

Displays the sale items in a table. Inside a cfoutput tag, calculates each item’s sale price and displays the item information in a table row.

Because this code is inside a cfsavecontent tag, ColdFusion does not display the results of the cfoutput tag. Instead, it saves the formatted output as HTML and text in the ProductCache variable.

</cfsavecontent>

Ends the cfsavecontent tag block.

<cflock scope="Application" type="Exclusive"
        timeout=30>
    <cfset Application.productCache =
        productcache>
</cflock>

Inside an Exclusive cflock tag, saves the contents of the local variable ProductCache in the Application scope variable Application.productCache.

</cfif>

Ends the code that executes only if the Application.productCache variable does not exist.

<cflock scope="application" timeout="20"
        type="readonly">
    <cfoutput>#Application.ProductCache#</cfoutput>
</cflock>

Inside a cflock tag, displays the contents of the Application.productCache variable.


Optimizing database use

Poor database design and incorrect or inefficient use of the database are among the most common causes of inefficient applications. Consider the different methods that are available for using databases and information from databases when you design your application. For example, if you need to average the price of a number of products from an SQL query, it is more efficient to use SQL to get the average than to use a loop in ColdFusion.

Two important ColdFusion MX tools for optimizing your use of databases are the cfstoredproc tag and the cfquery tag cachedWithin attribute.

Using stored procedures

The cfstoredproc tag lets ColdFusion MX use stored procedures in your database management system. A stored procedure is a sequence of SQL statements that is assigned a name, compiled, and stored in the database system. Stored procedures can encapsulate programming logic in SQL statements, and database systems are optimized to execute stored procedures efficiently. As a result, stored procedures are faster than cfquery tags.

You use the cfprocparam tag to send parameters to the stored procedure, and the cfprocresult tag to get the record sets that the stored procedure returns.

The following example executes a Sybase stored procedure that returns three result sets, two of which the example uses. The stored procedure returns the status code and one output parameter, which the example displays.

<!--- cfstoredproc tag --->
<cfstoredproc procedure = "foo_proc" dataSource = "MY_SYBASE_TEST"
    username = "sa" password = "" returnCode = "Yes">

    <!--- cfprocresult tags --->
    <cfprocresult name = RS1>
    <cfprocresult name = RS3 resultSet = 3>

    <!--- cfprocparam tags --->
    <cfprocparam type = "IN"
        CFSQLType = CF_SQL_INTEGER
            value = "1" 	dbVarName = @param1>
    <cfprocparam type = "OUT"	CFSQLType = CF_SQL_DATE
        variable = FOO dbVarName = @param2>
<!--- Close the cfstoredproc tag. --->
</cfstoredproc>

<cfoutput>
    The output param value: '#foo#'<br>
</cfoutput>

<h3>The Results Information</h3>
<cfoutput query = RS1>
    #name#,#DATE_COL#<br>
</cfoutput>
<br>
<cfoutput>
    <hr>
    Record Count: #RS1.recordCount#<br>
    Columns: #RS1.columnList#<br>
    <hr>
</cfoutput>

<cfoutput query = RS3>
    #col1#,#col2#,#col3#<br>
</cfoutput>
<br>
<cfoutput>
    <hr><br>
    Record Count: #RS3.recordCount#<br>
    Columns: #RS3.columnList#<br>
    <hr>

    The return code for the stored procedure is: '#cfstoredproc.statusCode#'<br>
</cfoutput>

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfstoredproc procedure = "foo_proc"
    dataSource = "MY_SYBASE_TEST" username = "sa"
    password = "" returnCode = "Yes">

Runs the stored procedure foo_proc on the MY_SYBASE_TEST data source. Populates the cfstoredproc statusCode variable with the status code returned by stored procedure.

<cfprocresult name = RS1>
<cfprocresult name = RS3 resultSet = 3>

Gets two record sets from the stored procedure: the first and third result sets it returns.

<cfprocparam type = "IN"
    CFSQLType = CF_SQL_INTEGER
        value = "1" dbVarName = @param1>
<cfprocparam type = "OUT" CFSQLType = CF_SQL_DATE
    variable = FOO dbVarName = @param2>
</cfstoredproc>

Specifies two parameters for the stored procedure, an input parameter and an output parameter. Sets the input parameter to 1 and the ColdFusion variable that gets the output to FOO.

Ends the cfstoredproc tag body.

<cfoutput>
    The output param value: '#foo#'<br>
</cfoutput>

<h3>The Results Information</h3>
<cfoutput query = RS1>
    #name#,#DATE_COL#<br>
</cfoutput>
<br>

<cfoutput>
    <hr>
    Record Count: #RS1.recordCount#<br>
    Columns: #RS1.columnList#<br>
    <hr>
</cfoutput>

<cfoutput query = RS3>
    #col1#,#col2#,#col3#<br>
</cfoutput>
<br>

<cfoutput>
    <hr><br>
    Record Count: #RS3.recordCount#<br>
    Columns: #RS3.columnList#<br>
    <hr>
    The return code for the stored procedure is:
    '#cfstoredproc.statusCode#'<br>
</cfoutput>

Displays the results of running the stored procedure:

  • The output parameter value,
  • The contents of the two columns in the first record set identified by the name and DATE_COL variables. You set the values of these variables elsewhere on the page.
  • The number of rows and the names of the columns in the first record set
  • The contents of the columns in the other record set identified by the col1, col2, and col3 variables.
  • The number of rows and the names of the columns in the record set.
  • The status value returned by the stored procedure.

For more information on creating stored procedures, see your database management software documentation. For more information on using the cfstoredproc tag, see CFML Reference.

Using the cfquery tag cachedWithin attribute

The cfquery tag cachedWithin attribute tells ColdFusion to save the results of a database query for a specific period of time. This way, ColdFusion accesses the database on the first page request, and does not query the database on further requests until the specified time expires. Using the cachedWithin attribute can significantly limit the overhead of accessing databases that do not change rapidly.

This technique is useful if the database contents only change at specific, known times, or if the database does not change frequently and the purpose of the query does not require absolutely up- to-date results.

You must use the CreateTimeSpan function to specify the cachedWithin attribute value (in days, hours, minutes, seconds format). For example, the following code caches the results of getting the contents of the Employees table of the cfdocexamples data source for one hour.

<cfquery datasource="cfdocexamples" name="master"

    cachedWithin=#CreateTimeSpan(0,1,0,0)#>
    SELECT * FROM Employees
</cfquery>


Providing visual feedback to the user

If an application might take a while to process data, it is useful to provide visual feedback to indicate that something is happening, so the user does not assume that there is a problem and request the page again. Although doing this does not optimize your application’s processing efficiency, it does make the application appear more responsive.

You can use the cfflush tag to return partial data to a user, as shown in Introduction to Retrieving and Formatting Data.

You can also use the cfflush tag to create a progress bar. For information on this technique, see the technical article "Understanding Progress Meters in ColdFusion 5" at www.macromedia.com/v1/handlers/index.cfm?id=21216&method=full. (Although this article was written for ColdFusion 5, it also applies to ColdFusion MX.)
Previous


Handling Errors

Macromedia ColdFusion MX includes many tools and techniques for responding to errors that your application encounters. These tools include error handling mechanisms and error logging tools. This chapter describes these tools and how to use them.

This chapter does not discuss techniques for preventing errors, including methods for specifying user input validation. It also does not discuss code debugging. For information on user input validation, see Introduction to Retrieving and Formatting Data and Building Dynamic Forms with cfform Tags. For information on debugging, see Debugging and Troubleshooting Applications.

Contents

About error handling in ColdFusion

Understanding errors

Error messages and the standard error format

Determining error-handling strategies

Specifying custom error messages with the cferror tag

Logging errors with the cflog tag

Handling runtime exceptions with ColdFusion tags
Next


About error handling in ColdFusion

By default, ColdFusion generates its own error messages when it encounters errors. In addition, it provides a variety of tools and techniques for you to customize error information and handle errors when they occur. You can use any of the following error-management techniques.

  • Specify custom pages for ColdFusion to display in each of the following cases:
    • When a ColdFusion page is missing (the Missing Template Handler page)
    • When an otherwise-unhandled exception error occurs during the processing of a page (the Site-wide Error Handler page)

    You specify these pages on the Settings page in the Server Settings are in the ColdFusion MX Administrator; for more information, see the ColdFusion MX Administrator Help.

  • Use the cferror tag to specify ColdFusion pages to handle specific types of errors.
  • Use the cftry, cfcatch, cfthrow, and cfrethrow tags to catch and handle exception errors directly on the page where they occur.
  • In CFScript, use the try and catch statements to handle exceptions.
  • Use the onError event in Application.cfc to handle exception errors that are not handled by try/catch code on the application pages.
  • Log errors. ColdFusion logs certain errors by default. You can use the cflog tag to log other errors.

The remaining sections in this chapter provide the following information:

  • The basic building blocks for understating types of ColdFusion errors and how ColdFusion handles them
  • How to use the cferror tag to specify error-handling pages
  • How to log errors
  • How to handle ColdFusion exceptions

Note: This chapter discusses using the cftry and cfcatch tags, but not the equivalent CFScript try and catch statements. The general discussion of exception handling in this chapter applies to tags and CFScript statements. However, the code that you use and the information available in CFScript differs from those in the tags. For more information on handling exceptions in CFScript, see Handling errors in UDFs.


Understanding errors

There are many ways to look at errors; for example, you can look at errors by their causes. You can also look at them by their effects, particularly by whether your application can recover from them. You can also look at them the way ColdFusion does. The following sections discuss these ways of looking at errors.

This section describes the following topics:

  • About error causes and recovery
  • ColdFusion error types
  • About ColdFusion exceptions
  • How ColdFusion handles errors

About error causes and recovery

Errors can have many causes. Depending on the cause, the error might be recoverable. A recoverable error is one for which your application can identify the error cause and take action on the problem. Some errors, such as time-out errors, might be recoverable without indicating to the user that an error was encountered. An error for which a requested application page does not exist is not recoverable, and the application can only display an error message.

Errors such as validation errors, for which the application cannot continue processing the request, but can provide an error-specific response, can also be considered recoverable. For example, an error that occurs when a user enters text where a number is required can be considered recoverable, because the application can recognize the error and redisplay the data field with a message providing information about the error’s cause and telling the user to reenter the data.

Some types of errors might be recoverable in some, but not all circumstances. For example, your application can retry a request following a time-out error, but it must also be prepared for the case where the request always times out.

Error causes fall in the broad categories listed in the following table:

Category | Description
Program errors | Can be in the code syntax or the program logic. The ColdFusion compiler identifies and reports program syntax errors when it compiles CFML into Java classes. Errors in your application logic are harder to locate. For information on debugging tools and techniques, see Debugging and Troubleshooting Applications. Unlike ColdFusion syntax errors, SQL syntax errors are only caught at runtime.
Data errors | Are typically user data input errors. You use validation techniques to identify errors in user input data and enable the user to correct the errors.
System errors | Can come from a variety of causes, including database system problems, time-outs due to excessive demands on your server, out-of-memory errors in the system, file errors, and disk errors.

Although these categories do not map completely to the way ColdFusion categorizes errors they provide a useful way of thinking about errors and can help you in preventing and handling errors in your code.


ColdFusion error types

Before you can effectively manage ColdFusion errors, you must understand how ColdFusion classifies and handles them. ColdFusion categorizes errors as detailed in the following table:

Type

Description

Exception

An error that prevents normal processing from continuing. All ColdFusion exceptions are, at their root, Java exceptions.

Missing template

An HTTP request for a ColdFusion page that cannot be found. Generated if a browser requests a ColdFusion page that does not exist.

Missing template errors are different from missing include exceptions, which result from cfinclude tags or custom tag calls that cannot find their targets.

Form field data validation

Server-side form field validation errors are a special kind of ColdFusion MX exception. You specify server-side form validation by using cfform attributes or hidden HTML form fields. All other types of server-side validation, such as the cfparam tag generate runtime exceptions. For more information on validating form fields see Validating Data.

ColdFusion includes a built-in error page for server-side form field validation errors, and the cferror tag includes a type attribute that lets you handle these errors in a custom error page, but if you use onError processing in Application.cfc, or try/catch error handling, the error appears as an Application exception. For more information on handling Form field validation in Application.cfc see Handling server-side validation errors in the onError method.

Note: The onSubmit and onBlur form field validation techniques use JavaScript or Macromedia Flash validation on the client browser; this chapter does not discuss client-side validation errors.

Most ColdFusion errors are exceptions. The following sections describe them in detail.


About ColdFusion exceptions

You can categorize ColdFusion exceptions in two ways:

  • When they occur
  • Their type

When exceptions occur

ColdFusion errors can occur at two times, when the CFML is compiled into Java and when the resulting Java executes, called runtime exceptions.

Compiler exceptions

Compiler exceptions are programming errors that ColdFusion identifies when it compiles CFML into Java. Because compiler exceptions occur before the ColdFusion page is converted to executable code, you cannot handle them on the page that causes them. However, other pages can handle these errors. For more information, see Handling compiler exceptions

Runtime exception

A runtime exception occurs when the compiled ColdFusion Java code runs. It is an event that disrupts the application’s normal flow of instructions. Exceptions can result from system errors or program logic errors. Runtime exceptions include:

  • Error responses from external services, such as an ODBC driver or CORBA server
  • CFML errors or the results of cfthrow or cfabort tags
  • Internal errors in ColdFusion MX

ColdFusion exception types

ColdFusion exceptions have types that you specify in the cferror, cfcatch, and cfthrow error-handling tags. A cferror or cfcatch tag will handle only exceptions of the specified type. You identify an exception type by using an identifier from one (or more) of the following type categories:

  • Basic
  • Custom
  • Advanced
  • Java class

Note: Use only custom error type names and the Application basic type name in cfthrow tags. All other built-in exception type names identify specific types of system-identified errors, so you should not use them for errors that you identify yourself.

Basic exception types

All ColdFusion exceptions except for custom exceptions belong to a basic type category. These types consist of a broadly-defined categorization of ColdFusion exceptions. The following table describes the basic exception types:

Type

Type name

Description

Database failures

Database

Failed database operations, such as failed SQL statements, ODBC problems, and so on.

Missing include file errors

MissingInclude

Errors where files specified by the cfinclude, cfmodule, and cferror tags are missing. (A cferror tag generates a missingInclude error only when an error of the type specified in the tag occurs.)

The MissingInclude error type is a subcategory of Template error. If you do not specifically handle the MissingInclude error type, but do handle the Template error type, the Template error handler catches these errors. MissingInclude errors are caught at runtime.

Template errors

Template

General application page errors, including invalid tag and attribute names. Most Template errors are caught at compile time, not runtime.

Object exceptions

Object

Exceptions in ColdFusion code that works with objects.

Security exceptions

Security

Catchable exceptions in ColdFusion code that works with security.

Expression exceptions

Expression

Failed expression evaluations; for example, if you try to add 1 and "a".

Locking exceptions

Lock

Failed locking operations, such as when a cflock critical section times out or fails at runtime.

Verity Search engine exception

SearchEngine

Exceptions generated by the Verity search engine when processing cfindex, cfcollection, or cfsearch tags.

Application-defined exception events raised by cfthrow

Application

Custom exceptions generated by a cfthrow tag that do not specify a type, or specify the type as Application.

All exceptions

Any

Any exceptions. Includes all types in this table and any exceptions that are not specifically handled in another error handler, including unexpected internal and external errors.

Note: The Any type includes all error with the Java object type of java.lang.Exception. It does not include java.lang.Throwable errors. To catch Throwable errors, specify java.lang.Throwable in the cfcatch tag type attribute.

Custom exceptions

You can generate an exception with your own type by specifying a custom exception type name, for example MyCustomErrorType, in a cfthrow tag. You then specify the custom type name in a cfcatch or cferror tag to handle the exception. Custom type names must be different from any built-in type names, including basic types and Java exception classes.

Advanced exception types

The Advanced exceptions consist of a set of specific, narrow exception types. These types are supported in ColdFusion MX for backward-compatibility. For a list of advanced exception types, see Advanced Exception types in ColdFusion Tags in CFML Reference.

Java exception classes

Every ColdFusion exception belongs to, and can be identified by, a specific Java exception class in addition to its basic, custom, or advanced type. The first line of the stack trace in the standard error output for an exception identifies the exception’s Java class.

For example, if you attempt to use an array function such as ArrayIsEmpty on an integer variable, ColdFusion generates an exception that belongs to the Expression exception basic type and the coldfusion.runtime.NonArrayException Java class.

In general, most applications do not need to use Java exception classes to identify exceptions. However, you can use Java class names to catch exceptions in non-CFML Java objects; for example, the following line catches all Java input/output exceptions:

<cfcatch type="java.io.IOException">


How ColdFusion handles errors

The following sections describe briefly how ColdFusion handles errors. The rest of this chapter expands on this information.

Missing template errors

If a user requests a page that the ColdFusion cannot find, and the Administrator Server Settings Missing Template Handler field specifies a Missing Template Handler page, ColdFusion uses that page to display error information. Otherwise, it displays a standard error message.

Form field validation errors

When a user enters invalid data in an HTML tag that uses onServer or hidden form field server-side data validation ColdFusion does the following:

  1. If the Application CFC (Application.cfc) has an onError event handler method, ColdFusion calls the method.
  2. If the Application.cfc initialization code or the Application.cfm page has a cferror that specifies a Validation error handler, ColdFusion displays the specified error page.
  3. Otherwise, it displays the error information in a standard format that consists of a default header, a bulleted list describing the errors, and a default footer.

For more information on using hidden form field validation, see Validating Data. For more information on Application.cfc, see Designing and Optimizing a ColdFusion Application

Compiler exception errors

If ColdFusion encounters a compiler exception, how it handles the exception depends on whether the error occurs on a requested page or on an included page:

  • If the error occurs on a page that is accessed by a cfinclude or cfmodule tag, or on a custom tag page that you access using the cf_ notation, ColdFusion handles it as a runtime exception in the page that accesses the tag. See the Runtime exception errors section, next, for a description of how these errors are handled.
  • If the error occurs directly on the requested page, and the Administrator Settings Site-wide Error Handler field specifies an error handler page, ColdFusion displays the specified error page. Otherwise, ColdFusion reports the error using the standard error message format described in Error messages and the standard error format.

Runtime exception errors

If ColdFusion encounters a runtime exception, it does the action for the first matching condition in the following table:

Condition | Action
The code with the error is inside a cftry tag and the exception type is specified in a cfcatch tag. | Executes the code in the cfcatch tag. If the cftry block does not have a cfcatch tag for this error, tests for an appropriate cferror handler or site-wide error handler.
The ColdFusion MX application has an Application.cfc with an onError method | Executes the code in the onError method. For more information on using the onError method, see Handling errors in Application.cfc
A cferror tag specifies an exception error handler for the exception type. | Uses the error page specified by the cferror tag.
The Administrator Settings Site-wide Error Handler field specifies an error handler page. | Uses the custom error page specified by the Administrator setting.
A cferror tag specifies a Request error handler. | Uses the error page specified by the cferror tag.
The default case. | Uses the standard error message format

For example, if an exception occurs in CFML code that is not in a cftry block, and Application.cfc does not have an onError method, but a cferror tag specifies a page to handle this error type, ColdFusion uses the specified error page.


Error messages and the standard error format

If your application does not handle an error, ColdFusion displays a diagnostic message in the user’s browser.

Error information is also written to a log file for later review. (For information on error logging, see Logging errors with the cflog tag.)

The standard error format consists of the information listed in the following table. ColdFusion does not always display all sections.

Section

Description

Error description

A brief, typically on-line, description of the error.

Error message

A detailed description of the error. The error message diagnostic information displayed depends on the type of error. For example, if you specify an invalid attribute for a tag, this section includes a list of all valid tag attributes.

Error location

The page and line number where ColdFusion encountered the error, followed by a short section of your CFML that includes the line. This section does not display for all errors.

In some cases, the cause of an error can be several lines above the place where ColdFusion determines that there is a problem, so the line that initially causes the error might not be in the display.

Resources

Links to documentation, the Knowledge Base, and other resources that can help you resolve the problem.

Error environment information

Information about the request that caused the error. All error messages include the following:

  • User browser
  • User IP address
  • Date and time of error

Stack trace

The Java stack at the time of the exception, including the specific Java class of the exception. This section can be helpful if you must contact Macromedia Technical Support.

The stack trace is collapsed by default. Click the heading to display the trace.

Tip: If you get a message that does not explicitly identify the cause of the error, check the key system parameters, such as available memory and disk space.


Determining error-handling strategies

ColdFusion provides you with many options for handling errors, particularly exceptions, as described in the section How ColdFusion handles errors. This section describes considerations for determining which forms of error handling to use.

Handling missing template errors

Missing template errors occur when ColdFusion receives an HTTP request for a page ending in .cfm that it cannot find. You can create your own missing template error page to present application-specific information or provide an application-specific appearance. You specify the missing template error page on the Administrator Settings page.

The missing error page can use CFML tags and variables. In particular, you can use the CGI.script_name variable in text such as the following to identify the requested page:

<cfoutput>The page #Replace(CGI.script_name, "/", "")# is not available.<br>
Make sure that you entered the page correctly.<br>
</cfoutput>

(In this code, the Replace function removes the leading slash sign from the script name to make the display more friendly.)

Handling form field validation errors

When you use server-side form field validation, the default validation error message describes the error cause plainly and clearly. However, you might want to give the error message a custom look or provide additional information such as service contact phone numbers and addresses. In this case, use the cferror tag with the Validation attribute in the Application.cfc initialization code or on the Application.cfm page to specify your own validation error handler. The section Example of a validation error page provides an example of such a page. You can also put form field validation error handling code in the Application.cfc onError method.

Handling compiler exceptions

You cannot handle compiler exceptions directly on the page where they occur, because the exception is caught before ColdFusion starts running the page code. You should fix all compiler exceptions as part of the development process. Use the reported error message and the code debugging techniques discussed in Debugging and Troubleshooting Applications to identify and correct the cause of the error.

Compiler exceptions that occur on pages you access by using the cfinclude or cfmodule tags can actually be handled as runtime errors by surrounding the cfinclude or cfmodule tag in a cftry block. The compiler exception on the accessed page gets caught as a runtime error on the base page. However, you should avoid this "solution" to the problem, as the correct method for handling compiler errors is to remove them before you deploy the application.

Handling runtime exceptions

You have many choices for handling exceptions, and the exact path you take depends on your application and its needs. The following table provides a guide to selecting an appropriate technique:

Technique

Use

cftry

Place cftry blocks around specific code sections where exceptions can be expected and you want to handle those exceptions in a context-specific manner; for example, if you want to display an error message that is specific to that code.

Use cftry blocks where you can recover from an exception. For example, you can retry an operation that times out, or access an alternate resource. You can also use the cftry tag to continue processing where a specific exception will not harm your application; for example, if a missing resource is not required.

For more information, see Handling runtime exceptions with ColdFusion tags.

Application.cfc onError method

Implement the onError method in your Application.cfc to consistently handle application-specific exceptions that might be generated by multiple code sections in the application. For more information on error handling using Application.cfc, see Handling errors in Application.cfc.

cferror with exception- specific error handler pages

Use the cferror tag to specify error pages for specific exception types. These pages cannot recover from errors, but they can provide the user with information about the error’s cause and steps that they can take to prevent the problem.

For more information, see Specifying custom error messages with the cferror tag.

cferror with a Request error page

Use the cferror tag to specify a Request error handler that provides a customized, application-specific message for unrecoverable exceptions. Put the tag in the Application.cfc initialization code or on the Application.cfm page to make it apply to all pages in an application.

A Request error page cannot use CFML tags, but it can display error variables. As a result, you can use it to display common error information, but you cannot provide error-specific instructions. Typically, Request pages display error variable values and application-specific information, including support contact information.

For example code, see Example of a request error page.

Site-wide error handler page

Specify a site-wide error handler in the Administrator to provide consistent appearance and contents for all otherwise-unhandled exceptions in all applications on your server.

Like the Request page, the site-wide error handler cannot perform error recovery. However, it can include CFML tags in addition to the error variables.

Because a site-wide error handler prevents ColdFusion from displaying the default error message, it allows you to limit the information reported to users. It also lets you provide all users with default contact information or other instructions.


Specifying custom error messages with the cferror tag

Custom error pages let you control the error information that users see. You can specify custom error pages for different types of errors and handle different types of errors in different ways. For example, you can create specific pages to handle errors that could be recoverable, such as request time-outs. You can also make your error messages consistent with the look and feel of your application.

You can specify the following types of custom error message pages:

Type

Description

Validation

Handles server-side form field data validation errors. The validation error page cannot include CFML tags, but it can display error page variables.

You can use this attribute only in the Application.cfc initialization code or on the Application.cfm page. It has no effect when used on any other page. Therefore, you can specify only one validation error page per application, and that page applies to all server-side validation errors.

Exception

Handles specific exception errors. You can specify individual error pages for different types of exceptions.

Request

Handles any exception that is not otherwise-handled. The request error page runs after the CFML language processor finishes. As a result, the request error page cannot include CFML tags, but can display error page variables. A request error page is useful as a backup if errors occur in other error handlers.

Specifying a custom error page

You specify the custom error pages with the cferror tag. For Validation errors, the tag must be in the Application.cfc initialization code or on the Application.cfm page. For Exception and Request errors, you can set the custom error pages on each application page. However, because custom error pages generally apply to an entire application, it is more efficient to put these cferror tags in the Application.cfc or Application.cfm file also. For more information on using these pages, see Designing and Optimizing a ColdFusion Application.

The cferror tag has the attributes listed in the following table:

Attribute | Description
Type | The type of error that will cause ColdFusion to display this page: Exception, Request, or Validation.
Exception | Use only for the Exception type. The specific exception or exception category that will cause the page to be displayed. This attribute can specify any of the types described in About ColdFusion exceptions.
Template | The ColdFusion page to display.
MailTo | (Optional) An e-mail address. The cferror tag sets the error page error.mailTo variable to this value. The error page can use the error.mailTo value in a message that tells the user to send an error notification. ColdFusion does not send any message itself.

The following cferror tag specifies a custom error page for exceptions that occur in locking code and informs the error page of the of an e-mail address it can use to send a notification each time this type of error occurs:

<cferror type = "exception"
exception = "lock"
template = "../common/lockexcept.cfm"
mailto = "server@mycompany.com">

For detailed information on the cferror tag, see CFML Reference.

Creating an error application page

The following table lists the rules and considerations that apply to error application pages:

Type

Considerations

Validation
  • Cannot use CFML tags.
  • Can use HTML tags.
  • Can use the Error.InvalidFields, Error.validationHeader, and Error.validationFooter variables by enclosing them with number signs (#).
  • Cannot use any other CFML variables.

Request

  • Cannot use CFML tags.
  • Can use HTML tags.
  • Can use nine CFML error variables, such as Error.Diagnostics, by enclosing them with number signs.
  • Cannot use other CFML variables.

Exception
  • Can use full CFML syntax, including tags, functions, and variables.
  • Can use nine standard CFML Error variables and cfcatch variables. Use either Error or cferror as the prefix for both types of variables.
  • Can use other application-defined CFML variables.
  • To display any CFML variable, use the cfoutput tag.

The following table describes the variables available on error pages:

Error page type | Error variable | Description
Validation | error.invalidFields | Unordered list of validation errors that occurred. This includes any text that you specify in the value attribute or a hidden tag used to validate form input.
 | error.validationHeader | Text for the header of the default validation message.
 | error.validationFooter | Text for the footer of the default validation message.
Exception and request | error.browser | Browser that was running when the error occurred.
 | error.dateTime | Date and time when the error occurred.
 | error.diagnostics | Detailed error diagnostics.
 | error.generatedContent | Any content that ColdFusion generated in response to the request prior to the error.
 | error.HTTPReferer | Page containing the HTML link to the page on which the error occurred. This value is an empty string if the user specified the page directly in the browser.
 | error.mailTo | E-mail address of the administrator who should be notified. This value is set in the mailTo attribute of the cferror tag.
 | error.queryString | URL query string of the client's request, if any.
 | error.remoteAddress | IP address of the remote client.
 | error.template | Page being executed when the error occurred.
Exception only | error.message | Error message associated with the exception.
 | error.rootCause | Java servlet exception reported by the JVM as the cause of the "root cause" of the exception. This variable is a Java object.
 | error.tagContext | Array of structures containing information for each tag in the tag stack The tag stack consists of each tag that is currently open. For more information, see Exception information in cfcatch blocks
 | error.type | Exception type. For more information, see About ColdFusion exceptions.

Exception error pages can also use all of the exception variables listed in the section Exception information in cfcatch blocks. To use these variables, replace the cfcatch prefix with cferror or error. For example, to use the exception message in an error page, refer to it as error.message.

In general, production Exception and Request pages should not display detailed error information, such as that supplied by the error.diagnostics variable. Typically, Exception pages e-mail detailed error information to an administrative address or log the information using the cflog tag instead of displaying it to the user. For more information on using the cflog tag, see Logging errors with the cflog tag.

Example of a request error page

The following example shows a custom error page for a request error:

<html>
<head>
<title>Products - Error</title>
</head>
<body>

<h2>Sorry</h2>

<p>An error occurred when you requested this page.</p>
<p>Please send e-mail with the following information to #error.mailTo# to report
this error.</p>

<table border=1>
<tr><td><b>Error Information</b> <br>
    Date and time: #error.DateTime# <br>
    Page: #error.template# <br>
    Remote Address: #error.remoteAddress# <br>
    HTTP Referer: #error.HTTPReferer#<br>
</td></tr></table>

<p>We apologize for the inconvenience and will work to correct the problem.</p>
</body>
</html>

Example of a validation error page

The following example shows a simple custom error page for a validation error:

<html>
<head>
<title>Products - Error</title>
</head>
<body>

<h2>Data Entry Error</h2>

<p>You failed to correctly complete all the fields
in the form. The following problems occurred:</p>

#error.invalidFields#

</body>
</html>


Logging errors with the cflog tag

ColdFusion provides extensive capabilities for generating, managing, and viewing log files, as described in Configuring and Administering ColdFusion MX. It also provides the cflog tag which adds entries to ColdFusion logs.

ColdFusion automatically logs errors to the default logs if you use the default error handlers. In all other cases, you must use the cflog tag in your error handling code to generate log entries.

The cflog tag lets you specify the following information:

  • A custom file or standard ColdFusion log file in which to write the message.
  • Text to write to the log file. This can include the values of all available error and cfcatch variables.
  • Message severity (type): Information Warning, Fatal, or Error.
  • Whether to log any of the following: application name, thread ID, system date, or system time. By default, all get logged.

For example, you could use a cflog tag in an exception error-handling page to log the error information to an application-specific log file, as in the following page:

<html>
<head>
<title>Products - Error</title>
</head>
<body>

<h2>Sorry</h2>

<p>An error occurred when you requested this page.
The error has been logged and we will work to correct the problem.
We apologize for the inconvenience. </p>

<cflog type="Error"
        file="myapp_errors"
        text="Exception error --
            Exception type: #error.type#
            Template: #error.template#,
            Remote Address: #error.remoteAddress#,
            HTTP Reference: #error.HTTPReferer#
            Diagnostics: #error.diagnostics#">

</body>
</html>

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cflog 	 type="Error"
  file="myapp_errors"
  text="Exception error
  Exception type: #Error.type#
  Template: #Error.template#,
  Remote Address: #Error.remoteAddress#,
  HTTP Reference: #error.HTTPReferer#
  Diagnostics: #Error.diagnostics#">

When this page is processed, log an entry in the file myapp_errors.log file in the ColdFusion log directory. Identify the entry as an error message and include an error message that includes the exception type, the path of the page that caused the error, the remote address that called the page, and the error’s diagnostic message.

A log file entry similar to the following is generated if you try to call a nonexistent custom tag and this page catches the error (line breaks added for clarity):

"Error","web-13","12/19/01","11:29:07",MYAPP,"Exception error --
        Exception type: coldfusion.runtime.CfErrorWrapper
        Template: /MYStuff/MyDocs/exceptiontest.cfm,
        Remote Address: 127.0.0.1,
        HTTP Reference:
        Diagnostics: Cannot find CFML template for custom tag testCase. Cannot
        find CFML template for custom tag testCase. ColdFusion attempted looking
        in the tree of installed custom tags but did not find a custom tag with
        this name."

The text consists of a comma-delimited list of the following entries:

  • Log entry type, specified by the cflog type attribute
  • ID of the thread that was executing
  • Date the entry was written to the log
  • Time the entry was written to the log
  • Application name, as specified in the Application.cfc initialization code (by setting the This.application variable) or by a cfapplication tag (for example, in an Application.cfm file).
  • The message specified by the cflog text attribute.


Handling runtime exceptions with ColdFusion tags

Exceptions include any event that disrupts the normal flow of instructions in a ColdFusion page, such as failed database operations, missing include files, or developer-specified events. Ordinarily, when ColdFusion encounters an exception, it stops processing and displays an error message, or an error page specified by a cferror tag or the Site-wide Error Handler option on the Settings page in the Administrator. However, you can use the ColdFusion exception handling tags to catch and process runtime exceptions directly in ColdFusion pages.

This ability to handle exceptions directly in your application pages enables your application to do the following:

  • Respond appropriately to specific errors within the context of the current application page
  • Recover from errors whenever possible.

This section describes the following topics:

  • Exception-handling tags
  • Using cftry and cfcatch tags
  • Using the cftry tag: an example
  • Using the cfthrow tag
  • Using the cfrethrow tag
  • Example: using nested tags, cfthrow, and cfrethrow


Exception-handling tags

ColdFusion provides the exception-handling tags listed in the following table:

Tag | Description
cftry | If any exceptions occur while processing the tag body, look for a cfcatch tag that handles the exception, and execute the code in the cfcatch tag body.
cfcatch | Execute code in the body of this tag if the exception caused by the code in the cftry tag body matches the exception type specified in this tag’s attributes. Used in cftry tag bodies only.
cfthrow | Generate a user-specified exception.
cfrethrow | Exit the current cfcatch block and generates a new exception of the same type. Used only in cfcatch tag bodies.


Using cftry and cfcatch tags

The cftry tag lets you go beyond reporting error data to the user:

  • You can include code that recovers from errors so your application can continue processing without alerting the user.
  • You can create customized error messages that apply to the specific code that causes the error.

For example, you can use cftry to catch errors in code that enters data from a user registration form to a database. The cfcatch code could do the following:

  1. Retry the query, so the operation succeeds if the resource was only temporarily unavailable.
  2. If the retries fail:
    • Display a custom message to the user
    • Post the data to an email address so the data could be entered by company staff after the problem has been solved.

Code that accesses external resources such as databases, files, or LDAP servers where resource availability is not guaranteed is a good candidate for using try/catch blocks.

Try/catch code structure

In order for your code to directly handle an exception, the tags in question must appear within a cftry block. It is a good idea to enclose an entire application page in a cftry block. You then follow the cftry block with cfcatch blocks, which respond to potential errors. When an exception occurs within the cftry block, processing is thrown to the cfcatch block for that type of exception.

Here is an outline for using cftry and cfcatch to handle errors:

<cftry>
    Put your application code here ...
    <cfcatch type="exception type1">
        Add exception processing code here ...
    </cfcatch>
    <cfcatch type="exception type2">
        Add exception processing code here ...
    </cfcatch>
    ...
    <cfcatch type="Any">
        Add exception processing code appropriate for all other exceptions
here ...
    </cfcatch>
</cftry>

Try/catch code rules and recommendations

Follow these rules and recommendations when you use cftry and cfcatch tags:

  • The cfcatch tags must follow all other code in a cftry tag body.
  • You can nest cftry blocks. For example, the following structure is valid:
    <cftry>
    code that may cause an exception
    <cfcatch ...>
        <cftry>
            First level of exception handling code
            <cfcatch ...>
                Second level of exception handling code
            </cfcatch
        </cftry>
    </cfcatch>
</cftry>

    If an exception occurs in the first level of exception-handling code, the inner cfcatch block can catch and handle it. (An exception in a cfcatch block cannot be handled by cfcatch blocks at the same level as that block.)

  • ColdFusion always responds to the latest exception that gets raised. For example, if code in a cftry block causes an exception that gets handled by a cfcatch block, and the cfcatch block causes an exception that has no handler, ColdFusion will display the default error message for the exception in the cfcatch block, and you will not be notified of the original exception.
  • If an exception occurs when the current tag is nested inside other tags, the CFML processor checks the entire stack of open tags until it finds a suitable cftry/cfcatch combination or reaches the end of the stack.
  • Use cftry with cfcatch to handle exceptions based on their point of origin within an application page, or based on diagnostic information.
  • The entire cftry tag, including all its cfcatch tags, must be on a single ColdFusion page. You cannot put the <cftry> start tag on one page and have the </cftry> end tag on another page.
  • For cases when a cfcatch block is not able to successfully handle an error, consider using the cfrethrow tag, as described in Using the cfrethrow tag.
  • If an exception can be safely ignored, use a cfcatch tag with no body; for example:
    <cfcatch Type = Database />
  • In particularly problematic cases, you might enclose an exception-prone tag in a specialized combination of cftry and cfcatch tags to immediately isolate the tag's exceptions.

Exception information in cfcatch blocks

Within the body of a cfcatch tag, the active exception’s properties are available in a cfcatch object. The following sections describe the object contents.

Standard cfcatch variables

The following table describes the variables that are available in most cfcatch blocks:

Property variable

Description

cfcatch.Detail

A detailed message from the CFML compiler. This message, which can contain HTML formatting, can help to determine which tag threw the exception.

The cfcatch.Detail value is available in the CFScript cfcatch statement as the exceptionVariable parameter.

cfcatch.ErrorCode

The cfthrow tag can supply a value for this code through the errorCode attribute. For Type="Database", cfcatch.ErrorCode has the same value as cfcatch.SQLState.

Otherwise, the value of cfcatch.ErrorCode is the empty string.

cfcatch.ExtendedInfo

Custom error message information. This is returned only to cfcatch tags for which the type attribute is Application or a custom type.

Otherwise, the value of cfcatch.ExtendedInfo is the empty string.

cfcatch.Message

The exception’s default diagnostic message, if one was provided. If no diagnostic message is available, this is an empty string.

The cfcatch.Message value is included in the value of the CFScript catch statement exceptionVariable parameter.

cfcatch.RootCause

The Java servlet exception reported by the JVM as the cause of the "root cause" of the exception.

cfcatch.TagContext

An array of structures structure containing information for each tag in the tag stack The tag stack consists of each tag that is currently open.

cfcatch.Type

The exception’s type, returned as a string.

Note: If you use cfdump to display the cfcatch variable, the display does not include variables that do not have values.

The cfcatch.TagContext variable contains an array of tag information structures. Each structure represents one level of the active tag context at the time when ColdFusion detected the exception. That is, there is one structure for each tag that is open at the time of the exception. For example, if the exception occurs in a tag on a custom tag page, the tag context displays information about the called custom tag and the tag in which the error occurs.

The structure at position 1 in the array represents the currently executing tag at the time the exception was detected. The structure at position ArrayLen (cfcatch.tagContext) represents the initial tag in the stack of tags that were executing when the compiler detected the exception.

The following table lists the tagContext structure attributes:

Entry | Description
Column | Obsolete (retained for backwards compatibility). Always 0.
ID | The tag in which the exception occurred. Exceptions in CFScript are indicated by two question marks (??). All custom tags, including those called directly, are identified as cfmodule.
Line | The line on the page in which the tag is located.
Raw_Trace | The raw Java stack trace for the error.
Template | The pathname of the application page that contains the tag.
Type | The type of page; it is always a ColdFusion page.

Database exceptions

The following additional variables are available whenever the exception type is database:

Property variable

Description

cfcatch.NativeErrorCode

The native error code associated with this exception. Database drivers typically provide error codes to assist in the diagnosis of failing database operations. The values assumed by cfcatch.NativeErrorCode are driver-dependent.

If no error code is provided, the value of cfcatch.nativeErrorCode is -1. The value is 0 for queries of queries.

cfcatch.SQLState

The SQLState code associated with this exception. Database drivers typically provide error codes to assist in the diagnosis of failing database operations. SQLState codes are more consistent across database systems than native error codes.

If the driver does not provide an SQLState value, the value of cfcatch.SQLState is -1.

cfcatch.Sql

The SQL statement sent to the data source.

cfcatch.queryError

The error message as reported by the database driver.

cfcatch.where

If the query uses the cfqueryparam tag, query parameter name-value pairs.

Expression exceptions

The following variable is only available for Expression exceptions:

Property variable

Description

cfcatch.ErrNumber

An internal expression error number, valid only when type="Expression".

Locking exceptions

The following additional information is available for exceptions related to errors that occur in cflock tags:

Property variable

Description

cfcatch.lockName

The name of the affected lock. This is set to "anonymous" if the lock name is unknown.

cfcatch.lockOperation

The operation that failed. This is set to "unknown" if the failed operation is unknown.

Missing include exceptions

The following additional variable is available if the error is caused by a missing file specified by a cfinclude tag:

Property variable

Description

cfcatch.missingFileName

The name of the missing file.


Using the cftry tag: an example

The following example shows the cftry and cfcatch tags. It uses the cfdocexamples data source, which many of the examples in this manual use, and a sample included file, includeme.cfm.

If an exception occurs during the cfquery statement's execution, the application page flow switches to the cfcatch type="Database" exception handler. It then resumes with the next statement after the cftry block, once the cfcatch type="Database" handler completes. Similarly, the cfcatch type="MissingInclude" block handles exceptions raised by the cfinclude tag.

<!--- Wrap code you want to check in a cftry block --->
<cfset EmpID=3>
<cfparam name="errorCaught" default="">
<cftry>
    <cfquery name="test" datasource="cfdocexamples">
        SELECT Dept_ID, FirstName, LastName
        FROM Employee
        WHERE Emp_ID=#EmpID#
    </cfquery>

    <html>
    <head>
    <title>Test cftry/cfcatch</title>
    </head>
    <body>
    <cfinclude template="includeme.cfm">
    <cfoutput query="test">
        <p>Department: #Dept_ID#<br>
        Last Name: #LastName#<br>
        First Name: #FirstName#</p>
    </cfoutput>

<!--- Use cfcatch to test for missing included files. --->
<!--- 	Print Message and Detail error messages. --->
<!--- Block executes only if a MissingInclude exception is thrown. --->
    <cfcatch type="MissingInclude">
        <h1>Missing Include File</h1>
        <cfoutput>
        <ul>
            <li><b>Message:</b> #cfcatch.Message#
            <li><b>Detail:</b> #cfcatch.Detail#
            <li><b>File name:</b> #cfcatch.MissingFileName#
        </ul>
        </cfoutput>
        <cfset errorCaught = "MissingInclude">
    </cfcatch>

<!--- Use cfcatch to test for database errors.--->
<!--- 	Print error messages. --->
<!--- Block executes only if a Database exception is thrown. --->
    <cfcatch type="Database">
        <h1>Database Error</h1>
        <cfoutput>
        <ul>
            <li><b>Message:</b> #cfcatch.Message#
            <li><b>Native error code:</b> #cfcatch.NativeErrorCode#
            <li><b>SQLState:</b> #cfcatch.SQLState#
            <li><b>Detail:</b> #cfcatch.Detail#
            </ul>
        </cfoutput>
        <cfset errorCaught = "Database">
    </cfcatch>

<!--- Use cfcatch with type="Any" --->
<!--- to find unexpected exceptions. --->
    <cfcatch type="Any">
        <cfoutput>
            <hr>
            <h1>Other Error: #cfcatch.Type#</h1>
            <ul>
                <li><b>Message:</b> #cfcatch.Message#
                <li><b>Detail:</b> #cfcatch.Detail#
            </ul>
        </cfoutput>
        <cfset errorCaught = "General Exception">
    </cfcatch>
</body>
</html>
</cftry>

Use the following procedure to test the code.

To test the code:

  1. Make sure there is no includeme.cfm file and display the page. The cfcatch type="MissingInclude" block displays the error.
  2. Create a nonempty includeme.cfm file and display the page. If your database is configured properly, you should see an employee entry and not get any error.
  3. In the cfquery tag, change the line:
    FROM Employee

    to:

    FROM Employer

    Display the page. This time the cfcatch type="Database" block displays an error message.

  4. Change Employer to Employee.

    Change the cfoutput line:

    <p>Department: #Dept_ID#<br>

    to:

    <p>Department: #DepartmentID#<br>

    Display the page. This time the cfcatch type="Any" block displays an error message indicating an expression error.

  5. Change DepartmentID back to Dept_ID and redisplay the page. The page displays properly.

    Open \CFusion\Log\MyAppPage.log in your text editor. You should see a header line, an initialization line, and four detail lines, similar to the following:

    "Severity","ThreadID","Date","Time","Application","Message"
"Information","web-0","11/20/01", "16:27:08",, "cf_root\runtime\servers\default\logs\ MyAppPage.log initialized"
"Information","web-0","11/20/01","16:27:08",,
    "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: MissingInclude"
"Information","web-1","11/20/01","16:27:32",,"
    Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: "
"Information","web-0","11/20/01","16:27:49",,
    "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: Database"
"Information","web-1","11/20/01","16:28:21",,
    "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: General Exception"
"Information","web-0","11/20/01","16:28:49",,
    "Page: web_root/MYStuff/MyDocs/ cftryexample.cfm Error: "

Reviewing the code

The following table describes the code:

Code

Description

<cfset EmpID=3>

<cfparam name="errorCaught" default="">

Initializes the employee ID to a valid value. An application would get the value from a form or other source.

Sets the default errorCaught variable value to the empty string (to indicate no error was caught).

There is no need to put these lines in a cftry block.

<cftry>

<cfquery name="test"
datasource="cfdocexamples">

SELECT Dept_ID, FirstName, LastName

FROM Employee

WHERE Emp_ID=#EmpID#

</cfquery>

Starts the cftry block. Exceptions from here to the end of the block can be caught by cfcatch tags.

Queries the cfdocexamples database to get the data for the employee identified by the EmpID variable.

<html>

<head>

<title>Test cftry/cfcatch</title>

</head>

<body>

<cfinclude template="includeme.cfm">

<cfoutput query="test">

<p>Department: #Dept_ID#<br>

Last Name: #LastName#<br>

First Name: #FirstName#</p>

</cfoutput>

Begins the HTML page. This section contains all the code that displays information if no errors occur.

Includes the includeme.cfm page.

Displays the user information record from the test query.

<cfcatch type="MissingInclude">

<h1>Missing Include File</h1>

<cfoutput>

<ul>

<li><b>Message:</b> #cfcatch.Message#

<li><b>Detail:</b> #cfcatch.Detail#

<li><b>File name:</b>
#cfcatch.MissingFilename#

</ul>

</cfoutput>

<cfset errorCaught = "MissingInclude">

</cfcatch>

Handles exceptions thrown when a page specified by the cfinclude tag cannot be found.

Displays cfcatch variables, including the ColdFusion basic error message, detail message, and the name of the file that could not be found.

Sets the errorCaught variable to indicate the error type.

<cfcatch type="Database">

<h1>Database Error</h1>

<cfoutput>

<ul>

<li><b>Message:</b> #cfcatch.Message#

<li><b>Native error code:</b>
#cfcatch.NativeErrorCode#

<li><b>SQLState:</b> #cfcatch.SQLState#

<li><b>Detail:</b> #cfcatch.Detail#

</ul>

</cfoutput>

<cfset errorCaught = "Database">

</cfcatch>

Handles exceptions thrown when accessing a database.

Displays cfcatch variables, including the ColdFusion basic error message, the error code and SQL state reported by the databases system, and the detailed error message.

Sets the errorCaught variable to indicate the error type.

<cfcatch type="Any">

<cfoutput>

<hr>

<h1>Other Error: #cfcatch.Type#</h1>

<ul>

<li><b>Message:</b> #cfcatch.message#

<li><b>Detail:</b> #cfcatch.Detail#

</ul>

</cfoutput>

<cfset errorCaught = "General Exception">

</cfcatch>

Handles any other exceptions generated in the cftry block.

Since the error can occur after information has displayed (in this case, the contents of the include file), draws a line before writing the message text.

Displays the ColdFusion basic and detailed error message.

Sets the errorCaught variable to indicate the error type.

</body>

</html>

</cftry>

Ends the HTML page, then the cftry block.


Using the cfthrow tag

You can use the cfthrow tag to raise your own, custom exceptions. When you use the cfthrow tag, you specify any or all of the following information:

Attribute | Meaning
type | The type of error. It can be a custom type that has meaning only to your application, such as InvalidProductCode. You can also specify Application, the default type. You cannot use any of the predefined ColdFusion error types, such as Database or MissingTemplate.
message | A brief text message indicating the error.
detail | A more detailed text message describing the error.
errorCode | An error code that is meaningful to the application. This field is useful if the application uses numeric error codes.
extendedInfo | Any additional information of use to the application.

All of these values are optional. You access the attribute values in cfcatch blocks and Exception type error pages by prefixing the attribute with either cfcatch or error, as in cfcatch.extendedInfo. The default ColdFusion error handler displays the message and detail values in the Message pane and the remaining values in the Error Diagnostic Information pane.

Catching and displaying thrown errors

The cfcatch tag catches a custom exception when you use any of the following values for the cfcatch type attribute:

  • The custom exception type specified in the cfthrow tag.
  • A custom exception type that hierarchically matches the initial portion of the type specified in the cfthrow tag. For more information, see the next section, Custom error type name hierarchy.
  • Application, which matches an exception that is thrown with the Application type attribute or with no type attribute.
  • Any, which matches any exception that is not caught by a more specific cfcatch tag.

Similarly, if you specify any of these types in a cferror tag, the specified error page will display information about the thrown error.

Because the cfthrow tag generates an exception, a Request error handler or the Site-wide error handler can also display these errors.

Custom error type name hierarchy

You can name custom exception types using a method that is similar to Java class naming conventions: domain name in reverse order, followed by project identifiers, as in the following example:

<cfthrow
    type="com.myCompany.myApp.Invalid_field.codeValue"
    errorcode="Dodge14B">

This fully qualified naming method is not required; you can use shorter naming rules, for example, just myApp.Invalid_field.codeValue, or even codeValue.

This naming method is not just a convention, however; ColdFusion MX uses the naming hierarchy to select from a possible hierarchy of error handlers. For example, assume you use the following cfthrow statement:

<cfthrow type="MyApp.BusinessRuleException.InvalidAccount">

Any of the following cfcatch error handlers would handle this error:

<cfcatch type="MyApp.BusinessRuleException.InvalidAccount">
<cfcatch type="MyApp.BusinessRuleException">
<cfcatch type="MyApp">

The handler that most exactly matches handles the error. Therefore, in this case, the MyApp.BusinessRuleException.InvalidAccount handler gets invoked. However, if you used the following cfthrow tag:

<cfthrow type="MyApp.BusinessRuleException.InvalidVendorCode

the MyApp.BusinessRuleException handler receives the error.

The type comparison is no case-sensitive.

When to use the cfthrow tag

Use the cfthrow tag when your application can identify and handle application-specific errors. One typical use for the cfthrow tag is in implementing custom data validation. The cfthrow tag is also useful for throwing errors from a custom tag page to the calling page.

For example, on a form action page or custom tag used to set a password, the application can determine whether the password entered is a minimum length, or contains both letters and number, and throw an error with a message that indicates the password rule that was broken. The cfcatch block handles the error and tells the user how to correct the problem.


Using the cfrethrow tag

The cfrethrow tag lets you create a hierarchy of error handlers. It tells ColdFusion to exit the current cfcatch block and "rethrow" the exception to the next level of error handler. Thus, if an error handler designed for a specific type of error cannot handle the error, it can rethrow the error to a more general-purpose error handler. The cfrethrow tag can only be used in a cfcatch tag body.

The cfrethrow tag syntax

The following pseudocode shows how you can use the cfrethrow tag to create an error-handling hierarchy:

<cftry>
    <cftry>
        Code that might throw a database error
        <cfcatch Type="Database">
            <cfif Error is of type I can Handle>
                Handle it
            <cfelse>
                <cfrethrow>
            </cfif
        </cfcatch>
    </cftry>
    <cfcatch Type="Any">
        General Error Handling code
    </cfcatch>
</cftry>

Although this example uses a Database error as an example, you can use any cfcatch type attribute in the innermost error type.

Follow these rules when you use the cfrethrow tag:

  • Nest cftry tags, with one tag for each level of error handling hierarchy. Each level contains the cfcatch tags for that level of error granularity.
  • Place the most general error catching code in the outermost cftry block.
  • Place the most specific error catching code in the innermost cftry block.
  • Place the code that can cause an exception error at the top of the innermost cftry block.
  • End each cfcatch block except those in the outermost cftry block with a cfrethrow tag.


Example: using nested tags, cfthrow, and cfrethrow

The following example shows many of the techniques discussed in this chapter, including nested cftry blocks and the cfthrow and cfrethrow tags. The example includes a simple calling page and a custom tag page:

  • The calling page does little more than call the custom tag with a single attribute, a name to be looked up in a database. It does show, however, how a calling page can handle an exception thrown by the custom tag.
  • The custom tag finds all records in the cfdocexamples database with a matching last name, and returns the results in a Caller variable. If it fails to connect with the main database, it tries a backup database.

The calling page

The calling page represents a section from a larger application page. To keep things simple, the example hard-codes the name to be looked up.

<cftry>
    <cf_getEmps EmpName="Jones">
    <cfcatch type="myApp.getUser.noEmpName">
        <h2>Oops</h2>
        <cfoutput>#cfcatch.Message#</cfoutput><br>
    </cfcatch>
</cftry>
<cfif isdefined("getEmpsResult")>
    <cfdump var="#getEmpsResult#">
</cfif>

Reviewing the code

The following table describes the code:

Code | Description
<cftry> <cf_getEmps EmpName="Jones"> | In a cftry block, calls the cf_getEmps custom tag (getEmps.cfm).
<cfcatch type="myApp.getUser.noEmpName"> <h2>Oops</h2> <cfoutput>#cfcatch.Message#</cfoutput><br> </cfcatch> </cftry> | If the tag throws an exception indicating that it did not receive a valid attribute, catches the exception and displays a message, including the message variable set by the cfthrow tag in the custom tag.
<cfif isdefined("getEmpsResult")> <cfdump var="#getEmpsResult#"> </cfif> | If the tag returns a result, uses the cfdump tag to display it. (A production application would not use the cfdump tag.)

The custom tag page

The custom tag page searches for the name in the database and returns any matching records in a getEmpsResult variable in the calling page. It includes several nested cftry blocks to handle error conditions. For a full description, see Reviewing the code, following the example:

Save the following code as getEmps.cfm in the same directory as the calling page.

<!--- If the tag didn’t pass an attribute, throw an error to be handled by
            the calling page --->
<cfif NOT IsDefined("attributes.EmpName")>
    <cfthrow Type="myApp.getUser.noEmpName"
        message = "Last Name was not supplied to the cf_getEmps tag.">
    <cfexit method = "exittag">
<!--- Have a name to look up --->
<cfelse>
<!--- Outermost Try Block --->
    <cftry>

<!--- Inner Try Block --->
        <cftry>
<!--- Try to query the main database and set a caller variable to the result --->
            <cfquery Name = "getUser" DataSource="cfdocexamples">
                SELECT *
                FROM Employee
                WHERE LastName = ’#attributes.EmpName#’
            </cfquery>
            <cfset caller.getEmpsResult = getuser>
<!--- If the query failed with a database error, check the error type
            to see if the database was found --->
            <cfcatch type= "Database">
                <cfif (cfcatch.SQLState IS "S100") OR (cfcatch.SQLState IS
                    "IM002")>

<!--- If the database wasn't found, try the backup database --->
<!--- Use a third-level Try block --->
                    <cftry>
                        <cfquery Name = "getUser" DataSource="cfdocexamplesBackup">
                            SELECT *
                            FROM Employee
                            WHERE LastName = ’#attributes.EmpName#’
                        </cfquery>
                         <cfset caller.getEmpsResult = getuser>

<!--- If still get a database error, just return to the calling page
            without setting the caller variable. There is no cfcatch body.
            This might not be appropriate in some cases.
            The Calling page ends up handling this case as if a match was not
            found --->
                         <cfcatch type = "Database" />
<!--- Still in innermost try block. Rethrow any other errors to the next
            try block level --->
                        <cfcatch type = "Any">
                            <cfrethrow>
                        </cfcatch>
                    </cftry>

<!--- Now in second level try block.
            Throw all other types of Database exceptions to the next try
                block level --->
                <cfelse>
                    <cfrethrow>
                </cfif>
            </cfcatch>
<!--- Throw all other exceptions to the next try block level --->
            <cfcatch type = "Any">
                    <cfrethrow>
            </cfcatch>
        </cftry>

<!--- Now in Outermost try block.
         Handle all unhandled exceptions, including rethrown exceptions, by
            displaying a message and exiting to the calling page.--->
        <cfcatch Type = "Any">
            <h2>Sorry</h2>
            <p>An unexpected error happened in processing your user inquiry.
                Please report the following to technical support:</p>
            <cfoutput>
                Type: #cfcatch.Type#
                Message: #cfcatch.Message#
            </cfoutput>
            <cfexit method = "exittag">
        </cfcatch>
    </cftry>
</cfif>

Reviewing the code

The following table describes the code:

Code

Description

<cfif NOT IsDefined("attributes.EmpName")>
  cfthrow Type="myApp.getUser.noEmpName"
    message = "Last Name was not supplied to
        the cf_getEmps tag.">
  <cfexit method = "exittag">

Makes sure the calling page specified an EmpName attribute. If not, throws a custom error that indicates the problem and exits the tag. The calling page handles the thrown error.

<cfelse>
  <cftry>

If the tag has an EmpName attribute, does the remaining work inside an outermost try block. The cfcatch block at its end handles any otherwise-uncaught exceptions.

<cftry>
  <cfquery Name = "getUser"
        DataSource="cfdocexamples">
    SELECT *
    FROM Employee
    WHERE LastName = '#attributes.EmpName#'
  </cfquery>
  <cfset caller.getEmpsResult = getuser>

Starts a second nested try block. This block catches exceptions in the database query.

If there are no exceptions, sets the calling page’s getEmpsResult variable with the query results.

<cfcatch type= "Database">
  <cfif (cfcatch.sqlstate IS "S100") OR
        (cfcatch.sqlstate IS "IM002")>
    <cftry>
      <cfquery Name = "getUser" DataSource=
            "cfdocexamplesBackup"
        SELECT *
        FROM Employee
        WHERE LastName = '#attributes.EmpName#'
      </cfquery>
      <cfset caller.getEmpsResult = getuser>

If the query threw a Database error, checks to see if the error was caused by an inability to access the database (indicated by an SQLState variable value of S100 or IM002).

If the database was not found, starts a third nested try block and tries accessing the backup database. This try block catches exceptions in this second database access.

If the database inquiry succeeds, sets the calling page’s getEmpsResult variable with the query results.

  <cfcatch type = "Database" />

If the second database query failed with a database error, gives up silently. Because the Database type cfcatch tag does not have a body, the tag exits. The calling page does not get a getEmpsResult variable. It cannot tell whether the database had no match or an unrecoverable database error occurred, but it does know that no match was found.

  <cfcatch type = "Any">
    <cfrethrow>
  </cfcatch>
</cftry>

If the second database query failed for any other reason, throws the error up to the next try block.

Ends the innermost try block

  <cfelse>
    <cfrethrow>
  </cfif>
</cfcatch>

In the second try block, handles the case in which the first database query failed for a reason other than a failure to find the database.

Rethrows the error up to the next level, the outermost try block.

  <cfcatch type = "Any">
    <cfrethrow>
  </cfcatch>
</cftry>

In the second try block, catches any errors other exceptions and rethrows them up to the outermost try block.

Ends the second try block.

    <cfcatch Type = "Any">
      <h2>Sorry</h2>
      <p>An unexpected error happened in processing
            your user inquiry.
        Please report the following to technical support:</p>
      <cfoutput>
        Type: #cfcatch.Type#
        Message: #cfcatch.Message#
      </cfoutput>
    <cfexit method = "exittag">
    </cfcatch>
  </cftry>
</cfif>

In the outermost try block, handles any exceptions by displaying an error message that includes the exception type and the exception’s error message. Because there was no code to try that is not also in a nested try block, this cfcatch tag handles only errors that are rethrown from the nested blocks.

Exits the custom tag and returns to the calling page.

Ends the catch block, try block, and initial cfif block.

Testing the code

To test the various ways errors can occur and be handled in this example, try the following:

  • In the calling page, change the attribute name to any other value; for example, My Attrib. Then change it back.
  • In the first cfquery tag, change the data source name to an invalid data source; for example, NoDatabase.
  • With an invalid first data source name, change the data source in the second cfquery tag to cfdocexamples.
  • Insert cfthrow tags throwing custom exculpations in various places in the code and observe the effects.
Previous


Using Persistent Data and Locking

Macromedia ColdFusion MX provides several variable scopes in which data persists past the life of a single request. These are the Client, Application, Session, and Server scopes. These scopes let you save data over time and share data between pages and even applications. (This chapter refers to these scopes as persistent scopes.) In particular, you can use the Client and Session scopes to maintain information about a user across multiple requests.

ColdFusion MX lets you lock access to sections of code to ensure that ColdFusion does not attempt to run the code, or access the data that it uses, simultaneously or in an unpredictable order. This locking feature is important for ensuring the consistency of all shared data, including data in external sources in addition to data in persistent scopes.

This chapter describes how to use persistent scopes to develop an application and how to use locking to ensure data consistency.

Contents

About persistent scope variables

Managing the client state

Configuring and using client variables

Configuring and using session variables

Configuring and using application variables

Using server variables

Locking code with cflock

Examples of cflock
Next


About persistent scope variables

ColdFusion MX provides four variable scopes, described in the following table, that let you maintain data that must be available to multiple applications or users or must last beyond the scope of the current request.

Variable scope

Description

Client

Contains variables that are available for a single client browser over multiple browser sessions in an application. For information about browser sessions, see, What is a session?.

Useful for client-specific information, such as client preferences, that you want to store for a significant period of time.

Data is stored as cookies, database entries, or Registry values. Client variables can time out after an extended period.

Although do not have to use the Client scope prefix in the variable name, code that uses the prefix is more efficient and easier to maintain.

Session

Contains variables that are available for a single client browser for a single browser session in an application.

Useful for client-specific information, such as shopping cart contents, that you want to persist while the client is visiting your application.

Data is stored in memory and times out after a period of inactivity or when the server shuts down.

ColdFusion MX Administrator lets you select between two kinds of session management, Standard ColdFusion Session management and J2EE session management. For information about types of session management, see ColdFusion and J2EE session management.

You must use the Session scope prefix in the variable name.

Application

Contains variables that are available to all pages in an application for all clients.

Useful for application-specific information, such as contact information, that can vary over time and should be stored in a variable.

Data is stored in memory and times out after a period of inactivity or when the server shuts down.

You must use the Application scope prefix in the variable name.

Server

Contains variables that are available to all applications in a server and all clients.

Useful for information that applies to all pages on the server, such as an aggregate page-hit counter.

Data is stored in memory. The variables do not time out, but you can delete variables you create, and all server variables are automatically deleted when the server stops running.

You must use the Server scope prefix in the variable name.

The following sections provide information that is common to all or several of these variables. Later sections describe how to use the Client, Session, Application, and Server scopes in your applications, and provide detailed information about locking code.

ColdFusion persistent variables and ColdFusion structures

All persistent scopes are available as ColdFusion structures. As a result, you can use ColdFusion structure functions to access and manipulate Client, Session, Application, and Server scope contents. This chapter does not cover using these functions in detail, but does mention features or limitations that apply to specific scopes.

Note: Although you can use the StructClear function to clear your data from the Server scope, the function does not delete the names of the variables, only their values, and it does not delete the contents of the Server.os and Server.ColdFusion structures. Using the StructClear function to clear the Session, or Application scope clears the entire scope, including the built-in variables. Using the StructClear function to clear the Client scope clears the variables from the server memory, but does not delete the stored copies of the variables.

ColdFusion persistent variable issues

Variables in the Session, Application, and Server scopes are kept in ColdFusion server memory. This storage method has several implications:

  • All variables in these scopes are lost if the server stops running.
  • Variables in these scopes are not shared by servers in a cluster.
  • To prevent race conditions and ensure data consistency, lock access to all code that changes variables in these scopes or reads variables in these scopes with values that can change.

Note: If you use J2EE session management and configure the J2EE server to retain session data between server restarts, ColdFusion retains session variables between server restarts.

Additionally, you must be careful when using client variables in a server cluster, where an application can run on multiple servers.

Locking memory variables

Because ColdFusion is a multithreaded system in which multiple requests can share Session, Application, and Server scope variables, it is possible for two or more requests to try to access and modify data at the same time. ColdFusion runs in a J2EE environment, which prevents simultaneous data access, so multiple requests do not cause severe system errors. However, such requests can result in inconsistent data values, particularly when a page might change more than one variable.

To prevent data errors with session, application, and server variables, lock code that writes and reads data in these scopes. For more information, see Locking code with cflock.

Using variables in clustered systems

Because memory variables are stored in memory, they are not available to all servers in a cluster. As a result, you generally do not use Session, Application, or Server scope variables in clustered environment. However, you might use these scope variables in a clustered system in the following circumstances:

  • If the clustering system supports "sticky" sessions, in which the clustering system ensures that each user session remains on a single server. In this case, you can use session variables as you would on a single server.
  • You can use Application and Server scope variables in a cluster for write-once variables that are consistently set, for example, from a database.

To use client variables on a clustered system, store the variables as cookies or in a database that is available to all servers. If you use database storage, on one server only, select the Purge Data for Clients that Remain Unvisited option on the Client Variables, Add/Edit Client Store page in the Server Settings area in the ColdFusion MX Administrator.

For more information on using client and session variables in clustered systems, see Managing client identity information in a clustered environment.


Managing the client state

Because the web is a stateless system, each connection that a browser makes to a web server is unique to the web server. However, many applications must keep track of users as they move through the pages within the application. This is the definition of client state management.

ColdFusion provides tools to maintain the client state by seamlessly tracking variables associated with a browser as the user moves from page to page within the application. You can use these variables in place of other methods for tracking client state, such as URL parameters, hidden form fields, and HTTP cookies.

About client and session variables

ColdFusion provides two tools for managing the client state: client variables and session variables. Both types of variables are associated with a specific client, but you manage and use them differently, as described in the following table:

Variable type

Description

Client

Data is saved as cookies, database entries, or Registry entries. Data is saved between server restarts, but is initially accessed and saved more slowly than data stored in memory.

Each type of data storage has its own time-out period. You can specify the database and Registry data time-outs in ColdFusion MX Administrator. ColdFusion sets Cookie client variables to expire after approximately 10 years.

Data is stored on a per-user and per-application basis. For example, if you store client variables as cookies, the user has a separate cookie for each ColdFusion application provided by a server.

Client variables must be simple variables, such as numbers, dates, or strings. They cannot be arrays, structures, query objects, or other objects.

Client variable names can include periods. For example, My.ClientVar is a valid name for a simple client variable. Avoid such names, however, to ensure code clarity.

You do not have to prefix client variables with the scope name when you reference them, However, if you do not use the Client prefix, you might unintentionally refer to a variable with the same name in another scope. Using the prefix also optimizes performance and increases program clarity.

You do not lock code that uses client variables.

You can use client variables that are stored in cookies or a common database in clustered systems.

Session

Data is stored in memory so it is accessed quickly.

Data is lost when the client browser is inactive for a time-out period. You specify the time-out in the ColdFusion MX Administrator, the Application.cfc initialization code, or Application.cfm.

As with client variables, data is available to a single client and application only.

Variables can store any ColdFusion data type.

You must prefix all variable names with the Session scope name.

Lock code that uses session variables to prevent race conditions.

You can use session variables in clustered systems only if the systems support "sticky" sessions, where a session is limited to a single server.

Session variables are normally better than client variables for values that need to exist for only a single browser session. You should reserve client variables for client-specific data, such as client preferences that you want available for multiple browser sessions.

Maintaining client identity

Because the web is a stateless system, client management requires some method for maintaining knowledge of the client between requests. Normally you do this using cookies, but you can also do it by passing information between application pages. The following sections describe how ColdFusion maintains client identity in a variety of configurations and environments, and discuss issues that can arise with client state management.

  • About client identifiers
  • Using client and session variables without cookies
  • Client identifiers and security
  • Managing client identity information in a clustered environment


About client identifiers

To use client and session variables, ColdFusion must be able to identify the client. It normally does so by setting the following two cookie values on the client’s system:

  • CFID A sequential client identifier
  • CFToken A random-number client security token

These cookies uniquely identify the client to ColdFusion, which also maintains copies of the variables as part of the Session and Client scopes. You can configure your application so that it does not use client cookies, but in this case, you must pass these variables to all the pages that your application calls. For more information about maintaining client and session information without using cookies, see Using client and session variables without cookies.

You can configure ColdFusion MX to use J2EE servlet session management instead of ColdFusion session management for session variables. This method of session management does not use CFID and CFToken values, but does use a client-side jsessionid session management cookie. For more information on using J2EE session management, see ColdFusion and J2EE session management.


Using client and session variables without cookies

Often, users disable cookies in their browsers. In this case, ColdFusion cannot maintain the client state automatically. You can use client or session variables without using cookies, by passing the client identification information between application pages. However, this technique has significant limitations, as follows:

  • Client variables are effectively the same as session variables, except that they leave unusable data in the client data store.

    Because the client’s system does not retain any identification information, the next time the user logs on, ColdFusion cannot identify the user with the previous client and must create a new client ID for the user. Any information about the user from a previous session is not available, but remains in client data storage until ColdFusion deletes it. If you clear the Purge Data for Clients that Remain Unvisited option in the ColdFusion MX Administrator, ColdFusion never deletes this data.

    Therefore, do not use client variables, if you allow users to disable cookies. To retain client information without cookies, require users to login with a unique ID. You can then save user-specific information in a database with the user’s ID as a key.

  • ColdFusion creates a new session each time the user requests a page directly in the browser, because the new request contains no state information to indicate the session or client.

Note: You can prevent ColdFusion from sending client information to the browser as cookies by setting This.setClientCookies variable in Application.cfc or the setClientCookies attribute of the cfapplication tag to No.

To use ColdFusion session variables without using cookies, each page must pass the CFID and CFToken values to any page that it calls as part of the request URL. If a page contains any HTML href a= links, cflocation tags, form tags, or cfform tags the tags must pass the CFID and CFToken values in the tag URL. To use J2EE session management, you must pass the jsessionid value in page requests. To use ColdFusion client variables and J2EE session variables, you must pass the CFID, CFToken, and jsessionid values in URLs.

ColdFusion provides the URLSessionFormat function, which does the following:

  • If the client does not accept cookies, automatically appends all required client identification information to a URL.
  • If the client accepts cookies, does not append the information.

The URLSessionFormat function automatically determines which identifiers are required, and sends only the required information. It also provides a more secure and robust method for supporting client identification than manually encoding the information in each URL, because it only sends the information that is required, when it is required, and it is easier to code.

To use the URLSessionFormat function, enclose the request URL in the function. For example, the following cfform tag posts a request to another page and sends the client identification, if required:

<cfform method="Post" action="#URLSessionFormat("MyActionPage.cfm")#>

Tip: If you use the same page URL in multiple URLSessionFormat functions, you can gain a small performance improvement and simplify your code if you assign the formatted page URL to a variable, for example:

<cfset myEncodedURL=URLSessionFormat(MyActionPage.cfm)>
<cfform method="Post" action="#myEncodedURL#">


Client identifiers and security

The following client identifier issues can have security implications:

  • Ensuring the uniqueness and complexity of the CFToken identifier
  • Limiting the availability of Session identifiers

The next sections discuss these issues.

Ensuring CFToken uniqueness and security

By default, ColdFusion uses an eight-digit random number in the CFToken identifier. This CFToken format provides a unique, secure identifier for users under most circumstances. (In ColdFusion MX, the method for generating this number uses a cryptographic-strength random number generator that is seeded only when the server starts.)

However, in the ColdFusion MX Administrator, you can enable the Settings page to produce a more complex CFToken identifier. If you enable the Use UUID for cftoken option, ColdFusion creates the CFToken value by prepending a 16-digit random hexadecimal number to a ColdFusion UUID. The resulting CFToken identifier looks similar to the following:

3ee6c307a7278c7b-5278BEA6-1030-C351-3E33390F2EAD02B9

Providing Session security

ColdFusion uses the same client identifiers for the Client scope and the standard Session scope. Because the CFToken and CFID values are used to identify a client over a period of time, they are normally saved as cookies on the user’s browser. These cookies persist until the client’s browser deletes them, which can be a considerable length of time. As a result, hackers could have more access to these variables than if ColdFusion used different user identifiers for each session.

A hacker who has the user’s CFToken and CFID cookies could gain access to user data by accessing a web page during the user’s session using the stolen CFToken and CFID cookies. While this scenario is unlikely, it is theoretically possible.

You can remove this vulnerability by selecting the Use J2EE Session Variables option on the ColdFusion MX Administrator Memory Variables page. The J2EE session management mechanism creates a new session identifier for each session, and does not use either the CFToken or the CFID cookie value.


Managing client identity information in a clustered environment

To maintain your application’s client identity information in a clustered server environment, you must specify This.setdomaincookies="True" in the Application.cfc initialization code, or use the cfapplication setdomaincookies attribute in your Application.cfm page.

The setdomaincookies attribute specifies that the server-side copies of the CFID and CFToken variables used to identify the client to ColdFusion are stored at the domain level (for example, .macromedia.com). If CFID and CFToken variable combinations already exist on each host in the cluster, ColdFusion migrates the host-level variables on each cluster member to the single, common domain-level variable. Following the setting or migration of host-level cookie variables to domain-level variables, ColdFusion creates a new cookie variable (CFMagic) that tells ColdFusion that domain-level cookies have been set.

If you use client variables in a clustered system, you must also use a database or cookies to store the variables.


Configuring and using client variables

Use client variables for data that is associated with a particular client and application and that must be saved between user sessions. Use client variables for long-term information such as user display or content preferences.

This section describes the following topics:

  • Enabling client variables
  • Using client variables

Enabling client variables

To enable client variables, you specify This.clientmanagement="True" in the Application.cfc initialization code, or set the cfapplication tag clientmanagement attribute to Yes in the Application.cfm file. For example, to enable client variables in an application named SearchApp, you can use the following line in the application’s Application.cfm page:

<cfapplication NAME="SearchApp" clientmanagement="Yes">

Choosing a client variable storage method

By default, Coldfusion stores client variables in the Registry. In most cases, however, it is more appropriate to store the information as client cookies or in a SQL database.

The ColdFusion MX Administrator Client Variables page controls the default client variable location. You can override the default location by specifying a This.clientStorage value in Application.cfc or by setting the clientStorage attribute in the cfapplication tag.

You can specify the following values for the client storage method:

  • Registry(default). Client variables are stored under the key HKEY_LOCAL_MACHINE\ SOFTWARE\Macromedia\ColdFusion\CurrentVersion\Clients.
  • Name of a data source configured in ColdFusion MX Administrator
  • Cookie

Generally, it is most efficient to store client variables in a database. Although the Registry option is the default, the Registry has significant limitations for client data storage. The Registry cannot be used in clustered systems and its use for client variables on UNIX is not supported in ColdFusion MX.

Using cookie storage

When you set the client storage method to Cookie, the cookie that ColdFusion creates has the application’s name. Storing client data in a cookie is scalable to large numbers of clients, but this storage mechanism has some limitations. In particular, if the client turns off cookies in the browser, client variables do not work.

Consider the following additional limitations before implementing cookie storage for client variables:

  • Any Client variable that you set after a cfflush tag is not sent to the browser, so the variable value does not get saved.
  • Some browsers allow only 20 cookies to be set from a particular host. ColdFusion uses two of these cookies for the CFID and CFToken identifiers, and also creates a cookie named cfglobals to hold global data about the client, such as HitCount, TimeCreated, and LastVisit. This limits you to 17 unique applications per client-host pair.
  • Some browsers set a size limit of 4K bytes per cookie. ColdFusion encodes nonalphanumeric data in cookies with a URL encoding scheme that expands at a 3-1 ratio, which means you should not store large amounts of data per client. ColdFusion throws an error if you try to store more than 4,000 encoded bytes of data for a client.

Configuring database storage

When you specify a database for client variable storage, do not always have to manually create the data tables that store the client variables.

If ColdFusion can identify that the database you are using supports SQL creation of database tables, you only need to create the database in advance. When you click the Add button on the Select Data Source to Add as Client Store box on the Memory Variables page, the Administrator displays a Add/Edit Client Store page which contains a Create Client Database Tables selection box. Select this option to have ColdFusion create the necessary tables in your database. (The option does not appear if the database already has the required tables.)

If your database does not support SQL creation of tables, or if you are using the ODBC socket [Macromedia] driver to access your database, you must use your database tool to create the client variable tables. Create the CDATA and CGLOBAL tables.

The CDATA table must have the following columns:

Column | Data type
cfid | CHAR(64), TEXT, VARCHAR, or any data type capable of taking variable length strings up to 64 characters
app | CHAR(64), TEXT, VARCHAR, or any data type capable of taking variable length strings up to 64 characters
data | MEMO, LONGTEXT, LONG VARCHAR, CLOB, or any data type capable of taking long, indeterminate-length strings

The CGLOBAL table must have the following columns:

Column | Data type
cfid | CHAR(64), TEXT, VARCHAR, or any data type capable of taking variable length strings up to 64 characters
data | MEMO, LONGTEXT, LONG VARCHAR, CLOB, or any data type capable of taking long, indeterminate-length strings
lvisit | TIMESTAMP, DATETIME, DATE, or any data type that stores date and time values

Note: Different databases use different names for their data types. The names in the preceding tables are common, but your database might use other names.

To improve performance, you should also create indexes when you create these tables. For the CDATA table, index these cfid and app columns. For the CGLOBAL table, index the cfid column.

Specifying client variable storage in your application

The override the default client variable storage location, set the This.clientstorage variable in the Application.cfc initialization code, or use the cfapplication tag clientStorage attribute.

The following lines from an Application.cfc file tell ColdFusion to store the client variables in the mydatasource data source:

<cfscript>
    This.name"SearchApp";
    This.clientManagement="Yes";
    This.clientStorage="mydatasource";
</cfscript>

The following code from an Application.cfm file does the same thing as the previous example:

<cfapplication name"SearchApp"
    clientmanagement="Yes"
    clientstorage="mydatasource">


Using client variables

When you enable client variables for an application, you can use them to keep track of long-term information that is associated with a particular client.

Client variables must be simple data types: strings, numbers, lists, Booleans, or date and time values. They cannot be arrays, record sets, XML objects, query objects, or other objects. If you must store a complex data type as a client variable, you can use the cfwddx tag to convert the data to WDDX format (which is represented as a string), store the WDDX data, and use the cfwddx tag to convert the data back when you read it. For more information on using WDDX, see Using WDDX.

Note: When saving client variable data in WDDX format, in the case of the registry and SQL Server, the limit is about 4K; with ORACLE, the limit is about 2K.

Creating a client variable

To create a client variable and set its value, use the cfset or cfparam tag and use the Client scope identifier as a variable prefix; for example:

<cfset Client.FavoriteColor="Red">

After you set a client variable this way, it is available for use within any page in your application that is accessed by the client for whom the variable is set.

The following example shows how to use the cfparam tag to check for the existence of a client parameter and set a default value if the parameter does not already exist:

<cfparam name="Client.FavoriteColor" default="Red">

Accessing and changing client variables

You use the same syntax to access a client variable as for other types of variables. You can use client variables anywhere you use other ColdFusion variables.

To display the favorite color that has been set for a specific user, for example, use the following code:

<cfoutput>
    Your favorite color is #Client.FavoriteColor#.
</cfoutput>

To change the client’s favorite color, for example, use code such as the following:

<cfset Client.FavoriteColor = Form.FavoriteColor>

Standard client variables

The Client scope has the following built-in, read-only variables that your application can use:

Variable

Description

Client.CFID

The client ID, normally stored on the client system as a cookie.

Client.CFToken

The client security token, normally stored on the client system as a cookie.

Client.URLToken

Value depends on whether J2EE session management is enabled.

No session management or ColdFusion session management: A combination of the CFID and CFToken values, in the form CFID=IDNum&CFTOKEN=tokenNum. This variable is useful if the client does not support cookies and you must pass the CFID and CFToken variables from page to page.

J2EE session management: A combination of CFID, CFToken, and session ID values in the form CFID=IDNum&CFTOKEN=tokenNum&jsessionid=SessionID.

Client.HitCount

The number of page requests made by the client.

Client.LastVisit

The last time the client visited the application.

Client.TimeCreated

The time the CFID and CFToken variables that identify the client to ColdFusion were first created.

Note: ColdFusion lets you delete or change the values of the built-in client variables. As a general rule, avoid doing so.

You use the Client.CFID, Client.CFToken, and Client.URLToken variables if your application supports browsers that do not allow cookies. For more information on supporting browsers that do not allow cookies, see Using client and session variables without cookies.

You can use the Client.HitCount and time information variables to customize behavior that depends on how often users visit your site and when they last visited. For example, the following code shows the date of a user's last visit to your site:

<cfoutput>
    Welcome back to the Web SuperShop. Your last
    visit was on #DateFormat(Client.LastVisit)#.
</cfoutput>

Getting a list of client variables

To obtain a list of the custom client parameters associated with a particular client, use the GetClientVariablesList function, as follows:

<cfoutput>#GetClientVariablesList()#</cfoutput>

The GetClientVariablesList function returns a comma-separated list of the names of the client variables for the current application. The standard system-provided client variables (CFID, CFToken, URLToken, HitCount, TimeCreated, and LastVisit) are not returned in the list.

Deleting client variables

To delete a client variable, use the StructDelete function or the DeleteClientVariable function. For example, the following lines are equivalent:

<cfset IsDeleteSuccessful=DeleteClientVariable("MyClientVariable")>
<cfset IsDeleteSuccessful=StructDelete(Client, "MyClientVariable")>

The Client Variables page in the ColdFusion MX Administrator lets you set a time-out period of inactivity after which ColdFusion removes client variables stored in either the Registry or a data source. (The default value is 10 days for client variables stored in the Registry, and 90 days for client variables stored in a data source.)

Note: You cannot delete the system-provided client variables (CFID, CFToken, URLToken, HitCount, TimeCreated, and LastVisit).

Using client variables with cflocation

If you use the cflocation tag to redirect ColdFusion to a path that ends with .dbm or .cfm, the Client.URLToken variable is automatically appended to the URL. You can prevent this behavior by adding the attribute addtoken="No" to the cflocation tag.

Caching client variable

When ColdFusion reads or writes client variables, it caches the variables in memory to help decrease the overhead of accessing the client data. As a result, ColdFusion only accesses the client data store when you read its value for the first time or, for values you set, when the request ends. Additional references to the client variable use the cached value in ColdFusion memory, thereby processing the page more quickly.

Exporting the client variable database

If your client variable database is stored in the Windows system Registry and you need to move it to another machine, you can export the Registry key that stores your client variables and take it to your new server. The system Registry lets you export and import Registry entries.

To export your client variable database from the Registry in Windows:

  1. Open the Registry editor.
  2. Find and select the following key:
    HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\ColdFusion\CurrentVersion\
    Clients
  3. On the Registry menu, click Export Registry File.
  4. Enter a name for the Registry file.

After you create a Registry file, you can copy it to a new machine and import it by clicking Import Registry File on the Registry editor Registry menu.

Note: On UNIX systems, the registry entries are kept in /opt/coldfusion/registry/cf.registry, a text file that you can copy and edit directly.


Configuring and using session variables

Use session variables when you need the variables for a single site visit or set of requests. For example, you might use session variables to store a user’s selections in a shopping cart application. (Use client variables if you need a variable in multiple visits.)

Caution: Put code that uses session variables inside cflock tags in circumstances that might result in race conditions from multiple accesses to the same variable. For information on using cflock tags see Locking code with cflock.

This section describes the following topics:

  • What is a session?
  • Configuring and enabling session variables
  • Storing session data in session variables
  • Standard session variables
  • Getting a list of session variables
  • Creating and deleting session variables
  • Accessing and changing session variables
  • Ending a session

What is a session?

A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.

This logical view of a session begins with the first connection to an application by a client and ends after that client's last connection. However, because of the stateless nature of the web, it is not always possible to define a precise point at which a session ends. A session should end when the user finishes using an application. In most cases, however, a web application has no way of knowing if a user has finished or is just lingering over a page.

Therefore, sessions always terminate after a time-out period of inactivity. If the user does not access a page of the application within this time-out period, ColdFusion interprets this as the end of the session and clears any variables associated with that session.

The default time-out for session variables is 20 minutes. You can change the default time-out on the Memory Variables page in the Server Settings area in the ColdFusion MX Administrator.

You can also set the time-out period for session variables inside a specific application (thereby overruling the Administrator default setting) by setting the Application.cfc This.sessionTimeout variable or by using the cfapplication tag sessionTimeout attribute. However, you cannot set a time-out value for that is greater than the maximum session time-out value set on the Administrator Memory Variables page.

For detailed information on ending sessions and deleting session variables, see Ending a session.

ColdFusion and J2EE session management

The ColdFusion server can use either of the following types of session management:

  • ColdFusion session management
  • J2EE servlet session management

ColdFusion session management uses the same client identification method as ColdFusion client management.

J2EE session management provides the following advantages over ColdFusion session management:

  • J2EE session management uses a session-specific session identifier, jsessionid, which is created afresh at the start of each session.
  • You can share session variables between ColdFusion pages and JSP pages or Java servlets that you call from the ColdFusion pages.
  • The session automatically ends when the user closes all browser windows.
  • The Session scope is serializable (convertible into a sequence of bytes that can later be fully restored into the original object). With ColdFusion session management, the Session scope is not serializable. Only serializable scopes can be shared across servers.

Therefore, consider using J2EE session management in any of the following cases:

  • You want to maximize session security, particularly if you also use client variables
  • You want to share session variables between ColdFusion pages and JSP pages or servlets in a single application.
  • You want to be able to manually terminate a session while maintaining the client identification cookie for use by the Client scope.
  • You want to support clustered sessions; for example, to support session failover among servers.


Configuring and enabling session variables

To use session variables, you must enable them in two places:

  • ColdFusion MX Administrator
  • The Application.cfc initialization code This.sessionManagement variable or the active cfapplication tag.

ColdFusion MX Administrator, Application.cfc, and the cfapplication tag also provide facilities for configuring session variable behavior, including the variable time-out.

Selecting and enabling session variables in ColdFusion MX Administrator

To use session variables, they must be enabled on the ColdFusion MX Administrator Memory Variables page. (They are enabled by default.) You can also use the Administrator Memory Variables page to do the following:

  • Select to use ColdFusion session management (the default) or J2EE session management.
  • Change the default session time-out. Application code can override this value. The default value for this time-out is 20 minutes.
  • Specify a maximum session time-out. Application code cannot set a time-out greater than this value. The default value for this time-out is two days.

Enabling session variables in your application

You must also enable session variables in the initialization code of your Application.cfc file or in the cfapplication tag in your Application.cfm file.

Do the following in the Application.cfc initialization code, below the cfcomponent tag, to enable session variables:

  • Set This.sessionManagement="Yes".
  • Set This.name to specify the application's name.
  • Optionally, set This.sessionTimeout to set an application-specific session time-out value. Use the CreateTimeSpan function to specify the number of days, hours, minutes, and seconds for the time-out.

Do the following in the Application.cfm file to enable session variables:

  • Set sessionManagement="Yes"
  • Use the name attribute to specify the application's name.
  • Optionally, use the sessionTimeout attribute to set an application-specific session time-out value. Use the CreateTimeSpan function to specify the number of days, hours, minutes, and seconds for the time-out.

The following sample code enables session management for the GetLeadApp application and sets the session variables to time out after a 45-minute period of inactivity:

<cfapplication name="GetLeadApp"
sessionmanagement="Yes"
sessiontimeout=#CreateTimeSpan(0,0,45,0)#>


Storing session data in session variables

Session variables are designed to store session-level data. They are a convenient place to store information that all pages of your application might need during a user session, such as shopping cart contents or score counters.

Using session variables, an application can initialize itself with user-specific data the first time a user accesses one of the application’s pages. This information can remain available while that user continues to use that application. For example, you can retrieve information about a specific user’s preferences from a database once, the first time a user accesses any page of an application. This information remains available throughout that user’s session, thereby avoiding the overhead of retrieving the preferences repeatedly.


Standard session variables

If you use ColdFusion session variables, the Session scope has four built-in, read-only variables that your application can use. If you use J2EE session management, the Session scope has two built-in variables. Generally, you use these variables in your ColdFusion pages only if your application supports browsers that do not allow cookies. For more information on supporting browsers that do not allow cookies, see Using client and session variables without cookies. The following table describes the built-in session variables.

Variable

Description

Session.CFID

ColdFusion session management only: the client ID, normally stored on the client system as a cookie.

Session.CFToken

ColdFusion session management only: the client security token, normally stored on the client system as a cookie.

Session.URLToken

ColdFusion session management: A combination of the CFID and CFToken values in the form CFID=IDNum&CFTOKEN=tokenNum. Use this variable if the client does not support cookies and you must pass the CFID and CFToken variables from page to page.

J2EE session management: A combination of the CFID and CFToken cookies and the J2EE session ID, in the form CFID=IDNum&CFTOKEN=tokenNum&jsessionid=SessionID.

Session.SessionID

A unique identifier for the session.

ColdFusion session management: a combination of the application name and CFID and CFToken values.

J2EE session management: the jsessionid value.

Note: ColdFusion lets you delete or change the values of the built-in session variables. As a general rule, avoid doing so.

If you enable client variables and ColdFusion session management, ColdFusion uses the same values for the Client and Session scope CFID, CFToken, and URLtoken variables. ColdFusion gets the values for these variables from the same source, the client’s CFID and CFTOKEN cookies.

If you use J2EE session management, the Session scope does not include the Session.CFID or Session.CFToken variables, but does include the Session.URLToken and Session.SessionID variables. In this case, the Session.SessionID is the J2EE session ID and Session.URLToken consists of the string jsessionid= followed by the J2EE session ID.


Getting a list of session variables

Use the StructKeyList function to get a list of session variables, as follows:

<cflock timeout=20 scope="Session" type="Readonly">
    <cfoutput> #StructKeyList(Session)# </cfoutput>
</cflock>

Caution: Always put code that accesses session variables inside cflock tags.


Creating and deleting session variables

Use a standard assignment statement to create a new session variable, as follows:

<cflock timeout=20 scope="Session" type="Exclusive">
    <cfset Session.ShoppingCartItems = 0>
</cflock>

Use the structdelete tag to delete a session variable; for example:

<cflock timeout=20 scope="Session" type="Exclusive">
    <cfset StructDelete(Session, "ShoppingCartItems")>
</cflock>

Note: If you set session variables on a CFML template that uses the cflocation tag, ColdFusion might not set the variables. For more information, see Macromedia TechNote 22712 at www.macromedia.com/v1/Handlers/index.cfm?ID=22712&Method=Full.


Accessing and changing session variables

You use the same syntax to access a session variable as for other types of variables. However, you must lock any code that accesses or changes session variables.

For example, to display the number of items in a user’s shopping cart, use favorite color that has been set for a specific user, for example, use the following code:

<cflock timeout=20 scope="Session" type="Exclusive">
    <cfoutput>
        Your shopping cart has #Session.ShoppingCartItems# items.
    </cfoutput>
</cflock>

To change increase the number of items in the shopping cart, use the following code:

<cflock timeout=20 scope="Session" type="Exclusive">
    <cfset Session.ShoppingCartItems = Session.ShoppingCartItems + 1>
</cflock>


Ending a session

The following rules apply to ending a session and deleting Session scope variables:

  • If you use ColdFusion session management, ColdFusion automatically ends sessions and deletes all Session scope variables if the client is inactive for the session time-out period. The session does not end when the user closes the browser.
  • If you use J2EE session management, ColdFusion MX ends the session and deletes all Session scope variables when the user closes the browser, or if the client is inactive for the session time-out period. If the session times out, however, the browser continues to send the same session ID, and ColdFusion will reuse this ID for sessions with this browser instance, as long as the browser remains active.
  • Logging a user out does not end the session or delete Session scope variables.
  • In many cases, you can effectively end a session by clearing the Session scope, as shown in the following line. The following list, however, includes important limitations and alternatives:
    <cfset StructClear(Session)>
  • Clearing the Session scope does not clear the session ID, and future requests from the browser continue to use the same session ID until the browser exits. It also does not log the user out, even if you use Session scope storage for login information. Always use the cflogout tag to log users out.
  • If you use J2EE session management, you can invalidate the session, as follows:
    <cfset getPageContext().getSession().invalidate()>

    This line creates a pointer to the servlet page context and calls an internal method to reset the session. This clears all session information, including the session ID Session scope variables, and if you are using session login storage, the login information, for future request. However, the session information does remain available until the end of the current request. After you invalidate a session, attempts by the browser to access the application will generate an invalid session exception until the session times out.

    Note: You cannot destroy the session and create a session on the same request, as creating a new session involves sending session cookies back.

  • If you do not use client cookies, the Session scope and login state is available to your application only as long as you pass the session’s CFID, CFTOKEN, and, for J2EE sessions, jsessionid values in the URL query string. After you stop using these values, however, the session data remains in memory until the session time-out period elapses.


Configuring and using application variables

Application variables are available to all pages within an application, that is, pages that have the same application name. Because application variables are persistent, you easily can pass values between pages. You can use application variables for information including the application name, background color, data source names, or contact information.

You set the application name in the cfapplication tag, normally on your application’s Application.cfm page. The application name is stored in the Application.applicationName variable.

Unlike client and session variables, application variables do not require that a client name (client ID) be associated with them. They are available to any clients that use pages in the application.

Caution: Put code that uses application variables inside cflock tags in circumstances that might result in race conditions from multiple accesses to the same variable. For information on using cflock tags, see Locking code with cflock.

The following sections describe how to configure and use application variables.

Configuring and enabling application variables

To use application variables, do the following:

  • Ensure that they are enabled in the ColdFusion MX Administrator. (They are enabled by default.)
  • Specify the application name by setting the This.name variable in the initialization code of the Application.cfc or by setting the name attribute of the cfapplication tag for the current page.

    Note: ColdFusion supports unnamed applications for compatibility with J2EE applications. For more information, see Unnamed ColdFusion Application and Session scopes.

The ColdFusion MX Administrator also lets you specify the following information:

  • A default variable time-out. If all pages in an application are inactive for the time-out period, ColdFusion deletes all the application variables. The Application.cfc file or cfapplication tag can override this value for a specific application. The default value for this time-out is two days.
  • A maximum time-out. The application code cannot set a time-out greater than this value. The default value for this time-out is two days.

You can set the time-out period for application variables within a specific application by using the This.applicationTimeout variable of Application.cfc or the applicationTimeout attribute of the cfapplication tag.

Storing application data in application variables

Application variables are a convenient place to store information that all pages of your application might need, no matter which client is running that application. Using application variables, an application could, for example, initialize itself when the first user accesses any page of that application. This information can then remain available indefinitely, thereby avoiding the overhead of repeated initialization.

Because the data stored in application variables is available to all pages of an application, and remains available until a specific period of inactivity passes or the ColdFusion server shuts down, application variables are convenient for application-global, persistent data.

However, because all clients running an application see the same set of application variables, these variables are not appropriate for client-specific or session-specific information. To target variables for specific clients, use client or session variables.

Using application variables

Generally, application variables should hold information that you write infrequently. In most cases, the values of these variables are set once, most often when an application first starts. Then the values of these variables are referenced many times throughout the life of the application or the course of a session.

In circumstances that might result in race conditions from multiple accesses to the same variable, put code that writes to Application scope variables or reads Application scope variables with data that can change inside cflock tags.

Because each Application scope variable is shared in memory by all requests in the application, these variables can become bottlenecks if used inappropriately. Whenever a request is reading or writing an Application scope variable, any other requests that use the variable must wait until the code accessing the variable completes. This problem is increased by the processing time required for locking. If many users access the application simultaneously and you use Application scope variables extensively, your application performance might degrade. If your application uses many application variables, consider whether the variables must be in the Application scope or whether they can be Session or Request scope variables.

The application scope has one built-in variable, Application.applicationName, which contains the application name you specify in the cfapplication tag.

You access and manipulate application variables the same way you use session variables, except that you use the variable prefix Application, not Session, and specify Session as the lock scope. For examples of using session variables see Creating and deleting session variables and Accessing and changing session variables.

For information on locking write-once read-many application variables efficiently, see Locking application variables efficiently


Using server variables

Server variables are associated with a single ColdFusion server. They are available to all applications that run on the server. Use server variables for data that must be accessed across clients and applications, such as global server hit counts.

Server variables do not time out, but they are lost when the server shuts down. You can delete server variables.

Server variables are stored on a single server. As a result, you should not use server variables if you use ColdFusion on a server cluster.

You access and manipulate server variables the same way use Session and application variables, except you use the variable prefix Server.

Caution: Put code that uses server variables inside cflock tags in circumstances that might result in race conditions from multiple accesses to the same variable. You do not have to lock access to built-in server variables.

ColdFusion provides the following standard built-in read-only server variables:

Variable | Description
Server.ColdFusion.AppServer | The name of the J2EE application server ColdFusion is using. For ColdFusion MX server editions, which have an integrated application server, the name is JRun4.
Server.ColdFusion.Expiration | The date on which the ColdFusion MX license expires if it is the trial version.
Server.ColdFusion.ProductLevel | The server product level, such as Enterprise.
Server.ColdFusion.ProductName | The name of the product (ColdFusion MX).
Server.ColdFusion.ProductVersion | The version number for the server that is running, such as 6,0,0.
Server.ColdFusion.Rootdir | Directory under which ColdFusion is installed, such as C:\cfusion.
Server.ColdFusion.SerialNumber | The serial number assigned to this server installation.
Server.ColdFusion.SupportedLocales | The locales, such as English (US) and Spanish (Standard), supported by the server.
Server.OS.AdditionalInformation | Additional information provided by the operating system, such as the Service Pack number.
Server.OS.arch | The processor architecture, such as x86 for Intel Pentium processors.
Server.OS.BuildNumber | The specific operating system build, such as 1381
Server.OS.Name | The name of the operating system, such as Windows NT.
Server.OS.Version | The version number of the operating system, such as 4.0.


Locking code with cflock

The cflock tag controls simultaneous access to ColdFusion code. The cflock tag lets you do the following:

  • Protect sections of code that access and manipulate shared data in the Session, Application, and Server scopes.
  • Ensure that file updates do not fail because files are open for writing by other applications or ColdFusion tags.
  • Ensure that applications do not try to simultaneously access ColdFusion extension tags written using the CFX API that are not thread-safe. This is particularly important for CFX tags that use shared (global) data structures without protecting them from simultaneous access (not thread-safe). However, Java CFX tags can also access shared resources that could become inconsistent if the CFX tag access is not locked.
  • Ensure that applications do not try to simultaneously access databases that are not thread-safe. (This is not necessary for most database systems.)

ColdFusion MX is a multithreaded web application server that can process multiple page requests at a time. As a result, the server can attempt to access the same information or resources simultaneously, as the result of two or more requests.

Although ColdFusion MX is thread-safe and does not try to modify a variable simultaneously, it does not ensure the correct order of access to information. If multiple pages, or multiple invocations of a page, attempt to write data simultaneously, or read and write it at the same time, the resulting data can be inconsistent, as shown in the following Sample locking scenarios section.

Similarly, ColdFusion MX cannot automatically ensure that two sections of code do not attempt to access external resources such as files, databases, or CFX tags that cannot properly handle simultaneous requests. Nor can ColdFusion MX ensure that the order of access to these shared resources is consistent and results in valid data.

By locking code that accesses such resources so that only one thread can access the resource at a time, you can prevent race conditions.

This section describes the following topics:

  • Sample locking scenarios
  • Using the cflock tag with write-once variables
  • Using the cflock tag
  • Considering lock granularity
  • Nesting locks and avoiding deadlocks


Sample locking scenarios

The following examples present scenarios in which you need to lock ColdFusion code. These scenarios show only two of the circumstances where locking is vital.

Reading and writing a shared variable

If you have an application-wide value, such as a counter of the total number of tickets sold, you might have code such as the following on a login page:

<cfset Application.totalTicketsSold = Application.totalTicketsSold + ticketOrder>

When ColdFusion executes this code, it performs the following operations:

  1. Retrieves the current value of Application.totalTicketsSold from temporary storage.
  2. Increments this value.
  3. Stores the result back in the Application scope.

Suppose that ColdFusion processes two ticket orders at approximately the same time, and that the value of Application.totalTicketsSold is initially 160. The following sequence might happen:

  1. Order 1 reads the total tickets sold as 160.
  2. Order 2 reads the total tickets sold as 160.
  3. Order 1 adds an order of 5 tickets to 160 to get 165.
  4. Order 2 adds an order of 3 tickets to 160 to get 163.
  5. Order 1 saves the value 165 to Application.totalTicketsSold
  6. Order 2 saves the value 163 to Application.totalTicketsSold

The application now has an inaccurate count of the tickets sold, and is in danger of selling more tickets than the auditorium can hold.

To prevent this from happening, lock the code that increments the counter, as follows:

<cflock scope="Application" timeout="10" type="Exclusive">
    <cfset Application.totalTicketsSold = Application.totalTicketsSold + ticketOrder>
</cflock>

The cflock tag ensures that while ColdFusion performs the processing in the tag body, no other threads can access the Application scope. As a result, the second transaction is not processed until the first one completes. The processing sequence looks something like the following:

  1. Order 1 reaches the lock tag, which gets an Application scope lock.
  2. Order 1 reads the total tickets sold as 160.
  3. Order 2 reaches the lock tag. Because there is an active Application scope lock, ColdFusion waits for the lock to free.
  4. Order 1 adds an order of 5 tickets to 160 to get 165.
  5. Order 1 saves the value 165 to Application.totalTicketsSold.
  6. Order 1 exits the lock tag. The Application scope lock is now free.
  7. Order 2 gets the Application scope lock and can begin processing.
  8. Order 2 reads the total tickets sold as 165.
  9. Order 2 adds an order of 3 tickets to 165 to get 168.
  10. Order 2 saves the value 168 to Application.totalTicketsSold.
  11. Order 2 exits the lock tag, which frees the Application scope lock. ColdFusion can process another order.

The resulting Application.totalTickesSold value is now correct.

Ensuring consistency of multiple variables

Often an application sets multiple shared scope variables at one time, such as a number of values submitted by a user on a form. If the user submits the form, clicks the back button, and then resubmits the form with different data, the application might end up with a mixture of data from the two submissions, in much the same manner as shown in the previous section.

For example, an application might store information about order items in a Session scope shopping cart. If the user submits an item selection page with data specifying sage green size 36 shorts, and then resubmits the item specifying sea blue size 34 shorts, the application might end up with a mixture of information from the two orders, such as sage green size 34 shorts.

By putting the code that sets all of the related session variables in a single cflock tag, you ensure that all the variables get set together. In other words, setting all of the variables becomes an atomic, or single, operation. It is similar to a database transaction, where everything in the transaction happens, or nothing happens. In this example, the order details for the first order all get set, and then they are replaced with the details from the second order.

For more examples of using locking in applications, see Examples of cflock.


Using the cflock tag with write-once variables

You do not need to use cflock when you read a variable or call a user-defined function name in the Session, Application, or Server scope if it is set in only one place in the application, and is only read (or called, for a UDF) everywhere else. Such data is called write-once. If you set an Application or Session scope variable in Application.cfm and never set it on any other pages, you must lock the code that sets the variable, but do not have to lock code on other pages that reads the variable’s value. If you set the variable in the corresponding start method in Application.cfc (for example, onApplicationStart for Application scope variables), you do not have to lock the code that sets the variable.

However, although leaving code that uses write-once data unlocked can improve application performance, it also has risks. You must ensure that the variables are truly written only once. For example, you must ensure that the variable is not rewritten if the user refreshes the browser or clicks a back button. Also, it can be difficult to ensure that you, or future developers, do not later set the variable in more than one place in the application.


Using the cflock tag

The cflock tag ensures that concurrently executing requests do not run the same section of code simultaneously and thus manipulate shared data structures, files, or CFX tags inconsistently. It is important to remember that cflock protects code sections that access or set data, not the variables themselves.

You protect access to code by surrounding it in a cflock tag; for example:

<cflock scope="Application" timeout="10" type="Exclusive">
    <cfif not IsDefined("Application.number")>
        <cfset Application.number = 1>
    </cfif>
</cflock>

Lock types

The cflock tag offers two modes of locking, specified by the type attribute:

Exclusive locks (the default lock type) Allow only one request to process the locked code. No other requests can run code inside the tag while a request has an exclusive lock.

Enclose all code that creates or modifies session, application, or server variables in exclusive cflock tags.

Read-only locks Allow multiple requests to execute concurrently if no exclusive locks with the same scope or name are executing. No requests can run code inside the tag while a request has an exclusive lock.

Enclose code that only reads or tests session, application, or server variables in read-only cflock tags. You specify a read-only lock by setting the type="readOnly" attribute in the cflock tag, for example:

<cflock scope="Application" timeout="10" type="readOnly">
    <cfif IsDefined("Application.dailyMessage")>
        <cfoutput>#Application.dailyMessage#<br></cfoutput>
    </cfif>
</cflock>

Although ColdFusion does not prevent you from setting shared variables inside read-only lock tag, doing so loses the advantages of locking. As a result, you must be careful not to set any session, application, or server variables inside a read-only cflock tag body.

Note: You cannot upgrade or downgrade a lock from one type to another. In other words, do not nest an exclusive lock in a read-only lock of the same name or scope; the exclusive lock will always time out. Also, do not nest a read-only lock inside an exclusive lock with the same name or scope; doing so has no effect.

Lock scopes and names

The cflock tag prevents simultaneous access to sections of code, not to variables. If you have two sections of code that access the same variable, they must be synchronized to prevent them from running simultaneously. You do this by identifying the locks with the same scope or name attributes.

Note: ColdFusion does not require you to identify exclusive locks. If you omit the identifier, the lock is anonymous and you cannot synchronize the code in the cflock tag block with any other code. Anonymous locks do not cause errors when they protect a resource that is used in a single code block, but they are bad programming practice. You must always identify read-only locks.

Controlling access to data with the scope attribute

When the code that you are locking accesses session, application, or server variables, synchronize access by using the cflock scope attribute.

You can set the attribute to any of the following values:

Scope | Meaning
Server | All code sections with this attribute on the server share a single lock.
Application | All code sections with this attribute in the same application share a single lock.
Session | All code sections with this attribute that run in the same session of an application share a single lock.

If multiple code sections share a lock, the following rules apply:

  • When code is running in a cflock tag block with the type attribute set to Exclusive, code in cflock tag blocks with the same scope attribute is not allowed to run. They wait until the code with the exclusive lock completes.
  • When code in a cflock tag block with the type readOnly is running, code in other cflock tag blocks with the same scope attribute and the readOnly type attribute can run, but any blocks with the same scope attribute and an Exclusive type cannot run and must wait until all code with the read-only lock completes. However, if a read-only lock is active and code with an exclusive lock with the same scope or name is waiting to execute, read-only requests using the same scope or name that are made after the exclusive request is queued must wait until code with the exclusive lock executes and completes.

Controlling locking access to files and CFX tags with the name attribute

The cflock name attribute provides a second way to identify locks. Use this attribute when you use locks to protect code that manges file access or calls non-thread-safe CFX code.

When you use the name attribute, specify the same name for each section of code that accesses a specific file or a specific CFX tag.

Controlling and minimizing lock time-outs

You must include a timeout attribute in your cflock tag. The timeout attribute specifies the maximum time, in seconds, to wait to obtain the lock if it is not available. By default, if the lock does not become available within the time-out period, ColdFusion generates a Lock type exception error, which you can handle using cftry and cfcatch tags.

If you set the cflock throwOnTimeout attribute to No, processing continues after the time-out at the line after the </cflock> end tag. Code in the cflock tag body does not run if the time-out occurs before ColdFusion can acquire the lock. Therefore, never use the throwOnTimeout attribute for CFML that must run.

Normally, it does not take more than a few seconds to obtain a lock. Very large time-outs can block request threads for long periods of time and radically decrease throughput. Always use the smallest time-out value that does not result in a significant number of time-outs.

To prevent unnecessary time-outs, lock the minimum amount of code possible. Whenever possible, lock only code that sets or reads variables, not business logic or database queries. One useful technique is to do the following:

  1. Perform a time-consuming activity outside of a cflock tag
  2. Assign the result to a Variables scope variable
  3. Assign the Variables scope variable’s value to a shared scope variable inside a cflock block.

For example, if you want to assign the results of a query to a session variable, first get the query results using a Variables scope variable in unlocked code. Then, assign the query results to a session variable inside a locked code section. The following code shows this technique:

<cfquery name="Variables.qUser" datasource="#request.dsn#">
    SELECT FirstName, LastName
    FROM Users
    WHERE UserID = #request.UserID#
</cfquery>
<cflock scope="Session" timeout="5" type="exclusive">
    <cfset Session.qUser = Variables.qUser>
</cflock>


Considering lock granularity

When you design your locking strategy, consider whether you should have multiple locks containing small amounts of code or few locks with larger blocks of code. There is no simple rule for making such a decision, and you might do performance testing with different options to help make your decision. However, you must consider the following issues:

  • If the code block is larger, ColdFusion will spend more time inside the block, which might increase the number of times an application waits for the lock to released.
  • Each lock requires processor time. The more locks you have, the more processor time is spent on locking code.


Nesting locks and avoiding deadlocks

Inconsistent nesting of cflock tags and inconsistent naming of locks can cause deadlocks (blocked code). If you are nesting locks, you must consistently nest cflock tags in the same order and use consistent lock scopes (or names).

A deadlock is a state in which no request can execute the locked section of the page. All requests to the protected section of the page are blocked until there is a time-out. The following table shows one scenario that would cause a deadlock:

User 1 | User 2
Locks the Session scope. | Locks the Application scope.
Tries to lock the Application scope, but the Application scope is already locked by User 2. | Tries to lock the Session scope, but the Session scope is already locked by User 1.

Neither user’s request can proceed, because it is waiting for the other to complete. The two are deadlocked.

Once a deadlock occurs, neither of the users can do anything to break the deadlock, because the execution of their requests is blocked until the deadlock is resolved by a lock time-out.

You can also cause deadlocks if you nest locks of different types. An example of this is nesting an exclusive lock inside a read-only lock of the same scope or same name.

In order to avoid a deadlock, lock code sections in a well-specified order, and name the locks consistently. In particular, if you need to lock access to the Server, Application, and Session scopes, you must do so in the following order:

  1. Lock the Session scope. In the cflock tag, specify scope="Session".
  2. Lock the Application scope. In the cflock tag, specify scope="Application".
  3. Lock the Server scope. In the cflock tag, specify scope="Server".
  4. Unlock the Server scope.
  5. Unlock the Application scope.
  6. Unlock the Session scope.

Note: You can skip any pair of lock and unlock steps in the preceding list if you do not need to lock a particular scope. For example, you can omit steps 3 and 4 if you do not need to lock the Server scope.

Copying shared variables into the Request scope

You can avoid locking some shared-scope variables multiple times during a request by doing the following:

  1. Copy the shared-scope variables into the Request scope in code with an exclusive lock in the Application.cfc onRequestStart method or the Application.cfm page.
  2. Use the Request scope variables on your ColdFusion pages for the duration of the request.
  3. Copy the variables back to the shared scope in code with an exclusive lock in the Application.cfc onRequestEnd method on the OnRequestEnd.cfm page.

With this technique the "last request wins." For example, if two requests run simultaneously, and both requests change the values of data that was copied from the shared scope, the data from the last request to finish is saved in the shared scope, and the data from the previous request is not saved.

Locking application variables efficiently

The need to lock application variables can reduce server performance, because all requests that use Application scope variables must wait on a single lock. This issue is a problem even for write-once read-many variables, because you still must ensure the variable exists, and possibly set the value before you can read it.

You can minimize this problem by using a technique such as the following to test for the existence of application variables and set them if they do not exist:

  1. Use an Application scope flag variable to indicate if the variable or variables are initialized. In a read-only lock, check for the existence of the flag, and assign the result to a local variable.
  2. Outside the cflock bock, test the value of the local variable
  3. If it the local variable indicates that the application variables are not initialized, get an exclusive Application scope lock.
  4. Inside the lock, again test the Application scope flag, to make sure another page has not set the variables between step one and step four.
  5. If the variables are still not set, set them and set the Application scope flag to true.
  6. Release the exclusive lock.

The following code shows this technique:

<!--- Initialize local flag to false. --->
<cfset app_is_initialized = False>
<!--- Get a readonly lock --->
<cflock scope="application" type="readonly">
    <!--- read init flag and store it in local variable --->
    <cfset app_is_initialized = IsDefined("APPLICATION.initialized")>
</cflock>
<!--- Check the local flag --->
<cfif not app_is_initialized >
<!--- Not initialized yet, get exclusive lock to write scope --->
    <cflock scope="application" type="exclusive">
        <!--- Check nonlocal flag since multiple requests could get to the
                exclusive lock --->
        <cfif not IsDefined("APPLICATION.initialized") >
            <!--- Do initializations --->
            <cfset APPLICATION.varible1 = someValue >
             ...
            <!--- Set the Application scope initialization flag --->
            <cfset APPLICATION.initialized = "yes">
        </cfif>
    </cflock>
</cfif>


Examples of cflock

The following examples show how to use cflock blocks in a variety of situations.

  • Example with application, server, and session variables
  • Example of synchronizing access to a file system
  • Example of protecting ColdFusion extensions

Example with application, server, and session variables

This example shows how you can use cflock to guarantee the consistency of data updates to variables in the Application, Server, and Session scopes.

This example does not handle exceptions that arise if a lock times out. As a result, users see the default exception error page on lock time-outs.

The following sample code might be part of the Application.cfm file:

<cfapplication name="ETurtle"
    sessiontimeout=#createtimespan(0,1,30,0)#
    sessionmanagement="yes">

<!--- Initialize the Session and Application
variables that will be used by E-Turtleneck. Use
the Session lock scope for the session variables. --->

<cflock scope="Session"
    timeout="10" type ="Exclusive">
    <cfif not IsDefined("session.size")>
        <cfset session.size = "">
    </cfif>
    <cfif not IsDefined("session.color")>
        <cfset session.color = "">
    </cfif>
</cflock>

<!--- Use the Application scope lock for the Application.number variable.
This variable keeps track of the total number of turtlenecks sold.
The following code implements the scheme shown in the Locking Application
variables effectively section --->

<cfset app_is_initialized = "no">
<cflock scope="Application" type="readonly">
    <cfset app_is_initialized = IsDefined("Application.initialized")>
</cflock>
<cfif not app_is_initialized >
    <cflock scope="application" timeout="10" type="exclusive">
        <cfif not IsDefined("Application.initialized") >
            <cfset Application.number = 1>
            <cfset Application.initialized = "yes">
        </cfif>
    </cflock>
</cfif>

<!--- Always display the number of turtlenecks sold --->

<cflock scope="Application"
    timeout="10"
    type ="ReadOnly">
    <cfoutput>
    E-Turtleneck is proud to say that we have sold
    #Application.number# turtlenecks to date.
    </cfoutput>
</cflock>

The remaining sample code could appear inside the application page where customers place orders:

<html>
<head>
<title>cflock Example</title>
</head>

<body>
<h3>cflock Example</h3>

<cfif IsDefined("Form.submit")>

<!--- Lock session variables --->
<!--- Note that we use the automatically generated Session
    ID as the order ID --->
<cflock scope="Session"
    timeout="10" type="ReadOnly">
    <cfoutput>Thank you for shopping E-Turtleneck.
    Today you have chosen a turtleneck in size
    <b>#form.size#</b> and in the color <b>#form.color#</b>.
    Your order ID is #Session.sessionID#.
    </cfoutput>
</cflock>

<!--- Lock session variables to assign form values to them. --->

<cflock scope="Session"
    timeout="10"
    type="Exclusive">
    <cfparam name=Session.size default=#form.size#>
    <cfparam name=Session.color default=#form.color#>
</cflock>
<
!--- Lock the Application scope variable application.number to
update the total number of turtlenecks sold. --->

<cflock scope="Application"
    timeout="30" type="Exclusive">
    <cfset application.number=application.number + 1>
</cflock>

<!--- Show the form only if it has not been submitted. --->
<cfelse>
<form action="cflock.cfm" method="Post">

<p> Congratulations! You have just selected
the longest-wearing, most comfortable turtleneck
in the world. Please indicate the color and size
you want to buy.</p>

<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td>Select a color.</td>
<td><select type="Text" name="color">
        <option>red
        <option>white
        <option>blue
        <option>turquoise
        <option>black
        <option>forest green
        </select>
    </td>
</tr>
<tr>
    <td>Select a size.</td>
    <td><select type="Text" name="size">
        <option>small
        <option>medium
        <option>large
        <option>xlarge
        </select>
    </td>
</tr>
<tr>
    <td></td>
    <td><input type="Submit" name="submit" value="Submit">
    </td>
</tr>
</table>
</form>
</cfif>

</body>
</html>

Note: In this simple example, the Application.cfm page displays the Application.number variable value. Because the Application.cfm file is processed before any code on each ColdFusion page, the number that displays after you click the submit button does not include the new order. One way you can resolve this problem is by using the OnRequestEnd.cfm page to display the value at the bottom of each page in the application.


Example of synchronizing access to a file system

The following example shows how to use a cflock block to synchronize access to a file system. The cflock tag protects a cffile tag from attempting to append data to a file already open for writing by the same tag executing on another request.

If an append operation takes more than 30 seconds, a request waiting to obtain an exclusive lock to this code might time out. Also, this example uses a dynamic value for the name attribute so that a different lock controls access to each file. As a result, locking access to one file does not delay access to any other file.

<cflock name=#filename# timeout=30 type="Exclusive">
    <cffile action="Append"
        file=#fileName#
        output=#textToAppend#>
</cflock>


Example of protecting ColdFusion extensions

The following example shows how you can build a custom tag wrapper around a CFX tag that is not thread-safe. The wrapper forwards attributes to the non-thread-safe CFX tag that is used inside a cflock tag.

<cfparam name="Attributes.AttributeOne" default="">
<cfparam name="Attributes.AttributeTwo" default="">
<cfparam name="Attributes.AttributeThree" default="">

<cflock timeout=5
        type="Exclusive"
        name="cfx_not_thread_safe">
    <cfx_not_thread_safe attributeone=#attributes.attributeone#
        attributetwo=#attributes.attributetwo#
        attributethree=#attributes.attributethree#>
</cflock>
Previous


Securing Applications

This chapter provides an overview of Macromedia ColdFusion security features, including brief descriptions of several ColdFusion security features and links to additional documentation not included in this chapter.

This chapter includes a summary of resource security (ColdFusion MX Standard) or sandbox security (ColdFusion MX Enterprise), where security restricts access to specific resources, such as tags and files. The information describes how you use the ColdFusion MX Administrator to configure sandbox or resource security, and discusses structuring an application to take advantage of this security.

This chapter also includes detailed description of user security, which depends on a user identity. It explains in detail how to implement user security in ColdFusion applications.

Other chapters discuss specific security issues as part of the context of their topics. For links to some of the more significant security features, see the cross references in ColdFusion security features. Also see the security entries in the Index. For detailed information on using Administrator-controlled security features, see Configuring and Administering ColdFusion MX.

This chapter does not discuss general security issues or web server security concepts and issues in any detail. For example, it does not discuss web server security management issues, such as enabling HTTPS protocol support. For information on enabling web server security features, see your web server documentation. Many books and other resources are available on web and application security.

Contents

ColdFusion security features

About resource and sandbox security

About user security

Using ColdFusion security tags and functions

Security scenarios

Implementing user security
Next


ColdFusion security features

ColdFusion provides scalable, granular security for building and deploying your ColdFusion applications.

ColdFusion provides the following types of security resources:

Development ColdFusion MX Administrator is protected by a password. Additionally, you can specify a password for access to data sources from Macromedia Dreamweaver MX. For more information on configuring Administrator security passwords, see the ColdFusion MX Administrator online Help.

CFML features The CFML language includes specific features that you can use to enhance application security. These include the following features:

  • The cfqueryparam tag This tag helps prevent users from injecting malicious SQL expressions. For more information on using this tag for database security, see Enhancing security with cfqueryparam,
  • Scriptprotect setting This setting helps protect against cross-site scripting attacks. You can set this value with the ColdFusion MX Administrator Enable Global Script Protection setting, in the Application.cfc This.scriptprotect variable, or in the corresponding cfapplication tag scriptprotect attribute. For more information on this feature, see cfapplication in CFML Reference. For information on Application.cfc see Defining the application and its event handlers in Application.cfc.
  • Encryption and hashing functions The Encrypt, Decrypt, and Hash functions let you select a secure algorithm for encrypting and decrypting data or generating a hash "fingerprint." You can select from among several secure algorithms that are supported by the underlying Java security mechanisms; for encryption, these include, AES, Blowfish, DES and Triple DES. For more information, see the Encrypt, Decrypt, and Hash, functions in CFML Reference.
  • Data validation tools ColdFusion includes a variety of tools for validating form input and other data values, including ways to ensure that users do not submit malicious form data. For information on data validation see Validating Data; for specific information on security and validation, see Security considerations.

Note: This chapter does not discuss development or CFML language security features. For additional information on security in ColdFusion programs, see the security entries in the index.

Resource/Sandbox The ColdFusion MX Administrator can limit access to ColdFusion resources, including selected tags and functions, data sources, files, and host addresses. In the Standard Edition, you configure a single set of resource limitations that apply to all your ColdFusion applications.

In the Enterprise Edition, you can have multiple sandboxes, based on the location of your ColdFusion pages, each with its own set of resource limitations. You can confine applications to secure areas, thereby flexibly restricting the access that the application has to resources.

User ColdFusion applications can require users to log in to use application pages. You can assign users to roles (sometimes called groups); ColdFusion pages can determine the logged-in user’s roles or ID and selectively determine what to do based on this information. User security is also called authentication and authorization security.

Note: You can also use the cfencode utility, located in the cf_root/bin directory, to obscure ColdFusion pages that you distribute. Although this technique cannot prevent persistent hackers from determining the contents of your pages, it does prevent inspection of the pages.


About resource and sandbox security

ColdFusion provides two levels of resource-based security:

  • ColdFusion MX Standard refers to its resource-based security as resource security. It lets you specify a single set of limitations on access to ColdFusion resources that apply to all ColdFusion applications.
  • ColdFusion MX Enterprise refers to its resource-based security as sandbox security. Sandbox security is a superset of resource security. Sandbox security lets you create multiple sandboxes, each corresponding to a different directory. For each sandbox, you specify a set of resource limitations that apply to all ColdFusion pages in the sandbox directory and its subdirectories. If you create a sandbox that is a subdirectory of a sandbox, the subdirectory’s rules override the parent directory’s rules.

The ColdFusion MX Administrator Resource Security page (in Standard) and Sandbox Security page (in Enterprise) let you enable resource-based security. In ColdFusion Standard, the page lets you configure the resource settings that apply to all your ColdFusion applications. In ColdFusion Enterprise, the page lets you create sandboxes and configure the resource limitations for each sandbox individually.

Resource control

ColdFusion lets you control access to the following resources:

Resource

Description

Data sources

Enables access to specified data sources.

CF tags

Prevents pages from using CFML tags that access external resources. You can prevent pages in the directory from using any or all of the following tags:

cfcollection, cfcontent, cfcookie, cfdirectory, cfdocument, cfexecute, cffile, cfftp, cfgridupdate, cfhttp, cfhttpparam, cfindex, cfinsert, cfinvoke, cfldap, cflog, cfmail, cfobject, cfobjectcache, cfpop, cfquery, cfregistry, cfreport, cfschedule, cfsearch, cfstoredproc, cftransaction, cfupdate

CF functions

Prevents pages from using CFML functions that access external resources. You can prevent pages from using any or all of the following functions:

CreateObject (COM), CreateObject (Java), CreateObject (Web Service), DirectoryExists. ExpandPath, FileExists, GetBaseTemplatePath, GetDirectoryFromPath, GetFileFromPath, GetGatewayHelper, GetProfileString, GetTempDirectory, GetTempFile, GetTemplatePath, SendGatewayMessage, SetProfileString

Files/directories

Sets read, write, execute, and delete access to specified directories, directory trees, or files.

Server/ports

Controls access from ColdFusion to IP addresses and port numbers. You can specify host names or numeric addresses, and you can specify individual ports and port ranges..

Note: For more information on configuring resource and sandbox security, see Configuring and Administering ColdFusion MX and the ColdFusion MX Administrator online Help.

Sandbox security

In ColdFusion Enterprise, sandbox security lets you apply different sets of rules to different directory structures. You can use it to partition a shared hosting environment so that a number of applications with different purposes, and possibly different owners, run securely on a single server. When multiple applications share a host, you set up a separate directory structure for each application, and apply rules that let each application access only its own data sources and files.

Sandbox security also lets you structure and partition an application to reflect the access rights that are appropriate to different functional components. For example, if your application has both employee inquiry functions and HR functions that include creating, accessing, and modifying sensitive data, you could structure the application as follows:

  • HR pages go in one directory with access rules that enable most activities.
  • Employee pages go in another directory whose rules limit the files they can modify and the tags they can use.
  • Pages required for both HR and employee functions go in a third directory with appropriate access rules.


About user security

User security lets your application use security rules to determine what it shows. It has two elements:

Authentication Ensures that a valid user is logged-in, based on an ID and password provided by the user. ColdFusion (or, in some cases if you use web server authentication, the web server) maintains the user ID information while the user is logged-in.

Authorization Ensures that the logged-in user is allowed to use a page or perform an operation. Authorization is typically based on one or more roles (sometimes called groups) to which the user belongs. For example, in an employee database, all users could be members of either the employee role or the contractor role. They could also be members of roles that identify their department, position in the corporate hierarchy, or job description. For example, someone could be a member of some or all of the following roles:

  • Employees
  • Human Resources
  • Benefits
  • Managers

Roles enable you to control access in your application resources without requiring the application to maintain knowledge about individual users. For example, suppose you use ColdFusion for your company’s intranet. The Human Resources department maintains a page on the intranet on which all employees can access timely information about the company, such as the latest company policies, upcoming events, and job postings. You want everyone to be able to read the information, but you want only certain authorized Human Resources employees to be able to add, update, or delete information.

Your application gets the user’s roles from the user information data store when the user logs in, and then enables access to specific pages or features based on the roles. Typically, you store user information in a database, LDAP directory, or other secure information store.

You can also use the user ID for authorization. For example, you might want to let employees view customized information about their salaries, job levels, and performance reviews. You certainly would not want one employee to view sensitive information about another employee, but you would want managers to be able to see, and possibly update, information about their direct reports. By employing both user IDs and roles, you can ensure that only the appropriate people can access or work with sensitive data.

The following figure shows a typical flow of control for user authentication and authorization. Following sections expand on this diagram to describe how you implement user security in ColdFusion.

This is a picture of the feature being described.

This section describes the following topic:

  • Authenticating users

Authenticating users

You can use either, or both, of the following forms of authentication to secure your ColdFusion application:

  • Web server authentication, where the web server authenticates the user and does not allow access to the website by users without valid login IDs
  • Application authentication, where the ColdFusion application authenticates the user and does not allow access to the application by users without valid login IDs

About web server authentication

All major web servers support basic HTTP authentication. Some web servers also support other authentication methods, including Digest HTTP authentication and Microsoft NTLM authentication.

Note: Macromedia Dreamweaver MX and Studio MX do not support NTLM security with RDS. Therefore, you cannot use RDS with these applications if the ColdFusion RDS servlet (cf_root/CFIDE/main/ide.cfm) is in a directory that is protected using NTLM security.

In web server authentication, the web server requires the user to log in to access pages in a particular directory, as follows:

  1. When the user first requests a page in the secured directory, the web server notifies the browser that the requested page requires credentials (a user ID and password).

    Basic HTTP authentication sends the user ID and password in a base64-encoded string with each request. Use SSL (Secure Sockets Layer) for all page transactions, to protect the user ID and password from unauthorized access. For more information on SSL and the keytool utility, see About LDAP Server Security.

  2. The browser prompts the user for the credentials.
  3. The user supplies the credentials and the browser send the information back to the web server along with the original request.
  4. The web server checks the user ID and password, using its own user authentication mechanism.
  5. If the user logs in successfully, the browser caches the authentication information and sends it in an HTTP Authorization header with every subsequent page request from the user.
  6. The web server processes the requested page and all future page requests from the browser that contain the HTTP Authorization header, if it is valid for the requested page.

You can use web server authentication without using any ColdFusion security features. In this case, you configure and manage all user security through the web server’s interfaces.

You can also use web server authentication with ColdFusion application authentication, and thus you can use ColdFusion security for authorization. If the web server uses basic HTML authentication, the ColdFusion cflogin tag provides access to the user ID and password that the user entered to log in to the web server. If the web server uses Digest or NTLM authentication, the cflogin tag normally gets the user ID, but not the password.

As a result, your application can rely on the web server to authenticate the user against its user and password information, and does not have to display a login page. You use the cflogin and cfloginuser tags to log the user into the ColdFusion user security system, and use the IsUserInRole and GetAuthUser functions to ensure user authorization. For more information on this form of security, see A web server authentication security scenario.

Note: If a user has logged in using web server authentication and has not logged in using ColdFusion application authentication, the GetAuthUser tag returns the web server user ID. You could use this feature to combine web server authentication with application authorization based on the user’s ID.

About application authentication

With application authentication, you do not rely on the web server to enforce application security. The application performs all user authentication and authorization. The application displays a login page, checks the user’s identity and login against its own authorization store, such as an LDAP directory or database, and logs the user into ColdFusion using the cfloginuser tag. The application can then use the IsUserInRole and GetAuthUser functions to check the user’s roles or identity for authorization before running a ColdFusion page or specific code on a page. For an example of application authentication use, see An application authentication security scenario.

ColdFusion authentication storage and persistence

How ColdFusion application authentication information is maintained by the browser and ColdFusion, and therefore how long it is available, depends on the following:

  • Whether the user’s browser enables cookies
  • Whether the application supports the Session scope for login storage

Note: For detailed information on Session scope, see Configuring and using session variables. Cookie scope contains the cookies that are sent by the browser; for more information on using cookies, see cfcookie in CFML Reference.

Authentication and cookies

Because HTTP is connectionless, a login can last beyond a single web page viewing only if the browser provides a unique identifier that software on the server can use to confirm that the current user is authenticated. Normally, this is done by using memory-only cookies that are automatically destroyed when the user closes all open browser windows. The specific cookies and how they are used depend on whether the application supports the Session scope for login storage.

Note: For information on user logins without cookies, see Using ColdFusion security without cookies.

Using the Session scope

If you do the following, ColdFusion maintains login information in the Session scope instead of the Cookie scope:

  • Enable the Session scope in the ColdFusion MX Administrator and the Application.cfc initialization code or cfapplication tag.
  • Specify loginStorage="Session" in the Application.cfc initialization code or cfapplication tag.

When ColdFusion maintains login information in the Session scope, it stores the authentication details in a Session.cfauthorization variable, and ColdFusion uses the session cookie information to identify the user. Session-based authentication has the following advantages over less persistent login storage:

  • After the user logs in, the user ID and password are not passed between the server and the browser.
  • The login information and the session share a single time-out. There is no need to manually synchronize sessions and logins.
  • If you use server clusters, the Session scope login ID can be available across the cluster. For more information on server clustering, see Configuring and Administering ColdFusion MX.

If you do not enable the Session scope, the authentication information is not kept in a persistent scope. Instead, the detailed login information is put in a memory-only cookie (CFAUTHORIZATION_applicationName) with a base64-encoded string that contains the user name, password, and application name. The client sends this cookie to the web server each time it makes a page request while the user is logged-in. Use SSL for all page transactions to protect the user ID and password from unauthorized access.

Using ColdFusion security without cookies

You can implement a limited-lifetime form of ColdFusion security if the user’s browser does not support cookies. In this case you do not use the cflogin tag, only the cfloginuser tag. It is the only time you should use the cfloginuser tag outside a cflogin tag.

Without browser cookies, the effect of the cfloginuser tag is limited to a single HTTP request. You must provide your own authentication mechanism and call cfloginuser on each page on which you use ColdFusion login identification.


Using ColdFusion security tags and functions

ColdFusion provides the following tags and functions for user security:

Tag or function

Purpose

cflogin

A container for user authentication and login code. The body of the tag runs only if the user is not logged in. When using application-based security, you put code in the body of the cflogin tag to check the user-provided ID and password against a data source, LDAP directory, or other repository of login identification. The body of the tag includes a cfloginuser tag (or a ColdFusion page that contains a cfloginuser tag) to establish the authenticated user’s identity in ColdFusion.

cfloginuser

Identifies (logs in) a user to ColdFusion. Specifies the user’s ID, password, and roles. This tag is typically used inside a cflogin tag.

The cfloginuser tag requires three attributes, name, password, and roles, and does not have a body. The roles attribute is a comma-delimited list of role identifiers to which the logged-in user belongs. All spaces in the list are treated as part of the role names, so you should not follow commas with spaces.

While the user is logged-in to ColdFusion, security functions can access the user ID and role information.

cflogout

Logs out the current user. Removes knowledge of the user ID and roles from the server. If you do not use this tag, the user is automatically logged out as described in Logging out users.

The cflogout tag does not take any attributes, and does not have a body.

cfNTauthenticate

Authenticates a user name and password against the NT domain on which ColdFusion server is running, and optionally retrieves the user’s groups.

cffunction

If you include a roles attribute, the function executes only when there is a logged-in user who belongs to one of the specified roles.

IsUserInRole

Returns True if the current user is a member of the specified role.

GetAuthUser

Returns the ID of the currently logged-in user.

This tag first checks for a login made with cfloginuser tag. If none exists, it checks for a web server login (cgi.remote_user.

This section describes the following topics:

  • Using the cflogin tag
  • Getting the user ID and password
  • Logging out users


Using the cflogin tag

The cflogin tag executes only if there is no currently logged-in user. It has the following three optional arguments that control the characteristics of a ColdFusion login:

Attribute | Use
idleTimeout | If no page requests occur during the idleTimeout period, ColdFusion logs out the user. The default is 1800 seconds (30 minutes). This is ignored if login information is stored in the Session scope.
applicationToken | Limits the login validity to a specific application as specified by a ColdFusion page’s cfapplication tag. The default value is the current application name.
cookieDomain | Specifies the domain of the cookie used to mark a user as logged-in. You use cookieDomain if you have a clustered environment (for example, x.acme.com, x2.acme.com, and so on). This lets the cookie work for all the computers in the cluster.

Login identification scope and the applicationToken attribute

The login identification created by the cflogin tag is valid only for pages within the directory that contains the page that uses the cflogin tag and any of its subdirectories. Therefore, if a user requests a page in another directory tree, the current login credentials are not valid for accessing those pages. This security limitation lets you use the same user names and passwords for different sections of your application (for example, a UserFunctions tree and a SecurityFunctions tree) and enforce different roles to the users depending on the section.

ColdFusion uses the applicationToken value to generate a unique identifier that enforces this rule. The default applicationToken value is the current application name, as specified by a cfapplication tag or Application.cfc unitization code. In normal use, you do not need to specify an applicationToken value in the cflogin tag.

Specifying the Internet domain

Use the cookieDomain attribute to specify the domain of the cookie used to mark a user as logged-in. You use cookieDomain if you have a clustered environment (for example, www.acme.com, www2.acme.com, and so on). This lets the cookie work for all computers in the cluster. For example, to ensure that the cookie works for all servers in the acme.com domain, specify cookieDomain=".acme.com". To specify a domain name, start the name with a period.

Caution: Before setting the cookie domain, consider the other applications or servers in the broader domain might have access to the cookie. For example, a clustered payroll application at payroll1.acme.com, payroll2.acme.com, and so on, might reveal sensitive information to the test computer at test.acme.com, if the cookie domain is broadly set to .acme.com.


Getting the user ID and password

The cflogin tag has a built-in cflogin structure that contains two variables, cflogin.username and cflogin.password, if the page is executing in response to any of the following:

  • Submission of a login form that contains input fields with the names j_username and j_password.
  • A request that uses HTTP Basic authentication and, therefore, includes an Authorization header with the user name and password.
  • A message from the Macromedia Flash Remoting gatewayConnection object that has the setCredentials method set.
  • A request that uses NTLM or Digest authentication. In this case, the user name and password are hashed using a one-way algorithm before they are put in the Authorization header; ColdFusion gets the user name from the web server and sets the cflogin.password value to the empty string.

You use the first three techniques with application authentication, and the last technique with web server authentication. The cflogin structure provides a consistent interface for determining the user’s login ID and password, independent of the technique that you use for displaying the login form.

Caution: Login forms send the user name and password without encryption. Basic HTTP authentication sends the user name and password in a base64-encoded string with each request; this format can easily be converted back to plain text. Use these techniques only with https requests, or when you are not concerned about password security.

The following sections describe how you provide login information to your application for authentication

Using a login form to get user information

When you build an application that gets the User ID and password using a login form, the cflogin tag checks for the existence of a cflogin structure containing the user’s login information. If the structure does not exist, it displays a login form, typically using a cfinclude tag on a login page; the following code shows this use.

In the Application.cfc onRequestStart method, or a ColdFusion page or CFC method called by the method, you have the following:

<cflogin>
    <cfif NOT IsDefined("cflogin")>
        <cfinclude template="loginform.cfm">
    </cfif>
     <cfabort>
     <cfelse>
    <!--- Code to authenticate the user based on the cflogin.user and
        cflogin.password values goes here. --->
    <!--- If User is authenticated, determine any roles and use a line like the
        following to log in the user. --->
        <cfloginuser name="#cflogin.name#" Password = "#cflogin.password#"
            roles="#loginQuery.Roles#">
</cflogin>

A simple login form looks like the following:

<cfform name="loginform" action="#CGI.script_name#?#CGI.query_string#"
        method="Post">
    <table>
       <tr>
            <td>username:</td>
            <td><cfinput type="text" name="j_username" required="yes"
                message="A username is required"></td>
       </tr>
       <tr>
            <td>password:</td>
            <td><cfinput type="password" name="j_password" required="yes"
                message="A password is required"></td>
       </tr>
    </table>
    <br>
    <input type="submit" value="Log In">
</cfform>

Using a browser dialog box to get user information

Application authentication does not require you to use a login form; you can rely on the browser to display its standard login dialog box, instead. To do so, your cflogin tag body returns an HTTP status 401 to the browser if the user is not logged in or if the login fails; that is, if it does not have a valid cflogin structure. The browser displays its login dialog box. When the user clicks the login button on the dialog box, the browser returns the login information as an HTTP Authorization header to ColdFusion, which puts the information in the cflogin tag’s cflogin structure.

This technique has the advantage of simplicity; you do not need a login form and the user gets a familiar-looking login page. You must be careful of security issues, however. The browser sends the user name and password in a base64-encoded string, not just when the user logs in, but with each request. Use SSL (Secure Sockets Layer) for all page transactions to protect the user ID and password from unauthorized access.

Note: You must ensure that your web server is configured correctly to support browser-based login forms for this use. For example, in IIS 5, you must enable anonymous access and might have to disable Basic authentication and Integrated Windows authentication.

The following cflogin tag tells the browser to display a login form if the user has not logged in:

<cflogin>
    <cfif NOT IsDefined("cflogin")>
        <cfheader statuscode="401">
        <cfheader name="www-Authenticate" value="Basic
            realm=""MM Wizard #args.authtype# Authentication""">
    </cfif>
    <cfabort>
    <cfelse>
        <!--- code to authenticate the user based on the cflogin.user and
            cflogin.password values goes here. --->
</cflogin>

Logging in a user using Flash Remoting

If you are developing a Rich Internet Application with Macromedia Flash and Flash Remoting, your ColdFusion application does not need to be coded specially for a Flash login. The Flash Remoting gateway makes the user ID and password available to the cflogin tag in the cflogin structure.

In your Flash code, you use the ActionScript SetCredentials method to send login information to ColdFusion. Your Flash SWF file displays the user ID and password fields, and uses their contents in the setCredentials method, as follows:

if (inited == null)
{
    inited = true;
    NetServices.setDefaultGatewayUrl("http://localhost/flashservices/gateway");
    gatewayConnection = NetServices.createGatewayConnection();
    gatewayConnection.setCredentials(userID, password);
    myService = gatewayConnection.getService("securityTest.thecfc", this);
}

For more information on using Flash Remoting, see Using Flash Remoting MX.


Logging out users

After a user logs in, the ColdFusion user authorization and authentication information remains valid until any of the following happens:

  • The application uses a cflogout tag to log out the user, usually in response to the user clicking a log-out link or button.
  • If your application uses the Session scope for login information, the session ends.
  • If your application does not use the Session scope for login information, the user does not request a new page for the cflogin tag idleTimeout period.
  • If your application does not use Session scope for login information, or if you use J2EE-based session identification, the user closes all browser windows.

Logging a user out by using the cflogout tag does not close the user’s session, but if you use session login storage, it does remove the login information (the Session.cfauthorization variable) from the Session scope. For more information on ending sessions, see Ending a session.

Caution: If you use web server–based authentication or any form authentication that uses a Basic HTTP Authorization header, the browser continues to send the authentication information to your application until the user closes the browser, or in some cases, all open browser windows. As a result, after the user logs out and your application uses the cflogout tag, until the browser closes, the cflogin structure in the cflogin tag will contain the logged-out user’s UserID and password. If a user logs out and does not close the browser, another user might access pages with the first user’s login.


Security scenarios

The following sections provide two detailed security scenarios. The first scenario uses the web server to perform the authentication against its user and password database. The second scenario uses ColdFusion for all authentication and authorization.

A web server authentication security scenario

An application that uses web server authentication might work as follows. The example in Web server–based authentication user security example implements this scenario.

  1. When the user requests a page from a particular directory on the server for the first time after starting the browser, the web server displays a login page and logs in the user. The web server handles all user authentication.
  2. Because the user requested a ColdFusion page, the web server hands the request to ColdFusion.
  3. When ColdFusion receives a request for a ColdFusion page, it instantiates the Application.cfc and runs onRequestStart method. If you use an Application.cfm page in place of the Application.cfc, it runs the contents of the Application.cfm page before it runs the requested page. The onRequestStart method or Application.cfm page contains a cflogin tag. ColdFusion executes the cflogin tag body if the user is not logged into ColdFusion. The user is logged in if the cfloginuser tag has run successfully for this application and the user has not been logged out.
  4. Code in the cflogin tag body uses the user ID and password from the browser login, contained in the cflogin.name and cflogin.password variables, as follows. (With Digest or NTLM web server authentication, the cflogin.password variable is the empty string.)
    1. It checks the user’s name against information it maintains about users and roles. In a simple case, the application might have two roles, one for users and one for administrators. The CFML assigns the Admin role to any user logged on with the user ID Admin and assigns the User role to all other users.
    2. It calls the cfloginuser tag with the user’s ID, password, and roles, to identify the user to ColdFusion.
  5. Application.cfc or the Application.cfm page completes processing, and ColdFusion processes the requested application page.
  6. The application uses the IsUserInRole function to check whether the user belongs to a role before it runs protected code that must be available only to users in that role.
  7. The application can use the GetAuthUser function to determine the user ID; for example, to display the ID for personalization. It can also use the ID as a database key to get user-specific data.

Caution: If you use web server–based authentication or any form authentication that uses a Basic HTTP Authorization header, the browser continues to send the authentication information to your application until the user closes the browser, or in some cases, all open browser windows. As a result, after the user logs out and your application uses the cflogout tag, until the browser closes, the cflogin structure in the cflogin tag will contain the logged-out user’s UserID and password. If a user logs out and does not close the browser, another user might access pages with the first user’s login.

An application authentication security scenario

An application that does its own authentication might work as follows. The example in Application-based user security example implements this scenario.

  1. Whenever ColdFusion receives a request for a ColdFusion page, it instantiates the Application.cfc and runs the onRequestStart method. If you use an Application.cfm page in place of Application.cfc, ColdFusion runs the contents of the Application.cfm page before it runs the requested page. The onRequestStart method or Application.cfm page contains the cflogin tag. ColdFusion executes the cflogin tag body if the user is not logged in. A user is logged in if the cfloginuser tag has run during the current session and the user had not been logged out by a cflogout tag.
  2. Code in the cflogin tag body checks to see if it has received a user ID and password, normally from a login form.
  3. If there is no user ID or password, the code in the cflogin tag body displays a login form that asks for the user’s ID and password.

    The form posts the login information back to the originally requested page, and the cflogin tag in the onRequestStart method or the Application.cfm page runs again. This time, the cflogin tag body code checks the user name and password against a database, LDAP directory, or other policy store, to ensure that the user is valid and get the user’s roles.

  4. If the user name and password are valid, the cflogin tag body code calls the cfloginuser tag with the user’s ID, password, and roles, to identify the user to ColdFusion.
  5. When the user is logged in, application pages use the IsUserInRole function to check whether the user belongs to a role before they run protected code that must be available only to users in that role.

    The application can use the GetAuthUser function to determine the user ID; for example, to display the ID for personalization. It can also use the ID as a database key to get user-specific data.

  6. Each application page displays a link to a logout form that uses the cflogout tag to log out the user. Typically, the logout link is in a page header that appears in all pages. The logout form can also be in the Application.cfc (for example, in the onRequestStart or onRequestEnd method) or on the Application.cfm page.

Although this scenario shows one method for implementing user security, it is only an example. For example, your application could require users to log in for only some pages, such as pages in a folder that contains administrative functions. When you design your user security implementation, remember the following:

  • Code in the cflogin tag body executes only if there is no user logged in.
  • With application authentication, you write the code that gets the identification from the user and tests this information against a secure credential store.
  • After you have authenticated the user, you use the cfloginuser tag to log the user into ColdFusion.

The following figure shows this flow of control. For simplicity, it omits the log-out option.

A six-step authentication scenerio


Implementing user security

The following sections provide several examples of ways to implement security.

  • Using the Dreamweaver Login Wizard
  • Web server–based authentication user security example
  • Application-based user security example
  • Using an LDAP directory for security information


Using the Dreamweaver Login Wizard

ColdFusion MX installs a Login Wizard command in the Dreamweaver Commands menu that generates a skeleton set of pages for managing user authentication and authorization.

The wizard asks you to you select how to authenticate the login information. You can select one of the following options:

  • Simple You specify a single user ID and password in the wizard. All users must enter this information to log in. You can use this option for testing, or you can use the generated files as a template where you can replace the authentication code with more complex code; for example, to verify the ID and password against a database.
  • NT domain You specify an NT domain in the wizard, and the wizard generates code that queries the domain.
  • LDAP You specify the LDAP server and port, the username and password required to access the login data, and the distinguished name to use to start the search for the username. The wizard generates the code to query the LDAP server with the user ID and password.

The wizard asks you to select one of the following options for displaying the request for login information:

  • Browser Dialog Box
  • ColdFusion Login Form


Structure code generated by the Login Wizard

The wizard generates or modifies the following files in the directory or site that you specify:

Application.cfc If this file does not exist, the wizard creates it with a single onRequestStart method; it does not specify an application name or any other methods. If the file exists, but does not have an onRequestStart method, it adds the method. If Application.cfc and the onRequestStart method exist, the wizard inserts the required code at the beginning of the method. The resulting onRequestStart method has a cfinclude tag that specifies mm_wizard_application_include.cfm; it also has a simple form with a logout button, which will display at the top of each page in the application.

Note: If the wizard creates the Application.cfc file, you should, at least, change the file to specify the application name. For more information on Application.cfc, see Designing and Optimizing a ColdFusion Application.

mm_wizard_application_include.cfm The Login Wizard uses the information specified in the wizard fields to set several CFC method arguments. It then uses them to invoke the performlogin method of the master login CFC, mm_wizard.authenticate.

mm_wizard_authenticate.cfc This CFC contains all of the user authentication and login logic. The CFC consists of the following methods:

  • The ntauth, ldapauth, and simpleauth authentication methods check the user’s name and ID against the valid login information, and return information about whether the user is authenticated. For the details of how they authenticate the user and the specific return values, see the methods.
  • The performLogin method is the master login method. It contains the cflogin tag, which displays the login form and calls the required authentication method. If the authentication method’s return argument indicates a valid user, the method logs the user in.
  • The logout method logs a user out. If you specified Browser Dialog Box as the login page type, it also calls the closeBrowser method to close the browser window. This behavior is necessary because the browser continues to send the old login credentials after the user logs out, and the cflogin tag will automatically use them and log the user in again.
  • The closeBrowser method closes the browser window or tells the user to close the browser window to complete the logout, depending on the browser type.

mm_wizard_login.cfm This file contains a ColdFusion MX login form. The wizard generates this file for all options, but does not use it if you specify Browser Dialog login.

index.cfm or mm_wizard_index.cfm The wizard generates an index.cfm page if the directory does not have one; otherwise, creates an mm_wizard_index.cfm page. These pages let you test the generated login code before you implement your application, or without using any of your standard application pages. To test your login, open the index.cfm page in your browser.


Modifying the login code for your application

The Login Wizard creates a basic framework for authenticating a user. You must customize this framework to meet your application’s needs. Typical security-related changes include the following:

  • Providing user-specific role information in the cflogin tag
  • Authenticating users against a database

Providing user-specific role information

The Login Wizard sets all users in a single role. In mm_wizard_authenticate.cfc, the performlogin method is hard-coded to set the role to "user." The authentication routines handle roles differently. (For the details, see the mm_wizard_authenticate.cfc code.) If your application uses roles for authorization, you must change the authentication method to get and return valid role information, and change the performlogin method to use the information in the roles attribute of its cfloginuser tag.

Authenticating users against a database

If you use a database to maintain user IDs and passwords, you can create your login framework by specifying simple authentication, and modify the code to use the database. The following instructions describe a simple way to change the code to use a database. They do not include all the cleanup work (particularly, removing the hard-coded user name and password), that you should do for a well-formatted application.

Replace the following code:

<cfif sUserName eq uUserName AND sPassword eq uPassword>
    <cfset retargs.authenticated="YES">
<cfelse>
    <cfset retargs.authenticated="NO">
</cfif>
<cfreturn retargs>

With code similar to the following:

<cfquery name="loginQuery" dataSource="#Application.DB#" >
    SELECT *
    FROM Users
    WHERE UserName = <cfqueryparam value="#uUserName#" CFSEQLType=
        "CF_SQL_VARCHAR"	AND password = <cfqueryparam value="#uPassword#"
        CFSEQLType="CF_SQL_VARCHAR>"
</cfquery>

<cfif loginQuery.recordcount gt 0>
    <cfset retargs.authenticated="YES">
    <cfset retargs.roles=loginQuery.roles>
<cfelse>
    <cfset retargs.authenticated="NO">
</cfif>
<cfreturn retargs>

Note: For greater security, consider using a hashed password. Do not store the password directly in the database; instead, use the hash function to create a secure password fingerprint, and store it in the database. When the user provides a password, use the Hash function on the submitted string and compare it with the value in the database.

Web server–based authentication user security example

The example in this section shows how you might implement user security using web-server–based basic authentication and two roles, user and administrator.

This example has two ColdFusion pages:

  • The Application.cfc page logs the user into the ColdFusion security system and assigns the user to specific roles based on the user’s ID.

    This page also includes the one-button form and logic for logging out a user, which appears at the top of each page.

  • The securitytest.cfm page is a sample application page. It displays the logged-in user’s roles.

This simple example does not provide a user log-out interface. You can test the security behavior by adding your own pages to the same directory as the Application.cfc page.

This section includes the following examples:

  • Example: Application.cfc
  • Example: securitytest.cfm


Example: Application.cfc

The Application.cfc page consists of the following:

<cfcomponent>
<cfset This.name = "Orders">
<cffunction name="OnRequestStart">
    <cfargument name = "request" required="true"/>
    <cflogin>
        <cfif IsDefined("cflogin")>
            <cfif cflogin.name eq "admin">
                <cfset roles = "user,admin">
            <cfelse>
                <cfset roles = "user">
            </cfif>
            <cfloginuser name = "#cflogin.name#" password = "#cflogin.password#"
                roles = "#roles#" />
        <cfelse>
            <!--- This should never happen. --->
            <h4>Authentication data is missing.</h4>
            Try to reload the page or contact the site administrator.
        <cfabort>
        </cfif>
    </cflogin>
</cffunction>
</cfcomponent>

Reviewing the code

The Application.cfc onRequestStart method executes before the code in each ColdFusion page in an application. For more information on the Application.cfc page and when it is executed, see Designing and Optimizing a ColdFusion Application.

The following table describes the CFML code in Application.cfc and its function:

Code

Description

<cfcomponent>
<cfset This.name = "Orders">
<cffunction name="OnRequestStart">
    <cfargument name = "request"
        required="true"/>

Identifies the application and starts the onRequestStart method that runs at the starts of each request. The login information on this page only applies to this application.

<cflogin>
    <cfif IsDefined("cflogin")>
        <cfif cflogin.name eq "admin">
            <cfset roles = "user,admin">
        <cfelse>
                <cfset roles = "user">
            </cfif>

Executes if there is no logged-in user.

Makes sure the user is correctly logged in by the web server. (Otherwise, there would be no cflogin variable.)

Sets a roles variable based on the user’s ID. Assigns users named "admin" to the admin role. Assigns all other users to the users role.

<cfloginuser name = "#cflogin.name#"
    password = "#cflogin.password#"
    roles = "#roles#" />

Logs the user into the ColdFusion security system and specifies the user’s password, name, and roles. Gets the password and name directly from the cflogin structure.

<cfelse>
    <!--- This should never happen. --->
    <h4>Authentication data is missing.</h4>
        Try to reload the page or contact the
            site administrator.
    <cfabort>

This code should never run, but if the user somehow got to this page without logging in to the web server, this message would display and ColdFusion would stop processing the request.

    </cfif>
</cflogin>
</cffunction>
</cfcomponent>

Ends the if/else block.

Ends the cflogin tag body.

Ends the onRequestStart method.

Ends the Application component.


Example: securitytest.cfm

The securitytest.cfm page shows how any application page can use ColdFusion user authorization features. The web server ensures the existence of an authenticated user, and the Application.cfc page ensures that the user is assigned to roles the page content appears. The securitytest.cfm page uses the IsUserInRole and GetAuthUser functions to control the information that is displayed.

The securitytest.cfm page consists of the following:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>Basic authentication security test page</title>
</head>

<body>
<cfoutput>
    <h2>Welcome #GetAuthUser()#!</h2>
</cfoutput>

ALL Logged-in Users see this message.<br>
<br>
<cfscript>
    if (IsUserInRole("admin"))
        WriteOutput("Users in the admin role see this message.<br><br>");
    if (IsUserInRole("user"))
        WriteOutput("Everyone in the user role sees this message.<br><br>");
</cfscript>

</body>
</html>

Reviewing the code

The following table describes the securitytest.cfm page CFML code and its function:

Code

Description

<cfoutput>
<h2>Welcome #GetAuthUser()#!</h2>
</cfoutput>

User is already logged in by Application.cfc. Displays a welcome message that includes the user’s login ID.

ALL Logged-in Users see this 	message.<br>
<br>

Displays this message in all cases. The page does not display until a user is logged in.

<cfscript>
    if (IsUserInRole("admin"))
        WriteOutput("Users in the admin role
            see this message.<br><br>");
    if (IsUserInRole("user"))
        WriteOutput("Everyone in the user role
            sees this message.<br><br>");
</cfscript>

Tests whether the user belongs to each of the valid roles. If the user is in a role, displays a message with the role name.

The user sees one message per role to which the user belongs.


Application-based user security example

The example in this section shows how you might implement user security by authenticating users and then allowing users to see or use only the resources that they are authorized to access.

This example has three ColdFusion pages:

  • The Application.cfc page contains the authentication logic that checks whether a user is logged in, requests the login page if the user is not logged in, and authenticates the data from the login page. If the user is authenticated, it logs the user in.

    This page also includes the one-button form and logic for logging out a user, which appears at the top of each page.

  • The loginform.cfm page displays the login form. The code on this page could also be included in Application.cfc.
  • The securitytest.cfm page is a sample application page. It displays the logged-in user’s roles.

You can test the security behavior by adding your own pages to the same directory as the Application.cfc page.

The example gets user information from the LoginInfo table of the cfdocexamples database that is installed with ColdFusion. You can replace this database with any database containing UserID, Password, and Roles fields. The sample database contains the following data:

UserID | Password | Roles
BobZ | Ads10 | Employee,Sales
JaniceF | Qwer12 | Contractor,Documentation
RandalQ | ImMe | Employee,Human Resources,Manager

Because spaces are meaningful in roles strings, you should not follow the comma separators in the Roles fields with spaces.

This section includes the following examples:

  • Example: Application.cfc
  • Example: loginform.cfm
  • Example: securitytest.cfm


Example: Application.cfc

The Application.cfc page consists of the following:

<cfcomponent>
<cfset This.name = "Orders">
<cfset This.Sessionmanagement="True">
<cfset This.loginstorage="session">

<cffunction name="OnRequestStart">
    <cfargument name = "request" required="true"/>
    <cfif IsDefined("Form.logout")>
        <cflogout>
    </cfif>

    <cflogin>
        <cfif NOT IsDefined("cflogin")>
            <cfinclude template="loginform.cfm">
            <cfabort>
        <cfelse>
            <cfif cflogin.name IS "" OR cflogin.password IS "">
                <cfoutput>
                    <h2>You must enter text in both the User Name and Password fields.
                    </h2>
                </cfoutput>
                <cfinclude template="loginform.cfm">
                <cfabort>
            <cfelse>
                <cfquery name="loginQuery" dataSource="cfdocexamples">
                SELECT UserID, Roles
                FROM LoginInfo
                WHERE
                    UserID = '#cflogin.name#'
                    AND Password = '#cflogin.password#'
                </cfquery>
                <cfif loginQuery.Roles NEQ "">
                    <cfloginuser name="#cflogin.name#" Password = "#cflogin.password#"
                        roles="#loginQuery.Roles#">
                <cfelse>
                    <cfoutput>
                        <H2>Your login information is not valid.<br>
                        Please Try again</H2>
                    </cfoutput>
                    <cfinclude template="loginform.cfm">
                    <cfabort>
                </cfif>
            </cfif>
        </cfif>
    </cflogin>

    <cfif GetAuthUser() NEQ "">
        <cfoutput>
             <form action="securitytest.cfm" method="Post">
                <input type="submit" Name="Logout" value="Logout">
            </form>
        </cfoutput>
    </cfif>

</cffunction>
</cfcomponent>

Reviewing the code

The Application.cfc page executes before the code in each ColdFusion page in an application. For more information on the Application.cfc page and when it is executed, see Designing and Optimizing a ColdFusion Application.

The following table describes the CFML code in Application.cfc and its function:

Code

Description

<cfcomponent>
<cfset This.name = "Orders">
<cfset This.Sessionmanagement="True">
<cffunction name="OnRequestStart">
    <cfargument name = "request"
        required="true"/>

Identifies the application, enables session management, and enables storing login information in the Session scope.

Begins the definition of the onRequestStart method that runs at the starts of each request.

<cfif IsDefined("Form.logout")>
    <cflogout>
</cfif>

If the user just submitted the logout form, logs out the user. The following cflogin tag runs as a result.

<cflogin>
    <cfif NOT IsDefined("cflogin")>
        <cfinclude template="loginform.cfm">
        <cfabort>

Executes if there is no logged-in user.

Tests to see if the user has submitted a login form. If not, uses cfinclude to display the form. The built-in cflogin variable exists and contains the user name and password only if the login form used j_username and j_password for the input fields.

The cfabort tag prevents processing of any code that follows on this page.

<cfelse>
    <cfif cflogin.name IS "" OR
        cflogin.password IS "">
        <cfoutput>
          <H2>You must enter text in both the
          User Name and Password fields</H2>
        </cfoutput>
        <cfinclude template="loginform.cfm">
        <cfabort>

Executes if the user submitted a login form.

Tests to make sure that both name and password have data. If either variable is empty, displays a message, followed by the login form.

The cfabort tag prevents processing of any code that follows on this page.

<cfelse>
    <cfquery name="loginQuery"
            dataSource="cfdocexamples">
        SELECT UserID, Roles
        FROM LoginInfo
        WHERE
            UserID = '#cflogin.name#'
            AND Password = '#cflogin.password#'
    </cfquery>

Executes if the user submitted a login form and both fields contain data.

Uses the cflogin structure’s name and password entries to find the user record in the database and get the user’s roles.

<cfif loginQuery.Roles NEQ "">
    <cfloginuser name="#cflogin.name#"
        Password = "#cflogin.password#"
        roles="#loginQuery.Roles#">

If the query returns data in the Roles field, logs in the user using the user’s name and password and the Roles field from the database. In this application, every user must be in some role.

<cfelse>
    <cfoutput>
        <H2>Your login information is not
            valid.<br>
        Please Try again</H2>
    </cfoutput>
    <cfinclude template="loginform.cfm">
    <cfabort>

Executes if the query did not return a role. If the database is valid, this means there was no entry matching the user ID and password. Displays a message, followed by the login form.

The cfabort tag prevents processing of any code that follows on this page.

            </cfif>
        </cfif>
    </cfif>
</cflogin>

Ends the loginquery.Roles test code.

Ends the form entry empty value test.

Ends the form entry existence test.

Ends the cflogin tag body.

<cfif GetAuthUser() NEQ "">
    <cfoutput>
        <form action="MyApp/index.cfm"
                method="Post">
            <input type="submit" Name="Logout"
                value="Logout">
        </form>
    </cfoutput>
</cfif>

If a user is logged-in, displays the Logout button.

If the user clicks the button, posts the form to the application’s (theoretical) entry page, index.cfm.

Application.cfc then logs out the user and displays the login form. If the user logs in again, ColdFusion displays index.cfm.

</cffunction>
</cfcomponent>

Ends the onRequestStart method

Ends the Application component.


Example: loginform.cfm

The loginform.cfm page consists of the following:

<H2>Please Log In</H2>
<cfoutput>
    <form action="#CGI.script_name#?#CGI.query_string#" method="Post">
        <table>
            <tr>
                <td>username:</td>
                <td><input type="text" name="j_username"></td>
            </tr>
            <tr>
                <td>password:</td>
                <td><input type="password" name="j_password"></td>
            </tr>
        </table>
        <br>
        <input type="submit" value="Log In">
    </form>
</cfoutput>

Reviewing the code

The following table describes the loginform.cfm page CFML code and its function:

Code

Description

<H2>Please Log In</H2>
<cfoutput>
    <form
action="#CGI.script_name#?#CGI.
query_string#"
method="Post">
        <table>
            <tr>
                <td>username:</td>
                <td><input type="text"
                    name="j_username"></td>
            </tr>
            <tr>
                <td>password:</td>
                <td><input type="password"
                    name="j_password"></td>
            </tr>
        </table>
        <br>
        <input type="submit" value="Login">
    </form>
</cfoutput>

Displays the login form.

Constructs the form action attribute from CGI variables, with a ? character preceding the query string variable. This technique works because loginform.cfm is accessed by a cfinclude tag on Application.cfc, so the CGI variables are those for the originally requested page.

The form requests a user ID and password and posts the user’s input to the page specified by the newurl variable.

Uses the field names j_username and j_password. ColdFusion automatically puts form fields with these values in the cflogin.name and cflogin.password variables inside the cflogin tag.


Example: securitytest.cfm

The securitytest.cfm page shows how any application page can use ColdFusion user authorization features. Application.cfc ensures the existence of an authenticated user before the page content appears. The securitytest.cfm page uses the IsUserInRole and GetAuthUser functions to control the information that is displayed.

The securitytest.cfm page consists of the following:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>Security test page</title>
</head>

<body>
<cfoutput>
    <h2>Welcome #GetAuthUser()#!</h2>
</cfoutput>

ALL Logged-in Users see this message.<br>
<br>
<cfscript>
    if (IsUserInRole("Human Resources"))
        WriteOutput("Human Resources members see this message.<br><br>");
    if (IsUserInRole("Documentation"))
        WriteOutput("Documentation members see this message.<br><br>");
    if (IsUserInRole("Sales"))
        WriteOutput("Sales members see this message.<br><br>");
    if (IsUserInRole("Manager"))
        WriteOutput("Managers see this message.<br><br>");
    if (IsUserInRole("Employee"))
        WriteOutput("Employees see this message.<br><br>");
    if (IsUserInRole("Contractor"))
        WriteOutput("Contractors see this message.<br><br>");
</cfscript>

</body>
</html>

Reviewing the code

The following table describes the securitytest.cfm page CFML code and its function:

Code

Description

<cfoutput>
<h2>Welcome #GetAuthUser()#!</h2>
</cfoutput>

Displays a welcome message that includes the user’s login ID.

ALL Logged-in Users see this 	message.<br>
<br>

Displays this message in all cases. The page does not display until a user is logged in.

<cfscript>
    if (IsUserInRole("Human Resources"))
        WriteOutput("Human Resources members
        see this message.<br><br>");
    if (IsUserInRole("Documentation"))
        WriteOutput("Documentation members see
        this message.<br><br>");
    if (IsUserInRole("Sales"))
        WriteOutput("Sales members see this
        message.<br><br>");
    if (IsUserInRole("Manager"))
        WriteOutput("Managers see this
        message.<br><br>");
    if (IsUserInRole("Employee"))
        WriteOutput("Employees see this
        message.<br><br>");
    if (IsUserInRole("Contractor"))
        WriteOutput("Contractors see this
        message.<br><br>");
</cfscript>

Tests whether the user belongs to each of the valid roles. If the user is in a role, displays a message with the role name.

The user sees one message per role to which he or she belongs.


Using an LDAP directory for security information

LDAP directories are often used to store security information. The following example of a cflogin tag checks an LDAP directory to authenticate the user and retrieve the user’s roles.

For more information on using LDAP directories with ColdFusion, see Managing LDAP Directories.

<cfapplication name="Orders" sessionmanagement="Yes" loginstorage="Session">
<cflogin>
    <cfif isDefined("cflogin")>
        <!--- setting basic attributes --->
        <cfset LDAP_root = "o=mycompany.com">
        <cfset LDAP_server = "ldap.mycompany.com">
        <cfset LDAP_port = "389">

        <!--- Create the prefix and suffix parts of the user's DN. --->
        <cfset userPrefix = "cn=">
        <cfset userSuffix = ",ou=Users,o=mycompany.com">

        <!--- Concatenate the user's DN and use it to authenticate. --->
        <cfset LDAP_username = userPrefix&cflogin.name&userSuffix>

        <!--- This filter will look for groups for containing the user's ID. --->
        <cfset userfilter =
            "(&(objectClass=groupOfUniqueNames)(uniqueMember=#LDAP_username#))">

        <!--- Search for groups containing the user's dn.
            The groups represent the user's roles.
            NOTE: Your LDAP permissions must allow authenticated users to search.
            groups. --->
        <cftry>
            <cfldap action="QUERY"
                name="auth"
                attributes="cn"
                referral="yes"
                start="#LDAP_root#"
                scope="SUBTREE"
                server="#LDAP_server#"
                port="#LDAP_port#"
                filter="#userfilter#"
                username="#LDAP_username#"
                password="#cflogin.password#"
            >
             <cfcatch type="any">
                <cfif FindNoCase("Invalid credentials", cfcatch.detail)>
                    <cfoutput>
                        <script>alert("User ID or Password invalid for user:
                            #cflogin.name#")</script>
                    </cfoutput>
                    <cfabort>
                <cfelse>
                    <cfoutput>
                        <script>alert("Unknown error for user: #cflogin.name#
                            #cfcatch.detail#")</script>
                    </cfoutput>
                    <cfabort>
                </cfif>
            </cfcatch>
        </cftry>

<!--- If the LDAP query returned a record, the user is valid. --->
        <cfif auth.recordcount>
            <cfloginuser name="#cflogin.name#" password="#cflogin.password#"
                roles="#valueList(auth.cn)#">
        </cfif>
    </cfif>
</cflogin>

Reviewing the code

The following table describes the code and its function. Comments and some tab characters have been removed for brevity.

Code

Description

<cflogin>
    <cfif isDefined("cflogin")>
        <!--- setting basic attributes --->
        <cfset LDAP_root = "o=mycompany.com">
        <cfset LDAP_server =
            "ldap.mycompany.com">
        <cfset LDAP_port = "389">

        <cfset userPrefix = "cn=">
        <cfset userSuffix =
            ",ou=Users,o=mycompany.com">

        <cfset LDAP_username =
            userPrefix&cflogin.name&userSuffix>

        <cfset userfilter =
            "(&(objectClass=groupOfUniqueNames)
            (uniqueMember=#LDAP_username#))">

Starts the cflogin tag body. Sets several variables to the values used as attributes in the cfldap tag.

Sets prefix and suffix values used to create a distinquished name (dn) for binding to the LDAP server.

Creates the user’s bind dn by concatenating the prefix and suffix with cflogin.name. This variable is used for authenticating the user to the LDAP server.

Sets the filter used to search the directory and retrieve the user’s group memberships. The group membership represents the user’s roles within the organization.

<cftry>
    <cfldap action="QUERY"
        name="auth"
        attributes="cn"
        referral="yes"
        start="#LDAP_root#"
        scope="SUBTREE"
        server="#LDAP_server#"
        port="#LDAP_port#"
        filter="#userfilter#"
        username="#LDAP_username#"
        password="#cflogin.password#"
    >

In a cftry block, uses the user’s concatenated dn to authenticate to the LDAP server and retrieve the common name (cn) attribute for groups to which the user is a member. If the authentication fails the LDAP server returns an error.

Note: The LDAP permissions must allow an authenticated user to read and search groups in order for the query to return results.

<cfcatch type="any">
    <cfif FindNoCase("Invalid credentials",
            cfcatch.detail)>
        <cfoutput>
            <script>alert("User ID or Password
                invalid for user:
                #cflogin.name#")</script>
        </cfoutput>
        <cfabort>
    <cfelse>
        <cfoutput>
        <script>alert("Unknown error for user:
            #cflogin.name#
            #cfcatch.detail#")</script>
        </cfoutput>
        <cfabort>
    </cfif>
</cfcatch>
</cftry>

Catches any exceptions.

Tests to see if the error information includes the string "invalid credentials", which indicates that either the dn or password is invalid. If so, displays a dialog box with an error message indicating the problem.

Otherwise, displays a general error message.

If an error is caught, the cfabort tag ends processing of the request after displaying the error description.

End of cfcatch and cftry blocks.

<cfif auth.recordcount>
    <cfloginuser name="#cflogin.name#"
        password="#cflogin.password#"
        roles="#valueList(auth.cn)#">
</cfif>
</cfif>
</cflogin>

If the authorization query returns a valid record, logs in the user. Uses the valueList function to create a comma-separated list of the users retrieved group memberships, and passes them in the cfloginuser roles attribute.

Ends the initial isDefined("cflogin") cfif block .

Ends the cflogin tag body

Previous


Developing Globalized Applications

Macromedia ColdFusion MX lets you develop dynamic applications for the Internet. Many ColdFusion applications are accessed by users from different countries and geographical areas. One design detail that you must consider is the globalization of your application so that you can best serve customers in different areas.

This chapter contains information that you can use to develop applications that can be accessible to many different users.

Contents

Introduction to globalization

About character encodings

Locales

Processing a request in ColdFusion

Tags and functions for globalizing

Handling data in ColdFusion MX
Next


Introduction to globalization

Globalization lets you create applications for all of your customers in all the languages that you support. In some cases, globalization can let you accept data input using a different character set than the one you used to implement your application. For example, you can create a website in English that lets customers submit form data in Japanese. Or, you can allow a request URL to contain parameter values entered in Korean.

Your application also can process data containing numeric values, dates, currencies, and times. Each of these types of data can be formatted differently for different countries and regions.

You can also develop applications in languages other than English. For example, you can develop your application in Japanese so that the default character encoding is Shift-JIS, your ColdFusion pages contain Japanese characters, and your interface displays in Japanese.

Globalizing your application requires that you perform one or more of the following actions:

  • Accept input in more than one language.
  • Process dates, times, currencies, and numbers formatted for multiple locales.
  • Process data from a form, database, HTTP connection, e-mail message, or other input formatted in multiple character sets.
  • Create ColdFusion pages containing text in languages other than English.

This section describes the following topics:

  • Defining globalization
  • Importance of globalization in ColdFusion applications
  • How ColdFusion MX supports globalization
  • Character sets, character encodings, and locales


Defining globalization

You will probably find several different definitions for globalization. For this chapter, globalization is defined as an architectural process where you put as much application functionality as possible into a foundation that can be shared among multiple languages.

Globalization is composed of the following two parts:

Internationalization Developing language-neutral application functionality that can recognize, process, and respond to data regardless of its representation. That is, whatever the application can do in one language, it can also do in another. For example, think of copying and pasting text. A copy and paste operation should not be concerned with the language of the text it operates on. For a ColdFusion application, you might have processing logic that performs numeric calculations, queries a database, or performs other operations, independent of language.

Localization Taking shared, language-neutral functionality, and applying a locale-specific interface to it. Sometimes this interface is referred to as a skin. For example, you can develop a set of menus, buttons, and dialog boxes for a specific language, such as Japanese, that represents the language-specific interface. You then combine this interface with the language-neutral functionality of the underlying application. As part of localization, you create the functionality to handle input from customers in a language-specific manner and respond with appropriate responses for that language.


Importance of globalization in ColdFusion applications

The Internet has no country boundaries. Customers can access websites from anywhere in the world, at any time, or on any date. Unless you want to lock your customers into using a single language, such as English, to access your site, you should consider globalization issues.

One reason to globalize your applications is to avoid errors and confusion for your customers. For example, a date in the form 1/2/2003 is interpreted as January 2, 2003 in the United States, but as February 1, 2003 in European countries.

Another reason to globalize your applications is to display currencies in the correct format. Think of how your customers would feel when they find out the correct price for an item is 15,000 American dollars, not 15,000 Mexican pesos (about 1600 American dollars).

Your website can also accept customer feedback or some other form of text input. You might want to support that feedback in multiple languages using a variety of character sets.


How ColdFusion MX supports globalization

ColdFusion MX is implemented in Java. As a Java application, ColdFusion MX uses Java globalization features. For example, ColdFusion MX stores all strings internally using the Unicode character set. Because it uses Unicode, ColdFusion can represent any text data from any language.

In addition, ColdFusion MX includes many tags and functions designed to support globalizing your applications. You can use these tags and functions to set locales, convert date and currency formats, control the output encoding of ColdFusion pages, and perform other actions.


Character sets, character encodings, and locales

When you discuss globalization issues, two topics that you must consider are the character sets or character encodings recognized by the application and the locales for which the application must format data.

A character set is a collection of characters. For example, the Latin alphabet is the character set that you use to write English, and it includes all of the lower- and upper-case letters from A to Z. A character set for French includes the character set used by English, plus special characters such as "é," "à," and "ç."

The Japanese language uses three alphabets: Hiragana, Katakana, and Kanji. Hiragana and Katakana are phonetic alphabets that each contain 46 characters plus two accents. Kanji contains Chinese ideographs adapted to the Japanese language. The Japanese language uses a much larger character set than English because Japanese supports more than 10,000 different characters.

In order for a ColdFusion application to process text, the application must recognize the character set used by the text. The character encoding maps between a character set definition and the digital codes used to represent the data.

In general use, the terms character set (or charset) and character encoding are often used interchangeably, and most often a specific character encoding encodes one character set. However, this is not always true; for example, there are multiple encodings of the Unicode character set. For more information on character encodings, see About character encodings.

Note: ColdFusion uses the term charset to indicate character encoding in some attribute names, structure field keys, and function parameter names.

A locale identifies the exact language and cultural settings for a user. The locale controls how dates and currencies are formatted, how to display time, and how to display numeric data. For example, the locale English (US) determines that a currency value displays as:

$100,000.00

while a locale of Portuguese (Brazilian) displays the currency as:

R$ 100.000

In order to correctly display date, time, currency, and numeric data to your customers, you must know the customer’s locale. For more information on locales, see Locales.


About character encodings

A character encoding maps each character in a character set to a numeric value that can be represented by a computer. These numbers can be represented by a single byte or multiple bytes. For example, the ASCII encoding uses seven bits to represent the Latin alphabet, punctuation, and control characters.

You use Japanese encodings, such as Shift-JIS, EUC-JP, and ISO-2022-JP, to represent Japanese text. These encodings can vary slightly, but they include a common set of approximately 10,000 characters used in Japanese.

The following terms apply to character encodings:

SBCS Single-byte character set; a character set encoded in one byte per character, such as ASCII or ISO 8859-1.

DBCS Double-byte character set; a method of encoding a character set in no more than two bytes, such as Shift-JIS. Many character encoding schemes that are referred to as double-byte, including Shift-JIS, allow mixing of single-byte and double-byte encoded characters. Others, such as UCS-2, use two bytes for all characters.

MBCS Multiple-byte character set; a character set encoded with a variable number of bytes per character, such as UTF-8.

The following table lists some common character encodings; however, there are many additional character encodings that browsers and web servers support:

Encoding | Type | Description
ASCII | SBCS | 7-bit encoding used by English and Indonesian Bahasa languages
Latin-1 (ISO 8859-1) | SBCS | 8-bit encoding used for many Western European languages
Shift_JIS | DBCS | 16-bit Japanese encoding Note: You must use an underscore character (_), not a hyphen (-) in the name in CFML attributes.
EUC-KR | DBCS | 16-bit Korean encoding
UCS-2 | DBCS | Two-byte Unicode encoding
UTF-8 | MBCS | Multibyte Unicode encoding. ASCII is 7-bit; non-ASCII characters used in European and many Middle Eastern languages are two-byte; and most Asian characters are three-byte

The World Wide Web Consortium maintains a list of all character encodings supported by the Internet. You can find this information at www.w3.org/International/O-charset.html.

Computers often must convert between character encodings. In particular, the character encodings most commonly used on the Internet are not used by Java or Windows. Character sets used on the Internet are typically single-byte or multiple-byte (including DBCS character sets that allow single-byte characters). These character sets are most efficient for transmitting data, because each character takes up the minimum necessary number of bytes. Currently, Latin characters are most frequently used on the web, and most character encodings used on the web represent those characters in a single byte.

Computers, however, process data most efficiently if each character occupies the same number of bytes. Therefore, Windows and Java both use double-byte encoding for internal processing.

The Java Unicode character encoding

ColdFusion MX uses the Java Unicode Standard for representing character data internally. This standard corresponds to UCS-2 encoding of the Unicode character set. The Unicode character set can represent many languages, including all major European and Asian character sets. Therefore, ColdFusion MX can receive, store, process, and present text from all languages supported by Unicode.

The Java Virtual Machine (JVM) that is used to processes ColdFusion pages converts between the character encoding used on a ColdFusion page or other source of information to UCS-2. The page or data encodings that ColdFusion supports depend on the specific JVM, but include most encodings used on the web. Similarly, the JVM converts between its internal UCS-2 representation and the character encoding used to send the response to the client.

By default, ColdFusion MX uses UTF-8 to represent text data sent to a browser. UTF-8 represents the Unicode character set using a variable-length encoding. ASCII characters are sent using a single byte. Most European and Middle Eastern characters are sent as two bytes, and Japanese, Korean, and Chinese characters are sent as three bytes. One advantage of UTF-8 is that it sends ASCII character set data in a form that can be recognized by systems designed to process only single-byte ASCII characters, while it is flexible enough to handle multiple-byte character representations.

While the default format of text data returned by ColdFusion is UTF-8, you can have ColdFusion return a page to any character set supported by Java. For example, you can return text using the Japanese language Shift-JIS character set. Similarly, ColdFusion can handle data that is in many different character sets. For more information, see Determining the page encoding of server output.

Character encoding conversion issues

Because different character encodings support different character sets, you can encounter errors if your application gets text in one encoding and presents it in another encoding. For example, the Windows Latin-1 character encoding, Windows-1252, includes characters with hexadecimal representations in the range 80-9F, while ISO 8859-1 does not include characters in that range. As a result, under the following circumstances, characters in the range 80-9F, such as the euro symbol (Ä), are not displayed properly:

  • A file encoded in Windows-1252 includes characters in the range 80-9F.
  • ColdFusion reads the file, specifying the Windows-1252 encoding in the cffile tag.
  • ColdFusion displays the file contents, specifying ISO-8859 in the cfcontent tag.

Similar issues can arise if you convert between other character encodings; for example, if you read files encoded in the Japanese Windows default encoding and display them using Shift-JIS. To prevent these problems, ensure that the display encoding is the same as the input encoding.


Locales

A locale identifies the exact language and cultural settings to use for a user. The locale controls how to format the following:

  • Dates
  • Times
  • Numbers
  • Currency amounts

ColdFusion MX supports all locales supported by the JVM that it uses.

Note: Current JVM versions (through 1.4.2) do not support localized numbers such as Arabic-hindic numbers used in Arabic locales or hindic digits used in Hindi locales. ColdFusion uses Arabic numbers in all locales.

Locale names

ColdFusion MX 7 supports two formats for specifying locale names: the standard Java locale names and the ColdFusion naming convention that was required through ColdFusion MX 6.1.

  • You can specify all locales using a name consisting of the following:
    • Two lowercase letters to identify the language; for example, en for English, or zh for Chinese.
    • Optionally, an underscore and a two uppercase letters to identify the regional variant of the language; for example, US for the United States, or HK for Hong Kong.

    For example, en_US represents United States English and es_MX represents Mexican Spanish. For a list of the Java locale identifiers supported in the Sun 1.4.2 JVM and their meanings, see http://java.sun.com/j2se/1.4.2/docs/guide/intl/locale.doc.html.

  • Prior to ColdFusion MX 7, ColdFusion supported a limited set of locales, and used identifiers that consisted of the name of the language, followed, for most languages, by a regional identifier in parentheses, such as English (US) or German (Standard). ColdFusion MX continues to support these names; for a list, see SetLocale in CFML Reference.

The Server.coldfusion.supportedlocales variable is a comma-delimited list of the locale names that you can specify.

ColdFusion also includes a GetLocaleDisplayName function that returns a locale name in a format that is meaningful to users. It lets you display the locale using words in the user’s language; for example, français (France).

Determining the locale

ColdFusion MX 7 determines the locale value as follows:

  • By default, ColdFusion uses the JVM locale, and the default JVM locale is the operating system locale. You can set the JVM locale value explicitly in ColdFusion MX 7 in the JVM Arguments field on the Java and JVM Settings page in the ColdFusion MX Administrator; for example:
    -Duser.language=de -Duser.region=DE.
  • A locale set using the SetLocale function persists for the current request or until it is reset by another SetLocale function in the request.
  • If a request has multiple SetLocale functions, the current locale setting affects how locale-sensitive ColdFusion tags and functions (such as the functions that start with LS) format data. The last SetLocale function that ColdFusion processes before sending a response to the requestor (typically the client browser) determines the value of the response Content-Language HTTP header. The browser that requested the page displays the response according to the rules for the language specified by the Content-Language header.
  • ColdFusion ignores any SetLocale functions that follow a cfflush tag.

Using the locale

The SetLocale function determines the default formats that ColdFusion uses to output date, time, number, and currency values. You use the GetLocale function to determine the current locale setting of ColdFusion, or you can use the GetLocaleDisplayName function to get the locale name in a format that is meaningful to users. If you have not made a call to SetLocale, GetLocale returns the locale of the JVM.

The current locale has two effects:

  • When ColdFusion formats date, time, currency, or numeric output, it determines how to format the output. You can change the locale multiple times on a ColdFusion page to format information according to different locale conventions. This enables you to output a page that properly formats different currency values, for example.
  • When ColdFusion returns a page to the client, it includes the HTTP Content-Language header. ColdFusion uses the last locale setting on the page for this information.

Note: In earlier versions of ColdFusion, the default locale was always English, not the operating system’s locale. For the Japanese version of ColdFusion, the default was Japanese.

The following example uses the LSCurrencyFormat function to output the value 100,000 in monetary units for all the ColdFusion-supported locales. You can run this code to see how the locale affects the data returned to a browser.

<p>LSCurrencyFormat returns a currency value using the locale convention.
<!--- loop through list of locales; show currency values for 100,000 units --->
<cfloop LIST = "#Server.Coldfusion.SupportedLocales#"
index = "locale" delimiters = ",">
<cfset oldlocale = SetLocale(locale)>
    <cfoutput><p><b><I>#locale#</I></b><br>
        Local: #LSCurrencyFormat(100000, "local")#<br>
        International: #LSCurrencyFormat(100000, "international")#<br>
        None: #LSCurrencyFormat(100000, "none")#<br>
        <hr noshade>
    </cfoutput>
</cfloop>

This example uses the ColdFusion variable Server.Coldfusion.SupportedLocales, which contains a list of all supported ColdFusion locales.


Processing a request in ColdFusion

When ColdFusion receives an HTTP request for a ColdFusion page, ColdFusion resolves the request URL to a physical file path and reads the file contents to parse it. A ColdFusion page can be encoded in any character encoding supported by the JVM used by ColdFusion, but might need to be specified so that ColdFusion can identify it.

The following figure shows an example of a client making a request to ColdFusion:

Client making a request to ColdFusion

The content of the ColdFusion page on the server can be static data (typically HTML and plain text not processed by ColdFusion), and dynamic content written in CFML. Static content is written directly to the response to the browser, and dynamic content is processed by ColdFusion.

The default language of a website might be different from that of the person connecting to it. For example, you could connect to an English website from a French computer. When ColdFusion generates a response, the response must be formatted in the way expected by the customer. This includes both the character set of the response and the locale.

The following sections describe how ColdFusion determines the character set of the files that it processes, and how it determines the character set and locale of its response to the client.

  • Determining the character encoding of a ColdFusion page
  • Determining the page encoding of server output


Determining the character encoding of a ColdFusion page

When a request for a ColdFusion page occurs, ColdFusion opens the page, processes the content, and returns the results back to the browser of the requestor. In order to process the ColdFusion page, though, ColdFusion has to interpret the page content.

One piece of information used by ColdFusion is the Byte Order Mark (BOM) in a ColdFusion page. The BOM is a special character at the beginning of a text stream that specifies the order of bytes in multibyte characters used by the page. The following table lists the common BOM values:

Encoding | BOM signature
UTF-8 | EF BB BF
UTF-16 Big Endian | FE FF
UTF-16 Little Endian | FF FE

To insert a BOM character in a CFML page easily, your editor must support BOM characters. Many web page development tools support insertion of these characters, including Macromedia Dreamweaver MX, which automatically sets the BOM based on the Page Properties Document Encoding selection.

If your page does not contain a BOM, you can use the cfprocessingdirective tag to set the character encoding of the page. If you insert the cfprocessingdirective tag on a page that has a BOM, the information specified by the cfprocessingdirective tag must be the same as for the BOM; otherwise, ColdFusion issues an error.

The following procedure describes how ColdFusion recognizes the encoding format of a ColdFusion page.

To determine the page encoding (performed by ColdFusion):

  1. Use the BOM, if specified on the page.

    Macromedia recommends that you use BOM characters in your files.

  2. Use the pageEncoding attribute of the cfprocessingdirective tag, if specified. For detailed information on how to use this attribute, see the cfprocessingdirective tag in CFML Reference.
  3. Default to the JVM default file character encoding. By default, this is the operating system default character encoding. To specify the JVM default file character encoding, use the
    -Dfile.encoding= switch in the JVM Arguments field of the ColdFusion MX Administrator Java and JVM Settings page.


Determining the page encoding of server output

Before ColdFusion can return a response to the client, it must determine the encoding to use for the data in the response. By default, ColdFusion returns character data using the Unicode UTF-8 format.

ColdFusion pages (.cfm pages) default to using the Unicode UTF-8 format for the response, even if you include the HTML meta tag in the page. Therefore, the following example will not modify the character set of the response:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
           "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html;
charset="Shift_JIS">
</head>
...

In this example, the response will still use the UTF-8 character set. Use the cfcontent tag to set the output character set.

However, within a ColdFusion page you can use the cfcontent tag to override the default character encoding of the response. Use the type attribute of the cfcontent tag to specify the MIME type of the page output, including the character set, as follows:

<cfcontent type="text/html charset=EUC-JP">

Note: ColdFusion MX also provides attributes that let you specify the encoding of specific elements, such as HTTP requests, request headers, files, and mail messages. For more information, see Tags and functions for controlling character encoding and Handling data in ColdFusion MX.

The rest of this chapter describes ColdFusion tags and functions that you use for globalization, and discusses specific globalization issues.


Tags and functions for globalizing

ColdFusion MX supplies many tags and functions that you can use to develop globalized applications.

Tags and functions for controlling character encoding

The following tags and functions let you specify the character encoding of text that ColdFusion generates and interprets:

Tag or function | Attribute or parameter | Use
cfprocessingdirective | pageencoding | Specifies the encoding of a ColdFusion page so ColdFusion can parse it. For more information, see Determining the character encoding of a ColdFusion page.
cfcontent | type | Specifies the encoding in which to return the results to the client browser. For more information, see Determining the page encoding of server output.
cffile | charset | Specifies how to encode data written to a file, or the encoding of a file being read. For more information, see File data.
cfheader | charset | Specifies the character encoding in which to encode the HTTP header value.
cfhttp | charset | Specifies the character encoding of the HTTP request.
cfhttpparam | mimeType | Specifies the MIME media type of a file; can positionally include the file’s character encoding.
cfmail | charset | Specifies the character encoding of the mail message, including the headers.
cfmailpart | charset | Specifies the character encoding of one part of a multipart mail message.
cfprocessingdirective | pageEncoding | Identifies the character encoding of the contents of a page to be processed by ColdFusion MX..
CharsetDecode | encoding | Converts a string in the specified encoding to a binary object.
CharsetEncode | encoding | Converts a binary object to a string in the specified encoding.
GetEncoding |  | Returns the character encoding of text in the Form or URL scope.
SetEncoding | charset | Specifies the character encoding of text in the Form or URL scope. Used when the character set of the input to a form, or the character set of a URL, is not in UTF-8 encoding.
ToBase64 | encoding | Specifies the character encoding of the string being converted to Base 64.
ToString | encoding | Returns a string encoded in the specified character encoding.
URLDecode | charset | Specifies the character encoding of the URL being decoded.
URLEncodedFormat | charset | Specifies the character encoding to use for the URL.

Functions for controlling and using locales

ColdFusion MX provides the following functions that let you specify and identify the locale and format text based on the locale:

Tag or function | Use
GetLocale | Returns the current locale setting.
GetLocaleDisplayName | Returns the name of a locale in the language of a specific locale. The default value is the current locale in the locale’s language..
LSCurrencyFormat | Converts numbers into a string in a locale-specific currency format. For countries that use the euro, the result depends on the JVM version.
LSDateFormat | Converts the date part of a date/time value into a string in a locale-specific date format.
LSEuroCurrencyFormat | Converts a number into a string in a locale-specific currency format. Formats using the euro for all countries that use euro as the currency.
LSIsCurrency | Determines whether a string is a valid representation of a currency amount in the current locale.
LSIsDate | Determines whether a string is a valid representation of a date/time value in the current locale.
LSIsNumeric | Determines whether a string is a valid representation of a number in the current locale.
LSNumberFormat | Converts a number into a string in a locale-specific numeric format.
LSParseCurrency | Converts a string that is a currency amount in the current locale into a formatted number. For countries that use the euro, the result depends on the JVM version.
LSParseDateTime | Converts a string that is a valid date/time representation in the current locale into a date-time object.
LSParseEuroCurrency | Converts a string that is a currency amount in the current locale into a formatted number. Requires euro as the currency for all countries that use the euro.
LSParseNumber | Converts a string that is a valid numeric representation in the current locale into a formatted number.
LSTimeFormat | Converts the time part of a date/time value into a string in a locale-specific date format.
SetLocale | Specifies the locale setting.

Note: Many functions that have names starting with LS have corresponding functions that do not have this prefix: DateFormat, IsDate, IsNumeric, NumberFormat, ParseDateTime, and TimeFormat. These function use English (US) locale rules.

If you do not precede calls to the LS functions with a call to the SetLocale function, they use the locale defined by the JVM, which typically is the locale of the operating system.

The following example uses the LSDateFormat function to display the current date in the format for each locale supported by ColdFusion MX:

<!--- This example shows LSDateFormat --->
<html>
<head>
<title>LSDateFormat Example</title>
</head>
<body>
<h3>LSDateFormat Example</h3>
<p>Format the date part of a date/time value using the locale convention.
<!--- loop through a list of locales; show date values for Now()--->
<cfloop list = "#Server.Coldfusion.SupportedLocales#"
    index = "locale" delimiters = ",">
    <cfset oldlocale = SetLocale(locale)>

    <cfoutput><p><B><I>#locale#</I></B><br>
        #LSDateFormat(Now(), "mmm-dd-yyyy")#<br>
        #LSDateFormat(Now(), "mmmm d, yyyy")#<br>
        #LSDateFormat(Now(), "mm/dd/yyyy")#<br>
        #LSDateFormat(Now(), "d-mmm-yyyy")#<br>
        #LSDateFormat(Now(), "ddd, mmmm dd, yyyy")#<br>
        #LSDateFormat(Now(), "d/m/yy")#<br>
        #LSDateFormat(Now())#<br>
        <hr noshade>
    </cfoutput>
</cfloop>
</body>
</html>

Additional globalization tags and functions

In addition to the tags and functions that are specifically for globalized applications, you might find the following useful when writing a globalized application:

  • All string manipulation functions. For more information, see the String functions list in ColdFusion Functions in CFML Reference.
  • The GetTimeZoneInfo function, which returns the time zone of the operating system.


Handling data in ColdFusion MX

Many of the issues involved with globalizing applications deal with processing data from the various sources supported by ColdFusion MX, including the following:

  • General character encoding issues
  • Locale-specific content
  • Input data from URLs and HTML forms
  • File data
  • Databases
  • E-mail
  • HTTP
  • LDAP
  • WDDX
  • COM
  • CORBA
  • Searching and indexing

This section describes how to handle data from each of these sources.

General character encoding issues

Applications developed for earlier versions of ColdFusion that assumed that the character length of a string was the same as the byte length might produce errors in ColdFusion MX. The byte length of a string depends on the character encoding.

Locale-specific content

The following sections provide information on how to handle locale-specific content in pages that support multiple locales, and how to handle euro values.

Generating multi-locale content

In an application that supports users in multiple locales and produces output that is specific to multiple locales, you call the SetLocale function in every request to set the locale for that specific request. When processing has completed, the locale should be set back to its previous value. One useful technique is to save the user’s desired locale in a Session variable once the user has selected it, and use the Session variable value to set the locale for each user request during the session.

Supporting the euro

The euro is the currency of many European countries, and ColdFusion supports the reading and writing of correctly formatted euro values. Unlike other supported currencies, the euro is not tied to any single country (or locale). The LSCurrencyFormat and LSParseCurrency functions rely on the underlying JVM for their operations, and the rules used for currencies depend on the JVM. For Sun JVMs, the 1.3 releases did not support euros and used the older country-specific currencies. The 1.4 releases use euros for all currencies that are in the euro zone as of 2002. If you are using a JVM that does not support the euro, use the LSEuroCurrencyFormat and LSParseEuroCurrency functions to format and parse euro values in locales that use euros as their currency.

Input data from URLs and HTML forms

A web application server receives character data from request URL parameters or as form data.

The HTTP 1.1 standard only allows US-ASCII characters (0-127) for the URL specification and for message headers. This requires a browser to encode the non-ASCII characters in the URL, both address and parameters, by escaping (URL encoding) the characters using the "%xx" hexadecimal format. URL encoding, however, does not determine how the URL is used in a web document. It only specifies how to encode the URL.

Form data uses the message headers to specify the encoding used by the request (Content headers) and the encoding used in the response (Accept headers). Content negotiation between the client and server uses this information.

This section contains suggestions on how you can handle both URL and form data entered in different character encodings.

Handling URL strings

URL requests to a server often contain name/value pairs as part of the request. For example, the following URL contains name/value pairs as part of the URL:

http://company.com/prod_page.cfm?name=Stephen;ID=7645

As discussed previously, URL characters entered using any character encoding other than US-ASCII are URL-encoded in a hexadecimal format. However, by default, a web server assumes that the characters of a URL string are single-byte characters.

One common method used to support non-ASCII characters within a URL is to include a name/value pair within the URL that defines the character encoding of the URL. For example, the following URL uses a parameter called encoding to define the character encoding of the URL parameters:

http://company.com/prod_page.cfm?name=Stephen;ID=7645;encoding=Latin-1

Within the prod_page.cfm page, you can check the value of the encoding parameter before processing any of the other name/value pairs. This guarantees that you will handle the parameters correctly.

You can also use the SetEncoding function to specify the character encoding of URL parameters. The SetEncoding function takes two parameters: the first specifies a variable scope and the second specifies the character encoding used by the scope. Since ColdFusion writes URL parameters to the URL scope, you specify "URL" as the scope parameter to the function.

For example, if the URL parameters were passed using Shift-JIS, you could access them as follows:

<cfscript>
        setEncoding("URL", "Shift_JIS");
        writeoutput(URL.name);
        writeoutput(URL.ID);
</cfscript>

Note: To specify the Shift-JIS character encoding, use the Shift_JIS attribute, with an underscore (_), not a hyphen (-).

Handling form data

The HTML form tag and the ColdFusion cfform tag let users enter text on a page, then submit that text to the server. The form tags are designed to work only with single-byte character data. Since ColdFusion uses two bytes per character when it stores strings, ColdFusion converts each byte of the form input into a two-byte representation.

However, if a user enters double-byte text into the form, the form interprets each byte as a single character, rather than recognize that each character is two bytes. This will corrupt the input text, as the following example shows:

  1. A customer enters three double-byte characters in a form, represented by six bytes.
  2. The form returns the six bytes to ColdFusion as six characters. ColdFusion converts them to a representation using two bytes per input byte for a total of twelve bytes.
  3. Outputting these characters results in corrupt information displayed to the user.

To work around this issue, use the SetEncoding function to specify the character encoding of input form text. The SetEncoding function takes two parameters: the first specifies the variable scope and the second specifies the character encoding used by the scope. Since ColdFusion writes form parameters to the Form scope, you specify "Form" as the scope parameter to the function. If the input text is double-byte, ColdFusion preserves the two-byte representation of the text.

The following example specifies that the form data contains Korean characters:

<cfscript>
    setEncoding("FORM", "EUC-KR");
</cfscript>
<h1> Form Test Result </h1>
<strong>Form Values :</strong>

<cfset text = "String = #form.input1# , Length = #len(Trim(form.input1))#">
<cfoutput>#text#</cfoutput>

File data

You use the cffile tag to write to and read from text files. By default, the cffile tag assumes that the text that you are reading, writing, copying, moving, or appending is in the JVM default file character encoding, which is typically the system default character encoding. For cffile action="Read", ColdFusion MX also checks for a byte order mark (BOM) at the start of the file; if there is one, it uses the character encoding that the BOM specifies.

Note: To specify the JVM default file character encoding, use the -Dfile.encoding= switch in the JVM Arguments field on the Java and JVM page in the ColdFusion MX Administrator.

Problems can arise if the file character encoding does not correspond to JVM character encoding, particularly if the number of bytes used for characters in one encoding does not match the number of bytes used for characters in the other encoding.

For example, assume that the JVM default file character encoding is ISO 8859-1, which uses a single byte for each character, and the file uses Shift-JIS, which uses a two-byte representation for many characters. When reading the file, the cffile tag treats each byte as an ISO 8859-1 character, and converts it into its corresponding two-byte Unicode representation. Because the characters are in Shift-JIS, the conversion corrupts the data, converting each two-byte Shift-JIS character into two Unicode characters.

To enable the cffile tag to correctly read and write text that is not encoded in the JVM default character encoding, you can pass the charset attribute to it. Specify as a value the character encoding of the data to read or write, as the following example shows:

<cffile action="read"
    charset="EUC-KR"
    file = "c:\web\message.txt"
    variable = "Message" >

Databases

ColdFusion applications access databases using drivers for each of the supported database types. The conversion of client native language data types to SQL data types is transparent and is done by the driver managers, database client, or server. For example, the character data (SQL CHAR, VARCHAR) you use with JDBC API is represented using Unicode-encoded strings.

Database administrators configure data sources and usually are required to specify the character encodings for character column data. Many of the major vendors, such as Oracle, Sybase, and Informix, support storing character data in many character encodings, including Unicode UTF-8 and UTF-16.

The database drivers supplied with ColdFusion MX correctly handle data conversions from the database native format to the ColdFusion Unicode format. You should not have to perform any additional processing to access databases. However, you should always check with your database administrator to determine how your database supports different character encodings.

E-mail

ColdFusion sends e-mail messages using the cfmail, cfmailparam, and cfmailpart tags.

By default, ColdFusion sends mail in UTF-8 encoding. You can specify a different default encoding on the Mail page in the ColdFusion MX Administrator, and you can use the charset attribute of the cfmail and cfmailpart tags to specify the character encoding for a specific mail message or part of a multipart mail message.

HTTP

ColdFusion MX supports HTTP communication using the cfhttp and cfhttpparam tags and the GetHttpRequestData function.

The cfhttp tag supports making HTTP requests. The cfhttp tag uses the Unicode UTF-8 encoding for passing data by default, and you can use the charset attribute to specify the character encoding. You can also use the cfhttpparam tag mimeType attribute to specify the MIME type and character set of a file.

LDAP

ColdFusion MX supports LDAP (Lightweight Directory Access Protocol) through the cfldap tag. LDAP uses the UTF-8 encoding format, so you can mix all retrieved data with other data and safely manipulated it. No extra processing is required to support LDAP.

WDDX

ColdFusion MX supports the cfwddx tag. ColdFusion stores WDDX (Web Distributed Data Exchange) data as UTF-8 encoding, so it automatically supports double-byte character encodings. You do not have to perform any special processing to handle double-byte characters with WDDX.

COM

ColdFusion MX supports COM through the cfobject type="com" tag. All string data used in COM interfaces is constructed using wide characters (wchars), which support double-byte characters. You do not have to perform any special processing to interface with COM objects.

CORBA

ColdFusion MX supports CORBA through the cfobject type="corba" tag. The CORBA 2.0 interface definition language (IDL) basic type "String" used the Latin-1 character encoding, which used the full 8-bits (256) to represent characters.

As long as you are using CORBA later than version 2.0, which includes support for the IDL types wchar and wstring, which map to Java types char and string respectively, you do not have to do anything to support double-byte characters.

However, if you are using a version of CORBA that does not support wchar and wstring, the server uses char and string data types, which assume a single-byte representation of text.

Searching and indexing

ColdFusion MX supports Verity search through the cfindex, cfcollection, and cfsearch tags. To support multilingual searching, the ColdFusion MX product CD-ROM includes the Verity language packs that you install to support different languages.

Previous


Debugging and Troubleshooting Applications

Macromedia ColdFusion MX provides detailed debugging information to help you resolve problems with your application. This chapter describes how you configure ColdFusion MX to provide debugging information, how to understand the information it provides, and how to use the cftrace and cftimer tags to provide detailed information on code execution. It also provides additional information on tools for validating your code before you run it and techniques for troubleshooting particular problems.

Note: Macromedia Dreamweaver MX provides integrated tools for displaying and using ColdFusion debugging output. For information on using these tools, see the Dreamweaver MX online Help.

Contents

Configuring debugging in the ColdFusion MX Administrator

Using debugging information from browser pages

Controlling debugging information in CFML

Using the cftrace tag to trace execution

Using the cftimer tag to time blocks of code

Using the Code Compatibility Analyzer

Troubleshooting common problems
Next


Configuring debugging in the ColdFusion MX Administrator

ColdFusion can provide important debugging information for every application page requested by a browser. The ColdFusion MX Administrator lets you specify which debugging information to make available and how to display it. The following sections briefly describe the Administrator settings. For more information, see the online Help for the Debugging pages.

Debugging Settings page

In the Administrator, the following options on the Debugging Settings page determine the information that ColdFusion displays in debugging output:

Option

Description

Enable Robust Exception Information

Enables the display of the following information when ColdFusion displays the exception error page. (Cleared by default.)

  • Path and URL of the page that caused the error
  • Line number and short snippet of the code where the error was identified
  • Any SQL statement and data source
  • Java stack trace

Enable Debugging

Enables debugging output. When this option is cleared, no debugging information is displayed, including all output of cftrace and cftimer calls. (Cleared by default.)

You should disable debugging output on production servers. Doing so increases security by ensuring that users cannot see debugging information. It also improves server response times. You can also limit debugging output to specific IP addresses; for more information, see Debugging IP addresses page.

Select Debugging Output Format

Determines how to display debugging output:

  • The classic.cfm template (the default) displays information as plain HTML text at the bottom of the page.
  • The dockable.cfm template uses DHTML to display the debugging information using an expanding tree format in a separate window. This window can be either a floating pane or docked to the browser window. For more information on the dockable output format, see Using the dockable.cfm output format.

Report Execution Times

Lists ColdFusion pages that run as the result of an HTTP request and displays execution times, ColdFusion also highlights in red pages with processing times greater than the specified value, and you can select between a summary display or a more detailed, tree structured, display.

General Debug Information

Displays general information about the request: ColdFusion MX Version, Template, Time Stamp, User Locale, User Agent, User IP, and Host Name.

Database Activity

Displays debugging information about access to SQL data sources and stored procedures. (Selected by default.)

Exception information

Lists all ColdFusion exceptions raised in processing the request. (Selected by default.)

Tracing information

Displays an entry for each cftrace tag. When this option is cleared, the debugging output does not include tracing information, but the output page does include information for cftrace tags that specify inline="Yes". (Selected by default.)

For more information on using the cftrace tag, seeUsing the cftrace tag to trace execution.

Variables

Enables the display of ColdFusion variable values. When this option is cleared, disables display of all ColdFusion variables in the debugging output. (Selected by default.)

When enabled, ColdFusion displays the values of variables in the selected scopes. You can select to display the contents of any of the ColdFusion scopes except Variables, Attributes, Caller, and ThisTag. To enhance security, Application, Server, and Request variable display is disabled by default,

Enable Performance Monitoring

Allows the standard NT Performance Monitor application to display information about a running ColdFusion application server.

Enable CFSTAT

Enables you to use of the cfstat command line utility to monitor real-time performance. This utility displays the same information that ColdFusion writes to the NT System Monitor, without using the System Monitor application. For information on the cfstat utility, see Configuring and Administering ColdFusion MX.

The following figure shows a sample debugging output using the classic output format:

Sample debugging output using the classic output format

Debugging IP addresses page

By default, when you enable debugging output, the output is visible only to local users (that is, via IP address 127.0.0.1). You can specify additional IP addresses whose users can see debugging output, or even disable output to local users. In the Administrator, use the Debugging IPs page to specify the addresses that can receive debugging messages.

Note: If you must enable debugging on a production server, for example to help locate the cause of a difficult problem, use the Debugging IP Addresses page to limit the output to your development systems and prevent clients from seeing the debugging information.


Using debugging information from browser pages

The ColdFusion debugging output that you configure in the Administrator displays whenever an HTML request completes. It represents the server conditions at the end of the request. For information on displaying debugging information while a request is processed, see Using the cftrace tag to trace execution.

The following figure shows a sample collapsed debugging output using the dockable.cfm debugging output format. The next sections show each of the debugging sections and describe how you can use the information they display.

A sample collapsed debugging output using the dockable.cfm debugging output format

This section describes the following topics:

  • General debugging information
  • Execution Time
  • Database Activity
  • Exceptions
  • Trace points
  • Scope variables
  • Using the dockable.cfm output format


General debugging information

ColdFusion displays general debugging information. In the classic.cfm output format, the information is at the top of the debugging output. In the dockable.cfm output format, it looks like the following figure:

Sample debugging output using the classic output format

(In the classic.cfm output format, the section is first in the debugging output and has no heading.)

The general debugging information includes the following values. The table lists the names used in the classic output template view.

Name | Description
ColdFusion | The ColdFusion MX version.
Template | The requested template. (In the dockable.cfm format, this appears in the Page Overview section and is called Page.)
TimeStamp | The time the request was completed. (In the dockable.cfm format, this appears in the Page Overview section and is called Date.)
Locale | The locality and language that determines how information is processed, particularly the message language.
User Agent | The identity of the browser that made the HTTP request.
Remote IP | The IP address of the client system that made the HTTP request.
Host Name | The name of the host running the ColdFusion server that executed the request.


Execution Time

The Execution Time section displays the time required to process the request. It displays information about the time required to process all pages required for the request, including the Application.cfc, Application.cfm, and OnRequestEnd.cfm pages, if used, and any CFML custom tags, pages included by the cfinclude tag, and any ColdFusion component (CFC) pages.

Tip: To display execution time for a specific block of code, use the cftimer tag.

You can display the execution time in two formats:

  • Summary
  • Tree

Note: Execution tine decreases substantially between the first and second time you use a page after creating it or changing it. The first time ColdFusion uses a page it compiles the page into Java bytecode, which the server saves and loads into memory. Subsequent uses of unmodified pages do not require recompilation of the code, and therefore are substantially faster.

Summary execution time format

The summary format displays one entry for each ColdFusion page processed during the request. If a page is processed multiple times it appears only once in the summary. For example, if a custom tag gets called three time in a request, it appears only once in the output. In the classic.cfm output format, the summary format looks like the following figure:

The summary format displays one entry for each ColdFusion page processed during the request.

The following table describes the display fields:

Column | Description
Total Time | The total time required to process all instances of the page and all pages that it uses. For example, if a request causes a page to be processed two times, and the page includes another page, the total time includes the time required to process both pages twice.
Avg Time | The average time for processing each instance of this page and the pages that it uses. The Avg Time multiplied by the Count equals the Total Time.
Count | The number of times the page is processed for the request.
Template | The path name of the page.

The page icon indicates the requested page.

Any page with an average processing time that exceeds the highlight value that you set on the Debugging Settings page in the ColdFusion MX Administrator appears in red.

The next to last line of the output displays the time that ColdFusion took to parse, compile, and load pages, and to start and end page processing. This figure is not included in the individual page execution times. The last line shows the sum of all the time it took to process the request.

Tree execution time format

The tree execution time format is a hierarchical, detailed view of how ColdFusion processes each page. If a page includes or calls second page, the second page appears below and indented relative to the page that uses it. Each page appears once for each time it is used. Therefore, if a page gets called three times in processing a request, it appears three times in the tree. Therefore the tree view displays both processing times and an indication of the order of page processing.

The tree format looks as follows in the dockable.cfm output format:

The tree execution time format in the dockable.cfm output format

As in the summary view, the execution times (in parentheses) show the times to process the listed page and all pages required to process the page, that is, all pages indented below the page in the tree.

By looking at this output in this figure you can determine the following information:

  • ColdFusion took 0 ms to process an Application.cfm page as part of the request.
  • The requested page was tryinclude.cfm. It took 203 ms to process this page and all pages required to execute it. The code directly on this page took 71 milliseconds (203 - 93 - 16 - 23) to process.
  • The mytag2.cfm page was processed three times. All processing took 93 milliseconds, and the average processing time was 31 milliseconds. (This page does not call any other pages.)
  • The mytag1.cfm page was processed two times. All processing took 78 milliseconds, and the average processing time was 39 milliseconds. This time included the time to process mytag2.cfm (this tag calls the mytag2 custom tag); therefore, the code directly on the page took an average of 8 milliseconds and a total of 16 milliseconds to process.
  • The includeme.cfm page took about 62 ms to process. This processing time includes the time to process the mytag1.cfm, and therefore also the time to process mytag2.cfm once. Therefore the code directly on the page took 23 milliseconds (62-39) to process.
  • ColdFusion took 125 ms for processing that was not associated with a specific page.
  • The total processing time was 328 milliseconds, the sum of 125 + 203.


Database Activity

In the Administrator, when Database Activity is selected on the Debugging Settings page, the debugging output includes information about database access.

SQL Queries

The SQL Queries section provides information about tags that generate SQL queries or result in retrieving a cached database query: cfquery, cfinsert, cfgridupdate, and cfupdate. The section looks like the following figure in the dockable.cfm output format:

The SQL Queries section provides information about tags that generate SQL queries or result in retrieving a cached database query

The output displays the following information:

  • Page on which the query is located.
  • The time when the query was made.
  • Query name.
  • An indicator if the result came from a cached query.
  • SQL statement, including the results of processing any dynamic elements such as CFML variables and cfqueryparam tags. This information is particularly useful because it shows the results of all ColdFusion processing of the SQL statement.
  • Data source name.
  • Number of records returned; 0 indicates no match to the query.
  • Query execution time.
  • Any query parameters values from cfqueryparam tags.

Stored Procedures

The stored procedures section displays information about the results of using the cfstoredproc tag to execute a stored procedure in a database management system.

The Stored Procedures section looks as follows in the classic.cfm output format:

The stored procedures section displays information about the results of using the cfstoredproc tag

The output displays the following information:

  • Stored procedure name
  • Data source name
  • Query execution time
  • Page on which the query is located.
  • The time when the query was made.
  • A table displaying the procedure parameters sent and received, as specified in the cfprocparam tags, including the ctype, CFSQLType, value variable, and dbVarName attributes. The variable information for OUT and INOUT parameters includes the returned value.
  • A table listing the procedure result sets returned, as specified in the cfprocresult tag.


Exceptions

In the Administrator, when Exception Information is selected on the Debugging Settings page, the debugging output includes a list of all ColdFusion exceptions raised in processing the application page. This section looks like the following figure when displaying information about an exception thrown by the cfthrow tag using the dockable.cfm output format:

The stored procedures section displays information about the results of using the cfstoredproc tag

The exception information includes information about any application exceptions that are caught and handled by your application code or by ColdFusion MX.

Exceptions represent events that disrupt the normal flow of an application. You should catch and, whenever possible, recover from forseeable exceptions in your application, as described in Handling Errors. However, you might also want to be alerted to caught exceptions when you are debugging your application. For example, if a file is missing, your application can catch the cffile exception and use a backup or default file instead. If you enable exception information in the debugging output, you can immediately see when this happens.


Trace points

In the Administrator, when Tracing Information is selected on the Debugging Settings page, the debugging output includes the results of all cftrace tags, including all tags that display their results in-line. Therefore, the debugging output contains a historical record of all trace points encountered in processing the request. This section looks like the following figure when you use the classic.cfm output format:

If enabled, the debugging output includes the results of all cftrace tags, including all tags that display their results in-line

For more information on using the cftrace tag, see Using the cftrace tag to trace execution.


Scope variables

In the Administrator, when the Variables option and one or more variable scopes are selected on the Debugging Settings page, the debugging output displays the values of all variables in the selected scopes. The debugging output displays the values that result after all processing of the current page.

By displaying selected scope variables you can determine the effects of processing on persistent scope variables, such as application variables. This can help you locate problems that do not generate exceptions.

The Form, URL, and CGI scopes are useful for inspecting the state of a request. They let you inspect parameters that affect page behavior, as follows:

URL variables Identify the HTTP request parameters.

Form variables Identify the form fields posted to an action page.

CGI variables Provide a view of the server environment following the request.

Similarly, the Client, Session, Application, and Server scope variables show the global state of the application, and can be useful in tracing how each page affects the state of the ColdFusion persistent variables.


Using the dockable.cfm output format

The dockable.cfm output format has several features that are not included in the classic.cfm debugging display, as shown in the following figure of a docked debug pane:

The dockable.cfm output format contains an Application page and Debug pane features

Application page selections

ColdFusion displays two buttons at the bottom of each page, as described in the following table:

Button | Description
Debug This page | Tells ColdFusion to display the debugging information for the selected frame. Refreshes the debug pane if you select it for the current frame (or the application does not use frames).
Floating/Docked debug pane | Toggles the display between a floating window and a pane docked to the left of the selected frame.

Debug pane features

The debug pane has the following features:

  • You can expand and collapse each debugging information category, such as Exceptions, by clicking on the plus or minus sign (+ or -) in front of each category heading. You can also expand and collapse each scope data type display in the Scoped Variables section.
  • The top of the debug pane displays the URL of the application page being debugged (as identified by the cgi.script_name variable). Click this link to refresh the page and display the debugging information that results. (You can also refresh the page and debugging information by using your browser’s Refresh button or key.)
  • The debug pane also displays a box where you can enter a page pathname or URL. When you click the Go button, ColdFusion processes the page and the debug pane is updated with the debugging information for the new page.


Controlling debugging information in CFML

The following sections describe how you can use CFML tags and functions to display or hide debugging and tracing information.

  • Generating debugging information for an individual query
  • Controlling debugging output with the cfsetting tag
  • Using the IsDebugMode function to run code selectively

Generating debugging information for an individual query

In the Administrator, the cfquery tag debug attribute overrides the Database Activity setting on the Debugging Settings page. The debug attribute has an effect only when debugging output is enabled on the Debugging Settings page, as follows:

  • If Database Activity is selected in the Administrator, specify debug="No" to prevent ColdFusion from displaying the query’s SQL and statistics in the debugging output.
  • If Database Activity is not selected in the Administrator, specify debug="Yes" or debug to have ColdFusion display the query’s SQL and statistics in the debugging output.

For example, if Database Activity is not selected in the Administrator, you can use the following code to show the query execution time, number of records returned, ColdFusion page, timestamp, and the SQL statement sent to the data source for this query only:

<cfquery name="TestQuery" datasource="cfdocexamples" debug>
    SELECT * FROM TestTable
</cfquery>

The debug attribute can be useful to disable query debugging information generated by queries in custom tags that you call frequently, so that you only see the debugging information for queries in pages that call the tags.

You can also view stored procedure-specific debugging information by specifying the debug attribute in the cfstoredproc tag.


Controlling debugging output with the cfsetting tag

Use the cfsetting tag showDebugOutput attribute to turn off debugging output for a specific page. The attribute controls debugging output only if the Debugging Settings page in the ColdFusion MX Administrator enables debugging output. The attribute’s default value is Yes. The following tag suppresses all debugging output for the current page:

<cfsetting showDebugOutput="No">

You can put this tag in the initialization code of the Application.cfc file or on your Application.cfm page to suppress all debugging output for an application, and override it on specific pages by setting showDebugOutput="Yes" in cfsetting tags on those pages. Conversely, you can leave debugging on for the application, and use the cfsetting showDebugOutput="No" tag to suppress debugging on individual pages where the output could cause errors or confusion.

You can also use the showDebugOutput attribute to control debugging output if you do not have access to the ColdFusion MX Administrator, but only if the Administrator enables debugging.


Using the IsDebugMode function to run code selectively

The IsDebugMode function returns True if debugging is enabled. You can use this function in a cfif tag condition to selectively run code only when debugging output is enabled. The IsDebugMode function lets you tell ColdFusion to run any code in debug mode, so it provides more flexibility than the cftrace tag for processing and displaying information.

You can use the IsDebugMode function to selectively log information only when debugging is enabled. Because you control the log output, you have the flexibility of silently logging information without displaying trace information in the browser. For example, the following code logs the application page, the current time, and the values of two variables to the log file MyAppSilentTrace.log when debugging is enabled:

<cfquery name="MyDBQuery" datasource="cfdocexamples">
    SELECT *
    FROM Employee
</cfquery>
<cfif IsDebugMode()>
    <cflog file="MyAppSilentTrace" text="Page: #cgi.script_name#,
completed query MyDBQuery; Query Execution time:
#cfquery.ExecutionTime# Status: #Application.status#">
</cfif>

Tip: If you use cfdump tags frequently for debugging, put them in <cfif IsDebugMode()> tags; for example <cfif IsDebugMode()><cfdump var=#myVar#></cfif>. This way you ensure that if you leave any cfdump tags in production code, they are not displayed when you disable debugging output.


Using the cftrace tag to trace execution

The cftrace tag displays and logs debugging data about the state of your application at the time the cftrace tag executes. You use it to provide "snapshots" of specific information as your application runs.

This section describes the following topics:

  • About the cftrace tag
  • Using tracing
  • Calling the cftrace tag

About the cftrace tag

The cftrace tag provides the following information:

  • A severity identifier specified by the cftrace tag type attribute
  • A timestamp indicating when the cftrace tag executed
  • The time elapsed between the start of processing the request and when the current cftrace tag executes.
  • The time between any previous cftrace tag in the request and the current one. If this is the first cftrace tag processed for the request, the output indicates "1st trace". ColdFusion does not display this information in inline trace output, only the log and in the standard debugging output.
  • The name of the page that called the cftrace tag
  • The line on the page where the cftrace call is located
  • A trace category specified by the category attribute
  • A message specified by the text attribute
  • The name and value, at the time the cftrace call executes, of a single variable specified by the var attribute

A typical cftrace tag might look like the following:

<cftrace category="UDF End" inline = "True" var = "MyStatus"
text = "GetRecords UDF call has completed">

You can display the cftrace tag output in either or both of the following ways:

  • As a section in the debugging output To display the trace information in the debugging output, in the Administrator, select Tracing Information on the Debugging Settings page.
  • In-line in your application page When you specify the inline attribute in a cftrace tag, ColdFusion displays the trace output on the page at the cftrace tag location. (An inline cftrace tag does not display any output if it is inside a cfsilent tag block.)

The cftrace tag executes only if you select Enable Debugging on the ColdFusion MX Administrator Debugging Settings page. To display the trace results in the debugging output, you must also specify Tracing Information on the Debugging Settings page; otherwise, the trace information is logged and inline traces are displayed, but no trace information appears in the debugging output.

Note: When you use in-line trace tags, ColdFusion sends the page to the browser after all page processing is completed, but before it displays the debugging output from the debug template. As a result, if an error occurs after a trace tag but before the end of the page, ColdFusion might not display the trace for that tag.

An in-line trace messages look like the following:

An in-line trace message

The following table lists the displayed information:

Entry | Meaning
The Information icon for the logging severity type | Trace type (severity) specified in the cftrace call; in this case, Information.
[CFTRACE 13:21:11.011] | Time when the cftrace tag executed.
[501 ms] | Time taken for processing the current request to the point of the cftrace tag.
[C:\CusionMX\wwwroot\MYStuff\ mydocs\tractest.cfm] | Path in the web server of the page that contains the cftrace tag.
@ line:14 | The line number of the cftrace tag.
[UDF End] | Value of the cftrace tag category attribute.
GetRecords UDF call has completed | The cftrace tag text attribute with any variables replaced with their values.
MyStatus Success | Name and value of the variable specified by the cftrace tag var attribute.

ColdFusion logs all cftrace output to the file logs\cftrace.log in your ColdFusion installation directory.

A log file entry looks like the following:

"Information","web-29","04/01/02","13:21:11","MyApp","[501 ms (1st trace)] [C:\CFusionMX7\wwwroot\MYStuff\mydocs\tractest.cfm @ line: 14] - [UDF End] [MyStatus = Success] GetRecords UDF call has completed "

This entry is in standard ColdFusion log format, with comma-delimited fields inside double-quote characters. The information displayed in the trace output is in the last, message, field.

The following table lists the contents of the trace message and the log entries. For more information on the log file format, see Logging errors with the cflog tag.

Entry | Meaning
Information | The Severity specified in the cftrace call.
web-29 | Server thread that executed the code.
04/01/02 | Date the trace was logged.
13:21:11 | Time the trace was logged.
MyApp | The application name, as specified in a cfapplication tag.
501 ms (1st trace)] | The time ColdFusion took to process the current request up to the cftrace tag, This is the first cftrace tag processed in this request. If there had been a previous cftrace tag, the parentheses would contain the number of milliseconds between when the previous cftrace tag ran and when this tag ran.
[C:\CFusionMX7\wwwroot\MYStuff\mydocs\ tracetest.cfm @ line: 14] | Path of the page on which the trace tag is located and the line number of the cftrace tag on the page.
[UDF End] | Value of the cftrace tag category attribute.
[MyStatus = Success] | Name and value of the variable specified by the cftrace tag var attribute. If the variable is a complex data type, such as an array or structure, the log contains the variable value and the number of entries at the top level of the variable, such as the number of top-level structure keys.
GetRecords UDF call has completed | The cftrace tag text attribute with any variables replaced with their values.


Using tracing

As its name indicates, the cftrace tag is designed to help you trace the execution of your application. It can help you do any of several things:

  • You can time the execution of a tag or code section. This capability is particularly useful for tags and operations that can take substantial processing time. Typical candidates include all ColdFusion tags that access external resources, including cfquery, cfldap, cfftp, cffile, and so on. To time execution of any tag or code block, call the cftrace tag before and after the code you want to time.
  • You can display the values of internal variables, including data structures. For example, you can display the raw results of a database query.
  • You can display an intermediate value of a variable. For example, you could use this tag to display the contents of a raw string value before you use string functions to select a substring or format it.
  • You can display and log processing progress. For example, you can put a cftrace call at the head of pages in your application or before critical tags or calls to critical functions. (Doing this could result in massive log files in a complex application, so you should use this technique with care.)
  • If a page has many nested cfif and cfelseif tags you can put cftrace tags in each conditional block to trace the execution flow. When you do this, you should use the condition variable in the message or var attribute.
  • If you find that the ColdFusion server is hanging, and you suspect a particular block of code (or call to a cfx tag, COM object, or other third-party component), you can put a cftrace tag before and after the suspect code, to log entry and exit.


Calling the cftrace tag

The cftrace tag takes the following attributes. All attributes are optional.

Attribute

Purpose

abort

A Boolean value. If you specify True, ColdFusion stops processing the current request immediately after the tag. This attribute is the equivalent of placing a cfabort tag immediately after the cftrace tag. The default is False. If this attribute is True, the output of the cftrace call appears only in the cftrace.log file. The line in the file includes the text "[ABORTED]".

category

A text string specifying a user-defined trace type category. This attribute lets you identify or process multiple trace lines by categories. For example, you could sort entries in a log according to the category.

The category attribute is designed to identify the general purpose of the trace point. For example, you might identify the point where a custom tag returns processing to the calling page with a "Custom Tag End" category. You can also use finer categories; for example, by identifying the specific custom tag name in the category.

You can include simple ColdFusion variables, but not arrays, structures, or objects, in the category text by enclosing the variable name in number signs (#).

inline

A Boolean value. If you specify True, ColdFusion displays trace output in-line in the page. The default is False.

The inline attribute lets you display the trace results at the place that the cftrace call is processed. This provides a visual cue directly in the ColdFusion page display.

Trace output also appears in a section in the debugging information display.

text

A text message describing this trace point. You can include simple ColdFusion variables, but not arrays, structures, or objects, in the text output by enclosing the variable name in number signs (#).

type

A ColdFusion logging severity type. The inline trace display and dockable.cfm output format show a symbol for each type. The default debugging output shows the type name, which is also used in the log file. The type name must be one of the following:

The Information icon for the logging severity type
Information (default)

The Warning icon for the logging severity type
Warning

The Error icon for the logging severity type
Error

The Fatal Information icon for the logging severity type
Fatal Information

var

The name of a single variable that you want displayed. This attribute can specify a simple variable, such as a string, or a complex variable, such as a structure name. Do not surround the variable name in number signs.

Complex variables are displayed in inline output in cfdump format; the debugging display and log file report the number of elements in the complex variable, instead of any values.

You can use this attribute to display an internal variable that the page does not normally show, or an intermediate value of a variable before the page processes it further.

To display a function return value, put the function inside the message. Do not use the function in the var attribute, because the attribute cannot evaluate functions.

Note: If you specify inline trace output, and a cftrace tag is inside a cfsilent tag block, ColdFusion does not display the trace information in line, but does include it in the standard debugging display.

The following cftrace tag displays the information shown in the example output and log entry in the About the cftrace tag section:

<cftrace abort="False" category="UDF End" inline = "True" text = "GetRecords UDF
    call has completed" var = "MyStatus">


Using the cftimer tag to time blocks of code

The cftimer tag displays execution time for a specified section of CFML code.

Using timing

Use this tag to determine how long it takes for a block of code to execute. This is particularly useful when ColdFusion debugging output indicates excessive execution time, but does not pinpoint the long-running block of code.

To use this tag, you must enable debugging in the ColdFusion MX Administrator Debugging Settings page. In the Debugging Settings page, you must also specifically enable usage of the cftimer tag by checking the Timer Information check box.

Tip: If you enable debugging for the cftimer tag only and display timing information in an HTML comment, you can generate timing information without disturbing production users.

Calling the cftimer tag

You can control where the cftimer tag displays timing information, as follows:

  • Inline Displays timing information following the </cftimer> tag.
  • Outline Displays timing information at the beginning of the timed code and draws a box around the timed code. (This requires browser support for the HTML FIELDSET attribute.)
  • Comment Displays timing information in an HTML comment in the format <!-- label: elapsed-time ms -->. The default label is cftimer.
  • Debug Displays timing information in the debugging output under the heading CFTimer Times.

The following example calls the cftimer tag multiple times, each time using a different type attribute:

<HTML>
<body>
<h1>CFTIMER test</h1>
<!--- type="inline" --->
     <cftimer label="Query and Loop Time Inline" type="inline">
        <cfquery name="empquery" datasource="cfdocexamples">
                select *
                from Employees
        </cfquery>

        <cfloop query="empquery">
            <cfoutput>#lastname#, #firstname#</cfoutput><br>
        </cfloop>
    </cftimer>
<hr><br>
<!--- type="outline" --->
     <cftimer label="Query and CFOUTPUT Time with Outline" type="outline">
        <cfquery name="coursequery" datasource="cfdocexamples">
                select *
                from CourseList
        </cfquery>

        <table border="1" width="100%">
        <cfoutput query="coursequery">
        <tr>
        <td>#Course_ID#</td>
        <td>#CorName#</td>
        <td>#CorLevel#</td>
        </tr>
        </cfoutput>
        </table>
    </cftimer>
<hr><br>
<!--- type="comment" --->
     <cftimer label="Query and CFOUTPUT Time in Comment" type="comment">
        <cfquery name="parkquery" datasource="cfdocexamples">
                select *
                from Parks
        </cfquery>
        <p>Select View &gt; Source to see timing information</p>
        <table border="1" width="100%">
        <cfoutput query="parkquery">
        <tr>
        <td>#Parkname#</td>
        </tr>
        </cfoutput>
        </table>
    </cftimer>

<hr><br>
<!--- type="debug" --->
     <cftimer label="Query and CFOUTPUT Time in Debug Output" type="debug">
        <cfquery name="deptquery" datasource="cfdocexamples">
                select *
                from Departments
        </cfquery>
        <p>Scroll down to CFTimer Times heading to see timing information</p>
        <table border="1" width="100%">
        <cfoutput query="deptquery">
        <tr>
        <td>#Dept_ID#</td>
        <td>#Dept_Name#</td>
        </tr>
        </cfoutput>
        </table>
    </cftimer>
</body>


Using the Code Compatibility Analyzer

The Code Compatibility Analyzer has two purposes:

  • It can validate your application’s CFML syntax. To do so, the analyzer runs the ColdFusion compiler on your pages, but does not execute the compiled code. It reports errors that the compiler encounters.
  • It can identify places where ColdFusion MX might behave differently than previous versions. The analyzer identifies the following kinds of features:
    • No longer supported Their use results in errors. For example, ColdFusion now generates an error if you use the cflog tag with the thread="Yes" attribute.
    • Deprecated They are still available, but their use is not recommended and the they might not be available in future releases. Deprecated features might also behave differently now than in previous releases. For example, the cfservlet tag is deprecated.
    • Modified behavior They might behave differently than in previous versions. For example, the StructKeyList function no longer lists the structure key names in alphabetical order.

    The analyzer provides information about the incompatibility and its severity, and suggests a remedy where one is required.

You can run the Code Compatibility Analyzer from the ColdFusion MX Administrator. Select Code Analyzer from the list of Debugging & Logging pages.

Note: The CFML analyzer does not execute the pages that it checks. Therefore, it cannot detect invalid attribute combinations if the attribute values are provided dynamically at runtime.

For more information on using the Code Compatibility Analyzer, see Migrating ColdFusion 5 Applications.


Troubleshooting common problems

This section describes a few common problems that you might encounter and ways to resolve them.

  • CFML syntax errors
  • Data source access and queries
  • HTTP/URL

For more information on troubleshooting ColdFusion, see the Macromedia ColdFusion Support Center Testing and Troubleshooting page at http://www.macromedia.com/support/coldfusion/troubleshoot.html. For common tuning and precautionary measurements that can help you prevent technical problems and improve application performance, see the ColdFusion tech tips article, TechNote number 13810. A link to the article is located near the top of the Testing and Troubleshooting page.


CFML syntax errors

Problem: You get an error message such as the following:

Encountered "function or tag name" at line 12, column 1.
Encountered "\"" at line 37, column 20.
Encountered "," at line 24, column 61.
Unable to scan the character '\"' which follows "" at line 38, column 53.

These errors typically indicate that you have unbalanced <, ", or # characters. One of the most common coding errors is to forget to close quoted code, number sign-delimited variable names, or opening tags. Make sure the code in the identified line and previous lines do not have missing characters.

The line number in the error message often does not identify the line that causes the error. Instead, it identifies the first line where the ColdFusion compiler encountered code that it could not handle as a result of the error.

Problem: You get an error message you do not understand.

Make sure all your CFML tags have matching end tags where appropriate. It is a common error to omit the end tag for the cfquery, cfoutput, cftable, or cfif tag.

As with the previous problem, the line number in the error message often does not identify the line that causes the error, but the first line where the ColdFusion compiler encounters code that it could not handle as a result of the error. Whenever you have an error message that does not appear to report a line with an error, check the code that precedes it for missing text.

Problem: Invalid attribute or value.

If you use an invalid attribute or attribute values, ColdFusion returns an error message. To prevent such syntax errors, use the CFML Code Analyzer. Also see Using the cftrace tag to trace execution.

Problem: You suspect that there are problems with the structure or contents of a complex data variable, such as a structure, array, query object, or WDDX-encoded variable.

Use the cfdump tag to generate a table-formatted display of the variable’s structure and contents. For example, to dump a structure named relatives, use the following line. You must surround the variable name with number signs (#).

<cfdump var=#relatives#>


Data source access and queries

Problem: You cannot make a connection to the database.

You must create the data source before you can connect. Connection errors can include problems with the location of files, network connections, and database client library configuration.

Create data sources before you refer to them in your application source files. Verify that you can connect to the database by clicking the Verify button on the Data Sources page of the ColdFusion MX Administrator. If you are unable to make a simple connection from that page, you might need to consult your database administrator to help solve the problem.

Also, check the spelling of the data source name.

Problem: Queries take too long.

Copy and paste the query from the Queries section of the debugging output into your database's query analysis tool. Then retrieve and analyze the execution plan generated by the database server's query optimizer. (The method for doing this varies from dbms to dbms.) The most common cause of slow queries is the lack of a useful index to optimize the data retrieval. In general, avoid table scans (or "clustered index" scans) whenever possible.


HTTP/URL

Problem: ColdFusion MX cannot correctly decode the contents of your form submission.

The method attribute in forms sent to the ColdFusion server must be Post, for example:

<form action="test.cfm" method="Post">

Problem: The browser complains or does not send the full URL string when you include spaces in URL parameters.

Some browsers automatically replace spaces in URL parameters with the %20 escape sequence, but others might display an error or just send the URL string up to the first character (as does Netscape 4.7).

URL strings cannot have embedded spaces. Use a plus sign (+) or the standard HTTP space character escape sequence, (%20) wherever you want to include a space. ColdFusion correctly translates these elements into a space.

A common scenario in which this error occurs is when you dynamically generate your URL from database text fields that have embedded spaces. To avoid this problem, include only numeric values in the dynamically generated portion of URLs.

Or, you can use the URLEncodedFormat function, which automatically replaces spaces with %20 escape sequences. For more information on the URLEncodedFormat function, see CFML Reference.
Previous


Introduction to Databases and SQL

Macromedia ColdFusion MX lets you create dynamic applications to access and modify data stored in a database. You do not need a thorough knowledge of databases to develop ColdFusion applications, but you must know some basic concepts and techniques. This chapter contains an overview of many important database and SQL concepts.

This chapter does not contain a complete description of database theory and SQL syntax. Each database server (such as SQL Server, Oracle, or DB2) has unique capabilities and properties. For more information, see the documentation that ships with your database server.

Contents

What is a database?

Using SQL

Writing queries using an editor
Next


What is a database?

A database defines a structure for storing information. Databases are typically organized into tables, which are collections of related items. You can think of a table as a grid of columns and rows. ColdFusion MX works primarily with relational databases, such as Oracle, DB2, and SQL Server.

The following figure shows the basic layout of a database table:

Basic layout of a database table

A column defines one piece of data stored in all rows of the table. A row contains one item from each column in the table.

For example, a table might contain the ID, name, title, and other information for individuals employed by a company. Each row, called a data record, corresponds to one employee. The value of a column within a record is referred to as a record field.

The following figure shows an example table, named employees, containing information about company employees:

Example table containing employee information

The record for employee 4 contains the following field values:

  • LastName field is "Smith"
  • FirstName field is "John"
  • Title field is "Engineer"

This example uses the EmpID field as the table’s primary key field. The primary key contains a unique identifier to maintain each record's unique identity. Primary keys field can include an employee ID, part number, or customer number. Typically, you specify which column contains the primary key when you create a database table.

To access the table to read or modify table data, you use the SQL programming language. For example, the following SQL statement returns all rows from the table where the department ID is 3:

SELECT * FROM employees WHERE DEPTID=3

Note: In this chapter, SQL keywords and syntax are always represented by uppercase letters. Table and column names use mixed uppercase and lowercase letters.

This section describes the following topics:

  • Using multiple database tables
  • Database permissions
  • Commits, rollbacks, and transactions
  • Database design guidelines


Using multiple database tables

In many database designs, information is distributed to multiple tables. The following figure shows two tables, one for employee information and one for employee addresses:

d
Employee information and employee address tables

In this example, each table contains a column named EmpID. This column associates a row of the employees table with a row in the addresses table.

For example, to obtain all information about an employee, you request a row from the employees table and the row from the addresses table with the same value for EmpID.

One advantage of using multiple tables is that you can add tables containing new information without modifying the structure of your existing tables. For example, to add payroll information, you add a new table to the database where the first column contains the employee’s ID and the columns contain current salary, previous salary, bonus payment, and 401(k) percent.

Also, an access to a small table is more efficient than an access to a large table. Therefore, if you update the street address of an employee, you update only the addresses table, without having to access any other table in the database.


Database permissions

In many database environments, a database administrator defines the access privileges for users accessing the database, usually through username and password. When a person attempts to connect to a database, the database ensures that the username and password are valid and then imposes access requirements on the user.

Privileges can restrict user access so that a user can do the following:

  • Read data.
  • Read data and add rows .
  • Read data, add rows, modify existing tables.

In ColdFusion MX, you use the ColdFusion MX Administrator to define database connections, called data sources. As part of defining these connections, you specify the username and password used by ColdFusion to connect to the database. The database can then control access based on this username and password.

For more information on creating a data source, see Configuring and Administering ColdFusion MX.


Commits, rollbacks, and transactions

Before you access data stored in a database, it is important to understand several database concepts, including:

  • Commit
  • Rollback
  • Transactions

A database commit occurs when you make a permanent change to a database. For example, when you write a new row to a database, the write does not occur until the database commits the change.

Rollback is the process of undoing a change to a database. For example, if you write a new row to a table, you can rollback the write up to the point where you commit the write. After the commit, you can no longer rollback the write.

Most databases support transactions where a transaction consists of one or more SQL statements. Within a transaction, your SQL statements can read, modify, and write a database. You end a transaction by either committing all your changes within the transaction or rolling back all of them.

Transactions can be useful when you have multiple writes to a database and want to make sure all writes occurred without error before committing them. In this case, you wrap all writes within a single transaction and check for errors after each write. If any write causes an error, you rollback all of them. If all writes occur successfully, you commit the transaction.

A bank might use a transaction to encapsulate a transfer from one account to another. For example, if you transfer money from your savings account to your checking account, you do not want the bank to debit the balance of your savings account unless it also credits your checking account. If the update to the checking account fails, the bank can rollback the debit of the savings account as part of the transaction.

ColdFusion MX includes the cftransaction tag that lets you implement database transactions for controlling rollback and commit. For more information, see CFML Reference.


Database design guidelines

From this basic description, the following database design rules emerge:

  • Each record should contain a unique identifier as the primary key such as an employee ID, a part number, or a customer number. The primary key is typically the column used to maintain each record's unique identity among the tables in a relational database. Databases allow you to use multiple columns for the primary key.
  • When you define a column, you define a SQL data type for the column, such as allowing only numeric values to be entered in the salary column.
  • Assessing user needs and incorporating those needs in the database design is essential to a successful implementation. A well-designed database accommodates the changing data needs within an organization.

The best way to familiarize yourself with the capabilities of your database product or database management system (DBMS) is to review the product documentation.


Using SQL

This section introduces SQL, describes basic SQL syntax, and contains examples of SQL statements. It provides enough information for you to begin using ColdFusion MX. However, this section does not contain an exhaustive description of the entire SQL programming language. For complete SQL information, see the SQL reference that ships with your database.

A query is a request to a database. The query can ask for information from the database, write new data to the database, update existing information in the database, or delete records from the database.

Structured Query Language (SQL) is an ANSI/ISO standard programming language for writing database queries. All databases supported by ColdFusion support SQL, and all ColdFusion tags that access a database allow you to pass SQL statements to the tag.

This section describes the following topics:

  • SQL example
  • Basic SQL syntax elements
  • Reading data from a database
  • Modifying a database


SQL example

The most commonly used SQL statement in ColdFusion is the SELECT statement. The SELECT statement reads data from a database and returns it to ColdFusion. For example, the following SQL statement reads all the records from the employees table:

SELECT * FROM employees

You interpret this statement as "Select all rows from the table employees" where the wildcard symbol (*) corresponds to all columns.

Tip: If you are using Macromedia Dreamweaver MX 2004 or Macromedia HomeSite+, you can use the built-in query builder to build SQL statements graphically by selecting the tables and records to retrieve. For more information, see Writing queries using an editor.

In many cases, you do not want all rows from a table, but only a subset of rows. The next example returns all rows from the employees table, where the value of the DeptID column for the row is 3:

SELECT * FROM employees WHERE DeptID=3

You interpret this statement as "Select all rows from the table employees where the DeptID is 3".

SQL also lets you specify the table columns to return. For example, instead of returning all columns in the table, you can return a subset of columns:

SELECT LastName, FirstName FROM employees WHERE DeptID=3

You interpret this statement as "Select the columns FirstName and LastName from the table employees where the DeptID is 3".

In addition to with reading data from a table, you can write data to a table using the SQL INSERT statement. The following statement adds a new row to the employees table:

INSERT INTO employees(EmpID, LastName, Firstname)
VALUES(51, 'Doe', 'John')


Basic SQL syntax elements

The following sections briefly describe the main SQL command elements.

Statements

A SQL statement always begins with a SQL verb. The following keywords identify commonly used SQL verbs:

Keyword | Description
SELECT | Retrieves the specified records.
INSERT | Adds a new row.
UPDATE | Changes values in the specified rows.
DELETE | Removes the specified rows.

Statement clauses

Use the following keywords to refine SQL statements:

Keyword | Description
FROM | Names the data tables for the operation.
WHERE | Sets one or more conditions for the operation.
ORDER BY | Sorts the result set in the specified order.
GROUP BY | Groups the result set by the specified select list items.

Operators

The following basic operators specify conditions and perform logical and numeric functions:

Operator | Description
AND | Both conditions must be met
OR | At least one condition must be met
NOT | Exclude the condition following
LIKE | Matches with a pattern
IN | Matches with a list of values
BETWEEN | Matches with a range of values
= | Equal to
<> | Not equal to
< | Less than
> | Greater than
<= | Less than or equal to
>= | Greater than or equal to
+ | Addition
- | Subtraction
/ | Division
* | Multiplication

Case sensitivity with databases

ColdFusion MX is a case-insensitive programming environment. Case insensitivity means the following statements are equivalent:

<cfset foo="bar">
<CFSET FOO="BAR">
<CfSet FOO="bar">

However, many databases, especially UNIX databases, are case-sensitive. Case sensitivity means that you must match exactly the case of all column and table names in SQL queries.

For example, the following queries are not equivalent in a case-sensitive database:

SELECT LastName FROM EMPLOYEES
SELECT LASTNAME FROM employees

In a case-sensitive database, employees and EMPLOYEES are two different tables.

For information on how your database handles case, see the product documentation.

SQL notes and considerations

When writing SQL in ColdFusion, keep the following guidelines in mind:

  • There is a lot more to SQL than what is covered here. It is a good idea to purchase one or several SQL guides for reference.
  • The data source, columns, and tables that you reference must exist in order to perform a successful query.
  • Some DBMS vendors use nonstandard SQL syntax (known as a dialect) in their products. ColdFusion does not validate the SQL; it is passed on to the database for validation, so you are free to use any syntax that is supported by your database. Check your DBMS documentation for nonstandard SQL usage.


Reading data from a database

You use the SQL SELECT statement to read data from a database. The SQL statement has the following general syntax:

SELECT column_names
FROM table_names
[ WHERE search_condition ]
[ GROUP BY group_expression ] [HAVING condition]
[ ORDER BY order_condition [ ASC | DESC ] ]

The statements in square brackets are optional.

Note: There are additional options to SELECT depending on your database. For a complete syntax description for SELECT, see the product documentation.

This section describes options to the SELECT statement.

  • Results of a SELECT statement
  • Filtering results
  • Sorting results
  • Returning a subset of columns
  • Using column aliases
  • Accessing multiple tables


Results of a SELECT statement

When the database processes a SELECT statement, it returns a record set containing the requested data. The format of a record set is a table with rows and columns. For example, if you write the following query:

SELECT * FROM employees WHERE DeptID=3

The query returns the following table:

Results from the SELECT query

Since the data returned to ColdFusion MX by a SELECT statement is in the form of a database table, ColdFusion MX lets you write a SQL query on the returned results. This functionality is called query of queries. For more information on query of queries, see Accessing and Retrieving Data.

The next example uses a SELECT statement to return only a specific set of columns from a table:

SELECT LastName, FirstName FROM employees WHERE DeptID=3

The query returns the following table:

Results of a SELECT query returning selected table columns


Filtering results

The SELECT statement lets you filter the results of a query to return only those records that meet specific criteria. For example, if you want to access all database records for employees in department 3, you use the following query:

SELECT * FROM employees WHERE DeptID=3

You can combine multiple conditions using the WHERE clause. For example, the following example uses two conditions:

SELECT * FROM employees WHERE DeptID=3 AND Title='Engineer'


Sorting results

By default, a database does not sort the records returned from a SQL query. In fact, you cannot guarantee that the records returned from the same query are returned in the same order each time you run the query.

However, if you require records in a specific order, you can write your SQL statement to sort the records returned from the database. To do so, you include an ORDER BY clause in the SQL statement.

For example, the following SQL statement returns the records of the table ordered by the LastName column:

SELECT * FROM employees ORDER BY LastName

You can combine multiple fields in the ORDER BY clause to perform additional sorting:

SELECT * FROM employees ORDER BY DepartmentID, LastName

This statement returns row ordered by department, then by last name within the department.


Returning a subset of columns

You might want only a subset of columns returned from a database table, as in the following example, which returns only the FirstName, LastName, and Phone columns. This example is useful if you are building a web page that shows the phone numbers for all employees.

SELECT FirstName, LastName, Phone FROM employees

However, this query does not to return the table rows in alphabetical order. You can include an ORDER clause in the SQL, as follows:

SELECT the FirstName, LastName, Phone
FROM employees
ORDER BY LastName, FirstName


Using column aliases

You might have column names that you do not want to retain in the results of your SQL statement. For example, your database is set up with a column that uses a reserved word in ColdFusion, such as EQ. In this case, you can rename the column as part of the query, as follows:

SELECT EmpID, LastName, EQ as MyEQ FROM employees

The results returned by this query contains columns named EmpID, LastName, and MyEQ.


Accessing multiple tables

In a database, you can have multiple tables containing related information. You can extract information from multiple tables as part of a query. In this case, you specify multiple table names in the SELECT statement, as follows:

SELECT LastName, FirstName, Street, City, State, Zip
FROM employees, addresses
WHERE employees.EmpID = addresses.EmpID
ORDER BY LastName, FirstName

This SELECT statement uses the EmpID field to connect the two tables. This query prefixes the EmpID column with the table name. This is necessary because each table has a column named EmpID. You must prefix a column name with its table name if the column name appears in multiple tables.

In this case, you extract LastName and FirstName information from the employees table and Street, City, State, and Zip information from the addresses table. You can use output such as this is to generate mailing addresses for an employee newsletter.

The results of a SELECT statement that references multiple tables is a single result table containing a join of the information from corresponding rows. A join means information from two or more rows is combined to form a single row of the result. In this case, the resultant record set has the following structure:

Results of a SELECT query that performs a join

What is interesting in this result is that even though you used the EmpID field to combine information from the two tables, you did not include that field in the output.


Modifying a database

You can use SQL to modify a database in the following ways:

  • Inserting data into a database
  • Updating data in a database
  • Deleting data from a database
  • Updating multiple tables

The following sections describe these modifications.


Inserting data into a database

You use SQL INSERT statement to write information to a database. A write adds a new row to a database table. The basic syntax of an INSERT statement is as follows:

INSERT INTO table_name(column_names)
VALUES(value_list)

where:

  • column_names specifies a comma-separated list of columns.
  • value_list specifies a comma-separated list of values. The order of values has to correspond to the order that you specified column names.

Note: There are additional options to INSERT depending on your database. For a complete syntax description for INSERT, see the product documentation.

For example, the following SQL statement adds a new row to the employees table:

INSERT INTO employees(EmpID, LastName, Firstname)
VALUES(51, 'Smith', 'John')

This statement creates a new row in the employees table and sets the values of the EmpID, LastName, and FirstName fields of the row. The remaining fields in the row are set to Null. Null means the field does not contain a value.

When you, or your database administrator, creates a table, you can set properties on the table and the columns of the table. One of the properties you can set for a column is whether the field supports Null values. If a field supports Nulls, you can omit the field from the INSERT statement. The database automatically sets the field to Null when you insert a new row.

However, if the field does not support Nulls, you must specify a value for the field as part of the INSERT statement; otherwise, the database issues an error.

The LastName and FirstName values in the query are contained within single-quotation marks. This is necessary because the table columns are defined to contain character strings. Numeric data does not require the quotation marks.


Updating data in a database

Use the UPDATE statement in SQL to update the values of a table row. Update lets you update the fields of a specific row or all rows in the table. The UPDATE statement has the following syntax:

UPDATE table_name
SET column_name1=value1, ... , column_nameN=valueN
[ WHERE search_condition ]

Note: There are additional options to UPDATE depending on your database. For a complete syntax description for UPDATE, see the product documentation.

You should not attempt to update a record’s primary key field. Your database typically enforces this restriction.

The UPDATE statement uses the optional WHERE clause, much like the SELECT statement, to determine which table rows to modify. The following UPDATE statement updates the e-mail address of John Smith:

UPDATE employees SET Email='jsmith@mycompany.com' WHERE EmpID = 51

Be careful using UPDATE. If you omit the WHERE clause to execute the following statement:

UPDATE employees SET Email = 'jsmith@mycompany.com'

you update the Email field for all rows in the table.


Deleting data from a database

The DELETE statement removes rows from a table. The DELETE statement has the following syntax:

DELETE FROM table_name
[ WHERE search_condition ]

Note: There are additional options to DELETE depending on your database. For a complete syntax description for DELETE, see the product documentation.

You can remove all rows from a table using a statement in the form:

DELETE FROM employees

Typically, you specify a WHERE clause to the DELETE statement to delete specific rows of the table. For example, the following statement deletes John Smith from the table:

DELETE FROM employees WHERE EmpID=51


Updating multiple tables

The examples in this section all describe how to modify a single database table. However, you might have a database that uses multiple tables to represent information.

One way to update multiple tables is to use one INSERT statement per table and to wrap all INSERT statements within a database transaction. A transaction contains one or more SQL statements that can be rolled back or committed as a unit. If any single statement in the transaction fails, you can roll back the entire transaction, cancelling any previous writes that occurred within the transaction. You can use the same technique for selects, updates, and deletes. The following example uses the cftransaction tag to wrap multiple SQL statements:

<cftransaction>

<cfquery name="qInsEmp" datasource="cfdocexamples">
INSERT INTO Employees (FirstName,LastName,EMail,Phone,Department)
VALUES ('Simon', 'Horwith', 'SHORWITH','(202)-797-6570','Research and Development')
</cfquery>

<cfquery name="qGetID" datasource="cfdocexamples">
SELECT MAX(Emp_ID) AS New_Employee
FROM Employees
</cfquery>

</cftransaction>


Writing queries using an editor

Dreamweaver MX 2004 and HomeSite+ provide a graphical user interface (GUI) for writing and executing queries. A GUI is useful for developing and testing your queries before you insert them into a ColdFusion application.

This section contains a brief description of these GUIs. For more information, see the documentation on your specific tool.

Writing queries using Dreamweaver MX 2004

This section describes how to define a query using the Dreamweaver MX 2004 Recordset dialog box, which allows you to create a record set without having to manually enter SQL statements. Defining a record set using this method can be as easy as selecting a database connection and table from the pop-up menus.

To define a record set without writing SQL:

  1. In the Dreamweaver Document window, open the page that will use the record set.
  2. To open the Data Bindings panel, select Window > Data Bindings.
  3. In the Data Bindings panel, click the Plus (+) button and choose Recordset (Query) from the pop-up menu.

    The Simple Recordset dialog box appears:

    The Dreamweaver MX Simple Recordset dialog box

  4. Complete the dialog box.
  5. Click the Test button to execute the query and ensure that it retrieves the information you intended.

    If you defined a filter that uses parameters input by users, the Test button displays the Test Value dialog box. Enter a value in the Test Value text box and click OK. If an instance of the record set is successfully created, a table displaying the data from your record set appears.

  6. Click OK to add the record set to the list of available content sources in the Data bindings panel.

If you prefer to write your own SQL statements, or need to create more complex queries then the Simple Recordset dialog box allows, you can define record sets using the Advanced Recordset dialog box

Creating an advanced record set by writing SQL:

  1. In the Dreamweaver Document window, open the page that will use the record set.
  2. Select Windows > Data Bindings to display the Data Bindings panel.
  3. In the Data Bindings panel, click the Plus (+) button and select Recordset (Query) from the pop-up menu.

    If the Simple Recordset dialog box appears, switch to the Advanced Recordset dialog box by clicking the Advanced button.

    The Advanced Recordset dialog box appears:

    The Dreamweaver MX Advanced Recordset dialog box

  4. Complete the dialog box.
  5. Click the Test button to execute the query and ensure that it retrieves the information you intended.

    If you defined a filter that uses parameters input by users, the Test button displays the Test Value dialog box. Enter a value in the Test Value text field and click OK. If an instance of the record set is successfully created, a table displaying the data from your record set appears.

  6. Click OK to add the record set to the list of available content sources in the Data Bindings panel.

Writing queries using Macromedia HomeSite+

Macromedia HomeSite+ includes the combined features of HomeSite 5 and ColdFusion Studio 5, with additional support for new ColdFusion MX tags. HomeSite+ supports SQL Builder for writing queries.

SQL Builder is a powerful visual tool for building, testing, and saving SQL statements for use in application data queries. You can copy completed SQL code blocks directly into your ColdFusion applications.

To open SQL Builder:

Do one of the following:

  • Select Tools > SQL Builder from the HomeSite+ menu, select an RDS server, select a database from the drop-down list, and click New Query.
  • In the Database tab, select an RDS server, right-click a database name or a table, and select New Query.
  • Open the cfquery tag editor, select an RDS server, and click New Query.

The SQL Builder interface

The following figure shows the SQL Builder interface:

The SQL Builder interface

The SQL Builder is divided into the following four sections:

Section | Use
Toolbar | Contains buttons for SQL keywords and commands.
Table pane | Provides a view of the tables in your query and allows you to create joins between tables.
Properties pane | Allows you to set the properties of the query, such as the columns that are being selected or the columns that are being updated.
SQL pane | Shows you the SQL statement as it is built. The SQL pane does not support reverse editing, so any changes you make in this pane will not be made to the query in the Properties pane or the Table pane.

Writing SQL statements

SQL Builder opens a SELECT statement by default, since this is the most common type of query. SQL Builder supports the following four types of SQL statements:

  • Select (default)
  • Insert
  • Update
  • Delete
Previous


Accessing and Retrieving Data

This chapter describes how to retrieve data from a database and work with query data. This chapter also shows how to use the cfquery tag to query a data source, and use the cfoutput tag to output the query results to a web page. This chapter also describes how to use the cfqueryparam tag to help reduce security risks.

Contents

Working with dynamic data

Retrieving data

Outputting query data

Getting information about query results

Enhancing security with cfqueryparam
Next


Working with dynamic data

A web application page is different from a static web page because it can publish data dynamically. This can involve querying databases, connecting to LDAP or mail servers, and leveraging COM, DCOM, CORBA, or Java objects to retrieve, update, insert, and delete data at runtime--as your users interact with pages in their browsers.

For ColdFusion developers, the term data source can refer to a number of different types of structured content accessible locally or across a network. You can query websites, LDAP servers, POP mail servers, and documents in a variety of formats. Most commonly though, a database drives your applications, and for this discussion a data source means the entry point from ColdFusion to a database.

In this chapter, you build a query to retrieve data from the cfdocexamples data source. In Windows, this data source connects to a Microsoft Access database (cfdocexamples.mdb). In UNIX, this data source connects to a PointBase database. In subsequent chapters in this manual, you insert and update data in this database.

To query a database, you must use:

  • ColdFusion data sources
  • The cfquery tag
  • SQL commands


Retrieving data

You can query databases to retrieve data at runtime. The retrieved data, called the record set, is stored on that page as a query object. A query object is a special entity that contains the record set values, plus RecordCount, CurrentRow, ColumnList, SQL, Cached, and SQLParameter query variables. You specify the query object’s name in the name attribute of the cfquery tag. The query object is often called simply the query.

The following is a simple cfquery tag:

<cfquery name = "GetSals" datasource = "cfdocexamples">
    SELECT * FROM Employee
    ORDER BY LastName
</cfquery>

Note: The terms "record set" and "query object" are often used synonymously when discussing record sets for queries. For more information, see Using Query of Queries.

When retrieving data from a database, perform the following tasks:

  • To tell ColdFusion how to connect to a database, use the cfquery tag on a page.
  • To specify the data that you want to retrieve from the database, write SQL commands inside the cfquery block.
  • Reference the query object and use its data values in any tag that presents data, such as cfoutput, cfgrid, cftable, cfgraph, or cftree.

The cfquery tag

The cfquery tag is one of the most frequently used CFML tags. You use it to retrieve and reference the data returned from a query. When ColdFusion encounters a cfquery tag on a page, it does the following:

  • Connects to the specified data source.
  • Performs SQL commands that are enclosed within the block.
  • Returns result set values to the page in a query object.

The cfquery tag syntax

The following code shows the syntax for the cfquery tag:

<cfquery name="EmpList" datasource="cfdocexamples">
    SQL code...
</cfquery>

In this example, the query code tells ColdFusion to do the following:

  • Connect to the cfdocexamples data source (the cfdocexamples.mdb database).
  • Execute SQL code that you specify.
  • Store the retrieved data in the query object EmpList.

When creating queries to retrieve data, keep the following guidelines in mind:

  • You must use opening <cfquery> and ending </cfquery> tags, because the cfquery tag is a block tag.
  • Enter the query name and datasource attributes within the opening cfquery tag.
  • To tell the database what to process during the query, place SQL statements inside the cfquery block.
  • When referencing text literals in SQL, use single-quotation marks ('). For example, SELECT * FROM mytable WHERE FirstName='Jacob' selects every record from mytable in which the first name is Jacob.
  • Surround attribute values with double quotation marks ("attrib_value").
  • Make sure that a data source exists in the ColdFusion MX Administrator before you reference it in a cfquery tag.
  • Columns and tables that you refer to in your SQL statement must exist, otherwise the query will fail.
  • Reference the query data by naming the query in one of the presentation tags, such as cfoutput, cfgrid, cftable, cfgraph, or cftree.
  • When ColdFusion returns database columns, it removes table and owner prefixes. For example, if you query Employee.Emp_ID in the query, the Employee, is removed and returns as Emp_ID. You can use an alias to handle duplicate column names; for more information, see Using Query of Queries.
  • You cannot use SQL reserved words, such as MIN, MAX, COUNT, in a SQL statement. Because reserved words are database-dependent, see your database’s documentation for a list of reserved words.

Building queries

As discussed earlier in this chapter, you build queries using the cfquery tag and SQL.

Note: This and many subsequent procedures use the cfdocexamples data source that connects to the cfdocexamples.mdb database. This data source is installed by default. For information on adding or configuring a data source, see Configuring and Administering ColdFusion MX.

To query the table:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Employee List</title>
</head>
<body>
<h1>Employee List</h1>
<cfquery name="EmpList" datasource="cfdocexamples">
    SELECT FirstName, LastName, Salary, Contract
    FROM Employee
</cfquery>
</body>
</html>

    Note: Macromedia recommends that you create structured, reusable code by putting queries in ColdFusion components; however, for simplicity, the examples in this chapter include the query in the body of the ColdFusion page. For more information about using ColdFusion components, see Building and Using ColdFusion Components.

  2. Save the page as emplist.cfm in the myapps directory under your web_root directory. For example, the default path on a Windows computer would be:

    C:\CFusionMX7\wwwroot\myapps\

  3. Enter the following URL in your web browser:

    http://localhost/myapps/emplist.cfm

    Only the header appears.

  4. View the source in the browser:

    Viewing the browser source code for emplist.cfm

    ColdFusion creates the EmpList data set, but only HTML and text return to the browser. When you view the page’s source, you see only HTML tags and the heading "Employee List." To display the data set on the page, you must code tags and variables to output the data.

Reviewing the code

The query you just created retrieves data from the cfdocexamples database. The following table describes the highlighted code and its function:

Code

Description

<cfquery name="EmpList" datasource="cfdocexamples">

Queries the database specified in the cfdocexamples data source.

SELECT FirstName, LastName, Salary, Contract
FROM Employee

Gets information from the FirstName, LastName, Salary, and Contract fields in the Employee table.

</cfquery>

Ends the cfquery block.


Outputting query data

After you define a query, you can use the cfoutput tag with the query attribute to output data from the record set. When you use the query attribute, keep the following in mind:

  • ColdFusion loops through all the code contained within the cfoutput block, once for each row in the record set returned from the database.
  • You must reference specific column names within the cfoutput block to output the data to the page.
  • You can place text, CFML tags, and HTML tags inside or surrounding the cfoutput block to format the data on the page.
  • Although you do not have to specify the query name when you refer to a query column, you should use the query name as a prefix for best practices reasons. For example, if you specify the Emplist query in your cfoutput tag, you can refer to the Firstname column in the Emplist query as Firstname. However, using the query name as a prefix--Emplist.Firstname-- is preferred, and is in the following procedure.

The cfoutput tag accepts a variety of optional attributes but, ordinarily, you use the query attribute to define the name of an existing query.

To output query data on your page:

  1. Edit emplist.cfm so that it appears as follows:
    <html>
<head>
<title>Employee List</title>
</head>
<body>
<h1>Employee List</h1>
<cfquery name="EmpList" datasource="cfdocexamples">
    SELECT FirstName, LastName, Salary, Contract
    FROM Employee
</cfquery>
<cfoutput query="EmpList">
#EmpList.FirstName#, #EmpList.LastName#, #EmpList.Salary#, #EmpList.Contract#<br>
</cfoutput>
</body>
</html>
  2. Save the file and view it in your web browser:

    A list of employees appears in the browser, with each line displaying one row of data.

    Note: You might need to refresh your browser to see your changes.

You created a ColdFusion application page that retrieves and displays data from a database. At present, the output is raw and needs formatting. For more information, see Introduction to Retrieving and Formatting Data.

Reviewing the code

The results of the query appear on the page. The following table describes the highlighted code and its function:

Code

Description

<cfoutput query="EmpList">

Displays information retrieved in the EmpList query.

#EmpList.FirstName#, #EmpList.LastName#,
#EmpList.Salary#, #EmpList.Contract#

Displays the value of the FirstName, LastName, Salary, and Contract fields of each record, separated by commas and spaces.

<br>

Inserts a line break (go to the next line) after each record.

</cfoutput>

Ends the cfoutput block.

Query output notes and considerations

When outputting query results, keep the following guidelines in mind:

  • A cfquery must retrieve data before the cfoutput tag can display its results. Although you can include both on the same page, Macromedia recommends that you put queries in ColdFusion components and output the results on a separate page. For more information, see Building and Using ColdFusion Components.
  • To output data from all the records of a query, specify the query name by using the query attribute in the cfoutput tag.
  • Columns must exist and be retrieved to the application to output their values.
  • Inside a cfoutput block that uses a cfquery attribute, you can prefix the query variables with the name of the query; for example, Emplist.FirstName.
  • As with other attributes, surround the query attribute value with double-quotation marks (").
  • As with any variables that you reference for output, surround column names with number signs (#) to tell ColdFusion to output the column’s current values.
  • Add a <br> tag to the end of the variable references so that ColdFusion starts a new line for each row that the query returns.


Getting information about query results

Each time you query a database with the cfquery tag, you get the data (the record set) and the query variables; together these comprise the query object. The following table describes the query variables, which are sometimes referred to as query properties:

Variable | Description
RecordCount | The total number of records returned by the query.
ColumnList | A comma-delimited list of the query columns, in alphabetical order.
SQL | The SQL statement executed.
Cached | Whether the query was cached.
SQLParameters | Ordered array of cfqueryparam values.
ExecutionTime | Cumulative time required to process the query, in milliseconds.

In your CFML code, you can use these variables as if they were columns in a database table. Use the result attribute to specify the name of the structure that ColdFusion populates with these variables. You then use that structure name to refer to the query variables as illustrated in the following example:

To output information about the query on your page:

  1. Edit emplist.cfm so that it appears as follows:
    <cfset Emp_ID = 1>
<cfquery name="EmpList" datasource="cfdocexamples" result="tmpResult">
    SELECT FirstName, LastName, Salary, Contract
    FROM Employee
    WHERE Emp_ID = <cfqueryPARAM value = "#Emp_ID#"
                       CFSQLType = "CF_SQL_INTEGER">
</cfquery>
<cfoutput query="EmpList">
    #EmpList.FirstName#, #EmpList.LastName#, #EmpList.Salary#, #EmpList.Contract#<br>
</cfoutput> <br>
<cfoutput>
    The query returned #tmpResult.RecordCount# records.<br>
    The query columns are:  #tmpResult.ColumnList#.<br>
    The SQL is #tmpResult.SQL#.<br>
    Whether the query was cached: #tmpResult.Cached#.<br>
    Query execution time: #tmpResult.ExecutionTime#.<br>
</cfoutput>
<cfdump var="#tmpResult.SQLParameters#">
  2. Save the file and view it in your web browser:

    The number of employees now appears below the list of employees. You might have to refresh your browser and scroll to see the RecordCount output.

Reviewing the code

You now display the number of records retrieved in the query. The following table describes the code and its function:

Code

Description

<cfoutput>

Displays what follows.

The query returned

Displays the text "The query returned".

#EmpList.RecordCount#

Displays the number of records retrieved in the EmpList query.

records.

Displays the text "records."

</cfoutput>

Ends the cfoutput block.

Query variable notes and considerations

When using query variables, keep the following guidelines in mind:

  • Reference the query variable within a cfoutput block so that ColdFusion outputs the query variable value to the page.
  • Surround the query variable reference with number signs (#) so that ColdFusion knows to replace the variable name with its current value.
  • Do not use the cfoutput tag query attribute when you output the RecordCount or ColumnList property. If you do, you get one copy of the output for each row. Instead, prefix the variable with the name of the query.


Enhancing security with cfqueryparam

Some DBMSs let you send multiple SQL statements in a single query. However, hackers might try to modify URL or form variables in a dynamic query by appending malicious SQL statements to existing parameters. Be aware that there are potential security risks when you pass parameters in a query string. This can happen in many development environments, including ColdFusion, ASP, and CGI. Using the cfqueryparam tag can reduce this risk.

About query string parameters

When you let a query string pass a parameter, ensure that only the expected information is passed. The following ColdFusion query contains a WHERE clause, which selects only database entries that match the last name specified in the LastName field of a form:

<cfquery name="GetEmployees" datasource="cfdocexamples">
  SELECT FirstName, LastName, Salary
  FROM Employee
  WHERE LastName='#Form.LastName#'
</cfquery>

Someone could call this page with the following malicious URL:

http://myserver/page.cfm?Emp_ID=7%20DELETE%20FROM%20Employee

The result is that ColdFusion tries to execute the following query:

<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT * 	FROM Employee
    WHERE Emp_ID = 7 DELETE FROM Employee
</cfquery>

In addition to an expected integer for the Emp_ID column, this query also passes malicious string code in the form of a SQL statement. If this query successfully executes, it deletes all rows from the Employee table--something you definitely do not want to enable by this method. To prevent such actions, you must evaluate the contents of query string parameters.

Using cfqueryparam

You can use the cfqueryparam tag to evaluate query string parameters and pass a ColdFusion variable within a SQL statement. This tag evaluates variable values before they reach the database. You specify the data type of the corresponding database column in the cfsqltype attribute of the cfqueryparam tag. In the following example, because the Emp_ID column in the cfdocexamples data source is an integer, you specify a cfsqltype of cf_sql_integer:

<cfquery name="EmpList" datasource="cfdocexamples">
    SELECT * 	FROM Employee
    WHERE Emp_ID = <cfqueryparam value = "#Emp_ID#"
                            cfsqltype = "cf_sql_integer">
</cfquery>

The cfqueryparam tag checks that the value of Emp_ID is an integer data type. If anything else in the query string is not an integer, such as a SQL statement to delete a table, the cfquery tag does not execute. Instead, the cfqueryparam tag returns the following error message:

Invalid data '7 DELETE FROM Employee' for CFSQLTYPE 'CF_SQL_INTEGER'.

Using cfqueryparam with strings

When passing a variable that contains a string to a query, specify a cfsqltype value of cf_sql_char, and specify the maxLength attribute, as in the following example:

<cfquery name = "getFirst" dataSource = "cfdocexamples">
    SELECT * FROM employees
    WHERE LastName = <cfqueryparam value = "#LastName#"
                                cfsqltype = "cf_sql_char" maxLength = "17">
</cfquery>

In this case, cfqueryparam performs the following checks:

  • It ensures that LastName contains a string.
  • It ensures that the string is 17 characters or less.
  • It escapes the string with single-quotation marks so that it appears as a single value to the database. Even if a hacker passes a bad URL, it appears as follows:

    WHERE LastName = 'Smith DELETE FROM MyCustomerTable'.

Using cfSqlType

The following table lists the available SQL types against which you can evaluate the value attribute of the cfqueryparam tag:

BIGINT | BIT | CHAR | DATE
DECIMAL | DOUBLE | FLOAT | IDSTAMP
INTEGER | LONGVARCHAR | MONEY | MONEY4
NUMERIC | REAL | REFCURSOR | SMALLINT
TIME | TIMESTAMP | TINYINT | VARCHAR

Note: Specifying the cfsqltype attribute causes the DBMS to use bind variables, which can greatly enhance performance.
Previous


Updating Your Database

This chapter describes how to use ColdFusion to insert, update, and delete information in a database.

Contents

About updating your database

Inserting data

Updating data

Deleting data
Next


About updating your database

ColdFusion was originally developed as a way to readily interact with databases. You can quickly insert, update, and delete the contents of your database by using ColdFusion forms, which are typically a pair of pages. One page displays the form with which your end user will enter values; the other page performs the action (insert, update or delete).

Depending on the extent and type of data manipulation, you can use CFML with or without SQL commands. If you use SQL commands, ColdFusion requires a minimal amount of SQL knowledge.


Inserting data

You usually use two application pages to insert data into a database:

  • An insert form
  • An insert action page

You can create an insert form with standard HTML form tags or with cfform tags (see Creating custom forms with the cfform tag). When the user submits the form, form variables are passed to a ColdFusion action page that performs an insert operation (and whatever else is called for) on the specified data source. The insert action page can contain either a cfinsert tag or a cfquery tag with a SQL INSERT statement. The insert action page should also contain a confirmation message for the end user.

Creating an HTML insert form

The following procedure creates a form using standard HTML tags. The form looks like the following in your web browser:

An HTML insert form in a web browser

To create an insert form:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Insert Data Form</title>
</head>

<body>
<h2>Insert Data Form</h2>

<table>
<!--- begin html form;
put action page in the "action" attribute of the form tag --->
<form action="insert_action.cfm" method="post">
<tr>
    <td>Employee ID:</td>
    <td><input type="text" name="Emp_ID" size="4" maxlength="4"></td>
</tr>
<tr>
    <td>First Name:</td>
    <td><input type="Text" name="FirstName" size="35" maxlength="50"></td>
</tr>
<tr>
    <td>Last Name:</td>
    <td><input type="Text" name="LastName" size="35" maxlength="50"></td>
</tr>
<tr>
    <td>Department Number:</td>
    <td><input type="Text" name="Dept_ID" size="4" maxlength="4"></td>
</tr>
<tr>
    <td>Start Date:</td>
    <td><input type="Text" name="StartDate" size="16" maxlength="16"></td>
</tr>
<tr>
    <td>Salary:</td>
    <td><input type="Text" name="Salary" size="10" maxlength="10"></td>
</tr>
<tr>
    <td>Contractor:</td>
    <td><input type="checkbox" name="Contract" value="Yes" checked>Yes</td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td><input type="Submit" value="Submit">&nbsp;<input type="Reset"
value="Clear Form"></td>
</tr>
</form>
<!--- end html form --->
</table>

</body>
</html>
  2. Save the file as insert_form.cfm in the myapps directory under your web_root and view it in your web browser.

Note: The form will not work until you write an action page for it. For more information, see Creating an action page to insert data.

Data entry form notes and considerations

If you use the cfinsert tag in the action page to insert the data into the database, you should follow these rules for creating the form page:

  • You only need to create HTML form fields for the database columns into which you will insert data.
  • By default, cfinsert inserts all of the form’s fields into the database columns with the same names. For example, it puts the Form.Emp_ID value in the database Emp_ID column. The tag ignores form fields that lack corresponding database column names.

Note: You can also use the formfields attribute of the cfinsert tag to specify which fields to insert; for example, formfields="prod_ID,Emp_ID,status".

Creating an action page to insert data

You can use the cfinsert tag or the cfquery tag to create an action page that inserts data into a database.

Creating an insert action page with cfinsert

The cfinsert tag is the easiest way to handle simple inserts from either a cfform or an HTML form. This tag inserts data from all the form fields with names that match database field names.

To create an insert action page with cfinsert:

  1. Create a ColdFusion page with the following content:
    <html>
<head> <title>Input form</title> </head>

<body>
<!--- If the Contractor check box is clear,
    set the value of the Form.Contract to "No" --->
<cfif not isdefined("Form.Contract")>
   <cfset Form.Contract = "No">
</cfif>

<!--- Insert the new record --->
<cfinsert datasource="cfdocexamples" tablename="Employee">

<h1>Employee Added</h1>
<cfoutput>You have added #Form.FirstName# #Form.Lastname# to the
            employee database.
</cfoutput>

</body>
</html>
  2. Save the page as insert_action.cfm.
  3. View insert_form.cfm in your web browser and enter values.

    Note: You might want to compare views of the Employee table in the cfdocexamples data source before and after inserting values in the form.

  4. Click Submit.

    ColdFusion inserts your values into the Employee table and displays a confirmation message.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfif not isdefined("Form.Contract")>
   <cfset Form.Contract = "No">
</cfif>

Sets the value of Form.Contract to No if it is not defined. If the Contractor check box is unchecked, no value is passed to the action page; however, the database field must have some value.

<cfinsert datasource="cfdocexamples"
    tablename="Employee">

Creates a new row in the Employee table of the cfdocexamples database. Inserts data from the form into the database fields with the same names as the form fields.

<cfoutput>You have added
#Form.FirstName# #Form.Lastname#
to the employee database.
</cfoutput>

Informs the user that values were inserted into the database.

Note: If you use form variables in cfinsert or cfupdate tags, ColdFusion automatically validates any form data it sends to numeric, date, or time database columns. You can use the hidden field validation functions for these fields to display a custom error message. For more information, see Introduction to Retrieving and Formatting Data.

Creating an insert action page with cfquery

For more complex inserts from a form submittal, you can use a SQL INSERT statement in a cfquery tag instead of using a cfinsert tag. The SQL INSERT statement is more flexible because you can insert information selectively or use functions within the statement.

The following procedure assumes that you have created the insert_action.cfm page, as described in Creating an insert action page with cfinsert.

To create an insert action page with cfquery:

  1. In insert_action.cfm, replace the cfinsert tag with the following highlighted cfquery code:
    <html>
<head>
    <title>Input form</title>
</head>

<body>
<!--- If the Contractor check box is clear),
    set the value of the Form.Contract to "No" --->
<cfif not isdefined("Form.Contract")>
   <cfset Form.Contract = "No">
</cfif>

<!--- Insert the new record --->
<cfquery name="AddEmployee" datasource="cfdocexamples">
    INSERT INTO Employee
    VALUES (#Form.Emp_ID#, '#Form.FirstName#',
    '#Form.LastName#', #Form.Dept_ID#,
    '#Form.StartDate#', #Form.Salary#, '#Form.Contract#')
</cfquery>

<h1>Employee Added</h1>
<cfoutput>You have added #Form.FirstName# #Form.Lastname# to the
            employee database.
</cfoutput>

</body>
</html>
  2. Save the page.
  3. View insert_form.cfm in your web browser and enter values.
  4. Click Submit.

    ColdFusion inserts your values into the Employee table and displays a confirmation message.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfquery name="AddEmployee" datasource="cfdocexamples">
    INSERT INTO Employee
    VALUES (#Form.Emp_ID#,
        '#Form.FirstName#',
        '#Form.LastName#',
        #Form.Dept_ID#,
        '#Form.StartDate#',
        #Form.Salary#,
        '#Form.Contract#')
</cfquery>

Inserts a new row into the Employee table of the cfdocexamples database. Specifies each form field to be added.

Because you are inserting data into all database fields in the same left-to-right order as in the database, you do not have to specify the database field names in the query.

Because #From.Emp_ID#, #Form.Dept_ID#, and #Form.Salary# are numeric, they do not need to be enclosed in quotation marks.

Inserting into specific fields

The preceding example inserts data into all the fields of a table (the Employee table has seven fields). There might be times when you do not want users to add data into all fields. To insert data into specific fields, the SQL statement in the cfquery must specify the field names following both INSERT INTO and VALUES. For example, the following cfquery omits salary and start date information from the update. Database values for these fields are 0 and NULL, respectively, according to the database’s design.

<cfquery name="AddEmployee" datasource="cfdocexamples">
    INSERT INTO Employee
        (Emp_ID,FirstName,LastName,
        Dept_ID,Contract)
    VALUES
        (#Form.Emp_ID#,'#Form.FirstName#','#Form.LastName#',
        #Form.Dept_ID#,'#Form.Contract#')
</cfquery>


Updating data

You usually use the following two application pages to update data in a database:

  • An update form
  • An update action page

You can create an update form with cfform tags or HTML form tags. The update form calls an update action page, which can contain either a cfupdate tag or a cfquery tag with a SQL UPDATE statement. The update action page should also contain a confirmation message for the end user.

Creating an update form

The following are the key differences between an update form and an insert form:

  • An update form contains a reference to the primary key of the record that is being updated.

    A primary key is a field(s) in a database table that uniquely identifies each record. For example, in a table of employee names and addresses, only the Emp_ID is unique to each record.

  • An update form is usually populated with existing record data.

The easiest way to designate the primary key in an update form is to include a hidden input field with the value of the primary key for the record you want to update. The hidden field indicates to ColdFusion which record to update.

To create an update form:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Update Form</title>
</head>

<body>
<cfquery name="GetRecordtoUpdate"
    datasource="cfdocexamples">
    SELECT * FROM Employee
    WHERE Emp_ID = #URL.Emp_ID#
</cfquery>

<cfoutput query="GetRecordtoUpdate">
<table>
<form action="update_action.cfm" method="Post">
    <input type="Hidden" name="Emp_ID"
        value="#Emp_ID#"><br>
<tr>
    <td>First Name:</td>
    <td><input type="text" name="FirstName" value="#FirstName#"></td>
</tr>
<tr>
    <td>Last Name:</td>
    <td><input type="text" name="LastName" value="#LastName#"></td>
</tr>
<tr>
    <td>Department Number:</td>
    <td><input type="text" name="Dept_ID" value="#Dept_ID#"></td>
</tr>
<tr>
    <td>Start Date:</td>
    <td><input type="text" name="StartDate" value="#StartDate#"></td>
</tr>
<tr>
    <td>Salary:</td>
    <td><input type="text" name="Salary" value="#Salary#"></td>
</tr>
<tr>
    <td>Contractor:</td>
    <td><cfif #Contract# IS "Yes">
        <input type="checkbox" name="Contract" checked>Yes
    <cfelse>
        <input type="checkbox" name="Contract">Yes
    </cfif></td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td><input type="Submit" value="Update Information"></td>
</tr>
</form>
</table>
</cfoutput>

</body>
</html>
  2. Save the file as update_form.cfm.
  3. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following:

    http://localhost/myapps/update_form.cfm?Emp_ID=3

    Note: Although you can view an employee’s information, you must code an action page before you can update the database. For more information, see Creating an action page to update data.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfquery name="GetRecordtoUpdate"
    datasource="cfdocexamples">
    SELECT * FROM Employee
    WHERE Emp_ID = #URL.Emp_ID#
</cfquery>

Queries the cfdocexamples data source and returns records in which the employee ID matches what was entered in the URL that called this page.

<cfoutput query="GetRecordtoUpdate">
...
</cfoutput>

Makes available as variables the results of the GetRecordtoUpdate query in the form created in subsequent lines.

<form action="update_action.cfm" method="Post">
...
</form>

Creates a form whose variables will be processed on the update_action.cfm action page.

<input type="Hidden" name="Emp_ID"
    value="#Emp_ID#"><br>

Uses a hidden input field to pass the Emp_ID (primary key) value to the action page.

First Name:
<input type="text" name="FirstName"
value="#FirstName#"><br>
Last Name:
<input type="text" name="LastName"
value="#LastName#"><br>
Department Number:
<input type="text" name="Dept_ID"
        value="#Dept_ID#"><br>
Start Date:
<input type="text" name="StartDate"
value="#StartDate#"><br>
Salary:
<input type="text" name="Salary"
value="#Salary#"><br>

Populates the fields of the update form. This example does not use ColdFusion formatting functions. As a result, start dates look like 1985-03-12 00:00:00 and salaries do not have dollar signs or commas. The user can replace the information in any field using any valid input format for the data.

Contractor:
<cfif #Contract# IS "Yes">
    <input type="checkbox" name="Contract"
        checked>Yes<br>
<cfelse>
    <input type="checkbox" name="Contract">
        Yes <br>
</cfif>
<br>
<input type="Submit" value="Update Information">
</form>
</cfoutput>

The Contract field requires special treatment because a check box displays and sets its value. The cfif structure puts a check mark in the check box if the Contract field value is Yes, and leaves the box empty otherwise.

Creating an action page to update data

You can create an action page to update data with either the cfupdate tag or cfquery with the UPDATE statement.

Creating an update action page with cfupdate

The cfupdate tag is the easiest way to handle simple updates from a front-end form. The cfupdate tag has an almost identical syntax to the cfinsert tag.

To use the cfupdate tag, you must include the primary key field(s) in your form submittal. The cfupdate tag automatically detects the primary key field(s) in the table that you are updating and looks for them in the submitted form fields. ColdFusion uses the primary key field(s) to select the record to update (therefore, you cannot update the primary key value itself). It then uses the remaining form fields that you submit to update the corresponding fields in the record. Your form only needs to have fields for the database fields that you want to change.

To create an update page with cfupdate:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Update Employee</title>
</head>
<body>
<cfif not isdefined("Form.Contract")>
    <cfset form.contract = "No">
<cfelse>
    <cfset form.contract = "Yes">
</cfif>

<cfupdate datasource="cfdocexamples"
    tablename="Employee">

<h1>Employee Updated</h1>
<cfoutput>
You have updated the information for #Form.FirstName#
#Form.LastName# in the employee database.
</cfoutput>

</body>
</html>
  2. Save the page as update_action.cfm.
  3. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following:

    http://localhost/myapps/update_form.cfm?Emp_ID=3

    The current information for that record appears:

    An HTML update form using the cfupdate tag

  4. Enter new values in any of the fields, and click Update Information.

    ColdFusion updates the record in the Employee table with your new values and displays a confirmation message.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfif not isdefined("Form.Contract")>
   <cfset Form.contract = "No">
<cfelse>
    <cfset form.contract = "Yes">
</cfif>

Sets the value of Form.Contract to No if it is not defined, or to Yes if it is defined. If the Contractor check box is unchecked, no value is passed to the action page; however, the database field must have some value.

<cfupdate datasource="cfdocexamples"
    tablename="Employee">

Updates the record in the database that matches the primary key on the form (Emp_ID). Updates all fields in the record with names that match the names of form controls.

<cfoutput>
You have updated the information for
    #Form.FirstName# #Form.LastName#
    in the employee database.
</cfoutput>

Informs the user that the change was made successfully.

Creating an update action page with cfquery

For more complicated updates, you can use a SQL UPDATE statement in a cfquery tag instead of a cfupdate tag. The SQL UPDATE statement is more flexible for complicated updates.

The following procedure assumes that you have created the update_action.cfm page as described in Creating an update action page with cfupdate.

To create an update page with cfquery:

  1. In update_action.cfm, replace the cfupdate tag with the following highlighted cfquery code:
    <html>
<head>
    <title>Update Employee</title>
</head>
<body>
<cfif not isdefined("Form.Contract")>
    <cfset form.contract = "No">
<cfelse>
    <cfset form.contract = "Yes">
</cfif>

<!--- cfquery requires date formatting when retrieving from
Access. Use the left function when setting StartDate to trim
the ".0" from the date when it first appears from the
Access database --->
 <cfquery name="UpdateEmployee" datasource="cfdocexamples">
    UPDATE Employee
    SET FirstName = '#Form.Firstname#',
        LastName = '#Form.LastName#',
        Dept_ID = #Form.Dept_ID#,
        StartDate = '#left(Form.StartDate,19)#',
        Salary = #Form.Salary#
    WHERE Emp_ID = #Form.Emp_ID#
</cfquery>

<h1>Employee Updated</h1>
<cfoutput>
You have updated the information for
#Form.FirstName# #Form.LastName#
in the employee database.
</cfoutput>
</body>
</html>
  2. Save the page.
  3. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following:

    http://localhost/myapps/update_form.cfm?Emp_ID=3

  4. Enter new values in any of the fields, and click Update Information.

    ColdFusion updates the record in the Employee table with your new values and displays a confirmation message.

When the cfquery tag retrieves date information from a Microsoft Access database, it displays the date and time with tenths of seconds, as follows:

Date information including tenths of seconds

This example uses the Left function to trim the two final characters. The cfdocexamples data source connects to company.mdb.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfquery name="UpdateEmployee"
    datasource="cfdocexamples">
    UPDATE Employee
    SET FirstName = '#Form.Firstname#',
        LastName = '#Form.LastName#',
        Dept_ID = #Form.Dept_ID#,
        StartDate = '#left(Form.StartDate,19)#',
        Salary = #Form.Salary#
    WHERE Emp_ID = #Form.Emp_ID#
</cfquery>

Updates the specified columns in the record in the Employee table of the cfdocexamples database that matches the primary key (Emp_ID).

Because #Form.Dept_ID#, #Form.Salary#, and #Form.Emp_ID# are numeric, they do not need to be enclosed in quotation marks.

Because of the way cfquery gets and displays dates from Access databases, you use the Left function to trim the returned value.


Deleting data

You use a cfquery tag with a SQL DELETE statement to delete data from a database. ColdFusion has no cfdelete tag.

Deleting a single record

To delete a single record, use the table’s primary key in the WHERE condition of a SQL DELETE statement. In the following procedure, Emp_ID is the primary key, so the SQL Delete statement is as follows:

DELETE FROM Employee WHERE Emp_ID = #Form.Emp_ID#

You often want to see the data before you delete it. The following procedure displays the data to be deleted by reusing the form page used to insert and update data. Any data that you enter in the form before submitting it is not used, so you can use a table to display the record to be deleted instead.

To delete one record from a database:

  1. In update_form.cfm, change the title to "Delete Form" and the text on the submit button to "Delete Record".
  2. Change the form tag so that it appears as follows:
    <form action="delete_action.cfm" method="Post">
  3. Save the modified file as delete_form.cfm.
  4. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Delete Employee Record</title>
</head>
<body>

<cfquery name="DeleteEmployee"
    datasource="cfdocexamples">
        DELETE FROM Employee
        WHERE Emp_ID = #Form.Emp_ID#
</cfquery>

<h1>The employee record has been deleted.</h1>
<cfoutput>
You have deleted #Form.FirstName# #Form.LastName# from the
    employee database.
</cfoutput>
</body>
</html>
  5. Save the page as delete_action.cfm.
  6. View delete_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following:

    http://localhost/myapps/delete_form.cfm?Emp_ID=3.Click Delete Record

    ColdFusion deletes the record in the Employee table and displays a confirmation message.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfquery name="DeleteEmployee"
    datasource="cfdocexamples">
        DELETE FROM Employee
        WHERE Emp_ID = #Form.Emp_ID#
</cfquery>

Deletes the record in the database whose Emp_ID column matches the Emp_ID (hidden) field on the form. Since the Emp_ID is the table’s primary key, only one record is deleted.

<cfoutput>
You have deleted #Form.FirstName#
    #Form.LastName# from the
    employee database.
</cfoutput>

Informs the user that the record was deleted.

Deleting multiple records

You can use a SQL condition to delete several records. The following example deletes the records for everyone in the Sales department (which has Dept_ID number 4) from the Employee table:

DELETE FROM Employee
WHERE Dept_ID = 4

To delete all the records from the Employee table, use the following code:

DELETE FROM Employee

Caution: Deleting records from a database is not reversible. Use DELETE statements carefully.
Previous


Using Query of Queries

A query that retrieves data from a record set is called a Query of Queries. After you generate a record set, you can interact with its results as if they were database tables by using Query of Queries. This chapter describes the benefits and procedures for this feature.

Contents

About record sets

About Query of Queries

Query of Queries user guide
Next


About record sets

Query of Queries is based on manipulating the record set, which you can create using the cfquery tag and other ways.

When you execute a database query, ColdFusion retrieves the data in a record set. In addition to presenting record set data to the user, you can manipulate this record set to improve your application’s performance.

Because a record set contains rows (records) and columns (fields), you can think of it as a virtual database table, or as a spreadsheet. For example, the cfpop tag retrieves a record set in which each row is a message and each column is a message component, such as To, From, and Subject.

Creating a record set

You can perform a Query of Queries on any ColdFusion tag or function that generates a record set, including the following:

  • cfcollection
  • cfdirectory
  • cfftp
  • cfhttp
  • cfindex
  • cfldap
  • cfmail
  • cfpop
  • cfprocresult
  • cfquery (against a database or against another Query of Queries)
  • cfsearch
  • cfstoredproc
  • cfwddx
  • The QueryNew function

Creating a record set with a function

In addition to creating a record set by using a cfquery or other CFML tags, you can create it with the QueryNew () function.

To create a record set with the QueryNew() function:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>The queryNew function</title>
</head>
<body>
<h2>QueryNew Example</h2>

<!--- create a query, specify data types for each column --->
<cfset qInstruments = queryNew("name, instrument, years_playing", "CF_SQL_VARCHAR, CF_SQL_VARCHAR, CF_SQL_INTEGER")>

<!--- add rows --->
<cfset newrow = queryaddrow(qInstruments, 3)>

<!--- set values in cells --->
<cfset temp = querysetcell(qInstruments, "name", "Thor", 1)>
<cfset temp = querysetcell(qInstruments, "instrument", "hammer", 1)>
<cfset temp = querysetcell(qInstruments, "years_playing", "1000", 1)>

<cfset temp = querysetcell(qInstruments, "name", "Bjorn", 2)>
<cfset temp = querysetcell(qInstruments, "instrument", "sitar", 2)>
<cfset temp = querysetcell(qInstruments, "years_playing", "24", 2)>

<cfset temp = querysetcell(qInstruments, "name", "Raoul", 3)>
<cfset temp = querysetcell(qInstruments, "instrument", "flute", 3)>
<cfset temp = querysetcell(qInstruments, "years_playing", "12", 3)>

<!--- output the query --->
<cfoutput query="qInstruments">
    <pre>#name#	#instrument# #years_playing#</pre>
</cfoutput>

<h3>Individual record retrieval:</h3>
<cfoutput>
<p>#qInstruments.name[2]# has played #qInstruments.instrument[2]# for
    #qInstruments.years_playing[2]# years.</p>
</cfoutput>

</body>
</html>
  2. Save the page as queryNew.cfm in the myapps directory under the web_root directory.
  3. Display queryNew.cfm in your browser


About Query of Queries

After you have created a record set with a tag or function, you can retrieve data from the record set in one or more dependent queries. A query that retrieves data from a record set is called a Query of Queries. A typical use of a Query of Queries is to retrieve an entire table into memory with one query, and then access the table data (the record set) with subsequent sorting or filtering queries. In essence, you query the record set as if it were a database table.

Note: Because you can generate a record set in ways other than using the cfquery tag, the term In Memory Query is sometimes used instead of Query of Queries.

Benefits of Query of Queries

Performing a Query of Queries has many benefits, including the following:

  • If you need to access the same tables multiple times, you greatly reduce access time, because the data is already in memory (in the record set).

    A Query of Queries is ideal for tables of 5,000 to 50,000 rows, and is limited only by the memory of the ColdFusion MX host computer.

  • You can perform joins and union operations on results from different data sources.

    For example, you can perform a union operation on queries from different databases to eliminate duplicates for a mailing list.

  • You can efficiently manipulate cached query results in different ways. You can query a database once, and then use the results to generate several different summary tables.

    For example, if you need to summarize the total salary by department, by skill, and by job, you can make one query to the database and use its results in three separate queries to generate the summaries.

  • You can obtain drill-down, master-detail information for which you do not access the database for the details.

    For example, you can select information about departments and employees in a query, and cache the results. You can then display the employees’ names. When users select an employee, the application displays the employee’s details by selecting information from the cached query, without accessing the database.

  • You can use a Query of Queries in report definitions to generate subreport data. For more information, see Using subreports.

Performing a Query of Queries

There are four steps to perform a Query of Queries.

To perform a Query of Queries:

  1. Generate a record set through a master query.

    You can write a master query using a tag or function that creates a record set. For more information, see Creating a record set.

  2. Write a detail query--a cfquery tag that specifies dbtype="query".
  3. In the detail query, write a SQL statement that retrieves the relevant records. Specify the names of one or more existing queries as the table names in your SQL code. Do not specify a datasource attribute.
  4. If the database content does not change rapidly, use the cachedwithin attribute of the master query to cache the query results between page requests. This way, ColdFusion accesses the database on the first page request, and does not query the database again until the specified time expires. You must use the CreateTimeSpan function to specify the cachedwithin attribute value (in days, hours, minutes, seconds format).

The detail query generates a new query result set, identified by the value of the name attribute of the detail query. The following example illustrates the use of a master query and a single detail query that extracts information from the master.

To use the results of a query in a query:

  1. Create a ColdFusion page with the following content:
    <h1>Employee List</h1>
<!--- LastNameSearch (normally generated interactively) --->
<cfset LastNameSearch="Doe">

<!--- Master Query --->
<cfquery datasource="cfdocexamples" name="master"
    cachedwithin=#CreateTimeSpan(0,1,0,0)#>
    SELECT * from Employee
</cfquery>

<!--- Detail Query (dbtype=query, no data source) --->
<cfquery dbtype="query" name="detail">
    SELECT Emp_ID, FirstName, LastName
    FROM master
    WHERE LastName=<cfqueryparam value="#LastNameSearch#"
cfsqltype="cf_sql_char" maxLength="20"></cfquery>

<!--- output the detail query results --->
<p>Output using a query of query:</p>
<cfoutput query=detail>
    #Emp_ID#: #FirstName# #LastName#<br>
</cfoutput>

<p>Columns in the master query:</p>
<cfoutput>
    #master.columnlist#<br>
</cfoutput>

<p>Columns in the detail query:</p>
<cfoutput>
    #detail.columnlist#<br>
</cfoutput>
  2. Save the page as query_of_query.cfm in the myapps directory under the web_root.
  3. Display query_of_query.cfm in your browser

Reviewing the code

The master query retrieves the entire Employee table from the cfdocexamples data source. The detail query selects only the three columns to display for employees with the specified last name. The following table describes the code and its function:

Code

Description

cfset LastNameSearch="Doe"

Sets the last name to use in the detail query. In a complete application, this information comes from user interaction.

<cfquery datasource="cfdocexamples"
name="master"
    cachedwithin=#CreateTimeSpan(0,1,0,0)#>
    SELECT * 	from Employee
</cfquery>

Queries the cfdocexamples data source and selects all data in the Employees table. Caches the query data between requests to this page, and does not query the database if the cached data is less than an hour old.

<cfquery dbtype="query" name="detail">
    SELECT Emp_ID, FirstName, LastName
    FROM master
    WHERE LastName=<cfqueryparam
    value="#LastNameSearch#"
    cfsqltype="cf_sql_char"
    maxLength="20"></cfquery>

Uses the master query as the source of the data in a new query, named detail. This new query selects only entries that match the last name specified by the LastNameSearch variable. The query also selects only three columns of data: employee ID, first name, and last name. The query uses the cfqueryparam tag to prevent passing erroneous or harmful code.

<cfoutput query=detail>
    #Emp_ID#: #FirstName# #LastName# <br>
</cfoutput>

Uses the detail query to display the list of employee IDs, first names, and last names.

<cfoutput>
    #master.columnlist#<br>
</cfoutput>

Lists all the columns returned by the master query.

<cfoutput>
    #detail.columnlist#<br>
</cfoutput>

Lists all the columns returned by the detail query.

Displaying record set data incrementally

If your database is large, you can limit the number of rows displayed at one time. The following example shows how to use the currentRow query variable of a Query of Queries to do this. For more information on query variables, see Getting information about query results.

To display record set data incrementally:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>QoQ with incremental row return</title>
</head>

<body>
<h3>QoQ with incremental row return</h3>
<!--- define startrow and maxrows to facilitate 'next N' style browsing --->
<cfparam name = "MaxRows" default = "5">
<cfparam name = "StartRow" default = "1">

<!--- master query: retrieve all info from Employee table --->
<cfquery name = "GetSals" datasource = "cfdocexamples">
    SELECT * FROM Employee
    ORDER BY LastName
</cfquery>

<!--- detail query: select 3 fields from the master query --->
<cfquery name = "GetSals2" dbtype = "query">
    SELECT   FirstName, LastName, Salary
    FROM     GetSals
    ORDER BY LastName
</cfquery>

<!--- build table to display output --->
<table cellpadding = 1 cellspacing = 1>
    <tr>
      <td bgcolor = f0f0f0>
      <b><i>&nbsp;</i></b>
      </td>

      <td bgcolor = f0f0f0>
      <b><i>FirstName</i></b>
      </td>

      <td bgcolor = f0f0f0>
      <b><i>LastName</i></b>
      </td>

      <td bgcolor = f0f0f0>
      <b><i>Salary</i></b>
      </td>
    </tr>

<!--- Output the query and define the startrow and maxrows
       parameters. Use the query variable currentRow to
       keep track of the row you are displaying. --->
    <cfoutput query = "GetSals2" startrow = "#StartRow#" maxrows = "#MaxRows#">
    <tr>
      <td valign = top bgcolor = ffffed>
          <b>#GetSals2.currentRow#</b>
      </td>

      <td valign = top>
          <font size = "-1">#FirstName#</font>
      </td>

      <td valign = top>
          <font size = "-1">#LastName#</font>
      </td>

      <td valign = top>
          <font size = "-1">#LSCurrencyFormat(Salary)#</font>
      </td>
    </tr>
    </cfoutput>
<!--- If the total number of records is less than or equal to
    the total number of rows, provide a link to the same page, with the
    StartRow value incremented by MaxRows (5, in this example) --->
    <tr>
      <td colspan = 4>
      <cfif (startrow + maxrows) lte getsals2.recordcount>
        <a href="qoq_next_row.cfm?startrow=<cfoutput>#Evaluate(StartRow +
    MaxRows)#</cfoutput>">See next <cfoutput>#MaxRows#</cfoutput>
        rows</a>
      </cfif>
      </td>
    </tr>
</table>
</body>
</html>
  2. Save the page as qoq_next_row.cfm in the myapps directory under the web_root.
  3. Display qoq_next_row.cfm in your browser

Using the cfdump tag with query results

As you debug your CFML code, you can use the cfdump tag to quickly display the contents of your query. This tag has the following format:

<cfdump var="#query_name#">

For more information on the cfdump tag, see CFML Reference.

Using Query of Queries with non-SQL record sets

A Query of Queries can operate on any CFML tag or function that returns a record set; you are not limited to operating on cfquery results. You can perform queries on non-SQL record sets, such as a cfdirectory tag, a cfsearch tag, a cfldap tag, and so on.

The following example shows how a Query of Queries interacts with the record set of a Verity search. This example assumes that you have a valid Verity collection, called bbb, which contains documents with a target word, film, or its variants (films, filmed, filming). Change the name of the collection and the search criteria to as appropriate for your Verity collection. For more information on Verity, see Building a Search Interface.

To use Query of Queries with a Verity record set:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>QoQ and Verity</title>
</head>

<body>
<!--- master query: retrieve all documents from the bbb collection
that contain ’film’ (or its stemmed variants); change values for
collection and criteria as needed for your Verity collection --->
<cfsearch name = "quick"
    collection="bbb"
    type = "simple"
    criteria="film">

<h3>Master query dump:</h3>
<cfdump var="#quick#">

<!--- detail query: retrieve from the master query only those
documents with a score greater than a criterion (here,
0.7743) --->
<cfquery name="qoq" dbtype="query">
    SELECT * from quick
    WHERE quick.score > 0.7743
</cfquery>

<h3>Detail query dump:</h3>
<cfdump var="#qoq#">

</body>
</html>
  2. Save the page as qoq_verity.cfm in the myapps directory under the web_root.
  3. Display qoq_verity.cfm in your browser

The next example shows how a Query of Queries combines record sets from a cfdirectory tag, which is limited to retrieval of one file type per use.

To use Query of Queries to combine record sets:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Images Folder</title>
</head>

<body>
<h2>Image Retrieval with QoQ</h2>
<!--- set the images directory --->
<cfset dir = ("C:\pix\")>

<!--- Retrieve all GIFs --->
<cfdirectory name="GetGIF"
  action="list"
  directory="#dir#"
  filter="*.gif">

<!--- Retrieve all JPGs --->
<cfdirectory name="GetJPG"
  action="list"
  directory="#dir#"
  filter="*.jpg">

<!--- Join the queries with a UNION in a QoQ (cfdirectory
      automatically returns the directory name as "Name") --->
<cfquery dbtype="query" name="GetBoth">
  SELECT * FROM GetGIF
  UNION
  SELECT * FROM GetJPG
  ORDER BY Name
</cfquery>

<!--- Display output in a linked, ordered list --->
<cfoutput>
  <p>The <strong>#dir#</strong> directory contains #GetBoth.RecordCount#
    images:<br>
  <ol>
    <cfloop query="GetBoth">
      <li><a href="../images/#Name#">#GetBoth.Name#</a><br>
    </cfloop>
  </ol>
</cfoutput>

</body>
</html>
  2. Save the page as qoq_cfdirectory.cfm in the myapps directory under the web_root.
  3. Display qoq_cfdirectory.cfm in your browser


Query of Queries user guide

The following sections discuss Query of Queries functionality. If you know SQL or have interacted with databases, you might be familiar with some of these features.

  • Using dot notation
  • Using joins
  • Using unions
  • Using conditional operators
  • Managing data types for columns
  • Using the CAST function
  • Using aggregate functions
  • Using group by and having expressions
  • Using ORDER BY clauses
  • Using aliases
  • Handling null values
  • Concatenating strings
  • Escaping reserved keywords
  • Using Queries of Queries with dates
  • Understanding Query of Queries performance
  • Understanding Query of Queries processing

Using dot notation

ColdFusion supports using dot notation in table names.

Example

If a structure named A contains a field named B, which contains a table named Products, you can refer to the table with dot notation, as follows:

SELECT tape_ID, length
FROM A.B.Products;


Using joins

A join operation uses a single SELECT statement to return a result set from multiple, related tables, typically those with a primary key - foreign key relationship. There are two SQL clauses that perform joins:

  • WHERE clause ColdFusion supports joins through a WHERE clause.
  • INNER JOIN and OUTER JOIN ColdFusion does not support joins through INNER JOIN or OUTER JOIN clauses.

Note: Query of Queries supports joins between two tables only.


Using unions

The UNION operator lets you combine the results of two or more SELECT expressions into a single record set. The original tables must have the same number of columns, and corresponding columns must be UNION-compatible data types. Columns are UNION-compatible data types if they meet one of the following conditions:

  • The same data type; for example, both Tinyint
  • Both Numeric; for example, Tinyint, Smallint, Integer, Bigint, Double, Float, Real, Decimal, or Numeric
  • Both Characters; for example, Char, Varchar, or LongVarchar
  • Both Dates; for example, Time, TimeStamp, or Date

Note: Query Of Queries does not support ODBC-formatted dates and times.

Syntax

select_expression = select_expression UNION [ALL] select_expression

Example

This example uses the following tables:

Table1
Type(int) | Name(varchar)
1 | Tennis
2 | Baseball
3 | Football
Table2
ID(int) | Sport(varchar)
3 | Football
4 | Volleyball
5 | PingPong

To combine Table1 and Table2, use a UNION statement, as follows:

SELECT * FROM Table1
UNION
SELECT * FROM Table2

The UNION statement produces the following result (UNION) table:

Result table
Type(int) | Name(varchar)
1 | Tennis
2 | Baseball
3 | Football
4 | Volleyball
5 | PingPong

Using aliases for column names

The column names of a UNION table are the column names in the result set of the first SELECT statement in the UNION operation; ColdFusion ignores the column names in the other SELECT statement. To change the column names of the result table, you can use an alias, as follows:

Select Type as SportType, Name as SportName from Table1
UNION
Select * from Table2

Duplicate rows and multiple tables

By default, the UNION operator removes duplicate rows from the result table. If you use the keyword ALL, then duplicates are included.

You can combine an unlimited number of tables using the UNION operator, for example:

Select * from Table1
UNION
Select * from Table2
UNION
Select * from Table3
...

Parentheses and evaluation order

By default, the Query of Queries SQL engine evaluates a statement containing UNION operators from left to right. You can use parentheses to change the order of evaluation. For example, the following two statements are different:

/* First statement. */
SELECT * FROM TableA
UNION ALL
(SELECT * FROM TableB
UNION
SELECT * FROM TableC
)

/* Second statement. */
(SELECT * FROM TableA
UNION ALL
SELECT * FROM TableB
)
UNION
SELECT * FROM TableC

In the first statement, there are no duplicates in the union between TableB and TableC. Then, in the union between that set and TableA, the ALL keyword includes the duplicates. In the second statement, duplicates are included in the union between TableA and TableB but are eliminated in the subsequent union with TableC. The ALL keyword has no effect on the final result of this expression.

Using other keywords with UNION

When you perform a UNION, the individual SELECT statements cannot have their own ORDER BY or COMPUTE clauses. You can only have one ORDER BY or COMPUTE clause after the last SELECT statement; this clause is applied to the final, combined result set. You can only specify GROUP BY and HAVING expressions in the individual SELECT statements.


Using conditional operators

ColdFusion lets you use the following conditional operators in your SQL statements:

  • Test
  • Null
  • Comparison
  • Between
  • IN
  • LIKE

Test conditional

This conditional tests whether a Boolean expression is True, False, or Unknown.

Syntax

cond_test ::= expression [IS [NOT] {TRUE | FALSE | UNKNOWN} ]

Example

SELECT _isValid FROM Chemicals
WHERE _isValid IS true;

Null conditional

This conditional tests whether an expression is null.

Syntax

null_cond ::= expression IS [NOT] NULL

Example

SELECT bloodVal FROM Standards
WHERE bloodVal IS NOT null;

Comparison conditional

This conditional lets you compare an expression against another expression of the same data type (Numeric, String, Date, or Boolean). You can use it to selectively retrieve only the relevant rows of a record set.

Syntax

comparison_cond ::= expression [> | >= | <> | != | < | <=] expression

Example

The following example uses a comparison conditional to retrieve only those dogs whose IQ is at least 150:

SELECT dog_name, dog_IQ
FROM Dogs
WHERE dog_IQ >= 150;

Between conditional

This conditional lets you compare an expression against another expression. You can use it to selectively retrieve only the relevant rows of a record set. Like the comparison conditional, the BETWEEN conditional makes a comparison; however, the between conditional makes a comparison against a range of values. Therefore, its syntax requires two values, which are inclusive, a minimum and a maximum. You must separate these values with the AND keyword.

Syntax

between_cond ::= expression [NOT] BETWEEN expression AND expression

Example

The following example uses a BETWEEN conditional to retrieve only those dogs whose IQ is between 150 and 165, inclusive:

SELECT dog_name, dog_IQ
FROM Dogs
WHERE dog_IQ BETWEEN 150 AND 165;

IN conditional

This conditional lets you specify a comma-delimited list of conditions to match. It is similar in function to the OR conditional. In addition to being more legible when working with long lists, the IN conditional can contain another SELECT statement.

Syntax

in_cond ::= expression [NOT] IN (expression_list)

Example

The following example uses the IN conditional to retrieve only those dogs who were born at either Ken’s Kennels or Barb’s Breeders:

SELECT dog_name, dog_IQ, Kennel_ID
FROM Dogs
WHERE kennel_ID IN ('Kens','Barbs');

LIKE conditional

This conditional lets you perform wildcard searches, in which you compare your data to search patterns. This strategy differs from other conditionals, such as BETWEEN or IN, because the LIKE conditional compares your data to a value that is partially unknown.

Syntax

like_cond ::= left_string_exp [NOT] LIKE right_string_exp [ESCAPE escape_char]

The left_string_exp can be either a constant string, or a column reference to a string column. The right_string_exp can be either a column reference to a string column, or a search pattern. A search pattern is a search condition that consists of literal text and at least one wildcard character. A wildcard character is a special character that represents an unknown part of a search pattern, and is interpreted as follows:

  • The underscore (_) represents any single character.
  • The percent sign (%) represents zero or more characters.
  • Square brackets ([ ]) represents any character in the range.
  • Square brackets with a caret [^] represent any character not in the range.
  • All other characters represent themselves.

Note: Earlier versions of ColdFusion do not support bracketed ranges.

Examples

The following example uses the LIKE conditional to retrieve only those dogs of the breed Terrier, whether the dog is a Boston Terrier, Jack Russell Terrier, Scottish Terrier, and so on:

SELECT dog_name, dog_IQ, breed
FROM Dogs
WHERE breed LIKE '%Terrier';

The following examples are select statements that use bracketed ranges:

SELECT lname FROM Suspects WHERE lname LIKE 'A[^c]%';
SELECT lname FROM Suspects WHERE lname LIKE '[a-m]%';
SELECT lname FROM Suspects WHERE lname LIKE '%[]';
SELECT lname FROM Suspects WHERE lname LIKE 'A[%]%';
SELECT lname FROM Suspects WHERE lname LIKE 'A[^c-f]%';

Case sensitivity

Unlike the rest of ColdFusion, Query of Queries is case-sensitive. However, Query of Queries supports two string functions, UPPER() and LOWER(), which you can use to achieve case-insensitive matching.

Examples

The following example matches only 'Sylvester':

SELECT dog_name
FROM Dogs
WHERE dog_name LIKE 'Sylvester';

The following example is not case-sensitive; it uses the LOWER() function to treat 'Sylvester', 'sylvester', 'SYLVESTER', and so on as all lowercase, and matches them with the all lowercase string, ‘sylvester’:

SELECT dog_name
FROM Dogs
WHERE LOWER(dog_name) LIKE 'sylvester';

If you use a variable on the right side of the LIKE conditional and want to ensure that the comparison is not case-sensitive, use the LCase or UCase function to force the variable text to be all of one case, as in the following example:

WHERE LOWER(dog_name) LIKE '#LCase(FORM.SearchString)#';

Escaping wildcards

You can specify your own escape character using the conditional ESCAPE clause.

Example

The following example uses the ESCAPE clause to enable a search for a literal percent sign (%), which ColdFusion normally interprets as a wildcard character:

SELECT emp_discount
FROM Benefits
WHERE emp_discount LIKE '10\%'
ESCAPE '\';


Managing data types for columns

A Query of Queries requires that every column have metadata that defines the column’s data type. All queries that ColdFusion MX creates have metadata. However, a query created with QueryNew function that omits the second parameter does not contain metadata. You use this optional second parameter to define the data type of each column in the query.

To specify column data types in the QueryNew function:

  • Type a QueryNew function, specifying the column names in the first parameter and the data types in the second parameter, as the following example shows:
    <cfset qInstruments = queryNew("name, instrument, years_playing", "CF_SQL_VARCHAR, CF_SQL_VARCHAR, CF_SQL_INTEGER")>

Tip: To see the metadata for a Query of Queries, use the GetMetaData function.

To specify the column data types in the QueryAddColumn function:

  1. Create a query by specifying the QueryNew function with no parameters.
<!--- Make a query. --->
<cfset myQuery = QueryNew("")>
  1. Add and populate a column with the QueryAddColumn function, specifying the data type in the third parameter:
<!--- Create an array. --->
<cfset FastFoodArray = ArrayNew(1)>
<cfset FastFoodArray[1] = "French Fries">
<cfset FastFoodArray[2] = "Hot Dogs">
<cfset FastFoodArray[3] = "Fried Clams">
<cfset FastFoodArray[4] = "Thick Shakes">
<!--- Use the array to add a column to the query. --->
<cfset nColumnNumber = QueryAddColumn(myQuery, "FastFood", "CF_SQL_VARCHAR",

    FastFoodArray)>

If you do not specify the data type, ColdFusion MX examines the first fifty rows of each column to determine the data type when performing conditional expressions.

In some cases, ColdFusion MX can guess a data type that is inappropriate for your application. In particular, if you use columns in a WHERE clause or other conditional expression, the data types must be compatible. If they are not compatible, you must use the CAST function to recast one of the columns to a compatible data type. For more information on casting, see Using the CAST function. For more information on data type compatibility, see Understanding Query of Queries processing.

Note: Specifying the data type in the QueryNew function helps you avoid compatibility issues.


Using the CAST function

In some cases, a column’s data type may not be compatible with the processing you want to do. For example, query columns returned by the cfhttp tag are all of type CF_SQL_VARCHAR, even though the contents may be numeric. In this case, you can use the Query of Queries CAST function to convert a column value into an expression of the correct data type.

The syntax for the CAST function is as follows:

CAST ( expression AS castType )

Where castType is one of the following:

  • BINARY
  • BIGINIT
  • BIT
  • DATE
  • DECIMAL
  • DOUBLE
  • INTEGER
  • TIME
  • TIMESTAMP
  • VARCHAR

For example:

<cfhttp url="http://quote.yahoo.com/download/quotes.csv?Symbols=csco,jnpr&format=sc1l1&ext=.csv"
        method="GET"
        name="qStockItems"
        columns="Symbol,Change,LastTradedPrice"
        textqualifier=""""
        delimiter=","
        firstrowasheaders="no">
<cfoutput>
  <cfdump var="#qStockItems#">
  <cfdump var="#qStockItems.getColumnNames()#">
</cfoutput>

<cfoutput>
  <cfloop index="i" from="1" to="#arrayLen(qStockItems.getColumnNames())#">
       #qStockItems.getMetaData().getColumnTypeName(javaCast("int",i))#<br/>
  </cfloop>
</cfoutput>
<cftry>
    <cfquery name="hello" dbtype="query">
        SELECT SUM(CAST(qStockItems.LastTradedPrice as INTEGER))
           AS SUMNOW from qStockItems
    </cfquery>
    <cfcatch>Error in Query of Queries</cfcatch>
</cftry>

<cfoutput>
  <cfdump var="#hello#">
</cfoutput>


Using aggregate functions

Aggregate functions operate on a set of data and return a single value. Use these functions for retrieving summary information from a table, as opposed to retrieving an entire table and then operating on the record set of the entire table.

Consider using aggregate functions to perform the following operations:

  • To display the average of a column
  • To count the number of rows for a column
  • To find the earliest date in a column

Since not every relational database management system (RDBMS) supports all aggregate functions, refer to your database’s documentation. The following table lists the aggregate functions that ColdFusion supports:

Function | Description
AVG() | Returns the average (mean) for a column.
COUNT() | Returns the number of rows in a column.
MAX() | Returns the largest value of a column.
MIN() | Returns the lowest value of a column.
SUM() | Returns the sum of values of a column.

Syntax

aggregate_func ::= <COUNT>(* | column_name) | AVG | SUM | MIN | MAX)
([ALL | DISTINCT] numeric_exp)

Example

The following example uses the AVG() function to retrieve the average IQ of all terriers:

SELECT dog_name, AVG(dog_IQ) AS avg_IQ
FROM Dogs
WHERE breed LIKE '%Terrier';

Arbitrary expressions in aggregate functions

ColdFusion supports aggregate functions of any arbitrary expression, as follows:

SELECT lorange, count(lorange+hirange)
FROM roysched
GROUP BY lorange;

Aggregate functions in arbitrary expressions

ColdFusion supports mathematical expressions that include aggregate functions, as follows:

SELECT MIN(lorange) + MAX(hirange)
FROM roysched
GROUP BY lorange;


Using group by and having expressions

ColdFusion supports the use of any arbitrary arithmetic expression, as long as it is referenced by an alias.

Examples

The following code is correct:

SELECT (lorange + hirange)/2 AS midrange,
COUNT(*)
FROM roysched
GROUP BY midrange;

The following code is correct:

SELECT (lorange+hirange)/2 AS x,
COUNT(*)
FROM 	roysched GROUP BY x
HAVING x > 10000;

The following code is not supported in Query of Queries:

SELECT (lorange + hirange)/2 AS midrange,
COUNT(*)
FROM roysched
GROUP BY (lorange + hirange)/2;


Using ORDER BY clauses

ColdFusion supports the ORDER BY clause to sort. Make sure that it is the last clause in your SELECT statement. You can sort by multiple columns, by relative column position, by nonselected columns. You can specify a descending sort direction with the DESC keyword (by default, most RDBMS sorts are ascending, which makes the ASC keyword unnecessary).

Syntax

order_by_column ::= ( <IDENTIFIER> | <INTEGER_LITERAL> ) [<ASC> | <DESC>]

Examples

The following example shows a simple sort using an ORDER BY clause:

SELECT acetylcholine_levels, dopamine_levels
FROM results
ORDER BY dopamine_levels

The following example shows a more complex sort; results are first sorted by ascending levels of dopamine, then by descending levels of acetylcholine. The ASC keyword is unnecessary, and is used only for legibility.

SELECT acetylcholine_levels, dopamine_levels
FROM results
ORDER BY 2 ASC, 1 DESC


Using aliases

ColdFusion supports the use of database column aliases. An alias is an alternate name for a database field or value. ColdFusion lets you reuse an alias in the same SQL statement.

One way to create an alias is to concatenate (append) two or more columns to generate a value. For example, you can concatenate a first name and a last name to create the value fullname. Because the new value does not exist in a database, you refer to it by its alias. The AS keyword assigns the alias in the SELECT statement.

Examples

ColdFusion supports alias substitutions in the ORDER BY, GROUP BY, and HAVING clauses.

Note: ColdFusion does not support aliases for table names.

SELECT FirstName + ' ' + LastName AS fullname
from Employee;

The following examples rely on these two master queries:

<cfquery name="employee" datasource="2pubs">
    SELECT * FROM employee
</cfquery>

<cfquery name="roysched" datasource="2pubs">
    SELECT * FROM roysched
</cfquery>

ORDER BY example

<cfquery name="order_by" dbtype="query">
    SELECT (job_id + job_lvl)/2 AS job_value
    FROM employee
    ORDER BY job_value
</cfquery>

GROUP BY example

<cfquery name="group_by" dbtype="query">
    SELECT	 	lorange+hirange AS x, count(hirange)
    FROM 		roysched
    GROUP BY 	x
</cfquery>

HAVING example

<cfquery name="having" dbtype="query">
    SELECT (lorange+hirange)/2 AS x,
    COUNT(*)
    FROM 	roysched GROUP BY x
    HAVING x > 10000
</cfquery>


Handling null values

ColdFusion uses Boolean logic to handle conditional expressions. Proper handling of NULL values requires the use of ternary logic. The IS [NOT] NULL clause works correctly in ColdFusion. However the following expressions do not work properly when the column breed is NULL:

WHERE (breed > 'A')
WHERE NOT (breed > 'A')

The correct behavior should not include NULL breed columns in the result set of either expression. To avoid this limitation, you can add an explicit rule to the conditionals and rewrite them in the following forms:

WHERE breed IS NOT NULL AND (breed > 'A')
WHERE breed IS NOT NULL AND not (breed > 'A')


Concatenating strings

Query of Queries support two string concatenation operators: + and ||, as the following examples show:

LASTNAME + ', ' + FIRSTNAME
LASTNAME || ', ' || FIRSTNAME


Escaping reserved keywords

ColdFusion has a list of reserved keywords, which are typically part of the SQL language and are not normally used for names of columns or tables. To escape a reserved keyword for a column name or table name, enclose it in brackets.

Caution: Earlier versions of ColdFusion let you use some reserved keywords without escaping them.

Examples

ColdFusion supports the following SELECT statement examples:

SELECT [from] FROM parts;
SELECT [group].firstname FROM [group];
SELECT [group].[from] FROM [group];

ColdFusion does not support nested escapes, such as in the following example:

SELECT [[from]] FROM T;

The following table lists ColdFusion reserved keywords:

ABSOLUTE | ACTION | ADD | ALL | ALLOCATE
ALTER | AND | ANY | ARE | AS
ASC | ASSERTION | AT | AUTHORIZATION | AVG
BEGIN | BETWEEN | BIT | BIT_LENGTH | BOTH
BY | CASCADE | CASCADED | CASE | CAST
CATALOG | CHAR | CHARACTER | CHARACTER_ LENGTH | CHAR_LENGTH
CHECK | CLOSE | COALESCE | COLLATE | COLLATION
COLUMN | COMMIT | CONNECT | CONNECTION | CONSTRAINT
CONSTRAINTS | CONTINUE | CONVERT | CORRESPONDING | COUNT
CREATE | CROSS | CURRENT | CURRENT_DATE | CURRENT_TIME
CURRENT_ TIMESTAMP | CURRENT_ USER | CURSOR | DATE | DAY
DEALLOCATE | DEC | DECIMAL | DECLARE | DEFAULT
DEFERRABLE | DEFERRED | DELETE | DESC | DESCRIBE
DESCRIPTOR | DIAGNOSTICS | DISCONNECT | DISTINCT | DOMAIN
DOUBLE | DROP | ELSE | END | END-EXEC
ESCAPE | EXCEPT | EXCEPTION | EXEC | EXECUTE
EXISTS | EXTERNAL | EXTRACT | FALSE | FETCH
FIRST | FLOAT | FOR | FOREIGN | FOUND
FROM | FULL | GET | GLOBAL | GO
GOTO | GRANT | GROUP | HAVING | HOUR
IDENTITY | IMMEDIATE | IN | INDICATOR | INITIALLY
INNER | INPUT | INSENSITIVE | INSERT | INT
INTEGER | INTERSECT | INTERVAL | INTO | IS
ISOLATION | JOIN | KEY | LANGUAGE | LAST
LEADING | LEFT | LEVEL | LIKE | LOCAL
LOWER | MATCH | MAX | MIN | MINUTE
MODULE | MONTH | NAMES | NATIONAL | NATURAL
NCHAR | NEXT | NO | NOT | NULL
NULLIF | NUMERIC | OCTET_LENGTH | OF | ON
ONLY | OPEN | OPTION | OR | ORDER
OUTER | OUTPUT | OVERLAPS | PAD | PARTIAL
POSITION | PRECISION | PREPARE | PRESERVE | PRIMARY
PRIOR | PRIVILEGES | PROCEDURE | PUBLIC | READ
REAL | REFERENCES | RELATIVE | RESTRICT | REVOKE
RIGHT | ROLLBACK | ROWS | SCHEMA | SCROLL
SECOND | SECTION | SELECT | SESSION | SESSION_USER
SET | SMALLINT | SOME | SPACE |
SQL | SQLCODE | SQLERROR | SQLSTATE | SUBSTRING
SUM | SYSTEM USER | TABLE | TEMPORARY | THEN
TIME | TIMESTAMP | TIMEZONE HOUR | TIMEZONE_MINUTE | TO
TRAILING | TRANSACTION | TRANSLATE | TRANSLATION | TRIM
TRUE | UNION | UNIQUE | UNKNOWN | UPDATE
UPPER | USAGE | USER | USING | VALUE
VALUES | VARCHAR | VARYING | VIEW | WHEN
WHENEVER | WHERE | WITH | WORK | WRITE
YEAR | ZONE |  |  |


Using Queries of Queries with dates

If you create a query object with the QueryNew function and populate a column with date constants, ColdFusion MX stores the dates as a string inside the query object until a Query of Queries is applied to the query object. When ColdFusion applies a Query of Queries to the query object, it converts the string representations into date objects.

Query of Queries supports date constants in SQL and ODBC format, as follows:

  • SQL format Dates, times, or timestamps in one of the following format:
    • Date string yyyy-mm-dd, for example, 1955-06-13.
    • Time string hh:mm:ss[.[nnn]], for example, 14:34:30.75.
    • Timestamp string yyyy-mm-dd hh:mm:ss[.[nnn]], for example, 1924-01-14 12:00:00.000.
  • ODBC format Dates, times, or timestamps in one of the following format:
    • Date string {d 'value'}, for example, {d '2004-07-06'}.
    • Time string {t 'value'}, for example, {t '13:45:30'}.
    • Timestamp string {ts 'value'}, for example, {ts '2004-07-06 13:45:30'}.

Tip: If you want to convert the date to its original format, use the DateFormat function and apply the "mm/dd/yy" mask.


Understanding Query of Queries performance

Query of Queries performs very well on single-table query objects that were accessed directly from a database. This is because ColdFusion MX stores meta information for a query object accessed from a database.

When working with a query resulting in a SQL join, Query of Queries performs as follows:

  • Query of Queries is very efficient for simple joins in which there is only one equality between two column references or constants; for example:
    SELECT T1.a, b, c, d FROM T1, T2 WHERE T1.a = T2.a
  • Query of Queries is less efficient for joins in which the predicate contains multiple expressions; for example:
    SELECT T1.a, b, c, d FROM T1, T2
WHERE T1.a = T2.a AND T1.b + T1.c = T2.b + T2.c


Understanding Query of Queries processing

The following discussions describe how Query of Queries handles the following:

  • Column comparisons
  • Queries passed by reference
  • Complex objects

Comparing columns with different data types

ColdFusion MX 7 includes enhancements that allow you to compare columns with different data types.

If one of the operands has a known column type (only constants have an unknown column type), Query of Queries tries to coerce the constant with an unknown type to the type of the operand with metadata. The pairs of allowed coercions are as follows:

  • Binary, string
  • Dates, string
  • Numeric, bigdecimal
  • Boolean, numeric

That is, ColdFusion MX can coerce between binary and string, but not between date and string.

If both operands have known data types, the types must be the same. The only exception is that ColdFusion MX can coerce among integer, float, and double.

If both operands are constants, ColdFusion MX tries to coerce the values, first to the most restrictive type, then to the least restrictive type.

  • First to binary then to string.
  • First to date then to string.
  • First to boolean then to numeric.

Passing queries by reference

A Query of Queries is copied by reference from its related query; this means that ColdFusion MX does not create a new query when you create a Query of Queries. It also means that changes to a Query of Queries, such as ordering, modifying, and deleting data, are also applied to the base query object.

If you do not want the original query to change, use the Duplicate function to create a copy and create the Query of Queries using the copied query.

Managing complex objects

You cannot use Query Of Queries on a record set that contains complex objects, such as arrays and structures.

Note: You can store a record set in a complex objects.
Previous


Managing LDAP Directories

CFML applications use the cfldap tag to access and manage LDAP (Lightweight Directory Access Protocol) directories. This chapter provides information on how to use this tag to view, query, and update LDAP directories.

This chapter teaches you how to query and update an LDAP database. It does not assume that you are familiar with LDAP, and provides an introduction to LDAP directories and the LDAP protocol. However, it does assume that you have information on your LDAP database’s structure and attributes, and it does not explain how to create an LDAP directory or manage a directory server. To learn more about LDAP and LDAP servers, see your LDAP server documentation and published books on LDAP.

The examples in this chapter use the Airius sample LDAP database that is supplied with the Netscape and iPlanet Directory Servers.

Contents

About LDAP

The LDAP information structure

Using LDAP with ColdFusion

Querying an LDAP directory

Updating an LDAP directory

Advanced topics
Next


About LDAP

The LDAP protocol enables organizations to arrange and access directory information in a hierarchy. In this context, directory refers to a collection of information, such as a telephone directory, not a collection of files in a folder on a disk drive.

LDAP originated in the mid-1990s as a response to the need to access ISO X.500 directories from personal computers that had limited processing power. Since then, products such as iPlanet Server have been developed that are native LDAP directory servers. Several companies now provide LDAP access to their directory servers, including Novell NDS, Microsoft Active Directory Services (ADS), Lotus Domino, and Oracle.

An LDAP directory is typically a hierarchically structured database. Each layer in the hierarchy typically corresponds to a level of organizational structure.

The following example shows a simple directory structure:

An example of an LDAP hierarchically structured database.

This example is fully symmetrical: all the entries at each layer are of the same type.

You can also structure an LDAP directory so that the layers under one entry contain different information from the layers under another entry.

The following figure show such an asymmetric directory:

An asymemetrical LDAP database.

In this directory structure, the second level of the tree divides the directory into two organizational units: people and groups. The third level contains entries with information that is specific to the organizational unit. Each person’s entry includes a name, e-mail address, and telephone number. Each group’s entry includes the names of group members.

This complexity and flexibility is a key to LDAP's usefulness. With it, you can represent any organizational structure.

LDAP offers performance advantages over conventional databases for accessing hierarchical, directory-like information that is read frequently and changed infrequently.

Although LDAP is often used for e-mail, address, telephone, or other organizational directories, it is not limited to these types of applications. For example, you can store ColdFusion MX Advanced Security information in an LDAP database.


The LDAP information structure

The following sections describe the LDAP information structure: the elements of an LDAP directory and how they are structured. These sections describe the following basic LDAP concepts:

  • Entry
  • Attribute
  • Distinguished name (DN)
  • Schema, including the object class and attribute type

Entry

The basic information object of LDAP is the entry. An entry is composed of one or more attributes. Entries are subject to content rules defined by the directory schema (see Schema).

Each node, not just the terminal nodes, of an LDAP directory is an entry. In the preceding figures, each item is an entry. For example, in the first diagram, both USA and Ferrari are entries. The USA entry’s attributes could include a Language attribute, and the Ferrari entry could include an entry for the chief executive officer.

Attribute

An LDAP directory entry consists of one or more attributes. Attributes have types and values. The type determines the information that the values can contain. The type also specifies how the value is processed. For example, the type determines whether an attribute can have multiple values. The mail attribute type, which contains an e-mail address, is multivalued so you can store multiple e-mail addresses for one person.

Some commonly-used attribute types have short keyword type names. Often these correspond to longer type names, and the two names can be used interchangeably. The following table lists common attribute type keywords used in LDAP directories:

Keyword | Long name | Comment
c | CountryName |
st | stateOrProvinceName |
l | LocalityName | Typically, city, but can be any geographical unit
street | StreetAddress |
o | OrganizationName |
ou | OrganizationalUnitName |
cn | CommonName | Typically, first and last name
sn | SurName |
dc | domaincomponent |
mail | mail | E-mail address

For more information, see Attribute type.

Distinguished name (DN)

An entry’s distinguished name uniquely identifies it in the directory. A DN is made up of relative distinguished names (RDNs). An RDN identifies the entry among the children of its parent entry. For example, in the first figure in About LDAP, the RDN for the Ferrari entry is "o=Ferrari".

An entry’s DN consists of an entry’s RDN followed by the DN of its parent. In other words, it consists of the RDNs for the entry and each of the entry’s parent entries, up to the root of the directory tree. The RDNs are separated by commas and optional spaces. For example, in the first figure, the DN for the Ferrari entry is "o=Ferrari, c=Italy".

As with file system pathnames and URLs, entering the correct LDAP name format is essential to successful search operations.

Note: The RDN is an attribute of a directory entry. The full DN is not. However, you can output the full DN by specifying "dn" in a query’s attributes list. For more information, see cfldap in CFML Reference. ColdFusion always returns DNs with spaces after the commas.

A multivalued RDN is made up of more than one attribute-value pair. In multivalued RDNs, the attribute-value pairs are separated by plus signs (+). In the sample directories, individuals could have complex RDNs consisting of their common name and their e-mail address; for example, "cn=Robert Boyd + mail=rjboyd@macromedia.com".

Schema

The concepts of schemas and object classes are central to a thorough understanding of LDAP. Although detailed descriptions of them are beyond the scope of this chapter, the following sections provide enough information to use the cfldap tag effectively.

A directory schema is a set of rules that determines what can be stored in a directory. It defines, at a minimum, the following two basic directory characteristics:

  • The object classes to which entries can belong
  • The directory attribute types

Object class

Object classes enable LDAP to group related information. Frequently, an object class corresponds to a real object or concept, such as a country, person, room, or domain (in fact, these are all standard object type names). Each entry in an LDAP directory must belong to one or more object classes.

The following characteristics define an object class:

  • The class name
  • A unique object ID that identifies the class
  • The attribute types that entries of the class must contain
  • The attribute types that entries of the class can optionally contain
  • (Optional) A superior class from which the class is derived

If an entry belongs to a class that derives from another class, the entry’s objectclass attribute lists the lowest-level class and all the superior classes from which the lowest-level class derives.

When you add, modify, or delete a directory entry, you must treat the entry’s object class as a possibly multivalued attribute. For example, when you add a new entry, you specify the object class in the cfldap tag attributes attribute. To retrieve an entry’s object class names, specify "objectclass" in the list of query attributes. To retrieve entries that provide a specific type of information, you can use the object class name in the cfldap tag filter attribute.

Attribute type

A schema’s attribute type specification defines the following properties:

  • The attribute type name
  • A unique object ID that identifies the attribute type
  • (Optional) An indication of whether the type is single-valued or multivalued (the default is multivalued)
  • The attribute syntax and matching rules (such as case sensitivity)

The attribute type definition can also determine limits on the range or size of values that the type represents, or provide an application-specific usage indicator. For standard attributes, a registered numeric ID specifies the syntax and matching rule information. For more information on attribute syntaxes, see ETF RFC 2252 at http://www.ietf.org/rfc/rfc2252.txt.

Operational attributes, such as creatorsName or modifyTimeStamp, are managed by the directory service and cannot be changed by user applications.


Using LDAP with ColdFusion

The cfldap tag extends the ColdFusion query capabilities to LDAP network directory services. The cfldap tag lets you use LDAP in many ways, such as the following:

  • Create Internet White Pages so users can locate people and resources and get information about them.
  • Provide a front end to manage and update directory entries.
  • Build applications that incorporate data from directory queries in their processes.
  • Integrate applications with existing organizational or corporate directory services.

The cfldap tag action attribute supports the following operations on LDAP directories:

Action | Description
query | Returns attribute values from a directory.
add | Adds an entry to a directory.
modify | Adds, deletes, or changes the value of an attribute in a directory entry.
delete | Deletes an entry from a directory.
modifyDN | Renames a directory entry (changes its distinguished name).

The following table lists the attributes that are required and optional for each action. For more information on each attribute, see the cfldap tag in CFML Reference.

Action | Required attributes | Optional attributes
query | server, name, start, attributes | port, username, password, timeout, secure, rebind, referral, scope, filter, sort, sortControl startRow, maxRows, separator, delimiter
add | server, dn, attributes | port, username, password, timeout, secure, rebind, referral, separator, delimiter
modify | server, dn, attributes | port, username, password, timeout, secure, rebind, referral, modifyType, separator, delimiter
modifyDN | server, dn, attributes | port, username, password, timeout, secure, rebind, referral
delete | server, dn | port, username, password, timeout, secure, rebind, referral


Querying an LDAP directory

The cfldap tag lets you search an LDAP directory. The tag returns a ColdFusion query object with the results, which you can use as you would any query result. When you query an LDAP directory, you specify the directory entry where the search starts and the attributes whose values to return. You can specify the search scope and attribute content filtering rules and use other attributes to further control the search.

This section describes the following topics:

  • Scope
  • Search filter
  • Getting all the attributes of an entry
  • Example: querying an LDAP directory

Scope

The search scope sets the limits of a search. The default scope is the level below the distinguished name specified in the start attribute. This scope does not include the entry identified by the start attribute. For example, if the start attribute is "ou=support, o=macromedia" the level below support is searched. You can restrict a query to the level of the start entry, or extend it to the entire subtree below the start entry.


Search filter

The search filter syntax has the form attribute operator value. The default filter, objectclass=*, returns all entries in the scope.

The following table lists the filter operators:

Operator | Example | Matches
=* | (mail=*) | All entries that contain a mail attribute.
= | (o=macromedia) | Entries in which the organization name is macromedia.
~= | (sn~=Hansen) | Entries with a surname that approximates Hansen. The matching rules for approximate matches vary among directory vendors, but anything that "sounds like" the search string should be matched. In this example, the directory server might return entries with the surnames Hansen and Hanson.
>= | (st>=ma) | The name "ma" and names appearing after "ma" in an alphabetical state attribute list.
<= | (st<=ma) | The name "ma" and names appearing before "ma" in an alphabetical state attribute list.
* | (o=macro*) | Organization names that start with "macro".
 | (o=*media) | Organization names that end with "media".
 | (o=mac*ia) | Organization names that start with "mac" and end with "ia". You can use more than one * operator in a string; for example, m*ro*dia.
 | (o=*med*) | Organization names that contain the string "med", including the exact string match "med".
& | (&(o=macromedia) (co=usa)) | Entries in which the organization name is "macromedia" and the country is "usa".
| | (|(o=macromedia) (sn=macromedia) (cn=macromedia)) | Entries in which the organization name is "macromedia" or the surname is "macromedia", or the common name is "macromedia".
! | (!(STREET=*)) | Entries that do not contain a StreetAddress attribute.

The Boolean operators & and | can operate on more than two attributes and precede all of the attributes on which they operate. You surround a filter with parentheses and use parentheses to group conditions.

If the pattern that you are matching contains an asterisk, left parenthesis, right parenthesis, backslash, or NUL character, you must use the following three-character escape sequence in place of the character:

Character | Escape sequence
* | \2A
( | \28
) | \29
\ | \5C
NUL | \00

For example, to match the common name St*r Industries, use the filter
(cn=St\2Ar Industries).

LDAP v3 supports an extensible match filter that permits server-specific matching rules. For more information on using extensible match filters, see your LDAP server documentation.

Searching and sorting notes

  • To search for multiple values of a multivalued attribute type, use the & operator to combine expressions for each attribute value. For example, to search for an entry in which cn=Robert Jones and cn=Bobby Jones, specify the following filter:
    filter="(&(cn=Robert Jones)(cn=Bobby Jones))"
  • You can use object classes as search filter attributes; for example, you can use the following search filter:
    filter="(objectclass=inetorgperson)"
  • To specify how query results are sorted, use the sort field to identify the attribute(s) to sort. By default, ColdFusion returns sorted results in case-sensitive ascending order. To specify descending order, case-insensitive sorting, or both, use the sortControl attribute.
  • ColdFusion requests the LDAP server to do the sorting. This can have the following effects:
    • The sort order might differ between ColdFusion MX and previous versions.
    • If you specify sorting and the LDAP server does not support sorting, ColdFusion generates an error. To sort results from servers that do not support sorting, use a query of queries on the results.
  • If you use filter operators to construct sophisticated search criteria, performance might degrade if the LDAP server is slow to process the synchronous search routines that cfldap supports. You can use the cfldap tag timeout and maxRows attributes to control the apparent performance of pages that perform queries, by limiting the number of entries and by exiting the query if the server does not respond in a specified time.


Getting all the attributes of an entry

Typically, you do not use a query that gets all the attributes in an entry. Such a query would return attributes that are used only by the directory server. However, you can get all the attributes by specifying attributes="*" in your query.

If you do this, ColdFusion returns the results in a structure in which each element contains a single attribute name-value pair. The tag does not return a query object. ColdFusion does this because LDAP directory entries, unlike the rows in a relational table, vary depending on their object class.

For example, the following code retrieves the contents of the Airius directory:

<cfldap name="GetList"
    server=#myServer#
    action="query"
    attributes="*"
    scope="subtree"
    start="o=airius.com"
    sort="sn,cn">

This tag returns entries for all the people in the organization and entries for all the groups. The group entries have a different object class, and therefore different attributes from the person entries. If ColdFusion returned both types of entries in one query object, some rows would have only the group-specific attribute values and the other rows would have only person-specific attribute values. Instead, ColdFusion returns a structure in which each attribute is an entry.


Example: querying an LDAP directory

The following example uses the cfldap tag to get information about the people in the Airius corporation’s Santa Clara office. Users can enter all or part of a person’s name and get a list of matching names with their departments, e-mail addresses, and telephone numbers.

This example uses the sample Airius corporate directory that is distributed with the Netscape Directory Server. If you do not have access to this directory, modify the code to work with your LDAP directory.

To query an LDAP directory:

  1. Create a file that looks like the following:
    <!--- This example shows the use of CFLDAP --->
<html>
<head> <title>cfldap Query Example</title> </head>

<h3>cfldap Query Example</h3>

<body>
<p>This tool queries the Airius.com database to locate all people in
    the company's Santa Clara office whose common names contain the
    text entered in the form.</p>

<p>Enter a full name, first name, last name, or name fragment.</p>

<form action="cfldap.cfm" method="POST">
    <input type="text" name="name"><br><br>
    <input type="submit" value="Search">
</form>

<!--- make the LDAP query --->
<!-- Note that some search text is required.
    A search filter of cn=** would cause an error -->
<cfif (isdefined("form.name") AND (form.name IS NOT ""))>
    <cfldap
        server="ldap.airius.com"
        action="query"
        name="results"
        start="ou=People, o=Airius.com"
        scope="onelevel"
        filter="(&(cn=*#form.Name#*)(l=Santa Clara))"
        attributes="cn,sn,ou,mail,telephonenumber"
        sort="ou,sn"
        maxrows=100
        timeout=20000
    >

<!--- Display results --->
    <table border=0 cellspacing=2 cellpadding=2>
     <tr>
            <th colspan=4><cfoutput>#results.RecordCount# matches found</cfoutput>
            </th>
     </tr>
     <tr>
            <th>Name</th>
            <th>Department</th>
            <th>E-Mail</th>
            <th>Phone</th>
     </tr>
    <cfoutput query="results">
     <tr>
            <td>#cn#</td>
            <td>#listFirst(ou)#</td>
            <td><a href="mailto:#mail#">#mail#</a></td>
            <td>#telephonenumber#</td>
     </tr>
    </cfoutput>
    </table>
</cfif>

</body>
</html>
  2. Change the server attribute from ldap.airius.com to the name of your installation of the Airius database.
  3. Save the page as cfldap.cfm and run it in your browser.

Reviewing the code

The following table describes the code:

Code

Description

<form action="cfldap.cfm" method="POST">
<input type="text" name="name">
<br><br>
<input type="submit" value="Search">
</form>

Uses a form to get the name or name fragment to search for.

<cfif (isdefined("form.name")
    AND (form.name IS NOT ""))>

Ensures that the user has submitted the form. This is necessary because the form page is also the action page. Ensures that the user entered search text.

<cfldap
  server="ldap.airius.com"
  action="query"
  name="results"
  start="ou=People, o=Airius.com"
   scope="onelevel"

  filter="(&(cn=*#form.Name#*)
    (l=Santa Clara))"

  attributes="cn,sn,ou,mail,
    telephonenumber"

  sort="ou,sn"

  maxrows=100
  timeout=20000
>

Connects anonymously to LDAP server ldap.airius.com, query the directory, and return the results to a query object named results.

Starts the query at the directory entry that has the distinguished name ou=People, o=Airius.com, and searches the directory level immediately below this entry.

Requests records for entries that contain the location (l) attribute value "Santa Clara" and the entered text in the common name attribute.

Gets the common name, surname, organizational unit, e-mail address, and telephone number for each entry.

Sorts the results first by organization name, then by surname. Sorts in the default sorting order.

Limit the request to 100 entries. If the server does not return the data in 20 seconds, generates an error indicating that LDAP timed out.

<table border=0 cellspacing=2
    cellpadding=2>
  <tr>
    <th colspan=4>
      <cfoutput>#results.RecordCount#
         matches found</cfoutput>
    </th>
  </tr>
  <tr>
    <th>Name</th>
    <th>Department</th>
    <th>E-Mail</th>
    <th>Phone</th>
  </tr>
  <cfoutput query="results">
  <tr>
    <td>#cn#</td>
    <td>#ListFirst(ou)#</td>
    <td><a href="mailto:#mail#">#mail#
    </a></td>
    <td>#telephonenumber#</td>
  </tr>
  </cfoutput>
 </table>
</cfif>

Starts a table to display the output

Displays the number of records returned.

Displays the common name, department, e-mail address, and telephone number of each entry.

Displays only the first entry in the list of organizational unit values. (For more information, see the description that follows this table.)

This search shows the use of a logical AND statement in a filter. It returns one attribute, the surname, that is used only for sorting the results.

In this query, the ou attribute value consists of two values in a comma-delimited list. One is the department name. The other is People. This is because the Airius database uses the ou attribute type twice:

  • In the distinguished names, at the second level of the directory tree, where it differentiates between organizational units such as people, groups, and directory servers
  • As the department identifier in each person’s entry

Because the attribute values are returned in order from the person entry to the directory tree root, the ListFirst function extracts the person’s department name.


Updating an LDAP directory

The cfldap tag lets you do the following to LDAP directory entries:

  • Add
  • Delete
  • Add attributes
  • Delete attributes
  • Replace attributes
  • Change the DN (rename the entry)

These actions let you manage LDAP directory contents remotely.

The following sections show how to build a ColdFusion page that lets you manage an LDAP directory:

  • Adding a directory entry
  • Deleting a directory entry
  • Updating a directory entry

The form displays directory entries in a table and includes a button that lets you populate the form fields based on the unique user ID.

The example ColdFusion page does not add or delete entry attributes or change the DN. The sections Adding and deleting attributes of a directory entry and Changing a directory entry’s DN describe these operations.

To keep the code short, this example has limitations that are not appropriate in a production application. In particular, it has the following limitations:

  • If you enter an invalid user ID and click either the Update or the Delete button, ColdFusion generates a "No such object" error, because there is no directory entry to update or delete. Your application should verify that the ID exists in the directory before it tries to change or delete its entry.
  • If you enter a valid user ID in an empty form and click Update, the application deletes all the attributes for the User. The application should ensure that all required attribute fields contain valid entries before updating the directory.


Adding a directory entry

When you add an entry to an LDAP directory, you specify the DN, all the required attributes, including the entry’s object class, and any optional attributes. The following example builds a form that adds an entry to an LDAP directory.

To add an entry:

  1. Create a file that looks like the following:
    <!--- set the LDAP server ID, user name, and password as variables
    here so they can be changed in only one place --->
<cfset myServer="ldap.myco.com">
<cfset myUserName="cn=Directory Manager">
<cfset myPassword="password">

<!--- Initialize the values used in form fields to empty strings --->
<cfparam name="fullNameValue" default="">
<cfparam name="surnameValue" default="">
<cfparam name="emailValue" default="">
<cfparam name="phoneValue" default="">
<cfparam name="uidValue" default="">

<!---When the form is submitted, add the LDAP entry --->
<cfif isdefined("Form.action") AND Trim(Form.uid) IS NOT "">
    <cfif Form.action is "add">
        <cfif Trim(Form.fullName) is "" OR Trim(Form.surname) is ""
            OR Trim(Form.email) is "" OR Trim(Form.phone) is "">
                <h2>You must enter a value in every field.</h2>
                <cfset fullNameValue=Form.fullName>
                <cfset surnameValue=Form.surname>
                <cfset emailValue=Form.email>
                <cfset phoneValue=Form.phone>
                <cfset uidValue=Form.uid>
        <cfelse>
            <cfset attributelist="objectclass=top, person,
                    organizationalperson, inetOrgPerson;
                cn=#Trim(Form.fullName)#; sn=#Trim(Form.surname)#;
                mail=#Trim(Form.email)#;
                telephonenumber=#Trim(Form.phone)#;
                ou=Human Resources;
                uid=#Trim(Form.uid)#">
            <cfldap action="add"
                attributes="#attributeList#"
                dn="uid=#Trim(Form.uid)#, ou=People, o=Airius.com"
                server=#myServer#
                username=#myUserName#
                password=#myPassword#>
            <cfoutput><h3>Entry for User ID #Form.uid# has been added</h3>
            </cfoutput>
        </cfif>
    </cfif>
</cfif>

<html>
<head>
    <title>Update LDAP Form</title>
</head>
<body>
<h2>Manage LDAP Entries</h2>

<cfform action="update_ldap.cfm" method="post">
    <table>
        <tr><td>Full Name:</td>
            <td><cfinput type="Text"
                 name="fullName"
                 value=#fullNameValue#
                 size="20"
                 maxlength="30"
                 tabindex="1"></td>
        </tr>
        <tr><td>Surname:</td>
            <td><cfinput type="Text"
                name="surname"
                Value= "#surnameValue#"
                size="20"
                maxlength="20"
                tabindex="2"></td>
        </tr>
        <tr>
            <td>E-mail Address:</td>
            <td><cfinput type="Text"
                name="email"
                value="#emailValue#"
                size="20"
                maxlength="20"
                tabindex="3"></td>
        </tr>
        <tr>
            <td>Telephone Number:</td>
            <td><cfinput type="Text"
                name="phone"
                value="#phoneValue#"
                size="20"
                maxlength="20"
                tabindex="4"></td>
        </tr>
        <tr>
            <td>User ID:</td>
            <td><cfinput type="Text"
                name="uid"
                value="#uidValue#"
                size="20"
                maxlength="20"
                tabindex="5"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="Submit"
                 name="action"
                 value="Add"
                 tabindex="8"></td>
        </tr>
    </table>
    <br>
    *All fields are required for Add<br>
</cfform>

<!---Output the user list --->
<h2>User List for the Human Resources Department</h2>
<cfldap name="GetList"
    server=#myServer#
    action="query"
    attributes="cn,sn,mail,telephonenumber,uid"
    start="o=Airius.com"
    scope="subtree"
    filter="ou=Human Resources"
    sort="sn,cn"
    sortControl="asc, nocase">

<table border="1">
    <tr>
        <th>Full Name</th>
        <th>Surname</th>
        <th>Mail</th>
        <th>Phone</th>
        <th>UID</th>
    </tr>
    <cfoutput query="GetList">
    <tr>
        <td>#GetList.cn#</td>
        <td>#GetList.sn#</td>
        <td>#GetList.mail#</td>
        <td>#GetList.telephonenumber#</td>
        <td>#GetList.uid#</td>
    </tr>
    </cfoutput>
</table>
</body>
</html>
  2. At the top of the file, change the myServer, myUserName, and myPassword variable assignments to values that are valid for your LDAP server.
  3. Save the page as update_ldap.cfm and run it in your browser.

Reviewing the code

The following table describes the code:

Code

Description

<cfset myServer="ldap.myco.com">
<cfset myUserName="cn=Directory
    Manager">
<cfset myPassword="password">

Initializes the LDAP connection information variables. Uses variables for all connection information so that any changes have to be made in only one place.

<cfparam name="fullNameValue"
    default="">
<cfparam name="surnameValue"
    default="">
<cfparam name="emailValue"
    default="">
<cfparam name="phoneValue"
    default="">
<cfparam name="uidValue" default="">

Sets the default values of empty strings for the form field value variables. The data entry form uses cfinput fields with value attributes so that the form can be prefilled and so that, if the user submits an incomplete form, ColdFusion can retain any entered values in the form when it redisplays the page.

<cfif isdefined("Form.action") AND Trim(Form.uid) IS NOT "">

Ensures that the user entered a User ID in the form.

<cfif Form.action is "add">

If the user clicks Add, processes the code that follows.

<cfif Trim(Form.fullName) is ""
    OR Trim(Form.surname) is ""
    OR Trim(Form.email) is ""
    OR Trim(Form.phone) is "">
        <h2>You must enter a value in every
            field.</h2>
        <cfset fullNameValue=
            Form.fullName>
        <cfset surnameValue=
            Form.surname>
        <cfset emailValue=Form.email>
        <cfset phoneValue=Form.phone>
        <cfset uidValue=Form.uid>

If any field in the submitted form is blank, display a message and set the other form fields to display data that the user submitted.

<cfelse>
    <cfset attributelist=
        "objectclass=top,person,
            organizationalperson,
            inetOrgPerson;
        cn=#Trim(Form.fullName)#;
        sn=#Trim(Form.surname)#;
        mail=#Trim(Form.email)#;
            telephonenumber=
        #Trim(Form.phone)#;
        ou=Human Resources;
        uid=#Trim(Form.uid)#">

If the user entered data in all fields, sets the attributelist variable to specify the entry’s attributes, including the object class and the organizational unit (in this case, Human Resources).

The Trim function removes leading or trailing spaces from the user data.

    <cfldap action="add"
        attributes="#attributeList#"
        dn="uid=#Trim(Form.uid)#,
        ou=People, o=Airius.com"
        server=#myServer#
        username=#myUserName#
        password=#myPassword#>
    <cfoutput><h3>Entry for User ID
        #Form.uid# has been added</h3>
    </cfoutput>
</cfif>
</cfif>
</cfif>

Adds the new entry to the directory.

<cfform action="update_ldap.cfm"
         method="post">
    <table>
        <tr><td>Full Name:</td>
            <td><cfinput type="Text"
                 name="fullName"
                 value=#fullNameValue#
                 size="20"
                 maxlength="30"
                 tabindex="1"></td>
        </tr>
.
.
.
        <tr><td colspan="2">
            <input type="Submit"
                 name="action"
                 value="Add"
                 tabindex="6"></td>
        </tr>
    </table>
    <br>
    *All fields are required for Add<br>
</cfform>

Outputs the data entry form, formatted as a table. Each cfinput field always has a value, set by the value attribute when the page is called. The value attribute lets ColdFusion update the form contents when the form is redisplayed after the user clicks Add. The code that handles cases in which the user fails to enter all the required data uses this feature.

<cfldap name="GetList"
    server=#myServer#
    action="query"
    attributes="cn,sn,mail,
        telephonenumber,uid"
    start="o=Airius.com"
    scope="subtree"
    filter="ou=Human Resources"
    sort="sn,cn"
    sortControl="asc, nocase">

Queries the directory and gets the common name, surname, e-mail address, telephone number, and user ID from the matching entries.

Searches the subtree from the entry with the DN of o=Airius.com, and selects all entries in which the organizational unit is Human Resources.

Sorts the results by surname and then common name (to sort by last name, then first). Sorts in default ascending order that is not case-sensitive.

<table border="1">
    <tr>
    <th>Full Name</th>
    <th>Surname</th>
    <th>Mail</th>
    <th>Phone</th>
    <th>UID</th>
    </tr>
    <cfoutput query="GetList">
    <tr>
    <td>#GetList.cn#</td>
    <td>#GetList.sn#</td>
    <td>#GetList.mail#</td>
    <td>#GetList.telephonenumber#</td>
    <td>#GetList.uid#</td>
    </tr>
    </cfoutput>
</table>
</body>
</html>

Display the query results in a table.


Deleting a directory entry

To delete a directory entry, you must specify the entry DN.

The following example builds on the code that adds an entry. It adds Retrieve and Delete buttons. The Retrieve button lets you view a user’s information in the form before you delete it.

To delete an entry:

  1. Open update_ldap.cfm, which you created in Adding a directory entry.
  2. Between the first and second </ cfif > tags, add the following code:
    <cfelseif Form.action is "Retrieve">
    <cfldap name="GetEntry"
        server=#myServer#
        action="query"
        attributes="cn,sn,mail,telephonenumber,uid"
        scope="subtree"
        filter="uid=#Trim(Form.UID)#"
        start="o=Airius.com">
    <cfset fullNameValue = GetEntry.cn[1]>
    <cfset surnameValue = GetEntry.sn[1]>
    <cfset emailValue = GetEntry.mail[1]>
    <cfset phoneValue = GetEntry.telephonenumber[1]>
    <cfset uidValue = GetEntry.uid[1]>
<cfelseif Form.action is "Delete">
    <cfldap action="delete"
        dn="uid=#Trim(Form.UID)#, ou=People, o=Airius.com"
        server=#myServer#
        username=#myUserName#
        password=#myPassword#>
    <cfoutput><h3>Entry for User ID #Form.UID# has been deleted
    </h3></cfoutput>
  3. At the end of the code for the Add button (the input tag with Value=Add at the bottom of the form), delete the </td> end tag.
  4. After the end of the Add button input tag, add the following code:
        &nbsp
    <input type="Submit"
         name="action"
         value="Retrieve"
         tabindex="7">
    &nbsp
    <input type="Submit"
         name="action"
         value="Delete"
         tabindex="8"></td>
  5. Save the file and run it in your browser.

Reviewing the code

The following table describes the code:

Code

Description

<cfelseif Form.action is "Retrieve">
    <cfldap name="GetEntry"
        server=#myServer#
        action="query"
        attributes="cn,sn,mail,
            telephonenumber,uid"
        scope="subtree"
        filter="uid=#Trim(Form.UID)#"
        start="o=Airius.com">
    <cfset fullNameValue=
        GetEntry.cn[1]>
    <cfset surnameValue=GetEntry.sn[1]>
    <cfset emailValue=GetEntry.mail[1]>
    <cfset phoneValue=
        GetEntry.telephonenumber[1]>
    <cfset uidValue=GetEntry.uid[1]>

If the user clicks Retrieve, queries the directory and gets the information for the specified User ID.

Sets the form field’s Value attribute to the corresponding query column.

This example uses the array index [1] to identify the first row of the GetEntry query object. Because the query always returns only one row, the index can be omitted.

<cfelseif Form.action is "Delete">
    <cfldap action="delete"
        dn="uid=#Trim(Form.UID)#,
            ou=People, o=Airius.com"
        server=#myServer#
        username=#myUserName#
        password="password">
    <cfoutput><h3>Entry for User
        ID #Form.UID# has been
        deleted</h3></cfoutput>

The user clicks delete, deletes the entry with the specified User ID and informs the user that the entry was deleted.

&nbsp
<input type="Submit"
    name="action"
    value="Retrieve"
    tabindex="7">
&nbsp
<input type="Submit"
    name="action"
    value="Delete"
    tabindex="8"></td>

Displays submit buttons for the Retrieve and Delete actions.


Updating a directory entry

The cfldap tag lets you change the values of entry attributes. To do so, you specify the entry DN in the dn attribute, and list the attributes to change and their new values in the attributes attribute.

The following example builds on the code that adds and deletes an entry. It can update one or more of an entry’s attributes. Because the UID is part of the DN, you cannot change it.

To update an entry:

  1. Open update_ldap.cfm, which you created in Adding a directory entry.
  2. Between the cfelseif Form.action is "Retrieve" block and the </ cfif > tag, add the following code:
    <cfelseif Form.action is "Update">
<cfset attributelist="cn=#Trim(form.FullName)#; sn=#Trim(Form.surname)#; mail=#Trim(Form.email)#;
    telephonenumber=#Trim(Form.phone)#">
<cfldap action="modify"
    modifytype="replace"
    attributes="#attributeList#"
    dn="uid=#Trim(Form.UID)#, ou=People, o=Airius.com"
    server=#myServer#
    username=#myUserName#
    password=#myPassword#>
<cfoutput><h3>Entry for User ID #Form.UID# has been updated</h3>
</cfoutput>
  3. At the end of the code for the Delete button (the input tag with Value=Delete) at the bottom of the form), delete the </td> mark.
  4. After the end of the Delete button input tag, add the following code:
    &nbsp
<input type="Submit"
    name="action"
    value="Update"
    tabindex="9"></td>
  5. Save the file and run it in your browser.

Reviewing the code

The following table describes the code:

Code

Description

<cfelseif Form.action is "Update">
    <cfset attributelist="cn=#Trim
        (form.FullName)#;
        sn=#Trim(Form.surname)#;
        mail=#Trim(Form.email)#;
        telephonenumber=#Trim(Form.phone)#">
    <cfldap action="modify"
            modifytype="replace"
            attributes="#attributeList#"
                dn="uid=#Trim(Form.UID)#,
                ou=People, o=Airius.com"
            server=#myServer#
            username=#myUserName#
            password=#myPassword#>
        <cfoutput><h3>Entry for User ID
            #Form.UID# has been updated</h3>
        </cfoutput>

If the user clicks Update, sets the attribute list to the form field values and replaces the attributes for the entry with the specified UID.

Displays a message to indicate that the entry was updated.

This code replaces all of the attributes in a form, without checking whether they are blank. A more complete example would check for blank fields and either require entered data or not include the corresponding attribute in the attributes string.

&nbsp
<input type="Submit"
    name="action"
    value="Update"
    tabindex="9"></td>

Defines the Submit button for the update action.


Adding and deleting attributes of a directory entry

The following table lists the cfldap tag attributes that you must specify to add and delete LDAP attributes in an entry:

Action

cfldap syntax

Add attribute to entry

dn = "entry dn"
action = "modify"
modifyType = "add"
attributes = "attribname=attribValue[;...]"

Delete attribute from entry

dn = "entry dn"
action = "modify"
modifyType = "delete"
attributes = "attribName[;...]"

You can add or delete multiple attributes in one statement. To do this, use semicolons to separate the attributes in the attribute string.

The following example specifies the description and seealso LDAP attributes:

attributes="description=Senior Technical Writer;seealso=writers"

You can change the character that you use to separate values of multivalued attributes in an attribute string. You can also change the character that separates attributes when a string contains multiple attributes. For more information, see Specifying an attribute that includes a comma or semicolon.

You can add or delete attributes only if the directory schema defines them as optional for the entry’s object class.


Changing a directory entry’s DN

To change the DN of an entry, you must provide the following information in the cfldap tag:

dn="original DN"
action="modifyDN"
attributes="dn=new DN"

For example:

<cfldap action="modifyDN"
    dn="#old_UID#, ou=People, o=Airius.com"
    attributes="uid=#newUID#"
    server=#myServer#
    username=#myUserName#
    password=#myPassword#>

The new DN and the entry attributes must conform to the directory schema; therefore, you cannot move entries arbitrarily in a directory tree. You can only modify a leaf only. For example, you cannot modify the group name if the group has children.

Note: LDAP v2 does not let you change entry DNs.


Advanced topics

The following sections present advanced topics that enable you to use LDAP directories more effectively.

  • Specifying an attribute that includes a comma or semicolon
  • Using cfldap output
  • Viewing a directory schema
  • Referrals
  • Managing LDAP security

Specifying an attribute that includes a comma or semicolon

LDAP attribute values can contain commas. The cfldap tag normally uses commas to separate attribute values in a value list. Similarly, an attribute can contain a semicolon, which cfldap normally uses to delimit (separate) attributes in an attribute list. To override the default separator and delimiter characters, you use the cfldap tag separator and delimiter attributes.

For example, assume you want to add the following attributes to an LDAP entry:

cn=Proctor, Goodman, and Jones
description=Friends of the company; Rationalists

Use the cfldap tag in the following way:

<cfldap action="modify"
    modifyType="add"
    attributes="cn=Proctor, Goodman, and Jones: description=Friends
of the company; Rationalists"
    dn="uid=goodco, ou=People, o=Airius.com"
    separator="&"
    delimiter=":"
    server=#myServer#
    username=#myUserName#
    password=#myPassword#>


Using cfldap output

You can create a searchable Verity collection from LDAP data. For an example of building a Verity collection using an LDAP directory, see Indexing query results obtained from an LDAP directory.

The ability to generate queries from other queries is very useful when cfldap queries return complex data. For more information on querying queries, see Using Query of Queries.


Viewing a directory schema

LDAP v3 exposes a directory's schema information in a special entry in the root DN. You use the directory root subschemaSubentry attribute to access this information.

The following ColdFusion query shows how to get and display the directory schema. It displays information from the schema’s object class and attribute type definitions. For object classes, it displays the class name, superior class, required attribute types, and optional attribute types. For attribute types, it displays the type name, type description, and whether the type is single- or multivalued.

The example does not display all the information in the schema. For example, it does not display the matching rules. It also does not display the object class IDs, attribute type IDs, attribute type syntax IDs, or the object class descriptions. (The object class description values are all "Standard Object Class.")

Note: To be able to view the schema for an LDAP server, the server must support LDAP v3.

This example does not work on iPlanet Directory Server 5.0. It does work on a 4.x server.

To view the schema for an LDAP directory:

  1. Create a new file that looks like the following:
    <html>
<head>
    <title>LDAP Schema</title>
</head>

<body>
<!--- Start at Root DSE to get the subschemaSubentry attribute --->
<cfldap
    name="EntryList"
    server="ldap.mycorp.com"
    action="query"
    attributes="subschemaSubentry"
    scope="base"
    start="">

<!--- Use the DN from the subschemaSubEntry attribute to get the schema --->
<cfldap
    name="EntryList2"
    server="ldap.mycorp.com"
    action="query"
    attributes="objectclasses, attributetypes"
    scope="base"
    filter="objectclass=*"
    start=#entryList.subschemaSubentry#>

<!--- Only one record is returned, so query loop is not required --->
<h2>Object Classes</h2>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Superior class</th>
        <th>Must have</th>
        <th>May have</th>
    </tr>
    <cfloop index = "thisElement" list = #Entrylist2.objectclasses#>
        <cfscript>
            thiselement = Trim(thisElement);
            nameloc = Find("NAME", thisElement);
            descloc = Find("DESC", thisElement);
            suploc = Find("SUP", thisElement);
            mustloc = Find("MUST", thisElement);
            mayloc = Find("MAY", thisElement);
            endloc = Len(thisElement);
        </cfscript>
        <tr>
            <td><cfoutput>#Mid(thisElement, nameloc+6, descloc-nameloc-8)#
                </cfoutput></td>
            <cfif #suploc# NEQ 0>
                <td><cfoutput>#Mid(thisElement, suploc+5, mustloc-suploc-7)#
                </cfoutput></td>
            <cfelse>
                <td>NONE</td>
            </cfif>
            <cfif #mayloc# NEQ 0>
                <td><cfoutput>#Replace(Mid(thisElement, mustloc+6,
                    mayloc-mustloc-9), " $ ", ", ", "all")#</cfoutput></td>
                <td><cfoutput>#Replace(Mid(thisElement, mayloc+5, endloc-mayloc-8),
                    " $ ", ", ", "all")#</cfoutput></td>
            <cfelse>
                <td><cfoutput>#Replace(Mid(thisElement, mustloc+6,
                    endloc-mustloc-9), " $ ", ", ", "all")#</cfoutput></td>
                <td>NONE</td>
            </cfif>
        </tr>
    </cfloop>
</table>
<br><br>

    <h2>Attribute Types</h2>
<table border="1" >
    <tr>
        <th>Name</th>
        <th>Description</th>
        <th>multivalued?</th>
    </tr>
    <cfloop index = "thisElement"
        list = #ReplaceNoCase(EntryList2.attributeTypes, ", alias", "<br> Alias",
        "all")# delimiters = ",">
        <cfscript>
            thiselement = Trim(thisElement);
            nameloc = Find("NAME", thisElement);
            descloc = Find("DESC", thisElement);
            syntaxloc = Find("SYNTAX", thisElement);
            singleloc = Find("SINGLE", thisElement);
            endloc = Len(thisElement);
        </cfscript>
        <tr>
            <td><cfoutput>#Mid(thisElement, nameloc+6, descloc-nameloc-8)#
                </cfoutput></td>
            <td><cfoutput>#Mid(thisElement, descloc+6, syntaxloc-descloc-8)#
                </cfoutput></td>
            <cfif #singleloc# EQ 0>
                 <td><cfoutput>Yes</cfoutput></td>
            <cfelse>
                 <td><cfoutput>No</cfoutput></td>
            </cfif>
        </tr>
    </cfloop>
</table>
</body>
</html>
  2. Change the server from ldap.mycorp.com to your LDAP server. You might also need to specify a user ID and password in the cfldap tag.
  3. Save the template as ldapschema.cfm in myapps under your web root directory and view it in your browser.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfldap
    name="EntryList"
    server="ldap.mycorp.com"
    action="query"
    attributes="subschemaSubentry"
    scope="base"
    start="">

Gets the value of the subschemaSubentry attribute from the root of the directory server. The value is the DN of the schema.

<cfldap
    name="EntryList2"
    server="ldap.mycorp.com"
    action="query"
    attributes="objectclasses,
        attributetypes"
    scope="base"
    filter="objectclass=*"
    start=#entryList.subschemaSubentry#>

Uses the schema DN to get the objectclasses and attributetypes attributes from the schema.

<h2>Object Classes</h2>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Superior class</th>
        <th>Must have</th>
        <th>May have</th>
    </tr>
    <cfloop index = "thisElement" list =
            #Entrylist2.objectclasses#>
        <cfscript>
            thisElement = Trim(thisElement);
            nameloc = Find("NAME",
                thisElement);
            descloc = Find("DESC",
                thisElement);
            suploc = Find("SUP", thisElement);
            mustloc = Find("MUST",
                thisElement);
            mayloc = Find("MAY", thisElement);
            endloc = Len(thisElement);
        </cfscript>

Displays the object class name, superior class, required attributes, and optional attributes for each object class in a table.

The schema contains the definitions of all object classes in a comma delimited list, so the code uses a list type cfloop tag.

The thisElement variable contains the object class definition. Trim off any leading or trailing spaces, then use the class definition field keywords in Find functions to get the starting locations of the required fields, including the Object class ID. (The ID is not displayed.)

Gets the length of the thisElement string for use in later calculations.

        <tr>
            <td><cfoutput>#Mid(thisElement,
                nameloc+6, descloc-nameloc-8)
                #</cfoutput></td>
            <cfif #suploc# NEQ 0>
                <td><cfoutput>#Mid(thisElement,
                suploc+5, mustloc-suploc-7)#
                </cfoutput></td>
            <cfelse>
                <td>NONE</td>
            </cfif>
            <cfif #mayloc# NEQ 0>
             <td><cfoutput>#Replace
                (Mid(thisElement, mustloc+6,
                mayloc-mustloc-9), " $ ", ", ",
                "all")#</cfoutput></td>
             <td><cfoutput>#Replace
                (Mid(thisElement, mayloc+5,
                endloc-mayloc-8), " $ ", ", ",
                "all")#</cfoutput></td>
            <cfelse>
             <td><cfoutput>#Replace
                (Mid(thisElement, mustloc+6,
                endloc-mustloc-9), " $ ", ", ",
                "all")#</cfoutput></td>
             <td>NONE</td>
            </cfif>
        </tr>
    </cfloop>
</table>

Displays the field values. Uses the Mid function to extract individual field values from the thisElement string.

The top object class does not have a superior class entry. Handles this special case by testing the suploc location variable. If the value is not 0, handles normally, otherwise, output "NONE".

There might not be any optional attributes. Handles this case similarly to the superior class. The calculation of the location of required attributes uses the location of the optional attributes if the field exists; otherwise, uses the end of the object class definition string.

    <h2>Attribute Types</h2>
    <table border="1" >
        <tr>
            <th>Name</th>
            <th>Description</th>
            <th>Multivalued?</th>
        </tr>
        <cfloop index = "thisElement" list =
             #ReplaceNoCase(attributeTypes, ",
             alias", "<br> Alias", "all")#
             delimiters = ",">
            <cfscript>
             thiselement = Trim(thisElement);
             nameloc = Find("NAME",
                thisElement);
             descloc = Find("DESC",
                thisElement);
             syntaxloc = Find("SYNTAX",
                thisElement);
             singleloc = Find("SINGLE",
                thisElement);
             endloc = Len(thisElement);
            </cfscript>
        <tr>
            <td><cfoutput>#Mid(thisElement,
                nameloc+6, descloc-nameloc-8)#
                </cfoutput></td>
            <td><cfoutput>#Mid(thisElement,
                descloc+6, syntaxloc-descloc-8)
                #</cfoutput></td>
            <cfif #singleloc# EQ 0>
                 <td><cfoutput>Yes</cfoutput>
                </td>
            <cfelse>
                 <td><cfoutput>No</cfoutput>
                </td>
            </cfif>
        </tr>
    </cfloop>
</table>
</cfloop>

Does the same types of calculations for the attribute types as for the object classes.

The attribute type field can contain the text ", alias for....". This text includes a comma, which also delimits attribute entries. Use the ReplaceNoCase function to replace any comma that precedes the word "alias" with an HTML <br> tag.

The attribute definition includes a numeric syntax identifier, which the code does not display, but uses its location in calculating the locations of the other fields.


Referrals

An LDAP database can be distributed over multiple servers. If the requested information is not on the current server, the LDAP v3 standard provides a mechanism for the server to return a referral to the client that informs the client of an alternate server. (This feature is also included in some LDAP v2-compliant servers.)

ColdFusion can handle referrals automatically. If you specify a nonzero referral attribute in the cfldap tag, ColdFusion sends the request to the server specified in the referral.

The referral attribute value specifies the number of referrals allowed for the request. For example, if the referral attribute is 1, and server A sends a referral to server B, which then sends a referral to server C, ColdFusion returns an error. If the referral attribute is 2, and server C has the information, the LDAP request succeeds. The value to use depends on the topology of the distributed LDAP directory, the importance of response speed, and the value of response completeness.

When ColdFusion follows a referral, the rebind attribute specifies whether ColdFusion uses the cfldap tag login information in the request to the new server. The default, No, sends an anonymous login to the server.


Managing LDAP security

When you consider how to implement LDAP security, you must consider server security and application security.

Server security

The cfldap tag supports secure socket layer (SSL) v2 security. This security provides certificate-based validation of the LDAP server. It also encrypts data transferred between the ColdFusion server and the LDAP server, including the user password, and ensures the integrity of data passed between the servers. To specify SSL v2 security, set the cfladap tag secure="cfssl_basic" attribute.

About LDAP Server Security

ColdFusion MX uses Java Native Directory Interface (JNDI), the LDAP provider, and an SSL package to create the client side of an SSL communication. The LDAP server provides the server side. The LDAP server that the cfldap tag connects to using SSL holds an SSL server certificate, a certificate that is securely "signed" by a trusted authority and identifies (authenticates) the sender. During the initial SSL connection, the LDAP server presents its server certificate to the client. If the client trusts this certificate, the SSL connection is established and secure LDAP communication can begin.

ColdFusion determines whether to trust the server by comparing the server’s certificate with the information in the jre/lib/security/cacerts keystore of the JRE used by ColdFusion MX. The ColdFusion MX default cacerts file contains information about many certificate granting authorities. If you must update the file with additional information, you can use the keytool utility in the ColdFusion jre/bin directory to import certificates that are in X.509 format. For example, enter the following:

keytool -import -keystore cacerts -alias ldap -file ldap.crt -keypass bl19mq

The keytool utility initial keypass password is "change it". For more information on using the keytool utility, see the Sun JDK documentation.

Once ColdFusion establishes secure communication with the server, it must provide the server with login credentials. You specify the login credentials in the cfldap tag username and password attributes. When the server determines that the login credentials are valid, ColdFusion can access the directory.

Using LDAP security

To use security, first ensure that the LDAP server supports SSL v2 security.

Specify the cfldap tag secure attribute as follows:

secure = "cfssl_basic"

For example:

<cfldap action="modify"
    modifyType="add"
    atributes="cn=Lizzie"
    dn="uid=lborden, ou=People, o=Airius.com"
    server=#myServer#
    username=#myUserName#
    password=#myPassword#
    secure="cfssl_basic"
    port=636>

The port attribute specifies the server port used for secure LDAP communications, which is 636 by default. If you do not specify a port, ColdFusion attempts to connect to the default, nonsecure, LDAP port 389.

Application security

To ensure application security, you must prevent outsiders from gaining access to the passwords that you use in cfldap tags. The best way to do this is to use variables for your username and password attributes. You can set these variables on one encrypted application page. For more information on securing applications, see Securing Applications.
Previous


Building a Search Interface

You can provide a full text search capability for documents and data sources on a ColdFusion site by enabling the Verity search engine. Verity full text search lets people visiting your site use simple one- and two-word searches to quickly find the information thFey need. You can use the more robust Verity Query Language and the Verity advanced search operators to transparently implement business-specific meaning behind searches. This allows even one word searches to return accurate results.

This chapter describes how to build a Verity search interface with which users can perform powerful searches on your site. It also describes how to index your documents and data sources so that users can search them.

Contents

About Verity

Creating a search tool for ColdFusion applications

Creating a search page

Enhancing search results

Working with data returned from a query
Next


About Verity

To efficiently search through paragraphs of text or files of varying types, you need full-text search capabilities. Macromedia ColdFusion MX includes the Verity search engine, which provides full-text indexing and searching.

The Verity engine performs searches against collections, not against the actual documents. A collection is a special database created by Verity that contains metadata that describes the documents that you have indexed. The indexing process examines documents of various types in a collection and creates a metadata description--the index--which is specialized for rapid search and retrieval operations.

The ColdFusion implementation of Verity supports collections of the following basic data types:

  • Text files such as HTML pages and CFML pages
  • Binary documents (see Supported file types)
  • Record sets returned from a query and CF query object, including: cfquery, cfldap, and cfpop queries

You can build collections from individual documents or from an entire directory tree. Collections can be stored anywhere, so you have a great deal of flexibility in accessing indexed data.

In your ColdFusion application, you can search multiple collections, each of which can focus on a specific group of documents or queries, according to subject, document type, location, or any other logical grouping. Because you can perform searches against multiple collections, you have substantial flexibility in designing your search interface.

This section describes the following topics:

  • Using Verity with ColdFusion
  • Advantages of using Verity
  • Supported file types
  • Specifying a language


Using Verity with ColdFusion

Here are some ways to use Verity with ColdFusion:

  • Index your website and provide a generalized search mechanism, such as a form interface, for executing searches.
  • Index specific directories that contain documents for subject-based searching.
  • Index specific categories of documents. By organizing your documents into categories, you can let users search specific types of documents. For example, if your website contains FAQs, documentation, and tutorials, you can create a search that lets users search within each of these categories.
  • Index cfquery record sets, giving users the ability to search against the data. Because collections contain data optimized for retrieval, this method is much faster than performing multiple database queries to return the same data.
  • Index cfldap and cfpop query results.
  • Manage and search collections generated outside of ColdFusion using native Verity tools. Collections must be registered with the Verity K2 administration service. To do this you must either use the Verity tools, or map the collection using the cfcollection tag.
  • Index e-mail generated by ColdFusion application pages and create a searching mechanism for the indexed messages.
  • Build collections of inventory data and make those collections available for searching from your ColdFusion application pages.
  • Support international users in a range of languages using the cfindex, cfcollection, and cfsearch tags.


Advantages of using Verity

Verity can index the output from queries so that you or a user can search against the record sets. Searching query results has a clear advantage over using SQL to search a database directly in speed of execution because metadata from the record sets are stored in a Verity index that is optimized for searching.

Performing a Verity search has the following advantages over other search methods:

  • You can reduce the programming overhead of query constructs by allowing users to construct their own queries and execute them directly. You need to be concerned only with presenting the output to the client web browser.
  • Verity can index database text fields, such as notes and product descriptions, that cannot be effectively indexed by native database tools.
  • When indexing collections that contain documents in formats such as Adobe Acrobat (PDF) and Microsoft Word, Verity scans for the document title (if one was entered), in addition to the document text, and displays the title in the search results list.
  • When Verity indexes web pages, it can return the URL for each document. This is a valuable document management feature.

For more information, see Indexing data returned by a query.


Supported file types

The ColdFusion Verity implementation supports a wide array of file and document types. As a result, you can index web pages, ColdFusion applications, and many binary document types and produce search results that include summaries of these documents.

Verity supports the following formats:

Document format | Format | Version(s)
Text and markup | ANSI (TXT) | All versions
 | ASCII (TXT) | All versions
 | HTML (HTM) | 3
 | IBM DCA/RFT (Revisable Form Text) (DC) | SC23-0758-1
 | Rich Text Format/WordPad (RTF) | 1 through 1.6
 | Unicode Text (TXT) | 3, 4
Word processing | Adobe Maker Interchange Format (MIF) | 5, 5.5, 6, 7
 | Applix Words (AW) | 3.11, 4.2, 4.3, 4.4, 4, 41, 4.2
 | DisplayWrite (IP) | 4
 | Folio Flat File (FFF) | 3.1
 | Fujitsu Oasys (OA2) | 7
 | JustSystems Ichitaro (JTD) | 8, 9, 10, 12
 | Lotus AMI Pro (SAM) | 2, 3
 | Lotus Word Pro (LWP) (Windows only) | 96, 97, Millennium Edition R9
 | Microsoft Word for PC (DOC) | 4, 5, 5.5, 6
 | Microsoft Word for Windows (DOC) | 1 through 2002
 | Microsoft Word for Macintosh (DOC) | 4, 5, 6, 98
 | Microsoft Works (WPS) | 1 through 2000
 | Microsoft Windows Write (WRI) | 1, 2, 3
 | WordPerfect for Windows V5 (WO) | 5, 5.1
 | WordPerfect for Windows V6 and higher (WPD) | 6, 7, 8, 10, 2000
 | WordPerfect for Macintosh | 1.02, 2, 2.1, 2.2, 3, 3.1
 | WordPerfect for Linux | 6
 | XyWrite (XY4) | 4.12
Spreadsheet formats | Applix Spreadsheets (AS) | 4.2, 4.3, 4.4
 | Comma Separated Values (CSV) | No specific version
 | Corel Quattro Pro (QPW, WB3) | 5, 6, 7, 8
 | Lotus 1-2-3 for SmartSuite (123) | 96, 97, Millennium Edition R9
 | Lotus 1-2-3 (WK4) | 2, 3, 4, 5
 | Lotus 1-2-3 Charts (123) | 2, 3, 4, 5
 | Microsoft Excel for Windows (XLS) | 2.2, 3, 4, 5, 96, 97, 2000, 2002
 | Microsoft Excel for Macintosh (XLS) | 98
 | Microsoft Excel Charts (XLS) | 2, 3, 4, 5, 6, 7
 | Microsoft Works Spreadsheet (S30,S40) | 1, 2, 3, 4
Presentation formats | Applix Presents (AG) | 4.0, 4.2, 4.3, 4.4
 | Corel Presentations (SHW) | 7, 9, 10, 11, 2000
 | Lotus Freelance Graphics for Windows (PRE) | 2, 96, 97, 98, Millennium Edition R9
 | Lotus Freelance Graphics 2 (PRE) | 2
 | Microsoft PowerPoint for Windows (PPT) | 95, 97, 2000, 2002
 | Microsoft PowerPoint for PC (PPT) | 4
 | Microsoft PowerPoint for Macintosh (PPT) | 98
 | Microsoft Project (MPP) | 98, 2000, 2002
Display formats | Adobe Portable Document Format (PDF) | 1.1 (Acrobat 2.0) to 1.4 (Acrobat 5.0)
Graphics formats supported for indexing | AutoCAD Drawing format (DWG) (standalone) (does not extract metadata) | R13, R14, and R2000
 | AutoCAD Drawing format (DXF) (standalone) (does not extract metadata) | R13, R14, and R2000
 | Computer Graphics Metafile (CGM) (embedded) | No specific version
 | Enhanced Metafile (EMF) (embedded and standalone) | No specific version
 | Lotus Pic (PIC) (standalone) | No specific version
 | Microsoft Visio (standalone) | 6
 | Tagged Image File (TIFF) (standalone) | 5
 | Windows Metafile (WMF) (embedded and standalone) | 3
Multimedia formats | MPEG-1 audio layer 3 (MP3) | ID3 versions 1 and 2
Container formats | DynaZIP | No specific version
 | PKZIP (zip) | PKWARE versions through 2.04g
 | WinZIP | No specific version
E-mail formats | Microsoft Outlook (msg) | 97, 2000, 2002
 | Microsoft Outlook Express (eml) | No specific version


Specifying a language

If you install the optional Coldfusion International Search pack, you can specify a language other than English when creating a collection.

ColdFusion supports Verity Locales in European, Asian, and Middle Eastern languages. For more information about installing Verity Locales, see Installing and Using ColdFusion MX.

For English language support, Verity provides two options: English (Basic) and English (Advanced). The default language for Verity collections is English (Basic). Indexing a collection using English (Basic) is faster than using English (Advanced), however, English (Advanced) provides better search results.

You must specify a language when you create the collection. The language you specify should match the language the documents were authored in. By specifying the language your documents are written in, Verity is able to correctly interpret accented characters, and use variations of word stems and roots. If you have documents in several languages, create separate collections for each of them.

To specify a language when you are indexing data, select the language from the drop-down list when you create a collection with the ColdFusion MX Administrator. In CFML, the cfcollection, cfindex, and cfsearch tags have an optional language attribute that you use to specify the language of the collection.

Use the following table to find the correct value for the language attribute for your collection; for example, the following code creates a collection for simplified Chinese:

<cfcollection action = "create" collection = "lei_01"
  path = "c:\CFusionMX7\verity\collections"
  language = "simplified_chinese">

The following table lists the languages names and attributes that ColdFusion supports:

Language | Language attribute
Arabic | arabic
Chinese (simplified) | simplified_chinese
Chinese (traditional) | traditional_chinese
Czech | czech
Danish | danish
Dutch | dutch
English (Basic) | english
English (Advanced) | englishx
Finnish | finnish
French | french
German | german
Greek | greek
Hebrew | hebrew
Hungarian | hungarian
Italian | italian
Japanese | japanese
Korean | korean
Norwegian | norwegian
Norwegian (Bokmal) | bokmal
Norwegian (Nynorsk) | nynorsk
Polish | polish
Portuguese | portuguese
Russian | russian
Spanish | spanish
Swedish | swedish
Turkish | turkish

You can register collections in the ColdFusion MX Administrator or by creating a collection with the cfcollection tag. If you register a given collection with ColdFusion and you specify a language attribute, you do not have to specify the language attribute when using cfindex and cfsearch tags for that collection. If you do not register a given collection with ColdFusion, ColdFusion uses English (Basic), the default language, unless you specify the language in the language attribute for the cfindex and cfsearch tags for that collection.

Note: When you search a collection in a language other than English, you must translate operators such as AND and OR into the language of the collection.


Creating a search tool for ColdFusion applications

There are three main tasks in creating a search tool for your ColdFusion application:

  1. Create a collection.
  2. Index the collection.
  3. Design a search interface.

You can perform each task programmatically--that is, by writing CFML code. Alternatively, you can use the ColdFusion MX Administrator to create and index a collection.

This chapter presents the noncoding methods for developing a search tool, followed by code examples that perform the same task.

Creating a collection with the ColdFusion MX Administrator

Use the following procedure to quickly create a collection with the ColdFusion MX Administrator:

To create a collection with the ColdFusion MX Administrator:

  1. In the ColdFusion MX Administrator, select Data & Services > Verity Collections.

    The Verity Collections page appears.

  2. Enter a name for the collection; for example, DemoDocs.
  3. Enter a path for the directory location of the new collection; for example, C:\CFusionMX7\verity\collections\.

    By default in the server configuration, ColdFusion stores collections in cf_root\verity\collections\ in Windows and in cf_root/verity/collections on UNIX. In the multiserver configuration, the default location for collections is cf_webapp_root/verity/collections. In the J2EE configuration, the default location for collections is verity_root/verity/collections, where verity_root is the directory in which you installed Verity.

    Note: This is the location for the collection, not for the files that you will search.

  4. (Optional) Select a language other than English for the collection from the Language drop-down list.

    For more information on selecting a language, see Specifying a language.

  5. (Optional) Select Enable Category Support to create a Verity Parametric collection.

    For more information on using categories, see Narrowing searches using categories.

  6. Click Create Collection.

    The name and full path of the new collection appears in the list of Verity Collections.

You have successfully created an empty collection. A collection becomes populated with data when you index it. For more information, see the next section, About indexing a collection.

About indexing a collection

In order for information to be searched, it must be indexed. Indexing extracts both meaning and structure from unstructured information by indexing each document that you specify into a separate Verity collection that contains a complete list of all the words used in a given document along with metadata about that document. Indexed collections include information such as word proximity, metadata about physical file system addresses, and URLs of documents.

When you index databases and other record sets that you generated using a query, Verity creates a collection that normalizes both the structured and unstructured data. Search requests then check these collections rather than scanning the actual documents and database fields. This provides a faster search of information, regardless of the file type and whether the source is structured or unstructured.

Just as with creating a collection, you can index a collection either programmatically or using the ColdFusion MX Administrator. Use the following guidelines to determine which method to use:

Use the Administrator | Use the cfindex tag
To index document files | To index ColdFusion query results
When the collection does not require frequent updates | When the collection requires frequent updates
To create the collection without writing any CFML code | To dynamically update a collection from a ColdFusion application page
To create a collection once | When the collection requires updating by others

You can use cfcollection action="optimize" if you notice that searches on a collection take longer than they did previously.

Updating an index

Documents are modified frequently in many user environments. After you index your documents, any changes that you make are not reflected in subsequent Verity searches until you re-index the collection. Depending on your environment, you can create a scheduled task to automatically keep your indexes current. For more information on scheduled tasks, see Configuring and Administering ColdFusion MX.

Creating a ColdFusion search tool programmatically

You can create a Verity search tool for your ColdFusion application in CFML. Although writing CFML code can take more development time than using these tools, there are situations in which writing code is the preferred development method.

Creating a collection with the cfcollection tag

The following are cases in which you might prefer using the cfcollection tag rather than the ColdFusion MX Administrator to create a collection:

  • You want your ColdFusion application to be able to create, delete, and maintain a collection.
  • You do not want to expose the ColdFusion MX Administrator to users.
  • You want to create indexes on servers that you cannot access directly; for example, if you use a hosting company.

When using the cfcollection tag, you can specify the same attributes as in the ColdFusion MX Administrator:

Attribute | Description
action | (Optional) The action to perform on the collection (create, delete, repair, or optimize). The default value for the action attribute is list. For more information, see cfcollection in CFML Reference.
collection | The name of the new collection, or the name of a collection upon which you will perform an action.
path | The location for the Verity collection.
language | language
categories | (Optional) Specifies that cfcollection create a Verity Parametric Index (PI) for this collection. By default, the categories attribute is set to False. To create a collection using categories specify Yes.

You can create a collection by directly assigning a value to the collection attribute of the cfcollection tag, as shown in the following code:

<cfcollection action = "create"
    collection = "a_new_collection"
    path = "c:\CFusionMX7\verity\collections\">

If you want your users to be able to dynamically supply the name and location for a new collection, use the following procedures to create form and action pages.

To create a simple collection form page:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Collection Creation Input Form</title>
</head>

<body>
<h2>Specify a collection</h2>
<form action="collection_create_action.cfm" method="POST">

    <p>Collection name:
    <input type="text" name="CollectionName" size="25"></p>

    <p>What do you want to do with the collection?</p>
    <input type="radio"
        name="CollectionAction"
        value="Create" checked>Create<br>
    <input type="radio"
        name="CollectionAction"
        value="Optimize">Optimize<br>
    <input type="submit"
        name="submit"
        value="Submit">
</form>

</body>
</html>
  2. Save the file as collection_create_form.cfm in the myapps directory under the web root directory.

Note: The form will not work until you write an action page for it, which is the next procedure.

To create a collection action page:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>cfcollection</title>
</head>

<body>
<h2>Collection creation</h2>

<cfoutput>

    <cfswitch expression=#Form.collectionaction#>
        <cfcase value="Create">
            <cfcollection action="Create"
            collection="#Form.CollectionName#"
            path="c:\CFusionMX7\verity\collections\">
            <p>The collection #Form.CollectionName# is created.</p>
        </cfcase>

        <cfcase value="Repair">
            <cfcollection action="Repair"
            collection="#Form.CollectionName#">
            <p>The collection #Form.CollectionName# is repaired.</p>
        </cfcase>

        <cfcase value="Optimize">
            <cfcollection action="Optimize"
            collection="#Form.CollectionName#">
            <p>The collection #Form.CollectionName# is optimized.</p>
        </cfcase>

        <cfcase value="Delete">
            <cfcollection action="Delete"
            collection="#Form.CollectionName#">
            <p>The collection is deleted.</p>
        </cfcase>
    </cfswitch>
</cfoutput>
</body>
</html>
  2. Save the file as collection_create_action.cfm in the myapps directory under the web root directory.
  3. In the web browser, enter the following URL to display the form page:

    http://hostname:portnumber/myapps/collection_create_form.cfm

  4. Enter a collection name; for example, CodeColl.
  5. Verify that Create is selected and submit the form.
  6. (Optional) In the ColdFusion MX Administrator, reload the Verity Collections page.

The name and full path of the new collection appear in the list of Verity Collections.

You successfully created a collection, named CodeColl, that currently has no data. For information on indexing your collection using CFML, see Indexing a collection using the cfindex tag.

Indexing a collection using the cfindex tag

You can index a collection in CFML using the cfindex tag, which eliminates the need to use the ColdFusion MX Administrator. The cfindex tag populates the collection with metadata that is then used to retrieve search results. You can use the cfindex tag to index either physical files (documents stored within your website’s root folder), or the results of a database query.

Note: Prior to indexing a collection, you must create a Verity collection using either the ColdFusion MX Administrator, or the cfcollection tag. For more information, see Creating a collection with the ColdFusion MX Administrator, or Creating a collection with the cfcollection tag.

When using the cfindex tag, the following attributes correspond to the values that you would enter using the ColdFusion MX Administrator to index a collection:

Attribute

Description

collection

The name of the collection.

action

Specifies what the cfindex tag should do to the collection. The default action is to update the collection, which generates a new index. Other actions are to delete, purge, or refresh the collection.

type

Specifies the type of files or other data to which the cfindex tag applies the specified action. The value you assign to the type attribute determines the value to use with the key attribute (see the following list). When you enter a value for the type attribute, cfindex expects a corresponding value in the key attribute. For example, if you specify type=file, cfindex expects a directory path and filename for the key attribute.

The type attribute has the following possible values:

  • file Specifies a directory path and filename for the file that you are indexing.
  • path Specifies a directory path that contains the files that you are indexing.
  • custom Specifies custom data, such as a record set returned from a query.

extensions

(Optional) The delimited list of file extensions that ColdFusion uses to index files if type="path".

key

The value that you specify for the key attribute depends on the value set for the type attribute:

  • If type="file", the key is the directory path and filename for the file you are indexing.
  • If type="path", the key is the directory path that contains the files you are indexing.
  • If type="custom", the key is a unique identifier specifying the location of the documents you are indexing; for example, the URL of a specific web page or website whose contents you want to index. If you are indexing data returned by a query (from a database for example), the key is the name of the record set column that contains the primary key.
URLpath

(Optional) The URL path for files if type="file" and type="path". When the collection is searched with the cfsearch tag, ColdFusion MX works as follows:

  • type="file" The URLpath attribute contains the URL to the file.
  • type="path" The path name is automatically prefixed to filenames and returned as the URLpath attribute.

recurse

(Optional) Yes or No. If type = "path" , Yes specifies that directories below the path specified in the key attribute are included in the indexing operation.

language

(Optional) The language of the collection. The default is English Basic.

To learn more about support for languages, see Specifying a language.

You can use form and action pages similar to the following examples to select and index a collection.

To select which collection to index:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Select the Collection to Index</title>
</head>
<body>

<h2>Specify the index you want to build</h2>

<form method="Post" action="collection_index_action.cfm">
    <p>Enter the collection you want to index:
    <input type="text" name="IndexColl" size="25" maxLength="35"></p>
    <p>Enter the location of the files in the collection:
    <input type="text" name="IndexDir" size="50" maxLength="100"></p>
    <p>Enter a Return URL to prepend to all indexed files:
    <input type="text" name="urlPrefix" size="80" maxLength="100"></p>

    <input type="submit" name="submit" value="Index">

</form>

</body>
</html>
  2. Save the file as collection_index_form.cfm in the myapps directory under the web_root.

Note: The form does not work until you write an action page for it, which is the next procedure.

To use cfindex to index a collection:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Creating Index</title>
</head>
<body>
<h2>Indexing Complete</h2>

<cfindex collection="#Form.IndexColl#"
    action="refresh"
    extensions=".htm, .html, .xls, .txt, .mif, .doc"
    key="#Form.IndexDir#"
    type="path"
    urlpath="#Form.urlPrefix#"
    recurse="Yes"
    language="English">

<cfoutput>
    The collection #Form.IndexColl# has been indexed.
</cfoutput>
</body>
</html>
  2. Save the file as collection_index_action.cfm.
  3. In the web browser, enter the following URL to display the form page:

    http://hostname:portnumber/myapps/collection_index_form.cfm

  4. Enter a collection name; for example, CodeColl.
  5. Enter a file location; for example, C:\CFusionMX7\wwwroot\vw_files.
  6. Enter a URL prefix; for example, http://localhost:8500/vw_files (assuming that you are using the built-in web server).
  7. Click Index.

    A confirmation message appears on successful completion.

Note: For information about using the cfindex tag with a database to index a collection, see Working with data returned from a query.

Indexing a collection with the ColdFusion MX Administrator

As an alternative to programmatically indexing a collection, use the following procedure to index a collection with the ColdFusion MX Administrator.

To use ColdFusion MX Administrator to index a collection:

  1. In the list of Verity Collections, select a collection name; for example, CodeColl.
  2. Click Index to open the index page.
  3. For File Extensions, enter the types of files to index. Use a comma to separate multiple file types; for example, .htm, .html, .xls, .txt, .mif, .doc.
  4. Enter (or Browse to) the directory path that contains the files to be indexed; for example, C:\Inetpub\wwwroot\vw_files.
  5. (Optional) To extend the indexing operation to all directories below the selected path, select the Recursively index subdirectories check box.
  6. (Optional) Enter a Return URL to prepend to all indexed files.

    This step lets you create a link to any of the files in the index; for example, http://127.0.0.1/vw_files/.

  7. (Optional) Select a language other than English.

    For more information, see Specifying a language.

  8. Click Submit Changes.

    On completion, the Verity Collections page appears.

    Note: The time required to generate the index depends on the number and size of the selected files in the path.

This interface lets you easily build a very specific index based on the file extension and path information you enter. In most cases, you do not need to change your server file structures to accommodate the generation of indices.


Creating a search page

You use the cfsearch tag to search an indexed collection. Searching a Verity collection is similar to a standard ColdFusion query: both use a dedicated ColdFusion tag that requires a name attribute for their searches and both return a query object that contains rows matching the search criteria. The following table compares the two tags:

cfquery | cfsearch
Searches a data source | Searches a collection
Requires a name attribute | Requires a name attribute
Uses SQL statements to specify search criteria | Uses a criteria attribute to specify search criteria
Returns variables keyed to database table field names | Returns a unique set of variables
Uses cfoutput to display query results | Uses cfoutput to display search results

Note: You receive an error if you attempt to search a collection that has not been indexed.

The following are important attributes for the cfsearch tag:

Attribute | Description
name | The name of the search query.
collection | The name of the collection(s) being searched. Separate multiple collections with a comma; for example, collection = "sprocket_docs,CodeColl".
criteria | The search target (can be dynamic).
maxrows | The maximum number of records returned by the search. Always specify this attribute to ensure optimal performance (start with 300 or less, if possible).

Each cfsearch returns variables that provide the following information about the search:

Attribute | Description
RecordCount | The total number of records returned by the search.
CurrentRow | The current row of the record set.
RecordsSearched | The total number of records in the index that were searched. If no records were returned in the search, this property returns a null value.
Summary | Automatic summary saved by the cfindex tag.
Context | A context summary that contains the search terms, highlighted in bold (by default). This is enabled if you set the contextpassages attribute to a number greater than zero.

Additionally, if you specify the status attribute, the cfsearch tag returns the status structure, which contains the information in the following table:

Variable

Description

found

The number of documents that contain the search criteria.

searched

The number of documents searched. Corresponds to the recordsSearched column in the search results.

time

The number of milliseconds the search took, as reported by the Verity K2 search service.

suggestedQuery

An alternative query, as suggested by Verity, that may produce better results. This often contains corrected spellings of search terms. Present only when the suggestions tag attribute criteria is met.

Keywords

A structure that contains each search term as a key to an array of up to five possible alternative terms in order of preference. Present only when the suggestions tag attribute criteria is met.

You can use search form and results pages similar to the following examples to search a collection.

To create a search form:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Searching a collection</title>
</head>
<body>
<h2>Searching a collection</h2>

<form method="post" action="collection_search_action.cfm">
    <p>Enter search term(s) in the box below. You can use AND, OR, NOT, and
    parentheses. Surround an exact phrase with quotation marks.</p>
    <p><input type="text" name="criteria" size="50" maxLength="50">
    </p>
    <input type="submit" value="Search">
</form>
</body>
</html>
  2. Save the file as collection_search_form.cfm.

Enter search target words in this form, which ColdFusion passes as the variable criteria to the action page, which displays the search results.

To create the results page:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Search Results</title>
</head>
<body>
<cfsearch
    name = "codecoll_results"
    collection = "CodeColl"
    criteria = "#Form.criteria#"
    contextPassages = "1"
    contextBytes = "300"
    maxrows = "100">

<h2>Search Results</h2>
<cfoutput>
Your search returned #codecoll_results.RecordCount# file(s).
</cfoutput>

<cfoutput query="codecoll_results">
    <p>
    File: <a href="#URL#">#Key#</a><br>
    Document Title (if any): #Title#<br>
    Score: #Score#<br>
    Summary: #Summary#<br>
    Highlighted Summary: #context#</p>
</cfoutput>
</body>
</html>
  2. Save the file as collection_search_action.cfm.
  3. View collection_search_form.cfm in the web browser.
  4. Enter a target word(s) and click Search.

Note: As part of the indexing process, Verity automatically produces a summary of every document file or every query record set that gets indexed. The default summary result set column selects the best sentences, based on internal rules, up to a maximum of 500 characters. Every cfsearch operation returns summary information by default. For more information on this topic, see Using Verity Search Expressions. Alternatively, you can use the context result set column, which provides a context summary with highlighted search terms.


Enhancing search results

ColdFusion lets you enhance the results of searches by letting you incorporate search features that let users more easily find the information they need. The following search enhancements are available through Verity:

  • Highlighting search terms
  • Providing alternative spelling suggestions
  • Narrowing searches using categories

Highlighting search terms

Term highlighting lets users quickly scan retrieved documents to determine whether they contain the desired information. This can be especially useful when searching lengthy documents, letting users quickly locate relevant information returned by the search.

To implement term highlighting, use the following cfsearch attributes in the search results page:

Attributes | Description
ContextHighlightBegin | Specifies the HTML tag to prepend to the search term within the returned documents. This attribute must be used in conjunction with ContextHighlightEnd to highlight the resulting search terms. The default HTML tag is <b>, which highlights search terms using bold type.
ContextHighlightEnd | Specifies the HTML tag to append to the search term within the returned documents.
ContextPassages | The number of passages/sentences Verity returns in the context summary (the context column of the results). The default value is 0; this disables the context summary.
ContextBytes | The total number of bytes that Verity returns in the context summary. The default is 300 bytes.

The following example adds to the previous search results example, highlighting the returned search terms with bold type.

To create a search results page using term highlighting:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Search Results</title>
</head>
<body>
<cfsearch
    name = "codecoll_results"
    collection = "CodeColl"
    criteria = "#Form.Criteria#">
    ContextHighlightBegin="<b>"
    ContextHighlightEnd="</b>"
    ContextPassages="1"
    ContextBytes="500"
    maxrows = "100">
<h2>Search Results</h2>
<cfoutput>
Your search returned #codecoll_results.RecordCount# file(s).
</cfoutput>

<cfoutput query="codecoll_results">
    <p>
    File: <a href="#URL#">#Key#</a><br>
    Document Title (if any): #Title#<br>
    Score: #Score#<br>
    Summary: #Summary#<br>
    Highlighted Summary: #context#</p>
</cfoutput>
</body>
</html>
  2. Save the file as collection_search_action.cfm.

    Note: This overwrites the previous ColdFusion example page.

  3. View collection_search_form.cfm in the web browser:
  4. Enter a target word(s) and click Search.


Providing alternative spelling suggestions

Many unsuccessful searches are the result of incorrectly spelled query terms. Verity can automatically suggest alternative spellings for misspelled queries using a dictionary that is dynamically built from the search index.

To implement alternative spelling suggestions, you use the cfsearch tag’s suggestions attribute with an integer value. If the number of documents returned by the search is less than or equal to the value you specify, Verity provides alternative search term suggestions. In addition to using the suggestions attribute, you may also use the cfif tag to output the spelling suggestions, and a link through which to search on the suggested terms.

Note: Using alternative spelling suggestions incurs a small performance penalty. This occurs because the cfsearch tag must also look up alternative spellings in addition to the specified search terms.

The following example specifies that if the number of search results returned is less than 5, an alternative search term--which is displayed using the cfif tag--is displayed with a link that the user can click to activate the alternate search.

To create a search results page providing alternative spelling suggestions:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Search Results</title>
</head>
<body>
<cfsearch
    name = "codecoll_results"
    collection = "CodeColl"
    criteria = "#Form.Criteria#">
    status = "info"
    suggestions="5"
    ContextPassages = "1"
    ContextBytes = "300"
    maxrows = "100">
<h2>Search Results</h2>
<cfoutput>
Your search returned #codecoll_results.RecordCount# file(s).
</cfoutput>
<cfif info.FOUND LTE 5 AND isDefined("info.SuggestedQuery)>
    Did you mean:
    <a href="search,cfm?query=#info.SuggestedQuery#>#info.SuggestedQuery#</a>
</cfif>
<cfoutput query="codecoll_results">
    <p>
    File: <a href="#URL#">#Key#</a><br>
    Document Title (if any): #Title#<br>
    Score: #Score#<br>
    Summary: #Summary#<br>
    Highlighted Summary: #context#</p>
</cfoutput>
</body>
</html>
  2. Save the file as collection_search_action.cfm.

    Note: This overwrites the previous ColdFusion example page.

  3. View collection_search_form.cfm in the web browser:
  4. Enter any misspelled target words and click Search.


Narrowing searches using categories

Verity lets you organize your searchable documents into categories. Categories are groups of documents (or database tables) that you define, and then let users search within them. For example, if you wanted to create a search tool for a software company, you might create categories such as whitepapers, documentation, release notes, and marketing collateral. Users can then specify one or more categories in which to search for information. Thus, if users visiting the website wanted to learn about a conceptual aspect of your company’s technology, they might restrict their search to the whitepaper and marketing categories.

Typically, you will want to provide users with pop-up menus or check boxes from which they can select categories to narrow their searches. Alternately, you might create a form that lets users enter both a category name in which to search, and search keywords.

To create a search application that uses categories:

  1. Create a collection with support for categories enabled.

    See Creating collections with support for categories.

  2. Index the collection, specifying the category and categoryTree attributes appropriate to the collection.

    For more information on indexing Verity collections with support for categories, see Indexing collections that contain categories.

  3. Create a search page that lets users search within the categories that you’ve created.

    Create a search page using the cfsearch tag that lets users more easily search for information by restricting searches to the specified category and, if specified, its hierarchical tree.

    For more information on searching Verity collections with support for categories, see Searching collections that contain categories.


Creating collections with support for categories

You can either select Enable Category Support from the ColdFusion MX Administrator, or write a cfcollection tag that uses the category attribute. By enabling category support, you create a collection that contains a Verity Parametric Index (PI).

<cfcollection
action = "action"
collection = "collectionName"
path = "path_to_verity_collection"
language = "English"
categories = "yes">

For more information on using the cfcollection tag to create Verity collections with support for categories, see cfcollection in ColdFusion Tags in CFML Reference.


Indexing collections that contain categories

When you index a collection with support for categories enabled, you must do the following:

  • Specify a category name using the category attribute. The name (or names) that you provide identifies the category so that users can specify searches on the documents that the collection contains. For example, you might create five categories named taste, touch, sight, sound, and smell. When performing a search, users could select from either a pop-up menu or check box to search within one or more of the categories, thereby limiting their search within a given range of topics.
    <cfindex collection="#Form.IndexColl#"
    action="update"
    extensions=".htm, .html, .xls, .txt, .mif, .doc, .pdf"
    key="#Form.IndexDir#"
    type="path"
    urlpath="#Form.urlPrefix#"
    recurse="Yes"
    language="English"
    category="taste, touch, sight, sound, smell">
  • Specify a hierarchical document tree (similar to a file system tree) within which you can limit searches, when you use the categoryTree attribute. With the categoryTree attribute enabled, ColdFusion limits searches to documents contained within the specified path.

    To use the categoryTree attribute, you specify a hierarchical document tree by listing each category as a string, and separating them using forward slashes (/). The tree structure that you specify in a search is the root of the document tree from which you want the search to begin. The type=path attribute appends directory names to the end of the returned value (as it does when specifying the urlpath attribute).

    Note: You can specify only a single category tree.

    <cfindex collection="#Form.IndexColl#"
    action="update"
    extensions=".htm, .html, .xls, .txt, .mif, .doc, .pdf"
    key="#Form.IndexDir#"
    type="path"
    urlpath="#Form.urlPrefix#"
    recurse="Yes"
    language="English"
    category="taste, touch, sight, sound, smell"
    categoryTree="human/senses/taste">

    For more information on using the cfindex tag to create Verity collections with support for categories, see cfindex in ColdFusion Tags in CFML Reference.


Searching collections that contain categories

When searching data in a collection created with categories, you specify category and categoryTree. The values supplied to these attributes specify what category should be searched for the specified search string (the criteria attribute). The category attribute can contain a comma separated list of categories to search. Both attributes can be specified at the same time.

<cfsearch collection="collectionName"
    name="results"
    maxrows = "100"
    criteria="search keywords"
    category="FAQ,Technote"
    categoryTree="Docs/Tags">

Note: If cfsearch is executed on a collection that was created without category information, an exception is thrown.

To search collections that contain categories, you use the cfsearch tag, and create an application page that searches within specified categories. The following example lets the user enter and submit the name of the collection, the category in which to search, and the document tree associated with the category through a form. By restricting the search in this way, the users are better able to retrieve the documents that contain the information they are looking for. In addition to searching with a specified category, this example also makes use of the contextHighlight attribute, which highlights the returned search results.

<cfparam name="collection" default="test-pi">

<cfoutput>
<form action="#CGI.SCRIPT_NAME#" method="POST">
 Collection Name: <input Type="text" Name="collection" value="#collection#">
 <P>
 Category: <input Type="text" Name="category" value=""><br>
 CategoryTree: <input Type="text" Name="categoryTree" value=""><br>
 <P>
Search: <input Type="text" Name="criteria">
 <input Type="submit" Value="Search">
</form>
</cfoutput>

<cfif isdefined("Form.criteria")>
    <cfoutput>Search results for: <b>#criteria#</b></cfoutput>
    <br>
    <cfsearch collection="#form.collection#"
        category="#form.category#"
        categoryTree="#form.categoryTree#"
        name="sr"
        status="s"
        criteria="#form.criteria#"
        contextPassages="3"
        contextBytes="300"
        contextHighlightBegin="<i><b>"
        contextHighlightEnd="</b></i>"
        maxrows="100">
    <cfdump var="#s#">

    <cfoutput>
    <p>Number of records in query: #sr.recordcount#</P>
    </cfoutput>

    <cfdump var="#sr#">

    <cfoutput Query="sr">
    Title: <i>#title#</i><br>
    URL: #url#<br>
    Score: #score#<br>
    <hr>
    #context#<br>
    <br>
    #summary#<br>
    <hr>
    </cfoutput>
</cfif>

For more information on using the cfindex tag to create Verity collections with support for categories, see cfsearch in ColdFusion Tags in CFML Reference.


Retrieving information about the categories contained in a collection

You can retrieve the category information for a collection by using the cfcollection tag’s categoryList action. The categoryList action returns a structure that contains two keys:

Variable | Description
categories | The name of the category and its hit count, where hit count is the number of documents in the specified category.
categorytrees | The document tree (a/b/c) and hit count, where hit count is the number of documents at or below the branch of the document tree.

You can use the information returned by categoryList to display to users the number of documents available for searching, as well the document tree available for searching. You can also create a search interface that lets the user select what category to search within based on the results returned by categoryList.

<cfcollection
    action="categoryList"
    collection="collectionName"
    "name="info">

<cfoutput>
    <cfset catStruct=info.categories>
    <cfset catList=StructKeyList(catStruct)>
    <cfloop list="catList" index="cat"> Category: #cat# <br>
        Documents: #catStruct[cat]#<br>
    </cfloop>
</cfoutput>

To retrieve information about the categories contained in a collection, you use the cfcollection tag, and create an application page that retrieves category information from the collection and displays the number of documents contained by each category. This example lets the user enter and submit the name of the collection via a form, and then uses the categoryList action to retrieve information about the number of documents contained by the collection, and the hierarchical tree structure into which the category is organized.

<html>
<head>
    <title>Category information</title>
</head>
<body>
<cfoutput>
<form action="#CGI.SCRIPT_NAME#" method="POST">
    Enter Collection Name: <input Type="text" Name="collection"
        value="#collection#"><br>
 <input Type="submit" Value="GetInfo">
</form>
</cfoutput>
<cfif isdefined("Form.collection")>
    <cfoutput>
    Getting collection info...
    <br>
    <cfflush>
    <cfcollection
        action="categorylist"
        collection="#collection#"
        name="out">
    <br>
    <cfset categories=out.categories>
    <cfset tree=out.categorytrees>
    <cfset klist=StructKeyList(categories)>
    <table border=1>
    <th>Category</th> <th>Documents</th>
    <cfloop index="x" list="#klist#">
    <tr>
     <td>#x#</td> <td align="center">#categories[x]#</td>
    </tr>
    </cfloop>
    </table>
    <cfset klist=StructKeyList(tree)>
    <table border=1>
    <th>Category</th> <th>Documents</th>
    <cfloop index="x" list="#klist#">
    <tr>
     <td>#x#</td> <td align="center">#tree[x]#</td>
    </tr>
    </cfloop>
    </table>
    </cfoutput>
</cfif>
</body>

For more information on using the cfcollection tag to create Verity collections with support for categories, see cfcollection in ColdFusion Tags in CFML Reference.


Working with data returned from a query

Using Verity, you can search data returned by a query--such as a database record set--as if it were a collection of documents stored on your web server. Using Verity to search makes implementing a search interface much easier, as well as letting users more easily find information contained in database files. This section describes the reasons and procedures for indexing the results of database and other queries. It also describes how a database can direct the indexing process, using different values for the type attribute of the cfindex tag.

This section describes the following topics:

  • Recordsets and types of queries
  • Indexing data returned by a query
  • Indexing a file returned using a query
  • Indexing a path returned using a query
  • Indexing query results obtained from an LDAP directory
  • Indexing cfpop query results

Recordsets and types of queries

When indexing record sets generated from a query (using the cfquery, cfldap, or cfpop tag), cfindex creates indexes based on the type attribute and its set value:

Type | Attribute values
File | The key attribute is the name of a column in the query that contains a full filename (including path).
Path | The key attribute is the name of a column in the query that contains a directory pathname.
Custom | The key attribute specifies a column name that can contain anything you want. In this case, the body attribute is required, and is a comma-delimited list of the names of the columns that contain the text data that is to be indexed.

The cfindex tag treats all collections the same, whether they originate from a database recordset, or if they are a collection of documents stored within your website’s root folder.


Indexing data returned by a query

Indexing the results of a query is similar to indexing physical files located on your website, with the added step that you must write a query that retrieves the data you want to search. The following are the steps to perform a Verity search on record sets returned from a query:

  1. Create a collection.
  2. Write a query that retrieves the data you want to search, and generate a record set.
  3. Index the record set using the cfindex tag.

    The cfindex tag indexes the record set as if it were a collection of documents in a folder within your website.

  4. Search the collection.

    The information returned from the collection includes the database key and other selected columns. You can then use the information as-is, or use the key value to retrieve the entire row from the database table.

You should use Verity to search databases in the following cases:

  • You want to perform full-text search on database data. You can search Verity collections that contain textual data much more efficiently with a Verity search than using SQL to search database tables.
  • You want to give your users access to data without interacting directly with the data source itself.
  • You want to improve the speed of queries.
  • You want users to be able to execute queries, but not update database tables.

Unlike indexing documents stored on your web server, indexing information contained in a database requires an additional step--you must first write a query (using the cfquery, cfldap, or cfpop tag) that retrieves the data you want to let your users search. You then pass the information retrieved by the query to a cfindex tag, which indexes the data.

When indexing data with the cfindex tag, you must specify which column of the query represents the filename, which column represents the document title, and which column (or columns) represents the document’s body (the information that you want to make searchable).

When indexing a recordset retrieved from a database, the cfindex tag uses the following attributes that correspond to the data source:

Attribute | Description
key | Primary key column of the data source table.
title | Specifies a query column name.
body | Columns that you want to search for the index.
type | If set to custom, this attribute specifies the columns that you want to index. If set to file or path, this is a column that contains either a directory path and filename, or a directory path that contains the documents to be indexed.

Using the cfindex tag to index tabular data is similar to indexing documents, with the exception that you refer to column names from the generated record set in the body attribute. In the following example, the type attribute is set to custom, specifying that the cfindex tag index the contents of the record set columns Emp_ID, FirstName, LastName, and Salary, which are identified using the body attribute. The Emp_ID column is listed as the key attribute, making it the primary key for the record set.

To index a ColdFusion query:

  1. Create a Verity collection for the data that you want to index.

    The following example assumes that you have a Verity collection named CodeColl. You can use the ColdFusion MX Administrator to create the collection, or you can create the collection programmatically by using the cfcollection tag. For more information, see Creating a collection with the ColdFusion MX Administrator or Creating a collection with the cfcollection tag.

  2. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Adding Query Data to an Index</title>
</head>
<body>

<!--- Retrieve data from the table. --->
<cfquery name="getEmps" datasource="cfdocexamples">
    SELECT * FROM EMPLOYEE
</cfquery>

<!--- Update the collection with the above query results. --->
<cfindex
    query="getEmps"
    collection="CodeColl"
    action="Update"
    type="Custom"
    key="Emp_ID"
    title="Emp_ID"
    body="Emp_ID,FirstName,LastName,Salary">

<h2>Indexing Complete</h2>

<!--- Output the record set. --->
<p>Your collection now includes the following items:</p>
<cfoutput query="getEmps">
    <p>#Emp_ID# #FirstName# #LastName# #Salary#</p>
</cfoutput>
</body>
</html>
  3. Save the file as collection_db_index.cfm in the myapps directory under the web root directory.
  4. Open the file in the web browser to index the collection.

    The resulting record set appears.

To search and display the query results:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Searching a collection</title>
</head>
<body>

<h2>Searching a collection</h2>

<form method="post" action="collection_db_results.cfm">
    <p>Collection name: <input type="text" name="collname" size="30" maxLength="30"></p>

    <p>Enter search term(s) in the box below. You can use AND, OR, NOT,
    and parentheses. Surround an exact phrase with quotation marks.</p>
    <p><input type="text" name="criteria" size="50" maxLength="50">
    </p>
    <p><input type="submit" value="Search"></p>
</form>

</body>
</html>
  2. Save the file as collection_db_search_form.cfm in the myapps directory under the web_root.

    This file is similar to collection_search_form.cfm, except the form uses collection_db_results.cfm, which you create in the next step, as its action page.

  3. Create another ColdFusion page with the following content:
    <html>
<head>
<title>Search Results</title>
</head>

<body>

<cfsearch
   collection="#Form.collname#"
   name="getEmps"
   criteria="#Form.Criteria#"
    maxrows = "100">

<!--- Output the record set. --->
<cfoutput>
Your search returned #getEmps.RecordCount# file(s).
</cfoutput>

<cfoutput query="getEmps">
    <p><table>
    <tr><td>Title: </td><td>#Title#</td></tr>
    <tr><td>Score: </td><td>#Score#</td></tr>
    <tr><td>Key: </td><td>#Key#</td></tr>
    <tr><td>Summary: </td><td>#Summary#</td></tr>
    <tr><td>Custom 1:</td><td>#Custom1#</td></tr>
    <tr><td>Column list: </td><td>#ColumnList#</td></tr>
</table></p>

</cfoutput>
</body>
</html>
  4. Save the file as collection_db_results.cfm in the myapps directory under the web_root.
  5. View collection_db_search_form.cfm in the web browser and enter the name of the collection and search terms.


Indexing a file returned using a query

You can index an individual file using a query by retrieving a table row whose contents are a filename. In this case, the key specifies the column that contains the complete filename. The file is indexed using the cfindex tag as if it were a document under the web server root folder.

In the following example, the cfindex tag’s type attribute has been set to file, and the specified key is the name of the column that contains the full path to the file and the filename.

To index a file specified by a query:

<cfquery name="getEmps" datasource="cfdocexamples">
SELECT * FROM EMPLOYEE WHERE EMP_ID = 1
</cfquery>
<cfindex
    query="getEmps"
    collection="CodeColl"
    action="Update"
    type="file"
    key="Contract_File"
    title="Contract_File"
    body="Emp_ID,FirstName,LastName,Contract_File">

To search and display the file:

  1. Create a ColdFusion page that contains the following content:
<!--- Output the record set.--->
<p>Your collection now includes the following items:</p>
<cfoutput query="getEmps">
<p>#Emp_ID# #FirstName# #LastName# #Contract_File#</p>
</cfoutput>
<cfsearch
    collection="#Form.collname#"
    name="getEmps"
    criteria="#Form.Criteria#"
    maxrows = "100">

<!--- Output the file name contained in the record set. --->
<cfoutput>
Your search returned #getEmps.RecordCount# file(s).
</cfoutput>
<cfoutput query="getEmps">
<p><table>
    <tr><td>Title: </td><td>#Title#</td></tr>
    <tr><td>Score: </td><td>#Score#</td></tr>
    <tr><td>Key: </td><td>#Key#</td></tr>
    <tr><td>Summary: </td><td>#Summary#</td></tr>
    <tr><td>Custom 1:</td><td>#Custom1#</td></tr>
    <tr><td>Column list: </td><td>#ColumnList#</td></tr>
</table></p>
</cfoutput>


Indexing a path returned using a query

You can index a directory path to a document (or collection of documents) using a query by retrieving a row whose contents are a full directory path name. In this case, the key specifies the column that contains the complete directory path. Documents located in the directory path are indexed using the cfindex tag as if they were under the web server root folder.

In this example, the type attribute is set to path, and the key attribute is assigned the column name Project_Docs. The Project_Docs column contains directory paths, which Verity indexes as if they were specified as a fixed path pointing to a collection of documents without the use of a query.

To index a directory path within a query:

  1. Create a ColdFusion page that contains the following content:
    <cfquery name="getEmps" datasource="cfdocexamples">
SELECT * FROM EMPLOYEE WHERE Emp_ID = 15
</cfquery>
<!--- Update the collection with the above query results. --->
<!--- Key specifies a column that contains a directory path. --->
<cfindex
    query="getEmps"
    collection="CodeColl"
    action="update"
    type="path"
    key="Project_Docs"
    title="Project_Docs"
    body="Emp_ID,FirstName,LastName,Project_Docs">

<h2>Indexing Complete</h2>
<p>Your collection now includes the following items:</p>
<cfoutput query="getEmps">
<p>#Emp_ID# #FirstName# #LastName# #Project_Docs#</p>
</cfoutput>
  2. Save the file as indexdir.cfm in the myapps directory.

The ColdFusion cfindex tag indexes the contents of the specified directory path.

To search and display the directory path:

  1. Create a ColdFusion page that contains the following content:
    <cfsearch
    collection="#Form.collname#"
    name="getEmps"
    criteria="#Form.Criteria#"
    maxrows = "100">

<!--- Output the directory path contained in the record set. --->
<cfoutput>
Your search returned #getEmps.RecordCount# file(s).
</cfoutput>

<cfoutput query="getEmps">
<p><table>
    <tr><td>Title: </td><td>#Title#</td></tr>
    <tr><td>Score: </td><td>#Score#</td></tr>
    <tr><td>Key: </td><td>#Key#</td></tr>
    <tr><td>Summary: </td><td>#Summary#</td></tr>
    <tr><td>Custom 1:</td><td>#Custom1#</td></tr>
    <tr><td>Column list: </td><td>#ColumnList#</td></tr>
</table></p>
</cfoutput>
  2. Save the file as displaydir.cfm.


Indexing query results obtained from an LDAP directory

The widespread use of the Lightweight Directory Access Protocol (LDAP) to build searchable directory structures, internally and across the web, gives you opportunities to add value to the sites that you create. You can index contact information or other data from an LDAP-accessible server and let users search it.

When creating an index from an LDAP query, remember the following considerations:

  • Because LDAP structures vary greatly, you must know the server’s directory schema and the exact name of every LDAP attribute that you intend to use in a query.
  • The records on an LDAP server can be subject to frequent change.

In the following example, the search criterion is records with a telephone number in the 617 area code. Generally, LDAP servers use the Distinguished Name (dn) attribute as the unique identifier for each record so that attribute is used as the key value for the index.

<!--- Run the LDAP query. --->
<cfldap name="OrgList"
    server="myserver"
    action="query"
    attributes="o, telephonenumber, dn, mail"
    scope="onelevel"
    filter="(|(O=a*) (O=b*))"
    sort="o"
    start="c=US">

<!--- Output query record set. --->
<cfoutput query="OrgList">
    DN: #dn# <br>
    O: #o# <br>
    TELEPHONENUMBER: #telephonenumber# <br>
    MAIL: #mail# <br>
=============================<br>
</cfoutput>

<!--- Index the record set. --->
<cfindex action="update"
    collection="ldap_query"
    key="dn"
    type="custom"
    title="o"
    query="OrgList"
    body="telephonenumber">

<!--- Search the collection. --->
<!--- Use the wildcard * to contain the search string. --->
<cfsearch collection="ldap_query"
    name="s_ldap"
    criteria="*617*"
    maxrows = "100">

<!--- Output returned records. --->
<cfoutput query="s_ldap">
    #Key#, #Title#, #Body# <br>
</cfoutput>


Indexing cfpop query results

The contents of mail servers are generally volatile; specifically, the message number is reset as messages are added and deleted. To avoid mismatches between the unique message number identifiers on the server and in the Verity collection, you must re-index the collection before processing a search.

As with the other query types, you must provide a unique value for the key attribute and enter the data fields to index in the body attribute.

The following example updates the pop_query collection with the current mail for user1, and searches and returns the message number and subject line for all messages that contain the word action:

<!--- Run POP query. --->
<cfpop action="getall"
    name="p_messages"
    server="mail.company.com"
    userName="user1"
    password="user1">

<!--- Output POP query record set. --->
<cfoutput query="p_messages">
    #messagenumber# <br>
    #from# <br>
    #to# <br>
    #subject# <br>
    #body# <br>
<hr>
</cfoutput>

<!--- Index record set. --->
<cfindex action="refresh"
    collection="pop_query"
    key="messagenumber"
    type="custom"
    title="subject"
    query="p_messages"
    body="body">

<!--- Search messages for the word "action". --->
<cfsearch collection="pop_query"
    name="s_messages"
    criteria="action"
    maxrows = "100">

<!--- Output search record set. --->
<cfoutput query="s_messages">
    #key#, #title# <br>
</cfoutput>
Previous


Using Verity Search Expressions

This chapter describes Verity search expressions and how you can refine your searches to yield the most accurate results.

Contents

About Verity query types

Using simple queries

Using explicit queries

Using natural queries

Using Internet queries

Composing search expressions

Refining your searches with zones and fields
Next


About Verity query types

When you search a Verity collection, you can use a simple, explicit, natural, or Internet query. The following table compares the query types:

Query type

Content

Use of operators
and modifiers

CFML example

Simple

One or more words

Uses STEM operator and MANY modifier, by default

<cfsearch name = "band_search"
    collection="bbb"
    type = "simple"
    criteria="film">

Explicit

Words, operators, modifiers

Must be specified

<cfsearch name = "my_search"
    collection="bbb"
    type = "explicit"
criteria="<WILDCARD>'sl[iau]m'">

Natural

One or more words

Uses STEM operator and MANY modifier, by default

<cfsearch name = "my_search"
    collection="bbb"
    type = "natural"
criteria="Boston subway maps">

Internet

Words, operators, modifiers

<cfsearch name = "my_search"
    collection="bbb"
    type = "Internet"
criteria="Boston subway maps">

The query type determines whether the search words that you enter are stemmed, and whether the retrieved words contribute to relevance-ranked scoring. Both of these conditions occur by default in simple queries. For more information on the STEM operator and MANY modifier, see Stemming in simple queries.

Note: Operators and modifiers are formatted as uppercase letters in this chapter solely to enhance legibility. They might be all lowercase or uppercase.


Using simple queries

The simple query is the default query type and is appropriate for the vast majority of searches. When entering text on a search form, you perform a simple query by entering a word or comma-delimited strings, with optional wildcard characters. Verity treats each comma as a logical OR. If you omit the commas, Verity treats the expression as a phrase.

Caution: Many web search engines assume a logical AND for multiple word searches, and search for a phrase only if you use quotation marks. Because Verity treats multiple word searches differently, it might help your users if you provide examples on your search page or a brief explanation of how to search.

The following table shows examples of simple searches:

Example | Search result
low,brass,instrument | low or brass or instrument
low brass instrument | the phrase, low brass instrument
film | film, films, filming, or filmed
filming AND fun | film, films, filming, or filmed, and fun
filming OR fun | film, films, filming, or filmed, or fun
filming NOT fun | film, films, filming, or filmed, but not fun

The operators AND and OR, and the modifier NOT, do not require angle brackets (<>). Operators typically require angle brackets and are used in explicit queries. For more information about operators and modifiers, see Operators and modifiers.

Stemming in simple queries

By default, Verity interprets words in a simple query as if you entered the STEM operator (and MANY modifier). The STEM operator searches for words that derive from a common stem. For example, a search for instructional returns files that contain instruct, instructs, instructions, and so on.

The STEM operator works on words, not word fragments. A search for "instrument" returns documents containing "instrument," "instruments," "instrumental," and "instrumentation," whereas a search for "instru" does not. (A wildcard search for instru* returns documents with these words, and also those with instruct, instructional, and so on.)

Note: The MANY modifier presents the files returned in the search as a list based on a relevancy score. A file with more occurrences of the search word has a higher score than a file with fewer occurrences. As a result, the search engine ranks files according to word density as it searches for the word that you specify, as well as words that have the same stem. For more information on the MANY modifier, see Modifiers.

In CFML, enter your search terms, operators, and modifiers in the criteria attribute of the cfsearch tag:

<cfsearch name="search_name"
    collection="bbb"
    type="simple"
criteria="instructional">

Preventing stemming

When entering text on a search form, you can prevent Verity from implicitly adding the STEM operator by doing one of the following:

  • Perform an explicit query. For more information, see the next section, Using explicit queries.
  • Use the WORD operator. For more information, see Operators.
  • Enclose the search term that has double-quotation marks with single-quotation marks, as follows:
    <cfsearch name="search_name"
    collection="bbb"
    type="simple"
criteria='"instructional"'


Using explicit queries

In an explicit query, the Verity search engine literally interprets your search terms. The following are two ways to perform an explicit query:

  • On a search form, use quotation marks around your search term(s).
  • In CFML, use type="explicit" in the cfsearch tag.

When you put a search term in quotation marks, Verity does not use the STEM operator. For example, a search for "instructional"--enclosed in quotation marks, as shown in Preventing stemming--does not return files that contain instruct, instructs, instructions, and so on (unless the files also contain instructional).

Note: The Verity products and documentation refers to the Explicit parser as the BooleanPlus parser.

When you specify type="explicit" the search expression must be a valid Verity Query Language expression. As a result, an individual search term must be in explicit quotation marks. The following table shows valid and invalid criteria:

Attribute

Effect

criteria="government"

Generates an error

criteria="'government'" or
criteria='"government"'

Finds only government

criteria="<WORD>government"

Finds only government

criteria="<STEM>government"

Finds government, governments, and governmental

criteria="<MANY><STEM>government"

Finds government, governments, and governmental ranked by relevance

criteria="<WILDCARD>governmen*"

Finds government, governments, and governmental

Using AND, OR, and NOT

Verity has many powerful operators and modifiers available for searching (for more information, see Operators and modifiers). However, users might only use the most basic operators--AND, OR, and the modifier NOT. The following are a few important points:

  • You can type operators in uppercase or lowercase letters.
  • Verity reads operators from left to right.
  • The AND operator takes precedence over the OR operator.
  • Use parentheses to clarify the search. Terms enclosed in parentheses are evaluated first; innermost parentheses are evaluated first when there are nested parentheses.
  • To search for a literal AND, OR, or NOT, enclose the literal term in double-quotation marks; for example:

    love "and" marriage

Note: Although NOT is a modifier, you use it only with the AND and OR operators. Therefore, it is sometimes casually referred to as an operator.

The following table gives examples of searches and their results:

Search term | Returns files that contain
doctorate AND nausea | both doctorate and nausea
doctorate "and" nausea | the phrase doctorate and nausea
"doctorate and nausea" | the phrase doctorate and nausea
masters OR doctorate AND nausea | masters, or the combination of doctorate and nausea
masters OR (doctorate AND nausea) | masters, or the combination of doctorate and nausea
(masters OR doctorate) AND nausea | either masters or doctorate, and nausea
masters OR doctorate NOT nausea | either masters or doctorate, but not nausea

Using wildcards and special characters

Part of the strength of the Verity search is its use of wildcards and special characters to refine searches. Wildcard searches are especially useful when you are unsure of the correct spelling of a term. Special characters help you search for tags in your code.

Searching with wildcards

The following table shows the wildcard characters that you can use to search Verity collections:

Wildcard | Description | Example | Search result
? | Matches any single alphanumeric character. | apple? | apples or applet
* | Matches zero or more alphanumeric characters. Avoid using the asterisk as the first character in a search string. An asterisk is ignored in a set, ([]) or an alternative pattern ({}). | app*ed | Appleseed, applied, appropriated, and so on
[ ] | Matches any one of the characters in the brackets. Square brackets indicate an implied OR. | <WILDCARD> 'sl[iau]m' | slim, slam, or slum
{ } | Matches any one of a set of patterns separated by a comma, | <WILDCARD> 'hoist{s,ing,ed}' | hoists, hoisting, or hoisted
^ | Matches any character not in the set. | <WILDCARD>'sl[^ia]m' | slum, but not slim or slam
- | Specifies a range for a single character in a set. | <WILDCARD> 'c[a-r]t' | cat, cot, but not cut (that is, every word beginning with c, ending with t, and containing any single letter from a to r)

To search for a wildcard character as a literal, place a backslash character before it; for example:

  • To match a question mark or other wildcard character, precede the ? with one backslash. For example, type the following in a search form: Checkers\?
  • To match a literal asterisk, you precede the * with two backslashes, and enclose the search term with either single or double quotation marks. For example, type the following in a search form: 'M\\*' (or "M\\*") The following is the corresponding CFML code:
    <cfsearch name = "quick_search"
    collection="bbb"
    type = "simple"
    criteria="'M\\*'">

    Note: The last line is equivalent to criteria='"M\\*"'>.

Searching for special characters

The search engine handles a number of characters in particular ways as the following table describes:

Characters | Description
, ( ) [ | These characters end a text token. A token is a variable that stores configurable properties. It lets the administrator or user configure various settings and options.
= > < ! | These characters also end a text token. They are terminated by an associated end character.
' ` < { [ ! | These characters signify the start of a delimited token. They are terminated by an associated end character.

To search for special characters as literals, precede the following nonalphanumeric characters with a backslash character (\) in a search string:

  • comma (,)
  • left parenthesis (
  • right parenthesis )
  • double-quotation mark (")
  • backslash (\)
  • left curly brace ({)
  • left bracket ([)
  • less than sign (<)
  • backquote (`)

In addition to the backslash character, you can use paired backquote characters (` `) to interpret special characters as literals. For example, to search for the wildcard string "a{b" you can surround the string with back quotation marks, as follows:

`a{b`

To search for a wildcard string that includes the literal backquote character (`) you must use two backquote characters together and surround the entire string in back quotation marks:

`*n``t`

You can use paired back quotation marks or backslashes to escape special characters. There is no functional difference between the two. For example, you can query for the term: <DDA> using \<DDA\> or `<DDA>` as your search term.


Using natural queries

The Natural parser supports searching for similar documents, a search method sometimes referred to as similarity searching. The Natural parser supports searching the full text of documents only. The Natural parser does not support searching collection fields and zones. The Natural parser does not support Verity query language except for topics.

Note: The Verity products and documentation refer to the Natural parser as the Query-By-Example parser, as well as the Free Text parser.

Meaningful words are automatically treated as if they were preceded by the MANY modifier and the STEM operator. By implicitly applying the STEM operator, the search engine searches not only for the meaningful words themselves, but also for words that have the same stem. By implicitly applying the MANY modifier, Verity calculates each document’s score based on the word density it finds for meaningful words; the denser the occurrences of a word in a document, the higher the document’s score.

By default, common words (such as the, has, and for) are stripped away, and the query is built based on the more significant words (such as personnel, interns, schools, and mentors). Therefore, the results of a natural language search are likely to be less precise than a search performed using the simple or explicit parser.

The Natural parser interprets topic names as topic objects. This means that if the specified text block contains a topic name, the query expression represented by the topic is considered in the search.


Using Internet queries

With the Internet query parser, users can search entire documents or parts of documents (zones and fields) entering words, phrases, and plain language similar to that used by many web search engines. ColdFusion MX supports two Internet query parsers in the cfsearch type attribute.

Internet Uses standard, web-style query syntax. For more information, see Query syntax.

Internet_basic Similar to Internet. This query parser enhances performance, but produces less accurate relevancy statistics.

Note: Verity also includes the Internet_BasicWeb and Internet_AdvancedWeb query parsers, which are not directly supported by ColdFusion MX.

Search terms

In a search form enabled with the Internet query parser, users can enter words, phrases, and plain language. The Internet parser does not support the Verity query language (VQL).

Words

To search for multiple words, separate them with spaces.

Phrases

To search for an exact phrase, surround it with double-quotation marks. A string of capitalized words is assumed to be a name. Separate a series of names with commas. Commas aren’t needed when the phrases are surrounded by quotation marks.

The following example searches for a document that contains the phrases "San Francisco" and "sourdough bread":

"San Francisco" "sourdough bread"

Plain language

To search with plain language, enter a question or concept. The Internet Query Parser identifies the important words and searches for them. For example, enter a question such as:

Where is the sales office in San Francisco?

This query produces the same results as entering:

sales office San Francisco

Including and excluding search terms

You can limit searches by excluding or requiring search terms, or by limiting the areas of the document that are searched.

A minus sign (–) immediately preceding a search term (word or phrase) excludes documents containing the term.

A plus sign (+) immediately preceding a search term (word or phrase) means returned documents are guaranteed to contain the term.

If neither sign is associated with the search term, the results may include documents that do not contain the specified term as long as they meet other search criteria.

Field searches

The Internet parser lets users perform field searches. The fields that are available for searching depend on field extraction rules based on the document type of the documents in the collection.

To search a document field, type the name of the field, a colon (:), and the search term with no spaces.

field:term

If you enter a minus sign (–) immediately preceding field, documents that contain the specified term are excluded from the search results. For example, if you enter -field:term, documents that contain the specified term in the specified field are excluded from the results of the search.

If you enter a plus sign (+) immediately proceeding the field search specification, such as +field:term, documents are included in the search results only if the search term is present in the specified field.

Field searches are enabled by the enableField parameter in a template file. This parameter, set to 0 by default, must be set to 1 to allow searching a document field.

Caution: The enableField parameter is the only thing in a template file that should be modified.

Query syntax

The query syntax is very similar to the syntax that users expect to use on the web. Queries are interpreted according to the following rules:

  • Individual search terms are separated by whitespace characters, such as a space, tab, or comma; for example:

    cake recipes

  • Search phrases are entered within double-quotation marks; for example:

    "chocolate cake" recipe

  • Exclude terms with the negation operator, minus ( - ), or the NOT operator; for example:

    cake recipes -rum

    cake recipes NOT rum

  • Require a compulsory term with the unary inclusion operator, plus sign (+); in this example, the term chocolate must be included:

    cake recipes +chocolate

  • Require compulsory terms with the binary inclusion operator AND; in this example, the terms recipes and chocolate must be included:

    cake recipes and chocolate

Field searches

You can search fields or zones by specifying name: term, where:

name is the name of the field or zone

term is an individual search term or phrase

For example:

bakery city:"San Francisco"
bakery city:Sunnyvale

For more information, see Refining your searches with zones and fields.

Pass-through of terms

Search terms are passed through to the VDK-level and are interpreted as Verity Query Language (VQL) syntax. No issues arise if the terms contain only alphabetic or numeric characters. Other kinds of characters might be interpreted by the language you’re using. If a term contains a character that is not handled by the specified language, it might be interpreted as VQL. For example, a search term that includes an asterisk (*) might be interpreted as a wildcard.

Stop words

The configurable Internet query parser uses its own stop-word list, qp_inet.stp, to specify terms to ignore for natural language processing.

Note: You can override the "stop out" by using quotation marks around the word.

For example, the following stop words are provided in the query parser’s stop-word file for the English (Basic) template:

a | did | i | or | what
also | do | i’m | should | when
an | does | if | so | where
and | find | in | than | whether
any | for | is | that | which
am | from | it | the | who
are | get | its | there | whose
as | got | it’s | to | why
at | had | like | too | will
be | has | not | want | with
but | have | of | was | would
can | how | on | were | <or>

Verity provides a populated stop-word file for the English and English (Advanced) languages. You do not need to modify the qp_inet.stp file for these languages. If you use the configurable Internet query parser for another language, you must provide your own qp_inet.stp file that contains the stop words that you want to ignore in that language. This stop-word file must contain, at a minimum, the language-equivalent words for or and <or>.

Note: The configurable Internet query parser’s stop-word file contains a different word list than the vdk30.stp word file, which is used for other purposes, such as summarization.


Composing search expressions

The following rules apply to the composition of search expressions.

Case sensitivity

Verity searches are case-sensitive only when the search term is entered in mixed case. For example, a search for zeus finds zeus, Zeus, or ZEUS; however, a search for Zeus finds only Zeus.

To have your application always ignore the case that the user types, use the ColdFusion LCase () function in the criteria attribute of cfsearch. The following code converts user input to lowercase, thereby eliminating case-sensitivity concerns:

<cfsearch name="results"
    collection="#form.collname#"
    criteria="#LCase(form.criteria)#"
    type="#form.type#">

Prefix and infix notation

By default, Verity uses infix notation, in which precedence is implicit in the expression; for example, the AND operator takes precedence over the OR operator.

You can use prefix notation with any operator except an evidence operator (typically, STEM, WILDCARD, or WORD; for a description of evidence operators, see Evidence operators). In prefix notation, the expression explicitly specifies precedence. Rather than repeating an operator, you can use prefix notation to list the operator once and list the search targets in parentheses. For example, the following expressions are equivalent:

  • Moses <NEAR> Larry <NEAR> Jerome <NEAR> Daniel <NEAR> Jacob
  • <NEAR>(Moses,Larry,Jerome,Daniel,Jacob)

The following prefix notation example searches first for documents that contain Larry and Jerome, and then for documents that contain Moses:

OR (Moses, AND (Larry,Jerome))

The infix notation equivalent of this is as follows:

Moses OR (Larry AND Jerome)

Commas in expressions

If an expression includes two or more search terms within parentheses, a comma is required between the elements (whitespace is ignored). The following example searches for documents that contain any combination of Larry and Jerome together:

AND (Larry, Jerome)

Precedence rules

Expressions are read from left to right. The AND operator takes precedence over the OR operator; however, terms enclosed in parentheses are evaluated first. When the search engine encounters nested parentheses, it starts with the innermost term.

Example | Search result
Moses AND Larry OR Jerome | documents that contain Moses and Larry, or Jerome
(Moses AND Larry) OR Jerome | (same as above)
Moses AND (Larry OR Jerome) | documents that contain Moses and either Larry or Jerome

Delimiters in expressions

You use angle brackets (< >), double quotation marks ("), and backslashes (\) to delimit various elements in a search expression, as the following table describes:

Character | Usage
< > | Left and right angle brackets are reserved for designating operators and modifiers. They are optional for the AND, OR, and NOT, but required for all other operators.
" | Use double quotation marks in expressions to search for a word that is otherwise reserved as an operator or modifier, such as AND, OR, and NOT.
\ | To include a backslash in a search expression, insert two backslashes for each backslash character that you want included in the search; for example, C:\\CFusionmMX7\\bin.

Operators and modifiers

You are probably familiar with searches containing AND, OR, and NOT. Verity has many additional operators and modifiers, of various types, that offer you a high degree of specificity in setting search parameters.

Operators

An operator represents logic to be applied to a search element. This logic defines the qualifications that a document must meet to be retrieved. You can use operators to refine your search or to influence the results in other ways.

For example, you can construct an HTML form for conducting searches. In the form, you can search for a single term. You can refine the search by limiting the search scope in a number of ways. Operators are available for limiting a query to a sentence or paragraph, and you can search words based on proximity.

Ordinarily, you use operators in explicit searches, as follows:

"<operator>search_string"

The following operator types are available:

Operator type | Purpose
Concept | Identifies a concept in a document by combining the meanings of search elements.
Relational | Searches fields in a collection.
Evidence | Specifies basic and intelligent word searches.
Proximity | Specifies the relative location of words in a document.
Score | Manipulates the score returned by a search element. You can set the score percentage display to four decimal places.

The following table shows the operators, according to type, that are available for conducting searches of ColdFusion Verity collections:

Concept | Relational | Evidence | Proximity | Score
ACCRUE | < | STEM | NEAR | YESNO
ALL | <= | WILDCARD | NEAR/N | PRODUCT
AND | = | WORD | PARAGRAPH | SUM
ANY | > | THESAURUS | PHRASE | COMPLEMENT
OR | >= | SOUNDEX | SENTENCE |
 | CONTAINS | TYPO/N | IN |
 | MATCHES |  |  |
 | STARTS |  |  |
 | ENDS |  |  |
 | SUBSTRING |  |  |

Concept operators

Concept operators combine the meaning of search elements to identify a concept in a document. Documents retrieved using concept operators are ranked by relevance. The following table describes each concept operator:

Operator | Description
AND | Selects documents that contain all the search elements that you specify.
OR | Selects documents that show evidence of at least one of the search elements that you specify.
ACCRUE | Selects documents that include at least one of the search elements that you specify. Documents are ranked based on the number of search elements found.
ALL | Selects documents that contain all of the search elements that you specify. A score of 1.00 is assigned to each retrieved document. ALL and AND retrieve the same results, but queries using ALL are always assigned a score of 1.00.
ANY | Selects documents that contain at least one of the search elements that you specify. A score of 1.00 is assigned to each retrieved document. ANY and OR retrieve the same results, but queries using ANY are always assigned a score of 1.00.

Relational operators

Relational operators search document fields (such as AUTHOR) that you defined in the collection. Documents that contain specified field values are returned. Documents retrieved using relational operators are not ranked by relevance, and you cannot use the MANY modifier with relational operators.

You use the following operators for numeric and date comparisons:

Operator | Description
= | Equal
!= | Not equal
> | Greater than
>= | Greater than or equal to
< | Less than
<= | Less than or equal to

For example, to search for documents that contain values for 1999 through 2002, you perform either of the following searches:

  • A simple search for 1999,2000,2001,2002
  • An explicit search using the = operator: >=1999,<=2002

If a document field named PAGES is defined, you can search for documents that are 5 pages or fewer by entering PAGES < 5 in your search. Similarly, if a document field named DATE is defined, you can search for documents dated prior to and including December 31, 1999 by entering DATE <= 12-31-99 in your search.

The following relational operators compare text and match words and parts of words:

Operator

Description

Example

CONTAINS

Selects documents by matching the word or phrase that you specify with the values stored in a specific document field. Documents are selected only if the search elements specified appear in the same sequential and contiguous order in the field value.
  • In a document field named TITLE, to retrieve documents whose titles contain music, musical, or musician, search for TITLE <CONTAINS> Musi*.
  • To retrieve CFML and HTML pages whose meta tags contain Framingham as a content word, search for KEYWORD <CONTAINS> Framingham.

MATCHES

Selects documents by matching the query string with values stored in a specific document field. Documents are selected only if the search elements specified match the field value exactly. If a partial match is found, a document is not selected. When you use the MATCHES operator, you specify the field name to search, and the word, phrase, or number to locate. You can use ? and * to represent individual and multiple characters, respectively, within a string.

For examples, see the text immediately following this table.

STARTS

Selects documents by matching the character string that you specify with the starting characters of the values stored in a specific document field.

In a document field named REPORTER, to retrieve documents written by Clark, Clarks, and Clarkson, search for REPORTER <STARTS> Clark.

ENDS

Selects documents by matching the character string that you specify with the ending characters of the values stored in a specific document field.

In a document field named OFFICER, to retrieve arrest reports written by Tanner, Garner, and Milner, search for OFFICER <ENDS> ner.

SUBSTRING

Selects documents by matching the query string that you specify with any portion of the strings in a specific document field.

In a document field named TITLE, to retrieve documents whose titles contain words such as solution, resolution, solve, and resolve, search for TITLE <SUBSTRING> sol.

For example, assume a document field named SOURCE includes the following values:

  • Computer
  • Computerworld
  • Computer Currents
  • PC Computing

To locate documents whose source is Computer, enter the following:

SOURCE <MATCHES> computer

To locate documents whose source is Computer, Computerworld, and Computer Currents, enter the following:

SOURCE <MATCHES> computer*

To locate documents whose source is Computer, Computerworld, Computer Currents, and PC Computing, enter the following:

SOURCE <MATCHES> *comput*

For an example of ColdFusion code that uses the CONTAINS relational operator, see Field searches.

You can use the SUBSTRING operator to match a character string with data stored in a specified data source. In the example described in this section, a data source called TEST1 contains the table YearPlaceText, which contains three columns: Year, Place, and Text. Year and Place make up the primary key. The following table shows the TEST1 schema:

Year | Place | Text
1990 | Utah | Text about Utah 1990
1990 | Oregon | Text about Oregon 1990
1991 | Utah | Text about Utah 1991
1991 | Oregon | Text about Oregon 1991
1992 | Utah | Text about Utah 1992

The following application page matches records that have 1990 in the TEXT column and are in the Place Utah. The search operates on the collection that contains the TEXT column and then narrows further by searching for the string Utah in the CF_TITLE document field. Document fields are defaults defined in every collection corresponding to the values that you define for URL, TITLE, and KEY in the cfindex tag.

<cfquery name="GetText"
    datasource="TEST1">
    SELECT Year+Place AS Identifier, text
        FROM YearPlaceText
</cfquery>

<cfindex collection="testcollection"
    action="Update"
    type="Custom"
    title="Identifier"
    key="Identifier"
    body="TEXT"
    query="GetText">

<cfsearch name="GetText_Search"
    collection="testcollection"
    type="Explicit"
    criteria="1990 and CF_TITLE <SUBSTRING> Utah">
<cfoutput>
    Record Counts: <br>
    #GetText.RecordCount# <br>
    #GetText_Search.RecordCount# <br>
</cfoutput>

Query Results --- Should be 5 rows <br>
<cfoutput query="Gettext">
    #Identifier# <br>
</cfoutput>

Search Results -- should be 1 row <br>
<cfoutput query="GetText_Search">
    #GetText_Search.TITLE# <br>
</cfoutput>

Evidence operators

Evidence operators let you specify a basic word search or an intelligent word search. A basic word search finds documents that contain only the word or words specified in the query. An intelligent word search expands the query terms to create an expanded word list so that the search returns documents that contain variations of the query terms.

Documents retrieved using evidence operators are not ranked by relevance unless you use the MANY modifier.

The following table describes the evidence operators:

Operator | Description | Example
STEM | Expands the search to include the word that you enter and its variations. The STEM operator is automatically implied in any simple query. | <STEM>believe retrieves matches such as "believe," "believing," and "believer".
WILDCARD | Matches wildcard characters included in search strings. Certain characters automatically indicate a wildcard specification, such as apostrophe (*) and question mark(?). | spam* retrieves matches such as, spam, spammer, and spamming.
WORD | Performs a basic word search, selecting documents that include one or more instances of the specific word that you enter. The WORD operator is automatically implied in any SIMPLE query. | <WORD> logic retrieves logic, but not variations such as logical and logician.
THESAURUS | Expands the search to include the word that you enter and its synonyms. Collections do not have a thesaurus by default; to use this feature you must build one. | <THESAURUS> altitude retrieves documents containing synonyms of the word altitude, such as height or elevation.
SOUNDEX | Expands the search to include the word that you enter and one or more words that "sound like," or whose letter pattern is similar to, the word specified. Collections do not have sound-alike indexes by default; to use this feature you must build sound-alike indexes. | <SOUNDEX> sale retrieves words such as sale, sell, seal, shell, soul, and scale.
TYPO/N | Expands the search to include the word that you enter plus words that are similar to the query term. This operator performs "approximate pattern matching" to identify similar words. The optional N variable in the operator name expresses the maximum number of errors between the query term and a matched term, a value called the error distance. If N is not specified, the default error distance is 2. | <TYPO> swept retrieves kept.

The following example uses an evidence operator:

<cfsearch name = "quick_search"
    collection="bbb"
    type = "explicit"
    criteria="<WORD>film">

Proximity operators

Proximity operators specify the relative location of specific words in the document. To retrieve a document, the specified words must be in the same phrase, paragraph, or sentence. In the case of NEAR and NEAR/N operators, retrieved documents are ranked by relevance based on the proximity of the specified words. Proximity operators can be nested; phrases or words can appear within SENTENCE or PARAGRAPH operators, and SENTENCE operators can appear within PARAGRAPH operators.

The following table describes the proximity operators:

Operator

Description

Example

NEAR

Selects documents containing specified search terms. The closer the search terms are to one another within a document, the higher the document’s score. The document with the smallest possible region containing all search terms always receives the highest score. Documents whose search terms are not within 1000 words of each other are not selected.

war <NEAR> peace retrieves documents that contain stemmed variations of these words within close proximity to each other (as defined by Verity). To control search proximity, use NEAR/N.

NEAR/N

Selects documents containing two or more search terms within N number of words of each other, where N is an integer between 1 and 1024. NEAR/1 searches for two words that are next to each other. The closer the search terms are within a document, the higher the document's score.

You can specify multiple search terms using multiple instances of NEAR/N as long as the value of N is the same.

commute <NEAR/10> bicycle <NEAR/10> train <NEAR/10> retrieves documents that contain stemmed variations of these words within 10 words of each other.

PARAGRAPH

Selects documents that include all of the words you specify within the same paragraph. To search for three or more words or phrases in a paragraph, you must use the PARAGRAPH operator between each word or phrase.

<PARAGRAPH> (mission, goal, statement) retrieves documents that contain these terms within a paragraph.

PHRASE

Selects documents that include a phrase you specify. A phrase is a grouping of two or more words that occur in a specific order.

<PHRASE> (mission, oak) returns documents that contain the phrase mission oak.

SENTENCE

Selects documents that include all of the words you specify within the same sentence.

<SENTENCE> (jazz, musician) returns documents that contain these words in the same sentence.

IN

Selects documents that contain specified values in one or more document zones. A document zone represents a region of a document, such as the document’s summary, date, or body text. To search for a term only within the one or more zones that have certain conditions, you qualify the IN operator with the WHEN operator.

Chang <IN> author searches document zones named author for the word Chang.

The following example uses a proximity operator:

<cfsearch name = "quick_search"
    collection="bbb"
    type = "explicit"
    criteria="red<near>socks">

For an example using the IN proximity operator to search XML documents , see Zone searches.

Score operators

Score operators control how the search engine calculates scores for retrieved documents. The maximum score that a returned search element can have is 1.000. You can set the score to display a maximum of four decimal places.

When you use a score operator, the search engine first calculates a separate score for each search element found in a document, and then performs a mathematical operation on the individual element scores to arrive at the final score for each document.

The document’s score is available as a result column. You can use the SCORE result column to get the relevancy score of any document retrieved; for example:

<cfoutput>
    <a href="#Search1.URL#">#Search1.Title#</a><br>
    Document Score=#Search1.SCORE#<BR>
</cfoutput>

The following table describes the score operators:

Operator | Description | Example
YESNO | Forces the score of an element to 1 if the element’s score is nonzero. | <YESNO>mainframe. If the retrieval result of the search on mainframe is 0.75, the YESNO operator forces the result to 1. You can use YESNO to avoid relevance ranking.
PRODUCT | Multiplies the scores for the search elements in each document matching a query. | <PRODUCT>(computers, laptops) takes the product of the resulting scores.
SUM | Adds the scores for the search element in each document matching a query, up to a maximum value of 1. | <SUM>(computers, laptops) takes the sum of the resulting scores.
COMPLEMENT | Calculates scores for documents matching a query by taking the complement (subtracting from 1) of the scores for the query’s search elements. The new score is 1 minus the search element’s original score. | <COMPLEMENT>computers. If the search element’s original score is .785, the COMPLEMENT operator recalculates the score as .215.

Modifiers

You combine modifiers with operators to change the standard behavior of an operator in some way. The following table describes the available modifiers:

Modifier

Description

Example

CASE

Specifies a case-sensitive search. Normally, Verity searches are case-insensitive for search text entered in all uppercase or all lowercase, and case-sensitive for mixed-case search strings.

<CASE>Java OR <CASE>java retrieves documents that contain Java or java, but not JAVA.

MANY

Counts the density of words, stemmed variations, or phrases in a document and produces a relevance-ranked score for retrieved documents. Use with the following operators:

  • WORD
  • WILDCARD
  • STEM
  • PHRASE
  • SENTENCE
  • PARAGRAPH

<PARAGRAPH><MANY>javascript <AND> vbscript.

You cannot use the MANY modifier with the following operators:

  • AND
  • OR
  • ACCRUE
  • Relational operators

NOT

Excludes documents that contain the specified word or phrase. Use only with the AND and OR operators.

Java <AND> programming <NOT> coffee retrieves documents that contain Java and programming, but not coffee.

ORDER

Specifies that the search elements must occur in the same order in which you specify them in the query. Use with the following operators:

  • PARAGRAPH
  • SENTENCE
  • NEAR/N

Place the ORDER modifier before any operator.

<ORDER><PARAGRAPH> ("server", "Java") retrieves documents that contain server before Java.


Refining your searches with zones and fields

One of the strengths of Verity is its ability to perform full-text searches on documents of many formats. However, there are often times when you want to restrict a search to certain portions of a document, to improve search relevance. If a Verity collection contains some documents about baseball and other documents about caves, a search for the word bat might retrieve several irrelevant results.

If the documents are structured documents, you can take advantage of the ability to search zones and fields. The following are some examples of structured documents:

  • Documents created with markup languages (XML, SGML, HTML)
  • Internet Message Format documents
  • Documents created by many popular word-processing applications

Note: Although your word processor might open with what appears to be a blank page, the document has many regions such as title, subject, and author. Refer to your application’s documentation or online help system for how to view a document’s properties.

This section describes the following topics:

  • Zone searches
  • Field searches

Zone searches

You can perform zone searches on markup language documents. The Verity zone filter includes built-in support for HTML and several file formats; for a list of supported file formats, see Building a Search Interface. Verity searches XML files by treating the XML tags as zones. When you use the zone filter, the Verity engine builds zone information into the collection’s full-word index. This index, enhanced with zone information, permits quick and efficient searches over zones. The zone filter can automatically define a zone, or you can define it yourself in the style.zon file. You can use zone searching to limit your search to a particular zone. This can produce more accurate, but not necessarily faster, search results than searching an entire file.

Note: The contents of a zone cannot be returned in the results list of an application.

Examples

The following examples perform zone searching on XML files. In a list of rock bands, you could have XML files with tags for the instruments and for comments. In the following XML file, the word Pete appears in a comment field:

<band.xml>
     <Lead_Guitar>Dan</Lead_Guitar>
     <Rhythm_Guitar>Jake</Rhythm_Guitar>
     <Bass_Guitar>Mike</Bass_Guitar>
     <Drums>Chris</Drums>
     <COMMENT_A>Dan plays guitar, better than Pete.</COMMENT_A>
     <COMMENT_B>Jake plays rhythm guitar.</COMMENT_B>
</band.xml>

The following CFML code shows a search for the word Pete:

<cfsearch name = "band_search"
    collection="my_collection"
    type = "simple"
criteria="Pete">

The above search for Pete returns this XML file because this search target is in the COMMENT_A field. In contrast, Pete is the lead guitarist in the following XML file:

<band.xml>
     <Lead_Guitar>Pete</Lead_Guitar>
     <Rhythm_Guitar>Roger</Rhythm_Guitar>
    <Bass_Guitar>John</Bass_Guitar>
     <Drums>Kenny</Drums>
     <COMMENT_A>Who knows who's better than this band?</COMMENT_A>
     <COMMENT_B>Ticket prices correlated with decibels.</COMMENT_B>
</band.xml>

To retrieve only the files in which Pete is the lead guitarist, perform a zone search using the IN operator according to the following syntax:

(query) <IN> (zone1, zone2, ...)

Note: As with other operators, IN might be uppercase or lowercase. Unlike AND, OR, or NOT, you must enclose IN within brackets.

Thus, the following explicit search retrieves files in which Pete is the lead guitarist:

(Pete) <in> Lead_Guitar

This is expressed in CFML as follows:

<cfsearch name = "band_search"
    collection="my_collection"
    type = "explicit"
    criteria="(Pete) <in> Lead_Guitar">

To retrieve files in which Pete plays either lead or rhythm guitar, use the following explicit search:

(Pete) <in> (Lead_Guitar,Rhythm_Guitar)

This is expressed in CFML as follows:

<cfsearch name = "band_search"
    collection="bbb"
    type = "explicit"
    criteria="(Pete) <in> (Lead_Guitar,Rhythm_Guitar)">

Field searches

Fields are extracted from the document and stored in the collection for retrieval and searching, and can be returned on a results list. Zones, on the other hand, are merely the definitions of "regions" of a document for searching purposes, and are not physically extracted from the document in the same way that fields are extracted.

You must define a region of text as a zone before it can be a field. Therefore, it can be only a zone, or it can be both a field and a zone. Whether you define a region of text as a zone only or as both a field and a zone depends on your particular requirements.

A field must be defined in the style file, style.ufl, before you create the collection. To map zones to fields (to display field data), you must define and add these extra fields to style.ufl.

You can specify the values for the cfindex attributes TITLE, KEY, and URL as document fields for use with relational operators in the criteria attribute. (The SCORE and SUMMARY attributes are automatically returned by a cfsearch; these attributes are different for each record of a collection as the search criteria changes.) Text comparison operators can reference the following document fields:

  • cf_title
  • cf_key
  • cf_url
  • cf_custom1
  • cf_custom2
  • cf_custom3
  • cf_custom4

Text comparison operators can also reference the following automatically populated document fields:

  • title
  • key
  • url
  • vdksummary
  • author
  • mime-type

To explore how to use document fields to refine a search, consider the following database table, named Calls. This table has four columns and three records, as the following table shows:

call_ID | Problem_Description | Short_Description | Product
1 | Can’t bold text properly under certain conditions | Bold Problem | HomeSite+
2 | Certain optional attributes are acting as required attributes | Attributes Problem | ColdFusion
3 | Can’t do a File/Open in certain cases | File Open Problem | HomeSite+

A Verity search for the word certain returns three records. However, you can use the document fields to restrict your search; for example, a search to retrieve HomeSite+ problems with the word certain in the problem description.

These are the requirements to run this procedure:

  • Create and populate the Calls table in a database of your choice
  • Create a collection named Training (you can do this in CFML or in the ColdFusion MX Administrator).

The following table shows the relationship between the database column and cfindex attribute:

Database column | The cfindex attribute | Comment
call_ID | key | The primary key of a database table is often a key attribute.
Problem_Description | body | This column is the information to be indexed.
Short_Description | title | A short description is conceptually equivalent to a title, as in a running title of a journal article.
Product | custom1 | This field refines the search.

You begin by selecting all data in a query:

<cfquery name = "Calls" datasource = "MyDSN">
    Select * from Calls
</cfquery>

The following code shows the cfindex tag for indexing the collection (the type attribute is set to custom for tabular data):

<cfindex
    query = "Calls"
    collection = "training"
    action = "UPDATE"
    type = "CUSTOM"
    title = "Short_Description"
    key = "Call_ID"
    body = "Problem_Description"
    custom1 = "Product">

To perform the refined search for HomeSite+ problems with the word certain in the problem description, the cfsearch tag uses the CONTAINS operator in its criteria attribute:

<cfsearch
    collection = "training"
    name = "search_calls"
    criteria = "certain and CF_CUSTOM1 <CONTAINS> HomeSite">

The following code displays the results of the refined search:

<table border="1" cellspacing="5">
<tr>
    <th align="LEFT">KEY</th>
    <th align="LEFT">TITLE</th>
    <th align="LEFT">CUSTOM1</th>
</tr>

<cfoutput query = "search_calls">
<tr>
    <td>#KEY#</td>
    <td>#TITLE#</td>
    <td>#CUSTOM1#</td>
</tr>
</cfoutput>
</table>
Previous


Introduction to Retrieving and Formatting Data

This chapter provides an introduction to retrieving and formatting data. It describes how to use forms to get user data and how to control the data that is displayed by a dynamic web page. It also describes how to populate a table with query results and how to use Macromedia ColdFusion MX functions to format and manipulate data. This chapter assumes that you are familiar with HTML forms.

Contents

Using forms in ColdFusion MX

Working with action pages

Working with queries and data

Returning results to the user

Dynamically populating list boxes

Creating dynamic check boxes and multiple-selection list boxes
Next


Using forms in ColdFusion MX

ColdFusion MX lets you use a variety of types of forms. You can use plain HTML or CFML, and you can generate HTML, Macromedia Flash, or skinned XML forms. This section describes your form options and introduces a basic ColdFusion MX form.

  • ColdFusion forms tags
  • ColdFusion Form tag features
  • Creating a basic form
  • Forms guidelines

ColdFusion forms tags

You can use HTML or CFML tags to define your form. ColdFusion includes the following CFML tags that correspond to HTML tags, but provide additional functionality:

  • cfapplet
  • cfform
  • cfinput
  • cfselect
  • cftextarea

These tags support all the attributes of their HTML counterparts, plus ColdFusion attributes and features.

ColdFusion also provides the following forms tags that have no direct equivalent in HTML:

  • cfcalendar Lets users select dates from a Flash month-by-month calendar.
  • cfgrid Displays and lets users enter data in a row and column grid format; can get data directly from a query.
  • cfslider Lets users input data by moving a sliding marker.
  • cftree Displays data in a hierarchical tree format with graphical indicators; can get data directly from a query.


ColdFusion Form tag features

ColdFusion forms tags provide the following features:

Built-in validation support You can validate data in the client browser or on the server. You can specify that a field is required, contains a specific type of data, has a maximum length, or is in a range of values. You can also use data masking to control user input. For more information on validation, see Validating Data.

Note: ColdFusion also provides a method of doing on-server validation of HTML form controls.

Flash format forms and elements You can display a form as Flash, which works identically on a variety of platforms and provides additional display features not available in HTML. These features include accordion-style and multiple-tab form panes and automatic element positioning. You can also display cftree, cfgrid, and cfcalendar form elements as Flash items in an otherwise-HTML form. For more information on Flash forms and form elements, see Creating Forms in Macromedia Flash.

XML Skinable forms ColdFusion MX can generate XML forms and apply XSLT skins to format the forms. XML format forms let you separate the form presentation from the form logic and data field information. They give you detailed control over the appearance of the forms by applying custom skins, and let you create custom controls. For more information on XML skinnable forms, see Creating Skinnable XML Forms.

Direct support for ColdFusion variables You can easily use ColdFusion variables directly to populate your form controls. For example you can specify a query result to populate the cfgrid and cftree tags.

These features make CFML forms tags powerful and flexible, and let you easily develop fully featured, pleasing forms.

This chapter uses CFML tags, but does not describe or use most of their special features. Building Dynamic Forms with cfform Tags describes how to use many of the tags that are specific to ColdFusion, such as cftree and cfgrid. The other chapters listed above cover other CFML form tag features in detail.


Creating a basic form

The following simple form shows how you can create a form that lets a user enter data. This form uses basic CFML form tags. It does not use any of the advanced features of ColdFusion MX, such as validation, Flash or XML format, or special input controls. You could convert it to a purely HTML form by removing the initial "cf" prefix from the tag names, and the form would work.

Example form page and form control

The following table shows the format of form control tags:

Control

Code

Text control

<cfinput type="Text" name="ControlName" size="Value" maxlength="Value">

List (select) box

<cfselect name="ControlName">
    <option value="Value1">DisplayName1
    <option value="Value2">DisplayName2
    <option value="Value3">DisplayName3
</cfselect>

Radio buttons

<cfinput type="Radio" name="ControlName" value="Value1">DisplayName1
<cfinput type="Radio" name="ControlName" value="Value2">DisplayName2
<cfinput type="Radio" name="ControlName" value="Value3">DisplayName3

Check box

<cfinput type="Checkbox" name="ControlName" value="Yes|No">Yes

Reset button

<cfinput type="Reset" name="ControlName" value="DisplayName">

Submit button

<cfinput type="Submit" name="ControlName" value="DisplayName">

The following listing shows the form source in detail. To test the form and use it as input for later examples in this chapter, save this code as formpage.cfm.

<html>
<head>
<title>Input form</title>
</head>
<body>
<!--- Specify the action page in the form tag. The form variables will
        pass to this page when the form is submitted. --->

<cfform action="actionpage.cfm" method="post">

<!--- Text box. --->
<p>
First Name: <cfinput type="Text" name="FirstName" size="20"
maxlength="35"><br>
Last Name: <cfinput type="Text" name="LastName" size="20" maxlength="35"><br>
Salary: <cfinput type="Text" name="Salary" size="10" maxlength="10">
</p>

<!--- List box. --->
<p>
City
<cfselect name="City">
    <option value="Arlington">Arlington
    <option value="Boston">Boston
    <option value="Cambridge">Cambridge
    <option value="Minneapolis">Minneapolis
    <option value="Seattle">Seattle
</cfselect>
</p>

<!--- Radio buttons. --->
<p>
Department:<br>
<cfinput type="radio" name="Department" value="Training">Training<br>
<cfinput type="radio" name="Department" value="Sales">Sales<br>
<input type="radio" name="Department"
value="Marketing">Marketing<br>
</p>

<!--- Check box. --->
<p>
Contractor? <cfinput type="checkbox" name="Contractor"
value="Yes" checked>Yes
</p>

<!--- Reset button. --->
<cfinput type="Reset" name="ResetForm" value="Clear Form">
<!--- submit button --->
<cfinput type="Submit" name="SubmitForm" value="Submit">

</cfform>
</body>
</html>


Forms guidelines

When using forms, keep the following guidelines in mind:

  • To make the coding process easy to follow, name form controls the same as target database fields. For example, if a text control corresponds to a data source FirstName field, use FirstName as the control name.
  • For ease of use, limit radio buttons to between three and five mutually exclusive options. If you need more options, consider a drop-down list.
  • Use list boxes to allow the user to choose from many options or to choose multiple items from a list.
  • Check boxes, radio buttons, and list boxes do not pass data to action pages unless they are selected on a form. If you try to reference these variables on the action page, you receive an error if they are not present. For information on how to determine whether a variable exists on the action page, see Testing for a variable’s existence.
  • You can dynamically populate drop-down lists using query data. For more information, see Dynamically populating list boxes.


Working with action pages

When the user submits a form, ColdFusion runs the action page specified by the cfform or form tag action attribute. A ColdFusion action page is like any other application page, except that you can use the form variables that are passed to it from an associated form. The following sections describe how to create effective action pages.

  • Processing form variables on action pages
  • Using form data to generate SQL statements
  • Creating action pages
  • Testing for a variable’s existence
  • Requiring users to enter values in form fields
  • Form variable notes and considerations

Processing form variables on action pages

The action page gets a form variable for every form control that contains a value when the form is submitted.

Note: If multiple controls have the same name, one form variable is passed to the action page with a comma-delimited list of values.

A form variable’s name is the name that you assigned to the form control on the form page. Refer to the form variable by name within tags, functions, and other expressions on an action page.

On the action page, the form variables are in the Form scope, so you should prefix them with "Form." to explicitly tell ColdFusion that you are referring to a form variable. For example, the following code references the LastName form variable for output on an action page:

<cfoutput>
    #Form.LastName#
</cfoutput>

The Form scope also contains a list variable called Form.fieldnames. It contains a list of all form variables submitted to the action page. If no form variables are passed to the action page, ColdFusion does not create the Form.fieldnames list.


Using form data to generate SQL statements

As described in previous chapters, you can retrieve a record for every employee in a database table by composing a query like the following:

<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT  FirstName, LastName, Contract
    FROM   Employee
</cfquery>

When you want to return information about employees that matches user search criteria, you use the SQL WHERE clause with a SQL SELECT statement. When the WHERE clause is processed, it filters the query data based on the results of the comparison.

For example, to return employee data for only employees with the last name of Smith, you build a query that looks like the following:

<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT FirstName, LastName, Contract
    FROM    Employee
    WHERE  LastName = 'Smith'
</cfquery>

However, instead of putting the LastName directly in the SQL WHERE clause, you can use the text that the user entered in the form for comparison:

<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT FirstName, LastName, Salary
    FROM Employee
    WHERE LastName=<cfqueryparam value="#Form.LastName#"
CFSQLType="CF_SQL_VARCHAR">
</cfquery>

For security, this example encapsulates the form variable within the cfqueryparam tag to ensure that the user passed a valid string value for the LastName. For more information on using the cfqueryparam tag with queries and on dynamic SQL, see Accessing and Retrieving Data.


Creating action pages

Use the following procedure to create an action page for the formpage.cfm page that you created in the previous example.

To create an action page for the form:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>Retrieving Employee Data Based on Criteria from Form</title>
</head>

<body>
<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT FirstName, LastName, Salary
    FROM Employee
    WHERE LastName=<cfqueryparam value="#Form.LastName#"
    CFSQLType="CF_SQL_VARCHAR">
</cfquery>
<h4>Employee Data Based on Criteria from Form</h4>
<cfoutput query="GetEmployees">
#FirstName#
#LastName#
#Salary#<br>
</cfoutput>
<br>
<cfoutput>Contractor: #Form.Contractor#</cfoutput>
</body>
</html>
  2. Save the page as actionpage.cfm in the myapps directory.
  3. View the formpage.cfm page in your browser.
  4. Enter data, for example, Smith, in the Last Name box and submit the form.

    The browser displays a line with the first and last name and salary for each entry in the database that match the name you typed, followed by a line with the text "Contractor: Yes".

  5. Click Back in your browser to redisplay the form.
  6. Remove the check mark from the check box and submit the form again.

    This time an error occurs because the check box does not pass a variable to the action page. For information on modifying the actionpage.cfm page to fix the error, see Testing for a variable’s existence.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfquery name="GetEmployees"
datasource="cfdocexamples">

Queries the data source cfdocexamples and names the query GetEmployees.

SELECT FirstName, LastName, Salary
FROM Employee
WHERE LastName=<cfqueryparam
    value="#Form.LastName#"
    CFSQLType="CF_SQL_VARCHAR">

Retrieves the FirstName, LastName, and Salary fields from the Employee table, but only if the value of the LastName field matches what the user entered in the LastName text box in the form on formpage.cfm.

<cfoutput query="GetEmployees">

Displays results of the GetEmployees query.

#FirstName#
#LastName#
#Salary#<br>

Displays the value of the FirstName, LastName, and Salary fields for a record, starting with the first record, then goes to the next line. Keeps displaying the records that match the criteria you specified in the SELECT statement, followed by a line break, until you run out of records.

</cfoutput>

Closes the cfoutput block.

<br>
<cfoutput>Contractor: #Form.Contractor#
</cfoutput>

Displays a blank line followed by the text "Contractor": and the value of the form Contractor check box.

A more complete example would test to ensure the existence of the variable and would use the variable in the query.


Testing for a variable’s existence

Before relying on a variable’s existence in an application page, you can test to see if it exists using the ColdFusion IsDefined function. A function is a named procedure that takes input and operates on it. For example, the IsDefined function determines whether a variable exists. CFML provides a large number of functions, which are documented in CFML Reference.

The following code prevents the error in the previous example by checking to see whether the Contractor Form variable exists before using it:

<cfif IsDefined("Form.Contractor")>
<cfoutput>Contractor: #Form.Contractor#</cfoutput>
</cfif>

The argument passed to the IsDefined function must always be enclosed in double-quotation marks. For more information on the IsDefined function, see CFML Reference.

If you attempt to evaluate a variable that you did not define, ColdFusion cannot process the page and displays an error message. To help diagnose such problems, turn on debugging in the ColdFusion MX Administrator. The Administrator debugging information shows which variables are being passed to your application pages.


Requiring users to enter values in form fields

One of the limitations of HTML forms is the inability to define input fields as required. Because this is a particularly important requirement for database applications, ColdFusion lets you require users to enter data in fields. To specify a field as required, you can do either of the following:

  • Use the required attribute of the cfinput, cfselect, cftextarea, and cftree tags.
  • Use a hidden field that has a name attribute composed of the field name and the suffix "_required". You can use this technique with CFML and HTML form tags.

For example, to require that the user enter a value in the FirstName field of a cfinput tag, use the following syntax:

<cfinput type="Text" name="FirstName" size="20" maxlength="35" required="Yes">

To require that the user enter a value in the FirstName field of an HTML input tag, use the following syntax:

<input type="Text" name="FirstName" size="20" maxlength="35">
<input type="hidden" name="FirstName_required">

In either of these examples, if the user leaves the FirstName field empty, ColdFusion rejects the form submittal and returns a message informing the user that the field is required. You can customize the contents of this error message.

If you use a required attribute, you customize the message by using the message attribute, as follows:

<cfinput type="Text" name="FirstName" size="20" maxlength="35" required="Yes"
    message="You must enter your first name.">

If you use a hidden field tag, you customize the message using the value attribute of the hidden field, as follows:

<input type="hidden" name="FirstName_required"
    value="You must enter your first name.">


Form variable notes and considerations

When using form variables in an action page, keep the following guidelines in mind:

  • A form variable is available on the action page and pages that it includes.
  • Prefix form variables with "Form." when referencing them on the action page.
  • Surround variable values with number signs (#) for output.
  • Variables for check boxes, radio buttons, and list boxes with size attributes greater than 1 only get passed to the action page if you select an option. Text boxes, passwords, and textarea fields pass an empty string if you do not enter text.
  • An error occurs if the action page tries to use a variable that was not passed.
  • If multiple controls have the same name, one form variable is passed to the action page with a comma-delimited list of values.
  • You can validate form variable values on the client or the server.


Working with queries and data

The ability to generate and display query data is one of the most important and flexible features of ColdFusion. The following sections describe more about using queries and displaying their results. Some of these tools are effective for presenting any data, not just query results.

  • Using HTML tables to display query results
  • Formatting individual data items
  • Building flexible search interfaces

Using HTML tables to display query results

You can use HTML tables to specify how the results of a query appear on a page. To do so, you put the cfoutput tag inside the table tags. You can also use the HTML th tag to put column labels in a header row. To create a row in the table for each row in the query results, put the tr block inside the cfoutput tag.

In addition, you can use CFML functions to format individual pieces of data, such as dates and numeric values.

To put the query results in a table:

  1. Open the ColdFusion actionpage.cfm page in your editor.
  2. Modify the page so that it appears as follows:
    <html>
<head>
<title>Retrieving Employee Data Based on Criteria from Form</title>
</head>

<body>
<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT FirstName, LastName, Salary
    FROM Employee
    WHERE LastName=<cfqueryparam value="#Form.LastName#"
    CFSQLType="CF_SQL_VARCHAR">
</cfquery>
<h4>Employee Data Based on Criteria from Form</h4>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Salary</th>
</tr>
<cfoutput query="GetEmployees">
<tr>
<td>#FirstName#</td>
<td>#LastName#</td>
<td>#Salary#</td>
</tr>
</cfoutput>
</table>
<br>
<cfif IsDefined("Form.Contractor")>
    <cfoutput>Contractor: #Form.Contractor#</cfoutput>
</cfif>
</body>
</html>
  3. Save the page as actionpage.cfm in the myapps directory.
  4. View the formpage.cfm page in your browser.
  5. Enter Smith in the Last Name text box and submit the form.

    The records that match the criteria specified in the form appear in a table.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<table>

Puts data into a table.

<tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Salary</th>
</tr>

In the first row of the table, includes three columns, with the headings: First Name, Last Name, and Salary.

<cfoutput query="GetEmployees">

Tells ColdFusion to display the results of the GetEmployees query.

<tr>
    <td>#FirstName#</td>
    <td>#LastName#</td>
    <td>#Salary#</td>
</tr>

For each record in the query, creates a new row in the table, with three columns that display the values of the FirstName, LastName, and Salary fields of the record.

</cfoutput>

Ends the output region.

</table>

Ends the table.


Formatting individual data items

You can format individual data items. For example, you can format the salary data as monetary values. To format the salary data using the dollar format, you use the CFML function DollarFormat (number).

To change the format of the Salary:

  1. Open the file actionpage.cfm in your editor.
  2. Change the following line:
    <td>#Salary#</td>

    to

    <td>#DollarFormat(Salary)#</td>
  3. Save the page.


Building flexible search interfaces

One option with forms is to build a search based on the form data. For example, you could use form data as part of the WHERE clause to construct a database query.

To give users the option to enter multiple search criteria in a form, you can wrap conditional logic around a SQL AND clause as part of the WHERE clause. The following action page allows users to search for employees by department, last name, or both.

Note: ColdFusion MX provides the Verity search utility that you can also use to perform a search. For more information, see Building a Search Interface.

To build a more flexible search interface:

  1. Open the ColdFusion actionpage.cfm page in your editor.
  2. Modify the page so that it appears as follows:
    <html>
<head>
<title>Retrieving Employee Data Based on Criteria from Form</title>
</head>
<body>
<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT Departmt.Dept_Name,
        Employee.FirstName,
        Employee.LastName,
        Employee.StartDate,
        Employee.Salary
    FROM Departmt, Employee
    WHERE Departmt.Dept_ID = Employee.Dept_ID
    <cfif IsDefined("Form.Department")>
    AND Departmt.Dept_Name    =<cfqueryparam value="#Form.Department#"
                CFSQLType="CF_SQL_VARCHAR">
    </cfif>
    <cfif Form.LastName IS NOT "">
        AND Employee.LastName=<cfqueryparam value="#Form.LastName#"
                CFSQLType="CF_SQL_VARCHAR">
    </cfif>
</cfquery>

<h4>Employee Data Based on Criteria from Form</h4>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Salary</th>
</tr>
<cfoutput query="GetEmployees">
<tr>
<td>#FirstName#</td>
<td>#LastName#</td>
<td>#Salary#</td>
</tr>
</cfoutput>
</table>
</body>
</html>
  3. Save the file.
  4. View the formpage.cfm page in your browser.
  5. Select a department, optionally enter a last name, and submit the form.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

SELECT  Departmt.Dept_Name,
    Employee.FirstName,
    Employee.LastName,
    Employee.StartDate,
    Employee.Salary
    FROM Departmt, Employee
    WHERE Departmt.Dept_ID =
        Employee.Dept_ID

Retrieves the fields listed from the Departmt and Employee tables, joining the tables based on the Dept_ID field in each table.

    <cfif IsDefined("FORM.Department")>
    AND Departmt.Dept_Name = <cfqueryparam
        value="#Form.Department#"
        CFSQLType="CF_SQL_VARCHAR">
    </cfif>

If the user specified a department on the form, only retrieves records where the department name is the same as the one that the user specified. You must use number signs (#) in the SQL AND statement to identify Form.Department as a ColdFusion variable, but not in the IsDefined function.

<cfif Form.LastName IS NOT "">
AND Employee.LastName = <cfqueryparam
        value="#Form.LastName#"
        CFSQLType="CF_SQL_VARCHAR">
</cfif>

If the user specified a last name in the form, only retrieves the records in which the last name is the same as the one that the user entered in the form.


Returning results to the user

When you return your results to the user, you must make sure that your pages respond to the user’s needs and are appropriate for the type and amount of information. In particular, you must consider the following situations:

  • When there are no query results
  • When you return partial results

Handling no query results

Your code must accommodate the cases in which a query does not return any records. To determine whether a search has retrieved records, use the RecordCount query variable. You can use the variable in a conditional logic expression that determines how to display search results appropriately to users.

Note: For more information on query variables, including RecordCount, see Accessing and Retrieving Data.

For example, to inform the user when no records were found by the GetEmployees query, insert the following code before displaying the data:

<cfif GetEmployees.RecordCount IS "0">
    No records match your search criteria. <BR>
<cfelse>

You must do the following:

  • Prefix RecordCount with the query name.
  • Add a procedure after the cfif tag that displays a message to the user.
  • Add a procedure after the cfelse tag to format the returned data.
  • Follow the second procedure with a </cfif> tag end to indicate the end of the conditional code.

To return search results to users:

  1. Edit the actionpage.cfm page.
  2. Change the page so that it appears as follows:
    <html>
<head>
<title>Retrieving Employee Data Based on Criteria from Form</title>
</head>

<body>
<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT Departmt.Dept_Name,
        Employee.FirstName,
        Employee.LastName,
        Employee.StartDate,
        Employee.Salary
    FROM Departmt, Employee
    WHERE Departmt.Dept_ID = Employee.Dept_ID
    <cfif isdefined("Form.Department")>
        AND Departmt.Dept_Name = <cfqueryparam value="#Form.Department#"
                CFSQLType="CF_SQL_VARCHAR">
    </cfif>
    <cfif Form.LastName is not "">
        AND Employee.LastName = <cfqueryparam value="#Form.LastName#"
                CFSQLType="CF_SQL_VARCHAR">
    </cfif>
</cfquery>

<cfif GetEmployees.recordcount is "0">
No records match your search criteria. <br>
Please go back to the form and try again.
<cfelse>
<h4>Employee Data Based on Criteria from Form</h4>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Salary</th>
</tr>
<cfoutput query="GetEmployees">
<tr>
<td>#FirstName#</td>
<td>#LastName#</td>
<td>#Salary#</td>
</tr>
</cfoutput>
</cfif>
</table>
</body>
</html>
  3. Save the file.
  4. Return to the form, enter search criteria, and submit the form.
  5. If no records match the criteria you specified, the message appears.

Returning results incrementally

You can use the cfflush tag to incrementally display long-running requests to the browser before a ColdFusion page is fully processed. This tag lets you give the user quick feedback when it takes a long time to complete processing a request. For example, when a request takes time to return results, you can use the cfflush tag to display the message, "Processing your request -- please wait." You can also use it to incrementally display a long list as it gets retrieved.

The first time you use the cfflush tag on a page, it sends to the browser all of the HTML headers and any other available HTML. Subsequent cfflush tags on the page send only the output that ColdFusion generated after the previous flush.

You can specify an interval attribute to tell ColdFusion to flush the output each time that at least the specified number of bytes become available. (The count does not include HTML headers and any data that is already available when you make this call.) You can use the cfflush tag in a cfloop tag to incrementally flush data as it becomes available. This format is particularly useful when a query responds slowly with large amounts of data.

When you flush data, make sure that a sufficient amount of information is available, because some browsers might not respond if you flush only a very small amount. Similarly, if you use an interval attribute, set it for a reasonable size, such as a few hundred bytes or more, but not many thousands of bytes.

Limitations of the cfflush tag Because the cfflush tag sends data to the browser when it executes, it has several limitations, including the following:

  • Using any of the following tags or functions on a page anywhere after the cfflush tag can cause errors or unexpected results: cfcontent, cfcookie, cfform, cfheader, cfhtmlhead, cflocation, and SetLocale. (These tags and functions normally modify the HTML header, but cannot do so after a cfflush tag, because the cfflush tag sends the header.)
  • Using the cfset tag to set a cookie anywhere on a page that has a cfflush tag does not set the cookie in the browser.
  • Using the cfflush tag within the body of several tags, including cfsavecontent, cfquery, and custom tags, can cause errors.
  • If you save Client variables as cookies, any client variables that you set after a cfflush tag are not saved in the browser.
  • You can catch cfflush errors, except Cookie errors, with a cfcatch type="template" tag. Catch cookie errors with a cfcatch type="Any" tag.

Example: using the cfloop tag and Rand function

The following example uses the cfloop tag and the Rand random number generating function to artificially delay the generation of data for display. It simulates a situation in which it takes time to retrieve the first data and additional information becomes available slowly.

<html>
<head>
    <title>Your Magic numbers</title>
</head>

<body>
<h1>Your Magic numbers</h1>
<P>It will take us a little while to calculate your ten magic numbers.
It takes a lot of work to find numbers that truly fit your personality.
So relax for a minute or so while we do the hard work for you.</P>
<h2>We are sure you will agree it was worth the short wait!</h2>
<cfflush>

<cfflush interval=10>
<!--- Delay Loop to make is seem harder. --->
<cfloop index="randomindex" from="1" to="200000" step="1">
    <cfset random=rand()>
</cfloop>

<!--- Now slowly output 10 random numbers. --->
<cfloop index="Myindex" from="1" to="10" step="1">
    <cfloop index="randomindex" from="1" to="100000" step="1">
        <cfset random=rand()>
    </cfloop>
    <cfoutput>
        Magic number #Myindex# is:&nbsp;&nbsp;#RandRange(
100000, 999999)#<br><br>
    </cfoutput>
</cfloop>
</body>
</html>

Reviewing the code

The following table describes the code and its function:

Code

Description

<h2>We are sure you will agree it was
    worth the short wait!</h2>
<cfflush>

Sends the HTML header and all HTML output to the cfflush tag to the user. This displays the explanatory paragraph and H2 tag contents.

<cfflush interval=10>

Flushes additional data to the user whenever at least 10 bytes are available.

<cfloop index="randomindex" from="1"
        to="200000" step="1">
    <cfset random=Rand()>
</cfloop>

Inserts an artificial delay by using the Rand function to calculate many random numbers.

<cfloop index="Myindex" from="1"
        to="10" step="1">
    <cfloop index="randomindex"
        from="1" to="100000" step="1">
    <cfset random=rand()>
    </cfloop>
    <cfoutput>
    Magic number #Myindex#
        is:&nbsp;&nbsp;#RandRange
        (100000,999999)#<br><br>
    </cfoutput>
</cfloop>

Generates and displays 10 random numbers. This code uses two loops. The outer loop repeats ten times, once for each number to display. The inner loop uses the Rand function to create another delay by generating more (unused) random numbers. It then calls the RandRange function to generate a six-digit random number for display.


Dynamically populating list boxes

The code in Creating a basic form hard-coded the form’s list box options. Instead of manually entering the information on a form, you can dynamically populate a list box with database fields. When you write code this way, the form page automatically reflects the changes that you make to the database.

You use two tags to dynamically populate a list box:

  • Use the cfquery tag to retrieve the column data from a database table.
  • Use the cfoutput tag with the query attribute within the select tag to dynamically populate the options of this form control.

To dynamically populate a list box:

  1. Open the formpage.cfm page.
  2. Modify the file so that it appears as follows:
    <html>
<head>
<title>Input form</title>
</head>
<body>
<cfquery name="GetDepartments" datasource="cfdocexamples">
    SELECT DISTINCT Location
    FROM Departmt
</cfquery>

<!--- Define the action page in the form tag.
    The form variables pass to this page
    when the form is submitted --->

<cfform action="actionpage.cfm" method="post">

<!--- Text box. --->
<p>
First Name: <cfinput type="Text" name="FirstName" size="20" maxlength="35"><br>
Last Name: <cfinput type="Text" name="LastName" size="20" maxlength="35"><br>
Salary: <cfinput type="Text" name="Salary" size="10" maxlength="10">
</p>

<!--- List box. --->
City
<cfset optsize=getDepartments.recordcount + 1>
<cfselect name="City" query="GetDepartments" value="Location" size="#optsize#">
    <option value="">Select All
</cfselect>

<!--- Radio buttons. --->
<p>
Department:<br>
<cfinput type="radio" name="Department" value="Training">Training<br>
<cfinput type="radio" name="Department" value="Sales">Sales<br>
<cfinput type="radio" name="Department" value="Marketing">Marketing<br>
<cfinput type="radio" name="Department" value="HR">HR<br>
</p>

<!--- Check box. --->
<p>
Contractor? <cfinput type="checkbox" name="Contractor" value="Yes" checked>Yes
</p>

<!--- Reset button. --->
<cfinput type="reset" name="ResetForm" value="Clear Form">

<!--- Submit button. --->
<cfinput type="submit" name="SubmitForm" value="Submit">
</cfform>
</body>
</html>
  3. Save the page as formpage.cfm.
  4. View the formpage.cfm page in a browser.

    The changes that you just made appear in the form.

    Remember that you need an action page to submit values.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfquery name="GetDepartments"
datasource="cfdocexamples">
SELECT DISTINCT Location
FROM Departmt
</cfquery>

Gets the locations of all departments in the Departmt table. The DISTINCT clause eliminates duplicate location names from the returned query results.

<cfset optsize=getDepartments.recordcount + 1>

Sets the optsize variable to the number of entries to add dynamically to the selection list, plus one for the manually coded Select All option.

<cfselect name="City" query="GetDepartments" value="Location" size="#optsize#">
    <option value="">Select All
</cfselect>

Populates the City selection list from the Location column of the GetDepartments query. The control has one option for each row returned by the query.

Adds an option that allows users to select all locations. If the user selects this option, the form value is an empty string. The action page must check for the empty string and handle it appropriately.


Creating dynamic check boxes and multiple-selection list boxes

When an HTML or CFML form contains a list of check boxes with the same name or a multiple-selection list box (that is, a box in which users can select multiple items from the list), the user’s entries are made available as a comma-delimited list with the selected values. These lists can be very useful for a wide range of input types.

Note: If the user does not select a check box or make a selection from a list box, no variable is created. The cfinsert and cfupdate tags do not work correctly if there are no values. To prevent errors, make the form fields required, use dynamic SQL, or use the cfparam tag to set a default value for the form field.

This section describes the following topics:

  • Check boxes
  • Multiple selection lists


Check boxes

When you put a series of check boxes with the same name in a form, the variable that is created contains a comma-delimited list of values. The values can be either numeric values or alphanumeric strings. These two types of values are treated slightly differently.

Handling numeric values

Suppose you want a user to select one or more departments using check boxes. You then query the database to retrieve detailed information on the selected department(s). The code for a simple set of check boxes that lets the user select departments looks like the following:

<cfinput type="checkbox"
    name="SelectedDepts"
    value="1">
    Training<br>

<cfinput type="checkbox"
    name="SelectedDepts"
    value="2">
    Marketing<br>

<cfinput type="checkbox"
    name="SelectedDepts"
    value="3">
    HR<br>

<cfinput type="checkbox"
    name="SelectedDepts"
    value="4">
    Sales<br>
</html>

The user sees the name of the department, but the value attribute of each check box is a number that corresponds to the underlying database primary key for the department’s record.

If the user checks the Marketing and Sales items, the value of the SelectedDepts form field is 2,4 and you use the SelectedDepts value in the following SQL statement:

SELECT *
    FROM Departmt
    WHERE Dept_ID IN ( #Form.SelectedDepts# )

The ColdFusion server sends the following statement to the database:

SELECT *
    FROM Departmt
    WHERE Dept_ID IN ( 2,4 )

Handling string values

To search for a database field that contains string values (instead of numeric), you must modify the checkbox and cfquery syntax to make sure that the string values are sent to the data source in single-quotation marks (').

The first example searched for department information based on a numeric primary key field called Dept_ID. Suppose, instead, that the primary key is a database field called Dept_Name that contains string values. In that case, your code for check boxes should look like the following:

<cfinput type="checkbox"
    name="SelectedDepts"
    value="Training">
    Training<br>

<cfinput type="checkbox"
    name="SelectedDepts"
    value="Marketing">
    Marketing<br>

<cfinput type="checkbox"
    name="SelectedDepts"
    value="HR">
    HR<br>

<cfinput type="checkbox"
    name="SelectedDepts"
    value="Sales">
    Sales<br>

If the user checked Marketing and Sales, the value of the SelectedDepts form field would be the list Marketing,Sales and you use the following SQL statement:

SELECT *
    FROM Departmt
    WHERE Dept_Name IN
    (#ListQualify(Form.SelectedDepts,"'")#)

In SQL, all strings must be surrounded in single-quotation marks. The ListQualify function returns a list with the specified qualifying character (here, a single-quotation mark) around each item in the list.

If you select the second and fourth check boxes in the form, the following statement gets sent to the database:

SELECT *
    FROM Departmt
    WHERE Dept_Name IN ('Marketing','Sales')


Multiple selection lists

A multiple-selection list box is defined by a select or cfselect tag with a multiple or multipe="yes" attribute and a size attribute value greater than 1. ColdFusion treats the result when a user selects multiple choices from a multiple-selection list box like the results of selecting multiple check boxes. The data made available to your page from any multiple-selection list box is a comma-delimited list of the entries selected by the user; for example, a list box could contain the four entries: Training, Marketing, HR, and Sales. If the user selects Marketing and Sales, the form field variable value is Marketing,Sales.

You can use multiple-selection lists to search a database in the same way that you use check boxes. The following sections describe how you can use different types of multiple-selection data values.

  • Handling numeric values
  • Handling string values

Handling numeric values

Suppose you want the user to select departments from a multiple-selection list box. The query retrieves detailed information on the selected department(s), as follows:

Select one or more companies to get more information on:
<cfselect name="SelectDepts" multiple>
    <option value="1">Training
    <option value="2">Marketing
    <option value="3">HR
    <option value="4">Sales
</cfselect>

If the user selects the Marketing and Sales items, the value of the SelectDepts form field is 2,4. If this parameter is used in the following SQL statement:

SELECT *
    FROM Departmt
    WHERE Dept_ID IN (#form.SelectDepts#)

The following statement is sent to the database:

SELECT *
    FROM Departmt
    WHERE Dept_ID IN (2,4)

Handling string values

Suppose you want the user to select departments from a multiple-selection list box. The database search field is a string field. The query retrieves detailed information on the selected department(s), as follows:

<cfselect name="SelectDepts" multiple>
    <option value="Training">Training
    <option value="Marketing">Marketing
    <option value="HR">HR
    <option value="Sales">Sales
</cfselect>

If the user selects the Marketing and Sales items, the SelectDepts form field value is Marketing,Sales.

Just as you did when using check boxes to search database fields containing string values, use the ColdFusion ListQualify function with multiple-selection list boxes:

SELECT *
    FROM Departmt
    WHERE Dept_Name IN (#ListQualify(Form.SelectDepts,"'")#)

The following statement is sent to the database:

SELECT *
    FROM Departmt
    WHERE Dept_Name IN ('Marketing','Sales')
Previous


Building Dynamic Forms with cfform Tags

This chapter describes some of the ways that you can use the cfform tag to create rich, dynamic forms with sophisticated graphical controls, including several Java applet or Macromedia Flash controls. You can use these controls without writing a line of Java or Flash code. This chapter describes the cfform tag and its child tags, and covers using several of the form controls, independent of the output format.

Contents

Creating custom forms with the cfform tag

Building tree controls with the cftree tag

Building drop-down list boxes

Building slider bar controls

Creating data grids with the cfgrid tag

Embedding Java applets
Next


Creating custom forms with the cfform tag

The cfform tag and its CFML subtags let you create dynamic forms in three formats:

HTML Generates standard HTML tags wherever possible, and uses applets or Flash for more complex controls, such as grids, trees, and calendars. HTML format lets you present a familiar appearance, but does not let you easily separate data and presentation, or provide some of the more complex structures, such as Flash tabbed navigators or accordions, or customized XML controls.

Flash Presents a modern, visually pleasing appearance. Flash format supports several controls, such as tabbed navigators and accordions, that are not available in HTML format. Flash forms are also browser-independent. In Flash format, Flash Player works in all commonly used browsers on Windows and Macintosh systems, and in Netscape and Mozilla on Linux.

XML Lets you specify an Extensible Stylesheet Language Transformation (XSLT) skin that converts the XML into styled HTML output. ColdFusion MX provides several skins that you can use, and you can write your own custom skins and support custom controls.

The cfform tag and its subtags also provide you with several methods for validating input data. For example, you can perform the validation on the browser or on the server. You can check the data type, or you can mask data input.

Individual cfform tags have additional dynamic features. Several of the tags do not have HTML counterparts, and others directly support dynamically populating the control from data sources. Also, the cfform tag preservedata attribute retains user input in a form after the user submits the form, so the data reappears if the form gets redisplayed.

This chapter describes features of the cfform tag and focuses on using several of the cfform child tags that do not have HTML counterparts. The following chapters describe other features of ColdFusion forms that you create using the cfform tag:

  • Validating Data
  • Creating Forms in Macromedia Flash
  • Creating Skinnable XML Forms

This section describes the following topics:

  • The cfform controls
  • Preserving input data with the preservedata attribute
  • Browser considerations


The cfform controls

The following table describes the ColdFusion controls that you use in forms created using the cfform tag. You can use these tags only inside a cfform tag. Unless otherwise stated, these controls are supported in HTML, Flash, and XML skinable forms.

Control | Description | For more information
cfapplet | Embeds a custom Java applet in the form. Not supported in Flash format forms. | Embedding Java applets.
cfcalendar | Displays an interactive Macromedia Flash calendar that can be included in an HTML or Flash format form. ignored in XML skinable forms. The calendar lets a user select a date for submission as a form variable. | The cfcalendar tag in CFML Reference
cfformgroup | Creates a container control for organizing and formatting multiple form controls. Used in the cfform tag body of Macromedia Flash and XML skinable forms. Ignored in HTML forms. | Creating Forms in Macromedia Flash, Creating Skinnable XML Forms
cfformitem | Inserts a horizontal line, a vertical line, or formatted or unformatted text in a Flash form. Used in the cfform or cfformgroup tag body for Flash and XML forms. Ignored in HTML forms. | Creating Forms in Macromedia Flash, Creating Skinnable XML Forms
cfgrid | Creates a Java applet or Flash data grid that you can populate from a query or by defining the contents of individual cells. You can also use grids to insert, update, and delete records from a data source. | Creating data grids with the cfgrid tag
cfinput | Equivalent to the HTML input tag, with the addition of input validation. | Creating a basic form
cfselect | Displays a selection box. Equivalent to the HTML select tag, with the addition of input validation. | Building drop-down list boxes
cfslider | Creates a Java applet-based control that lets users enter data by moving a slider. Not supported in Flash format forms. | Building slider bar controls
cftextarea | Displays a text input area. Equivalent to the HTML textarea tag, with the addition of input validation. | The cftextarea tag in CFML Reference
cftree | Creates a Java applet or Flash hierarchical tree-format control that can include graphical images for the different elements. Can also generate a ColdFusion structure that represents the tree data and attributes. | Building tree controls with the cftree tag


Preserving input data with the preservedata attribute

The cfform preservedata attribute tells ColdFusion to continue displaying the user data in a form after the user submits the form. Data is preserved in the cfinput, cfslider, cftextinput, and cftree controls and in cfselect controls populated by queries. If you specify a default value for a control, and a user overrides that default in the form, the user input is preserved.

You can retain data on the form when the same page contains the form and the form’s action code; that is, the form submits to itself. You can also retain the data if the action page has a copy of the form, and the control names are the same in the forms on both pages. (The action page form does not need to be identical to the initial form. It can have more or fewer elements than the initial page form; only the form elements with identical names on both pages keep their data.)

Note: The preservedata setting on the action page controls the preservation of the data.

For example, if you save this form as preserve.cfm, it continues to display any text that you enter after you submit it, as follows:

<cfform action="preserve.cfm" preservedata="Yes">
    <p>Please enter your name:
    <cfinput type="Text" name="UserName" required="Yes"><p>
    <input type="Submit" name=""> <input type="RESET">
</cfform>

Usage notes for the preservedata attribute

When you use the preservedata attribute, follow these guidelines:

  • In the cftree tag, the preservedata attribute causes the tree to expand to the previously selected element. For this to work correctly, you must also set the completePath attribute to True.
  • The preservedata attribute has no effect on a cfgrid tag. If you populate the control from a query, you must update the data source with the new data (typically by using a cfgridupdate tag) before redisplaying the grid. The grid then displays the updated database information.


Browser considerations

The applet-based versions of the cfgrid, cfslider, and cftree forms use JavaScript and Java to display their content. To allow them to display consistently across a variety of browsers, these applets use the Java plug-in. As a result, they are independent of the level of Java support provided by the browser.

ColdFusion downloads and installs the browser plug-in if necessary. Some browsers display a single permission dialog box asking you to confirm the plug-in installation. Other browsers, particularly older versions of Netscape, require you to navigate some simple option windows.

Because the controls use JavaScript to return data to ColdFusion, if you disable JavaScript in your browser, it cannot properly run forms that contain these controls. In that case, the controls still display, but data return and validation does not work and you can receive a JavaScript error.

Because Java is handled by the plug-in and not directly by the browser, disabling Java execution in the browser does not affect the operation of the controls. If for some other reason, however, the browser is unable to render the controls as requested, a "not supported" message appears in place of the control.

You can use the cfform tag’s notsupported attribute to specify an alternative error message.

You can avoid browser Java and JavaScript issues with the cfgrid and cftree controls by using the Flash format versions of these controls. These controls work on Windows, Mac OS X, and Linux, and do not rely on Java support. There is no Flash format version of the cfslider control, and there is no applet format version of the cfcalendar control.


Building tree controls with the cftree tag

The cftree tag lets you display hierarchical information within a form in a space-saving collapsible tree populated from data source queries. To build a tree control with the cftree tag, you use individual cftreeitem tags to populate the control..

You can create trees in three formats:

Applet Creates a Java applet that the client must download. Downloading an applet takes time; therefore, using the cftree tag can be slightly slower than using an HTML form element to retrieve the same information. In addition, browsers must be Java-enabled for the cftree tag to work properly.

Flash Generates a Flash control that you can include in an HTML or Flash format form. For more information on Flash Format see Creating Forms in Macromedia Flash.

Object Creates a hierarchical ColdFusion structure that represents the tree data and many of the cftree and cftreeitem attributes.

The different formats support different sets of features and attributes. This section discusses general techniques that apply to all three formats, and indicates any techniques that do not apply to a specific format. It uses applet format for all examples, which use applet-specific attributes. For details on the features and attributes supported in each format, see the cftree entry in CFML Reference.

To create and populate a tree control from a query:

  1. Create a ColdFusion page with the following content:
    <cfquery name="engquery" datasource="cfdocexamples">
    SELECT FirstName + ' ' + LastName AS FullName
    FROM Employee
</cfquery>
<cfform name="form1" action="submit.cfm">
<cftree name="tree1"
    required="Yes"
    hscroll="No">
    <cftreeitem value="FullName"
        query="engquery"
        queryasroot="Yes"
        img="folder,document">
</cftree>
</cfform>
  2. Save the page as tree1.cfm and view it in your browser.

    The following figure shows the output of this CFML page:

    Tree control populated from a query

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cftree name="tree1"

Creates a tree and names it tree1.

required="Yes"

Specifies that a user must select an item in the tree.

hscroll="No"

Does not allow horizontal scrolling.

<cftreeitem value="FullName"
query="engquery"

Creates an item in the tree and puts the results of the query named engquery in it. Because this tag uses a query, it puts one item on the tree per query entry.

queryasroot="Yes"

Specifies the query name as the root level of the tree control.

img="folder,document"

Uses the folder and document images that ship with ColdFusion in the tree structure.

When populating a cftree tag with data from a cfquery tag, you can specify images or filenames for each level of the tree as a comma-separated list.

This section describes the following topics:

  • Grouping output from a query
  • The cftree form variables
  • Input validation
  • Structuring tree controls
  • Image names in a cftree tag
  • Embedding URLs in a cftree tag
  • Specifying the tree item in the URL


Grouping output from a query

In a query that you display using a cftree control, you might want to organize your employees by department. In this case, you separate column names with commas in the cftreeitem value attribute.

To organize the tree based on ordered results of a query:

  1. Create a ColdFusion page named tree2.cfm with the following content:
    <!--- CFQUERY with an ORDER BY clause. --->
<cfquery name="deptquery" datasource="cfdocexamples">
    SELECT Dept_ID, FirstName + ' ' + LastName
    AS FullName
    FROM Employee
    ORDER BY Dept_ID
</cfquery>

<!--- Build the tree control. --->
<cfform name="form1" action="submit.cfm">

<cftree name="tree1"
    hscroll="No"
    border="Yes"
    height="350"
    required="Yes"
>

<cftreeitem value="Dept_ID, FullName"
    query="deptquery"
    queryasroot="Dept_ID"
    img="computer,folder,document"
    imgopen="computer,folder"
    expand="yes">

</cftree>
<br>
<br><input type="Submit" value="Submit">
</cfform>
  2. Save the page and view it in your browser. It should look as follows

    Tree control containing ordered results from a query

Reviewing the code

The following table describes the highlighted code and its function

:

Code

Description

ORDER BY Dept_ID

Orders the query results by department.

<cftreeitem value="Dept_ID,FullName"

Populates the tree with the department ID, and under each department, the full name for each employee in the department.

queryasroot="Dept_ID"

Labels the root "Dept_ID".

img="computer,folder,document"
imgopen="computer,folder"

Uses the ColdFusion supplied computer image for the root level, folder image for the department IDs, and document for the names, independent of whether any level is expanded (open) or collapsed. The imgopen attribute has only two items, because the employee names can never be open.

The cftreeitem comma-separated value, img, and imgopen attributes correspond to the tree level structure. In applet format, if you omit the img attribute, ColdFusion uses the folder image for all levels in the tree; if you omit the imgopen attribute, ColdFusion uses the folder image for all expanded levels in the tree. Flash format ignores the img and imgopen attributes and always uses folders for levels with children and documents for nodes without children.


The cftree form variables

The cftree tag lets you force a user to select an item from the tree control by setting the required attribute to Yes. With or without the required attribute, ColdFusion passes two form variables to the application page specified in the cfform action attribute:

  • Form.treename.path Returns the complete path of the user selection, in the form: [root]\node1\node2\node_n\value
  • Form.treename.node Returns the node of the user selection.

To return the root part of the path, set the completepath attribute of the cftree tag to Yes; otherwise, the path value starts with the first node. If you specify a root name for a tree item using the queryasroot tag, that value is returned as the root. If you do not specify a root name, ColdFusion returns the query name as the root. If there is no query name, ColdFusion returns the tree name as the root.

In the previous example, if the user selects the name "John Allen" in the tree, ColdFusion returns the following form variables:

Form.tree1.path = 3\John Allen
Form.tree1.node = John Allen

The deptquery root does not appear in the path, because the cftree tag does not specify completePath="Yes". You can specify the character used to delimit each element of the path form variable in the cftree delimiter attribute. The default is a backslash character (\).


Input validation

Although the cftree tag does not include a validate attribute, you can use the required attribute to force a user to select an item from the tree control. In addition, you can use the onValidate attribute to specify your own JavaScript code to perform validation.


Structuring tree controls

Tree controls built with the cftree tag can be very complex. Knowing how to specify the relationship between multiple cftreeitem entries helps you handle the most complex cftree constructs.

Creating a one-level tree control

The following example consists of a single root and a number of individual items:

<cfquery name="deptquery" datasource="cfdocexamples">
    SELECT Dept_ID, FirstName + ' ' + LastName
    AS FullName
    FROM Employee
    ORDER BY Dept_ID
</cfquery>

<cfform name="form1" action="submit.cfm">
    <cftree name="tree1">
        <cftreeitem value="FullName"
        query="deptquery"
        queryasroot="Department">
        img="folder,document">
    </cftree>
<br>
<cfinput type="submit" value="Submit">
</cfform>

Creating a multilevel tree control

The following figure shows an example of a multilevel tree control:

Multilevel tree control

When populating a cftree control, you create the multilevel structure of the tree by specifying a parent for each item in the tree. The parent attribute of the cftreeitem tag allows your cftree tag to show relationships between elements in the tree.

In this example, every cftreeitem tag, except the top level Divisions, specifies a parent. For example, the cftreeitem value="Development" tag specifies Divisions as its parent.

The following code populates the tree directly, not from a query:

<cfform name="form2" action="cfform_submit.cfm">
<cftree name="tree1" hscroll="No" vscroll="No"
    border="No">
    <cftreeitem value="Divisions">
    <cftreeitem value="Development"
        parent="Divisions" img="folder">
    <cftreeitem value="Product One"
        parent="Development" img="document">
    <cftreeitem value="Product Two"
        parent="Development">
    <cftreeitem value="GUI"
        parent="Product Two" img="document">
    <cftreeitem value="Kernel"
        parent="Product Two" img="document">
    <cftreeitem value="Product Three"
        parent="Development" img="document">
    <cftreeitem value="QA"
        parent="Divisions" img="folder">
    <cftreeitem value="Product One"
        parent="QA" img="document">
    <cftreeitem value="Product Two"
        parent="QA" img="document">
    <cftreeitem value="Product Three"
        parent="QA" img="document">
    <cftreeitem value="Support"
        parent="Divisions" img="fixed">
    <cftreeitem value="Product Two"
        parent="Support" img="document">
    <cftreeitem value="Sales"
        parent="Divisions" img="computer">
    <cftreeitem value="Marketing"
        parent="Divisions" img="remote">
    <cftreeitem value="Finance"
        parent="Divisions" img="element">
</cftree>
</cfform>


Image names in a cftree tag

Note: This section applies to applet format trees. In Flash format, you cannot control the tree icons. Flash format uses open and closed folders and documents as the icons. In object format, the image information is preserved in fields in the object structure.

The default image displayed in a tree is a folder. However, you can use the img attribute of the cftreeitem tag to specify a different image.

When you use the img attribute, ColdFusion displays the specified image beside the tree items when they are not open. When you use the imgopen attribute, ColdFusion displays the specified image beside the tree items when they are open (expanded). You can specify a built-in ColdFusion image name, the file path to an image file, or the URL of an image of your choice, such as http://localhost/Myapp/Images/Level3.gif. You cannot use a custom image in Flash format. As a general rule, make the height of your custom images less than 20 pixels.

When populating a cftree control with data from a cfquery tag, you can use the img attribute of cftreeitem tag to specify images or filenames for each level of the tree as a comma-separated list.

The following are the ColdFusion built-in image names:

  • computer
  • document
  • element
  • folder
  • floppy
  • fixed
  • remote

Note: In applet format, you can also control the tree appearance by using the cftree tag lookAndFeel attribute to specify a Windows, Motif, or Metal look.


Embedding URLs in a cftree tag

The href attribute in the cftreeitem tag lets you designate tree items as links. To use this feature in a cftree control, you define the destination of the link in the href attribute of the cftreeitem tag. The URL for the link can be a relative URL or an absolute URL, as in the following examples.

To embed links in a cftree control:

  1. Create a ColdFusion page named tree3.cfm with the following contents:
    <cfform action="submit.cfm">
<cftree name="oak"
    highlighthref="Yes"
    height="100"
    width="200"
    hspace="100"
    vspace="6"
    hscroll="No"
    vscroll="No"
    border="No">
    <cftreeitem value="Important Links">
    <cftreeitem value="Macromedia Home"
        parent="Important Links"
        img="document"
        href="http://www.macromedia.com">
    <cftreeitem value="ColdFusion Developer Center"
        parent="Important Links"
        img="document"
        href="http://www.macromedia.com/devnet/mx/coldfusion/">
</cftree>
</cfform>
  2. Save the page and view it in your browser.

    The following figure shows the output of this code:

    Embedded links in a tree control

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

href="http://www.macromedia.com">

Makes the node of the tree a link.

href="http://www.
macromedia.com/devnet/mx/coldfusion/">

Makes the node of the tree a link.

Although this example does not show it, the href attribute can refer to the name of a column in a query if that query populates the tree item.


Specifying the tree item in the URL

When a user clicks on a tree item to link to a URL, the cftreeItemKey variable, which identifies the selected value, is appended to the URL in the following form:

http://myserver.com?CFTREEITEMKEY=selected_item_value_attribute

If the value attribute includes spaces, ColdFusion replaces the spaces with plus characters (+).

Automatically passing the name of the selected tree item as part of the URL makes it easy to implement a basic "drill down" application that displays additional information based on the selection. For example, if the specified URL is another ColdFusion page, it can access the selected value as the variable URL.CFTREEITEMKEY.

To disable this behavior, set the appendkey attribute in the cftree tag to No.


Building drop-down list boxes

The drop-down list box that you can create in a cfform tag with a cfselect tag is similar to the HTML select tag. However, the cfselect tag gives you more control over user inputs, provides error handling, and, most importantly, lets you automatically populate the selection list from a query.

You can populate the drop-down list box from a query, or using lists of option elements created by the option tag. The syntax for the option tag with the cfselect tag is the same as for the HTML option tag.

When you populate a cfselect tag with data from a query, you only need to specify the name of the query that is supplying data for the cfselect tag and the query column name for each list element to display.

To populate a drop-down list box with query data using the cfselect tag:

  1. Create a ColdFusion page with the following content:
    <cfquery name="getNames"
    datasource="cfdocexamples">
    SELECT * FROM Employee
</cfquery>

<cfform name="Form1" action="submit.cfm">

    <cfselect name="employees"
        query="getNames"
        value="Emp_ID"
        display="FirstName"
        required="Yes"
        multiple="Yes"
        size="8">
    </cfselect>

    <br><input type="Submit" value="Submit">
</cfform>
  2. Save the file as selectbox.cfm and view it in your browser.

    The following figure shows the output of this code:

    Drop-down list box containing query data

Because the tag includes the multiple attribute, the user can select multiple entries in the list box. Also, because the value tag specifies Emp_ID, the primary key for the Employee table, Employee IDs (not first names) get passed in the Form.Employee variable to the application page specified in the cfform action attribute.

You can use a query to create a two-level hierarchical list grouped by one of the query columns. For an example of this use, see the example for the cfselect entry in CFML Reference.


Building slider bar controls

You can use the cfslider control in a cfform tag to create a slider control and define a variety of characteristics, including label text, label font name, size, boldface, italics, and color, and slider range, positioning, and behavior. Slider bars are useful because they are highly visual and users can only enter valid values. The cfslider tag is not supported in Flash format forms.

To create a slider control:

  1. Create a ColdFusion page with the following content:
    <cfform name="Form1" action="submit.cfm">
    <cfslider name="myslider"
        bgcolor="cyan"
        bold="Yes"
        range="0,1000"
        scale="100"
        value="600"
        fontsize="14"
        label="Slider %value%"
        height="60"
        width="400">
</cfform>
  2. Save the file as slider.cfm and view it in your browser.

    The following figure shows the output of this code:

    Example slider control

To get the value of the slider in the action page, use the variable Form.slider_name; in this case, Form.myslider.


Creating data grids with the cfgrid tag

The cfgrid tag creates a cfform grid control that resembles a spreadsheet table and can contain data populated from a cfquery tag or from other sources of data. As with other cfform tags, the cfgrid tag offers a wide range of data formatting options, as well as the option of validating user selections with a JavaScript validation script.

You can also perform the following tasks with a cfgrid tag:

  • Sort data in the grid alphanumerically.
  • Update, insert, and delete data.
  • Display images in the grid.

Note: Flash format grids support a subset of the features available in applet format grids. For details on features supported in each format, see the cfgrid tag in CFML Reference.

Users can sort the grid entries in ascending order by double-clicking any column header. Double-clicking again sorts the grid in descending order. In applet format, you can also add sort buttons to the grid control.

When users select grid data and submit the form, ColdFusion passes the selection information as form variables to the application page specified in the cfform action attribute.

Just as the cftree tag uses the cftreeitem tag, the cfgrid tag uses the cfgridcolumn and cfgridrow tags. You can define a wide range of row and column formatting options, as well as a column name, data type, selection options, and so on. You use the cfgridcolumn tag to define individual columns in the grid or associate a query column with a grid column.

Use the cfgridrow tag to define a grid that does not use a query as the source for row data. If a query attribute is specified in the cfgrid tag, the cfgridrow tags are ignored.

The cfgrid tag provides many attributes that control grid behavior and appearance. This chapter describes only the most important of these attributes. For detailed information on these attributes, see the cfgrid tag in CFML Reference.

This section describes the following topics:

  • Working with a data grid and entering data
  • Creating an editable grid


Working with a data grid and entering data

The following figure shows an example applet format grid created using a cfgrid tag:

Example grid created using the cfgrid tag

The following table describes some navigating tips:

Action | Procedure
Sorting grid rows | Double-click the column header to sort a column in ascending order. Double-click again to sort the rows in descending order.
Rearranging columns | Click any column heading and drag the column to a new position.
Determining editable grid areas | When you click an editable cell, it is surrounded by a yellow box.
Determining noneditable grid areas | When you click a cell (or row or column) that you cannot edit, its background color changes. The default color is salmon pink.
Editing a grid cell | Double-click the cell. You must press Return when you finish entering the data.
Deleting a row | Click any cell in the row and click the Delete button. (Not available in Flash format grids.)
Inserting a row | Click the Insert button. An empty row appears at the bottom of the grid. To enter a value in each cell, double-click the cell, enter the value, and click Return. (Not available in Flash format grids.)

To populate a grid from a query:

  1. Create a new ColdFusion page named grid1.cfm with the following contents:
    <cfquery name="empdata" datasource="cfdocexamples">
    SELECT * FROM Employee
</cfquery>

<cfform name="Form1" action="submit.cfm" >
    <cfgrid name="employee_grid" query="empdata"
            selectmode="single">
        <cfgridcolumn name="Emp_ID">
        <cfgridcolumn name="LastName">
        <cfgridcolumn name="Dept_ID">
    </cfgrid>
    <br>
    <cfinput name="submitit" type="Submit" value="Submit">
</cfform>

    Note: Use the cfgridcolumn display="No" attribute to hide columns that you want to include in the grid but not expose to an end user. You typically use this attribute to include columns such as the table’s primary key column in the results returned by the cfgrid tag.

  2. Save the file and view it in your browser.

    The following figure shows the output of this code:

    Grid populated from a query

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfgrid name="employee_grid"
    query="empdata"

Creates a grid named employee_grid and populate it with the results of the query empdata.

If you specify a cfgrid tag with a query attribute defined and no corresponding cfgridcolumn attributes, the grid contains all the columns in the query.

selectmode="single">

Allows the user to select only one cell; does not allow editing. Other modes are row, column, and edit.

<cfgridcolumn name="Emp_ID">

Puts the contents of the Emp_ID column in the query results in the first column of the grid.

<cfgridcolumn name="LastName">

Puts the contents of the LastName column in the query results in the second column of the grid.

<cfgridcolumn name="Dept_ID">

Puts the contents of the Dept_ID column in the query results in the third column of the grid.


Creating an editable grid

You can build grids to allow users to edit data within them. Users can edit individual cell data, as well as insert, update, or delete rows. To enable grid editing, you specify selectmode="edit" in the cfgrid tag.

You can let users add or delete grid rows by setting the insert or delete attributes in the cfgrid tag to Yes. Setting the insert and delete attribute to Yes causes the cfgrid tag to display Insert and Delete buttons as part of the grid, as the following figure shows:

Grid showing the insert and delete buttons

You can use a grid in two ways to make changes to your ColdFusion data sources:

  • Create a page to which you pass the cfgrid form variables. In that page, perform cfquery operations to update data source records based on the form values returned by the cfgrid tag.
  • Pass grid edits to a page that includes the cfgridupdate tag, which automatically extracts the form variable values and passes that data directly to the data source.

Using the cfquery tag gives you complete control over interactions with your data source. The cfgridupdate tag provides a much simpler interface for operations that do not require the same level of control.

This section describes the following topics:

  • Controlling cell contents
  • How user edits are returned
  • Example: editing data in a grid
  • Updating the database with the cfgridupdate tag
  • Updating the database with the cfquery tag


Controlling cell contents

You can control the data that a user can enter into a cfgrid cell in the following ways:

  • By default, a cell is not editable. Use the cfgrid attribute selectmode="edit" to edit cell contents.
  • Use the cfgridcolumn type attribute to control sorting order, to make the fields check boxes, or to display an image.
  • Use the cfgridcolumn values attribute to specify a drop-down list of values from which the user can choose. You can use the valuesDisplay attribute to provide a list of items to display that differs from the actual values that you enter in the database. You can use the valuesDelimiter attribute to specify the separator between values in the values valuesDisplay lists.
  • Although the cfgrid tag does not have a validate attribute, it does have an onValidate attribute that lets you specify a JavaScript function to perform validation.

For more information on controlling the cell contents, see the attribute descriptions for the cfgridcolumn tag in CFML Reference.


How user edits are returned

When a user inserts or deletes a row in a grid or changes any cells in a row and submits the grid, ColdFusion creates the following arrays as Form variables:

Array name | Description
gridname.colname | Stores the new values of inserted, deleted, or updated cells. (Entries for deleted cells contain empty strings.)
gridname.Original.colname | Stores the original values of inserted, deleted, or updated cells.
gridname.RowStatus.Action | Stores the type of change made to the grid rows: D for delete, I for insert, or U for update.

Note: The periods in these names are not structure separators; they are part of the text of the array name.

ColdFusion creates a gridname.colname array and a gridname.Original.colname array for each column in the grid. For each inserted, deleted, or changed row in the grid, ColdFusion creates a row in each of these arrays.

For example, the following arrays are created if you update a cfgrid tag called mygrid that consists of two displayable columns (col1, col2) and one hidden column (col3):

Form.mygrid.col1
Form.mygrid.col2
Form.mygrid.col3
Form.mygrid.original.col1
Form.mygrid.original.col2
Form.mygrid.original.col3
Form.mygrid.RowStatus.Action

The value of the array index increments for each row that is added, deleted, or changed, and does not indicate a grid row number. All rows for a particular change have the same index in all arrays. Unchanged rows do not have entries in the arrays.

If the user makes a change to a single cell in col2, the following array elements contain the edit operation, the edited cell value, and the original cell value:

Form.mygrid.RowStatus.Action[1]
Form.mygrid.col2[1]
Form.mygrid.original.col2[1]

If the user changes the values of the cells in col1 and col3 in one row and the cell in col2 in another row, the information about the original and changed values is in the following array entries:

Form.mygrid.RowStatus.Action[1]
Form.mygrid.col1[1]
Form.mygrid.original.col1[1]
Form.mygrid.col3[1]
Form.mygrid.original.col3[1]
Form.mygrid.RowStatus.Action[2]
Form.mygrid.col2[2]
Form.mygrid.original.col2[2]

The remaining cells in the arrays (for example, Form.mygrid.col2[1] and Form.mygrid.original.col2[1]) have the original, unchanged values.


Example: editing data in a grid

The following example creates an editable grid. For code brevity, the example handles only three of the fields in the Employee table. A more realistic example would include, at a minimum, all seven table fields. It might also hide the contents of the Emp_ID column or display the Department name (from the Departmt table), instead of the Department ID.

To create the editable grid:

  1. Create a ColdFusion page with the following content:
    <cfquery name="empdata" datasource="cfdocexamples">
    SELECT * FROM Employee
</cfquery>

<cfform name="GridForm"
    action="handle_grid.cfm">

    <cfgrid name="employee_grid"
        height=425
        width=300
        vspace=10
        selectmode="edit"
        query="empdata"
        insert="Yes"
        delete="Yes">

        <cfgridcolumn name="Emp_ID"
            header="Emp ID"
            width=50
            headeralign="center"
            headerbold="Yes"
            select="No">

        <cfgridcolumn name="LastName"
            header="Last Name"
            width=100
            headeralign="center"
            headerbold="Yes">

        <cfgridcolumn name="Dept_ID"
            header="Dept"
            width=35
            headeralign="center"
            headerbold="Yes">

    </cfgrid>
    <br>
    <cfinput name="submitit" type="Submit" value="Submit">
</cfform>
  2. Save the file as grid2.cfm.
  3. View the results in your browser.

    The following figure shows the output of this code:

The following sections describe how to write the handle_grid.cfm page to process user edits to the grid.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfgrid name="employee_grid"
    height=425
    width=300
    vspace=10
    selectmode="edit"
    query="empdata"
    insert="Yes"
    delete="Yes">

Populates a cfgrid control with data from the empdata query. Selecting a grid cell enables you to edit it. You can insert and delete rows. The grid is 425 X 300 pixels and has 10 pixels of space above and below it.

<cfgridcolumn name="Emp_ID"
    header="Emp ID"
    width=50
    headeralign="center"
    headerbold="Yes"
    select="No">

Creates a 50-pixel wide column for the data in the Emp_ID column of the data source. Centers a header named Emp ID and makes it bold.

Does not allow users to select fields in this column for editing. Since this field is the table’s primary key, users should not be able to change it for existing records, and the DBMS should generate this field as an autoincrement value.

<cfgridcolumn name="LastName"
    header="Last Name"
    width=100
    headeralign="center"
    headerbold="Yes">

Creates a 100-pixel wide column for the data in the LastName column of the data source. Centers a header named Last Name and makes it bold.

<cfgridcolumn name="Dept_ID"
    header="Dept"
    width=35
    headeralign="center"
    headerbold="Yes">
</cfgrid>

Creates a 35-pixel wide column for the data in the Dept_ID column of the data source. Centers a header named Dept and makes it bold.


Updating the database with the cfgridupdate tag

The cfgridupdate tag provides a simple mechanism for updating the database, including inserting and deleting records. It can add, update, and delete records simultaneously. It is convenient because it automatically handles collecting the cfgrid changes from the various form variables, and generates appropriate SQL statements to update your data source.

In most cases, use the cfgridupdate tag to update your database. However, this tag does not provide the complete SQL control that the cfquery tag provides. In particular, the cfgridupdate tag has the following characteristics:

  • You can update only a single table.
  • Rows are deleted first, then rows are inserted, then any changes are made to existing rows. You cannot modify the order of changes.
  • Updating stops when an error occurs. It is possible that some database changes are made, but the tag does not provide any information on them.

To update the data source with the cfgridupdate tag:

  1. Create a ColdFusion page with the following contents:
    <html>
<head>
    <title>Update grid values</title>
</head>
<body>

<h3>Updating grid using cfgridupdate tag.</h3>

<cfgridupdate grid="employee_grid"
    datasource="cfdocexamples"
    tablename="Employee">

Click <a href="grid2.cfm">here</a> to display updated grid.

    </body>
</html>
  2. Save the file as handle_grid.cfm.
  3. View the grid2.cfm page in your browser, make changes to the grid, and then submit them.

Note: To update a grid cell, modify the cell contents, and then press Return.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfgridupdate grid="employee_grid"

Updates the database from the Employee_grid grid.

datasource="cfdocexamples"

Updates the cfdocexamples data source.

tablename="Employee"

Updates the Employee table.


Updating the database with the cfquery tag

You can use the cfquery tag to update your database from the cfgrid changes. This provides you with full control over how the updates are made and lets you handle any errors that arise.

To update the data source with the cfquery tag:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Catch submitted grid values</title>
</head>
<body>

<h3>Grid values for Form.employee_grid row updates</h3>

<cfif isdefined("Form.employee_grid.rowstatus.action")>

    <cfloop index = "counter" from = "1" to =
        #arraylen(Form.employee_grid.rowstatus.action)#>

        <cfoutput>
            The row action for #counter# is:
            #Form.employee_grid.rowstatus.action[counter]#
            <br>
        </cfoutput>

        <cfif Form.employee_grid.rowstatus.action[counter] is "D">
            <cfquery name="DeleteExistingEmployee"
                datasource="cfdocexamples">
                DELETE FROM Employee
                WHERE Emp_ID=<cfqueryparam
                            value="#Form.employee_grid.original.Emp_ID[counter]#"
                            CFSQLType="CF_SQL_INTEGER" >
            </cfquery>

        <cfelseif Form.employee_grid.rowstatus.action[counter] is "U">
            <cfquery name="UpdateExistingEmployee"
                datasource="cfdocexamples">
                UPDATE Employee
                SET
                    LastName=<cfqueryparam
                            value="#Form.employee_grid.LastName[counter]#"
                            CFSQLType="CF_SQL_VARCHAR" >,
                    Dept_ID=<cfqueryparam
                            value="#Form.employee_grid.Dept_ID[counter]#"
                            CFSQLType="CF_SQL_INTEGER" >
                WHERE Emp_ID=<cfqueryparam
                    value="#Form.employee_grid.original.Emp_ID[counter]#"
                    CFSQLType="CF_SQL_INTEGER">
            </cfquery>

        <cfelseif Form.employee_grid.rowstatus.action[counter] is "I">
            <cfquery name="InsertNewEmployee"
                datasource="cfdocexamples">
                INSERT into Employee (LastName, Dept_ID)
                VALUES (<cfqueryparam
                    value="#Form.employee_grid.LastName[counter]#"
                            CFSQLType="CF_SQL_VARCHAR" >,
                        <cfqueryparam value="#Form.employee_grid.Dept_ID[counter]#"
                            CFSQLType="CF_SQL_INTEGER" >)
            </cfquery>

        </cfif>
    </cfloop>
</cfif>

Click <a href="grid2.cfm">here</a> to display updated grid.

</body>
</html>
  2. Rename your existing handle_grid.cfm file as handle_grid2.cfm to save it, and then save this file as handle_grid.cfm.
  3. View the grid2.cfm page in your browser, make changes to the grid, and then submit them.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfif isdefined
  ("Form.employee_grid.rowstatus.action")>
  <cfloop index = "counter" from = "1" to =
  #arraylen(Form.employee_grid.rowstatus.action)#>

If there is an array of edit types, changes the table. Otherwise, does nothing. Loops through the remaining code once for each row to be changed. The counter variable is the common index into the arrays of change information for the row being changed.

<cfoutput>
  The row action for #counter# is:
  #Form.employee_grid.rowstatus.action[counter]#
  <br>
</cfoutput>

Displays the action code for this row: U for update, I for insert, or D for delete.

<cfif Form.employee_grid.rowstatus.action[counter]
   is "D">
 <cfquery name="DeleteExistingEmployee"
   datasource="cfdocexamples">
  DELETE FROM Employee
  WHERE Emp_ID=<cfqueryparam
   value="#Form.employee_grid.original.Emp_ID
    [counter]#"
   CFSQLType="CF_SQL_INTEGER" >
 </cfquery>

If the action is to delete a row, generates a SQL DELETE query specifying the Emp_ID (the primary key) of the row to be deleted.

<cfelseif Form.employee_grid.rowstatus.action
   [counter] is "U">
 <cfquery name="UpdateExistingEmployee"
   datasource="cfdocexamples">
  UPDATE Employee
  SET LastName=<cfqueryparam
    value="#Form.employee_grid.LastName[counter]#"
    CFSQLType="CF_SQL_VARCHAR" >,
   Dept_ID=<cfqueryparam
    value="#Form.employee_grid.Dept_ID[counter]#"
    CFSQLType="CF_SQL_INTEGER" >
  WHERE Emp_ID=<cfqueryparam
    value="#Form.employee_grid.original.Emp_ID
      [counter]#"
     CFSQLType="CF_SQL_INTEGER">
 </cfquery>

Otherwise, if the action is to update a row, generates a SQL UPDATE query to update the LastName and Dept_ID fields for the row specified by the Emp_ID primary table key.

<cfelseif
   Form.employee_grid.rowstatus.action[counter]
   is "I">
 <cfquery name="InsertNewEmployee"
   datasource="cfdocexamples">
  INSERT into Employee (LastName, Dept_ID)
  VALUES (<cfqueryparam
    value="#Form.employee_grid.LastName[counter]#"
    CFSQLType="CF_SQL_VARCHAR" >,
   <cfqueryparam
     value="#Form.employee_grid.Dept_ID[counter]#"
     CFSQLType="CF_SQL_INTEGER" >)
 </cfquery>

Otherwise, if the action is to insert a row, generates a SQL INSERT query to insert the employee’s last name and department ID from the grid row into the database. The INSERT statement assumes that the DBMS automatically increments the Emp_ID primary key. If you use the version of the cfdocexamples database that is provided for UNIX installations, the record is inserted without an Emp_ID number.

  </cfif>
 </cfloop>
</cfif>

Closes the cfif tag used to select among deleting, updating, and inserting.

Closes the loop used for each row to be changed.

Closes the cfif tag that surrounds all the active code.


Embedding Java applets

The cfapplet tag lets you embed Java applets either on a ColdFusion page or in a cfform tag. To use the cfapplet tag, you must first register your Java applet using the ColdFusion MX Administrator Java Applets page (under Extensions). In the ColdFusion MX Administrator, you define the interface to the applet, encapsulating it so that each invocation of the cfapplet tag is very simple.

The cfapplet tag within a form offers several advantages over using the HTML applet tag:

  • Return values The cfapplet tag requires a form field name attribute, so you can avoid coding additional JavaScript to capture the applet’s return values. You can reference return values like any other ColdFusion form variable: Form.variablename.
  • Ease of use The applet’s interface is defined in the ColdFusion MX Administrator, so each instance of the cfapplet tag in your pages only needs to reference the applet name and specify a form variable name.
  • Parameter defaults ColdFusion uses the parameter value pairs that you defined in the ColdFusion MX Administrator. You can override these values by specifying parameter value pairs in the cfapplet tag.

When an applet is registered, you enter just the applet source and the form variable name:

<cfapplet appletsource="Calculator"
    name="calc_value">

By contrast, with the HTML applet tag, you must declare all the applet’s parameters every time you want to use it in a ColdFusion page.

This section describes the following topics:

  • Registering a Java applet
  • Using the cfapplet tag to embed an applet
  • Handling form variables from an applet


Registering a Java applet

Before you can use a Java applet in your ColdFusion pages, you must register the applet in the ColdFusion MX Administrator.

To register a Java applet:

  1. Open the ColdFusion MX Administrator by clicking the Administrator icon in the Macromedia ColdFusion MX Program group and entering the Administrator password.
  2. Under Extensions, click Java Applets.

    The Java Applets page appears.

  3. Click the Register New Applet button.

    The Add/Edit Applet page appears.

  4. Enter options in the applet registration fields, as described in the ColdFusion MX Administrator online help. Use the Add button to add parameters.
  5. Click Submit.


Using the cfapplet tag to embed an applet

After you register an applet, you can use the cfapplet tag to place the applet in a ColdFusion page. The cfapplet tag has two required attributes: appletsource and name. Because you registered the applet and you defined each applet parameter with a default value, you can invoke the applet with a very simple form of the cfapplet tag:

<cfapplet appletSource="appletname" name="form_variable">

Overriding alignment and positioning values

To override any of the values defined in the ColdFusion MX Administrator for the applet, you can use the optional cfapplet parameters to specify custom values. For example, the following cfapplet tag specifies custom spacing and alignment values:

<cfapplet appletSource="myapplet"
    name="applet1_var"
    height=400
    width=200
    vspace=125
    hspace=125
    align="left">

Overriding parameter values

You can override the values that you assigned to applet parameters in the ColdFusion MX Administrator by providing new values for any parameter. To override a parameter, you must have already defined the parameter and its default value in the ColdFusion MX Administrator Applets page. The following example overrides the default values of two parameters, Param1 and Param2:

<cfapplet appletSource="myapplet"
    name="applet1_var"
    Param1="registered parameter1"
    Param2="registered parameter2">


Handling form variables from an applet

The cfapplet tag name attribute corresponds to a variable in the action page, Form.appletname, which holds any value that the applet method returns when it is executed in the cfform tag.

Not all Java applets return values. For instance, graphical widgets might not return a specific value. For this type of applet, the method field in the ColdFusion MX Administrator remains empty, but you must still provide a cfapplet name attribute.

You can only use one method for each applet that you register. If an applet includes more than one method that you want to access, you can register the applet with a unique name for each additional method you want to use.

To reference a Java applet return value in your application page:

  1. Specify the name of the method in the Add/Registered Java Applet page of the ColdFusion MX Administrator.
  2. Specify the method name in the name attribute of the cfapplet tag.

When your page executes the applet, ColdFusion creates a form variable with the name that you specified. If you do not specify a method, ColdFusion does not create a form variable.
Previous


Validating Data

This chapter explains how to validate data in Macromedia ColdFusion MX. It focuses on validating form data, but also contains information on how you can validate variable data and function parameters.

Contents

About ColdFusion MX validation

Validating form fields

Handling invalid data

Masking form input values

Validating form data with regular expressions

Validating form data using hidden fields

Validating form input and handling errors with JavaScript

Validating data with the IsValid function and the cfparam tag
Next


About ColdFusion MX validation

Data validation lets you control data that is entered into an application by ensuring that the data conforms to specific type or formatting rules. Validation techniques have the following features:

  • They let you provide feedback to users so that they can immediately correct information they provide. For example, a form can provide immediate feedback when a user enters a name in a telephone number field, or the form could force the user to enter the number in the correct format.
  • They help prevent application errors that might arise when processing invalid data. For example, a validation test can prevent a variable that is used in a calculation from having nonnumeric data.
  • They can help enhance security by preventing malicious users from providing data that takes advantage of system security weaknesses, such as buffer overrun attacks.

ColdFusion provides several techniques to ensure that data is valid. These include techniques for validating form data and for validating ColdFusion variables. They also include techniques for validating form data before the user submits it to ColdFusion, or on the ColdFusion server.

When you design data validation you consider the following factors:

The validation technique Whether to validate on the client’s browser or on the server, and the specific server- or client-side validation technique, such as whether to validate when a field loses focus or when the user submits the form.

The validation type The specific method that you use to validate the data, including the rules that you apply to test the data validity, such as testing for a valid telephone number.

The following sections describe the ColdFusion MX validation techniques and provide information on selecting a technique that is appropriate for your application. They also describe the validation types that ColdFusion MX supports. Later sections describe particular techniques in detail.

This section includes the following topics:

  • Validation techniques
  • Selecting a validation technique
  • Data validation types


Validation techniques

Different validation techniques apply to different ColdFusion tags or coding environments; for example, you can use masking only in HTML and Macromedia Flash format cfinput tags. Validation techniques also vary in where and when they execute; for example, on the client browser when the user submits form data, or on the server when processing data.

The following table describes the ColdFusion MX validation techniques:

Validation technique

Applies to

Where and when performed

Description

mask

(mask attribute)

HTML and Flash format cfinput tags

On the client as the user enters data

ColdFusion MX generates JavaScript or ActionScript to directly control the data a user enters by specifying a pattern. For example, 999-999-9999 requires a user to enter ten digits, and automatically fills in the dash (-) separators to create a formatted telephone number.

For detailed information on using masks, see Handling invalid data.

onBlur

(validateat=

"onBlur" attribute)

cfinput and cftextarea tags

On the client when the data field loses focus

In HTML and XML format, ColdFusion MX generates JavaScript that runs on the browser to check whether entered data is valid and provide immediate feedback, if the entry is invalid.

In Flash format, uses Flash built-in validation routines.

onSubmit

(validateat=

"onSubmit" attribute)

cfinput and cftextarea tags

On the client when the user clicks Submit

In HTML or XML format, the validation logic is identical to onBlur validation, but the test is not done until the user submits the form.

In Flash format, this validation type is identical to onBlur Validation. Flash checks do not differentiate between the two events for validation.

onServer

(validateat=

"onServer" attribute)

cfinput and cftextarea tags

On the server when ColdFusion gets the submitted form

ColdFusion MX checks submitted data for validity and runs a validation error page if the data is not valid. You can use the cferror tag to specify the validation error page.

hidden field

All Forms, including HTML-only forms

On the server when ColdFusion gets the submitted form

ColdFusion MX uses the same validation logic as with onServer validation, but you must create additional, hidden, fields and you can use this technique with HTML tags or CFML tags.

For detailed information on using hidden fields, see Validating form data using hidden fields.

JavaScript

(onValidate ="function" attribute)

cfgrid, cfinput, cfslider, cftextarea, and cftree tags in HTML and XML format forms

On the client, when the user clicks Submit, before field-specific onSubmit validation

ColdFusion MX includes the specified JavaScript function in the HTML page it sends to the browser, and the browser calls it.

For detailed information on using JavaScript for validation, see Validating form input and handling errors with JavaScript.

IsValid function

ColdFusion variables

On the server, when the function executes

ColdFusion MX tests the variable to determine whether it follows a specified validation rule and the function returns true or false.

For more information on using the IsValid function for validation, see Validating data with the IsValid function and the cfparam tag.

cfparam tag

ColdFusion variables

On the server, when the tag executes

ColdFusion MX checks the specified variable. If the value does not meet the validation criteria, ColdFusion generates an expression exception.

For more information on using the cfparam tag for validation, see, Validating data with the IsValid function and the cfparam tag.

cfargument tag

UDF and CFC function arguments

On the server, when a function is called or invoked

ColdFusion MX checks the argument value when it is passed to the function. If the value does not meet the validation criteria, ColdFusion generates an application exception.

For more information on using the cfargument tag, see Writing and Calling User-Defined Functions.

Note: For more information on ColdFusion error handling, see Handling Errors


Selecting a validation technique

The following considerations affect the validation technique that you select:

  • If you are validating form data, the techniques you use can vary depending on whether you are using HTML, Flash, or XML forms; for example, different form types have different validation limitations.
  • Different validation techniques are appropriate for different form controls and data types.
  • Available techniques vary depending on when and where you want the data validated; on the client or the server, when the user enters data or submits a form, or when ColdFusion processes a variable or function argument.
  • Each technique has specific features and considerations, such as the form of user feedback, feature limitations, and so on.
  • Security issues or concerns that apply to your environment or application can affect the technique you select.

The preceding table in the Validation techniques section described some of the considerations. The following table describes additional considerations for selecting a validation technique. For additional considerations that are specific to form fields, see Validation type considerations.

Validation technique | Features | Considerations | Security issues
mask (mask attribute) | Directly controls user input. | Limited to cfinput tags. Provides limited control over user input patterns. | In HTML and XML format, can be circumvented because JavaScript runs directly in the browser.
onBlur (validateat= "onBlur" attribute) | Provides immediate feedback if a user enters invalid data. | Limited to cfinput and cftextarea tags. In HTML or XML format, requires the browser to enable JavaScript. | In HTML and XML format, can be circumvented because JavaScript runs directly in the browser.
onSubmit (validateat= "onSubmit" attribute) | All entered data is available to the user; only the invalid data needs reentering. | Limited to cfinput and cftextarea tags. In Flash format, is identical to onBlur. In HTML or XML format, validates after all fields have been entered, and requires the browser to enable JavaScript. | In HTML and XML format, can be circumvented because JavaScript runs directly in the browser.
onServer (validateat= "onServer" attribute) | Does not require browser support. | Limited to cfinput and cftextarea tags. | Can be circumvented because validation rules are submitted with the form.
Hidden form field | Does not require browser support. Can be used with HTML or CFML form elements. | Limited to forms. | Can be circumvented because validation rules are submitted with the form.
JavaScript (onValidate = "function" attribute) | Allows all on-client processing supported by the browser. Can be used with HTML or CFML form elements. | Limited to specific ColdFusion form tags. Calls a single JavaScript function. JavaScript levels of support can vary among browsers, and users can disable JavaScript in their browsers. | Can be circumvented because JavaScript runs directly in the browser.
IsValid function | Can be used for any variable, not just form fields. Returns a Yes or No result that you use to determine further processing. | When used with a form field, runs after the data is submitted. Must be used each time a variable needs to be validated. Provides some data type checks not available in forms validation techniques. | None
cfparam tag | Can be used for any variable, not just form fields. The tag can set a default value in addition to validating data. | When used with a form field, the tag runs after the data is submitted. You respond to validation failures using error-handling code. | None
cfargument tag | Used for arguments to functions written using the cffunction tag. | Runs when the function is called on the server. You respond to validation failures using error-handling code. | None

Security considerations

Although form-specific validation techniques provide good methods for preventing users from submitting invalid or badly formatted data, they cannot prevent users from submitting maliciously formatted data from HTML forms. Malicious users can circumvent validation techniques that require validation on the browser using JavaScript or submission of validation rules in hidden fields. If you must use a technique for preventing malicious data submissions, consider using the following techniques:

  • The onSubmit or OnBlur validation in Flash forms, which use Flash built-in validation.
  • The IsValid function and the cfparam, and cfargument tags, which let you test variables and arguments in your CFML code.
  • The cfqueryparam tag in cfquery tags, described in Enhancing security with cfqueryparam, which can help protect databases from malicious query input.
  • The script protection option, which helps prevent cross-site scripting attacks. You can set this option on the ColdFusion MX Administrator Server Settings > Settings page or by using the Application.cfc This.scriptProtect variable or the cfapplication tag scriptprotect attribute. For more information on cross-site scripting attacks and this option, see the cfapplication tag page in the CFML Reference.


Data validation types

The following table lists the types of data you can validate when you use most ColdFusion validation techniques. It does not include mask validation. Some validation types are not available for all techniques; in these cases the table indicates the limitations. The onBlur and onSubmit validation algorithms for Flash format forms might vary from those described in the following table, and most commonly have less functionality. For more detailed descriptions of the onServer validation algorithms, see the table in Validating form data using hidden fields.

Type field | Description
date | When validating on the server, allows any date/time format that returns true in the IsDate function, including a time value. When validating on the client, same as USdate.
USdate * | A U.S. date of the format mm/dd/yy, with 1- or 2-digit days and months, and 1-through 4-digit years. The separators can be slash (/), hyphen (-), or period (.) characters
eurodate * | A date of the format dd/mm/yy, with 1- or 2-digit days and months, and 1- through 4-digit years. The separators can be slash (/), hyphen (-), or period (.) characters.
time * | When validating on the server, allows any date/time format that returns True in the IsDate function, including a date value. When validating on the client, allows a time of format hh:mm[:ss] [A/PM].
float * | A number; allows integers. When validating form fields on the server, integer values are converted to real numbers.
numeric | A number; allows integers. When validating form fields on the server, integer values are unchanged.
integer * | An integer.
range * | A numeric range specified by a range attribute or max and min attributes.
boolean | A value that can be converted to a Boolean value: Yes, No, True, or False, (all case-independent), or a number.
telephone * | Standard U.S. telephone formats. Allows an initial 1 long-distance designator and up to 5-digit extensions, optionally starting with x.
zipcode * | U.S. 5- or 9-digit ZIP code format #####-####. The separator can be a hyphen (-) or a space.
creditcard * | Strips blanks and dashes; verifies number using mod10 algorithm. The number must have 13–16 digits.
ssn * or social_security_ number * | US. Social Security number format, ###-##-####. The separator can be a dash (-) or a space.
email * | A valid e-mail address of the form name@server.domain. ColdFusion validates the format only; it does not check that entry is a valid active e-mail address.
URL * | A valid URL pattern; supports http, https, ftp file, mailto, and news URLs.
guid * | A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number.
uuid * | A universally unique identifier (UUID) that follows the ColdFusion format, xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx, where x is a hexadecimal number.
regex * or regular_expression * | Matches the value against a regular expression specified in a pattern attribute. Valid in HTML and XML format only; ignored in Flash format.

* Indicates attribute values that are not valid for the cfargument tag.

Note: For more details on how ColdFusion handles data when it does onServer and hidden field validation, see Validating form data using hidden fields

The following validation types can only be used in cfinput tags:

Type | Description
maxlength | Limits the input to a maximum number of characters specified by a maxlength attribute.
noblanks | Does not allow fields that consist only of blanks. ColdFusion uses this validation only if the required attribute is True.
SubmitOnce | Used only with cfform submit and image types; prevents the user from submitting the same form multiple times before until the next page loads, Use this attribute, for example, to prevent a user from submitting an order form a second time before getting the confirmation for the initial order, and thereby making a duplicate order, Valid in HTML and XML format only; ignored in Flash format.

You can use the following validation types in cfparam and cfargument tags and the IsValid function only:

:
Type | Description
any | Any type of value
array | An array of values
binary | A binary value
query | A query object
string | A string value or single character
struct | A structure
variableName * | A string formatted according to ColdFusion variable naming conventions.

* This value is not valid for the cfargument tag type attribute. The cfargument tag does support component names as type attribute values. For more information, see cfargument in CFML Reference.


Validating form fields

This section describes basic validation of form fields. Later sections in this chapter describe other validation types and techniques that you can use, including regular expression validation, masking, hidden field validation, JavaScript validation, and validation using CFML tags and functions.

In basic form field validation, you do the following:

  • Use a cfinput or cftextarea tag.
  • Specify a validation type, such as numeric, or multiple types.
  • Optionally, specify an error message.
  • Optionally, specify a validation technique. (By default, ColdFusion uses onSubmit validation.)

The following example specifies onBlur validation of a telephone number:

Phone: <cfinput type="text" name="HPhone"
        validateat="onBlur"
        validate="required,telephone"
        message="Please enter a standard U.S. telephone number with an optional
            extension, such as x12345">

The following sections describe considerations for validation in cfinput and cftextarea tags, and show a more complete example.

Validation type considerations

General considerations Consider the following issues when you determine how to validate form data:

  • When you validate form data using onBlur, onSubmit, onServer, or hidden form field validation, you can specify one or more validation types for each field that you validate. For example, you can specify that a field entry is required and that it must be numeric. To specify multiple validation types for onSubmit, onBlur, or onServer validation, specify the type values in a comma-delimited list.
  • If you use onBlur, onSubmit, or onServer type validation, you can specify only one error message for each field that you validate. If you use hidden field validation, you can create a custom message for each validation rule (with the exception of range checking).
  • In the cfinput tag, most validation type attributes apply only to text or password fields.

Validation algorithm differences The underlying validation code used when validating form data can differ depending on the validation technique and the form type. As a result, the algorithms used vary in some instances, including the following:

  • The validation algorithms used for date/time values in onSubmit and OnBlur validation are different from those used for all server-side validation techniques.
  • The algorithms used for onSubmit and OnBlur validation in Flash might vary from those used for HTML or XML format, and generally follow simpler rules.

For detailed information on the validation algorithms used for validation techniques used on the server, see Validating form data using hidden fields.

Validating data in XML skinnable forms

If you create an XML skinnable form and use any skin provided by Macromedia, such as the basic.xsl or silver.xsl skin, you can use all form validation techniques that are available for HTML forms.

If you use a custom skin (XSL file), the available validation techniques depend on the skin. The cf_webroot\CFIDE\scripts\xsl directory contains a _cfformvalidation.xsl file that implements all ColdFusion HTML form validation techniques and supports onBlur, onSubmit, onServer, and hidden form field validation. XML skin writers can include this file in their skin XSLT to implement ColdFusion validation for their skin.

Example: basic form validation

The following form asks for information that might be used when registering a new user. It checks to make sure that the user enters required information. (Only the telephone number is optional.) It also checks to make sure that the telephone number and e-mail address are properly formatted and that the number to be used in a challenge question is in the proper range. This example performs onSubmit validation. It posts back to itself, and dumps the submitted results.

<cfif IsDefined("form.fieldnames")>
    <cfdump var="#form#"><br>
</cfif>

<cfform name="myform" preservedata="Yes" >
    First Name: <cfinput type="text" size="15" name="firstname"
        required="yes" message="You must enter a first name."><br>
    Last Name: <cfinput type="text" size="25" name="lastname"
        required="yes" message="You must enter a last name."><br>
    Telephone: <cfinput type="text" size="20" name="telephone"
        validate="telephone" message="You must enter your telephone
        number, for example 617-555-1212 x1234"><br>
    E-mail: <cfinput type="text" size="25" name="email"
        validate="email" required="Yes"
        message="You must enter a valid e-mail address."><br>
    Password:	<cfinput type="password" size="12" name="password1"
        required="yes" maxlength="12"
        message="You must enter a password."><br>
    Reenter password:	<cfinput type="password" size="12" name="password2"
        required="yes" maxlength="12"
        message="You must enter your password twice."><br>
    We will ask you for the following number, in the range 100-999 if you forget
        your password.<br>
    Number: <cfinput type="text" size="5" name="chalenge"
        validate="range" range="100,999" required="Yes"
        message="You must enter a reminder number in the range 100-999."><br>
    <cfinput type="submit" name="submitit">
</cfform>


Handling invalid data

How you handle invalid data depends on the validation type. This section describes validation error-handling rules and considerations. For detailed information on error handling in ColdFusion, including invalid data handling, see Handling Errors.

  • For onBlur, onSubmit, or onServer validation, you can use the cfinput or cftextarea tag’s message attribute to specify a text-only error message to display. Otherwise, ColdFusion MX uses a default message that includes the name of the form field that was invalid. (For OnServer validation, you can customize this message, as described in Handling form field validation errors.) The following example displays an error message when the user enters an invalid e-mail address:
        E-mail: <cfinput type="text" size="25" name="email"
        validate="email" message="You must enter a valid e-mail address.">
  • For hidden form validation, you can specify a text-only error message in the hidden field’s value attribute. Otherwise, ColdFusion MX uses a default message that includes the name of the form field that was invalid. (You can customize this message, as described in Handling form field validation errors.) The following cfinput tag, for example, uses a hidden field validation to display an error message if the user enters an invalid address. (It uses onServer validation to display a different error message if the user fails to enter a number.)
    Telephone: <cfinput type="text" size="20" name="telephone"
    validateat="onServer" required="Yes"
    message="You must enter a telephone number">
    <cfinput type="hidden" name="telephone_cfformtelephone"
    value="The number you entered is not in the correct format.<br>Use a
    number such as (617) 555-1212, 617-555-1212, or 617-555-1212 x12345">
  • For HTML and XML format forms (using ColdFusion MX skins), most ColdFusion form tags have an onError attribute that lets you specify a Javascript function to run if an onSubmit error occurs.
  • For the IsValid function, you write separate code paths to handle valid and invalid data. The following example shows a simplified case that displays an error message if the user entered an invalid e-mail address, or a different message if the address is valid:
    <cfif IsValid("email", custEmail)>
    Thank you for entering a valid address.
    <!--- More processing would go here. --->
<cfelse>
    You must enter a valid e-mail address.<br>
    Click the Back button and try again.
</cfif>
  • For cfparam and cfargument tags, you use standard ColdFusion MX error-handling techniques. You can include the tag in a try block and use a catch block to handle the error, or you can use a custom error-handling page. The following example form action page code uses a custom error page, expresserr.cfm, to handle the error that the cfparam tag generates if a user submits a form with an invalid e-mail address:
    <cferror type="EXCEPTION" exception="expression" template="expresserr.cfm">
<cfif IsDefined("form.fieldnames")>
    <cfparam name="form.custEmail" type="email">
    <!--- Normal form processing code goes here. --->
</cfif>


Masking form input values

The cfinput tag mask attribute controls the format of data that can be entered into a text or datefield input field. You can also use a mask attribute in the cfcalendar tag. You can combine masking and validation on a field.

  • In HTML and Flash form format, a mask can control the format of data entered into a text field.
  • In the cfcalendar tag, and, for Flash format forms, the datefield type cfinput field, a mask can control the format of the date that ColdFusion MX uses for the date a user chooses in the displayed calendar.

Note: The standard ColdFusion MX XML skins do not support masking.

Masking text input

In text fields, ColdFusion automatically inserts literal mask characters, such as - characters in telephone numbers. Users type only the variable part of the field. You can use the following characters to mask data:

Mask character | Effect
A | Allows an uppercase or lowercase character: A–Z and a–z.
X | Allows an uppercase or lowercase character or number: A–Z, a–z, and 0–9.
9 | Allows a number: 0–9.
? | Allows any character.
All other characters | Automatically inserts the literal character.

The following pattern enforces entry of a part number of the format EB-1234-c1-098765, where the user starts the entry by typing the first numeric character, such as 1. ColdFusion fills in the preceding EB prefix and all hyphen (-) characters. The user must enter four numbers, followed by two alphanumeric characters, followed by six numbers.

<cfinput type="text" name="newPart" mask="EB-9999-XX-999999" />

Note: You cannot force a user to type an A, X, 9, or question mark (?) character. To ensure that a pattern is all-uppercase or all-lowercase, use the ColdFusion MX UCase or LCase functions in the action page.

Masking cfcalendar and datefield input

In the cfcalendar tag and the Flash format datefield input control, you use the following masks to determine the format of the output. You can use uppercase or lowercase characters in the mask:

Mask | Pattern
D | Single- or double-digit day of month, such as 1 or 28
DD | Double-digit day of month, such as 01 or 28
M | Single- or double-digit month, such as 1 or 12
MM | Double-digit month, such as 01 or 12
MMM | Abbreviated month name, such as Jan or Dec
MMMM | Full month name, such as January or December
YY | Two-character year, such as 05
YYYY | Four-character year, such as 2005
E | Single-digit day of week, in the range 0 (Sunday)–6 (Saturday)
EEE | Abbreviated day of week name, such as Mon or Sun
EEEE | Full month day of week name, such as Monday or Sunday

The following pattern specifies that the Flash forms sends the date selected using a datefield input control to ColdFusion as text in the format 04/29/2004:

<cfinput name="startDate" type="datefield" label="date:" mask="mm/dd/yyyy"/>


Validating form data with regular expressions

You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.

Regular expressions let you check input text for a wide variety of custom conditions for which the input must follow a specific pattern. You can concatenate simple regular expressions into complex search criteria to validate against complex patterns, such as any of several words with different endings.

You can use ColdFusion variables and functions in regular expressions. The ColdFusion server evaluates the variables and functions before the regular expression is evaluated. For example, you can validate against a value that you generate dynamically from other input data or database values.

Note: The rules listed in this section are for JavaScript regular expressions, and apply to the regular expressions used in cfinput and cftextinput tags only. These rules differ from those used by the ColdFusion functions REFind, REReplace, REFindNoCase, and REReplaceNoCase. For information on regular expressions used in ColdFusion functions, see Using Regular Expressions in Functions.

Special characters

Because special characters are the operators in regular expressions, in order to represent a special character as an ordinary one, you must escape it by preceding it with a backslash. For example, use two backslash characters (\\) to represent a backslash character.

Single-character regular expressions

The following rules govern regular expressions that match a single character:

  • Special characters are: + * ? . [ ^ $ ( ) { | \
  • Any character that is not a special character or escaped by being preceded by a backslash (\) matches itself.
  • A backslash (\) followed by any special character matches the literal character itself; that is, the backslash escapes the special character.
  • A period (.) matches any character except newline.
  • A set of characters enclosed in brackets ([]) is a one-character regular expression that matches any of the characters in that set. For example, "[akm]" matches an a, k, or m. If you include ] (closing square bracket) in square brackets, it must be the first character. Otherwise, it does not work, even if you use \].
  • A dash can indicate a range of characters. For example, [a-z] matches any lowercase letter.
  • If the first character of a set of characters in brackets is the caret (^), the expression matches any character except those in the set. It does not match the empty string. For example: "[^akm]" matches any character except a, k, or m. The caret loses its special meaning if it is not the first character of the set.
  • You can make regular expressions case insensitive by substituting individual characters with character sets; for example, "[Nn][Ii][Cc][Kk]" is a case-insensitive pattern for the name Nick (or NICK, or nick, or even nIcK).
  • You can use the following escape sequences to match specific characters or character classes:

    Escape
    seq

    Matches

    Escape
    seq

    Meaning

    [\b]

    Backspace.

    \s

    Any of the following white space characters: space, tab, form feed, and line feed.

    \b

    A word boundary, such as a space.

    \S

    Any character except the white space characters matched by \s.

    \B

    A nonword boundary.

    \t

    Tab.

    \cX

    The control character Ctrl-x. For example, \cv matches Ctrl-v, the usual control character for pasting text.

    \v

    Vertical tab.

    \d

    A digit character [0-9].

    \w

    An alphanumeric character or underscore. The equivalent of
    [A-Za-z0-9_].

    \D

    Any character except a digit.

    \W

    Any character not matched by \w. The equivalent of [^A-Za-z0-9_].

    \f

    Form feed.

    \n

    Backreference to the nth expression in parentheses. See Backreferences.

    \n

    Line feed.

    \ooctal

    The character represented in the ASII character table by the specified octal number.

    \r

    Carriage return.

    \xhex

    The character represented in the ASCII character table by the specified hexadecimal number.

Multicharacter regular expressions

Use the following rules to build a multicharacter regular expression:

  • Parentheses group parts of regular expressions together into a subexpression that can be treated as a single unit. For example, "(ha)+" matches one or more instances of ha.
  • A one-character regular expression or grouped subexpression followed by an asterisk (*) matches zero or more occurrences of the regular expression. For example, "[a-z]*" matches zero or more lowercase characters.
  • A one-character regular expression or grouped subexpression followed by a plus sign (+) matches one or more occurrences of the regular expression. For example, "[a-z]+" matches one or more lowercase characters.
  • A one-character regular expression or grouped subexpression followed by a question mark (?) matches zero or one occurrences of the regular expression. For example, "xy?z" matches either xyz or xz.
  • The carat (^) at the beginning of a regular expression matches the beginning of the field.
  • The dollar sign ($) at the end of a regular expression matches the end of the field.
  • The concatenation of regular expressions creates a regular expression that matches the corresponding concatenation of strings. For example, "[A-Z][a-z]*" matches any capitalized word.
  • The OR character (|) allows a choice between two regular expressions. For example, "jell(y|ies)" matches either jelly or jellies.
  • Braces ({}) indicate a range of occurrences of a regular expression. You use them in the form "{m, n}" where m is a positive integer equal to or greater than zero indicating the start of the range and n is equal to or greater than m, indicating the end of the range. For example, "(ba){0,3}" matches up to three pairs of the expression ba. The form "{m,}" requires at least m occurrences of the preceding regular expression. The form "{m}" requires exactly m occurrences of the preceding regular expression. The form "{,n}" is not allowed.

Backreferences

Backreferencing lets you match text in previously matched sets of parentheses. A slash followed by a digit n (\n) refers to the nth parenthesized subexpression.

One example of how you can use backreferencing is searching for doubled words; for example, to find instances of "the the" or "is is" in text. The following example shows backreferencing in a regular expression:

(\b[A-Za-z]+)[ ]+\1

This code matches text that contains a word that is repeated twice; that is, it matches a word, (specified by the \b word boundary special character and the "[A-Za-z]+)" followed by one or more spaces (specified by "[ ]+"), followed by the first matched subexpression, the first word, in parentheses. For example, it would match "is is", but not "This is".

Exact and partial matches

ColdFusion validation normally considers a value to be valid if any of it matches the regular expression pattern. Often you might want to ensure that the entire entry matches the pattern. If so, you must "anchor" it to the beginning and end of the field, as follows:

  • If a caret (^) is at the beginning of a pattern, the field must begin with a string that matches the pattern.
  • If a dollar sign ($) is at the end of a pattern, the field must end with a string that matches the pattern.
  • If the expression starts with a caret and ends with a dollar sign, the field must exactly match the pattern.

Expression examples

The following examples show some regular expressions and describe what they match:

Expression | Description
[\?&]value= | Any string containing a URL parameter value.
^[A-Z]:(\\[A-Z0-9_]+)+$ | An uppercase Windows directory path that is not the root of a drive and has only letters, numbers, and underscores in its text.
^(\+|-)?[1-9][0-9]*$ | An integer that does not begin with a zero and has an optional sign.
^(\+|-)?[1-9][0-9]*(\.[0-9]*)?$ | A real number.
^(\+|-)?[1-9]\.[0-9]*E(\+|-)?[0-9]+$ | A real number in engineering notation.
a{2,4} | A string containing two to four occurrences of a: aa, aaa, aaaa; for example, aardvark, but not automatic.
(ba){2,} | A string containing least two ba pairs; for example, Ali baba, but not Ali Baba.

Note: An excellent reference on regular expressions is Mastering Regular Expressions by Jeffrey E.F. Friedl, published by O'Reilly & Associates, Inc.


Validating form data using hidden fields

ColdFusion lets you specify form field validation on the server by using hidden form fields whose names consist of the name of the field to validate and the validation type. Hidden field validation uses the same underlying techniques and algorithms as onServer validation of ColdFusion form fields.

Hidden field validation has the following features:

  • You can use it with standard HTML tags. For example, you can validate data in an HTML input tag. This feature was particularly useful in releases prior to ColdFusion MX 7, because the cfinput tag did not support all HTML type attributes.
  • It is backward-compatible with validation prior to ColdFusion MX 7, when hidden field validation was the only way to do validation on the server.
  • Because you use a separate tag for each validation type, if you specify multiple validation rules for a field, you can specify a different error message for each rule.
  • You can use hidden field validation with any form field type that submits a data value, not just input, cfinput, textarea, or cftextarea.

Specifying hidden form field validation

To specify hidden field validation, you do the following:

  • Create one HTML input element or CFML cfinput tag of type="hidden" for each validation rule.
  • Specify the name of the field to validate as the first part of the hidden field name.
  • Specify the type of validation, starting with an underscore character (_), as the second part of the hidden field name.
  • You can specify multiple rules for each form data field. For example, to specify range and required validation for a field named myValue, create hidden myValue_cfformrange and myValue_cfformrequired fields.
  • For most types of validation, specify the error message as the field value attribute.
  • For range, maximum length, or regular expression validation, specify the rule, such as the maximum length, in the value attribute. For these validation types, you cannot specify a custom error message.

The following example uses hidden fields to require data in a date field and ensure that the field contains a date. It consists only of HTML tags.

<input type="text" name="StartDate" size="16" maxlength="16"><br>
<input type="hidden" name="StartDate_required"
        value="You must enter a start date.">
<input type="hidden" name="StartDate_date"
    value="Please enter a valid date as the start date.">

Use the following suffixes at the end of hidden form field names to specify the validation type. The type identifier always starts with an underscore. Several validation rules have two names you can use. The names that do not start with "_cf" were used in earlier releases and are retained for backward compatibility. For consistency and clarity, Macromedia recommends using the names that start with "_cf" in new forms.

Field name suffix

Verifies

_integer, _cfforminteger

An integer of the range -2,147,483,648 -- 2,147,483,647. Treats the initial characters "$ ¤ ¥ £ +" as valid input, but removes them from the number.

_cfformnumeric

Any numeric value. Treats the initial characters "$ ¤ ¥ £ +"as valid input, but does NOT remove them from the number.

_float, _cfformfloat

Any value (including an integer) that can be represented as a floating point number with up to 12 significant digits. Treats the initial characters "$ ¤ ¥ £ +" as valid input, but removes them from the number.

Converts input data to a real number; for example a dump of an integer value on the action page includes a decimal point followed by a 0.

_range, _cfformrange

A numeric value within boundaries specified by the value attribute. Specify the range in the value attribute using the format "min=minvalue max=maxvalue." You cannot specify a custom error message for this validation.

_date, _cfformdate

A date in any format that ColdFusion can understand; converts the input to ODBC date format. Allows entry of a time part, but removes it from the ODBC value.

_cfformusdate

A date in the form m/d/y, m-d-y , or m.d.y, The m and d format can be 1 or 2 digits; y can be 2 or 4 digits. Does not convert the string to an ODBC value and does not allow a time part.

_eurodate, _cfformeurodate

A date in the form d/m/y, d-m-y, or d.m.y. The m and d format can be 1 or 2 digits; y can be 2 or 4 digits. Converts the input to ODBC date format. Allows entry of a time part, but removes it from the ODBC value.

_time, _cfformtime

A time. Can be in 12-hour or 24-hour clock format, and can include seconds in the form hh:mm:ss or a case-independent am or pm indicator.

Converts the input to ODBC time format. Allows entry of a date part, but removes it from the ODBC value.

_cfformcreditcard

After stripping blanks and dashes, a number that conforms to the mod10 algorithm. Number must have 13-16 digits.

_cfformSSN, _cfformsocial_security_number

A nine-digit Social Security number. Can be of the form xxx-xx-xxxx or xxx xx xxxx.

_cfformtelephone

Standard U.S. telephone formats. Does not support international telephone numbers.

Allows area codes with or without parentheses, and hyphens (-), spaces, periods, or no separators between standard number groups. Can be preceded by a 1 long-distance designator, and can end with an up-to-5 digit extension, optionally starting with x. The area code and exchange must begin with a digit in the range 1 - 9.

_cfformzipcode

A 5-digit or 9-digit U.S. ZIP code. In 9-digit codes, the final four digits must be preceded by a hyphen (-) or space.

_cfformemail

A valid e-mail address. Valid address characters are a-zA-Z0-9_- and the period and separator. There must be a single at sign (@) and the text after the @ character must include a period, as in my_address@MyCo.com or b-b.jones27@hisco.co.uk.

_cfformURL

A valid URL. Must start with http:\\, https:\\, ftp:\\, file:\\, mailto:, or news:. Can include, as appropriate, username and password designators and query strings. The main part of the address can only have the characters A-Za-z0-9 and -.

_cfformboolean

A value that can be treated as a Boolean: Yes, No, True, False, 0, 1.

_cfformUUID

A universally unique identifier (UUID) that follows the ColdFusion format, xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx, where x is a hexadecimal number.

_cfformGUID

A unique identifier that follows the Microsoft/DCE format, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal number.

_cfformnoblanks

The field must not include blanks. ColdFusion uses this validation only if you also specify a _required hidden field.

_cfformmaxlength

The number of characters must not exceed the number specified by the tag value attribute.

_cfformregex, _cfformregular_expression

The data must match a JavaScript regular expression specified by the tag value attribute.

_required, _cfformrequired

Data must be entered or selected in the form field.

Hidden form field considerations

Consider the following rules and recommendations when determining whether and how to use hidden form field validation:

  • Use hidden field validation if you want to validate data from standard HTML input tags. The cfinput and cftextarea tags include a validateAt attribute that provides a simpler method for specifying server-side validation.
  • Consider using hidden field validation with the cfinput and cftextarea tags if you specify multiple validation rules for a single field and want to provide a separate error message for each validation.
  • Do not use the suffixes listed in the table as field names.
  • Adding a validation rule to a field does not make it a required field. You must add a separate _required hidden field to ensure user entry.

Hidden form field example

The following procedure creates a simple form for entering a start date and a salary. It uses hidden fields to ensure that you enter data and that the data is in the right format.

This example uses a self-submitting form; the same ColdFusion page is both the form page and its action page. The page uses an IsDefined function to check that form data has been submitted. This way, the pages does not show any results until you submit the input. The form uses HTML tags only; you can substitute these tags with the CFML equivalents.

<html>
<head>
    <title>Simple Data Form</title>
</head>
<body>
<h2>Simple Data Form</h2>

<!--- Form part. --->
<form action="datatest.cfm" method="Post">
    <input type="hidden"
        name="StartDate_cfformrequired"
        value="You must enter a start date.">
    <input type="hidden"
        name="StartDate_cfformdate"
        value="Enter a valid date as the start date.">
    <input type="hidden"
        name="Salary_cfformrequired"
        value="You must enter a salary.">
    <input type="hidden"
        name="Salary_cfformfloat"
        value="The salary must be a number.">
    Start Date:
    <input type="text"
        name="StartDate" size="16"
        maxlength="16"><br>
    Salary:
    <input type="text"
        name="Salary"
        size="10"
        maxlength="10"><br>
    <input type="reset"
        name="ResetForm"
        value="Clear Form">
    <input type="submit"
        name="SubmitForm"
        value="Insert Data">
</form>
<br>

<!--- Action part. --->
<cfif isdefined("Form.StartDate")>
    <cfoutput>
        Start Date is: #DateFormat(Form.StartDate)#<br>
        Salary is: #DollarFormat(Form.Salary)#
    </cfoutput>
</cfif>
</html>

When the user submits this form, ColdFusion scans the form fields to find any validation rules. It then uses the rules to analyze the user’s input. If any of the input rules are violated, ColdFusion displays an error page with the error message that you specified in the hidden field’s value attribute. The user must go back to the form, correct the problem, and resubmit the form. ColdFusion does not accept form submission until the user enters the entire form correctly.

Because numeric values often contain commas and currency symbols, ColdFusion automatically deletes these characters from fields with _cfforminteger and _cfformfloat rules before it validates the form field and passes the data to the form's action page. ColdFusion does not delete these characters from fields with _cfformnumeric rules.

Reviewing the code

The following table describes the code and its function:

Code

Description

<form action="datatest.cfm"
    method="post">

Gathers the information from this form sends it to the dataform.cfm page (this page) using the Post method.

<input type="hidden"
    name="StartDate_cfformrequired"
    value="You must enter a start date.">
<input type="hidden"
    name="StartDate_cfformdate"
    value="Enter a valid date as the
    start date.">

Requires input into the StartDate input field. If there is no input, displays the error information "You must enter a start date." Requires the input to be in a valid date format. If the input is not valid, displays the error information "Enter a valid date as the start date."

<input type="hidden"
    name="Salary_required"
    value="You must enter a salary.">
<input type="cfformhidden"
    name="Salary_cfformfloat"
    value="The salary must be a number.">

Requires input into the Salary input field. If there is no input, displays the error information "You must enter a salary." Requires the input to be in a valid number. If it is not valid, displays the error information "The salary must be a number."

Start Date:
<input type="text"
    name="StartDate" size="16"
    maxlength="16"><br>

Creates a text box called StartDate in which users can enter their starting date. Makes it 16-characters wide.

Salary:
<input type="text"
    name="Salary"
    size="10"
    maxlength="10"><br>

Creates a text box called Salary in which users can enter their salary. Makes it ten-characters wide.

<cfif isdefined("Form.StartDate")>
    <cfoutput>
        Start Date is:
            #DateFormat(Form.StartDate)#<br>
        Salary is:
            #DollarFormat(Form.Salary)#
    </cfoutput>
</cfif>

Displays the values of the StartDate and Salary form fields only if they are defined. They are not defined until you submit the form, so they do not appear on the initial form. Uses the DateFormat function to display the start date in the default date format. Uses the DollarFormat function to display the salary with a dollar sign and commas.


Validating form input and handling errors with JavaScript

ColdFusion MX lets you write your own validation routines in JavaScript, and lets you create JavaScript error handlers.

Validating input with JavaScript

In addition to native ColdFusion input validation using the validate attribute of the cfinput and cftextarea tags, the following tags support the onValidate attribute, which lets you specify a JavaScript function to handle your cfform input validation:

  • cfgrid
  • cfinput
  • cfslider
  • cftextarea
  • cftree

ColdFusion passes the following arguments to the JavaScript function that you specify in the onValidate attribute:

  • The form JavaScript DOM object
  • The name attribute of the form element
  • The value of the control to validate

For example, if you write the cfinput tag as the following:

<cfinput type="text"
    ...
<!--- Do not include () in JavaScript function name. --->
    onvalidate="handleValidation"
    ...
>

You define the JavaScript function as the following:

<script>
<!--
function handleValidation(form_object, input_object, object_value) {
...
}
//-->
</script>

Example: validating a password

The following example validates a password. The password must have at least one of each of the following: an uppercase letter, a lowercase letter, and a number. It must be between 8 and 12 characters long. If the password is invalid, the browser displays a message box. If the password is valid, it redisplays the page with a brief success message.

To use JavaScript to validate form data:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>JavaScript Validation</title>

<!--- JavaScript used for validation. --->
<script>
<!--
    // Regular expressions used for pattern matching.
    var anUpperCase = /[A-Z]/;
    var aLowerCase = /[a-z]/;
    var aNumber = /[0-9]/;
    /* The function specified by the onValidate attribute.
        Tests for existence of at least one uppercase, lowercase, and numeric
        character, and checks the length for a minimum.
        A maximum length test is not needed because of the cfinput maxlength
        attribute. */
    function testpasswd(form, ctrl, value) {
        if (value.length < 8 || value.search(anUpperCase) == -1 ||
            value.search (anUpperCase) == -1 || value.search (aNumber) == -1)
        {
            return (false);
        }
        else
        {
            return (true);
        }
    }
//-->
</script>
</head>

<body>
<h2>JavaScript validation test</h2>
<!--- Form is submitted only if the password is valid. --->
<cfif IsDefined("Form.passwd1")>
    <p>Your Password if valid.</p>
</cfif>
<p>Please enter your new password:</p>

<cfform name="UpdateForm" preservedata="Yes" >
    <!--- The onValidate attribute specifies the JavaScript validation
             function. The message attribute is the message that appears
             if the validation function returns False. --->
    <cfinput type="password" name="passwd1" required="YES"
        onValidate="testpasswd"
        message="Your password must have 8-12 characters and include uppercase
and lowercase letters and at least one number."
        size="13" maxlength="12">

<input type="Submit" value=" Update... ">
</cfform>

</body>
</html>
  2. Save the page as validjs.cfm.
  3. View the validjs.cfm page in your browser.

Handling failed validation

The onError attribute lets you specify a JavaScript function to execute if an onValidate, onBlur or onSubmit validation fails. For example, if you use the onValidate attribute to specify a JavaScript function to handle input validation, you can also use the onError attribute to specify a JavaScript function to handle a failed validation (that is, when onValidate returns a False value). If you use the onValidate attribute, you can also use the onError attribute to specify a JavaScript function that handles the validation errors. The following cfform tags support the onerror attribute:

  • cfgrid
  • cfinput
  • cfselect
  • cfslider
  • cftextinput
  • cftree

ColdFusion passes the following JavaScript objects to the function in the onerror attribute:

  • The JavaScript form object
  • The name attribute of the form element
  • The value that failed validation
  • The error message text specified by the CFML tag’s message attribute

The following example shows a form that uses an onError attribute to tell ColdFusion to call a showErrorMessage JavaScript function that uses the alert method to display an error message. The function assembles the message from the invalid value and the contents of the cfinput tag’s message attribute.

<!--- The JavaScript function to handle errors.
         Puts a message, including the field name and value, in an alert box. --->
<script>
    <!--
    function showErrorMessage(form, ctrl, value, message) {
        alert("The value " + value +" of the " + ctrl + " field " + message);
    }
    //-->
</script>

<!--- The form.
    The cfinput tags use the onError attribute to override the ColdFusion
    default error message mechanism. --->
<cfform>
    <!--- A minimum quantity is required and must be a number. --->
    Minimum Quantity: <cfinput type="Text" name="MinQuantity"
        onError="showErrorMessage" validate="numeric" required="Yes"
        message="is not a number." ><br>
    <!--- A maximum quantity is optional, but must be a number if supplied. --->
    Maximum Quantity: <cfinput type="Text" name="MaxQuantity"
        onError="showErrorMessage" validate="numeric"
            message="is not a number." ><br>
    <cfinput type="submit" name="submitit">
</cfform>


Validating data with the IsValid function and the cfparam tag

The IsValid function and cfparam tag validate any ColdFusion MX variable value, not just forms variables. Because they reside entirely on the ColdFusion server, they can provide a secure mechanism for ensuring that the required validation steps get performed. Users cannot evade any of the checks by modifying the form data that gets submitted. These techniques also provide greater flexibility in how you respond to user errors, because you can use full CFML syntax in your error-handling code.

These two validation techniques operate as follows:

  • The IsValid function tests the value of a ColdFusion variable. If the value is valid, it returns True; if the value is invalid, it returns False.
  • The cfparam tag with a type attribute tests the value of a ColdFusion value for validity. If the value is valid, it does nothing; if the value is invalid, it throws a ColdFusion expression exception.

You can use either technique interchangeably. The one you choose should depend on your coding style and programming practices. It can also depend on the specific information that you want to display if an error occurs.

Example: IsValid function validation

The following example checks whether a user has submitted a numeric ID and a valid e-mail address and phone number. If any of the submitted values does not meet the validation test, the page displays an error message.

<!--- Action code. First make sure the form was submitted. --->
<cfif isDefined("form.saveSubmit")>
    <cfif isValid("integer", form.UserID) and isValid("email", form.emailAddr)
            and isValid("telephone", form.phoneNo)>
        <cfoutput>
            <!--- Application code to update the database goes here --->
            <h3>The e-mail address and phone number for user #Form.UserID#
                have been added</h3>
        </cfoutput>
    <cfelse>
        <H3>Please enter a valid user ID, phone number, and e-mail address.</H2>
    </cfif>
    <cfelse>
</cfif>

<!--- The form. --->
<cfform action="#CGI.SCRIPT_NAME#">
    User ID:<cfinput type="Text" name="UserID"><br>
    Phone: <cfinput type="Text" name="phoneNo"><br>
    E-mail: <cfinput type="Text" name="emailAddr"><br>
    <cfinput type="submit" name="saveSubmit" value="Save Data"><br>
</cfform>

Examples: cfparam tag validation

The following two examples use cfparam tags to do the same tests as in the Example: IsValid function validation. They check whether a user has submitted a numeric ID and a valid e-mail address and phone number. If any of the submitted values does not meet the validation test, ColdFusion throws an expression exception.

In the first example, the error is handled by the exprerr.cfm page specified in the cferror tag. In this case, if the user made multiple errors, ColdFusion lists only one.

In the second example, each invalid field is handled in a separate try/catch block. In this case, the user gets information about each error.

Using an error-handling page

The self-posting form and action page looks as follows:

<!--- Action part of the page. --->
<!--- If an expression exception occurs, run the expresser.cfm page. --->
<cferror type="EXCEPTION" exception="expression" template="expresserr.cfm">
<!--- Make sure the form was submitted. --->
<cfif isDefined("form.saveSubmit")>
<!--- Use cfparam tags to check the form field data types. --->
        <cfparam name="form.emailAddr" type="email">
        <cfparam name="form.UserID" type="integer">
        <cfparam name="form.phoneNo" type="telephone">
    <!--- Application code to update the database goes here. --->
    <cfoutput>
        <h3>The e-mail address and phone number for user #Form.UserID#
            have been added</h3>
    </cfoutput>
</cfif>

<!--- The form. --->
<cfform action="#CGI.SCRIPT_NAME#">
    User ID:<cfinput type="Text" name="UserID"><br>
    Phone: <cfinput type="Text" name="phoneNo"><br>
    E-mail: <cfinput type="Text" name="emailAddr"><br>
    <cfinput type="submit" name="saveSubmit" value="Save Data"><br>
</cfform>

The expresserr.cfm page looks as follows:

<cfoutput>
    You entered invalid data.<br>
    Please click the browser Back button and try again<br>
    #cferror.RootCause.detailMessage#
</cfoutput>

Using cftry and cfcatch tags

The self-posting form and action page looks as follows:

<!--- Use a Boolean variable to indicate whether all fields are good. --->
<cfset goodData="Yes">
<!--- Make sure the form was submitted. --->
<cfif isDefined("form.saveSubmit")>
<!--- The cftry block for testing the User ID value. --->
    <cftry>
<!--- The cfparam tag checks the field data types. --->
        <cfparam name="form.UserID" type="integer">
<!--- If the data is invalid, ColdFusion throws an expression exception. --->
<!--- Catch and handle the exception. --->
        <cfcatch type="expression">
            <!--- Set the data validity indicator to False. --->
            <cfset goodData="No">
            <cfoutput>
                Invalid user ID.<br>
                #cfcatch.detail#<br><br>
            </cfoutput>
        </cfcatch>
    </cftry>
<!--- The cftry block for testing the e-mail address value. --->
    <cftry>
        <cfparam name="form.emailAddr" type="email">
        <cfcatch type="expression">
            <cfset goodData="No">
            <cfoutput>
                Invalid e-mail address.<br>
                #cfcatch.detail#<br><br>
            </cfoutput>
        </cfcatch>
    </cftry>
<!--- The cftry block for testing the telephone number value. --->
    <cftry>
        <cfparam name="form.phoneNo" type="telephone">
        <cfcatch type="expression">
            <cfset goodData="No">
            <cfoutput>
                Invalid telephone number.<br>
                #cfcatch.detail#<br><br>
            </cfoutput>
        </cfcatch>
    </cftry>
    <!--- Do this only if the validity indicator was not set to False in a
            validation catch block. --->
    <cfif goodData>
        <!--- Application code to update the database goes here. --->
        <cfoutput>
            <h3>The e-mail address and phone number for user #Form.UserID#
                have been added</h3>
        </cfoutput>
    </cfif> <!--- goodData is True--->
</cfif> <!--- Form was submitted. --->

<cfform action="#CGI.SCRIPT_NAME#" preservedata="Yes">
    User ID:<cfinput type="Text" name="UserID"><br>
    Phone: <cfinput type="Text" name="phoneNo"><br>
    E-mail: <cfinput type="Text" name="emailAddr"><br>
    <cfinput type="submit" name="saveSubmit" value="Save Data"><br>
</cfform>
Previous


Creating Forms in Macromedia Flash

This chapter describes how to create effective forms in Macromedia Flash format. In this format, Macromedia ColdFusion MX 7 displays forms using Flash, not HTML. This chapter describes Flash forms and how they differ from HTML forms, and discusses how to create Flash forms.

Contents

About Flash forms

Building Flash forms

Binding data in Flash forms

Setting styles and skins in Flash forms

Using ActionScript in Flash forms

Best practices for Flash forms
Next


About Flash forms

ColdFusion MX can deliver forms to the client in Macromedia Flash (SWF) file format. ColdFusion automatically generates the Flash binary from your CFML code and displays it on the client. Flash forms have the following advantages over HTML forms:

  • They are browser-independent. Flash Player works in all commonly used browsers on Windows and Macintosh systems, and in Netscape and Mozilla on Linux.
  • By default, they present a modern, visually pleasing appearance, and you can apply predefined color skins or customize the appearance with specifications similar to those in a Cascading Style Sheet (CSS).
  • They let you develop complex, multipart forms that do no require multiple pages, by using tabbed or accordion-style dialog boxes.
  • They automatically do much of the layout work for you.

Note: Flash form configuration requirements differ from ColdFusion MX requirements. For example, Flash forms might not work with all J2EE servers supported by ColdFusion MX. For more information, see Installing and Using ColdFusion MX.

In addition to creating Flash forms, ColdFusion MX lets you specify Flash format for cfcalendar, cftree, and cfgrid tags. Use these tags to embed Flash calendar choosers, trees, and grids in HTML forms, to eliminate the need to use Java applets. This chapter does not specifically discuss using Flash grids and trees in HTML forms; however, the information in this chapter about grids and trees also applies to these elements.

A Flash form example

Flash forms provide many features that help you quickly create easy-to-use, professional-looking, complex forms. The following figure contains a two-tab form that shows many of these features:

This is a picture of the feature being described.

This form includes the following features:

  • Each tab contains a different section of the overall form, and users can enter data on both tabs before submitting the form. This technique can eliminate the need for multiple forms on multiple HTML pages.
  • The first and last names are required fields, indicated by the red asterisks.
  • The Flash form automatically fills the e-mail field with data from the name fields, but the user can override this information.
  • When the user selects the date field, a calendar automatically opens for picking the date.

Flash form CFML differences from HTML forms

Because ColdFusion MX sends a Flash form to the client in SWF format, everything inside a Flash form is rendered by Flash. Rendering the form in Flash has several effects:

  • Plain text and HTML tags in the body of a Flash Form have no effect.
  • You must specify all form content inside CFML tags that support Flash forms.
  • ColdFusion provides two tags that let you take advantage of Flash features and perform tasks that you would otherwise do in HTML: you use the cfformitem tag to add text blocks and horizontal and vertical rules to your form, and you use the cfformgroup tag to structure your form.
  • Standard ColdFusion forms tags, such as cfinput and cftree, include attributes that work only with Flash forms, and attribute values that let you specify form style and behavior. These include the skin attribute with many Flash-specific style attribute values for appearance, and the bind attribute for filling a field value with data from other fields.

The reference pages for the individual tags in CFML Reference describe the form tags and their features, indicating which attributes and values work with Flash forms. This chapter describes how you can use CFML tags to build effective Flash forms.


Building Flash forms

You build Flash forms using standard ColdFusion form tags, plus the cfformgroup and cfformitem tags. These tags create the elements of the form, as follows:

  • The cfcalendar, cfgrid, cfinput, cfselect, cftextarea, and cftree tags create controls for data display and user input.
  • The cfformitem tag lets you add formatted or unformatted text, spacers, and horizontal and vertical rules without using HTML.
  • The cfformgroup tag creates containers, such as horizontally aligned boxes or tabbed navigators, that let you group, organize, and structure the form contents.

Flash forms follow a hierarchical structure of containers and children.

  1. The cfform tag is the master container, and its contents are child containers and controls.
  2. The cfformgroup tag defines a container that organizes its child elements.
  3. All other tags create individual controls, including display elements such as rules.

For example, the figure in the About Flash forms section has the following hierarchical structure of containers and children. (This outline only shows the structure of the page that is visible in the figure. It omits the structure of the Preferences tab.)

1	cfform
2		cfformgroup type="tabnavigator" -- Tab navigator container
3			cfformgroup type="page" -- Tabbed page container, child of tabnavigator
4				cfformgroup type="horizontal" -- Aligns its two children horizontally
5					cfinput type="text" -- First name input control
5					cfinput type="spacer" -- Space between the name input controls
5					cfinput type="text" -- Last name input control
4				cfformitem type="hrule" -- Displays a rule
4				cfformitem type="html" -- Displays formatted text
4				cffinput type="text" -- E-mail input control
4				cfformitem type="hrule" -- Displays a rule
4				cfinput type="text" -- Phone number input control
4				cfinput type="spacer" -- Space between the phone and date controls
4				cfinput type="datefield" -- Date input control
3			cfinput type="page" -- Second tabbed page container for preferences
            .
            .
2		cfformgroup type="horizontal" -- Follows the tabnavigator in the form
3		cfinput type="submit" -- Submit button control
3		cfinput type="reset" -- Reset button control

The following sections describe how you use the various Flash form elements to build a Flash form.

  • Adding text, images, rules, and space with the cfformitem tag
  • Using the cfformgroup tag to structure forms
  • Controlling sizes in Flash forms
  • Repeating Flash form elements based on query data
  • Creating complex forms with accordion and tab navigator containers


Adding text, images, rules, and space with the cfformitem tag

Because Flash forms do not support inline HTML, you use the cfformitem tag to add text blocks and horizontal and vertical rules to your form. (Flash form controls, such as cfinput, use the label or value attribute to specify text labels.) You can also use the cfformitem tag to add spacers between visual form elements.

The cfformitem type="hrule" and cfformitem type="vrule" tags put horizontal and vertical rules in the form. You can specify the rule thickness, color, and shadow characteristics by using style specifications. For more information on specifying rule styles, see Styles for cfformitem with hrule or vrule type attributes in ColdFusion MX Flash Form Style Reference in CFML Reference.

The cfformitem type="spacer" tag puts a blank space of the specified height and width on the form. This tag type does not use styles; it can be useful in improving the form appearance by helping you control the form layout.

The cfformitem type="text" tag lets you insert plain text in the form You can use the style attribute to apply a consistent format to the text.

The cfformitem type="html" tag lets you insert formatted text and images in the form. You can include basic HTML-style formatting tags in the body of this tag to add images and to format and style the text.

You can use the following formatting tags and attributes in the body of a cfformitem type="html" tag:

:
Tag | Valid attributes
a | href URL to link to. target window name; can be a standard HTML window name such as _blank.
b | None.
br | None.
font | color Must be in hexadecimal format, such as #FF00AA. Use a single number sign (#) character. face Can be a comma-delimited list of font face names; Flash uses the first font that is available on the client system. size In pixels; + and -relative values are allowed.
i | None.
img | See the attribute table for the img tag. Note: You must close this tag with /> or an </img> tag.
li | None.
p | align Must be one of the following: left, right, center.
textformat | See the attribute table for the textformat tag.
u | None.

The img tag supports the following attributes:

Attribute | Description
src | (Required) URL or pathname to a JPEG or SWF file. Images are not displayed until they have downloaded completely. Flash Player does not support progressive JPEG files.
width | Width of the image, in pixels.
height | Height of the image in pixels.
align | Horizontal alignment of the embedded image within the text field. Valid values are left and right. The default value is left.
hspace | Number of pixels of horizontal space that surround the image where no text appears. The default value is 8.
vspace | Number of pixels of vertical space that surround the image where no text appears. The default value is 8.

Note: Because of the Flash dynamic sizing rules, to ensure that the image displays properly, you might have to specify the formitem tag height attribute and the width and height attributes for the form or the containing cfformgroup tag. Also, the image always displays on a new line, not inline with text, and text that follows the image in your code occupies any available space to the right of the image.

The textformat tag is specific to Flash, and has the following attributes:

Attribute | Description
blockindent | Block indentation, in points.
indent | Indentation from the left margin to the first character in the paragraph.
leading | Amount of leading (vertical space) between lines.
leftmargin | Left margin of the paragraph, in points.
rightmargin | Right margin of the paragraph, in points.
tabstops | Custom tab stops as an array of nonnegative integers. To specify tabs in text, use the \t escape character.

For detailed descriptions of these tags, see the Flash documentation.

The following code creates a simple Flash form that consists of a formatted text area surrounded by horizontal rules:

<cfform name="myform" height="220" width="400" format="Flash" >
    <!--- Use text formitem tag with style specifications for the heading. --->
    <cfformitem type="text" style="fontWeight:bold; fontSize:14;">
    Flash form with formatted text and rules
    </cfformitem>
    <!--- The spacer adds space between the text and the rule --->
    <cfformitem type="spacer" height="2" />
    <cfformitem type="hrule" />
    <cfformitem type="html">
        <b><font color="#FF0000" size="+4" face="serif">
        This form has formatted text, including:</font></b><br>
        <textformat blockindent="20" leading="2">
            <li>colored text</li>
            <li><i>italic and bold text</i></li>
            <li>a bulleted list in an indented block</li>
        </textformat>
        <p><b>The text is preceded and followed by horizontal rules</b></p>
        It also has a link to a web page.</b><br>
        <a href="http://www.macromedia.com/" target="_blank">
        <font color="#0000FF"><u>
        This link displays the Macromedia home page in a new browser window
        </u></font></a>
    </cfformitem>
    <cfformitem type="spacer" height="2" />
    <cfformitem type="hrule" />
</cfform>

This form appears as follows:

Flash form that results from preceding code


Using the cfformgroup tag to structure forms

ColdFusion provides form group container types that provide basic structure to a Flash form. You specify these types in the type attribute of the cfformgroup tag. Use the following container types to control the layout of controls and groups of controls:

Type

Description

horizontal

Arranges individual controls horizontally, and optionally applies a label to the left of the controls. Use only for arranging ColdFusion form controls, including cfformitem controls. As a general rule, do not use to organize cfformgroup containers; use the hbox attribute instead.

If you put other cfformgroup tags inside a horizontal form group, the controls inside the included cfformgroup tag do not align with other controls in the horizontal group.

vertical

Arranges individual controls vertically, and optionally applies a label to the left (not top) of the controls. Use only for groups of ColdFusion form controls, including cfformitem controls. As a general rule, do not use to organize cfformgroup containers; use the vbox attribute instead.

If you put other cfformgroup tags inside a vertical form group, the controls inside the included cfformgroup tag do not align with other controls in the vertical group.

hbox

Arranges groups of controls horizontally. Does not apply a label. Use this attribute value to arrange other cfformgroup containers. This tag does not enforce alignment of child controls that have labels, so you should not use it to align individual controls.

vbox

Arranges groups of controls vertically. Does not apply a label. Use this attribute value to arrange other cfformgroup containers. This tag does not enforce alignment of child controls that have labels, so you should not use it to align individual controls.

hdividedbox

Arranges two or more children horizontally, and puts divider handles between the children that users can drag to change the relative sizes of the children. Does not apply a label. The direct children of an hdividedbox container must be cfformgroup tags with type attributes other than horizontal or vertical.

vdividedbox

Arranges two or more children vertically, and puts divider handles between the children that users can drag to change the relative sizes of the children. Does not apply a label. The direct children of a vdividedbox container must be cfformgroup tags with type attributes other than horizontal or vertical.

tile

Arranges its children in a rectangular grid in row-first order. Does not apply a label.

panel

Consists of a title bar containing the label attribute text, a border, and a content area with vertically arranged children.

accordion

Puts each of its child pages in an accordion pleat with a label bar. Displays the contents of one pleat at a time. Users click the labels to expand or contract the pleat pages. Does not apply a label.

tabnavigator

Puts each of its children on a tabbed page. Users click the tabs to display a selected page. Does not apply a label.

page

The immediate child of an accordion or tab navigator container. Specifies the label on the pleat bar or tab, and arranges its child containers and controls vertically.

For more information on using the accordion, tabnavigator, and page cfformgroup types, see Creating complex forms with accordion and tab navigator containers.

Example: structuring with the cfformgroup tag

The following example shows a form with an hdividedbox container with two vbox containers. The left box uses a horizontal container to arrange two radio buttons. The right box uses a tile container to lay out its check boxes. You can drag the divider handle to resize the two boxes. When you submit the form, the ColdFusion page dumps the Form scope to show the submitted data.

<cfif Isdefined("Form.fieldnames")>
<cfdump var="#form#" label="form scope">
<br><br>
</cfif>

<cfform name="myform" height="200" width="460" format="Flash" skin="HaloBlue">
    <cfformitem type="html" height="20">
        <b>Tell us your preferences</b>
    </cfformitem>
    <!--- Put the pet selectors to the left of the fruit selectors. --->
    <cfformgroup type="hdividedbox" >
    <!--- Group the pet selector box contents, aligned vertically. --->
        <cfformgroup type="VBox"  height="130">
            <cfformitem type="text" height="20">
                Pets:
            </cfformitem>
            <cfformgroup type="vertical" height="80">
                <cfinput type="Radio" name="pets" label="Dogs" value="Dogs"
                    checked>
                <cfinput type="Radio" name="pets" label="Cats" value="Cats">
            </cfformgroup>
        </cfformgroup>

    <!--- Group the fruit selector box contents, aligned vertically. --->
        <cfformgroup type="VBox" height="130">
            <cfformitem type="text" height="20">
                Fruits:
            </cfformitem>
            <cfformgroup type="tile" height="80" width="190" label="Tile box">
                <--- Flash requires unique names for all controls --->
                <cfinput type = "Checkbox" name="chk1" Label="Apples"
                    value="Apples">
                <cfinput type="Checkbox" name="chk2" Label="Bananas"
                    value="Bananas">
                <cfinput type="Checkbox" name="chk3" Label="Pears"
                    value="Pears">
                <cfinput type="Checkbox" name="chk4" Label="Oranges"
                value="Oranges">
                <cfinput type="Checkbox" name="chk5" Label="Grapes"
                    value="Grapes">
                <cfinput type="Checkbox" name="chk6" Label="Cumquats"
                    value="Cumquats">
            </cfformgroup>
        </cfformgroup>
    </cfformgroup>
    <cfformgroup type="horizontal">
        <cfinput type="submit" name="submit" width="100" value="Show Results">
        <cfinput type="reset" name="reset" width="100" value="Reset Fields">
    </cfformgroup>
</cfform>


Controlling sizes in Flash forms

Sizing elements in a Flash form is something of an art, rather than a science. As a general rule, if you don’t specify the height and width attributes, Flash tends to do a good job of laying out the form. However, keep in mind the following considerations:

  • If you do not specify the height and width attributes in the cfform tag, Flash reserves the full dimensions of the visible browser window, if the form is not in a table, or the table cell, if the form is in a table, even if they are not required for the form contents. Any HTML output that precedes or follows the form causes the output page to exceed the size of the browser window.
  • If you do not specify the height or width of a control, including a form group, Flash adjusts the dimensions, trying to fit the controls in the available space. For example, Flash often extends input boxes to the width of the containing control, if not otherwise specified.

In general, it is best to use the following process when you design your Flash form.

To determine the sizes of a Flash form and its controls:

  1. When you first create the form, don’t specify any height and width attributes on the form or its child tags. Run the form and examine the results to determine height and width values to use.
  2. Specify height and width attributes in the cfform tag for the desired dimensions of the form. You can specify absolute pixel values, or percentage values relative to the size of the containing window.
  3. Specify any height or width attributes on individual tags. These values must be in pixels.
  4. Repeat step 3 for various tags, and possibly step 2, until your form has a pleasing appearance.


Repeating Flash form elements based on query data

The repeater cfformgroup type tells Flash Player to iterate over a query and create a set of the cfformgroup tag’s child controls for each row in the query. For each set of child controls, bind attributes in the child tags can access fields in the current query row. This cfformgroup type lets you create Flash forms where the number of controls can change based on a query, without requiring ColdFusion to recompile the Flash SWF file for the form. This significantly enhances server performance.

Note: For more information on binding data, see Binding data in Flash forms.

Optionally, you can specify a start row and a maximum number of rows to use in the repeater. Unlike most ColdFusion tags, cfrepeater index values start at 0, not 1. To specify a repeater that starts on the first line of the query object and uses no more than 15 rows, use a tag such as the following:

<cfformgroup type="repeater" query="q1" startrow="0" maxrows="15">

One example that might use a repeater is a form that lets a teacher select a specific class and update the student grades. Each class can have a different number of students, so the form must have a varying number of input lines. Another example is a shopping cart application that displays the product name and quantity ordered and lets users change the quantity.

The following example uses the cfformgroup tag with a repeater type attribute value to populate a form. It creates a query, and uses the repeater to iterate over a query and create a firstname and lastname input box for each row in the query.

<cfif IsDefined("Form.fieldnames")>
    <cfdump var="#form#" label="form scope">
    <br><br>
</cfif>
<cfscript>
    q1 = queryNew("id,firstname,lastname");
    queryAddRow(q1);
    querySetCell(q1, "id", "1");
    querySetCell(q1, "firstname", "Rob");
    querySetCell(q1, "lastname", "Smith");
    queryAddRow(q1);
    querySetCell(q1, "id", "2");
    querySetCell(q1, "firstname", "John");
    querySetCell(q1, "lastname", "Doe");
    queryAddRow(q1);
    querySetCell(q1, "id", "3");
    querySetCell(q1, "firstname", "Jane");
    querySetCell(q1, "lastname", "Doe");
    queryAddRow(q1);
    querySetCell(q1, "id", "4");
    querySetCell(q1, "firstname", "Erik");
    querySetCell(q1, "lastname", "Pramenter");
</cfscript>

<cfform name="form1" format="flash" height="220" width="450">
    <cfselect label="select a teacher" name="sel1" query="q1" value="id"
        display="firstname" width="100" />
    <cfformgroup type="repeater" query="q1">
        <cfformgroup type="horizontal" label="name">
            <cfinput type="Text" name="fname"  bind="{q1.currentItem.firstname}">
            <cfinput type="Text" name="lname" bind="{q1.currentItem.lastname}">
        </cfformgroup>
    </cfformgroup>
    <cfinput type="submit" name="submitBtn" value="Send Data" width="100">
</cfform>


Creating complex forms with accordion and tab navigator containers

The accordion and tabnavigator attributes of the cfformgroup tag let you construct complex forms that would otherwise require multiple HTML pages. With accordions and tab navigator containers, users can switch among multiple entry areas without submitting intermediate forms. All data that they enter is available until they submit the form, and all form elements load at one time.

An accordion container puts each logical form page on an accordion pleat. Each pleat has a label bar; when the user clicks a bar, the current page collapses and the selected page expands to fill the available form space. The following figure shows a three-pleat accordion, open to the middle pleat, Preferences:

A three-pleat accordion form, showing the middle pleat, Preferences

A tab navigator container puts each logical form page on a tabbed frame. When the user clicks a tab, the selected page replaces the previous page. The figure in About Flash forms shows a tab navigator container.

The following example generates a two-tab tab navigator container that gets contact information and preferences. You can change it to an accordion container by changing the type attribute of the first cfformgroup tag from accordion to tabnavigator. To prevent the accordion from having scroll bars, you must also increase the cfform tag height attribute to 310 and the tabnavigator tag height attribute to 260.

<cfif IsDefined("Form.fieldnames")>
    <cfdump var="#form#" label="form scope">
    <br><br>
</cfif>
<br>
<cfform name="myform" height="285" width="480" format="Flash" skin="HaloBlue">
    <cfformgroup type="tabnavigator" height="240" style="marginTop: 0">
        <cfformgroup type="page" label="Contact Information">
            <!--- Align the first and last name fields horizontally. --->
            <cfformgroup type="horizontal" label="Your Name">
                <cfinput type="text" required="Yes" name="firstName" label="First"
                    value="" width="100"/>
                <cfinput type="text" required="Yes" name="lastName" label="Last"
                    value="" width="100"/>
            </cfformgroup>
            <cfformitem type="hrule" />
            <cfformitem type="HTML"><textformat indent="95"><font size="-2">
                Flash fills this field in automatically.
                You can replace the text.
                </font></textformat>
            </cfformitem>
            <!--- The bind attribute gets the field contents from the firstName
                    and lastName fields as they get filled in. --->
            <cfinput type="text" name="email" label="email"
                bind="{firstName.text}.{lastName.text}@mm.com">
            <cfformitem type="spacer" height="3" />
            <cfformitem type="hrule" />
            <cfformitem type="spacer" height="3" />

            <cfinput type="text" name="phone" validate="telephone" required="no"
                label="Phone Number">
            <cfinput type="datefield" name="mydate1" label="Requested date">
        </cfformgroup>

        <cfformgroup type="page" label="Preferences" style="marginTop: 0">
            <cfformitem type="html" height="20">
                <b>Tell us your preferences</b>
            </cfformitem>
            <!--- Put the pet selectors to the left of the fruit selectors. --->
            <cfformgroup type="hdividedbox" >
            <!--- Group the pet selector box contents, aligned vertically. --->
                <cfformgroup type="VBox"  height="130">
                    <cfformitem type="text" height="20">
                        Pets:
                    </cfformitem>
                    <cfformgroup type="vertical" height="80">
                        <cfinput type="Radio" name="pets" label="Dogs" value="Dogs"
                            checked>
                        <cfinput type="Radio" name="pets" label="Cats" value="Cats">
                    </cfformgroup>
                </cfformgroup>

            <!--- Group the fruit selector box contents, aligned vertically. --->
                <cfformgroup type="VBox" height="130">
                    <cfformitem type="text" height="20">
                        Fruits:
                    </cfformitem>
                    <cfformgroup type="tile" height="80" width="190" label="Tile box">
                        <--- Flash requires unique names for all controls. --->
                        <cfinput type = "Checkbox" name="chk1" Label="Apples"
                            value="Apples">
                        <cfinput type="Checkbox" name="chk2" Label="Bananas"
                            value="Bananas">
                        <cfinput type="Checkbox" name="chk3" Label="Pears"
                            value="Pears">
                        <cfinput type="Checkbox" name="chk4" Label="Oranges"
                            value="Oranges">
                        <cfinput type="Checkbox" name="chk5" Label="Grapes"
                            value="Grapes">
                        <cfinput type="Checkbox" name="chk6" Label="Kumquats"
                            value="Cumquats">
                    </cfformgroup>
                </cfformgroup>
            </cfformgroup>
        </cfformgroup>
    </cfformgroup>

    <cfformgroup type="horizontal">
        <cfinput type = "submit" name="submit" width="100" value = "Show Results">
        <cfinput type = "reset" name="reset" width="100" value = "Reset Fields">
    </cfformgroup>
</cfform>


Binding data in Flash forms

The bind attribute lets you set the value of the fields using the contents of other form fields. You can use the bind attribute with the cftextarea tag and any cfinput type that takes a value, including hidden. This data binding occurs dynamically as the user enters data within Flash on the client system. Flash does not send any information to ColdFusion until the user submits the form. To use the bind attribute to specify the field value, use the following formats:

Data source | bind attribute format
cfinput type = "text" or cftextarea text | bind="{sourceName.text}"
cfinput selected radio button | bind="{sourceName.selectedData}"
cftree selected item | bind="{sourceName.selectedNode.getProperty('data').value}
cfgrid selected item | bind="{sourceName.selectedItem.COLUMNAME}"
cfselect selected item | bind="{sourceName.selectedItem.data}"

Note: If you use the bind attribute, you cannot use the value attribute.

The following rules and techniques apply to the binding formats:

  • The sourceName value in these formats is the name attribute of the tag that contains the element that you are binding to.
  • You can bind to additional information about a selected item in a tree. Replace value with display to get the displayed value, or with path to get the path to the node in the tree.
  • You can bind to the displayed value of a cfselect item by replacing data with label.
  • If the user selects multiple items in a cfselect control, the selectedItem object contains the most recent selection, and a selectedItems array contains all selected items. You can access the individual values in the array, as in myTree.selectedItems[1].data. The selectedItems array exists only if the user selects multiple items; otherwise, it is undefined.
  • You can use ActionScript expressions in Flash bind statements.

The following example shows how to use the values from the firstName and lastName fields to construct an e-mail address. The user can change or replace this value with a typed entry.

<cfformgroup type="horizontal" label="Your Name">
    <cfinput type="text" required="Yes" name="firstName" label="First"
        value="" width="100"/>
    <cfinput type="text" required="Yes" name="lastName" label="Last"
        value="" width="100"/>
</cfformgroup>
<cfinput type="text" name="email" label="email"
    bind="{firstName.text}.{lastName.text}@mm.com">


Setting styles and skins in Flash forms

ColdFusion provides the following methods for controlling the style and appearance of Flash forms and their elements:

Skins provide a simple method for controlling the overall appearance of your form. A single skin controls the entire form.

Styles provide a finer-grained level of control than skins. Each style specifies a particular characteristic for a single control. Many styles are also inherited by a control’s children.

You can use both techniques in combination: you can specify a skin for your form and use styles to specify the appearance (such as input text font) of individual controls.

The following sections describe these methods and how you can use them. For detailed information on the style names and values that you can use, see ColdFusion MX Flash Form Style Reference in CFML Reference.

  • Controlling form appearance with Flash skins
  • About Flash form styles
  • Flash form style specification syntax
  • About Flash form style value formats
  • About Flash form style applicability and inheritance
  • Example: applying styles to a Flash form


Controlling form appearance with Flash skins

The cfform tag takes a skin attribute, which lets you select an overall appearance for your form. The skin determines the color used for highlighted and selected elements.

You can select the following Flash skins:

  • haloBlue
  • haloGreen (the default)
  • haloOrange
  • haloSilver


About Flash form styles

The ColdFusion Flash form tags have a style attribute that lets you specify control characteristics using CSS syntax. You can specify a style attribute in the following tags:

  • cfform
  • cfformgroup
  • cfcalendar
  • cfformitem, types hrule and vrule
  • cfgrid
  • cfinput
  • cfselect
  • cftextarea
  • cftree

The attributes for the cfform and cfformgroup generally apply to all the form or form group’s children.

Flash supports many, but not all, standard CSS styles. ColdFusion MX Flash forms only support applying specific CSS style specifications to individual CFML tags and their corresponding Flash controls and groups. You cannot use an external style sheet or define a document-level style sheet, as you can for HTML format forms.


Flash form style specification syntax

To specify a Flash style, use the following format:

style="stylename1: value; stylename2: value; ..."

For example, the following code specifies three style values for a text input control:

<cfinput type="text" name="text2" label="Last"
    style="borderSyle:inset; fontSize:12; backgroundColor:##FFEEFF">


About Flash form style value formats

Style properties can be Boolean values, strings, numbers, or arrays of these values. The following sections describe the formats for length, time, and color values.

Length format

You specify styles that take length or dimension values, including font sizes, in pixels.

The fontSize style property lets you use a set of keywords in addition to numbered units. You can use the following keywords when you set the fontSize style property. The exact sizes are defined by the client browser.

  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large

The following cfinput tag uses the style attribute with a fontSize keyword to specify the size of the text in the input box:

<cfinput type="text" name="text1" style="fontSize:X-large" label="Name">

Time format

You specify styles that take time values, such as the openDuration style that specifies how fast an accordion pleat opens, in milliseconds. The following example shows an accordion tag that takes one-half second to change between accordion pleats:

<cfformgroup type="accordion" height="260" style="openDuration: 500">

Color format

You define color values, such as those for the backgroundColor style, in the following formats:

Format | Description
hexadecimal | Hexadecimal colors are represented by a six-digit code preceded by two number sign characters (##). Two # characters are required to prevent ColdFusion from interpreting the character. The range of possible values is ##000000 to ##FFFFFF.
VGA color names | VGA color names are a set of 16 basic colors supported by all browsers that support CSS. The available color names are Aqua, Black, Blue, Fuchsia, Gray, Green, Lime, Maroon, Navy, Olive, Purple, Red, Silver, Teal, White, and Yellow. Some browsers support a larger list of color names. VGA color names are not case-sensitive.

Some styles support only the hexadecimal color format.

Some controls accept multiple colors. For example, the tree control’s depthColors style property can use a different background color for each level in the tree. To assign multiple colors, use a comma-delimited list, as the following example shows:

style="depthColors: ##EAEAEA, ##FF22CC, ##FFFFFF"


About Flash form style applicability and inheritance

Because of the way Flash control styles are implemented, some common styles are valid, but have no effect, in some tags. Therefore, in the table in Styles valid for all controls in ColdFusion MX Flash Form Style Reference in CFML Reference, the listed styles do not cause errors when used in controls, but might not have any effect.

Styles can be inheritable or noninheritable. If a style is noninheritable, it only affects the tag, and does not affect any of its children. For example, to maintain a consistent background color in an hbox form group and its children tags, you must specify the color in all tags. If a style is inheritable, it applies to the tag and its children.


Example: applying styles to a Flash form

The following form uses a skin and styles to control its appearance:

Form that uses a skin and styles to control its appearance

The code for the form is as follows. Comments in the code explain how formatting controls and styles determine the appearance.

<!--- Specify the form height and width, use the HaloBlue skin.
         Note: Flash ignores a backgroundColor style set in cfform. --->
<cfform name="myform" height="390" width="440" format="Flash" skin="HaloBlue">
    <!--- The input area is a panel. Styles to specify panel characteristics.
             Child controls inherit the background color and font settings. --->
    <cfformgroup type="Panel" label="Contact Information"
            style="marginTop:20; marginBottom:20; fontSize:14; fontStyle:italic;
            headerColors:##FFFF00, ##999900; backgroundColor:##FFFFEE;
            headerHeight:35; cornerRadius:12">
        <!--- This vbox sets the font size and style, and spacing between and
                 around its child controls. --->
        <cfformgroup type="vbox" style="fontSize:12; fontStyle:normal;
                verticalGap:18; marginLeft:10; marginRight:10">
            <!--- Use a horizontal group to align the first and last name fields
                     and set a common label. --->
            <cfformgroup type="horizontal" label="Name" >
                <!--- Use text styles to highlight the entered names. --->
                <cfinput type="text" required="Yes" name="firstName" label="First"
                    value="" width="120" style="color:##006090; fontSize:12;
                    fontWeight:bold" />
                <cfinput type="text" required="Yes" name="lastName" label="Last"
                    value="" width="120" style="color:##006090; fontSize:12;
                    fontWeight:bold"/>
            </cfformgroup>
            <!--- Horizontal rules surround the e-mail address.
                     Styles specify the rule characteristics. --->
            <cfformitem type="hrule" style="color:##999900; shadowColor:##DDDD66;
                strokeWidth:4"/>
            <cfformitem type="HTML" Style="marginTop:0; marginBottom:0">
                <textformat indent="57"> <font size="-1">Flash fills this field in
                automatically. You can replace the text.</font></textformat>
            </cfformitem>
            <cfinput type="text" name="email" label="email"
                bind="{firstName.text}.{lastName.text}@mm.com">
            <cfformitem type="hrule" style="color:##999900; shadowColor:##DDDD66;
                strokeWidth:4"/>
            <cfinput type="text" name="phone" validate="telephone" label="Phone">
            <!--- Styles control the colors of the current, selected, and
                rolled-over dates. --->
            <cfinput type="datefield" name="mydate1" label="Date"
                style="rollOverColor:##DDDDFF; selectionColor:##0000FF;
                todayColor:##AAAAFF">
        </cfformgroup> <!--- vbox --->
    </cfformgroup> <!--- panel --->
    <!--- A style centers the buttons at the bottom of the form. --->
    <cfformgroup type="horizontal"style="horizontalAlign:center">
        <cfinput type = "submit" name="submit" width="100" value = "Show Results">
        <cfinput type = "reset" name="reset" width="100" value = "Reset Fields">
    </cfformgroup>
</cfform>


Using ActionScript in Flash forms

ActionScript 2 is a powerful scripting language that is used in Macromedia Flash and other related products and is similar to JavaScript. You can use a subset of ActionScript 2 code in your Flash forms.

The following sections tells you how to include ActionScript in your Flash forms, and describes restrictions and additions to ActionScript that apply to ColdFusion MX Flash forms. It does not provide information on writing ActionScript. For details on ActionScript and how you can use it, see the Flash ActionScript 2 documentation, including the documents available in the Flash MX 2004 and Flex sections of Macromedia Livedocs.

This section includes the following topics:

  • Using ActionScript code in CFML
  • Restricted ActionScript keywords
  • Custom ActionScript functions


Using ActionScript code in CFML

You can use ActionScript in the following attribute of tags in CFML Flash format forms:

  • Form and control events, such as the onSubmit attribute of the cfform tag, or the onChange and onClick attributes of the cfinput tag. The attribute description on the tag reference pages in CFML Reference list the event attributes.
  • Bind expressions, which you can use to set field values. For more information on binding data, see Binding data in Flash forms.

Your ActionScript code must be inline in the form attribute specification. You cannot create your own ActionScript function as a separate script and use it in the attribute value.

The following example shows a simple Fahrenheit to Celsius converter that does the conversion directly on the client, without requiring the user to submit a form to the ColdFusion server.

<cfform format="flash" width="200" height="150">
    <cfinput type="text" name="fahrenheit" label="Fahrenheit" width="100"
        value="68">
    <cfinput type="text" name="celsius" label="Celsius" width="100">
    <cfinput type="button" name="convert" value="Convert" width="100"
        onClick="celsius.text = Math.round((farenheit.text-32)/1.8*10)/10">
</cfform>

Note: You do not use the text property (for example, fieldname.text) to access hidden fields. To access a hidden field, use the format formname.fieldname = 'value'.


Restricted ActionScript keywords

The following ActionScript keywords are restricted in ColdFusion MX Flash forms. If you use any of them, ColdFusion MX generates an error:

__proto__

createTextField

loadMovie

attachMovie

Delete

New

createChild

duplicateMovieClip

registerClass


Custom ActionScript functions

Custom ActionScript functions are the equivalent of CFML UDFs. ColdFusion does not fully support your writing or using custom ActionScript functions; however, it does include a small number of predefined custom ActionScript functions that you can use in your Flash form controls.

You can use the following functions in the ActionScript for all form controls to reset or submit the form:

  • resetForm()
  • submitForm()

You can use the following functions in cfgrid tags only to insert and delete rows in the grid:

  • GridData.insertRow(gridName)
  • GridData.deleteRow(gridName)

The following example shows how you can use the two GridData functions to add custom buttons that add and delete rows from a Flash form. These buttons are equivalent to the buttons that ColdFusion creates if you specify insert="yes" and delete="yes" in the cfgrid tag, but they allow you to specify you own button text and placement. This example puts the buttons on the side of the grid, instead of below it and uses longer than standard button labels..

<cfform format="flash" height="265" width="400">
    <cfformitem type="html">
        You can edit this grid as follows:
        <ul>
        <li>To change an item, click the field and type.</li>
        <li>To add a row, click the Insert Row button and type in the fields
            in the highlighted row.</li>
        <li>To delete a row, click anywhere in the row and click the
            Delete Row button</li>
        </ul>
        <p><b>When you are done, click the submit button.</b></p>
    </cfformitem>
    <!--- The hbox aligns the grid and the button vbox horizontally --->
    <cfformgroup type="hbox" style="verticalAlign:bottom;
            horizontalAlign:center">
        <!--- To make all elements align properly, all of the hbox children must
            be containers, so we must put the cfgrid tag in a vbox tag. --->
        <cfformgroup type="vbox">
            <!-- An editable grid with hard coded data (for simplicity).
                By default, this grid does not have insert or delete buttons. --->
            <cfgrid name="mygrid" height="120" width="250" selectmode="edit">
                <cfgridcolumn name="city">
                <cfgridcolumn name="state">
                <cfgridrow data="Rockville,MD">
                <cfgridrow data="Washington,DC">
                <cfgridrow data="Arlington,VA">
            </cfgrid>
        </cfformgroup>
        <!--- Group the Insert and Delete buttons vertically;
                use a vbox to ensure correct alignment. --->
        <cfformgroup type="vbox" name="buttons"  style="verticalAlign:bottom;
                horizontalAlign:center">
            <!--- Use a spacer to position the buttons. --->
            <cfformitem type="spacer" height="18" />
            <!--- Use the insertRow method in the onClick event to add a row. --->
            <cfinput type="button" name="ins" value="Insert a new row" width="125"
                onClick="GridData.insertRow(mygrid);">
            <!--- Use the deleteRow method in the onClick event to delete
                the selected row --->
            <cfinput type="button" name="del" value="Delete selected row"
                    width="125" onClick="GridData.deleteRow(mygrid)">
            <cfinput type="submit" name="f1" value="Submit" width="125">
        </cfformgroup>
    </cfformgroup>
</cfform>

<!--- Dump the form if it has been submitted. --->
<cfif IsDefined("form.fieldnames")>
<cfdump var="#form#"><br>
</cfif>


Best practices for Flash forms

The following sections describe best practices that can help you increase the performance of Flash forms.

Minimizing form recompilation

Flash forms are sent to the client as SWF files, which ColdFusion must compile from your CFML code. The following techniques can help limit how frequently ColdFusion must recompile a Flash form.

  • Only data should be dynamic. Whenever a variable name changes, or a form characteristic, such as an element width or a label changes, the Flash output must be recompiled. If a data value changes, the output does not need to be recompiled.
  • Use cfformgroup type="repeater" if you must loop no more than ten times over no more than ten elements. This tag does not require recompiling when the number of elements changes. It does have a processing overhead that increases with the number of loops and elements, however, so for large data sets or many elements, it is often more efficient not to use the repeater.

Caching data in Flash forms

The cfform tag timeout attribute specifies how many seconds ColdFusion retains Flash form data on the server. When a Flash form is generated, the values for the form are stored in memory on the server. When the Flash form is loaded on the client, it requests these form values from the server. If this attribute is 0, the default, the data on the server is immediately deleted after the data has been requested from the Flash form.

A Flash form can be reloaded multiple times if a user displays a page with a Flash form, goes to another page, and uses the browser Back button to return to the page with the form. This kind of behavior is common with search forms, login forms, and the like. When the user returns to the original page:

  • If the timeout value is 0, or the timeout period has expired, the data is no longer available, and ColdFusion returns a data-expired exception to the browser; in this case, the browser typically tells the user to reload the page.
  • If the timeout has not expired, the browser displays the original data.

If your form data contains sensitive information, such as credit card numbers or social security numbers, you should leave the timeout set to 0. Otherwise, consider setting a timeout value that corresponds to a small number of minutes.
Previous


Creating Skinnable XML Forms

This chapter describes how to create XML skinnable forms, which are forms that generate XForms-compliant XML and are normally formatted using an XSLT (extensible stylesheet language transformations) skin. The chapter also provides information on the format of the XML that Macromedia ColdFusion MX 7 generates for transformation by XSLT skins.

You can use XML skinnable forms with the skins that ColdFusion MX provides without having any knowledge of either XML or XSLT. Therefore, the first two sections in this chapter do not require that you have any knowledge of these technologies. The rest of this chapter, however, assumes that you have some familiarity with XML and XSLT. The chapter does not provide an introduction to, or detailed information on, writing XSLT, and it does not document XML. For information on using XML with ColdFusion MX, see Using XML and WDDX.

Contents

About XML skinnable forms

Building XML skinnable forms

ColdFusion XML format

Creating XSLT skins
Next


About XML skinnable forms

A ColdFusion MX form with a format="XML" attribute is an XML skinnable form. When ColdFusion MX processes an XML skinnable form, it generates the form as XML. By default, it applies an XML Stylesheet Language Transform (XSLT) skin to the XML and generates a formatted HTML page for display on the user’s browser. Optionally, you can specify an XSLT file, or you can process the raw XML in your ColdFusion page.

By using XML skinnable forms, you can control the type and appearance of the forms that ColdFusion MX generates and displays. ColdFusion MX provides a set of standard skins, including a default skin that it uses if you do not specify another skin (or tell it not to apply a skin). You can also create your own XSLT skin and have ColdFusion use it to give your forms a specific style or appearance.

ColdFusion forms and XForms

ColdFusion skinnable forms conform to and extend the W3C XForms specification. This specification provides an XML syntax for defining interactive forms using a syntax that is independent of form appearance. ColdFusion MX forms tags include attributes that provide information that does not correspond directly to the XForms model, such as appearance information, validation rules, and standard HTML attributes. ColdFusion skinnable forms retain this information in XForms extensions so that an XSL transformation can use the values to determine appearance or do other processing.

For more information on XML structure of ColdFusion skinnable forms, see ColdFusion XML format.

The role of the XSLT skin

An XSLT skin and associated cascading style sheet (CSS) determine how an XML skinnable form is processed and displayed, as follows:

  • The XSLT skin tells ColdFusion MX how to process the XML, and typically converts it to HTML for display. The skin specifies the CSS style sheet to use to format the output.
  • The CSS style sheet specifies style definitions that determine the appearance of the generated output.

XSLT skins give you extensive freedom in the generated output. They let you create a custom appearance for your forms, or even different appearances for different purposes. For example, you could use the same form in an intranet and on the Internet, and change only the skin to give a different appearance (or even select different subsets of the form for display). You can also create skins that process your form for devices, such as wireless mobile devices.

How ColdFusion processes XML skinnable forms

When ColdFusion processes a cfform tag that specifies XML format and an XSLT skin, it does the following to the form:

  1. Converts the CFML form tags into an XForms-compliant XML text format and makes it available in a variable with the same name as the form. ColdFusion ignores in-line text or HTML tags in the form, and does not pass them to the XML. (It does process HTML option tags that are children of a cfselect tag.)
  2. Applies an XSLT skin to the XML; for example, to convert the form into HTML. The XSLT file specifies the CSS style sheet.
  3. Returns the resulting, styled, form to the client, such as a user’s browser.

If you omit the cfform tag skin attribute, ColdFusion MX uses a default skin.

If you specify skin="none", ColdFusion MX performs the first step, but omits the remaining steps. Your application must handle the XML version of the form as needed. This technique lets you specify your own XSL engine, or incorporate the form as part of a larger form.

ColdFusion MX XSL skins

ColdFusion MX provides the following XSLT skins:

  • basic
  • basiccss
  • basiccss_top
  • beige
  • blue
  • bluegray
  • default
  • lightgray
  • red
  • silver

The XSLT skin files are located in the cf_webroot\CFIDE\scripts\xsl directory, and the CSS files that they use for style definitions are located in the cf_webroot\CFIDE\scripts\css directory.

The default skin and the basic skin format forms identically. ColdFusion uses the default skin if you do not specify a skin attribute in the cfform tag. The default and basic skins are simple skins that use tables for arranging the form contents. The basic skin uses div and span tags to arrange the elements. The skins with names of colors are similar to the basic skin, but make more use of color.

Example: a simple skinnable form

The following figure shows a simple XML skinnable form that uses the default skin to format the output:

A simple XML skinnable form that uses the default skin to format output

Later sections in this chapter use this form in their examples and description.


Building XML skinnable forms

You build ColdFusion XML skinnable forms using standard ColdFusion forms tags, including cfformgroup and cfformitem tags. These tags create the elements of the form, the building blocks of the form.

ColdFusion converts the following tags to XML for processing by the XSLT:

Standard ColdFusion form data control tags The cfgrid, cfinput, cfselect, cfslider, cftextarea, and tree tags specify the controls that the form displays.

cfformitem tags Add individual items to your form, such as text or rules. The valid types depend on the skin.

cfformgroup tags Group, organize, and structure the form contents. The valid types depend on the skin.

These tags are designed so you can develop forms in a hierarchical structure of containers and children. Using this model, the cfform tag is the master container, and its contents are children containers and controls. Each cfformgroup tag defines a container that organizes its child elements.

The specific tags and attributes that you use in your form depend on the capabilities of the XSLT skin. You use only the tag and attribute combinations that the skin supports. If you are using a skin provided by a third party, make sure that the supplier provides information on the supported attributes.

This section describes the following topics:

  • Using standard ColdFusion MX form tags
  • Using cfformitem tags
  • Using cfformgroup tags
  • Example: CFML for a skinnable XML form


Using standard ColdFusion MX form tags

You use standard ColdFusion MX form tags, such as cfinput or cftree, as you normally do in standard CFML forms to generate form input elements. ColdFusion MX maps most of these tags and their subtags (such as option tags in the cfselect tag) to equivalent XForms elements. ColdFusion maps applet and Macromedia Flash format cfgrid and cftree tags to ColdFusion XML extensions that contain Java applet or Flash objects. It converts XML format cfgrid and cftree tags to ColdFusion XML extension.

The specific attributes you can use and their meanings can depend on the skins.

Using ColdFusion MX skins The skins that are supplied with ColdFusion MX 7 support the attributes that you can use with HTML forms. You can also use label attributes to provide labels for the following tags:

  • cfinput with type attribute values of text, button, password, and file
  • cfselect
  • cfslider
  • cftextarea

Using other skins If you use any other skin, some attributes might not be supported, or the skin might support custom attributes. Get the information about the supported attributes from the XSLT skin developer.


Using cfformitem tags

ColdFusion MX does not process inline text or standard HTML tags when it generates an XML form; therefore, you use the cfformitem tag to add formatted HTML or plain text blocks and any other display elements, such as horizontal and vertical rules, to your form.

ColdFusion converts all cfformitem type attribute values to all-lowercase. For example, if you specify type="MyType" ColdFusion MX converts the type name to "mytype".

ColdFusion MX makes no other limitations on the cfformitem type attributes that you can use in a form, but the XSLT skin must process the attributes to display the items.

Using ColdFusion skins The skins provided in ColdFusion MX support the following cfformitem types:

  • hrule
  • text
  • html

The hrule type inserts an HTML hr tag, and the text type displays unformatted plain text.

The html type displays HTML-formatted text. You can include standard HTML text markup tags, such as strong, p, ul, or li, and their attributes. For example, the following text from the Example: a simple skinnable form section shows how you could use a cfformitem tag to insert descriptive text in a form:

<cfformitem type="html">
    <b>We value your input</b>.<br>
    <em>Please tell us a little about yourself and your thoughts.</em>
</cfformitem>

Using other skins If you use any other skin, the supported attributes and attribute values depend on the skin implementation. Get the information about the supported attributes and attribute values from the XSLT skin developer.


Using cfformgroup tags

The cfformgroup tag lets you structure forms by organizing its child tags, for example, to align them horizontally or vertically. Some skins might use cfformgroup tags for more complex formatting, such as tabbed navigator or accordion containers. ColdFusion MX makes no limitations on the type attributes that you can use in a form, but the XSLT must process the resulting XML to affect the display.

Using ColdFusion skins The skins provided in ColdFusion MX support the following type attribute values:

  • horizontal
  • vertical
  • fieldset

The horizontal and vertical types arrange their child tags in the specified direction and place a label to the left of the group of children. The following text from the Example: a simple skinnable form section shows how you could use a cfformgroup tag to apply a Name label and align first and last name fields horizontally:

<cfformgroup type="horizontal" label="Name">
    <cfinput type="text" name="firstname" label="First" required="yes">
    <cfinput type="text" name="lastname" label="Last" required="yes">
</cfformgroup>

The fieldset type corresponds to the HTML fieldset tag, and groups its children by drawing a box around them and replacing part of the top line with legend text. To specify the legend, use the label attribute. To specify the box dimensions, use the style attribute with height and width values.

The following code shows a simple form group with three text controls. The cfformgroup type="vertical" tag ensures that the contents of the form is consistently aligned. The cfformgroup type="horizontal" aligns the firstname and lastname fields horizontally.

<cfform name="comments" format="xml" skin="basiccss" width="400"
        preservedata="Yes" >
    <cfformgroup type="fieldset" label="Contact Information">
        <cfformgroup type="vertical">
            <cfformgroup type="horizontal" label="Name">
                <cfinput type="text" size="20" name="firstname" required="yes">
                <cfinput type="text" size="25" name="lastname" required="yes">
            </cfformgroup>
            <cfinput type="text" name="email" label="E-mail" validation="email">
        </cfformgroup>
     </cfformgroup>
</cfform>

Note: Because XML is case-sensitive, but ColdFusion is not, ColdFusion MX converts cfformgroup and cfformitem attributes to all-lowercase letters. For example, if you specify cfformgroup type="Random", ColdFusion converts the type to random in the XML.

Using other skins If you use any other skin, the supported attributes and attribute values depend on the skin implementation. Get the information about the supported attributes and attribute values from the skin developer.


Example: CFML for a skinnable XML form

The following CFML code creates the form shown in the figure in About XML skinnable forms. It shows how you can use CFML to structure your form.

<cfform name="comments" format="xml" skin="basiccss" width="400" preservedata="Yes" >
    <cfinput type="hidden" name="revision" value="12a">
    <cfformgroup type="fieldset" label="Basic Information">
        <cfformgroup type="vertical">
        <cfformgroup type="horizontal" label="Name">
            <cfinput type="text" size="20" name="firstname" required="yes">
            <cfinput type="text" size="25" name="lastname" required="yes">
        </cfformgroup>
        <cfinput type="text" name="email" label="E-mail" validate="email" maxlength="35">
        <cfselect name="satisfaction" style="width:120px" multiple="false" label="Satisfaction">
            <option selected>very satisfied</option>
            <option>somewhat satisfied</option>
            <option>somewhat dissatisfied</option>
            <option>very dissatisfied</option>
            <option>no opinion</option>
        </cfselect>
        </cfformgroup>
     </cfformgroup>
    <cfformitem name="html1" type="html">
    <p><b>We value your input</b>.<br>
    <em>Please tell us a little about yourself and your thoughts.</em></p>
    </cfformitem>
    <cftextarea name="thoughts" label="Additional Comments" rows="5" cols="66">We really want to hear from you!</cftextarea>
    <cfformgroup type="horizontal">
        <cfinput type="submit" name="submit" style="width:80" value="Tell Us">
        <cfinput type="reset" name="reset" style="width:80" value="Clear Fields">
    </cfformgroup>
</cfform>


ColdFusion XML format

This section describes the XML generated from a ColdFusion cfform tag and its children. It provides a building block toward creating your own XSL skins.

  • XML namespace use
  • XML structure
  • Data model
  • Control elements

XML namespace use

The XML that ColdFusion generates for forms uses elements and attributes in several XML namespaces. Namespaces are named collections of names that help ensure that XML names are unique. They often correspond to a web standard, a specific document type definition (DTD), or a schema. In XML, the namespace name and a colon (:) precede the name of the tag that is defined in that namespace; for example xf:model for the XForms namespace model tag.

ColdFusion uses several standard XML namespaces defined by the World Wid Web Consortium (W3C). These namespaces correspond to specifications for standard XML dialects such as XHTML, XForms and XML Events. ColdFusion XML forms also use a custom namespace for skinnable forms XML extensions. The following table lists the namespaces in the XML that ColdFusion generates.

Prefix | URL | Used for
html | http://www.w3.org/1999/xhtml | Form tag information, including action, height, width, and name. XHTML compliant.
xf | http://www.w3.org/2002/xforms | XForms model (including initial field values) and XForms elements that correspond to cfform tags.
ev | http://www.w3.org/2001/xml-events | System events. Used for the cfinput type="reset".
cf | http://www.macromedia.com/2004/cfform | All ColdFusion extensions, including passthrough of attributes that do not correspond to XForms elements or attributes.


XML structure

For each CFML tag, ColdFusion MX converts attributes and element values to XML in the XForms xf:model element, or in individual control elements, such as the XForms xf:input, xf:secret, or xf:group elements.

ColdFusion MX generates XForms XML in the following format. The numbers on each line indicate the level of nesting of the tags.

1	form tag
2		XForms model element
3			XForms instance element
4				cf:data element
3			XForms submission element
3			XForms bind element
3			XForms bind element
3		.
3		.
3		.
2		(end of model element)
2		XForms or ColdFusion extension control element
2		XForms or ColdFusion extension control element
            .
            .
            .
1	(end of form)

The following sections describe the data model and the elements that make up the XForms document.


Data model

The XForms data model specifies the data that the form submits. It includes information on each displayed control that can submit data, including initial values and validation information. It does not contain information about cfformgroup or cfformitem tags. The data model consists of the following elements and their children:

  • One xf:instance element
  • One xf:submission element
  • One xf:bind element for each form control that can submit data

xf:instance element

The XForms xf:instance element contains information about the form data controls. Any control that can submit data has a corresponding instance element. If the control has an initial value, the instance element contains that value.

The xf:instance element contains a single cf:data element that contains an element for each data control: cfgrid, most cfinput tag types, cfselect, cfslider, cftextarea, and cftree. Each element name is the corresponding CFML tag’s name attribute. For applet and Flash format cfgrid and cftree tags, the element name is the value of the cf_param_name parameter of the tree or grid’s Java applet object. Only cfinput tags of types submit, image, reset and button do not have instance data, because they cannot submit data.

Each element’s body contains the initial control data from the CFML tag’s value attribute or its equivalent. For example, for a cfselect tag, the xf:instance element body is a comma-delimited list that contains the name attributes of all the option tags with a selected attribute. For submit and image buttons, the body contains the name attribute value.

The following example shows the xf:instance element for the form shown in the figure in About XML skinnable forms:

<xf:instance>
    <cf:data>
            <firstname/>
            <lastname/>
            <email/>
            <revision>Comment Form revision 12a</revision>
            <satisfaction>very satisfied</satisfaction>
            <thoughts>We really want to hear from you!</thoughts>
    </cf:data>

xf:submission element

The xf:submission element specifies the action when the form is submitted, and contains the values of the cfform action and method attributes.:

The following example shows the XML for the form shown in the figure in About XML skinnable forms:

<xf:submission
action="/_MyStuff/phase1/forms/XForms/FrameExamples/Figure1.cfm" method="post"/>

xf:bind elements

The xf:bind elements provide information about the input control behavior, including the control type and any data validation rules. The XML has one bind element for each instance element that can submit data. It does not have bind elements for controls such as cfformitem tags, or cfinput tags with submit, input, reset, or image types. Each element has the following attributes:

Attribute | Description
id | CFML tag name attribute value
nodeset | XPath expression with the path in the XML to the instance element for the control
required | CFML tag required attribute value

Each xf:bind element has an xf:extension element with ColdFusion specific information, including type and validation values. The following table lists the cf namespace elements that are used in this section:

Element

Description

cf:attribute name="type"

Control type. One of the following:

CHECKBOX, FILE, IMAGE, PASSWORD, RADIO, SELECT, SUBMIT TEXT, CFSLIDER.

The TEXT type is used for cfinput type="text" and cftextinput.

cf:attribute name="onerror"

JavaScript function specified by the control’s onError attribute, if any.

cfargument name="maxlength

Value of the control’s maxlength attribute, if any.

cf:validate type="valiadationtype"

Data validation information.

Has one attribute, type, the validation type, and one or more cf:argument and cf:trigger children. ColdFusion MX generates a cf:validate element for each of the following:

  • cfinput or cftextarea validation attribute
  • cfinput or cftextarea range attribute
  • cfslider: the range and message attributes are specified by a cf:validate type="range" element

cf:argument

(in the body of a cf:validate element)

Data validation specification.

Has one attribute, name, and body text. Each cf:validate element can have multiple cf:argument children, corresponding to the validation-related CFML tag attribute values, such as maximum length, and maximum and minimum range values. The element body contains the CFML attribute value.

Valid name values are as follows. Unless specified otherwise, the name is identical to the corresponding CFML tag attribute name.

  • max
  • message
  • min
  • pattern

cf:trigger

(in the body of a cf:validate element)

When to do the validation; specifies a form element validateAt attribute value.

Has one attribute, event, which can be one of the following:

  • onBlur
  • onSubmit
  • onServer

If a validateAt attribute specifies multiple validation triggers, the XML has one cf:trigger element for each entry in the list.

The following example shows the xf:bind element of the form shown in the figure in About XML skinnable forms:

<xf:bind id="firstname"
        nodeset="//xf:model/xf:instance/cf:data/firstname"
        required="true()">
    <xf:extension>
        <cf:attribute name="type">TEXT</cf:attribute>
        <cf:attribute name="onerror">_CF_onError</cf:attribute>
    </xf:extension>
</xf:bind>
<xf:bind id="lastname"
        nodeset="//xf:model/xf:instance/cf:data/lastname"
        required="true()">
    <xf:extension>
        <cf:attribute name="type">TEXT</cf:attribute>
        <cf:attribute name="onerror">_CF_onError</cf:attribute>
    </xf:extension>
</xf:bind>
<xf:bind id="email"
        nodeset="//xf:model/xf:instance/cf:data/email" required="false()">
    <xf:extension>
        <cf:attribute name="type">TEXT</cf:attribute>
        <cf:attribute name="onerror">_CF_onError</cf:attribute>
    </xf:extension>
</xf:bind>
<xf:bind id="satisfaction"
        nodeset="//xf:model/xf:instance/cf:data/satisfaction"
        required="false()">
    <xf:extension>
        <cf:attribute name="type">SELECT</cf:attribute>
        <cf:attribute name="onerror">_CF_onError</cf:attribute>
    </xf:extension>
</xf:bind>
<xf:bind id="thoughts"
        nodeset="//xf:model/xf:instance/cf:data/thoughts" required="false()">
    <xf:extension>
        <cf:attribute name="type">TEXT</cf:attribute>
        <cf:attribute name="onerror">_CF_onError</cf:attribute>
    </xf:extension>
</xf:bind>


Control elements

The XML tags that follow the xf:bind element specify the form controls and their layout. The XML includes one element for each form control and cfformitem or cfformgroup tag.

CFML to XML tag mapping

ColdFusion MX maps CFML tags to XForms elements and ColdFusion extensions as the following table shows:

CFML tag | XML tag
cfinput type="text" | xf:input
cfinput type="password" | xf:secret
cfinput type="hidden" | None: instance data only
cfinput type="file" | xf:upload
cfinput type="radio" | xf:select1
cfinput type="checkbox" | xf:select
cfinput type="button" | xf:trigger
cfinput type="image" | xf:submit
cfinput type="reset" | xf:submit
cfinput type="submit" | xf:submit
cfselect multiple="false" | xf:select1
cfselect multiple="true" | xf:select
cftextarea | xf:textarea
cfslider | xf:range
cfgrid | cf:grid
cftree | cf:tree
cfformitem type="text" | xf:output
cfformitem type="html" | xf:output
cfformitem type="*" (all but text, html) | xf:group appearance="*"
cfformgroup type="*" | xf:group appearance="*"

ColdFusion converts cfformitem tags with text and html type attributes to XForms output elements with the tag body in a <![CDATA[ section. It converts all other cfformitem tags to XForms group elements, and sets each element’s appearance attribute to the cfformitem tag’s type attribute. The XSLT must process these elements to produce meaningful output. For example, the ColdFusion default skin transform displays the xf:output text blocks and processes the xf:group appearance="hrule" element, but it ignores all other xf:group elements.

General control element structure

Each control element that can be represented by a standard XForms control element has the following general structure. (For information on XML element structure for cfformitem, cfformgroup, cfgrid, and cftree tags, see the following sections.)

<xf:tagname bind="bindid" id="bindid">
    <xf:label>label</xf:label>
    <xf:extension>
        <cf:attribute name="type">controltype</cf:attribute>
        <cf:attribute name="attribname>attribvalue</cf:attribute>
        <cf:attribute name="attribname>attribvalue</cf:attribute>
        .
        .
        .
    </xf:extension>
</xf:tagname>

The following table describes the variable parts of this structure:

Part

Description

tagname

The xf or cf namespace element name, as identified in the table in CFML to XML tag mapping.

bindid

ID attribute of the model xf:bind element for this control. Specified by the control’s CFML tag name attribute.

label

Control label text. Specified by one of the following:

  • The CFML tag label attribute
  • The value attribute of the radiobutton, submit, and reset cfinput tags
  • The tag body content of cfselect option subtags,
  • Not used for cfgrid and cftree tags.

controltype

Type of control. One of the following:

  • The cfinput type attribute
  • Select, slider, or textarea, for the cfselect, cfslider, or cftextarea tags, respectively.
  • Not used for cfgrid and cftree tags.

attribname

Name of a CFML tag attribute. There is a cf:attribute tag for each attribute specified in the CFML code that does not otherwise have an entry in the XML.

attribvalue

Value of a CFML tag attribute.

Tag-specific element structure

The following sections describe tag-specific features of the XML for several types of input tags. It is not all-inclusive. For the specific structure of any ColdFusion form tag, see the XML generated from the tag by ColdFusion MX.

Selection tags

Tags that are used for selection, cfselect, cfinput type="radio", and cfinput type="checkbox" are converted to XForms select and select1 elements. These elements include an xf:choices element, which in turn has an xf:item element for each item a user can choose. Each item normally has an xf:label element and an xf:value element. Check boxes have a single item; select and radio button controls have more than one.

The following example shows the CFML code for a group of two radio buttons, followed by the generated XML control elements. This example also shows the use of a cfformgroup tag to arrange and label the radio button group.

CFML

<cfformgroup type="horizontal" label="Accept?">
    <cfinput type = "Radio" name = "YesNo" value = "Yes" checked>
    <cfinput type = "Radio" name = "YesNo" value = "No">
</cfformgroup>

XML

<xf:group appearance="horizontal">
    <xf:label>Accept?</xf:label>
    <xf:extension/>
    <xf:select1 appearance="full" bind="YesNo" id="YesNo">
        <xf:extension>
            <cf:attribute name="type">radio</cf:attribute>
        </xf:extension>
        <xf:choices>
            <xf:item>
                <xf:label>Yes</xf:label>
                <xf:value>Yes</xf:value>
                <xf:extension>
                    <cf:attribute name="checked">checked</cf:attribute>
                </xf:extension>
            </xf:item>
            <xf:item>
                <xf:label>No</xf:label>
                <xf:value>No</xf:value>
                <xf:extension/>
            </xf:item>
        </xf:choices>
    </xf:select1>
</xf:group>

cfgrid tags

ColdFusion MX represents a cfgrid tag using the cf:grid XML tag. This tag has four attributes: format, which can be Flash, Applet, or XML; and the id, name, and bind attributes, which all have the value of the cfgrid tag name attribute.

For applet and Flash format grids, ColdFusion inserts cfgrid controls in the XML as HTML embed objects in <![CDATA[ sections in the body of a cf:grid tag. The controls can be Java applets or in SWF file format.

For XML format grids, ColdFusion converts the CFML to XML in the following format:

cf:grid bind="gridname" name="gridname" format="xml" id="gridname>
    <metadata>
        <cfgridAttribute1>attributeValue</cfgridAttribute1>
        ...
        (There are an entry for attributes with a specified or default value.)
    </metadata>
    <columns>
        <column cfgridcolumnAttribute1="value" ... />
        ...
    </columns>
    <rows>
        <row>
            <column1Name>row1Column1Value</column1Name>
            <column2Name>row1Column2Value</column2Name>
            ...
        </row>
        <row>
            <column1Name>row2Column1Value</column1Name>
            <column2Name>row2Column2Value</column2Name>
        </row>
        ...
    </rows>
</cf:grid>

The following example shows a minimal grid with two nodes.

CFML

<cfgrid name="mygrid" Format="xml" selectmode="Edit" width="350	">
    <cfgridcolumn name="CorName" header="Course Name" >
    <cfgridcolumn name="Course_ID" header="ID">
    <cfgridrow data="one0,two0">
    <cfgridrow data="one1,two1">
</cfgrid>

XML

Most metadata lines are omitted for brevity:

<cf:grid bind="mygrid" format="XML" id="mygrid" name="mygrid">
    <metadata>
        <autowidth>false</autowidth>
        <insert>false</insert>
        <delete>false</delete>
        <sort>false</sort>
        <italic>false</italic>
        <bold>false</bold>
        <appendkey>true</appendkey>
        <highlughthref>true</highlughthref>
        <griddatalines>Left</griddatalines>
        <gridlines>true</gridlines>
        <rowheaders>true</rowheaders>
        <rowheaderalign>Left</rowheaderalign>
        <rowheaderitalic>false</rowheaderitalic>
        <rowheaderbold>false</rowheaderbold>
        <colheaders>true</colheaders>
        <colheaderalign>Left</colheaderalign>
        <colheaderitalic>false</colheaderitalic>
        <colheaderbold>false</colheaderbold>
        <selectmode>Edit</selectmode>
        <notsupported>&lt;b&gt; Browser must support Java to view ColdFusion Java
Applets&lt;/b&gt;</notsupported>
        <picturebar>false</picturebar>
        <insertbutton>insert</insertbutton>
        <deletebutton>delete</deletebutton>
        <sortAscendingButton>SortAsc</sortAscendingButton>
        <sortDescendingButton>SortDesc</sortDescendingButton>
    </metadata>
    <columns>
        <column bold="false" display="true" header="Course Name"
            headerBold="false" headerItalic="false" italic="false"
            name="CorName" select="true"/>
        <column bold="false" display="true" header="ID"
            headerBold="false" headerItalic="false" italic="false"
            name="Course_ID" select="true"/>
    </columns>
    <rows>
        <row>
            <CorName>one0</CorName>
            <Course_ID>two0</Course_ID>
        </row>
        <row>
            <CorName>one1</CorName>
            <Course_ID>two1</Course_ID>
        </row>
    </rows>
</cf:grid>

The cftree tags

For applet and Flash format trees, ColdFusion inserts cftree controls in the XML as HTML embed objects in <![CDATA[ sections in the tag body. The controls can be Java applets or in Flash SWF format. The cf:tree XML tag has two attributes: format, which can be Flash or Applet, and id.

For XML format trees, ColdFusion converts the CFML to XML in the following format:

cf:tree format="XML" id="treename>
    <metadata>
        <cftreeAttribute1>attributeValue</cftreeAttribute1>
        ...
    </metadata>
    <node cfml tree item attributes>
        <node //nested node with no children
            cfml tree item attributes />
        ...
    </node>
    ...
</cf:tree>

The following example shows a minimal tree with two nodes:

CFML

<cfform name="form2" Format="XML" >
<cftree name="tree1" hscroll="No" vscroll="No" format="xml"
    border="No">
    <cftreeitem value="Divisions">
    <cftreeitem value="Development"
        parent="Divisions" img="folder">
</cftree>
</cfform>

XML

The following code shows only the XML that is related to the tree appearance:

<cf:tree format="xml" id="tree1">
    <metadata>
        <fontWeight/>
        <align/>
        <lookAndFeel>windows</lookAndFeel>
        <delimiter>\</delimiter>
        <completePath>false</completePath>
        <border>false</border>
        <hScroll>false</hScroll>
        <vScroll>false</vScroll>
        <appendKey>true</appendKey>
        <highlightHref>true</highlightHref>
        <italic>false</italic>
        <bold>false</bold>
    </metadata>
    <node display="Divisions" expand="true" href="" img=""
        imgOpen="" parent="" path="Divisions" queryAsRoot="true"
                    value="Divisions">
        <node display="Development" expand="true" href=""
            img="folder" imgOpen="" parent="Divisions"
            path="Divisions\Development" queryAsRoot="true"
                        value="Development"/>
    </node>
</cf:tree>

The cfformgroup and cfformitem tags

All cfformgroup tags and all cfformitem tags, except type="html" and type="text", generate xf:group elements. The following rules determine the element structure:

  • The CFML tag type attribute determines the xf:group appearance attribute.
  • ColdFusion MX converts type attribute values to all-lowercase characters.
  • For cfformgroup tags only, the CFML label attribute determines the xf:group label attribute.
  • All other CFML attributes are put in cf:attribute elements in a xf:extension element.
  • The cfformitem tags generate an xf:output element with the body text in a <![CDATA[ section.

The following example shows two cformitem tags, and the resulting XML:

CFML

<cfformitem name="text1" type="text" style="color:green">
    Please tell us a little about yourself and your thoughts.
</cfformitem>
<cfformitem type="hrule" height="3" width="200" testattribute="testvalue" />

XML

<xf:output><![CDATA[Please tell us a little about yourself and your
thoughts.]]>
    <xf:extension>
        <cf:attribute name="style">color:green</cf:attribute>
    </xf:extension>
</xf:output>
<xf:group appearance="hrule">
    <xf:extension>
        <cf:attribute name="width">200</cf:attribute>
        <cf:attribute name="height">3</cf:attribute>
        <cf:attribute name="testattribute">testvalue</cf:attribute>
    </xf:extension>
</xf:group>

Example: control element XML

The following code shows the XML for the input controls for the form shown in the figure in About XML skinnable forms. This code immediately follows the end of the xf:model element.

<xf:group appearance="horizontal">
    <xf:label>name</xf:label>
    <xf:extension/>
    <xf:input bind="firstname" id="firstname">
        <xf:label>First</xf:label>
        <xf:extension>
            <cf:attribute name="type">text</cf:attribute>
            <cf:attribute name="size">20</cf:attribute>
        </xf:extension>
    </xf:input>
    <xf:input bind="lastname" id="lastname">
        <xf:label>Last</xf:label>
        <xf:extension>
            <cf:attribute name="type">text</cf:attribute>
            <cf:attribute name="size">25</cf:attribute>
        </xf:extension>
    </xf:input>
</xf:group>
<xf:input bind="email" id="email">
    <xf:label>Email</xf:label>
    <xf:extension>
        <cf:attribute name="type">text</cf:attribute>
        <cf:attribute name="validation">email</cf:attribute>
    </xf:extension>
</xf:input>
<xf:output><![CDATA[<b>We value your input</b>.<br>
    <em>Please tell us a little about yourself and your thoughts.</em>]]>
    <xf:extension/>
</xf:output>
<xf:group appearance="vertical">
    <xf:extension/>
    <xf:select1 appearance="minimal" bind="satisfaction" id="satisfaction">
        <xf:label>Satisfaction</xf:label>
        <xf:extension>
            <cf:attribute name="type">select</cf:attribute>
            <cf:attribute name="style">width:200</cf:attribute>
        </xf:extension>
        <xf:choices>
            <xf:item>
                <xf:label>very satisfied</xf:label>
                <xf:value>very satisfied</xf:value>
            </xf:item>
            <xf:item>
                <xf:label>somewhat satisfied</xf:label>
                <xf:value>somewhat satisfied</xf:value>
            </xf:item>
            <xf:item>
                <xf:label>somewhat dissatisfied</xf:label>
                <xf:value>somewhat dissatisfied</xf:value>
            </xf:item>
            <xf:item>
                <xf:label>very dissatisfied</xf:label>
                <xf:value>very dissatisfied</xf:value>
            </xf:item>
            <xf:item>
                <xf:label>no opinion</xf:label>
                <xf:value>no opinion</xf:value>
            </xf:item>
        </xf:choices>
    </xf:select1>
    <xf:textarea bind="thoughts" id="thoughts">
        <xf:label>Additional Comments</xf:label>
        <xf:extension>
            <cf:attribute name="type">textarea</cf:attribute>
            <cf:attribute name="rows">5</cf:attribute>
            <cf:attribute name="cols">40</cf:attribute>
        </xf:extension>
    </xf:textarea>
</xf:group>
<xf:group appearance="horizontal">
    <xf:extension/>
    <xf:submit id="submit" submission="comments">
        <xf:label>Tell Us</xf:label>
        <xf:extension>
            <cf:attribute name="type">submit</cf:attribute>
            <cf:attribute name="name">submit</cf:attribute>
        </xf:extension>
    </xf:submit>
    <xf:submit id="reset">
        <xf:label>Clear Fields</xf:label>
        <reset ev:event="DOMActivate"/>
        <xf:extension>
            <cf:attribute name="name">reset</cf:attribute>
        </xf:extension>
    </xf:submit>
</xf:group>


Creating XSLT skins

This section provides information to help you create your own XSLT skins to process the XML that ColdFusion MX generates. It assumes that you are familiar with XSLT and CSS programming, and does not provide general information on writing XSLT transformations or CSS styles. It does provide information about the following areas:

  • How ColdFusion passes form attribute values to the XML file
  • How extend XSLT skins that ColdFusion MX provides as templates
  • Basic techniques for extending the basic.xsl file to support additional cfformgroup and cfformitem tag type attributes
  • How to extend the ColdFusion CSS files to enhance form appearance.

XSLT skin file locations

If you specify an XSLT skin by name and omit the .xsl suffix, ColdFusion MX looks for the file in the cfform script source directory and its subdirectories. You can specify the script source directory in your cfform tag scriptsrc attribute, and you can set a default location on the Settings page in the ColdFusion MX Administrator. When you install ColdFusion MX, the default location is set to /CFIDE/scripts/ (relative to the web root).

You can also use a relative or absolute file path, or a URL, to specify the XSLT skin location. ColdFusion MX uses the CFML page’s directory as the root of relative paths. The following formats are valid:

Format

Location

<cfform format="xml" skin="basic">

Searches for XML/CSS in the default directory and its subdirectories.

<cfform format="xml" skin="c:\foo\bar\basic.xsl">

Uses the absolute path.

<cfform format="xml" skin="basic.xsl">

Searches in the current directory.

<cfform format="xml" skin="..\basic.xsl:">

Searches the parent of the current directory.

<cfform format="xml"
skin="http://anywhereOnTheWeb/basic.xsl">

Uses the specified URL.

Note: Hosting companies might move the default skin location folder out of CFIDE; this lets them secure the CFIDE while giving site developers access to the files that you need for cfform.

Attribute and value passthrough

ColdFusion passes form tag attributes or attribute values that it does not specifically process directly to the XML, as follows:

  • It converts cfformitem and cfformgroup type attributes to xf:group element appearance attributes.
  • It passes the name and value of tag attributes that it does not recognize or process in cf:attribute elements.

This passthrough feature lets you create custom versions of any of the following items for your XSLT to process:

  • The cfformitem types, such as rules, spacers, or other display elements
  • The cfgroup types, such as divided boxes or tabbed dialog boxes
  • The custom cfinput types, such as a custom year chooser element
  • ColdFusion tag attributes, such as those used to control validation

Extending ColdFusion XSLT skins

ColdFusion MX 7 provides basic XSLT transforms that you can use as templates and extend for making your own skin. Each skin has a base XSL file, which include several utility XSL files. Utility file names start with an underscore (_), and the files are shared by multiple base skins. The following tables describes the XSL files, which are located in the cf_webroot\CFIDE\scripts\xsl directory:

File | Description
default.xsl | The default transform that ColdFusion MX uses if you do not specify a skin attribute for an XML format form. Identical to the basic.xsl file.
basic.xsl | A basic form format that arranges form elements using a table.
basiccss.xsl | A basic form format that arranges form elements using HTML div and span tags.
colorname.xsl | A basic form format that arranges form elements using a table and applies a color scheme determined by the colorname to the form. Based on the basic.xsl file.
_cfformvalidation.xsl | Applies ColdFusion MX validation rules. Used by all skins.
_formelements.xsl | Transformation rules for form elements except for those defined using cfformgroup tags. Used by all skins
_group_type.xsl _group_type_table.xsl _group_type_css.xsl | Transformation rules for cfformgroup tags. The tag type attribute is part of the file name. Files with table in the name are used by basic.xsl and its derivatives. Files with css in the name are used by basiccss.xsl.

All skins support the same set of CFML tags and tag types, and do a relatively simple transformation from XML to HTML. For example, they do not support horizontal or vertical rules.

The ColdFusion MX skin XSL files have several features that you can use when designing and developing your own transformation. They do the following:

  • Provide an overall structure and initial templates for implementing custom transformations.
  • Show how you can handle the various elements in the ColdFusion-generated XML.
  • Use a structure of included files that can form a template for your XSLT code.
  • The base XSL files include a separate file, _cfformvalidation.xsl, with complete code for generating the hidden fields required for ColdFusion onServer validation and the JavaScript for performing ColdFusion onSubmit and onBlur validation. You can include this file without modification to do ColdFusion validation in your XSLT template, or you can change it to add other forms of validation or to change the validation rules.
  • The base XSL files include files, that implement several form groups, laying out the child tags and applying a label to the group. These files can serve as templates for implementing additional form group types or you can expand them to provide more sophisticated horizontal and vertical form groups.
  • You can add custom cfformgroup and cfformitem type attributes by including additional XSL files.

Extending basic.xsl cfformgroup and cfformitem support

The following procedure describes the steps for extending the basic.xsl file to support additional cfformgroup and cfformitem types. You can use similar procedures to extend other xsl files.

To add support for cfformgroup and cfformitem types to the basic.xsl:

  1. Create an XSL file.
  2. For each type attribute that you want to support, create an xsl:template element to do the formatting. The element’s match attribute must have the following format:
    match="xf:group[@appearance='type_attribute_name']"

    For example, to add a panel cfformgroup type, add an element with a start tag such as the following:

    <xsl:template match="xf:group[@appearance='panel']">
  3. Deploy your XSL file or files to the cf_webroot\CFIDE\scripts\xsl directory.
  4. Add an include statement to the basic.xsl file at the end of the Supported groups section; for example, if you create a my_group_panel.xsl file to handle a panel cfformgroup type, your basic.xsl file would include the following lines:
    <!-- include groups that will be supported for this skin-->
<xsl:include href="_group_vertical_table.xsl" />
<xsl:include href="_group_horizontal_table.xsl" />
<xsl:include href="_group_fieldset.xsl"/>
<xsl:include href="my_group_panel.xsl" />

Styling forms by extending the ColdFusion MX CSS files

Each ColdFusion MX skinnable form XSL file uses a corresponding CSS style sheet to specify the form style and layout characteristics. The following CSS files are located in the cf_webroot\CFIDE\scripts\css directory:

File | Description
basic_style.css default_style.css | Provides a plain style for ColdFusion XSL files that use table-based formatting. These files are identical and are used by the basic.xsl and default.xsl transforms. ColdFusion uses the default_style.css if you do not specify a skin in your cfform tag.
basic2_style.css | The basic_style with limited positioning changes for use with XSL files that have div-based formatting. Used by the basiccss.xsl transform.
css_layout.css | Style specifications for laying out forms that use div-based formatting. Used by the basiccss.xsl transform.
colorname_style.css | Used by the color-formatted ColdFusion MX skins. Defines the same classes as basic_style.css, with additional property specifications.

The ColdFusion XSL files and their corresponding CSS style sheets use classes extensively to format the form. The basic.xsl file, for example, has only one element style; all other styles are class-based. Although the CSS files contain specifications for all classes used in the XSL files, they do not always contain formatting information. The horizontal class definition in basic_style.css, which is used for horizontal form groups, for example, is empty.

You can enhance the style of XML skinnable forms without changing the XSL transform by enhancing the style sheets that ColdFusion MX provides.

Previous


Creating Charts and Graphs

This chapter explains how to use the cfchart tag to display charts and graphs. It describes ways that you can chart data and the tools you need to create effective charts.

Contents

About charts

Creating a basic chart

Charting data

Controlling chart appearance

Creating charts: examples

Administering charts

Writing a chart to a variable

Linking charts to URLs
Next


About charts

The ability to display data in a chart or graph can make data interpretation much easier. Rather than present a simple table of numeric data, you can display a bar, pie, line, or other applicable type of chart using colors, captions, and a two-dimensional or three-dimensional representation of your data.

The cfchart tag, along with the cfchartseries and cfchartdata tags, provide many different chart types. The attributes to these tags let you customize your chart appearance.

You can create 11 types of charts in Macromedia ColdFusion MX 7 in two and three dimensions. The following figure shows a sample of each type of chart.

Note: In two dimensions, bar and cylinder charts appear the same, as do cone and pyramid charts.

Two dimensional example of each type of ColdFusion chart


Creating a basic chart

You can create a chart in either of the following ways:

  • Using the cfchart, cfchartseries, and cfchartdata tags in a ColdFusion page.
  • Using the chart wizard that is included with the ColdFusion Report Builder. For more information, see Creating Reports for Printing

Creating a chart with ColdFusion tags

To create a chart with ColdFusion tags, you use the cfchart tag along with at least one cfchartseries tag. You can optionally include one or more cfchartdata tags within a cfchartseries tag. The following table describes these tags:

Tag | Description
cfchart | Specifies the container in which the chart appears. This container defines the height, width, background color, labels, fonts, and other characteristics of the chart. You must include at least one cfchartseries tag within the cfchart tag.
cfchartseries | Specifies a database query that supplies the data to the chart and one or more cfchartdata tags that specify individual data points. Specifies the chart type, colors for the chart, and other optional attributes.
cfchartdata | Optionally specifies an individual data point to the cfchartseries tag.

The following example shows an outline of the basic code that you use to create a chart:

<cfchart>
    <cfchartseries type="type">
            <cfchartdata item="something" value="number">
    </cfchartseries>
</chart>

The following example displays a simple pie chart that illustrates four values:

<cfchart>
    <cfchartseries type="pie">
        <cfchartdata item="New car sales" value="50000">
        <cfchartdata item="Used car sales" value="25000">
        <cfchartdata item="Leasing" value="30000">
        <cfchartdata item="Service" value="40000">
    </cfchartseries>
</cfchart>

The following figure shows the resulting chart:

Pie chart resulting from preceding code example

Creating a chart with the Report Builder wizard

The ColdFusion Report Builder includes a wizard that lets you create charts easily. The wizard lets you specify all of the chart characteristics that you can specify using the cfchart, cfchartseries, and cfchartdata tags. For information about using the Report Builder chart wizard, see Creating Reports for Printing.


Charting data

One of the most important considerations when you chart data is the way that you supply the data to the cfchart tag. You can supply data in the following ways:

  • Specify individual data points using cfchartdata tags.
  • Provide all the data in a single query using cfchartseries tags.
  • Combine data from a query with additional data points from cfchartdata tags.
  • Provide all the data in a report created with Report Builder. For more information, see Creating Reports for Printing.

Note: The cfchart tag charts numeric data only. As a result, you must convert any dates, times, or preformatted currency values, such as $3,000.53, to integers or real numbers.

This section describes the following topics:

  • Charting individual data points
  • Charting a query
  • Charting a query of queries
  • Combining a query and data points
  • Charting multiple data collections

Charting individual data points

When you chart individual data points, you specify each data point by inserting a cfchartdata tag in the cfchartseries tag body. For example, the following code creates a simple pie chart:

<cfchart>
    <cfchartseries type="pie">
        <cfchartdata item="New Vehicle Sales" value=500000>
        <cfchartdata item="Used Vehicle Sales" value=250000>
        <cfchartdata item="Leasing" value=300000>
        <cfchartdata item="Service" value=400000>
    </cfchartseries>
</cfchart>

This pie chart displays four types of revenue for a car dealership. Each cfchartdata tag specifies a department’s income and a description for the legend.

Note: If two data points have the same item name, ColdFusion creates a graph of the value for the last one specified within the cfchart tag.

The cfchartdata tag lets you specify the following information about a data point:

Attribute | Description
value | The data value to be charted. This attribute is required.
item | (Optional) The description for this data point. The item appears on the horizontal axis of bar and line charts, on the vertical axis of horizontalbar charts, and in the legend of pie charts.


Charting a query

Each bar, dot, line, or slice of a chart represents data from one row/column coordinate in your result set. A related group of data is called a chart series.

Because each bar, dot, line, or slice represents the intersection of two axes, you must craft the query result set such that the row and column values have meaning when displayed in a chart. This often requires that you aggregate data in the query. You typically aggregate data in a query using one of the following:

  • Specify a SQL aggregate function (SUM, AVG, MAX, and so on) using a GROUP BY clause in the SELECT statement.
  • Use a Query of Queries.
  • Retrieve data from a view, instead of a table.

When you chart a query, you specify the query name using the query attribute of the cfchartseries tag. For example, the code for a simple bar chart might be as follows:

<cfchart
        xAxisTitle="Department"
        yAxisTitle="Salary Average"
    >
    <cfchartseries
        type="bar"
        query="DataTable"
        valueColumn="AvgByDept"
        itemColumn="Dept_Name"
        />
</cfchart>

This example displays the values in the AvgByDept column of the DataTable query. It displays the Dept_Name column value as the item label by each bar.

The following table lists the attributes of the cfchartseries tag that you use when working with queries:

Attribute | Description
query | The query that contains the data. You must also specify the valueColumn and itemColumn.
valueColumn | The query column that contains the values to be charted.
itemColumn | The query column that contains the description for this data point. The item normally appears on the horizontal axis of bar and line charts, on the vertical axis of horizontalbar charts, and in the legend in pie charts.


Charting a query of queries

In addition to charting the results of a query, you can also chart the results of a queries of queries. For more information about using query of queries, see Using Query of Queries. Query of queries provides significant power in generating the data for the chart. For example, you can use aggregating functions such as SUM, AVG, and GROUP BY to create a query of queries with statistical data based on a raw database query. For more information, see Using Query of Queries.

You can also take advantage of the ability to dynamically reference and modify query data. For example, you can loop through the entries in a query column and reformat the data to show whole dollar values.

The example in the following procedure analyzes the salary data in the cfdocexamples database using a query of queries, and displays the data as a bar chart.

To chart a query of queries:

  1. Create a new ColdFusion page with the following content:
    <!-- Get the raw data from the database. -->
<cfquery name="GetSalaries" datasource="cfdocexamples">
    SELECT Departmt.Dept_Name,
        Employee.Salary
    FROM Departmt, Employee
    WHERE Departmt.Dept_ID = Employee.Dept_ID
</cfquery>

<!-- Generate a query with statistical data for each department. -->
<cfquery dbtype = "query" name = "DeptSalaries">
    SELECT
        Dept_Name,
        AVG(Salary) AS AvgByDept
    FROM GetSalaries
    GROUP BY Dept_Name
</cfquery>

<!--- Reformat the generated numbers to show only thousands. --->
<cfloop index="i" from="1" to="#DeptSalaries.RecordCount#">
    <cfset DeptSalaries.AvgByDept[i]=Round(DeptSalaries.AvgByDept[i]/1000)*1000>
</cfloop>

<html>
<head>
    <title>Employee Salary Analysis</title>
</head>

<body>
<h1>Employee Salary Analysis</h1>

<!--- Bar chart, from DeptSalaries Query of Queries. --->
<cfchart
        xAxisTitle="Department"
        yAxisTitle="Salary Average"
        font="Arial"
        gridlines=6
        showXGridlines="yes"
        showYGridlines="yes"
        showborder="yes"
        show3d="yes"
    >

    <cfchartseries
        type="bar"
        query="DeptSalaries"
        valueColumn="AvgByDept"
        itemColumn="Dept_Name"
        seriesColor="olive"
        paintStyle="plain"
    />
</cfchart>

<br>
</body>
</html>
  2. Save the page as chartdata.cfm in the myapps directory under the web root directory. For example, the directory path in Windows might be C:\Inetpub\wwwroot\myapps.
  3. Return to your browser and enter the following URL to view the chartdata.cfm page:

    http://localhost/myapps/chartdata.cfm

    The following figure appears:

    Three-dimentional bar chart showing the results of a query of queries

Note: If a query contains two rows with the same value for the itemColumn attribute, ColdFusion graphs the last row in the query for that value. For the preceding example, if the query contains two rows for the Sales department, ColdFusion graphs the value for the last row in the query for Sales.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfquery name="GetSalaries" datasource="cfdocexamples">
    SELECT Departmt.Dept_Name,
        Employee.Salary
    FROM Departmt, Employee
    WHERE Departmt.Dept_ID =
        Employee.Dept_ID
</cfquery>

Query the cfdocexamples database to get the Dept_Name and Salary for each employee. Because the Dept_Name is in the Departmt table and the Salary is in the Employee table, you need a table join in the WHERE clause. You can use the raw results of this query elsewhere on the page.

<cfquery dbtype = "query"
        name = "DeptSalaries">
    SELECT
        Dept_Name,
        AVG(Salary) AS AvgByDept
    FROM GetSalaries
    GROUP BY Dept_Name
</cfquery>

Generate a new query from the GetSalaries query. Use the AVG aggregating function to get statistical data on the employees. Use the GROUP BY statement to ensure that there is only one row for each department.

<cfloop index="i" from="1"
        to="#DeptSalaries.RecordCount#">
    <cfset DeptSalaries.AvgByDept[i]=
    Round(DeptSalaries.AvgByDept[i]
    /1000)*1000>
</cfloop>

Loop through all the rows in the DeptSalaries query and round the salary data to the nearest thousand. This loop uses the RecordCount query variable to get the number of rows, and directly changes the contents of the query object.

<cfchart
        xAxisTitle="Department"
        yAxisTitle="Salary Average"
        font="Arial"
        gridlines=6
        showXGridlines="yes"
        showYGridlines="yes"
        showborder="yes"
        show3d="yes" >
    <cfchartseries
        type="bar"
        query="DeptSalaries"
        valueColumn="AvgByDept"
        itemColumn="Dept_Name"
        seriesColor="olive"
        paintStyle="plain"/>
</cfchart>

Create a bar chart using the data from the AvgByDept column of the DeptSalaries query. Label the bars with the department names.

You can also rewrite this example to use the cfoutput and cfchartdata tags within the cfchartseries tag, instead of using the loop, to round the salary data, as the following code shows:

<cfchartseries
    type="bar"
    seriesColor="olive"
    paintStyle="plain">

    <cfoutput query="deptSalaries">
        <cfchartdata item="#dept_name#" value=#Round(AvgByDept/1000)*1000#>
    </cfoutput>

</cfchartseries>


Combining a query and data points

To chart data from both query and individual data values, you specify the query name and related attributes in the cfchartseries tag, and provide additional data points using the cfchartdata tag.

ColdFusion displays the chart data specified by a cfchartdata tag before the data from a query; for example, to the left on a bar chart. You can use the sortXAxis attribute of the cfchart tag to sort data alphabetically along the x-axis.

One use of combining queries and data points is to provide data that is missing from the database; for example, to provide the data for one department if the data for that department is missing. The example in the following procedure adds data for the Facilities and Documentation departments to the salary data obtained from the query shown in the previous section:

To chart a query and individual data points:

  1. Open the chartdata.cfm file in your editor.
  2. Edit the cfchart tag so that it appears as follows:
    <cfchart chartwidth="600">
    <cfchartseries
        type="bar"
        query="DeptSalaries"
        itemColumn ="Dept_Name"
        valueColumn="AvgByDept"
        >
        <cfchartdata item="Facilities" value="35000">
        <cfchartdata item="Documentation" value="45000">
    </cfchartseries>
</cfchart>
  3. Save the page as chartqueryanddata.cfm in the myapps directory under the web root directory. For example, the directory path in Windows might be C:\Inetpub\wwwroot\myapps.
  4. Return to your browser and enter the following URL to view the chartqueryanddata.cfm page:

    http://localhost/myapps/chartqueryanddata.cfm


Charting multiple data collections

Sometimes, you might have more than one series of data to display on a single chart, or you want to compare two sets of data on the same chart. In some cases, you might want to use different charting types on the same chart. For example, you might want to include a line chart on a bar chart.

To combine multiple data series into a single chart, insert multiple cfchartseries tags within a single cfchart tag. You control how the multiple data collections are charted using the seriesPlacement attribute of the cfchart tag. Using this attribute, you can specify the following options:

default Let ColdFusion determine the best method for combining the data.

cluster Place corresponding chart elements from each series next to each other.

stacked Combine the corresponding elements of each series.

percent Show the elements of each series as a percentage of the total of all corresponding elements.

The following figure shows these options for combining two bar charts:

The three options for combining two bar charts in a single chart

You can also combine chart types. The following is a combination bar and line chart:

Example cobining a bar chart and a line chart in a single chart

The only chart type that you cannot mix with others is the pie chart. If you define one of the data series to use a pie chart, no other chart will appear.

The example in the following procedure creates the chart in the previous figure, which shows a bar chart with a line chart added to it. In this example, you chart the salary of permanent employees (bar) against contract employees (line).

Note: The layering of multiple series depends on the order that you specify the cfchartseries tags. For example, if you specify a bar chart first and a line chart second, the bar chart appears in front of the line chart in the final chart.

To create a combination bar chart and line chart:

  1. Open the chartdata.cfm file in your editor.
  2. Edit the cfchart tag so that it appears as follows:
    <cfchart
        backgroundColor="white"
        xAxisTitle="Department"
        yAxisTitle="Salary Average"
        font="Arial"
        gridlines=6
        showXGridlines="yes"
        showYGridlines="yes"
        showborder="yes"
    >
    <cfchartseries
        type="line"
        seriesColor="blue"
        paintStyle="plain"
        seriesLabel="Contract Salaries"
        >
            <cfchartdata item="HR" value=70000>
            <cfchartdata item="Marketing" value=95000>
            <cfchartdata item="Sales" value=80000>
            <cfchartdata item="Training" value=93000>
        </cfchartseries>
    <cfchartseries
        type="bar"
        query="DeptSalaries"
        valueColumn="AvgByDept"
        itemColumn="Dept_Name"
        seriesColor="gray"
        paintStyle="plain"
        seriesLabel="Dept. Average Salaries"
        />

</cfchart>
  3. Save the file as chart2queries.cfm in the myapps directory under the web root directory.
  4. Return to your browser and view the chart2queries.cfm page.


Controlling chart appearance

You can control the appearance of charts by doing any of the following:

  • Using the default chart styles included with ColdFusion
  • Using the attributes of the cfchart and cfchartseries tags
  • Creating your own chart styles

Using the default chart styles included with ColdFusion

ColdFusion supplies a number of chart styles. These styles include:

  • beige
  • blue
  • default
  • red
  • silver
  • yellow

To use any of these styles, specify the style using the style attribute of the cfchart tag. The following example illustrates using the beige style:

<cfchart style="beige">
    <cfchartseries type="pie">
        <cfchartdata item="New car sales" value="50000">
        <cfchartdata item="Used car sales" value="25000">
        <cfchartdata item="Leasing" value="30000">
        <cfchartdata item="Service" value="40000">
    </cfchartseries>
</cfchart>


Using the attributes of the cfchart and cfchartseries tags

You can specify the appearance of charts by using the attributes of the cfchart and cfchartseries tags.

You can optionally specify the following characteristics to the cfchart tag on the types of charts indicated:

Chart characteristic

Attributes used

Description

Chart
type

File type

format

Whether to send the chart to the user as a JPEG, PNG, or SWF file. The SWF file is the default format.

All

Size

chartWidth
chartHeight

The width and height, in pixels, of the chart. This size defines the entire chart area, including the legend and background area around the chart.

The default height is 240 pixels; the default width is 320 pixels.

All

Color

foregroundColor
dataBackgroundColor
backgroundColor

The colors used for foreground and background objects.

The default foreground color is black; the default background colors are white.

You can specify 16 color names, use any valid HTML color format, or specify an 8-digit hexadecimal value to specify the RGB value and transparency. If you use numeric format, you must use double number signs; for example, blue or ##FF33CC. To specify the color and transparency, use the format ##xxFF33CC, where xx indicates the transparency. Opaque is indicated by the value FF; transparent is indicated by the value 00. For the complete list of colors, see Configuring and Administering ColdFusion MX.

All

Labels

font
fontSize
fontBold
frontItalic
labelFormat
xAxisTitle
yAxisTitle

The font attribute specifies the font for all text. The default value is Arial. If you are using a double-byte character set on UNIX, or using a double-byte character set in Windows with a file type of Flash, you must specify ArialUnicodeMs as the font.

Note: If a chart attempts to use a font that is not installed on the ColdFusion server, it uses a different font that is available. Also, if you do not specify the font, characters that are not ASCII, such as Japanese, Chinese, Korean and so on, may not display properly.

The fontSize specifies an Integer font size used for all text. The default value is 11.

The fontBold attribute specifies to display all text as bold. The default value is no.

The fontItalic attribute specifies to display all text as italic. The default value is no.

The labelFormat attribute specifies the format of the y-axis labels, number, currency, percent, or date. The default value is number.

The xAxisTitle and yAxisTitle attributes specify the title for each axis.

All

Border

showBorder

Use the showBorder attribute to draw a border around the chart. The border color is specified by the foregroundColor attribute. The default value is no.

All

Grid lines

showXGridlines
showYGridlines
gridLines

Use the showXGridlines and showYGridlines attributes to display
x-axis and y-axis grid lines. The default value No for x-axis gridlines, and Yes for y-axis gridlines.

The gridLines attribute specifies the total number of grid lines on the value axis, including the axis itself. The value of each grid line appears along the value axis. The cfchart tag displays horizontal grid lines only. A value of 0 (the default) means no grid lines.

Area
Bar
Cone
Curve
Cylinder
Horizontalbar
Line
Pyramid
Scatter
Step

Slice style

pieSliceStyle

Displays the pie chart as solid or sliced. The default value is sliced.

Pie

Markers

showMarkers
markerSize

The showMarkers attribute displays markers at the data points for two dimensional line, curve, and scatter charts. The default value is yes.

The markerSize attribute specifies an integer number of pixels for the marker size. ColdFusion determines the default value.

All

Value axis

scaleFrom
scaleTo

The minimum and maximum points on the data axis.

By default, the minimum is 0 or the lowest negative chart data value, and the maximum is the largest data value.

Note: If you specify a scaleFrom or scaleTo attribute that would result in cropping the chart, cfchart uses a value that shows the entire chart without cropping.

Area
Bar
Cone
Curve
Cylinder
Horizontalbar
Line
Pyramid
Scatter
Step

Axis type

XAxisType
sortXAxis

Whether the x-axis corresponds to a numeric scale or identifies different categories, and how to sort the items on the axis.

If the XAxisType attribute value is scale, the x-axis is numeric. All cfchartdata item attribute values must be numeric, and the axis is automatically sorted numerically. The scale value lets you create graphs of numeric relationships, such as population against age.

If the attribute value is category (the default), the axis indicates the data category.

The sortXAxis attribute determines the order of items when you specify the cfchartdata item attribute, whose values are treated as text. By default, the items are displayed in the order in which they are entered in the first chart series.

Area
Bar
Cone
Curve
Cylinder
Horizontalbar
Line
Pyramid
Scatter
Step

3D appearance

show3D
xOffset
yOffset

The show3D attribute displays the chart in three dimensions. The default value is No.

The xOffset and yOffset attributes specify the amount to which the chart should be rotated on a horizontal axis (xOffset) or vertical axis (yOffset). The value 0 is flat (no rotation), -1 and 1 are for a full 90 degree rotation left
(-1) or right (1). The default value is 1.

All

Multiple series

showLegend
seriesPlacement

The showLegend attribute lets you display the chart’s legend when the chart contains more than one series of data. The default value is Yes.

The seriesPlacement attribute specifies the location of each series relative to the others. By default, ColdFusion determines the best placement based on the graph type of each series.

All

Tips

tipStyle
tipBGColor

The tipStyle attribute lets you display a small pop-up window that shows information about the chart element pointed to by the mouse pointer. Options are none, mousedown, or mouseover. The default value is mouseover.

The tipBGColor attribute specifies the background color of the tip window for Flash format only. The default value is white.

All

You can also use the cfchartseries tag to specify attributes of chart appearance. The following table describes these attributes:

Chart
characteristic

Attributes used

Description

Chart
type

Multiple series

seriesLabel
seriesColor

The seriesLabel attribute specifies the text that displays for the series label.

The seriesColor attribute specifies a single color of the bar, line, pyramid, and so on. For pie charts, this is the first slice’s color. Subsequent slices are automatically colored based on the specified initial color, or use the colorList attribute.

All

Paint

paintStyle

Specifies the way color is applied to a data series. You can specify solid color, buttonized look, linear gradient fill with a light center and darker outer edge, and gradient fill on lighter version of color. The default value is solid.

All

Data point colors

colorList

A comma-separated list of colors to use for each data point for bar, pyramid, area, horizontalbar, cone, cylinder, step, and pie charts.

You can specify 16 color names, use any valid HTML color format, or specify an 8-digit hexadecimal value to specify the RGB value and transparency. If you use numeric format, you must use double number signs; for example, blue or ##FF33CC. To specify the color and transparency, use the format ##xxFF33CC, where xx indicates the transparency. Opaque is indicated by the value FF; transparent is indicated by the value 00. For the complete list of colors, see Configuring and Administering ColdFusion MX.

If you specify fewer colors than data points, the colors repeat. If you specify more colors than data points, the extra colors are not used.

Pie

Data markers

markerStyle

Specifies the shape used to mark the data point. Shapes include circle, diamond, letterx, mcross, rcross, rectangle, snow, and triangle. Supported for two-dimensional charts. The default value is rectangle.

Curve
Line
Scatter

Labels

dataLabelStyle

Specifies the way in which the color is applied to the item in the series Styles include None, Value, Rowlabel, Columnlabel, and Pattern.

All


Creating your own chart styles

You can create your own chart styles by doing either of the following:

  • Modifying the chart style XML files
  • Using WebCharts3D to create chart styles

Modifying the chart style XML files

You can modify the chart styles included with ColdFusion to create your own chart styles. The files that contain the style information are XML files located in the cf_root\charting\styles directory. You should only modify attributes specified in the file. To specify additional attributes, follow the instructions in the section Using WebCharts3D to create chart styles.

Note: There are two XML files for each default chart style. For example, the beige style for pie charts is defined in the beige_pie.xml file; the beige style for all other types of charts is defined in the beige.xml file.

To modify a chart style XML file:

  1. Open the XML file that you want to modify, for example beige.xml.
  2. Modify the file contents.
  3. Save the file with a different name; for example myBeige.xml.

Using WebCharts3D to create chart styles

ColdFusion MX 7 includes the WebCharts3D utility, which you can use to create chart style files.

To create your own chart style file with the WebCharts3D utility:

  1. Start WebCharts3D by double-clicking the webcharts.bat file in the CFusionMX7\charting directory.
  2. (Optional) Open an existing chart.
  3. Make the changes you want to the chart’s appearance.

    Note: To use the chart style file in the cfchart tag, you can only make the modifications indicated in the table that follows this procedure.

  4. Click the XML style tab.
  5. Click the Save button in the bottom right corner.
  6. Specify the name of the file; for example, mystyle.xml.
  7. Specify the directory in which you want to save the chart style file.

    Note: ColdFusion uses the same rules to look for the chart style XML files as it does for files included using the cfinclude tag. For more information, see cfinclude.

  8. Click Save.

The following table lists the attributes of the cfchart and cfchartseries tags and the associated WebCharts3D commands:

Attribute | WebCharts3D command
chartHeight | Drag the chart by handles.
chartWidth | Drag the chart by handles.
dataBackgroundColor | Background: minColor (type must be PlainColor)
font | font: Family (specify only supported fonts.)
fontBold | font: check Bold
fontItalic | font: check Italic
fontSize | font: Size
foregroundColor | foreground
gridlines | XAxis: labelcount
labelFormat | YAxis: LabelFormat: Number | Percent| Currency | Datetime
markerSize | Elements: markerSize
pieSliceStyle | style: solid | slice
rotated | Type Frame chart: Elements: Shape:
scaleFrom | Yaxis: isAbsolute; scaleMin(int)
scaleTo | Yaxis: isAbsolute; scaleMax(int)
seriesPlacement | Elements: place
show3D | is3D
showBorder | Decoration: style (none or simple)?
showLegend | Legend: isVisible
showMarkers | Elements: showMarkers
showXGridlines | Frame: isVGridVisible
showYGridlines | Frame: isHGridVisible
tipbgColor | Popup: background
tipStyle | Popup: showOn: MouseOver | MouseDown | Disabled
url | Elements: action | Series: action
xAxisTitle | Xaxis: TitleStyle: text (enter text)
xAxisType | xAxis: type: (category or scale)
xOffset | Frame: xDepth
yAxisTitle | Yaxis: TitleStyle: text (enter text)
yAxisType | Currently has no effect.
yOffset | Frame: yDepth

The following table lists the attributes of the cfchartseries tag and the associated WebCharts3D commands:

Attribute | WebCharts3D command
colorlist | Elements: series: Paint: color
markerStyle | Elements: series: Marker type: Rectangle | Triangle | Diamond | Circle | Letter | MCROSS | Snow | RCROSS
paintStyle | Paint: paint: Plain | Shade | Light
seriesColor | Elements: series: Paint: color
seriesLabel | Elements: series:
type | Type: Pie chart | Type Frame chart: Elements: Shape: Bar | Line | Pyramid | Area | Curve | Step | Scatter | Cone | Cylinder | Horizontalbar |


Creating charts: examples

This section contains examples of different types of charts.

  • Creating a bar chart
  • Creating an area chart
  • Setting curve chart characteristics

Creating a bar chart

The example in the following procedure adds a title to the bar chart, specifies that the chart is three dimensional, adds grid lines, sets the minimum and maximum y-axis values, and uses a custom set of colors.

To enhance the bar chart:

  1. Open the chartdata.cfm file in your editor.
  2. Edit the cfchart tag so that it appears as follows:
    <!--- Bar chart, from Query of Queries --->
<cfchart
        scaleFrom=40000
        scaleTo=100000
        font="arial"
        fontSize=16
        gridLines=4
        show3D="yes"
        foregroundcolor="##000066"
        databackgroundcolor="##FFFFCC"
        chartwidth="450"
    >

    <cfchartseries
        type="bar"
        query="DeptSalaries"
        valueColumn="AvgByDept"
        itemColumn="Dept_Name"
        seriescolor="##33CC99"
        paintstyle="shade"
        />

</cfchart>
  3. Save the file as chartdatastyle1.cfm.
  4. View the chartdatastyle1.cfm page in your browser.

Reviewing the code

The following table describes the code in the preceding example.

Code

Description

scaleFrom=40000

Set the minimum value of the vertical axis to 40000.

scaleTo=100000

Set the maximum value of the vertical axis to 100000. The minimum value is the default, 0.

font="arial"

Displays text using the Arial font.

fontSize=16

Makes the point size of the labels 16 points.

gridLines = 4

Displays four grid lines between the top and bottom of the chart.

show3D = "yes"

Shows the chart in 3D.

foregroundcolor="##000066"

Sets the color of the text, gridlines, and labels.

databackgroundcolor="##FFFFCC"

Sets the color of the background behind the bars.

seriescolor="##33CC99"

Sets the color of the bars.

paintstyle="shade"

Sets the paint display style.

Creating a pie chart

The example in the following procedure adds a pie chart to the page.

To create a pie chart:

  1. Open the chartdata.cfm file in your editor.
  2. Edit the DeptSalaries query and the cfloop code so that it appears as follows:
    <!--- A query to get statistical data for each department. --->
<cfquery dbtype = "query" name = "DeptSalaries">
    SELECT
        Dept_Name,
        SUM(Salary) AS SumByDept,
        AVG(Salary) AS AvgByDept
    FROM GetSalaries
    GROUP BY Dept_Name
</cfquery>

<!--- Reformat the generated numbers to show only thousands. --->
<cfloop index="i" from="1" to="#DeptSalaries.RecordCount#">
    <cfset DeptSalaries.SumByDept[i]=Round(DeptSalaries.SumByDept[i]/
    1000)*1000>
    <cfset DeptSalaries.AvgByDept[i]=Round(DeptSalaries.AvgByDept[i]/
    1000)*1000>
</cfloop>
  3. Add the following cfchart tag:
    <!--- Pie chart, from DeptSalaries Query of Queries. --->
<cfchart
        tipStyle="mousedown"
        font="Times"
        fontsize=14
        fontBold="yes"
        backgroundColor = "##CCFFFF"
        show3D="yes"
        >

    <cfchartseries
        type="pie"
        query="DeptSalaries"
        valueColumn="SumByDept"
        itemColumn="Dept_Name"
        colorlist="##6666FF,##66FF66,##FF6666,##66CCCC"
        />
</cfchart>
<br>
  4. Save the file as chartdatapie1.cfm.
  5. View the chartdatapie1.cfm page in your browser:

Reviewing the code

The following table describes the code and its function:

Code

Description

SUM(Salary) AS SumByDept,

In the DeptSalaries query, add a SUM aggregation function to get the sum of all salaries per department.

<cfset DeptSalaries.SumByDept[i]=
    Round(DeptSalaries.SumByDept[i]/
    1000)*1000>

In the cfloop tag, round the salary sums to the nearest thousand.

<cfchart
    tipStyle="mousedown"
    font="Times"
    fontBold="yes"
    backgroundColor = "##CCFFFF"
    show3D="yes"
    >

Show a tip only when a user clicks on the chart, display text in Times bold font, set the background color to light blue, and display the chart in three dimensions.

<cfchartseries
    type="pie"
    query="DeptSalaries"
    valueColumn="SumByDept"
    itemColumn="Dept_Name"
    colorlist=
        "##6666FF,##66FF66,##FF6666,##66CCCC"
/>

Create a pie chart using the SumByDept salary sum values from the DeptSalaries query.

Use the contents of the Dept_Name column for the item labels displayed in the chart legend.

Get the pie slice colors from a custom list, which uses hexadecimal color numbers. The double number signs prevent ColdFusion from trying to interpret the color data as variable names.


Creating an area chart

The example in the following procedure adds an area chart to the salaries analysis page. The chart shows the average salary by start date to the salaries analysis page. It shows the use of a second query of queries to generate a new analysis of the raw data from the GetSalaries query. It also shows the use of additional cfchart attributes.

To create an area chart:

  1. Open the chartdata.cfm file in your editor.
  2. Edit the GetSalaries query so that it appears as follows:
    <!-- Get the raw data from the database. -->
<cfquery name="GetSalaries" datasource="cfdocexamples">
    SELECT Departmt.Dept_Name,
        Employee.StartDate,
        Employee.Salary
    FROM Departmt, Employee
    WHERE Departmt.Dept_ID = Employee.Dept_ID
</cfquery>
  3. Add the following code before the html tag:
    <!--- Convert start date to start year. --->
<!--- You must convert the date to a number for the query to work --->
<cfloop index="i" from="1" to="#GetSalaries.RecordCount#">
<cfset GetSalaries.StartDate[i]=NumberFormat(DatePart("yyyy", GetSalaries.StartDate[i]) ,9999)>
</cfloop>

<!--- Query of Queries for average salary by start year. --->
<cfquery dbtype = "query" name = "HireSalaries">
    SELECT
        StartDate,
        AVG(Salary) AS AvgByStart
    FROM GetSalaries
    GROUP BY StartDate
</cfquery>

<!--- Round average salaries to thousands. --->
<cfloop index="i" from="1" to="#HireSalaries.RecordCount#">
    <cfset HireSalaries.AvgByStart[i]=Round(HireSalaries.AvgByStart[i]/1000)*1000>
</cfloop>
  4. Add the following cfchart tag before the end of the body tag block:
    <!--- Area-style Line chart, from HireSalaries Query of Queries. --->
<cfchart
        chartWidth=400
        BackgroundColor="##FFFF00"
        show3D="yes"
    >
    <cfchartseries
        type="area"
        query="HireSalaries"
        valueColumn="AvgByStart"
        itemColumn="StartDate"
     />
</cfchart>
<br>
  5. Save the page.
  6. View the chartdata.cfm page in your browser.

Reviewing the code

The following table describes the code and its function:

Code

Description

Employee.StartDate,

Add the employee start date to the data in the GetSalaries query.

<cfloop index="i" from="1"
    to="#GetSalaries.RecordCount#">
  <cfset GetSalaries.StartDate[i]=
  NumberFormat(DatePart("yyyy",
  GetSalaries.StartDate[i]) ,9999)>
</cfloop>

Use a cfloop tag to extract the year of hire from each employee’s hire data, and convert the result to a four-digit number.

<cfquery dbtype = "query" name =
"HireSalaries">
  SELECT
        StartDate,
    AVG(Salary) AS AvgByStart
  FROM GetSalaries
  GROUP BY StartDate
</cfquery>

Create a second query from the GetSalaries query. This query contains the average salary for each start year.

<cfloop index="i" from="1"
   to="#HireSalaries.RecordCount#">
  <cfset HireSalaries.AvgByStart[i]
  =Round(HireSalaries.AvgByStart[i]
  /1000)*1000>
</cfloop>

Round the salaries to the nearest thousand.

<cfchart
        chartWidth=400
        BackgroundColor="##FFFF00"
        show3D="yes" >
    <cfchartseries
        type="area"
        query="HireSalaries"
        valueColumn="AvgByStart"
        itemColumn="StartDate"
     />
</cfchart>

Create a line chart using the HireSalaries query. Chart the average salaries against the start date.

Limit the chart width to 400 pixels, show the chart in three dimensions, and set the background color to white.


Setting curve chart characteristics

Curves charts use the attributes already discussed. However, you should be aware that curve charts require a large amount of processing to render. For fastest performance, create them offline, write them to a file or variable, and then reference them in your application pages. For information on creating offline charts, see Writing a chart to a variable.


Administering charts

Use the ColdFusion MX Administrator to administer charts. In the Administrator, you can choose to save cached charts in memory or to disk. You can also specify the number of charts to cache, the number of charting threads, and the disk file for caching images to disk.

ColdFusion MX 7 caches charts as they are created. In that way, repeated requests of the same chart load the chart from the cache rather than having ColdFusion render the chart over and over again.

Note: You do not have to perform any special coding to reference a cached chart. Whenever you use the cfchart tag, ColdFusion MX inspects the cache to see if the chart has already been rendered. If so, ColdFusion MX loads the chart from the cache.

The following table describes the settings for the ColdFusion MX 7 charting and graphing engine:

Option | Description
Cache Type | Sets the cache type. Charts can be cached in memory or to disk. Caching in memory is faster, but more memory intensive.
Maximum number of images in cache | Specifies the maximum number of charts to store in the cache. When the limit is reached, the oldest chart in the cache is deleted to make room for a new one. The maximum number of charts you can store in the cache is 250.
Max number of charting threads | Specifies the maximum number of chart requests that can be processed concurrently. The minimum number is 1 and the maximum is 5. Higher numbers are more memory-intensive.
Disk cache location | When caching to disk, specifies the directory in which to store the generated charts.


Writing a chart to a variable

In some cases, your application might have charts that are static or charts that, because of the nature of the data input, take a long time to render. In this scenario, you can create a chart and write it to a variable.

Once written to a variable, other ColdFusion pages can access the variable to display the chart, or you can write the variable to disk to save the chart to a file. This lets you create or update charts only as needed, rather than every time someone requests a page that contains a chart.

You use the name attribute of the cfchart tag to write a chart to a variable. If you specify the name attribute, the chart is not rendered in the browser but is written to the variable.

You can save the chart as a Flash SWF file, or as a JPEG or PNG image file. If you save the image as a SWF file, you can pass the variable back to a Flash client using ColdFusion Flash Remoting. For more information, see Using the Flash Remoting Service.

Note: If you write the chart to a JPEG or PNG file, mouseover tips and URLs embedded in the chart for data drill-down do not work when you redisplay the image from the file. However, if you save the image as a SWF file, both tips and drill-down URLs work. For more information on data drill-down, see Linking charts to URLs.

To write a chart to a variable and a file:

  1. Create a new ColdFusion page with the following content:
    <cfchart 	name="myChart" 	format="jpg"	>
    <cfchartseries type="pie">
        <cfchartdata item="New Vehicle Sales" value=500000>
        <cfchartdata item="Used Vehicle Sales" value=250000>
        <cfchartdata item="Leasing" value=300000>
        <cfchartdata item="Service" value=400000>
    </cfchartseries>
</cfchart>

<cffile
    action="WRITE"
    file="c:\inetpub\wwwroot\charts\vehicle.jpg"
    output="#myChart#">
<img src="/charts/vehicle.jpg" height=240 width=320>
  2. Save the page as chartToFile.cfm in myapps under the web root directory.
  3. View the chartToFile.cfm page in your browser.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

<cfchart
    name="myChart"
    format="jpg">

Define a chart written to the myChart variable using the JPEG format.

<cffile
    action="WRITE"
    file=
        "c:\inetpub\wwwroot\charts\vehicle.jpg"
    output="#myChart#">

Use the cffile tag to write the chart to a file.

<img
    src="/chartsvehicle.jpg"
    height=240
    width=320>

Use the HTML img tag to display the chart.


Linking charts to URLs

ColdFusion provides a data drill-down capability with charts. This means that you can click the data and the legend areas of a chart to request a URL. For example, if you have a pie chart and want a user to be able to select a pie wedge for more information, you can build that functionality into your chart.

You use the url attribute of the cfchart tag to specify the URL to open when a user clicks anywhere on the chart. For example, the following code defines a chart that opens the page moreinfo.cfm when a user clicks on the chart:

<cfchart
    xAxisTitle="Department"
    yAxisTitle="Salary Average"
    url="moreinfo.cfm"
    >

        <cfchartseries
            seriesLabel="Department Salaries"
        ...
        />

</cfchart>

You can use the following variables in the url attribute to pass additional information to the target page:

  • $VALUE$ The value of the selected item, or an empty string
  • $ITEMLABEL$ The label of the selected item, or an empty string
  • $SERIESLABEL$ The label of the selected series, or an empty string

For example, to let users click on the graph to open the page moreinfo.cfm, and pass all three values to the page, you use the following url:

url="moreinfo.cfm?Series=$SERIESLABEL$&Item=$ITEMLABEL$&Value=$VALUE$"

The variables are not enclosed in number signs like ordinary ColdFusion variables. They are enclosed in dollar signs. If you click on a chart that uses this url attribute value, it could generate a URL in the following form:

http://localhost:8500/tests/charts/moreinfo.cfm?
Series=Department%20Salaries&Item=Training&Value=86000

You can also use JavaScript in the URL to execute client-side scripts. For an example, see Linking to JavaScript from a pie chart.

This section describes the following topics:

  • Dynamically linking from a pie chart
  • Linking to JavaScript from a pie chart


Dynamically linking from a pie chart

In the following example, when you click a pie wedge, ColdFusion displays a table that contains the detailed salary information for the department represented by the wedge. The example is divided into two parts: creating the detail page and making the pie chart dynamic.

Part 1: creating the detail page

This page displays salary information for the department you selected when you click on a wedge of the pie chart. The department name is passed to this page using the $ITEMLABEL$ variable.

To create the detail page:

  1. Create a new application page with the following content:
    <cfquery name="GetSalaryDetails" datasource="cfdocexamples">
    SELECT Departmt.Dept_Name,
        Employee.FirstName,
        Employee.LastName,
        Employee.StartDate,
        Employee.Salary,
        Employee.Contract
    FROM Departmt, Employee
    WHERE Departmt.Dept_Name = '#URL.Item#'
    AND Departmt.Dept_ID = Employee.Dept_ID
    ORDER BY Employee.LastName, Employee.Firstname
</cfquery>

<html>
<head>
    <title>Employee Salary Details</title>
</head>

<body>

<h1><cfoutput>#GetSalaryDetails.Dept_Name[1]# Department
    Salary Details</cfoutput></h1>
<table border cellspacing=0 cellpadding=5>
<tr>
    <th>Employee Name</th>
    <th>StartDate</th>
    <th>Salary</th>
    <th>Contract?</th>
</tr>
<cfoutput query="GetSalaryDetails" >
<tr>
    <td>#FirstName# #LastName#</td>
    <td>#dateFormat(StartDate, "mm/dd/yyyy")#</td>
    <td>#numberFormat(Salary, "$999,999")#</td>
    <td>#Contract#</td>
</tr>
</cfoutput>
</table>
</body>
</html>
  2. Save the page as Salary_details.cfm in the myapps directory under the web root directory.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfquery name="GetSalaryDetails"
        datasource="cfdocexamples">
    SELECT
        Departmt.Dept_Name,
        Employee.FirstName,
        Employee.LastName,
        Employee.StartDate,
        Employee.Salary,
        Employee.Contract
    FROM Departmt, Employee
    WHERE
        Departmt.Dept_Name =
            '#URL.Item#'
    AND Departmt.Dept_ID =
        Employee.Dept_ID
    ORDER BY Employee.LastName,
        Employee.Firstname
</cfquery>

Get the salary data for the department whose name was passed in the URL parameter string. Sort the data by the employee’s last and first names.

<table border cellspacing=0 cellpadding=5>
<tr>
    <th>Employee Name</td>
    <th>StartDate</td>
    <th>Salary</td>
    <th>Contract?</td>
</tr>
<cfoutput query="GetSalaryDetails" >
<tr>
    <td>#FirstName# #LastName#</td>
    <td>#dateFormat(StartDate,
        "mm/dd/yyyy")#</td>
    <td>#numberFormat(Salary, "$999,999")#</td>
    <td>#Contract#</td>
</tr>
</cfoutput>
</table>

Display the data retrieved by the query as a table. Format the start date into standard month/date/year format, and format the salary with a leading dollar sign, comma separator, and no decimal places.

Part 2: making the chart dynamic

  1. Open chartdata.cfm in your editor.
  2. Edit the cfchart tag for the pie chart so it appears as follows:
    <cfchart
        font="Times"
        fontBold="yes"
        backgroundColor="##CCFFFF"
        show3D="yes"
        url="Salary_Details.cfm?Item=$ITEMLABEL$"
        >

    <cfchartseries
        type="pie"
        query="DeptSalaries"
        valueColumn="AvgByDept"
        itemColumn="Dept_Name"
        colorlist="##990066,##660099,##006699,##069666"
    />
</cfchart>
  3. Save the file as chartdetail.cfm.
  4. View the chartdata.cfm page in your browser.
  5. Click the slices of the pie chart to request the Salary_details.cfm page and pass in the department name of the wedge you clicked. The salary information for that department appears.

Reviewing the code

The following table describes the highlighted code and its function:

Code

Description

url=
    "Salary_Details.cfm?Item=$ITEMLABEL$"

When the user clicks a wedge of the pie chart, call the Salary_details.cfm page in the current directory, and pass it the parameter named Item that contains the department name of the selected wedge.


Linking to JavaScript from a pie chart

In the following example, when you click a pie wedge, ColdFusion uses JavaScript to display a pop-up window about the wedge.

To create a dynamic chart using JavaScript:

  1. Create a new application page with the following content:
    <script>
function Chart_OnClick(theSeries, theItem, theValue){
alert("Series: " + theSeries + ", Item: " + theItem + ", Value: " + theValue);
    }
</script>

<cfchart
        xAxisTitle="Department"
        yAxisTitle="Salary Average"
        tipstyle=none
        url="javascript:Chart_OnClick('$SERIESLABEL$','$ITEMLABEL$','$VALUE$');"
    >
    <cfchartseries type="bar" seriesLabel="Average Salaries by Department">
        <cfchartData item="Finance" value="75000">
        <cfchartData item="Sales" value="120000">
        <cfchartData item="IT" value="83000">
        <cfchartData item="Facilities" value="45000">
    </cfchartseries>
</cfchart>
  2. Save the page as chartdata_withJS.cfm in the myapps directory under the web root directory.
  3. View the chartdata_withJS.cfm page in your browser:
  4. Click the slices of the pie chart to display the pop-up window.
Previous


Creating Reports for Printing

This chapter explains how to use ColdFusion MX tags, functions, and tools to create pages and reports that are suitable for printing.

Contents

About printable output

Creating PDF and FlashPaper output with the cfdocument tag

Creating reports with the ColdFusion MX 7 reporting

Font management with printable reports

Creating reports with Crystal Reports (Windows only)

Next


About printable output

Although all web browsers let you print HTML pages, HTML-format pages are not optimized for printed output. For example, lack of control over line breaks, page breaks, headers, footers, and page numbers are just a few of the problems that you encounter when designing reports and other pages meant to be printed.

In the context of ColdFusion MX, the term printable output refers to pages that include the following features:

  • Page numbers
  • Headers and footers
  • Page breaks
  • Clickable hyperlinks when viewed online

ColdFusion MX provides the following tags for generating printable output:

  • cfdocument Creates printable output and returns it to the browser or saves it in a file. For more information, see Creating PDF and FlashPaper output with the cfdocument tag.
  • cfreport Invokes the specified report definition to create printable output and return it to the browser or save it in a file. ColdFusion MX supports report definitions from the following tools:
    • ColdFusion Report Builder The ColdFusion Report Builder is a banded report writer that is integrated with ColdFusion MX. For more information, see Creating reports with the ColdFusion MX 7 reporting.
    • Crystal Reports Crystal Reports is a report writer whose report definitions you can use with the cfreport tag. For more information, see Creating reports with Crystal Reports (Windows only).

ColdFusion MX printable reports are available in the following formats:

FlashPaper ColdFusion MX creates a SWF file. Clients must have an up-to-date version of the Macromedia Flash Player installed.

Adobe Acrobat ColdFusion MX creates a PDF file. Clients must have the Acrobat Reader installed.

Microsoft Excel (ColdFusion MX 7 reporting only) ColdFusion MX 7 creates an Excel spreadsheet.

Note: The Excel report output format type provides limited support for the formatting options available in ColdFusion MX 7 reporting. Images and charts are not supported and numeric data containing formatting (commas, percents, currency, etc.) appears as plain text in Excel. The Excel output format supports simple reports only and it is recommended that careful design and layout consideration be given to reports designed for Excel output.

Crystal Reports (Windows only) ColdFusion MX passes control to Crystal Reports, which creates HTML. This option is available with the cfreport tag only.


Creating PDF and FlashPaper output with the cfdocument tag

The cfdocument tag converts everything between its start and end tags into PDF or FlashPaper output format and returns it to the browser or saves it to a file. This lets you easily convert HTML to printable output, as the following example shows:

<cfdocument format="FlashPaper">
<p>This is a document rendered by the
   cfdocument tag.</p>
</cfdocument>

The cfdocument tag supports all HTML and CFML tags, with the following exceptions:

  • cfchart
  • Macromedia Flash content
  • Interactive tags, such as form, cfform, and cfapplet
  • JavaScript that dynamically modifies elements or element positions

Additionally, the HTML wrapped by the cfdocument tag must be well-formed, with end tags for every start tag and proper nesting of block-level elements.

Note: ColdFusion MX does not return HTML and CFML outside of the <cfdocument> </cfdocument> pair.

This section describes the following topics:

  • Creating basic reports from HTML and CFML
  • Creating sections, headers, and footers
  • Using the cfdocument scope
  • Using cfhttp to display web pages
  • Using advanced PDF options
  • Saving printable reports in files


Creating basic reports from HTML and CFML

You can convert HTML-based reports into PDF or FlashPaper output by wrapping the HTML in the cfdocument start and end tags, and specifying cfdocument attributes, as appropriate, to customize the following items:

  • Page size
  • Page orientation
  • Margins
  • Encryption (PDF only)
  • User password and owner password (PDF only)
  • Permissions (PDF only)

For complete information on these options, see the cfdocument tag discussion in CFML Reference.

Note: Embedding fonts in the report can help ensure consistent display across multiple browsers and platforms. For more information on the considerations related to embedding fonts, see Font management with printable reports.

The following example displays a list of employees, using a cfoutput tag to loop through the query:

<cfdocument format="flashpaper">
<h1>Employee List</h1>
<!--- Inline query used for example purposes only --->
<cfquery name="EmpList" datasource="cfdocexamples">
   SELECT FirstName, LastName, Salary, Contract
   FROM Employee
</cfquery>
<cfoutput query="EmpList">
#EmpList.FirstName#, #EmpList.LastName#, #LSCurrencyFormat(EmpList.Salary)#, #EmpList.Contract#<br>
</cfoutput>
</cfdocument>


Creating sections, headers, and footers

You can use the cfdocumentitem and cfdocumentsection tags to fine-tune your printable output, as follows:

  • cfdocumentitem Creates page breaks, headers, or footers.
  • cfdocumentsection Divides output into sections, optionally specifying custom margins. Within a section, use the cfdocumentitem tag to specify unique headers and footers for each section.

cfdocumentitem

You use one or more cfdocumentitem tags to specify headers and footers or to create a page break. You can use cfdocumentitem tags with or without the cfdocumentsection tag, as follows:

  • With cfdocumentsection The cfdocumentitem attribute applies only to the section, and overrides previously specified headers and footers.
  • Without cfdocumentsection The cfdocumentitem attribute applies to the entire document, as follows:
    • If the tag is at the top of the document, it applies to the entire document.
    • If the tag is in the middle of the document, it applies to the rest of the document.
    • If the tag is at the end of the document, it has no affect.

You can use the cfdocumentitem tag to create a running header for an entire document, as the following example shows:

<cfdocument format="PDF">
<!--- Running header --->
<cfdocumentitem type="header">
  <font size="-3"><i>Directory Report</i></font>
</cfdocumentitem>
<h3>cfdirectory Example</h3>
<!--- Use cfdirectory to display directories by name and size --->
<cfdirectory
  directory="#GetDirectoryFromPath(GetTemplatePath())#"
  name="myDirectory" recurse="yes"
  sort="directory ASC, name ASC, size DESC">
<!---- Output the contents of the cfdirectory as a cftable ----->
<cftable query="myDirectory"
  htmltable colheaders>
  <cfcol header="DIRECTORY:" text="#directory#">
  <cfcol header="NAME:" text="#Name#">
  <cfcol header="SIZE:" text="#Size#">
</cftable>
</cfdocument>

cfdocumentsection

When using cfdocumentsection, all text in the document must be enclosed within cfdocumentsection tags. ColdFusion MX ignores HTML and CFML outside of cfdocumentsection tags. The margin attributes override margins specified in previous sections or in the parent cfdocument tag. If you specify margin attributes, the units are controlled by the unit attribute of the parent cfdocument tag; the default for the unit attribute is inches.

Within a section, use the cfdocumentitem tag to specify unique headers and footers for each section and a page break before each section, as the following example shows:

<cfquery datasource="cfdocexamples" name="empSalary">
SELECT Emp_ID, firstname, lastname, e.dept_id, salary, d.dept_name
FROM employee e, departmt d
WHERE e.dept_id = d.dept_id
ORDER BY d.dept_name
</cfquery>

<cfdocument format="PDF">
  <cfoutput query="empSalary" group="dept_id">
    <cfdocumentsection>
    <cfdocumentitem type="header">
        <font size="-3"><i>Salary Report</i></font>
    </cfdocumentitem>
    <cfdocumentitem type="footer">
        <font size="-3">Page #cfdocument.currentpagenumber#</font>
    </cfdocumentitem>
    <h2>#dept_name#</h2>
     <table width="95%" border="2" cellspacing="2" cellpadding="2" >
      <tr>
         <th>Employee</th>
         <th>Salary</th>
      </tr>
      <cfset deptTotal = 0 >
      <!--- inner cfoutput --->
      <cfoutput>
        <tr>
          <td><font size="-1">
            #empSalary.lastname#, #empSalary.firstname#</font>
          </td>
          <td align="right"><font size="-1">
            #DollarFormat(empSalary.salary)#</font>
          </td>
         </tr>
         <cfset deptTotal = deptTotal + empSalary.salary>
      </cfoutput>
        <tr>
          <td align="right"><font size="-1">Total</font></td>
          <td align="right"><font size="-1">#DollarFormat(deptTotal)#</font></td>
        </tr>
        <cfset deptTotal = 0>
       </table>
      </cfdocumentsection>
    </cfoutput>
</cfdocument>


Using the cfdocument scope

When you use the cfdocument tag, ColdFusion MX creates a new scope named cfdocument. This scope contains the following variables:

currentpagenumber Displays the current page number.

totalpagecount Displays the total page count.

Note: The cfdocument scope variables are reserved for page number rendering. Do not use them in ColdFusion expressions.

You typically use these variables in a header or footer to display the current page number and total number or pages, as the following example shows:

<cfdocumentitem type= "footer> #cfdocument.currentpagenumber# of #cfdocument.totalpagecount#</cfdocumentitem>


Using cfhttp to display web pages

You can use the cfhttp tag in combination with the cfdocument tag to display entire web pages in PDF or FlashPaper output format, as the following example shows:

<!--- You can pass a URL in the URL string --->
<cfparam name="url.target_url" default="http://www.boston.com">
<cfoutput>
<cfhttp url="#url.target_url#" resolveurl="yes">

<cfdocument format="FlashPaper">
<cfdocumentitem type="header">
  <cfoutput>#url.target_url#</cfoutput>
</cfdocumentitem>
<cfdocumentitem type="footer">
  <cfoutput>#cfdocument.currentpagenumber# /
    #cfdocument.totalpagecount#</cfoutput>
</cfdocumentitem>
<!--- Display the page --->
#cfhttp.filecontent#
</cfdocument>
</cfoutput>


Using advanced PDF options

The cfdocument tag supports the Acrobat security options, as the following table shows:

Security option

Description

Encryption

Use the encryption attribute to specify whether PDF output is encrypted. Specify one of the following:

  • 128-bit
  • 40-bit
  • none

User password

Use the userpassword attribute to specify a password that users must enter to view the document.

Owner password

Use the ownerpassword attribute to specify a password that users must enter to view and optionally modify the document.

Additionally, the cfdocument tag supports the following Acrobat security permissions through the permissions attribute. Specify one or more of the following values; separate multiple permissions with a comma:

Permission | Description
Printing | Specify the AllowPrinting attribute to enable viewers to print the document.
Modification | Specify the AllowModifyContents attribute to let viewers modify the document, assuming they have the required software.
Copy | Specify the AllowCopy attribute to let viewers select and copy text from the document.
Annotation | Specify AllowModifyAnnotations to let viewers add comments to the document. If users add annotations, they must save the PDF after making changes.
Screen readers | Specify AllowScreenReaders to enable access to the document through a screen reader.
Fill in | Specify AllowFillIn to enable users to use form fields.
Assembly | Specify AllowAssembly to enable users to create bookmarks and thumbnails, as well as insert, delete, and rotate pages.
Degraded printing | Specify AllowDegradedPrinting to enable low-resolution printing. Low resolution printing prints each page as a bitmap, so printing may be slower.

Note: The defaults for these options vary, based on encryption level. These options apply to PDF only. For more information, see the cfdocument discussion in CFML Reference.

The following example creates a PDF document that allows copying only:

<cfdocument format="PDF" encryption="40-bit"
   ownerpassword="us3rpa$$w0rd" userpassword="us3rpa$$w0rd"
   permissions="AllowCopy" >
<h1>Employee List</h1>
<cfquery name="EmpList" datasource="cfdocexamples">
   SELECT FirstName, LastName, Salary
   FROM Employee
</cfquery>
<cfoutput query="EmpList">
#EmpList.FirstName#, #EmpList.LastName#, #LSCurrencyFormat(EmpList.Salary)#<br>
</cfoutput>

</cfdocument>


Saving printable reports in files

You can use the cfdocument filename attribute to save the generated PDF or SWF output to a file, as the following example shows:

<!--- The compasstravel database is part of the Getting Started
      tutorial application, found under the cfdocs directory. --->
<cfquery datasource="compasstravel" name="compasstrips">
SELECT tripName, tripDescription, tripLocation, price
FROM trips
ORDER BY price
</cfquery>
<cfdocument format="pdf" filename="#GetDirectoryFromPath(GetTemplatePath())#/compasstrips.pdf" overwrite="yes">
  <cfdocumentsection>
    <h1 align="center">Compass Travel</h1>
    <h2 align="center">Destination Guide</h2>
    <p align="center"><img src="cfdocs/getting_started/photos/somewhere.jpg"></p>
  </cfdocumentsection>
  <cfdocumentsection>
    <cfdocumentitem type="header">
      <font size="-3"> <i>Compass Travel Trip Descriptions</i></font>
    </cfdocumentitem>
    <cfdocumentitem type="footer">
      <font size="-3"> <cfoutput>Page #cfdocument.currentpagenumber#</cfoutput> </font>
    </cfdocumentitem>
    <cfoutput query="compasstrips">
      <hr>
      <h2>#tripName#</h2>
      <p><b>#tripLocation#</b></p>
      <p>Price: #DollarFormat(price)#</p>
      <p>#tripDescription#</p>
    </cfoutput>
  </cfdocumentsection>
</cfdocument>


Creating reports with the ColdFusion MX 7 reporting

Macromedia ColdFusion MX 7 reporting adds integrated business reporting to ColdFusion, providing access to important business data. ColdFusion MX 7 reporting consists of server-side runtime processing and a graphical user interface (GUI), called the Report Builder.

For information on installing the Report Builder, see Getting started.

This section describes how to use the Report Builder to define report definitions. The Report Builder is a Windows-only tool that lets you build banded reports. A banded report consists of multiple horizontal sections (bands), one band for each part of a printed report. For example, data and text in the report header band prints at the beginning of the report, data and text in the page header band prints at the beginning of each page, and data and text in the page footer band prints at the end of each page. In the middle of the report is the detail band, which, at runtime, contains one row for each row in the report’s result set or database query.

The following figure shows the Report Builder workspace with a simple Employees by Department report:

The Report Builder workspace showing a simple Employees by Department report.

The following figure shows a preview of that report in FlashPaper format:

The preceding report shown in FlashPaper format.

This section contains the following discussions:

  • Reporting features
  • Reporting architecture
  • Getting started
  • Basic steps for creating reports
  • Report definition guidelines
  • Common reporting tasks and techniques
  • Using the Report Creation Wizard
  • Using the Query Builder
  • Using CFML in reports
  • Using charts
  • Using subreports


Reporting features

Although you can use the cfdocument tag to create similar looking reports, ColdFusion MX 7 reporting and the Report Builder provide many features that ease the report creation process, as the following table describes:

Feature

Description

Easy-to-use interface

Employ a banded user interface with integrated online Help, For more information, see User interface usage, tips, and techniques.

Query Builder

Display, select, and order database tables and columns used in a report. The Query Builder creates SQL (also called internal SQL), which you can optionally customize using Advanced Query Builder. For more information, see Using the Query Builder.

Multiple display options

Display ColdFusion Report (CFR) files directly in a browser (no coding is required to create or display a ColdFusion report), or invoke a report with the cfreport tag, optionally passing query data to use instead of the internal SQL. For more information, see Displaying reports.

Report preview

Use Preview (F12) to display your report, optionally displaying a CFM page that invokes the report through the cfreport tag. For more information, see Previewing reports.

Familiar language

Use CFML in the Report Builder, as follows:

Advanced query mode Create a customized query object for the report using the cfquery tag, the QueryNew function, or any tag that returns a query. For more information, see Advanced query mode.

Report functions Create user-defined functions that you can use to populate report fields. For more information, see Report functions.

Formatting Use CFML functions to format report fields. For more information, see Expressions and the Expression Builder.

Global control of textual data

Use text styles for report-wide control over display fields. For more information, see Using text styles.

Wizards

The Report Builder provides the following wizards:

Report Creation Wizard Define SQL, report fields, grouping, and other display options. For more information, see Using the Report Creation Wizard.

Chart Wizard Define chart data, chart type, chart series, and other charting options. For more information, see Using charts.

Subreport Wizard Insert a subreport and select other subreport options, including subreport parameters. For more information, see Using subreports.

Server Setup Wizard Create settings for an RDS server, including file location and URL. For more information, see Setup Wizard.

Grouping

Define groups, each of which has its own group header and group footer bands. In particular, you can use calculated fields in group footer bands to easily display group totals for numeric fields. For more information, see Grouping and group breaks.

Charting

Insert a chart in any report band, displaying data from a variety of sources. For more information, see Using charts.

Subreports

Insert another report in any report band, optionally passing it a subreport parameter to control the data displayed in the subreport. For more information, see Using subreports.

Tip: The Report Builder contains an extensive online Help system, including quick-start tutorial topics and context-sensitive dialog box Help. Make it a habit to consult the online Help (F1) whenever you have a question.


Reporting architecture

The Report Builder is a stand-alone application that creates report definitions, interacting with a ColdFusion MX server, as necessary. The major architectural components are as follows:

  • Report Builder and CFR files
  • RDS
  • Runtime

Note: The Report Builder runs in the Windows platform only. However, the CFR files created by the Report Builder run on all platforms that ColdFusion MX runs on and that have ColdFusion MX Reporting enabled.

Report Builder and CFR files

The Report Builder stores report definition information in a ColdFusion Report (CFR) file. This file contains field definitions, formatting, database SQL statements, CFML, and other information. You display a CFR file using the cfreport tag and, if enabled for the report, you can display the report by invoking the CFR file in a browser.

RDS

Remote Development Services (RDS) is a proprietary protocol that uses HTTP to enable the Query Builder and Chart Wizard to access database data through a ColdFusion data source. To enable this functionality in the Report Builder, you define settings for an RDS server. RDS server is another name for an associated ColdFusion server that has enabled RDS.

The following figure shows the interaction of the Report Builder, CFR files, and RDS:

The interaction of the Report Builder, CFR files, and RDS

For more information, see Configuring RDS.

Runtime

At runtime, you invoke the CFR file using a ColdFusion MX server that has ColdFusion MX 7 Reporting enabled. For more information on enabling ColdFusion MX reporting, see Getting started.

You can display the CFR file directly or invoke it through the cfreport tag. Additionally, you can optionally save the report to a file instead of returning output to the browser. The following figure shows the ColdFusion MX reporting runtime architecture:

Diagram of the ColdFusion MX reporting runtime architecture

If the report requires input parameters or a passed query, you must use the cfreport tag. If you pass a query attribute in the cfreport tag, it overrides any internal SQL statement in the report definition.


Getting started

Before you get started using ColdFusion MX reporting, you must install the Report Builder.

After you install the Report Builder, start it by opening the Report Builder icon in the location you specified at installation time (for example, the desktop or the Start menu).

The first time you open the Report Builder, the Server Setup Wizard runs. After you complete the Server Setup Wizard, select File > New from the menu bar to define a new report using the Report Creation Wizard. For more information, see Basic steps for creating reports.

This section contains the following discussions:

  • Installing the Report Builder
  • Setup Wizard
  • User interface usage, tips, and techniques

Installing the Report Builder

You can access the Report Builder installer from the following places:

The ColdFusion MX installation Go to the webroot/CFIDE/installers directory.

The ColdFusion MX CD Use the CD Browser to select the ColdFusion MX reporting option.

The Macromedia website Go to www.macromedia.com/software/coldfusion/reporting/.

When you install the Report Builder, it also registers Windows DLLs that are used by RDS. If these DLLs fail to register properly, the Report Builder generates errors at startup and when using RDS.

Setup Wizard

The first time you start the Report Builder, it runs the Setup Wizard. The Setup Wizard prompts you to define default settings for an associated ColdFusion MX server. These settings include the following:

  • Default unit of measurement: Inches, centimeters, or pixels
  • ColdFusion server (RDS must be enabled on this server). This is the RDS server that the Query Builder and Chart Wizard use to access database data. The Setup Wizard requires the following information:
    • Host name or IP address.
    • Web server port (typically 80 if using a web server connector, 8500 if using the built-in web server in the server configuration, 8300 if using the built-in web server with the cfusion server in the multiserver configuration, or a J2EE-server-specific web server port number).
    • RDS password for the associated ColdFusion server.
  • Directory path to the webroot used by the associated ColdFusion server (for example, C:\Inetpub\wwwroot or C:\CFusionMX7\wwwroot).
  • URL for the webroot used by the associated ColdFusion server (for example, http://localhost or http://localhost:8500).

After running the Setup Wizard, the Report Gallery dialog box appears. When you click the Using a Report Wizard radio button, the Report Builder runs the Report Creation Wizard, which prompts you for information and generates a complete report definition automatically.

For more information on the Report Creation Wizard, see Using the Report Creation Wizard.

User interface usage, tips, and techniques

The Report Builder user interface includes the following areas:

Toolbox Contains nonvariable elements placed in a report, including text, shapes, images, subreports, and graphs. To use toolbox elements, click on the element, and then click and drag in the report band to define the element's size. After you place an element on a report band, you can modify its appearance and behavior by using the Properties sheet.

Alignment palette Use Control-click or Shift-click to select multiple elements in a report band, and then click the appropriate alignment icon. You can also use Control-A to select all elements in a report band.

Report bands Place toolbox elements, query fields, and calculated fields on report bands. The default report bands are report header, page header, column header, detail, column footer, page footer, report footer, and watermark. Page header, page footer, and watermark are closed by default; to open them drag one of the adjacent splitter bars. To define additional bands for groups, select Report > Group Management.

Properties panel Contains display and report characteristics for the selected field. To change a property value, type or select a new value, and press Enter. For complete information on properties, see the online Help.

Fields and parameters panel Contains items for query fields, input parameters, and calculated fields. Use the add, edit, and delete icons to manage these fields. After you define a field, drag the field name to add the field, its associated label, or both, to a report band.

Text styles tool window Contains the text styles that you define for a report. Use the add, edit, and delete icons to manage text styles. After you define text styles, you apply them to text elements on the report instead of specifying font, font size, and so on, for each individual text element. If your report layout, platform, or font availability requirements change, you can modify the text style to apply the changes throughout the report. Additionally, you can specify that a text style is the report’s default font and the Report Builder applies it to all text elements you add to a report.

The following figure shows the main areas of the Report Builder user interface:

The main areas of the Report Builder user interface

The View menu lets you control whether toolboxes and tool windows appear. Additionally, you can click on a tool window’s title to undock it and drag it to another area of the screen. To re-dock a tool window, drag it to the side or corner until a rectangle appears, and then release the mouse button.

For more information, see Common reporting tasks and techniques and the online Help.


Basic steps for creating reports

The Report Builder is a very flexible tool that provides a variety of ways you can define a report. However, all reports use the following basic steps:

  1. Begin a new report by selecting File > New from the menu bar, clicking the New toolbar icon, or pressing Control+N.

    The ColdFusion Report Builder Gallery dialog box appears.

  2. Select the As a Blank Report option or the Using the Report Wizard option.

    Whether or not you use the Report Creation Wizard, continue with the following steps.

  3. Define the data to be retrieved, either using the Query Builder or by defining the cfquery tag whose query is passed to the report through the cfreport tag. It’s best to plan your data access before defining the report, as described in Report definition guidelines.

    Tip: You can use the Query Builder through the Report Creation Wizard or from the main Report Builder interface (select Report > Report Query from the menu bar).

  4. Define query fields. In addition to the Query Builder, you can also define query fields using the Import or Add Fields buttons on the Report Creation Wizard Define Query Fields panel or the Query Fields node on the Fields and Parameters tab.

    Tip: Use the Import button to import query field definitions from an existing report.

  5. Place query fields on the report. The Report Creation Wizard places query fields on the report bands automatically. To manually place query fields on a report, drag them from the Query Fields node on the Fields and Parameters tab to a report band. For more information, see Common reporting tasks and techniques.
  6. (Optional) Define input parameters. To define input parameters, use the Input Parameters area on the Fields and Parameters tab. You pass input parameters to a report through the cfreportparam tag. For more information on input parameters, see Using input parameters to pass variables and other data at runtime.
  7. (Optional) Define groups. Use the Report Creation Wizard Define Grouping panel or the Group Management dialog box (Report > Group Management) to define the query field whose change causes a group break. For more information on grouping, see Grouping and group breaks.
  8. (Optional) Define the related CFM page. Whether or not the report has an internal query, you may want to invoke it through the cfreport tag in a CFM page. If you define a CFM page, be sure to specify the URL of the CFM page in the Report Preview URL field of the Report Properties dialog box (used in report preview).

    Tip: The Code Snippet Preview dialog box generates a prototype CFM page (or CFC and calling CFM page) and lets you save this code to a file (or files).

  9. Preview, modify, repeat. To preview a report, select File > Preview from the menu bar, click the Preview toolbar icon, or press F12.

    For more information on report preview, see Previewing reports.


Report definition guidelines

To ensure a successful report, you should plan the following before defining it in the ColdFusion Report Builder:

  • Report design issues:

    Audience Why are you creating this report? Who is the audience?

    Data What data needs to be in the report? Where does it come from? Whether you use the Query Builder or pass a query to the report, you should plan the data in advance.

    Grouping Do you need groups? If so, ensure that the result set is returned in the correct order, and you define a group based on the sort column.

    Calculated fields Are there fields that need to be totalled or calculated? For column totals, use calculated fields. For calculated totals on individual rows, use SQL. For more information, see Common reporting tasks and techniques.

    input parameters Do you need to pass variable data to the report. If so, define an input parameter and pass values to the report at runtime using the cfreportparam tag. For more information, see Common reporting tasks and techniques.

  • Data retrieval strategy:

    Query Builder and basic SQL Use this option when your report has standard selection criteria (such as a WHERE clause with sorting and a fixed set of selection criteria) and when you need to develop a report quickly. This method also allows you to specify cfquery options, such as caching.

    Query Builder and advanced query mode Use this option when you want to use a ColdFusion query encapsulated in the report definition. This option is also useful if the query comes from the cfdirectory, cfldap, or cfpop tags; query of queries, or is dynamically constructed with the QueryNew function.

    The cfreport tag and a passed query Use this option when you need more control over the result set used in the report; for example, your application might have a form that your end users can use to construct dynamic selection criteria.

  • Related visual information:

    Charts For more information, see Using charts.

    Subreports For more information, see Using subreports.


Common reporting tasks and techniques

This section describes the following reporting tasks and techniques:

  • Grouping and group breaks
  • Defining, modifying, and using fields and input parameters
  • Using toolbox elements on report bands
  • Aligning elements
  • Using text styles
  • Previewing reports
  • Displaying page numbers
  • Using layered controls
  • Using links
  • Using the Properties sheet
  • Displaying reports
  • Using input parameters to pass variables and other data at runtime
  • Configuring RDS

For more information, including troubleshooting tips, see Report Builder online Help.


Grouping and group breaks

You can add clarity to a report’s organization by grouping the information. You can define separate headings for each new group and can also display group-specific summary information, such as subtotals at the end of each group’s area of the report. For example, you might create a report that displays departments, employees, and their salaries. Grouping the data by department lets users quickly understand department salary characteristics. When the department ID changes, the ColdFusion Report Builder triggers a group break, which completes the old group by displaying the group footer (which can contain calculated fields, such as total and average department salary) and starts the new group by displaying the group header.

The ColdFusion Report Builder does not group data itself. You must ensure that the SQL used for retrieve the result set is already grouped in the appropriate order; typically you implement grouping by specifying an ORDER BY clause in the SQL SELECT statement used for the report. For example, you might use the following SQL SELECT statement:

SELECT EmployeeID, LastName, FirstName, Title, City, Region, Country
FROM Employees
ORDER BY Country, City

For this example, you can define two groups: one that corresponds to Country, and a second group that corresponds to City. When you define more than one group, the Group Management dialog box appears Up Arrow and Down Arrow keys, which you can use to control group hierarchy. For example, country should be above city, because countries contain cities.

To define a group:

  1. Select Report > Group Management from the menu bar.
  2. Click Add.
  3. Specify a group name.
  4. Specify the value that controls grouping (also called a group expression). At runtime, ColdFusion triggers a group break when the result of this value changes. These values are often query field names. However, this value can also be a calculated field or other type of expression. Sample group expressions include the following:

    Query field Creates a group break when the associated column in the result set contains a different value. The field that you specify must be one of the sort criteria for the result set; for example, query.country.

    Calculated field Creates a group break when a calculated field returns a different value. For example, if the expression calc.FirstLetter returns the first letter of a query column, you can group a report in alphabetical order.

    Boolean expression Creates a group break when a Boolean expression returns a different value. For example, if your result set is sorted by the passpercentage column, you might use the Boolean expression query.passpercentage LT 50.

  5. Specify group break options:

    Start New Column Forces a new column on a group break.

    Start New Page Forces a new page on a group break.

    Reset Page Number Resets the page number to 1 on a group break.

  6. Specify band size and printing information:

    Min. height for group The minimum height that must remain on a page for ColdFusion to print the group band on that page.

    Reprint Header on Each Page Displays the group header on each page.

  7. Click OK.

    The Report Builder adds the group to the report and creates header and footer bands for the group.

  8. Click OK.

    The Group Management dialog box closes.

  9. Add headings, text, query fields, calculated fields, and other information to the group’s header and footer.

To create group subtotals:

  1. Create a calculated field to contain the group subtotal. Create the calculated field using the following criteria:
    • Specify a numeric data type.
    • Select Sum in the Calculation field.
    • Specify the field to sum on in the Perform Calculation On field. For example, on an employees by department report, you might sum on query.emp_salary.
    • Specify that the field should be reset when the group changes.
  2. Place the calculated field on the report.

For more information on calculated fields, see Defining, modifying, and using fields and input parameters or the Report Builder online Help.


Defining, modifying, and using fields and input parameters

The Report Builder supports variable data through query fields, input parameters, and calculated fields, as follows:

Query field Maps to columns in the database result set associated with the report. You define one query field for each column in the associated database query.

Calculated field Analyzes or sums multiple detail rows in a report. ColdFusion dynamically generates calculated field values at report-generation time, optionally recalculating the value with each new report, page, column, or group.

Input parameter Specifies data fields that you pass to the report at runtime through the cfreportparam tag or from a main report to a subreport. You can place input parameters directly on a report band or you can use them as input to a calculated field.

To define a query field:

  1. Click the Fields and Parameters tab. By default, this tab is in the lower-right area of the Report Builder window.
  2. Click Query Fields.
  3. Click the plus sign (+) at the top of the tab.

    The Add Query Field dialog box appears.

  4. Type a value for the name field. This must match a column name in the corresponding cfquery statement and cannot contain a period.
  5. Type a default label.
  6. Specify the data type of the corresponding database column, as follows:

    Object

    Time

    Long

    Boolean

    Double

    Short

    Byte

    Float

    Big Decimal

    Date

    Integer

    Image

    Time Stamp

    BLOB

    String
  7. Click OK.

Note: The Query Builder defines query fields automatically for all database columns in the result set (does not apply to the Advanced Query Builder). Additionally, if you run the Query Builder as part of the Report Creation Wizard, the wizard places query fields on the report.

To define a calculated field:

  1. Click the Fields and Parameters tab. By default, this tab is in the lower-right area of the Report Builder window.
  2. Click Calculated Fields.
  3. Click the plus sign (+) at the upper edge of the tab.

    The Add Calculated Field dialog box appears.

  4. Specify a name, default label text, and data type. Data type options are the same as for query fields.
  5. Specify calculation options:

    Calculation Specifies the type of calculation that ColdFusion performs. Valid values are: Average, Count, Highest, Lowest, Nothing, Standard Deviation, Sum, System, and Variance. If you specify Nothing, you typically use the Perform Calculation On field to specify a dynamic expression. With the exception of Nothing (for which you use the Perform Calculation On field) and System (for which you write a customized scriptlet class), you use these calculations for group, page, and report totals.

    Perform Calculation On Specifies a field or expression. Click the ... button to display the Expression Builder.

    Initial Value Specifies an initial value for the calculated field.

  6. Specify reset options, as follows:

    Reset Field When Specifies when to reset the calculated field value. Valid values are: None, Report, Page, Column Group.

    Reset Group If Reset Field When is set to Group, use this field to specify the group whose group break triggers the reset.

  7. Click OK.

For additional information on calculated fields, see "Add Calculated Field dialog box" in Report Builder online Help and Expressions and the Expression Builder.

To define an input parameter:

  1. Click the Fields and Parameters tab. By default, this tab is in the lower-right area of the Report Builder window.
  2. Click Input Parameters.
  3. Click the plus sign (+) at the top of the tab.
  4. The Add Input Parameter dialog box appears.

    Enter a value for the name field. This must match an input parameter, such as the name attribute of a cfreportparam tag included in the cfreport tag that invokes the report definition.

  5. Enter the default label text.
  6. Specify a data type and default value. Data type options are the same as for query fields.
  7. Click OK.

For more information on using input parameters, see Using input parameters to pass variables and other data at runtime and Using subreports.

To place a query field, calculated field, or input parameter on a report band:

  1. In the Fields and Parameters tab, use the radio buttons to specify whether to place the label, the field, or both.
  2. Drag the query field, calculated field, or input parameter from the Fields and Parameters tab to the appropriate report band.
  3. Drag the query field, calculated field, or input parameter to the desired band.
  4. (Optional) Use the Properties sheet to customize the field display.

For example, you might have a query field named query.emp_salary and a calculated field that sums query.emp_salary, resetting it with each group. Place query.emp_salary in the detail band, and the associated calculated field in the group footer band.


Using toolbox elements on report bands

You can use the toolbox to add graphic and textual elements, such as images, circles, squares, lines, dynamic fields, charts, and subreports, to report bands.

This section discusses text, images, circles, squares, lines, and dynamic fields. For information on charts, see Using charts. For information on subreports, see Using subreports.

The basic technique for adding toolbox elements is to click in the toolbox element and then drag to define an area in the appropriate report band. For some toolbox elements, such as image and text box, a dialog box immediately appears, prompting for more information. For all toolbox elements, you can customize the appearance of the element using the Properties sheet.

Tip: You can add toolbox elements through the Insert menu.

To use text boxes:

  1. Click the Label icon (abc) in the toolbox.
  2. Define the area for the label by dragging on the desired band.

    The Edit Label Text dialog box appears.

  3. Enter the label text. To add a line break, press Control+Enter.
  4. Click OK, or press Enter.

    Note: ColdFusion trims leading and trailing blanks from labels. To include leading and trailing blanks, define a dynamic field and include the blanks in the expression; for example, " My Title ".

To use image files:

  1. Click the Image icon in the toolbox.
  2. Define the area for the image by dragging on the desired band.

    The Image File Name dialog box appears.

  3. Navigate to the file containing the image, select the file, and click OK.

To use a database BLOB column as an image source:

  1. Click the Image icon in the toolbox.
  2. Define the area for the image by dragging on the desired band.

    The Image File Name dialog box appears.

    Tip: You can also drag the BLOB field from the Fields and Parameters tab to a report band.

  3. Click Cancel.

    The Expression Builder appears.

  4. Click the Image Type drop-down list box and change File/URL to BLOB.
  5. Select the query field or input parameter that contains the BLOB column.

    Note: The BLOB column must contain a binary image in GIF, JPEG, or PNG format.

  6. Click OK.

Note: These instructions assume that the contents of the BLOB column can be rendered as an image.

To use rectangles, ellipses, and lines:

  1. Click the rectangle, ellipses, or line icon in the toolbox.
  2. Define the area or line by dragging on the desired band.
  3. (Optional) Resize the selected element by dragging the handles that surround it.

    Tip: Pressing the Control key while resizing a rectangle, ellipsis, or line, constrains the element to a square, circle, or angles that are multiples of 45 degrees.

To use dynamic fields:

  1. Click the Field icon in the toolbox.
  2. Define the area for the dynamic field by dragging on the desired band.

    The Add Field dialog box appears (if you haven’t defined any query fields, the Expression Builder appears).

  3. Select the field to add. If you select a query field, calculated field, or input parameter, this is the same as dragging from the Fields and Parameters tab.
  4. (Optional) Select Manually Entered Expression.

    The Expression Builder appears. This option is useful for calculations that use variables in the same row. For example, to compute total price for an order detail line item, you might use the following expression:

    LSNumberFormat((query.unitprice * query.quantity), ",_.__")
  5. Click OK.


Aligning elements

Organized element layout is essential to a visually pleasing report. You achieve this organization by aligning, spacing, and centering visual elements on each band relative to each other, to the band itself, and to elements on other bands.

The Report Builder Align Palette includes the following options:

  • Align left, center, and right
  • Align top, horizontal, and bottom
  • Same heights, widths, and both
  • Space equally horizontally
  • Space equally vertically

You align, size, and space multiple report elements, as follows:

Relative to the band they are in You control relative alignment through the Align to Band icon, which is the bottom icon in the Align Palette. When it is enabled, the Align to Band icon has a rectangle surrounding it, and the Report Builder aligns and spaces one or more elements relative to the height and width of the band.

Relative to each other When Align to Band is disabled, Report Builder aligns and spaces two or more elements relative to each other.

To use the Align Palette:

  1. Select two or more elements by pressing Control-click, Shift-click, or using lasso select.
  2. Click the alignment icon, or select Modify > Alignment > alignment option from the menu bar.

Tip: The Align Palette options are also available from Modify > Alignment on the menu bar.

For complete information on fine-tuning element display, see Report Builder online Help.


Using text styles

A text style is similar to a font style in Microsoft Word. Instead of explicitly associating a text element with font specifications, you associate the element with a text style. This provides you with report-wide control of the font characteristics of your report.

Additionally, you can specify that a text style is the default. The ColdFusion Report Builder uses the default text style for all text fields for which you have applied no other font specifications or text styles. The default text style, if defined, is displayed in bold in the Text Styles panel.

Note: When choosing fonts for your report, you must ensure that the fonts are available on the server that runs ColdFusion and (if you don’t embed fonts) on the client computer. For more information on fonts, see Font management with printable reports.

To define a text style:

  1. Click the Text Styles tab. By default, this tab is in the lower-right area of the Report Builder window.
  2. Click the plus sign (+) at the top of the tab.

    The Add Text Style dialog box appears.

  3. Type a value for the name field.
  4. Add other text style characteristics.
  5. Click OK.

To specify that a text style is the default:

  1. Edit an existing text style or create one.

    The Add/Edit Text Style dialog box appears.

  2. Select the Default check box.
  3. Add or modify other text style characteristics, as appropriate.
  4. Click OK.

For complete information on using text styles, see Report Builder online Help.


Previewing reports

Report building is an iterative process and most developers periodically display the in-progress report to review their most recent changes. If your report uses an internal query and you have established default webroot settings, preview functionality is enabled automatically. If your report uses a passed query, you must define an associated CFM page and associate that page with the report. The Report Builder invokes this page when you request Report Preview.

To use Report Builder preview with a report that uses an internal query:

  1. (Optional) Define default server connection information using the Preferences dialog box, if you did not define these settings previously:
    • Default RDS server configuration (used for Query Builder and Chart Wizard only; not required for report preview).
    • Fully qualified path for the local web root directory; for example, C:\CFusionMX7\wwwroot or C:\Inetpub\wwwroot.
    • URL for the local web root, for example, http://localhost:8500 or http://localhost.
  2. (Optional) Specify the output format in the Report Properties dialog box (the default is FlashPaper).
  3. (Optional) If your report is designed to be invoked by a CFM page, specify the URL of the CFM page in the Report Properties dialog box.
  4. Save your report.
  5. Select File > Preview from the menu bar.
    or
    Click the Preview button on the toolbar.
    or
    Press F12.

    The Preview Report window displays your report.

    Note: If the Report Builder displays the Edit Preview Report URL dialog box instead of displaying the Preview window, select Edit > Preferences from the menu bar and ensure that the web root file and URL settings are correct on the Server Connection pane.

  6. Close the preview window by pressing F12.

If your report is designed to accept a query object from a cfreport tag, you must associate a URL with the report. If necessary, the Report Builder prompts for this URL when you preview the report. Otherwise, you can open the Report Properties dialog box, and specify the URL of the CFM page in the Report Preview URL field.

Tip: You can use the cfreport tag to invoke a report, regardless of whether the report has an internal query or is passed a query.

To use Report Builder preview with an associated CFM file:

  1. Select Report > Report Properties from the menu bar.
  2. Specify the URL of the associated CFM page in the Report Preview URL field. This CFM page must contain a cfreport tag whose template attribute specifies the current CFR file and, if necessary, passes a query in the query attribute.
  3. Save your report.
  4. Select File > Preview from the menu bar.
    or
    Click the Preview button on the toolbar.
    or
    Press F12.

    The Preview Report window displays your report in PDF, FlashPaper, or Excel format.


Displaying page numbers

The Report Builder includes a built-in calculated field named PAGE_NUMBER, which displays the current page number when you place it on a report band.

To add a built-in calculated field to a report:

  1. Click the Field tool in the toolbox.
  2. Drag in the center of the header or footer band to define the size of the page number field.

    The Add Field dialog box appears, listing all fields defined for the report, including built-in calculated fields and input parameters.

  3. Select calc.PAGE_NUMBER, and click OK.

Tip: You can use the Field tool to add any type of field (query field, calculated field, input parameter) to a report.

For information on the other built-in calculated fields, see the Report Builder online Help.


Using layered controls

Layered controls are elements that you place at the same location of a report band, and then use PrintWhen expressions to conditionally display one or the other at runtime. You can use layered elements to customize the circumstances under which the elements display and enhance a report’s ability to communicate important information.

To place an element directly over another element:

  1. Place the elements on the band.
  2. Specify a PrintWhen expression, display properties, and placement properties for each element using the Properties sheet, as follows:
  3. Specify a PrintWhen expression for each element. For example, you might specify the following expression to display one element when shippeddate is later than requireddate (that is, late) and another element when shippeddate is earlier than requireddate:

    First element query.shippeddate LTE query.requireddate

    Second element query.shippeddate GT query.requireddate

  4. Specify different display characteristics for each element. For example, if an order is late, display it in red text.
  5. Set the Top, Left, Height, and Width properties to the same values for each element.

Tip: When you specify identical placement properties, you access the individual elements through the Layered Controls menu.

To use the Layered Controls menu:

  1. Right-click on the top element.
  2. Select Layered Controls > elementname from the pop-up menu. The Report Builder identifies each layered element by displaying its PrintWhen expression.
  3. Select the element.

    The Properties sheet displays properties for the selected element.


Using links

You can include hyperlinks from query fields, calculated fields, input parameters, charts, and images to a variety of destinations:

  • An anchor or page within the same report
  • An anchor or page within another report
  • An HTML page, optionally specifying an anchor and URL parameters

One use for this feature is to create drill-down reports, in which you click an item to display detailed information. For example, clicking an employee line item passes the employee ID as a parameter to a page that displays complete information for the employee.

For complete usage information on creating anchors and hyperlinks, see the Report Builder online Help.


Using the Properties sheet

Every element on a report, including the report itself, is defined by a set of properties. These properties affect the look, feel, and behavior of each element.

For many properties, the Report Builder lets you define their values through user interface elements, such as dialog boxes, toolbar icons, and menu items. For example, you set a text label’s font size using a toolbar icon. You can set values for all properties, however, through the Properties sheet, which display all properties for the currently selected element.

Tip: Sometimes a report contains multiple, closely spaced elements and it is difficult to select an individual element using the mouse. In this case, selecting the element from the Properties sheet drop-down list is an easy way to select an element.

The Properties sheet has two views:

Sort alphabetically All properties for the currently selected element display in alphabetical order.

Sort into groups The Properties sheet displays related properties in the following predefined groups:

  • Colors and Style
  • Data
  • Font
  • Font Style
  • Formatting
  • Hyperlinks
  • Layout
  • Processing

The Report Builder displays only groups that relate to the currently selected element.

To set or modify a property for an element in the workspace:

  1. Select the element.
  2. The Report Builder displays its properties in the Properties sheet.
  3. Modify the property. Depending on the property, you enter a value, select a value from a list, or open the Expression Builder to use an expression.
  4. Press Enter.

To choose a different element:

  • Select the element from the drop-down list. When you select a new element, the Report Builder selects the element and displays its properties.

Tip: Although the Properties sheet is a powerful way to set properties, you typically set properties through dialog boxes and toolbar icons. For example, you use the Report Properties dialog box to set report-wide settings. For complete information on setting properties, see "Property reference" in Report Builder online Help.


Displaying reports

Your application can invoke a report by displaying the CFR file in a browser or by displaying a CFM page whose cfreport tag invokes the report.

You can optionally use the cfreport tag to save the report to a file.

The cfreport tag supports advanced PDF encryption options. For more information, see CFML Reference and Using advanced PDF options.

For information on report preview, see Previewing reports.

To display a report using the cfreport tag:

  1. Create a report, with or without an internal query.
  2. Create a CFM page and add a cfreport tag that invokes the report. If the report does not use an internal query, you must also populate a query and pass it using the query attribute. If the report uses an internal query and you use the query attribute, the passed query overrides the internal query.
    <cfquery name="northwindemployees" datasource="localnorthwind">
    SELECT EmployeeID, LastName, FirstName, Title, City, Region, Country
        FROM Employees
        ORDER BY Country, City
</cfquery>

<CFREPORT format="PDF" template="EmpReport.cfr"
   query="#northwindemployees#" />
  3. Open a browser and display the CFM page.

    ColdFusion MX generates the report.

    Tip: ColdFusion MX does not render text that occurs before or after the cfreport tag.

To display a CFR file in a browser:

  1. Create a report that uses an internal query and does not use input parameters.
  2. Open a browser and display the CFR file.

    ColdFusion MX generates the report.

To save a report to a file:

  1. Create a report, with or without an internal query.
  2. Create a CFM page and add a cfreport tag that invokes the report. Optionally pass a query attribute, as described in the previous procedure. Include a filename attribute that specifies the fully qualified name of the file to be created, as the following example shows:
    <CFREPORT format="PDF" template="emppicture.cfr"
  filename="#GetDirectoryFromPath(GetTemplatePath())#/emppicture.pdf"
  overwrite="yes"/>

    Tip: Use the .pdf extension for PDF output format, the .swf extension for FlashPaper output format, and the .xls extension for Excel format.

  3. Open a browser and display the CFM page.

    ColdFusion MX generates the report, saves the file, and displays an empty page.

To disable browser display of the CFR file:

  1. Open the Report Properties dialog box by selecting Report > Report Properties from the menu bar.
  2. Clear the Allow Direct .cfr Browser Invocation check box.
  3. Click OK.


Using input parameters to pass variables and other data at runtime

Input parameters are data fields that you pass to the report at runtime. You can place input parameters directly on a report band or you can use them as input to a calculated field.

Define input parameters in the same manner as query fields. You can specify a default value that ColdFusion uses when there is no corresponding parameter. For more information on defining input parameters, see Defining, modifying, and using fields and input parameters.

You use input parameters in the following ways:

  • Through the cfreportparam tag Input parameters must correspond, by name, to cfreportparam tags embedded in the cfreport invocation. For example, if you define an input parameter named ReportTime, you pass a cfreportparam tag with a name attribute set to ReportTime, as the following example shows:
    <cfreport format="PDF" template="FourthReport.cfr" query="#coursedept#">
   <cfreportparam name="ReportTime" value="#DateFormat(Now())#, #TimeFormat(Now())#">
</cfreport>
  • Subreport parameters When a subreport requires information from a main report, you define subreport parameters in the main report and corresponding input parameters in the subreport. For more information, see Using subreports.

For information on dynamically populating input parameters at runtime, see Advanced query mode.


Configuring RDS

You must configure one RDS server for each ColdFusion MX server for which you define reports. After you configure an RDS server, you can use the Query Builder to access data sources that you defined in the associated ColdFusion MX server, and select database columns for use as query fields in a report.

To add an RDS server:

  1. Open the Preferences dialog box by selecting Edit > Preferences from the menu bar.
  2. Click Server Connection.
  3. Click the plus sign (+) next to the drop-down list in the upper-left corner of the dialog box.

    The Configure RDS Server dialog box appears.

  4. Specify the following information:

    Description A name for the server connection. This name appears in the drop-down list on the left side of the Query Builder.

    Host name The host on which ColdFusion runs. Type localhost or an IP address.

    Port Web server port number. Accept the default port (80) or enter the port number of the ColdFusion server’s built-in web server (8500 is the default).

    Context Root (J2EE configuration only) Specifies the context root (if any) for the ColdFusion web application.

    Use Secure Sockets Layer Select this option if needed for SSL security.

    User Name Not applicable to ColdFusion RDS.

    Password RDS password. You set this password in the ColdFusion MX Administrator.

    Tip: Do not confuse the RDS password with the ColdFusion MX Administrator password, which you also manage through the ColdFusion MX Administrator.

    Prompt for password Specifies whether to prompt for an RDS password each time you use the Query Builder. If you select this option, leave the User Name and Password fields blank.

  5. Click OK.

To designate a default RDS server:

  1. Open the Preferences dialog box by selecting Edit > Preferences from the menu bar.
  2. Click Server Connection.
  3. Select an RDS server from the Preferred RDS Server drop-down list.
  4. Click OK.

    The Report Builder automatically connects to the specified server when you display the Query Builder or Chart Wizard.


Using the Report Creation Wizard

You can use the Report Creation Wizard to quickly start creating most types of reports. The wizard steps you through the report creation process through the following panels:

Panel

Description

Query Builder

Creates the SQL statement used for database access. You can type a SQL statement manually in the bottom pane or let the Query Builder create the SQL statement by using the data source browser to choose the data source, tables, and columns for the report. You can also use the Advanced Query Builder to create a query using CFML. For more information on using the Query Builder, see Using the Query Builder.

Define Query Fields

Lets you define query fields through the following ways:

Query Builder Automatically creates query fields for all columns retrieved by basic SQL. The Report Builder does not define fields automatically for advanced queries.

Importing fields from an existing report By importing query fields from an existing report.

Manually By creating them manually.

You also use the Define Query Fields panel to specify whether query fields appear on a report band.

For more information on query fields, see Defining, modifying, and using fields and input parameters.

Define Report Grouping

Lets you specify which query fields, if any, are used for group breaks.

The Report Builder does not automatically group data. You must ensure that the SQL used for retrieve the result set is already grouped in the appropriate order.

For more information on grouping, see Grouping and group breaks.

Report Layout

Lets you choose one of several report layout options. The layout options, which differ depending on the number of fields in the report and on whether or not the report uses grouping.

You also use the Report Layout panel to specify whether the report uses portrait or landscape orientation.

Report Style

Lets you further customize the appearance of the report through the following options:

Style Includes data and labels only, or include predefined headings.

Numerical totals Automatically creates column totals for all numerical fields.

Column specifications Controls the number of columns, and the spacing between columns.

Report Theme

Lets you specify a color scheme and whether the report header prints on a page by itself.

Report Name

Lets you specify the following:

Report header The report header automatically includes a text field for company name.

Page header The page header automatically includes the date.

Page footer The page footer automatically includes the page number.

For more information on the Report Creation Wizard and Report Creation Wizard panels, see Report Builder online Help.

The Report Creation Wizard takes the information that you enter into these panels and creates a report. In some cases, this report will have everything you need. However, in most cases, you will continue to make modifications. In particular, the Report Creation Wizard does not define the following:

Calculated fields For more information, see Defining, modifying, and using fields and input parameters.

Input parameters For more information, see Defining, modifying, and using fields and input parameters.

Charts For more information, see Using charts.

Subreports For more information, see Using subreports.


Using the Query Builder

You use the Query Builder to define the SQL statement that retrieves the result set used by a report. The following image shows the parts of the Query Builder interface:

Parts of the Query Builder interface

You use these parts, called panes, as follows:

Database pane Displays a list of data sources for an RDS server. Expand the data sources to display a list of tables in the related database. To use a table, double-click it or drag it to the Table pane. If you have selected a data source, you can also select a table by right-clicking on the Table pane.

Table pane Displays columns in the tables you selected. Double-click a column to add it to the Properties pane and to the SELECT statement that is displayed in the SQL pane.

Note: The Table pane can only browse data. You cannot modify data or add new records here. Also, views are available only in databases supporting the creation of views or tables stored as queries.

Properties pane Displays selected columns. Use this pane to specify additional criteria, such as ALIAS names, sorting, sort order, and selection criteria for the WHERE clause.

SQL pane Displays the SQL statement as it is being constructed. The SQL pane does not support reverse editing, so any changes that you make in this pane are not made in the Properties pane or the Table pane.

Query type Controls whether you create a SQL statement through the Query Builder or by creating a query using CFML (also known as advanced query mode). To create a query using CFML, click Advanced.

The Query Builder uses RDS to access database schema information through the data sources defined to a ColdFusion MX server. For more information, see Configuring RDS.

The Query Builder automatically defines query fields for the columns returned by your SQL statement. Because the Query Builder executes the SQL statement and analyzes the columns that it returns, automatic query field definition applies to both stored procedures and SELECT statements.

Note: The Query Builder does not create query fields automatically for queries generated using advanced query mode.

Not all DBMSs support all SQL syntax. Ensure that your DBMS supports the SQL statements generated by the Query Builder. For example, the Microsoft Access and Microsoft Access with Unicode drivers do not support FULL OUTER JOIN clauses.

To select an RDS server:

  • Select the RDS server from the drop-down list in the upper left corner of the Query Builder.

Caution: The Query Builder clears the current SELECT statement when you select a new RDS server.

You can define RDS settings for multiple ColdFusion servers. For more information, see Configuring RDS.

To select a data source in the current RDS server:

  • Select the data source name in the Data Source Used by the Query drop-down list at the upper edge of the Query Builder.

Caution: The Query Builder clears the current SQL statement when you select a new data source,

For more information on creating SQL statements with the Query Builder, see "Using the Query Builder" in Report Builder online Help.

To include cfquery attributes in the SQL statement:

  1. Use the Query Builder to create a SQL statement.
  2. Click the <cfquery> Attributes button.

    The CF Query Options dialog box appears.

  3. Specify cfquery attributes through dialog box fields.
  4. Click OK.


Using CFML in reports

CFML is the scripting language for the Report Builder. By leveraging CFML, you can easily create reports that select and format data to meet your needs. You can use CFML in the following areas of the Report Builder:

  • Advanced query mode
  • Report functions
  • Expressions

Advanced query mode

In some cases, you may want to use create a complex query, reuse an existing query, or encapsulate additional CFML processing as part of query creation for the report. In this case, you can use advanced query mode to create CFML that returns a query. When you click the Advanced button at the top of the Query Builder, the Report Builder displays a text entry area in which you can enter CFML that generates a query. ColdFusion executes this tag at report execution time and passes the query result set to the report.

Note: When you use advanced query mode, the Query Builder does not create query fields automatically. You must create the associated query fields manually.

The CFML used in advanced query mode must include a query object whose name matches that in the Variable containing query object field. You can use any CFML tag that returns a query object or the QueryNew function. The CFML can use multiple query objects, but can only return one.

Note: If you set an empty variable (for example, <cfset name="">), the Report Builder throws a Report data binding error.

This example CFML uses the cfhttp tag to retrieve a query:

<cfhttp url="http://quote.yahoo.com/download/quotes.csv?Symbols=csco,jnpr&format=sc1l1&ext=.csv"
method="GET"
name="qStockItems"
columns="Symbol,Change,LastTradedPrice"
textqualifier=""""
delimiter=","
firstrowasheaders="no">

Another possible use of advanced query mode is to test for passed parameters in the URL or FORM scopes and use these parameters to retrieve data, as the following example shows:

<!--- First look for URL parm.
      URL overrides cfreportparam. --->
<cfif isDefined("url.deptidin")>
  <cfset param.deptidin = url.deptidin>
</cfif>

<!-- Then look for FORM parm. Overrides URL parm. --->
<cfif isDefined("form.deptidin")>
  <cfset param.deptidin = form.deptidin>
</cfif>

<cfquery name="CFReportDataQuery" datasource="cfdocexamples">
SELECT    LastName, FirstName, Dept_ID
FROM      Employee
WHERE     (Dept_ID = #param.deptidin#)
</cfquery>


Report functions

Report functions are user-defined CFML functions that you code using the Report Function Editor and invoke in report fields. You can use them to format data (such as concatenating and formatting all the field that make up an address), to retrieve data, and for many other purposes.

To create a report function:

  1. Select Report > Report Functions from the menu bar.

    The Report Function Editor displays.

  2. Click the plus sign to add a new report function.

    The Add Report Function dialog box displays.

  3. Specify a name and click OK.
  4. The Report Function Editor places a cfreturn tag in the text entry area.
  5. Code the function. This is a ColdFusion user-defined function so all UDF rules and features are available for use. The following example show a report function that concatenates address fields:
    <cfargument name="Name" required="yes"/>
<cfargument name="Address1" required="yes"/>
<cfargument name="Address2" required="yes"/>
<cfargument name="City" required="yes"/>
<cfargument name="State" required="yes"/>
<cfargument name="Zip" required="yes"/>

<cfset variables.CRLF = Chr(13) & Chr(10)>
<cfset variables.ResultVar="">

<cfif Trim(arguments.Name) NEQ "">
   <cfset variables.ResultVar='#arguments.Name#'>
</cfif>
<cfif Trim(arguments.Address1) NEQ "">
   <cfif variables.ResultVar NEQ "">
      <cfset variables.ResultVar='#variables.ResultVar & variables.CRLF#'>
   </cfif>
   <cfset variables.ResultVar='#variables.ResultVar & arguments.Address1#'>
</cfif>
<cfif Trim(arguments.Address2) NEQ "">
   <cfif variables.ResultVar NEQ "">
      <cfset variables.ResultVar='#variables.ResultVar & variables.CRLF#'>
   </cfif>
   <cfset variables.ResultVar='#variables.ResultVar & arguments.Address2#'>
</cfif>
<cfif variables.ResultVar NEQ "">
   <cfset variables.ResultVar='#variables.ResultVar & variables.CRLF#'>
</cfif>

<cfset variables.ResultVar='#variables.ResultVar & arguments.City & ", " & arguments.State & " " & arguments.Zip#'>

<cfreturn variables.ResultVar>
  6. Click OK when you are finished.

To use a report function:

  1. Place a dynamic field on the appropriate report band.

    The Add Field dialog box displays.

  2. Specify Manually Entered Expression and click OK.

    The Expression Builder displays.

  3. Specify "report.functionname".
  4. Click OK.

Expressions and the Expression Builder

Many elements of the Report Builder (including query fields, calculated fields, input parameters, images, and report object attributes) are single operand ColdFusion expressions. Because these elements are expressions, you can manipulate them with CFML functions.

The Expression Builder is a graphical interface that lets you quickly apply CFML functions to Report Builder elements. Uses for the Expression Builder include the following:

  • Many of the report object attributes (such as PrintWhen) accept expressions, which you can associate with query parameters, input parameters, or ColdFusion page variables. You can tie report attributes and columns to display based on runtime data or user preference.
  • Concatenating fields
  • Formatting fields
  • Calculated fields
  • Accessing and displaying ColdFusion page variables and scopes

For information on using the Expression Builder, see Report Builder online Help.

For more information on expressions, see Using Expressions and Number Signs.


Using charts

Charts can help clarify large or complex data sets. The Report Builder lets you place a chart in any report band and supports many types of charts.

To add a chart to a report, you use the Chart Wizard, which steps you through the chart building process. The Chart Wizard, which is fully integrated with the Query Wizard to facilitate database-driven charts, helps you define the chart type, the data used for the report and other formatting options.

Tip: As you use the Chart Wizard to choose and define the various aspects of a given chart, the Report Builder uses RDS to generate chart images in real time. However, the data shown in these chart images is not real.

The Chart Wizard includes the following panels:

  • Chart Types Select the chart type (for example, bar) and sub-type (for example, 3D-stacked).
  • Chart Series Select the data for the series. When you add a series, the Report Builder lets you hard-code series data or open the Query Builder to populate the series using a database query.
  • Chart Formatting Specifies title & series, general appearance, 3D appearance, lines & markers, and font.

Tip: The data you specify through the Chart Wizard corresponds to the attributes specified in the cfchart, cfchartseries, and cfchartdata tags. For more information on these tags, refer to CFML Reference and ColdFusion MX Developer’s Guide.

For complete information on ColdFusion MX charting capabilities, see Creating Charts and Graphs. For more information on charting using the Report Builder, see Report Builder online Help.


Using subreports

Subreports let you nest a report within your report. The data you display in a subreport is typically related to the data in the main report and you enable this by passing one or more subreport parameters to the subreport. However, the data displayed in a subreport can also be unrelated to the data in the main report.

Reasons to use subreports including the following:

  • You wish to avoid complex SQL, such as a RIGHT OUTER JOIN.
  • Your report requires data from multiple databases.

The following figure illustrates the use of subreport parameters and the relationship between a report and a subreport:

This is a picture of the feature being described.

Note: Although the Report Builder supports multiple levels of nesting, it displays one level of nesting only.

For additional information on subreports, see Report Builder online Help.

Defining a subreport

You can define a subreport and include it in a report, or you can define it as part of inserting the subreport in the main report.

However, regardless of how you define it, a subreport has the following characteristics:

  • Data displayed in the detail band only. A subreport uses no header or footer bands.
  • If the subreport is related to the main report, it must include an internal query that uses a SELECT statement with a WHERE clause specifying the name of the input parameter used in the main report’s Subreport Expression property.

Adding an existing subreport to a report

If you have already defined a subreport, you add it to the main report and define subreport parameters, as necessary.

To add an existing subreport to a report:

  1. Define or open your main report.
  2. Click the Subreport icon in the toolbox.
  3. Drag an area for the subreport in the desired report band.

    The Subreport Source panel appears.

  4. Select From an Existing Report, specify the subreport, and click Next.

    The Report to Subreport Parameter Binding panel appears.

  5. Select the fields in the main report that correspond to fields in the subreport and click Next.

    The Finish Subreport Setup panel appears.

  6. Click Finish.

    The Report Builder adds the subreport to the main report, saving the report to subreport mappings as subreport parameters.

  7. To modify subreport parameter settings, select the subreport and click on Subreport Parameters in the Properties sheet.

Adding a new subreport to a report

If you are certain of the data required for a subreport, you can define a new subreport while adding it to the main report.

To add a new subreport to a report:

  1. Define or open your main report.
  2. Click the Subreport icon in the toolbox.
  3. Drag an area for the subreport in the desired report band.

    The Subreport Source panel appears.

  4. Select As a New Report and click Next.

    The Define Query Fields panel appears.

  5. Click Query Builder.

    The Query Builder appears.

  6. Select the tables and columns for the subreport.
  7. Specify a WHERE clause for the report by using the Condition and Criteria columns for the key columns.

    Specify WHERE for Condition and either ='#CFVariable#' (string column) or =#CFVariable# (numeric column) for Criteria, and then overtype CFVariable with the name of the input parameter for the subreport (you define the input parameter name later in the procedure.)

  8. Click Save.
  9. Click Next.

    The Define Report Grouping panel appears.

  10. Specify grouping fields, if appropriate for your subreport.
  11. Click Next.

    The Report Layout panel appears.

  12. Specify Free Form or Grid. Then click Next.

    The Report Style panel appears.

  13. Specify Only Detail Band and click Next.

    The Report Theme panel appears.

  14. Specify a color scheme and click Next.

    The Report Name panel appears.

  15. Specify headings, as appropriate, and click Next.

    The Subreport Binding panel appears.

  16. For each parameter required by the subreport, specify the following:
    • Parameter name.
    • Associated value from the main report (click the drop-down list box).
    • Data type.
  17. Click Next.

    The Subreport Filename panel appears.

  18. Specify a fully qualified filename for the subreport.
  19. Click Next.

    The Finish Subreport Setup panel appears.

  20. Click Finish.
  21. Modify the subreport, as necessary.

    The Report Builder adds the subreport to the main report.

Modifying subreport settings

The Report Builder lets you change subreport name and modify subreport parameters in a main report.

To modify subreport settings:

  1. Click the subreport element in the main report.

    Subreport settings display in the Properties sheet.

  2. To change the subreport, modify Subreport Expression.
  3. To modify subreport parameters:
    1. Click the Subreport Parameters property.
    2. Click the ... button.

      The Subreport Parameters dialog box appears.

    3. Add, modify, or delete subreport parameters.
    4. Click OK.


Font management with printable reports

Ideally, reports should achieve a consistent look across all client platforms and all browsers. ColdFusion MX handles this automatically for graphics and images, using the size specifications in the report definition. However, potential differences in font availability across browsers, browser versions, languages, and platforms can affect the font display for your report. There are a variety of factors that you must understand to ensure consistent report display.

Embedded fonts

You can ensure consistent report display by embedding fonts. However, reports with embedded fonts have a larger file size.

Output format

The FlashPaper and PDF output formats handle embedded fonts differently.

FlashPaper FlashPaper always embeds fonts, which ensures that reports always display appropriately.

PDF PDF reports can optionally embed fonts, however, if your report doesn't use embedded fonts, you must ensure that the fonts are available on the client computers.

Font availability on the server computer and the client computer

ColdFusion MX has different requirements for rendering the fonts in a report, depending on where the fonts are located.

Server computer For all formats, the fonts used in a report must reside on the computer that runs ColdFusion MX. ColdFusion MX requires these fonts to render the report accurately. ColdFusion MX automatically locates Acrobat built-in fonts and fonts stored in typical font locations (such as the Windows\fonts directory). However, if your server has additional fonts installed in non-standard locations, you must register them with the ColdFusion MX Administrator so that the cfdocument and cfreport tags can locate and render PDF and FlashPaper reports.

Client computer If your PDF report does not embed fonts, the fonts reside on the client computer to ensure consistent report display.

Mapping logical fonts to physical fonts

If you are using Java logical fonts, such as serif, sans serif, or monospaced, ColdFusion MX maps these fonts to physical fonts using specifications in the cf_root/lib/cffont.properties file (on the multiserver or J2EE configuration, this is the cf_webapp_root/WEB-INF/cfusion/lib directory). You can modify these mappings, if necessary. Also, if you are using an operating system whose locale is not English, you can create a locale-specific mapping file by appending .java-locale-code to the filename. If ColdFusion MX detects that it is running on a non-English locale, it first checks for a cffont.properties.java-locale-code file. For example, on a computer that uses the Chinese locale, name the file cffont.properties.cn. For more information on Java locale codes, see the Sun website.

Tip: The ColdFusion MX install includes a cffont.properties.ja file for the Japanese locale.

This discussion applies to both cfdocument and cfreport. For more information, see Report Builder online Help.


Creating reports with Crystal Reports (Windows only)

When running on Windows, the cfreport tag also supports the execution of reports created using Crystal Reports version 9 or 10.

Note: When you install Crystal Reports, you must select the Enable export to HTML and Enable export to Disk options. These options are not enabled by default, so you must use the Custom Install option.

To invoke a Crystal Report report definition using the cfreport tag:

  1. Create a report definition in Crystal Reports.
  2. Create a CFM page and add a cfreport tag that invokes the Crystal Reports report definition. The following example shows the cfreport tag invoking a Crystal Reports report definition and passing a filter condition:
    <cfreport report = ’/reports/monthlysales.rpt’>
     {Departments.Department} = ‘International’
</cfreport>
  3. Open a browser and display the CFM page.

Tip: ColdFusion MX uses COM to call Craxdrt9.dll for Crystal Reports version 9, and Craxdrt.dll for Crystal Reports version 10. If you have problems with the cfreport tag, ensure that these DLLs are registered and, if not, use regsvr32 to register them (the default location for these DLLs is C:\Program Files\Crystal Decisions\Report Designer Component\).

For complete information on defining reports in Crystal Reports, see the Crystal Reports documentation.
Previous


Using the Flash Remoting Service

Using the Macromedia Flash Remoting service of Macromedia ColdFusion MX 7, ColdFusion MX developers can work together with Macromedia Flash MX 2004 designers to build dynamic Flash user interfaces for ColdFusion MX applications.

This chapter describes how ColdFusion MX interacts with Flash Remoting for Flash MX 2004 ActionScript 2.0. For a complete description of Flash Remoting capabilities, including how ColdFusion MX interacts with Flash Remoting, see Using Flash Remoting MX 2004 and Flash Remoting ActionScript Dictionary in Flash Help. You can also access the Flash Remoting documentation on the Flash Remoting Developer Center at www.macromedia.com/devnet/mx/flashremoting.

Contents

About using the Flash Remoting service with ColdFusion

Configuring the Flash Remoting Gateway

Using the Flash Remoting service with ColdFusion pages

Using Flash with CFCs

Using the Flash Remoting service with ColdFusion Java objects

Handling errors with ColdFusion and Flash
Next


About using the Flash Remoting service with ColdFusion

Using the Flash Remoting service of ColdFusion MX, ColdFusion developers can work together with Flash MX 2004 designers to build Flash user interfaces (UIs) for ColdFusion applications. Building Flash UIs requires the separation of UI code from business logic code. You build user interface controls in Flash MX, and you build the business logic in ColdFusion MX.

The following is a simplified representation of the relationship between Flash and ColdFusion:

Simplifed representation of the relationship between Flash and ColdFusion

Planning your Flash application

When you are planning ColdFusion MX application development with Flash UIs, remember the importance of separating display code from business logic. Separating display code from business logic enables your ColdFusion applications to interact with multiple client types, such as Flash applications, web browsers, and web services.

When you build ColdFusion MX applications for multiple clients, your ColdFusion pages and components return common data types, including strings, integers, query objects, structures, and arrays. Clients that receive the results can process the passed data according to the client type, such as ActionScript with Flash, or CFML with ColdFusion MX.

To use the Macromedia Flash Remoting service with Macromedia ColdFusion MX, you build ColdFusion pages and components or deploy Java objects. In ColdFusion pages, you use the Flash variable scope to interact with Flash applications. ColdFusion components (CFCs) natively support Flash interaction. The public methods of Java objects are also available to the Flash Remoting service.

The Flash Remoting ActionScript API has been updated to comply with ActionScript 2.0. The ActionScript 2.0 version of the API consists of the following significant features:

Flash Remoting MX 2004 ActionScript 2.0 API Features

Enforcement of strict data typing, which requires you to declare the data types of variables and prohibits you from assigning different types of data to them.

Enforcement of case sensitivity, which means that myvar and myVar are two different variables, though they were considered the same variable with different spellings in ActionScript 1.0.

A new Service class, which lets you create a gateway connection and at the same time obtain a reference to a service and its methods. It includes the connection property, which returns the connection and also lets you set credentials for authorization on the remote server.

Note: The NetServices class is still supported but has been deprecated in favor of the new Service and Connection classes

A new Connection class that helps you create and use Flash Remoting connections.

Note: The Connection class supersedes the former NetConnection class.

A new PendingCall object returned on each call to a service method that is invoked using the Service object. The PendingCall object contains the responder property, which you use to specify the methods to handle the results of the service call.

A new RelayResponder class, which specifies the methods to which the result and fault outcomes of a service call are relayed.

A RecordSet object that contains new properties (columnNames, items, and length), new methods (clear(), contains(), editField(), getEditingData(), getIterator(), getLocalLength(), getRemoteLength(), isEmpty(), and sortItems()), and the new modelChanged event.

For more information on the ActionScript 2.0 Flash Remoting API, see Flash Remoting ActionScript Dictionary Help.

The remaining sections in this chapter explain how ColdFusion MX interacts with Flash Remoting applications.


Configuring the Flash Remoting Gateway

The following parameters in the ColdFusion web.xml file point the Flash Remoting gateway to the gateway-config.xml file.

<init-param>
    <param-name>gateway.configuration.file</param-name>
    <param-value>/WEB-INF/gateway-config.xml</param-value>
        </init-param>
<init-param>
    <param-name>whitelist.configuration.file</param-name>
    <param-value>/WEB-INF/gateway-config.xml</param-value>
</init-param>
<init-param>
    <param-name>whitelist.parent.node</param-name>
    <param-value>gateway-config</param-value>
</init-param>

Both the web.xml file and the gateway-config.xml file are located in the WEB-INF directory of your ColdFusion server. As a general rule, there is no need to change these web.xml settings.

ColdFusion MX 7 configures Flash gateways differently from previous ColdFusion MX releases. Parameters that worked prior to this release are no longer supported, and you specify all configuration parameters in the gateway-config.xml file. Also, the Flash gateway now supports a whitelist, which specifies which remote sources can be accessed through the gateway. The two web.xml entries that identify the whitelist should specify your gateway-config.xml file and gateway-config as the parent node.

You can modify the gateway-config.xml file to configure service adapters, add service names to the whitelist, change the logging level, and specify how the gateway handles case sensitivity.

You can configure gateway features in the gateway-config.xml file as follows:

Feature

Description

service adapters

By default, the PageableResultSetAdapter, the ColdFusionAdapter, the CFCAdapter (for ColdFusion components), and the CFSSASAdapter (for server-side ActionScript) adapters are enabled in ColdFusion.

You can also enable the JavaBeanAdapter, JavaAdapter, EJBAdapter, ServletAdapter, and CFWSAdapter (for web services) by removing their enclosing comment symbols (<!-- and -->). The following service adapter tags are defined as the default tag values:

<service-adapters>

  <adapter>flashgateway.adapter.resultset.PageableResultSetAdapter

  </adapter>

  <adapter>coldfusion.flash.adapter.ColdFusionAdapter</adapter>

  <adapter>coldfusion.flash.adapter.CFCAdapter</adapter>

  <adapter>coldfusion.flash.adapter.CFSSASAdapter</adapter>

  <!-- <adapter type="stateful-class">flashgateway.adapter.java.

        JavaBeanAdapter</adapter> -->

  <!-- <adapter type="stateless-class">flashgateway.adapter.java.

        JavaAdapter</adapter> -->

  <!-- <adapter type="ejb">flashgateway.adapter.java.EJBAdapter

       </adapter> -->

  <!-- <adapter type="servlet">flashgateway.adapter.java.ServletAdapter

       </adapter> -->

  <!-- <adapter>coldfusion.flash.adapter.CFWSAdapter</adapter> -->

</service-adapters>

security

You can edit security settings in child tags of the <security> tag.

In the <login-command> tag, you can set the flashgateway.security.LoginCommand implementation for performing local authentication on a specific application server. By default, the <login-command> tag is set to the following values:

<login-command>

  <class>flashgateway.security.JRunLoginCommand</class>

  <server-match>JRun</server-match>

</login-command>

In the <show-stacktraces> tag, you can enable stack traces. Stack traces are useful for debugging and product support, but they should not be sent to the client in production mode because they can expose internal information about the system. The following <show-stacktraces> tag is the default tag:

<show-stacktraces>false</show-stacktraces>

The <whitelist> tag specifies which remote sources can be accessed through the gateway. The * character can be used as a wildcard to imply ALL matches. The following <whitelist> tag shows the default value:

<whitelist>

  <source>*</source>

</whitelist>

When you deploy your application, ensure that you change this setting so that it specifies only the services that the gateway needs to access to run your application. Remember that for ColdFusion based services, directories are treated as "packages" and thus you specify a period delimited path from the web root to the directory or file containing the services you will allow access to. An asterisk wildcard allows access to all services in a particular directory. You can have multiple <source> tags.

The following whitelist allows access to the webroot/cfdocs/exampleapps/ directory, which includes the flash1 through flash5 Flash Remoting example directories. It also allows access to a webroot/BigApp/remoting directory and its children.

<whitelist>
  <source>cfdocs.exampleapps.*</source>
  <source>BigApp.remoting.*</source>
</whitelist>

logger level

You can set the level of logging between None, Error, Info, Warning, and Debug. The following tag is the default logger level tag:

<logger level="Error">coldfusion.flash.ColdFusionLogger</logger>

redirect URL

In the <redirect-url> tag, you can specify a URL to receive HTTP requests that are not sent with AMF data. By default, the <redirect-url> tag is set to {context.root}, which is the context root of the web application:

<redirect-url>{context.root}</redirect-url>

case sensitivity

The <lowercase-keys> tag specifies how the gateway handles case sensitivity. ActionScript 1.0 and ColdFusion use case insensitive data structures to store associative arrays, objects and structs. The Java representation of these data types requires a case-insensitive Map, which the gateway achieves by forcing all keys to lowercase.

ActionScript 2.0 is case sensitive and requires a <lowercase-keys> tag value of false.

The following <lowercase-keys> tag is the default tag:

<lowercase-keys>true</lowercase-keys>


Using the Flash Remoting service with ColdFusion pages

When you build a ColdFusion page that interacts with a Flash application, the directory name that contains the ColdFusion pages translates to the service name that you call in ActionScript. The individual ColdFusion page names within that directory translate to service functions that you call in ActionScript.

Note: Flash Remoting cannot interact with virtual directories accessed through a ColdFusion mapping.

In your ColdFusion pages, you use the Flash variable scope to access parameters passed to and from a Flash application. To access parameters passed from a Flash application, you use the parameter name appended to the Flash scope or the Flash.Params array. To return values to the Flash application, use the Flash.Result variable. To set an increment value for records in a query object to be returned to the Flash application, use the Flash.Pagesize variable.

The following table shows the variables contained in the Flash scope:

Variable | Description | For more information
Flash.Params | Array that contains the parameters passed from the Flash application. If you do not pass any parameters, Flash.params still exists, but it is empty. | See Accessing parameters passed from Flash.
Flash.Result | The variable returned from the ColdFusion page to the Flash application that called the function. Note: Because ActionScript performs automatic type conversion, do not return a Boolean literal to Flash from ColdFusion. Return 1 to indicate true, and return 0 to indicate false. | See Returning results to Flash.
Flash.Pagesize | The number of records returned in each increment of a record set to a Flash application. | See Returning records in increments to Flash.

The following table compares the ColdFusion MX data types and their ActionScript equivalents:

ActionScript data type | ColdFusion MX data type
Number (primitive data type) | Number
Boolean (primitive data type) | Boolean (0 or 1)
String (primitive data type) | String
ActionScript Object | Structure
ActionScript Object (as the only argument passed to a service function) | Arguments of the service function. ColdFusion pages (CFM files): flash variable scope, ColdFusion components (CFC files): named arguments
Null | Null (Asc() returns 0, which translates to not defined)
Undefined | Null (Asc() returns 0, which translates to not defined)
Ordered array Note: ActionScript array indexes start at zero (for example: my_ASarray[0]). | Array Note: ColdFusion array indexes start at one (for example: my_CFarray[1]).
Named (or associative) array | Struct
Date object | Date
XML object | XML document
RecordSet | Query object (when returned to a Flash application only; you cannot pass a RecordSet from a Flash application to a ColdFusion MX application)

Also, remember the following considerations regarding data types:

  • If a string data type on the server represents a valid number in ActionScript, Flash can automatically cast it to a number if needed.
  • To return multiple, independent values to the Flash application, place them in a complex variable that converts to a Flash Object, Array, or Associative Array, that can hold all of the required data. Return the single variable and access its elements in the Flash application.

For a complete explanation of using Flash Remoting data in ActionScript, see Using Flash Remoting MX 2004 Help.

Accessing parameters passed from Flash

To access variables passed from Flash applications, you append the parameter name to the Flash scope or use the Flash.Params array. Depending on how the values were passed from Flash, you refer to array values using ordered array syntax or structure name syntax. Only ActionScript objects can pass named parameters.

For example, if you pass the parameters as an ordered array from Flash, array[1] references the first value. If you pass the parameters as named parameters, you use standard structure-name syntax like params.name.

You can use most of the CFML array and structure functions on ActionScript collections. However, the StructCopy CFML function does not work with ActionScript collections. The following table lists ActionScript collections and describes how to access them in ColdFusion MX:

Collection

ActionScript example

Notes

Strict array

var myArray:Array = new Array();
myArray[0] = "zero";
myArray[1] = "one";
myService.myMethod(myArray);

The Flash Remoting service converts the Array argument to a ColdFusion MX array. All CFML array operations work as expected.

<cfset p1=Flash.Params[1][1]>

<cfset p2=Flash.Params[1][2]>

Named or associative array

var myStruct:Array = new Array();
myStruct["zero"] = "banana";
myStruct["one"] = "orange";
myService.myMethod(myStruct);

Named array keys are not case-sensitive in ActionScript.

<cfset p1=Flash.Params[1].zero>

<cfset p2=Flash.Params[1].one>

Mixed array

var myMxdArray:Array = new Array();
myMxdArray["one"] = 1;
myMxdArray[2] = true;

Treat this collection like a structure in ColdFusion MX. However, keys that start with numbers are invalid CFML variable names. Depending on how you attempt to retrieve this data, ColdFusion MX might throw an exception. For example, the following CFC method throws an exception:

<cfargument name="ca" type="struct">

<cfreturn ca.2>

The following CFC method does not throw an exception:

<cfargument name="ca" type="struct">

<cfreturn ca["2"]>

Using an ActionScript object initializer for named arguments

myService.myMethod
({ x:1, Y:2, z:3 });

This notation provides a convenient way of passing named arguments to ColdFusion pages. You can access these arguments in ColdFusion pages as members of the Flash scope:

<cfset p1 = Flash.x>

<cfset p2 = Flash.y>

<cfset p3 = Flash.z>

Or, you can access them as normal named arguments of a CFC method.

The Flash.Params array retains the order of the parameters as they were passed to the method. You use standard structure name syntax to reference the parameters; for example:

<cfquery name="flashQuery" datasource="cfdocexamples">
    SELECT ItemName, ItemDescription, ItemCost
    FROM tblItems
    WHERE ItemName EQ '#Flash.paramName#'
</cfquery>

In this example, the query results are filtered by the value of Flash.paramName, which references the first parameter in the passed array. If the parameters were passed as an ordered array from the Flash application, you use standard structure name syntax; for example:

<cfset Flash.Result = "Variable 1:#Flash.Params[1]#, Variable 2: #Flash.Params[2]#">

Tip: ActionScript array indexes start at zero. ColdFusion array indexes start at one.

Returning results to Flash

In ColdFusion pages, only the value of the Flash.Result variable is returned to the Flash application. For more information about supported data types between ColdFusion MX and Flash, see the data type table in Using the Flash Remoting service with ColdFusion pages. The following procedure creates the service function helloWorld, which returns a structure that contains simple messages to the Flash application.

To create a ColdFusion page that passes a structure to a Flash application:

  1. Create a folder in your web root, and name it helloExamples.
  2. Create a ColdFusion page, and save it as helloWorld.cfm in the helloExamples directory.
  3. Modify helloWorld.cfm so that the CFML code appears as follows:
    <cfset tempStruct = StructNew()>
<cfset tempStruct.timeVar = DateFormat(Now ())>
<cfset tempStruct.helloMessage = "Hello World">

    In the example, two string variables are added to a structure; one with a formatted date and one with a simple message. The structure is passed back to the Flash application using the Flash.Result variable.

    <cfset Flash.Result = tempStruct>
  4. Save the file.

Remember, the directory name is the service address. The helloWorld.cfm file is a method of the helloExamples Flash Remoting service. The following ActionScript example calls the helloWorld ColdFusion page and displays the values that it returns:

import mx.remoting.*;
import mx.services.Log;
import mx.rpc.*;

// Connect to helloExamples service and create the howdyService service object
    var howdyService:Service = new Service(
            "http://localhost/flashservices/gateway",
            null,
            "helloExamples",
            null,
            null );
// Call the service helloWorld() method
var pc:PendingCall = howdyService.helloWorld();
// Tell the service what methods handle result and fault conditions
pc.responder = new RelayResponder( this, "helloWorld_Result", "helloWorld_Fault" );

function helloWorld_Result(re:ResultEvent)
{
    // Display successful result
    messageDisplay.text = re.result.HELLOMESSAGE;
    timeDisplay.text = re.result.TIMEVAR;
}

function helloWorld_Fault(fe:FaultEvent)
{
    // Display fault returned from service
    messageDisplay.text = fe.fault;
}

Note: Due to ActionScript's automatic type conversion, do not return a Boolean literal to Flash from ColdFusion. Return 1 to indicate true, and return 0 to indicate false.

Returning records in increments to Flash

ColdFusion MX lets you return record set results to Flash in increments. For example, if a query returns 20 records, you can set the Flash.Pagesize variable to return five records at a time to Flash. Incremental record sets let you minimize the time that a Flash application waits for the application server data to load.

To create a ColdFusion page that returns a incremental record set to Flash:

  1. Create a ColdFusion page, and save it as getData.cfm in the helloExamples directory.
  2. Modify getData.cfm so that the code appears as follows:
    <cfparam name="pagesize" default="10">
<cfif IsDefined("Flash.Params")>
    <cfset pagesize = Flash.Params[1]>
</cfif>
<cfquery name="myQuery" datasource="cfdocexamples">
    SELECT *
    FROM tblParks
</cfquery>
<cfset Flash.Pagesize = pagesize>
<cfset Flash.Result = myQuery>

    In this example, if a single parameter is passed from the Flash application, the pagesize variable is set to the value of the Flash.Params[1] variable; otherwise, the value of the variable is the default, 10. Next, a cfquery statement queries the database. After that, the pagesize variable is assigned to the Flash.Pagesize variable. Finally, the query results are assigned to the Flash.Result variable, which is returned to the Flash application.

  3. Save the file.

When you assign a value to the Flash.Pagesize variable, you are specifying that if the record set has more than a certain number of records, the record set becomes pageable and returns the number of records specified in the Flash.Pagesize variable. For example, the following code calls the getData() function of the CFMService and uses the first parameter to request a page size of 5:

import mx.remoting.*;
import mx.services.Log;
import mx.rpc.*;
// Connect to helloExamples service and create the CFMService service object
    var CFMService:Service = new Service(
            "http://localhost/flashservices/gateway",
            null,
            "helloExamples",
            null,
            null );
// Call the service getData() method
var pc:PendingCall = CFMService.getData(5);
// Tell the service what methods handle result and fault conditions
pc.responder = new RelayResponder( this, "getData_Result", "getData_Fault" );

function getData_Result(re:ResultEvent)
{
    // Display successful result
    DataGlue.bindFormatStrings(employeeData, re.result, "#PARKNAME#, #CITY#, #STATE#");
}
function getData_Fault(fe:FaultEvent)
{
    // Display fault returned from service
    trace("Error description from server: " + fe.fault.description);
}

In this example, employeeData is a Flash list box. The result handler, getData_Result, displays the columns PARKNAME, CITY, and STATE in the employeeData list box. After the initial delivery of records, the RecordSet ActionScript class assumes the task of fetching records. In this case, the list box requests more records as the user scrolls the list box.

You can configure the client-side RecordSet object to fetch records in various ways using the ResordSet.setDeliveryMode ActionScript function.


Using Flash with CFCs

CFCs require little modification to work with a Flash application. The cffunction tag names the method and contains the CFML logic, the cfargument tag names the arguments, and the cfreturn tag returns the result to the Flash application. The name of the CFC file (*.cfc) translates to the service name in ActionScript.

Note: For CFC methods to communicate with Flash applications, you must set the cffunction tag’s access attribute to remote.

The following example replicates the helloWorld function that was previously implemented as a ColdFusion page. For more information, see Using the Flash Remoting service with ColdFusion pages.

To create a CFC that interacts with a Flash application:

  1. Create a CFC and save it as flashComponent.cfc in the helloExamples directory.
  2. Modify the code in flashComponent.cfc so that it appears as follows:
    <cfcomponent name="flashComponent">
    <cffunction name="helloWorld" access="remote" returnType="Struct">
          <cfset tempStruct = StructNew()>
          <cfset tempStruct.timeVar = DateFormat(Now ())>
          <cfset tempStruct.helloMessage = "Hello World">
          <cfreturn tempStruct>
    </cffunction>
</cfcomponent>

    In this example, the helloWorld function is created. The cfreturn tag returns the result to the Flash application.

  3. Save the file.

The helloWorld service function is now available through the flashComponent service to ActionScript. The following ActionScript example calls this function:

import mx.remoting.*;
import mx.services.Log;
import mx.rpc.*;

// Connect to the Flash component service and create service object
    var CFCService:Service = new Service(
            "http://localhost/flashservices/gateway",
            null,
            "helloExamples.flashComponent",
            null,
            null );
// Call the service helloWorld() method
var pc:PendingCall = CFCService.helloWorld();
// Tell the service what methods handle result and fault conditions
pc.responder = new RelayResponder( this, "helloWorld_Result", "helloWorld_Fault" );

function helloWorld_Result(re:ResultEvent)
{
    // Display successful result
    messageDisplay.text = re.result.HELLOMESSAGE;
    timeDisplay.text = re.result.TIMEVAR;
}

function helloWorld_Fault(fe:FaultEvent)
{
    // Display fault returned from service
    messageDisplay.text = fe.fault;
}

In this example, the CFCService object references the flashComponent component in the helloExamples directory. Calling the helloWorld function in this example executes the function that is defined in flashComponent.

For ColdFusion components, the component file name, including the directory structure from the web root, serves as the service name. Remember to delimit the path directories with periods rather than backslashes.


Using the Flash Remoting service with ColdFusion Java objects

You can run various kinds of Java objects with ColdFusion MX, including JavaBeans, Java classes, and Enterprise JavaBeans. You can use the ColdFusion MX Administrator to add additional directories to the classpath.

To add a directory to ColdFusion classpath:

  1. Open the ColdFusion MX Administrator.
  2. In the Server Settings menu, click the Java and JVM link.
  3. Add your directory to the Class Path form field.
  4. Click Submit Changes.
  5. Restart ColdFusion.

When you place your Java files in the classpath, the public methods of the class instance are available to your Flash movie.

For example, assume the Java class utils.UIComponents exists in a directory in your ColdFusion classpath. The Java file contains the following code:

package utils;
public class UIComponents
{
    public UIComponents()
    {
    }
    public String sayHello()
    {
        return "Hello";
    }
}

Note: You cannot call constructors with Flash Remoting. You must use the default constructor.

In ActionScript, the following javaService call invokes the sayHello public method of the utils.UIComponents class:

import mx.remoting.*;
import mx.services.Log;
import mx.rpc.*;

// Connect to service and create service object
    var javaService:Service = new Service(
            "http://localhost/flashservices/gateway",
            null,
            utils.UIComponents",
            null,
            null );
// Call the service sayHello() method
var pc:PendingCall = javaService.sayHello();
// Tell the service what methods handle result and fault conditions
pc.responder = new RelayResponder( this, "sayHello_Result", "sayHello_Fault" );

function sayHello_Result(re:ResultEvent)
{
    // Display successful result
    trace("Result is: " + re.result);
}

function sayHello_Fault(fe:FaultEvent)
{
    // Display fault returned from service
    trace("Error is: " + fe.fault.description);
}

Note: For more information about using Java objects with ColdFusion, see Using Java objects.


Handling errors with ColdFusion and Flash

To help with debugging, use the cftry and cfcatch tags in your ColdFusion page or component to return error messages to the Flash Player. For example, the ColdFusion page, causeError.cfm, contains the code:

<cftry>
    <cfset dev = Val(0)>
    <cfset Flash.Result = (1 / dev)>
    <cfcatch type = "any">
        <cfthrow message = "An error occurred in this service: #cfcatch.message#">
    </cfcatch>
</cftry>

The second cfset tag in this example fails because it tries to divide by zero (0). The message attribute of the cfthrow tag describes the error; ColdFusion returns this attribute to the Flash application.

To handle the error in your Flash application, create a fault handler similar to causeError_Fault in the following example:

import mx.remoting.*;
import mx.services.Log;
import mx.rpc.*;

// Connect to service and create service object
    var CFMService:Service = new Service(
            "http://localhost/flashservices/gateway",
            null,
            "helloExamples",
            null,
            null );
// Call the service causeError() method
var pc:PendingCall = CFMService.causeError();
// Tell the service what methods handle result and fault conditions
pc.responder = new RelayResponder( this, "causeError_Result", "causeError_Fault" );

function causeError_Result(re:ResultEvent)
{
    // Display successful result
    messageDisplay.text = re.result;
}

function causeError_Fault(fe:FaultEvent)
{
    // Display fault returned from service
    trace("Error message from causeError is: " + fe.fault.description);
}

This example displays the trace message from the causeError_Fault function in the Flash Output panel. The portion of the message that is contained in fe.fault.description is the portion of the message that is contained in #cfcatch.message# in the causeError.cfm page.

Note: When you create a ColdFusion page that communicates with Flash, ensure that the ColdFusion page works before using it with Flash.

Previous


Using Server-Side ActionScript

Macromedia ColdFusion MX server configuration includes the Macromedia Flash Remoting service, a module that lets Macromedia Flash MX developers create server-side ActionScript. These ActionScript files can directly access ColdFusion MX query and HTTP features through two new ActionScript functions: CF.query and CF.http.

Contents

About server-side ActionScript

Connecting to the Flash Remoting service

Using server-side ActionScript functions

Global and request scope objects

About the CF.query function and data sources

Using the CF.query function

Building a simple application

About the CF.http function

Using the CF.http function
Next


About server-side ActionScript

ColdFusion MX includes a module called the Flash Remoting service that acts as a broker for interactions between Flash MX and ColdFusion MX. Flash Remoting supports a range of object types, and lets you reference an ActionScript file that lives on a ColdFusion server. You can partition data-intensive operations on the server, while limiting the amount of network transactions necessary to get data from the server to the client.

Flash developers can create server-side ActionScript files to access ColdFusion MX resources; they do not have to learn CFML (ColdFusion Markup Language). This ability lets you logically separate the Flash presentation elements of your applications from the business logic. You have the option of creating ActionScript files that reside on the server to partition this processing away from your client applications.

You have a very simple interface for building queries using server-side ActionScript, and an equally simple interface for invoking these queries from your client-side ActionScript.

This section describes the following topics:

  • Client-side ActionScript requirements
  • Server-side requirements
  • Software requirements
  • Location of server-side ActionScript files
  • Benefits
  • What to do next


Client-side ActionScript requirements

On the client side, you only need a small piece of code that establishes a connection to the Flash Remoting service and references the server-side ActionScript you want to use.

For example (notice the embedded comments):

// This #include is needed to connect to the Flash Remoting service
#include "NetServices.as"

// This line determines where Flash MX should look for the Flash Remoting service.
// Ordinarily, you enter the URL to your ColdFusion server.
// Port 8500 is the Flash Remoting service default.
NetServices.setDefaultGatewayUrl("http://mycfserver:8500");

// With the Flash Remoting service URL defined, you can create a connection.
gatewayConnnection = NetServices.createGatewayConnection();

// Reference the server-side ActionScript.
// In this case, the stockquotes script file lives in the web root of the
// ColdFusion server identified previously. If it lived in a subdirectory
// of the web root called "mydir," you would reference it
// as "mydir.stockquotes".
stockService = gatewayConnnection.getService("stockquotes", this);

// This line invokes the getQuotes() method defined in the stockquotes
// server-side ActionScript.
stockService.getQuotes("macr");

// Once the record set is returned, you handle the results.
// This part is up to you.
function getQuotes_Result ( result )
{
    // Do something with results
}

Note: Client-side ActionScript does not support the two new server-side ActionScript functions, CF.query and CF.http.


Server-side requirements

Creating ActionScript that executes on the server helps leverage your knowledge of ActionScript. It also provides direct access to ColdFusion MX query and HTTP features. The CF.query and CF.http ActionScript functions let you perform ColdFusion MX HTTP and query operations.

Note: On the server side, ActionScript files use the extension .asr.

For example, the following server-side ActionScript code builds on the client-side code shown previously:

// Filename: stockquotes.asr
// Here is the getQuotes method invoked in the client-side ActionScript.
// It accepts a single stock quote symbol argument.
function getQuotes(symbol)
{
    // Query some provider for the specified stock quote and return the
    // results. In this case, the getQuotesFromProvider method is
    // defined elsewhere in this ActionScript code.
    data = getQuotesFromProvider(symbol);
    // Return the data to the client.
    // Note: this example does not include any of the error checking
    // logic you would normally use prior to returning the data.
    return data;
}

The getQuotes function conducts the stock quote request and returns the results of the request to the client as a RecordSet object.


Software requirements

To use server-side ActionScript files, you must have the following software installed:

  • Macromedia Flash MX
  • Macromedia ColdFusion MX
  • Flash Remoting Components

For more information about these products, go to www.macromedia.com.


Location of server-side ActionScript files

You can place ActionScript files (*.asr) on the server anywhere below the web server’s root directory. To specify subdirectories of the web root or a virtual directory, use package dot notation (use dots instead of slashes in a fully qualified directory name). For example, in the following assignment code, the stockquotes.asr file is located in the mydir/stock/ directory:

stockService = gatewayConnnection.getService("mydir.stock.stockquotes", this);

You can also point to virtual mappings, such as cfsuite.asr.stock.stockquotes where cfsuite is a virtual mapping and asr.stock is subdirectories of that mapping.


Benefits

Server-side ActionScript lets your ActionScript engineers use their knowledge of ActionScript to write code for the back end of their Flash applications, which can mean more meaningful levels of interactivity for your users. Your Flash applications can share a library of server-side ActionScript functions, which means you can define functions that are specifically tailored to your own business.

You could, for example, create a server-side ActionScript file that defines a whole library of SQL query methods. With these query methods defined on the server side, your Flash designers only have to invoke the specific query function they want to return data to their Flash MX movies. They do not have to write any SQL, and they do not have to create a new query every time they need to retrieve data from a ColdFusion MX data source. It is a way of creating reusable queries that your entire Flash design team can use.

Coding the ColdFusion MX query and HTTP operations in ActionScript is very straightforward. The CF.query and CF.http functions provide a well-defined interface for building SQL queries and HTTP operations.

For example, the following is a typical server-side ActionScript function definition that returns query data:

// This function shows a basic CF.query operation using only
// arguments for data source name and for SQL.
function basicQuery()
{
    mydata = CF.query({datasource:"customers",
        sql:"SELECT * FROM myTable"});
    return mydata;
}


What to do next

If you are already familiar with ActionScript, you only need to know a few things to get started:

  • How to establish a connection with the Flash Remoting service using client-side ActionScript. See Connecting to the Flash Remoting service
  • How to reference server-side ActionScript functions and methods. See Using server-side ActionScript functions.
  • How to code the server-side CF.query and CF.http functions. See Using the CF.query function and Using the CF.http function. Also see the reference pages for these functions in the CFML Reference.

For additional information on using Flash Remoting MX, see Using the Flash Remoting Service, and Using Flash Remoting MX.


Connecting to the Flash Remoting service

Before you can use functions defined in your server-side ActionScript files, you must connect the Macromedia Flash MX movie to the server-side Flash Remoting service.

To create a Flash Remoting service connection:

  1. Include the necessary ActionScript classes in the first frame of the Flash movie that will be using server-side ActionScript functions.
    1. Use the following command to include the NetServices class:
      #include "NetServices.as"
    2. (Optional) Use the following command to include the NetDebug class:
      #include "NetDebug.as"

    For more information about the NetDebug and RecordSet classes, see Using Flash Remoting MX.

  2. Since the Flash Remoting service serves as a broker for calls to server-side ActionScript functions, you must identify the Flash Remoting service URL as an argument in the NetServices.setDefaultGatewayUrl function. For example:
    NetServices.setDefaultGatewayURL("http://localhost:8500/flashservices")

    You must specify a server hostname. The default port number for the Flash Remoting service is 8500.

  3. Create the gateway connection using the NetServices.createGatewayConnection function; for example:
    gatewayConnection = NetServices.createGatewayConnection();


Using server-side ActionScript functions

After you connect to the Flash Remoting service, you call functions that are defined in your server-side ActionScript files, and return results.

To call a function:

  1. Create an instance of the server-side ActionScript file using the getService function. This function instantiates the server-side ActionScript file as an object to be used on the client side. For example:
    albumService = gatewayConnection.getService("recordsettest", this)

    Where recordsettest represents the name of the server-side ActionScript file, without the file extension .asr.

  2. Call a function defined in your server-side ActionScript object. Use dot notation to specify the object name followed by the function name; for example:
    albumService.getAlbum("The Color And The Shape", "1999");

    Where albumService is the instance of the server-side ActionScript file and getAlbum is a function that passes two arguments, "The Color and The Shape" and "1999".

    Note: Arguments must occur in the order defined in the function declaration.

  3. Handle the function results in ActionScript. See Using the function results in ActionScript.

Using the function results in ActionScript

To use the results returned by server-side ActionScript, you must create a corresponding results function. The results function uses a special naming convention that ties it to the function that calls the server-side ActionScript. For example, if you defined a client-side ActionScript function called basicCustomerQuery, you also must create a results function called basicCustomerQuery_Result.

The results returned by server-side ActionScript functions differ somewhat depending on whether you are using CF.http or CF.query:

  • The CF.query function returns a record set, which you manipulate using methods available in the RecordSet ActionScript class object. See Using results returned by the CF.query function.
  • The CF.http function returns simple text strings through properties that you reference in your server-side ActionScript. See Using results returned by the CF.http function.

Using results returned by the CF.query function

You use functions in the RecordSet ActionScript object to access the data returned in a CF.query record set; for example, how many records are in the record set and the names of the columns. You can also use the RecordSet functions to pull the query data out of the record set. To do so, you reference a specific row number in the record set and use the getItemAt RecordSet function, as in the following example:

// This function populates a Flash text box with data in the first row
// of the record set under the "email" column name.
function selectData_Result ( result )
{
    stringOutput.text = result.getItemAt(0)["email"];
    _root.employeesView.setDataProvider(result);
}

In the example, the column name is referenced in the getItemAt function between square brackets [ ]. (In ActionScript, indexes start at 0, so getItemAt(0) returns the first row.)

For more information, see Using the CF.query function.

Using results returned by the CF.http function

The CF.http server-side ActionScript function returns data as simple text. You write server-side functions that reference the properties available in the object returned by the CF.http function. These properties store the file content of the retrieved file, HTTP status codes, the MIME type of the returned file, and so on. On the client side, you create return functions to handle data returned by the CF.http function. You write these functions to handle simple text data.

For more information, see Using the CF.http function.


Global and request scope objects

Global and request scope objects are implicitly available in all server-side ActionScript. The following table describes these scope objects:

Scope name | Type | Description
config | Global | Initialization information for the server-side ActionScript adapter. Class: javax.servlet.ServletConfig
application | Global | The context for the current web application. The context defines methods that provide, for example, the MIME type of a file that can be used to write to a log file. There is one context per web application. Class: javax.servlet.ServletContext
request | Request | An object containing client request information. The object provides data, including parameter name and values, attributes, and an input stream. Class: HttpServletRequest (subtype of javax.servlet.ServletRequest)
response | Request | An object to assist in sending a response to the client. It provides HTTP-specific functionality in sending a response. Do not use the OutputStream or PrintWriter to send data back to the client. Class: HttpServletResponse (subtype of javax.servlet.ServletResponse)

For more information about these scope objects, see the documentation on the javax.servlet class at http://java.sun.com.


About the CF.query function and data sources

You use the CF.query function to populate Macromedia Flash MX movie elements with data retrieved from a Macromedia ColdFusion MX data source. To use the CF.query function you do the following:

To pull data into your Flash MX movie from a ColdFusion MX data source:

  1. Create a server-side ActionScript file that performs queries against a ColdFusion MX data source.
  2. Write ActionScript code in your Flash MX movie that references your ActionScript file (.asr) on the ColdFusion server.

You create server-side ActionScript to execute the query and return the data in a record set to the client--your Flash MX movie. You can use methods in the RecordSet ActionScript object on the client to manipulate data in the record set and present data in your Flash MX movie.

Note: Client-side ActionScript files use the .as extension. Server-side ActionScript files use the .asr (ActionScript remote) extension.

Publishing dynamic data

You use the server-side ActionScript feature in ColdFusion MX to publish dynamic data. To do this, you write server-side ActionScript files that perform queries against ColdFusion MX data sources. Before using ActionScript, you must understand how to do the following:

  • Create database queries in the server-side ActionScript file using the CF.query ActionScript function. See Using the CF.query function.
  • Reference the server-side ActionScript file in your Flash MX movie. See Connecting to the Flash Remoting service.

Using the CF.query function, you can do the following tasks:

  • Create user login interfaces that validate users against a ColdFusion MX data source.
  • Populate form elements and data grids with data from a ColdFusion MXdata source.
  • Create banners that pull data (such as URLs or image file paths) out of a database.

The CF.query function can retrieve data from any supported ColdFusion MX data source (see About ColdFusion MX data sources).

About ColdFusion MX data sources

For ColdFusion MX developers, the term data source can refer to a number of different types of structured data accessible locally or across a network. You can query websites, Lightweight Directory Access Protocol (LDAP) servers, POP mail servers, and documents in a variety of formats. For server-side ActionScript, a data source ordinarily means the entry point to a ColdFusion MX database.

Your ColdFusion MX administrator can help you identify and configure data sources. To create ActionScript files that successfully perform queries on ColdFusion MX data sources, you must know how the data source is identified by ColdFusion MX, as well as any other parameters that affect your ability to connect to that database, such as whether a username and password are required to connect.

You use server-side ActionScript in ColdFusion MX to return record set data to a Flash MX client from a ColdFusion MX data source. You specify the ColdFusion MX data source name and the SQL statement you execute on the data source as arguments in the CF.query function in server-side ActionScript.

Typically, your server-side ActionScript handles the interaction with the ColdFusion MX data source, and returns a record set to the Flash MX client through the Flash Remoting service.

For more detailed information about ColdFusion MX data sources, see Configuring and Administering ColdFusion MX.


Using the CF.query function

You use the CF.query function in your server-side ActionScript to retrieve data from a ColdFusion MX data source. This function lets you perform queries against any ColdFusion MX data source.

Note: The CF.query function maps closely to the cfquery CFML tag, although it currently supports a subset of the cfquery attributes.

Use the CF.query function to do the following:

  • Identify the data source you want to query.
  • Pass SQL statements to the data source.
  • Pass other optional parameters to the database.

For reference information about the CF.query function, see CF.query in CFML Reference.

About CF.query function syntax

You can write the CF.query ActionScript function using either named arguments or positional arguments. The named argument style is more readable, but it requires more code. Although the positional argument style supports a subset of CF.query arguments, it allows a more compact coding style that is more appropriate for simple expressions of the CF.query function.

Using CF.query named argument syntax

The CF.query function accepts the following named arguments:

// CF.query named argument syntax
CF.query
    ({
        datasource:"data source name",
        sql:"SQL stmts",
        username:"username",
        password:"password",
        maxrows:number,
        timeout:milliseconds
    })

Note: The named argument style requires curly braces {} to surround the function arguments.

Using CF.query positional argument syntax

Positional arguments support a subset of CF.query arguments, and you can create more efficient code. The following is the syntax for the positional argument style:

// CF.query positional argument syntax
CF.query(datasource, sql);
CF.query(datasource, sql, maxrows);
CF.query(datasource, sql, username, password);
CF.query(datasource, sql, username, password, maxrows);

Note: When using positional arguments, do not use curly braces {}.

About the CF.query record set

The CF.query function returns a RecordSet object, which is an instance of the RecordSet class of objects. The RecordSet class provides a wide range of functions for handling record set data.

You use methods in the RecordSet ActionScript class in your client-side ActionScript to change data returned in the CF.query record set.

Currently, the following methods are available in the RecordSet class:

:
Method | Description
addItem | Appends a record to the end of the specified RecordSet
addItemAt | Inserts a record at the specified index
addView | Requests notification of changes in a RecordSet object’s state
filter | Creates a new RecordSet object that contains selected records from the original RecordSet object
getColumnNames | Returns the names of all the columns of the RecordSet
getItemAt | Retrieves a record from a RecordSet object
getItemID | Gets the unique ID corresponding to a record
getLength | Returns the total number of records in a RecordSet object
getNumberAvailable | Returns the number of records that have been downloaded from the server
isFullyPopulated | Determines whether a RecordSet object can be edited or manipulated
isLocal | Determines whether a RecordSet object is local or server-associated
removeAll | Removes all records from the RecordSet object
removeItemAt | Removes a specified record
replaceItemAt | Replaces the entire contents of a record
setDeliveryMode | Changes the delivery mode of a server-associated record set
setField | Replaces one field of a record with a new value
sort | Sorts all records by a specified compare function
sortItemsBy | Sorts all the records by a selected field

These functions are available for every RecordSet object returned by the CF.query function to the Flash MX client. You invoke these functions as follows:

objectName.functionName();

For example, in the result function that you create to handle record set data returned by the CF.query function, you can reference the database column names returned in the record set using the getColumnNames RecordSet function:

function selectData_Result ( result )
{
    //result holds the query data; employeesView is a Flash list box
    stringOutput.text = result.getColumnNames();
    _root.employeesView.setDataProvider(result);
}


Building a simple application

The following procedure describes how to build a simple server-side ActionScript application. The example application, a corporate personnel directory, uses the NetServices object to connect to the personneldirectory server-side ActionScript. The personneldirectory server-side ActionScript retrieves data from a ColdFusion MX data source and returns the results to the Flash application as a RecordSet object.

Note: The server-side ActionScript application that you create provides the back-end services in an application.

This example requires the following:

  • A server-side ActionScript file named personneldirectory.asr that includes functions that interact with a ColdFusion MX data source.
  • A client-side Flash MX movie in which the NetServices object is created.

To create the application:

  1. Write server-side ActionScript that performs the database query and returns data to the client through the Flash Remoting service.
  2. Create the Flash movie interface. See Creating the Flash movie interface.
  3. Define a search function that sends user data to the Flash Remoting service. See Submitting user data to the Flash Remoting service.
  4. Define a result function that captures the results returned from the Flash Remoting service. See .
  5. Ensure that the Flash movie has established a connection to the Flash Remoting service. See Checking for a Flash Remoting service connection.

This section describes the following topics:

  • Writing the server-side ActionScript function
  • Creating the Flash movie interface
  • Submitting user data to the Flash Remoting service
  • Capturing Flash Remoting service results
  • Checking for a Flash Remoting service connection


Writing the server-side ActionScript function

The example in this section creates a search function that performs a simple search operation against a ColdFusion MX data source. This function accepts two arguments, firstName and lastName, and returns any records found that match these arguments.

To create a server-side ActionScript function:

  1. Create a server-side ActionScript file that contains the following code:
//search takes firstName lastName arguments
function search(firstName, lastName)
{
    searchdata = CF.query({datasource: "bigDSN",
        sql:"SELECT * from personnel WHERE fname = firstName AND lname = lastName"{);

    if (searchdata)
        return searchdata;
    else
        return null;
}
  1. Save the file as personneldirectory.asr.


Creating the Flash movie interface

The Flash movie interface example in this section consists of one frame with a variety of text boxes and a submit button.

To create the Flash movie interface:

  1. In the Flash MX authoring environment, create a new Flash source file, and save it as pDirectory.fla.
  2. Create two input text boxes. Name one text box variable lastName and the other firstName.
  3. Create a dynamic text box, and name its variable status.
  4. Insert a list box component, and name it dataView.
  5. Insert a push button component.
  6. Save your work.

The following figure shows what the pDirectory Flash movie might look like:

This image shows what the Flash MX movie should look like for the current example


Submitting user data to the Flash Remoting service

To send data to server-side ActionScript, you must create a function that passes the data from the Flash movie to server-side ActionScript. The search function, applied at the frame level, collects the user-entered data from the firstName and lastName text boxes and passes the data as function arguments to the directoryService object, which is created when the Flash movie connects to the Flash Remoting service. For more information, see Checking for a Flash Remoting service connection.

The following is a Flash MX ActionScript example:

#include "NetServices.as"
function search()
{
    // The search() method is defined in the server-side AS file
    directoryService.search(firstName.text, lastName.text);
    dataView.setDataProvider(null);
    status.text = "waiting...";
}

Reviewing the code

The following table describes the code and its function:

Code

Description

directoryService.search
(firstName.text, lastName.text);

Passes the contents of the firstName and lastName text boxes to server-side ActionScript.

dataView.setDataProvider
(null);

Clears the dataView list box component.

status.text = "waiting...";

Displays a message in the status text box while the record set is being retrieved from server-side ActionScript.


Capturing Flash Remoting service results

When you create a function that calls a server-side ActionScript function, you must also create a function to handle the data returned by server-side ActionScript. Define the function with the same name as the function making the initial call, but you append _Result to the name.

For example, if you create a function called basicQuery to return query data, you also need to define a results function to handle returned data; declare the results function as basicQuery_Result.

In the following example, the results function search_Result supplies the record set to the dataView.setDataProvider function:

function search_Result(resultset)
{
    dataView.setDataProvider(resultset);
    status.text = (0+resultset.getLength())+" names found.";
}

Reviewing the code

The following table describes the code and its function:

Code

Description

function search_Result
(resultset)

The _Result suffix tells the Flash Remoting service to return the results of the search function to this function.

dataView.setDataProvider
(resultset);

Assigns the results returned by the Flash Remoting service to the dataView list box.

status.text = (0+resultset.
getLength())+" names found.";

Displays the number of records returned by the Flash Remoting service.


Checking for a Flash Remoting service connection

To ensure that the Flash movie is connected to the Flash Remoting service, you use an if statement; for example:

if (inited == null)
{
    inited = true;
    NetServices.setDefaultGatewayUrl("http://localhost:8500/flashservices/
        gateway");
    gateway_conn = NetServices.createGatewayConnection();
    directoryService = gateway_conn.getService(personneldirectory, this);
    status.text = "Type into the text boxes, then click 'Search'";
}

In this example, the inited variable is evaluated for a value. If inited is null (not connected), the movie connects to the Flash Remoting service using the NetServices object. For more information about connecting to the Flash Remoting service, see Connecting to the Flash Remoting service.


About the CF.http function

You use the CF.http ActionScript function to retrieve information from a remote HTTP server using HTTP Get and Post methods, as follows:

  • Using the Get method, you send information to the remote server directly in the URL. This is common for a one-way transaction in which the CF.http function retrieves an object, such as the contents of a web page.
  • The Post method can pass variables to a form or CGI program, and can also create HTTP cookies.

The most basic way to use the CF.http function is to use it with the Get method argument to retrieve a page from a specified URL. The Get method is the default for the CF.http function.

The following server-side example retrieves file content from the specified URL:

function basicGet(url)
{
    // Invoke with just the url argument. This is an HTTP GET.
    result = CF.http(url);
    return result.get("Filecontent");
}

The client-side example could look like the following:

#include "NetServices.as"
NetServices.setDefaultGatewayUrl("http://mycfserver:8500");
gatewayConnnection = NetServices.createGatewayConnection();
myHttp = gatewayConnnection.getService("httpFuncs", this);

// This is the server-side function invocation
url = "http://anyserver.com";
myHttp.basicGet(url);

// Create the results function
function basicGet_Result()
{
    url = "http://anyserver.com
    ssasFile.basicGet(url)
}


Using the CF.http function

The CF.http function returns an object that contains properties, also known as attributes. You reference these attributes to access the contents of the file returned, header information, HTTP status codes, and so on. The following table shows the available properties:

Property | Description
Text | A Boolean value indicating whether the specified URL location contains text data.
Charset | The charset used by the document specified in the URL. HTTP servers normally provide this information, or the charset is specified in the charset parameter of the Content-Type header field of the HTTP protocol. For example, the following HTTP header announces that the character encoding is EUC-JP: Content-Type: text/html; charset=EUC-JP
Header | Raw response header. For example, macromedia.com returns the following header : HTTP/1.1 200 OK Date: Mon, 04 Mar 2002 17:27:44 GMT Server: Apache/1.3.22 (Unix) mod_perl/1.26 Set-Cookie: MM_cookie=207.22.48.162.4731015262864476; path=/; expires=Wed, 03-Mar-04 17:27:44 GMT; domain=.macromedia.com Connection: close Content-Type: text/html
Filecontent | File contents, for text and MIME files.
Mimetype | MIME type. Examples of MIME types include text/html, image/png, image/gif, video/mpeg, text/css, and audio/basic.
responseHeader | Response header. If there is one instance of a header key, this value can be accessed as a simple type. If there is more than one instance, values are put in an array in the responseHeader structure.
Statuscode | HTTP error code and associated error string. Common HTTP status codes returned in the response header include the following: 400: Bad Request 401: Unauthorized 403: Forbidden 404: Not Found 405: Method Not Allowed

Referencing HTTP Post parameters in the CF.http function

To pass HTTP Post parameters in the CF.http function, you must construct an array of objects and assign this array to a variable named params. The following arguments can only be passed as an array of objects in the params argument of the CF.http function:

Parameter

Description

name

The variable name for data that is passed

type

Transaction type:

  • URL
  • FormField
  • Cookie
  • CGI
  • File

value

Value of URL, FormField, Cookie, File, or CGI variables that are passed

In the following example, the CF.http function passes HTTP Post parameters in an array of objects:

function postWithParamsAndUser()
{
    // Set up the array of Post parameters. These are just like cfhttpparam tags.
    params = new Array();
    params[1] = {name:"arg2", type:"URL", value:"value2"};

    url = "http://localhost:8500/";

    // Invoke with the method, url, params, username, and password
    result = CF.http("post", url, params, "karl", "salsa");
    return result.get("Filecontent");
}

Using the CF.http Post method

You use the Post method to send cookie, form field, CGI, URL, and file variables to a specified ColdFusion page or CGI program for processing. For POST operations, you must use the params argument for each variable that you post. The Post method passes data to a specified ColdFusion page or an executable that interprets the variables being sent, and returns data.

For example, when you build an HTML form using the Post method, you specify the name of the page to which form data is passed. You use the Post method in the CF.http function in a similar way. However, with the CF.http function, the page that receives the Post does not display anything. See the following example:

function postWithParams()
{
    // Set up the array of Post parameters. These are just like cfhttpparam tags.
    // This example passes formfield data to a specified URL.
    params = new Array();
    params[1] = {name:"Formfield1", type:"FormField", value:"George"};
    params[2] = [name:"Formfield2", type:"FormField", value:"Brown"};

    url = "http://localhost:8500/";

    // Invoke CF.http with the method, url, and params
    result = CF.http("post", url, params);
    return result.get("Filecontent");
}

Using the CF.http Get method

You use the Get method to retrieve files, including text and binary files, from a specified server. You reference properties of the object returned by the CF.http function to access things like file content, header information, MIME type, and so on.

The following example uses the CF.http function to show a common approach to retrieving data from the web:

// Returns content of URL defined in url variable
// This example uses positional argument style
function get()
{
    url = "http://www.macromedia.com/software/coldfusion/";

    //Invoke with just the url argument. Get is the default.
    result = CF.http(url);
    return result.get("Filecontent");
}

For more information about CF.http function properties, see CF.http in CFML Reference.

Previous


Using XML and WDDX

This chapter describes how to use Macromedia ColdFusion MX to create, use, and manipulate XML documents. This chapter also presents Web Distributed Data Exchange (WDDX), an XML dialect for transmitting structured data, and describes how to use it to transfer data between applications and between CFML and JavaScript.

This chapter does not present XML concepts. Before you read this chapter you should become familiar with XML.

Contents

About XML and ColdFusion

The XML document object

ColdFusion XML tag and functions

Using an XML object

Creating and saving an XML document object

Modifying a ColdFusion XML object

Validating XML documents

Transforming documents with XSLT

Extracting data with XPath

Example: using XML in a ColdFusion application

Moving complex data across the web with WDDX

Using WDDX
Next


About XML and ColdFusion

In the last few years, XML has rapidly become the universal language for representing documents and data on the web. These documents can extend beyond the traditional concept of a paper document or its equivalent. For example, XML is often used to represent database or directory information. XML is also commonly used to represent transaction information, such as product orders or receipts, and for information such as inventory records and employee data.

Because XML represents data in a tagged, textual format it is an excellent tool for representing information that must be shared between otherwise-independent applications such as order entry and inventory management. No application needs to know anything about the other. Each application only needs to be prepared to get data in a format that is structured according to the XML DTD or Schema. For example, in a distributed order processing application, the order placement component, order fulfilment component, inventory management component, and billing component can all share information with each other in XML format. They could use a common XML DTD, of different components could communicate with each other using different DTDs.

After an application parses the XML document, it can then manipulate the information in any way that is appropriate. For example, you can convert tabular XML data into a ColdFusion recordset, perform queries on the data and then export the data an XML document. For example, the code in Example: using XML in a ColdFusion application takes a customer order in XML, converts the data to a recordset, and uses a query to determine the order cost. It then prepares a receipt as an XML document.

ColdFusion provides a comprehensive and easy-to-use set of tools for creating and using XML documents. ColdFusion lets you do the following with XML documents:

  • Convert XML text into ColdFusion XML document objects.
  • Create new ColdFusion XML document objects.
  • Modify ColdFusion XML document objects.
  • Validate XML against a DTD or Schema
  • Transform XML using XSLT (Extensible Stylesheet Language Transformation).
  • Extract data from XML documents using XPath expressions.
  • Convert ColdFusion XML document objects to text and save them in files.

ColdFusion MX can also represent forms that you create using the cfform tag as XML. You can have ColdFusion generate the XML and process it using an XSLT skin to generate output for display, or ColdFusion MX can generate XML text and put it in a variable for further processing. For more information on XML Forms, see Creating Skinnable XML Forms.


The XML document object

ColdFusion represents an XML document as an object, called an XML document object, that is much like a standard ColdFusion structure. In fact, most ColdFusion structure functions, such as StructInsert, work with XML document objects. For a full list of ColdFusion functions that work on XML document objects, see Functions for XML object management.

You can look at the overall structure of an XML document in two ways: a basic view and a DOM (Document Object Model)-based node view. The basic view presents all the information in the document, but does not separate the data into as fine-grained units as the node view. ColdFusion can access XML document contents using either view.

This section describes the following topics:

  • A simple XML document
  • Basic view
  • DOM node view
  • XML document structures

A simple XML document

The next sections describe the basic and node views of the following simple XML document. This document is used in many of the examples in this chapter.

<?xml version="1.0" encoding="UTF-8"?>
<employee>
<!-- A list of employees -->
    <name EmpType="Regular">
        <first>Almanzo</first>
        <last>Wilder</last>
    </name>
    <name EmpType="Contract">
        <first>Laura</first>
        <last>Ingalls</last>
    </name>
</employee>


Basic view

The basic view of an XML document object presents the object as a container that holds one root element structure. The root element can have any number of nested element structures. Each element structure represents an XML tag (start tag/end tag set) and all its contents; it can contain additional element structures. A basic view of the simple XML document looks like the following:

Basic view of a simple XML document


DOM node view

The DOM node view presents the XML document object using the same format as the document’s XML Document Object Model (DOM). In fact, an XML document object is a representation of a DOM object.

The DOM is a World Wide Web Consortium (W3C) recommendation (specification) for a platform- and language-neutral interface to dynamically access and update the content, structure, and style of documents. ColdFusion conforms to the DOM Level 2 Core specification, available at www.w3.org/TR/DOM-Level-2-Core.

In the DOM node view, the document consists of a hierarchical tree of nodes. Each node has a DOM node type, a node name, and a node value. Node types include Element, Comment, Text, and so on. The DOM structures the document object and each of the elements it contains into multiple nodes of different types, providing a finer-grained view of the document structure than the basic view. For example, if an XML comment is in the middle of a block of text, the DOM node view represents its position in the text while the basic view does not.

ColdFusion also lets you use the DOM objects, methods, and properties defined in the W3C DOM Level 2 Core specification to manipulate the XML document object.

For more information on referencing DOM nodes, see XML DOM node structure. This document does not cover the node view and using DOM methods and properties in detail.


XML document structures

An XML document object is a structure that contains a set of nested XML element structures. The following figure shows a section of the cfdump tag output for the document object for the XML in A simple XML document. This figure shows the long version of the dump, which provides complete details about the document object. Initially, ColdFusion displays a short version, with basic information. Click the dump header to change between short, long, and collapsed versions of the dump.

Output of the cfdump tag for an XML document

The following code displays this output. It assumes that you save the code in a file under your web root, such as C:\Inetpub\wwwroot\testdocs\employeesimple.xml

<cffile action="read" file="C:\Inetpub\wwwroot\testdocs\employeesimple.xml"
    variable="xmldoc">
<cfset mydoc = XmlParse(xmldoc)>
<cfdump var="#mydoc#">

The document object structure

At the top level, the XML document object has the following three entries:

Entry name | Type | Description
XmlRoot | Element | The root element of the document.
XmlComment | String | A string made of the concatenation of all comments on the document, that is, comments in the document prologue and epilog. This string does not include comments inside document elements.
XmlDocType | XmlNode | The DocType attribute of the document. This entry only exists if the document specifies a DocType. This value is read-only; you cannot set it after the document object has been created This entry does not appear when cfdump displays an XML element structure.

The element structure

Each XML element has the following entries:

Entry name | Type | Description
XmlName | String | The name of the element; includes the namesapce prefix.
XmlNsPrefix | String | The prefix of the namespace.
XmlNsURI | String | The URI of the namespace.
XmlText or XmlCdata | String | A string made of the concatenation of all text and CData text in the element, but not inside any child elements. When you assign a value to the XmlCdata element, ColdFusion puts the text inside a CDATA information item. When you retrieve information from document object, these element names return identical values.
XmlComment | String | A string made of the concatenation of all comments inside the XML element, but not inside any child elements.
XmlAttributes | Structure | All of this element’s attributes, as name-value pairs.
XmlChildren | Array | All this element’s children elements.
XmlParent | XmlNode | The parent DOM node of this element. This entry does not appear when cfdump displays an XML element structure.
XmlNodes | Array | An array of all the XmlNode DOM nodes contained in this element. This entry does not appear when cfdump displays an XML element structure.

XML DOM node structure

The following table lists the contents of an XML DOM node structure:

Entry name | Type | Description
XmlName | String | The node name. For nodes such as Element or Attribute, the node name is the element or attribute name.
XmlType | String | The node XML DOM type, such as Element or Text.
XmlValue | String | The node value. This entry is used only for Attribute, CDATA, Comment, and Text type nodes.

Note: The cfdump tag does not display XmlNode structures. If you try to dump an XmlNode structure, the cfdump tag displays "Empty Structure."

The following table lists the contents of the XmlName and XmlValue fields for each node type that is valid in the XmlType entry. The node types correspond to the objects types in the XML DOM hierarchy.

Node type

XmlName

xmlValue

CDATA

#cdata-section

Content of the CDATA section

COMMENT

#comment

Content of the comment

ELEMENT

Tag name

Empty string

ENTITYREF

Name of entity referenced

Empty string

PI (processing instruction)

Target entire content excluding the target

Empty string

TEXT

#text

Content of the text node

ENTITY

Entity name

Empty string

NOTATION

Notation name

Empty string

DOCUMENT

#document

Empty string

FRAGMENT

#document-fragment

Empty string

DOCTYPE

Document type name

Empty string

Note: Although XML attributes are nodes on the DOM tree, ColdFusion does not expose them as XML DOM node data structures. To view an element’s attributes, use the element structure’s XMLAttributes structure.

The XML document object and all its elements are exposed as DOM node structures. For example, you can use the following variable names to reference nodes in the DOM tree that you created from the XML example in A simple XML document:

mydoc.XmlName
mydoc.XmlValue
mydoc.XmlRoot.XmlName
mydoc.employee.XmlType
mydoc.employee.XmlNodes[1].XmlType


ColdFusion XML tag and functions

The following table lists the ColdFusion tag (cfxml) and functions that create and manipulate XML documents:

Tag or function

Description

<cfxml variable="objectName"
[caseSensitive="Boolean"]>

Creates a new ColdFusion XML document object consisting of the markup in the tag body. The tag can include XML and CFML tags. ColdFusion processes all CFML in the tag body before converting the resulting text to an XML document object.

If you specify the CaseSensitive="True" attribute, the case of names of elements and attributes in the document is meaningful. The default value is False.

For more information on using the cfxml tag, see Creating a new XML document object using the cfxml tag.

XmlParse(XMLText
[[, caseSensitive],
validator])

Converts an XML document in a file or a string variable into an XML document object, and optionally validates the document against a DTD or schema.

If you specify the optional second argument as True, the case of names of elements and attributes in the document is meaningful. The default value is False.

For more information on using the XmlParse function, see Creating an XML document object from existing XML.

XmlNew([caseSensitive])

Returns a new, empty XML document object.

If you specify the optional argument as True, the case of names of elements and attributes in the document is meaningful. The default value is False.

For more information on using the XmlNew function, see Creating a new XML document object using the XmlNew function.

XmlElemNew(objectName{,
namespaceURI],
elementName)

Returns a new XML document object element with the specified name, optionally belonging to the specified namespace. You can omit the namespaceURI parameter and use only a namespace prefix if the prefix is defined elsewhere in the object.

For more information on using the XmlElemNew function, see Adding an element.

XmlTransform(XMLVar,
XSLTStringVar[,
parameters])

Applies an Extensible Stylesheet Language Transformation (XSLT) to an XML document. The document can be represented as a string variable or as an XML document object. The function returns the resulting XML document as a string.

For more information on using the XmlTransform function, see Transforming documents with XSLT.

XmlSearch(objectName,
XPathExpression)

Uses an XPath expression to search an XML document object and returns an array of XML elements that match the search criteria.

For more information on using the XmlSearch function, see Extracting data with XPath.

XmlValidate(xmlDoc[,
validator])

Uses a Document Type Definition (DTD) or XML Schema to validate an XML text document (in a string or file) or an XML document object. The validator can be a DTD or Schema. If you omit the validator parameter, the document must specify a DTD or schema. For more information on using the XmlValidate function, see Validating XML documents

XmlChildPos(element,
elementName, position)

Returns the position (index) in an XmlChildren array of the Nth child with the specified element name. For example, XmlChildPos(mydoc.employee, "name", 2) returns the position in mydoc.employee.XmlChildren of the mydoc.employee.name[2] element. This index can be used in the ArrayInsertAt and ArrayDeleteAt functions.

For more information on using the XmlChildPos function, see Determining the position of a child element with a common name, Adding an element, and Deleting elements.

XmlGetNodeType(xmlNode)

Returns a string identifying the type of an XML document object node returned by the XmlSearch function or in an element’s XmlNodes array.

IsWDDX(String)

Determines whether a string is a well-formed WDDX packet.

IsXML(String)

Determines whether a string is well-formed XML text.

IsXmlAttribute(variable)

Determines whether the function parameter is an XML Document Object Model (DOM) attribute node.

IsXmlDoc(objectName)

Returns True if the function argument is an XML document object.

IsXmlElem(elementName)

Returns True if the function argument is an XML document object element.

IsXmlNode(variable)

Determines whether the function parameter is an XML document object node.

IsXmlRoot(elementName)

Returns True if the function argument is the root element of an XML document object.

ToString(objectName)

Converts an XML document object to a string representation.

XmlFormat(string)

Escapes special XML characters in a string so that the string can be used as text in XML.

About case-sensitivity and XML document objects

The tags and functions that create XML document objects let you specify whether ColdFusion will treat the object in a case-sensitive manner. If you do not specify case-sensitivity, ColdFusion ignores the case of XML document object component identifiers, such as element and attribute names. If you do specify case-sensitivity, names with different cases refer to different components. For example, if you do not specify case-sensitivity, the names mydoc.employee.name[1] and mydoc.employee.NAME[1] always refer to the same element. If you specify case-sensitivity, these names refer to two separate elements. You cannot use dot notation references for element or attribute names in a case-sensitive XML document; for more information see Referencing the contents of an XML object.


Using an XML object

Because an XML document object is represented as a structure, you can access XML document contents using either, or a combination of both, of the following ways:

  • Using the element names, such as mydoc.employee.name[1]
  • Using the corresponding structure entry names (that is, XmlChildren array entries), such as mydoc.employee.XmlChildren[1]

Similarly, you can use either, or a combination of both, of the following notation methods:

  • Structure (dot) notation, such as mydoc.employee
  • Associative array (bracket) notation, such as mydoc["employee"]

Referencing the contents of an XML object

Use the following rules when you reference the contents of an XML document object on the right side of an assignment or as a function argument:

  • By default, ColdFusion ignores element name case. As a result, it considers the element name MyElement and the element name myELement to be equivalent. To make element name matching case-sensitive, specify CaseSensitive="True" in the cfxml tag, or specify True as a second argument in the XmlNew or XmlParse function that creates the document object.
  • If your XML object is case sensitive, do not use dot notation to reference an element or attribute name. Use the name in associative array (bracket) notation, or a reference that does not use the case-sensitive name. For example, do not use names such as the following:
    MyDoc.employee.name[1]

MyDoc.employee.XmlAttributes.Version

    Instead, use names such as the following:

    MyDoc.xmlRoot.XmlChildren[1]
MyDoc.xmlRoot["name"][1]
MyDoc.["employee"]["name"][1]

MyDoc.xmlRoot.XmlAttributes["Version"]
MyDoc["employee"].XmlAttributes["Version"]

    Caution: Because ColdFusion always treats variable names as case-insensitive, using dot notation for element and attribute names in a case sensitive XML document can generate unexpected results (such as all-uppercase variable names), exceptions, or both.

  • If your XML object is case sensitive, you cannot use dot notation to reference an element or attribute name. Use the name in associative array (bracket) notation, or a reference that does not use the case-sensitive name (such as XmlChildren[1]) instead.
  • Use an array index to specify one of multiple elements with the same name; for example, #mydoc.employee.name[1] and #mydoc.employee.name[2].

    If you omit the array index on the last component of an element identifier, ColdFusion treats the reference as the array of all elements with the specified name. For example, mydoc.employee.name refers to an array of two name elements.

  • Use an array index into the XmlChildren array to specify an element without using its name; for example, mydoc.XmlRoot.XmlChildren[1].
  • Use associative array (bracket) notation to specify an element name that contains a period or colon; for example, myotherdoc.XmlRoot["Type1.Case1"].
  • You can use DOM methods in place of structure entry names.

For example, the following variables all refer to the XmlText value "Almanzo" in the XML document created in A simple XML document:

mydoc.XmlRoot.XmlChildren[1].XmlChildren[1].XmlText
mydoc.employee.name[1].first.XmlText
mydoc.employee.name[1]["first"].XmlText
mydoc["employee"].name[1]["first"].XmlText
mydoc.XmlRoot.name[1].XmlChildren[1]["XmlText"]

The following variables all refer to the EmpType attribute of the first name element in the XML document created in A simple XML document:

mydoc.employee.name[1].XmlAttributes.EmpType
mydoc.employee.name[1].XmlAttributes["EmpType"]
mydoc.employee.XmlChildren[1].XmlAttributes.EmpType
mydoc.XmlRoot.name[1].XmlAttributes["EmpType"]
mydoc.XmlRoot.XmlChildren[1].XmlAttributes.EmpType

Neither of these lists contains a complete set of the possible combinations that can make up a reference to the value or attribute.

Assigning data to an XML object

When you use an XML object reference on the left side of an expression, most of the preceding rules apply to the reference up to the last element in the reference string.

For example, the rules in Referencing the contents of an XML object apply to mydoc.employee.name[1].first in the following expression:

mydoc.employee.name[1].first.MyNewElement = XmlElemNew(mydoc, NewElement);

The rule for naming in case correct document objects, however, applies to the full reference string, as indicated by the following caution:

Caution: Because ColdFusion always treats variable names as case insensitive, using dot notation for element and attribute names in a case-sensitive XML document can generate unexpected results (such as all-uppercase variable names), exceptions, or both. In case-sensitive XML documents, use associative array notation or DOM notation names (such as XmlRoot or XmlChldren[2]).

Referencing the last element on the left side of an expression

The following rules apply to the meaning of the last component on the left side of an expression:

  • The component name is an element structure key name (XML property name), such as XmlComment, ColdFusion sets the value of the specified element structure entry to the value of the right side of the expression. For example, the following line sets the XML comment in the mydoc.employee.name[1].first element to "This is a comment":
    mydoc.employee.name[1].first.XmlComment = "This is a comment";
  • If the component name specifies an element name and does not end with a numeric index, for example mydoc.employee.name, ColdFusion assigns the value on the right of the expression to the first matching element.

    For example, if both mydoc.employee.name[1] and mydoc.employee.name[2] exist, the following expression replaces mydoc.employee.name[1] with a new element named address, not an element named name:

    mydoc.employee.name = XmlElemNew(mydoc, "address");

    After executing this line, if there had been both mydoc.employee.name[1] and mydoc.employee.name[2], there is now only one mydoc.employee.name element with the contents of the original mydoc.employee.name[2].

  • If the component name does not match an existing element, the element names on the left and right sides of the expression must match. ColdFusion creates a new element with the name of the element on the left of the expression. If the element names do not match, it generates an error.

    For example if there is no mydoc.employee.name.phoneNumber element, the following expression creates a new mydoc.employee.name.phoneNumber element:

    mydoc.employee.name.phoneNumber = XmlElemNew(mydoc, "phoneNumber");

    The following expression causes an error:

    mydoc.employee.name.phoneNumber = XmlElemNew(mydoc, "address");
  • If the component name does not match an existing element and the component’s parent or parents also do not exist, ColdFusion creates any parent nodes as specified on the left side and use the previous rule for the last element. For example, if there is no mydoc.employee.phoneNumber element, the following expression creates a phoneNumber element containing an AreaCode element:
    mydoc.employee.name.phoneNumber.AreaCode = XmlElemNew(mydoc, "AreaCode");

Assigning and retrieving CDATA values

To identify that element text is CDATA by putting it inside CDATA start and end marker information items, assign the text to the XmlCdata element, not the XmlText element. You must do this because ColdFusion escapes the < and > symbols in the element text when you assign it to an XmlText entry. You can assign a value to an element’s XmlText entry or its XmlCdata entry, but not to both, as each assignment overwrites the other.

When you retrieve data from the document object, references to XmlCdata and XmlText return the same string.

The following example shows how ColdFusion handles CDATA text:

<cfscript>
    myCDATA = "This is CDATA text";
    MyDoc = XmlNew();
    MyDoc.xmlRoot = XmlElemNew(MyDoc,"myRoot");
    MyDoc.myRoot.XmlChildren[1] = XmlElemNew(MyDoc,"myChildNodeCDATA");
    MyDoc.myRoot.XmlChildren[1].XmlCData = "#myCDATA#";
</cfscript>

<h3>Assigning a value to MyDoc.myRoot.XmlChildren[1].XmlCdata.</h3>
<cfoutput>
    The type of element MyDoc.myRoot.XmlChildren[1] is: #MyDoc.myRoot.XmlChildren[1].XmlType#<br>
    The value when output using XmlCdata is: #MyDoc.myRoot.XmlChildren[1].XmlCData#<br>
    The value when output using XmlText is: #MyDoc.myRoot.XmlChildren[1].XmlText#<br>
</cfoutput>
<br>
The XML text representation of Mydoc is:
<cfoutput><XMP>#tostring(MyDoc)#</XMP></cfoutput>

<h3>Assigning a value to MyDoc.myRoot.XmlChildren[1].XmlText.</h3>
<cfset MyDoc.myRoot.XmlChildren[1].XmlText = "This is XML plain text">
<cfoutput>
    The value when output using XmlCdata is: #MyDoc.myRoot.XmlChildren[1].XmlCData#<br>
    The value when output using XmlText is: #MyDoc.myRoot.XmlChildren[1].XmlText#<br>
</cfoutput>
<br>
The XML text representation of Mydoc is:
<cfoutput><XMP>#tostring(MyDoc)#</XMP></cfoutput>


Creating and saving an XML document object

The following sections show the ways you can create and save an XML document object. The specific technique that you use will depend on the application and your coding style.

  • Creating a new XML document object using the cfxml tag
  • Creating a new XML document object using the XmlNew function
  • Creating an XML document object from existing XML

Creating a new XML document object using the cfxml tag

The cfxml tag creates an XML document object that consists of the XML markup in the tag body. The tag body can include CFML code. ColdFusion processes the CFML code and includes the resulting output in the XML. The following example shows a simple cfxml tag:

<cfset testVar = True>
<cfxml variable="MyDoc">
    <MyDoc>
        <cfif testVar IS True>
            <cfoutput>The value of testVar is True.</cfoutput>
        <cfelse>
            <cfoutput>The value of testVar is False.</cfoutput>
        </cfif>
        <cfloop index = "LoopCount" from = "1" to = "4">
            <childNode>
                This is Child node <cfoutput>#LoopCount#.</cfoutput>
            </childNode>
        </cfloop>
    </MyDoc>
</cfxml>
<cfdump var=#MyDoc#>

This example creates a document object with a root element MyDoc, which includes text that displays the value of the ColdFusion variable testVar. MyDoc has four nested child elements, which are generated by an indexed cfloop tag. The cfdump tag displays the resulting XML document object.

Note: When you use the cfxml tag, do not include an <?xml ?> processing directive in the tag body. This directive is not required, and causes an error. To process XML text that includes the <?xml ?> directive, use the XmlParse function.

Creating a new XML document object using the XmlNew function

The XmlNew function creates a new XML document object, which you must then populate. For information on how to populate a new XML document, see Adding, deleting, and modifying XML elements.

Note: You cannot set the XmlDocType property for an XML document object that you create with the XmlNew function.

The following example creates and displays the same ColdFusion document object as in Creating a new XML document object using the cfxml tag.

<cfset testVar = True>
<cfscript>
    MyDoc = XmlNew();
    MyDoc.xmlRoot = XmlElemNew(MyDoc,"MyRoot");
    if (testVar IS TRUE)
        MyDoc.MyRoot.XmlText = "The value of testVar is True.";
    else
        MyDoc.MyRoot.XmlText = "The value of testVar is False.";
    for (i = 1; i LTE 4; i = i + 1)
        {
        MyDoc.MyRoot.XmlChildren[i] = XmlElemNew(MyDoc,"childNode");
        MyDoc.MyRoot.XmlChildren[i].XmlText = "This is Child node " & i &".";
        }
</cfscript>
<cfdump var=#MyDoc#>

Creating an XML document object from existing XML

The XmlParse function converts an XML document or document fragment represented as text into a ColdFusion document object. You can use a string variable containing the XML or the name or URL of a file that contains the text. For example, if your application uses cfhttp action="get" to get the XML document, use the following line to create the XML document object:

<cfset myXMLDocument = XmlParse(cfhttp.fileContent)>

The following example converts an XML text document is in a file to an XML document object:

C:\temp\myxmldoc.xml" variable="XMLFileText">
<cfset myXMLDocument=XmlParse("C:\temp\myxmldoc.xml" variable=")>

The XmlParse function takes a second, optional, attribute that specifies whether to maintain the case of the elements and attributes in the document object. The default is to have the document object be case-insensitive. For more information on case-sensitivity, see Referencing the contents of an XML object.

The XmlParse function also lets you specify a DTD or Schema to validate the XML text; if the XML is not valid, ColdFusion MX generates an error. You can specify the filename or URL of the validator, or the DTD or Schema can be in a CFML variable. You can also tell ColdFusion MX to use a DTD or Schema that is identified in the XML text. If you specify validation, you must also specify whether the document is be case-sensitive. The following example validates an XML document on file using a DTD that it specifies using a URL:

myDoc=XMLParse("C:\CFusionMX7\wwwroot\examples\custorder.xml", false,
        "http://localhost:8500/examples/custorder.dtd")>

Saving and exporting an XML document object

The ToString function converts an XML document object to a text string. You can then use the string variable in any ColdFusion tag or function.

To save the XML document in a file, use the ToString function to convert the document object to a string variable, then use the cffile tag to save the string as a file. For example, use the following code to save the XML document myXMLDocument in the file C:\temp\myxmldoc.xml:

<cfset XMLText=ToString(myXMLDocument)>
<cffile action="write" file="C:\temp\myxmldoc.xml" output="#XMLText#">


Modifying a ColdFusion XML object

As with all ColdFusion structured objects, you can often use a number of methods to change the contents of an XML document object. For example, you often have the choice of using an assignment statement or a function to update the contents of a structure or an array. The following section describes the array and structure functions that you can use to modify an XML document object. The section XML document object management reference provides a quick reference to modifying XML document object contents. Later sections describe these methods for changing document content in detail.

  • Functions for XML object management
  • Treating elements with the same name as an array
  • XML document object management reference
  • Adding, deleting, and modifying XML elements
  • Using XML and ColdFusion queries

Functions for XML object management

The following table lists the ColdFusion array and structure functions that you can use to manage XML document objects and their functions, and describes their common uses. In several cases you can use either an array function or a structure function for a purpose, such as for deleting all of an element’s attributes or children.

Function | Use
ArrayLen | Determines the number of child elements in an element, that is, the number of elements in an element’s XmlChildren array.
ArrayIsEmpty | Determines whether an element has any elements in its XmlChildren array.
StructCount | Determines the number of attributes in an element’s XmlAttributes structure.
StructIsEmpty | Determines whether an element has any attributes in its XmlAttributes structure. Returns True if the specified structure, including the XML document object or an element, exists and is empty.
StructKeyArray StructKeyList | Gets an array or list with the names of all of the attributes in an element’s XmlAttributes structure. Returns the names of the children of an XML element.
ArrayInsertAt | Adds a new element at a specific location in an element’s XmlChildren array.
ArrayAppend ArrayPrepend | Adds a new element at the end or beginning of an element’s XmlChildren array.
ArraySwap | Swaps the children in the XmlChildren array at the specified position.
ArraySet | Sets a range of entries in an XmlChildren array to equal the contents of a specified element structure. Each entry in the array range will be a copy of the structure. Can be used to set a single element by specifying the same index as the beginning and end of the range.
ArrayDeleteAt | Deletes a specific element from an element’s XmlChildren array.
ArrayClear | Deletes all child elements from an element’s XmlChildren array.
StructDelete | Deletes a selected attribute from an element’s XMLAttributes structure. Deletes all children with a specific element name from an element’s XmlChildren array. Deletes all attributes of an element. Deletes all children of an element. Deletes a selected property value.
StructClear | Deletes all attributes from an element’s XMLAttributes structure.
Duplicate | Copies an XML document object, element, or node structure.
IsArray | Returns True for the XmlChildren array. Returns false if you specify an element name, such as mydoc.XmlRoot.name, even if there are multiple name elements in XmlRoot.
IsStruct | Returns False for XML document objects, elements, and nodes. Returns True for XmlAttributes structures.
StructGet | Returns the specified structure, including XML document objects, elements, nodes, and XmlAttributes structures.
StructAppend | Appends a document fragment XML document object to another XML document object.
StructInsert | Adds a new entry to an XmlAttributes structure.
StructUpdate | Sets or replaces the value of a document object property such as XmlName, or of a specified attribute in an XmlAttributes structure.

Note: Array and structure functions not in the preceding or table or the table in the next section, do not work with XML document objects, XML elements, or XML node structures.


Treating elements with the same name as an array

In many cases an XML element has multiple children with the same name. For example, the example document used in this chapter has multiple name elements in the employee elements. In many cases, you can treat the child elements with identical names as an array. For example, to reference the second name element in mydoc.employee, you can specify mydoc.employee.name[2]. However, you can only use a limited set of Array functions when you use this notation. The following table lists the array functions that are valid for such references:

Array function

Result

IsArray(elemPath.elemName)

Always returns False.

ArrayClear(elemPath.elemName)

Removes all the elements with name elemName from the elemPath element.

ArrayLen(elemPath.elemName)

Returns the number of elements named elemName in the elemPath element.

ArrayDeleteAt(elemPath.elemName, n)

Deletes the nth child named elemlName from the elemPath element.

ArrayIsEmpty(elemPath.elemName)

Always returns False.

ArrayToList(elemPath.elemName, n)

Returns a comma separated list of all the XmlText properties of all the children of elemPath named elemName.


XML document object management reference

The following tables provide a quick reference to the ways you can modify the contents of an XML document object. The sections that follow describe in detail how to modify XML contents.

Note: If your XML object is case sensitive, you cannot use dot notation to reference an element or attribute name. Use the name in associative array (bracket) notation, or a reference that does not use the case-sensitive name (such as xmlChildren[1]) instead.

Adding information to an element

Use the following techniques to add new information to an element:

Type

Using a function

Using an assignment statement

Attribute

StructInsert(xmlElemPath.XmlAttributes,
    "key", "value")

xmlElemPath.XmlAttributes.key =
    "value"

xmlElemPath.XmlAttributes["key"]
    = "value"

Child element

To append:

ArrayAppend(xmlElempath.XmlChildren,
    newElem)

To insert:

ArrayInsertAt(xmlElempath.
    XmlChildren, position, newElem)

To append:

xmlElemPath.XmlChildren[i] =
    newElem

xmlElemPath.newChildName =
    newElem

(where newChildName must be the same as newElem.XmlName and cannot be an indexed name such as name[3])

Deleting information from an element

Use the following techniques to delete information from an element:

Type

Using a function

Using an assignment statement

Property

StructDelete(xmlElemPath, propertyName)

xmlElemPath.propertyName=""

Attribute

All attributes:

StructDelete(xmlElemPath, XmlAttributes)

A specific attribute:

StructDelete(xmlElemPath.XmlAttributes,
"attributeName")

Not available

Child element

All children of an element:

StructDelete(xmlElemPath, "XmlChildren")
or
ArrayClear(xmlElemPath.XmlChildren)

All children with a specific name:

StructDelete(xmlElementpath,
    "elemName")
ArrayClear(xmlElemPath.elemName)

A specific child:

ArrayDeleteAt(xmlElemPath.XmlChildren,
    position)
ArrayDeleteAt(xmlElemPath.elemName,
    position)

Not available

Changing contents of an element

Use the following techniques to change the contents of an element:

Type

Using a function

Using an assignment statement

Property

StructUpdate(xmlElemPath,
    "propertyName", "value")

xmlElemPath.propertyName =
    "value"

xmlElemPath["propertyName"] =
    "value"

Attribute

StructUpdate(xmlElemPath.XmlAttributes,
    "attributeName", "value")

xmlElemPath.XmlAttributes.
    attributeName="value"

xmlElemPath.XmlAttributes
    ["attributeName"] = "value"

Child element

(replace)

ArraySet(xmlElemPath.XmlChildren, index,
    index, newElement)

(use the same value for both index entries to change one element)

Replace first or only child named elementName:

parentElemPath.elementName =
    newElement

parentElemPath["elementName"]
    = newElement

Replace a specific child named elementName:

parentElemPath.elementName
    [index] = newElement

or

parentElemPath["elementName"]
    [index] = newElement


Adding, deleting, and modifying XML elements

The following sections describe the basic techniques for adding, deleting, and modifying XML elements. The example code uses the XML document described in A simple XML document.

Counting and finding the position of child elements

Often, an XML element has several children with the same name. For example, in the XML document defined in the simple XML document, the employee root element has multiple name elements.

To manipulate such an object, you often need to know the number of children of the same name, and you might need to know the position in the XmlChildren array of a specific child name that is used for multiple children. The following sections describe how to get this information.

Counting child elements

The following user-defined function determines the number of child elements with a specific name in an element:

<cfscript>
function NodeCount (xmlElement, nodeName)
{
    nodesFound = 0;
    for (i = 1; i LTE ArrayLen(xmlElement.XmlChildren); i = i+1)
    {
        if (xmlElement.XmlChildren[i].XmlName IS nodeName)
            nodesFound = nodesFound + 1;
    }
    return nodesFound;
}
</cfscript>

The following lines use this function to display the number of nodes named "name" in the mydoc.employee element:

<cfoutput>
Nodes Found: #NodeCount(mydoc.employee, "name")#
</cfoutput>

Determining the position of a child element with a common name

The XmlChildPos function determines the location in the XmlChildren array of a specific element with a common name. You use this index when you need to tell ColdFusion where to insert or delete child elements. For example, if there are several name elements in mydoc.employee, use the following code to locate name[2] in the XmlChildren array:

<cfset nameIndex = XmlChildPos(mydoc.employee, "name", 2)>

Adding an element

You can add an element by creating a new element or by using an existing element.

Use the XmlElemNew function to create a new, empty element. This function has the following form:

XmlElemNew(docObject, elementName)

where docObject is the name of the XML document object in which you are creating the element, and elementName is the name you are giving the new element.

Use an assignment statement with an existing element on the right side to create a new element using an existing element. See Copying an existing element for more information on adding elements using existing elements.

Adding an element using a function

You can use the ArrayInsertAt or ArrayAppend functions to add an element to an XML document object. For example, the following line adds a phoneNumber element after the last element for employee.name[2]:

<cfset ArrayAppend(mydoc.employee.name[2].XmlChildren, XmlElemNew(mydoc,
            "phoneNumber"))>

The following line adds a new department element as the first element in employee. The name elements become the second and third elements.

<cfset ArrayInsertAt(mydoc.employee.XmlChildren, 1, XmlElemNew(mydoc,
            "department"))>

You must use the format parentElement.XmlChildren to specify the array of elements to which you are adding the new element. For example, the following line causes an error:

<cfset ArrayInsertAt(mydoc.employee.name, 2, XmlElemNew(mydoc, "PhoneNumber")>

If you have multiple child elements with the same name, and you want to insert a new element in a specific position, use the XmlChildPos function to determine the location in the XmlChildren array where you want to insert the new element. For example, the following code determines the location of mydoc.employee.name[1] and inserts a new name element as the second name element:

<cfscript>
nameIndex = XmlChildPos(mydoc.employee, "name", 1);
ArrayInsertAt(mydoc.employee.XmlChildren, nameIndex + 1, XmlElemNew(mydoc,
                    "name"));
</cfscript>

Using a namespace When you use a function to add an element, you can assign the element to a namespace by including the namespace prefix in the element name. If you have not yet associated the prefix with a namespace URI, you must also include a parameter with the namespace URI in the XmlElemNew function. This parameter must be the second parameter in the method, and the element name must be the third parameter. ColdFusion MX then associates the namespace prefix with the URI, and you can omit the URI parameter in further xmlElemNew functions.

The following example adds two to the supplies document root two elements in the Prod namespace. The first XmlElemNew function use sets the association between the Prod namespace prefix and the URI; the second use only needs to specify the prefix on the element name.

<cfscript>
    mydoc.supplies.XmlChildren[1] = XmlElemNew(mydoc,
    "http://www.foo.com/Products", "Prod:soap");
    mydoc.supplies.XmlChildren[2] = XmlElemNew(mydoc, "Prod:shampoo");
</cfscript>

Adding an element using direct assignment

You can use direct assignment to append a new element to an array of elements. You cannot use direct assignment to insert an element into an array of elements.

When you use direct assignment, you can specify on the left side an index into the XmlChildren array greater than the last child in the array. For example, if there are two elements in mydoc.employee, you can specify any number greater than two, such as mydoc.employee.XmlChildren[6]. The element is always added as the last (in this case, third) child.

For example, the following line appends a name element to the end of the child elements of mydoc.employee:

<cfset mydoc.employee.XmlChildren[9] = XmlElemNew(mydoc, "name")>

If the parent element does not have any children with the same name as the new child, you can specify the name of the new node or the left side of the assignment. For example, the following line appends a phoneNumber element to the children of the first name element in mydoc.employee:

<cfset mydoc.employee.name[1].phoneNumber = XmlElemNew(mydoc, "phoneNumber")>

You cannot use the node name on the left to add an element with the same name as an existing element in the parent. For example, if mydoc.employee has two name nodes, the following line causes an error:

<cfset mydoc.employee.name[3] = XmlElemNew(mydoc, "name")>

However, the following line does work:

<cfset mydoc.employee.XmlChilren[3] = XmlElemNew(mydoc, "name")>

Copying an existing element

You can add a copy of an existing element elsewhere in the document. For example, if there is a mydoc.employee.name[1].phoneNumber element, but no mydoc.employee. name[2].phoneNumber, the following line creates a new mydoc.employee. name[2]. phoneNumber element with the same value as the original element. This assignment copies the original element. Unlike with standard ColdFusion structures, you get a true copy, not a reference to the original structure. You can change the copy without changing the original.

<cfset mydoc.employee.name[2].phoneNumber = mydoc.employee.name[1].phoneNumber>

When you copy an element, the new element must have the same name as the existing element. If you specify the new element by name on the left side of an assignment, the element name must be the same as the name on the right side. For example, the following expression causes an error:

<cfset mydoc.employee.name[2].telephne = mydoc.employee.name[1].phoneNumber>

Deleting elements

There are many ways to delete individual or multiple elements.

Deleting individual elements

Use the ArrayDeleteAt function to delete a specific element from an XML document object. For example, the following line deletes the second child element in the mydoc.employee element:

<cfset ArrayDeleteAt(mydoc.employee.XmlChildren, 2)>

If an element has only one child element with a specific name, you can also use the StructDelete function to delete the child element. For example, the following line deletes the phoneNumber element named in the second employee.name element:

<cfset StructDelete(mydoc.employee.name[2], "phoneNumber")>

When there are multiple child elements of the same name, you must specify the element position, either among the elements of the same name, or among all child elements. Fore example, you can use the following line to delete the second name element in mydoc.employee:

<cfset ArrayDeleteAt(mydoc.employee.name, 2)>

You can also determine the position in the XmlChildren array of the element you want to delete and use that position. To do so, use the XmlChildPos function. For example, the following lines determine the location of mydoc.employee.name[2] and delete the element:

<cfset idx = XmlChildPos(mydoc.employee, "name", 2)>
<cfset ArrayDeleteAt(mydoc.employee.XmlChildren, idx)>

Deleting multiple elements

If an element has multiple children with the same name, use the StructDelete function or ArrayClear function with an element name to delete all of an element’s child elements with that name. For example, both of the following lines delete all name elements from the employee structure:

<cfset StructDelete(mydoc.employee, "name")>
<cfset ArrayClear(mydoc.employee.name)>

Use the StructDelete or ArrayClear function with XmlChildren to delete all of an element’s child elements. For example, each of the following lines deletes all child elements of the mydoc.employee.name[2] element:

<cfset StructDelete(mydoc.employee.name[2], "XmlChildren")>
<cfset ArrayClear(mydoc.employee.name[2].XmlChildren)>

Adding, changing, and deleting element attributes

You modify an element’s attributes the same way you change the contents of any structure. For example, each of the following lines adds a Status attribute the second mydoc.employee.name element:

<cfset mydoc.employee.name[2].XmlAttributes.Status="Inactive">
<cfset StructInsert(mydoc.employee.name[2].XmlAttributes, "Status", "Inactive")>

To change an attribute, use a standard assignment statement; for example:

<cfset mydoc.employee.name[2].XmlAttributs.Status="Active">

To delete an attribute, use StructDelete; for example:

<cfset StructDelete(mydoc.employee.name[1].XmlAttributes, "Status")>

Changing element properties

To change an element’s properties, including its text and comment, use a standard assignment expression. For example, use the following line to add "in the MyCompany Documentation Department" to the mydoc.employee XML comment:

<cfset mydoc.employee.XmlComment = mydoc.employee.XmlComment & "in the
MyCompany Documentation Department">

Changing an element name

The XML DOM does not support changing an element name directly. To change the name of an element, you must create a new element with the new name, insert it into the XML document object before or after the original element, copy all the original element’s contents to the new element, and then delete the original element.

Clearing an element property value

To clear an element property value, either assign the empty string to the property or use the StructDelete function. For example, each of the following lines clears the comment string from mydoc.employee:

<cfset mydoc.employee.XmlComment = "">
<cfset StructDelete(mydoc.employee, "XmlComment")>

Replacing or moving an element

To replace an element with a new element, use a standard replacement expression. For example, to replace the mydoc.employee.department element with a new element named organization, use either of the following lines:

<cfset mydoc.employee.department = XmlElemNew(mydoc, "Organization")>
<cfset mydoc.employee.XmlChildren[1] = XmlElemNew(mydoc, "Organization")>

To replace an element with a copy of an existing element, use the existing element on the right side of an expression. For example, the following line replaces the phoneNumber element for mydoc.employee.name[2] with the phoneNumber element from mydoc.employee.name[1]:

<cfset mydoc.employee.name[2].phoneNumber=mydoc.employee.name[1].phoneNumber>

This creates a true copy of the name[1].phoneNumber element as name[2].phoneNumber.

To move an element, you must assign it to its new location, then delete it from its old location. For example, the following lines move the phoneNumber element from mydoc.employee.name[1] to mydoc.employee.name[2]:

<cfset mydoc.employee.name[2].phoneNumber=mydoc.employee.name[1].phoneNumber>
<cfset StructDelete(mydoc.employee.name[1], "phoneNumber")>

Note: You cannot copy or move an element from one document object to another document object.


Using XML and ColdFusion queries

You can convert XML documents into ColdFusion query objects and manipulate them using queries of queries. This technique does not require the use of XPath and provides a method of searching XML documents and extracting data that is natural to ColdFusion programmers.

Converting XML to a ColdFusion query

The following example reads an XML document, converts it to a query object, and then performs a query of queries on the object to extract selected data:

<!--- Read the file and convert it to an XML document object --->
<cffile action="read" file="C:\CFusionMX7\wwwroot\myexamples\employees.xml" variable="myxml">
<cfset mydoc = XmlParse(myxml)>

<!--- get an array of employees --->
<cfset emp = mydoc.employee.XmlChildren>
<cfset size = ArrayLen(emp)>

<cfoutput>
Number of employees = #size#
<br>
</cfoutput>
<br>
<!--- create a query object with the employee data --->
<cfset myquery = QueryNew("fname, lname") >
<cfset temp = QueryAddRow(myquery, #size#)>
<cfloop index="i" from = "1" to = #size#>
    <cfset temp = QuerySetCell(myquery, "fname",
        #mydoc.employee.name[i].first.XmlText#, #i#)>
    <cfset temp = QuerySetCell(myquery, "lname",
        #mydoc.employee.name[i].last.XmlText#, #i#)>
</cfloop>

<!--- Dump the query object --->
Contents of the myquery Query object: <br>
<cfdump var=#myquery#>
<br><br>

<!--- Select entries with the last name starting with A and dump the result --->
<cfquery name="ImqTest" dbType="query">
    SELECT lname, fname
    FROM myquery
    WHERE lname LIKE 'A%'
</cfquery>
<cfdump var=#imqtest#>

Converting a query object to XML

The following example shows how to convert a query object to XML. It uses cfquery to get a list of employees from the cfdocexamples database and saves the information as an XML document.

<!--- Query the database and get the names in the employee table --->
<cfquery name="myQuery" datasource="cfdocexamples">
    SELECT FirstName, LastName
    FROM employee
</cfquery>

<!--- Create an XML document object containing the data --->
<cfxml variable="mydoc">
    <employee>
        <cfoutput query="myQuery">
             <name>
                <first>#FirstName#</first>
                <last>#LastName#</last>
            </name>
        </cfoutput>
    </employee>
</cfxml>

<!--- dump the resulting XML document object --->
<cfdump var=#mydoc#>
<!--- Write the XML to a file --->
<cffile action="write" file="C:\inetpub\wwwroot\xml\employee.xml"
        output=#toString(mydoc)#>


Validating XML documents

ColdFusion MX provides the following methods for validating a document against a DTD or an XML Schema:

  • The XmlParse function can validate XML text that it is parsing against a DTD or Schema. It the function encounters a validation error, ColdFusion generates an error and stops parsing the text. If the validator generates warnings, but no errors, ColdFusion parses the document and returns the result.
  • The XmlValidate function can validate an XML text document or XML document object. against a DTD or Schema. The function returns a data structure with detailed information from the validator, including arrays of warning, error, and fatal error messages, and a Boolean status variable indicating whether the document is valid. Your application can examine the status information and determine how to handle it further.

For examples of XML validation, see XmlParse and XmlValidate in CFML Reference. The XmlParse example validates a document using a DTD. The XmlValidate example validates the document using an XML Schema that represents the same document structure as the DTD.


Transforming documents with XSLT

The Extensible Stylesheet Language Transformation (XSLT) technology transforms an XML document into another format or representation. For example, one common use of XSLT is to convert XML documents into HTML for display in a browser. XSLT has many other uses, including converting XML data to another format, such as converting XML in a vocabulary used by an order entry application into a vocabulary used by an order fulfillment application.

XSLT transforms an XML document by applying an Extensible Stylesheet Language (XSL) stylesheet. (When stored in a file, XSL stylesheets typically have the suffix xsl.) ColdFusion provides the XmlTransform function to apply an XSL transformation to an XML document. The function takes an XML document in string format or as an XML document object, and an XSL stylesheet in string format, and returns the transformed document as a string.

The following code:

  1. Reads the simpletransform.xsl stylesheet file into a string variable.
  2. Uses the stylesheet to transform the mydoc XML document object.
  3. Saves the resulting transformed document in a second file.
<cffile action="read" file="C:\CFusionMX7\wwwroot\testdocs\simpletransform.xsl"
    variable="xslDoc">
<cfset transformedXML = XmlTransform(mydoc, xslDoc)>
<cffile action="write" file="C:\CFusionMX7\wwwroot\testdocs\transformeddoc.xml"
    output=transformedXML>

XSL and XSLT are specified by the World Wide Web Consortium (W3C). For detailed information on XSL, XSLT, and XSL stylesheets, see the W3C website at
www.w3.org/Style/XSL/. There are also several books available on using XSL and XSLT.


Extracting data with XPath

XPath is a language for addressing parts of an XML document. Like XSL, XPath is a W3C specification. One of the major uses of XPath is in XSL transformations. However, XPath has more general uses. In particular, it can extract data from XML documents, such as complex data set representations. Thus, XPath is another data querying tool.

XPath uses a pattern called an XPath expression to specify the information to extract from an XML document. For example, the simple XPath expression /employee/name selects the name elements in the employee root element.

The XmlSearch function uses XPath expressions to extract data from XML document objects. The function takes an XML document object and an XPath expression in string format, and returns an array of XML document objects containing the elements that meet the expression criteria.

The following example extracts all the elements named last, which contain the employee’s last names, from the employeesimple.xml file, and displays the names:

<cffile action="read"
    file="C:\inetpub\wwwroot\examples\employeesimple.xml"
    variable="myxml">
<cfscript>
    myxmldoc = XmlParse(myxml);
    selectedElements = XmlSearch(myxmldoc, "/employee/name/last");
    for (i = 1; i LTE ArrayLen(selectedElements); i = i + 1)
        writeoutput(selectedElements[i].XmlText & "<br>");
</cfscript>

XPath is specified by the World-Wide Web Consortium. For detailed information on XPath, see the W3C website at www.w3.org/TR/xpath. Most books that cover XSLT also discuss XPath.


Example: using XML in a ColdFusion application

The example in this section shows how you can use XML to represent data, and how ColdFusion can use XML data in an application. Although the example is too simple to be used in an application without substantial changes, it presents some of the common uses of XML with ColdFusion.

The example receives an order in the form of an XML document, processes it, and generates an XML receipt document. In this case, the order document is in a file, but it could be received as the result of an HTTP request, or retrieved using cfpop, cfftp, or other methods. The ColdFusion page does the following with the order:

  1. Generates a query object from an XML document.
  2. Queries a database table to determine the order discount percentage to use.
  3. Uses a query of queries to calculate the total price, then calculates the discounted price.
  4. Generates the receipt as an XML document.

This example displays the results of the processing steps to show you what has been done.

The XML document

The order.xml document has the following structure:

  • The root element is named order and has one attribute, id.
  • There is one customer element with firstname, lastname, and accountnum attributes. The customer element does not have a body
  • There is one items element that contains multiple item elements
  • Each item element has an id attribute and contains a name, quantity, and unitprice element. The name, quantity, and unitprice elements contain their value as body text.

The following order.xml document works correctly with the information in the cfdocexamples database:

<order id="4323251">
    <customer firstname="Philip" lastname="Cramer" accountNum="21"/>
    <items>
        <item id="43">
            <name>
                Large Hammer
            </name>
            <quantity>
                1
            </quantity>
            <unitprice>
                15.95
            </unitprice>
        </item>
        <item id="54">
            <name>
                Ladder
            </name>
            <quantity>
                2
            </quantity>
            <unitprice>
                40.95
            </unitprice>
        </item>
        <item id="68">
            <name>
                Paint
            </name>
            <quantity>
                10
            </quantity>
            <unitprice>
                18.95
            </unitprice>
        </item>
    </items>
</order>

The ColdFusion page

The ColdFusion page looks like the following:

<!--- Convert file to XML document object --->
<cffile action="read" file="C:\CFusionMX7\wwwroot\examples\order.xml" variable="myxml">
<cfset mydoc = XmlParse(myxml)>

<!--- Extract account number --->
 <cfset accountNum=#mydoc.order.customer.XmlAttributes.accountNum#>
<!--- Display Order Information --->
<cfoutput>
    <b>Name=</b>#mydoc.order.customer.XmlAttributes.firstname#
         #mydoc.order.customer.XmlAttributes.lastname#
    <br>
    <b>Account=</b>#accountNum#
    <br>
    <cfset numItems = ArrayLen(mydoc.order.items.XmlChildren)>
    <b>Number of items ordered=</b> #numItems#
</cfoutput>
<br><br>

<!--- Process the order into a query object --->
<cfset orderquery = QueryNew("item_Id, name, qty, unitPrice") >
<cfset temp = QueryAddRow(orderquery, #numItems#)>
<cfloop index="i" from = "1" to = #numItems#>
    <cfset temp = QuerySetCell(orderquery, "item_Id",
        #mydoc.order.items.item[i].XmlAttributes.id#,#i#)>
    <cfset temp = QuerySetCell(orderquery, "name",
        #mydoc.order.items.item[i].name.XmlText#, #i#)>
    <cfset temp = QuerySetCell(orderquery, "qty",
        #mydoc.order.items.item[i].quantity.XmlText#, #i#)>
    <cfset temp = QuerySetCell(orderquery, "unitPrice",
        #mydoc.order.items.item[i].unitprice.XmlText#, #i#)>
</cfloop>

<!--- Display the order query --->
<cfdump var=#orderquery#>
<br><br>

<!--- Determine the discount --->
<cfquery name="discountQuery" datasource="cfdocexamples">
    SELECT *
    FROM employee
    WHERE Emp_Id = #accountNum#
</cfquery>
<cfset drate = 0>
<cfif #discountQuery.RecordCount# is 1>
    <cfset drate = 10>
</cfif>

<!--- Display the discount rate --->
<cfoutput>
    <b>Discount Rate =</b> #drate#%
</cfoutput>
<br><br>

<!--- Compute the total cost and discount price--->
<cfquery name="priceQuery" dbType="query">
    SELECT SUM(qty*unitPrice)
    AS totalPrice
    FROM orderquery
</cfquery>
<cfset discountPrice = priceQuery.totalPrice * (1 - drate/100)>

<!--- Display the full price and discounted price --->
<cfoutput>
    <b>Full Price=</b> #priceQuery.totalPrice#<br>
    <b>Discount Price=</b> #discountPrice#
</cfoutput>
<br><br>

<!---Generate an XML Receipt --->
<cfxml variable="receiptxml">
<receipt num = "34">
    <cfoutput>
        <price>#discountPrice#</price>
        <cfif drate GT 0 >
          <discountRate>#drate#</discountRate>
        </cfif>
    </cfoutput>
    <itemsFilled>
        <cfoutput query="orderQuery">
                <name>	#name# </name>
                <qty>   #qty# </qty>
                <price> #qty*unitPrice# </price>
        </cfoutput>
    </itemsFilled>
</receipt>
</cfxml>

<!--- Display the resulting receipt --->
<cfdump var=#receiptxml#>

Reviewing the code

The following table describes the CFML code and its function. For the sake of brevity, it does not include code that displays the processing results.

Code

Description

<cffile action="read"
file="C:\CFusionMX7\wwwroot\examples\order.xml"
    variable="myxml">
<cfset mydoc = XmlParse(myxml)>
<cfset accountNum=#mydoc.order.
    customer.XmlAttributes.accountNum#>

Reads the XML from a file and convert it to an XML document object.

Sets the accountNum variable from the customer entry’s accountnum attribute.

<cfset orderquery = QueryNew("item_Id,
    name, qty, unitPrice") >
<cfset temp = QueryAddRow(orderquery,
    #numItems#)>
<cfloop index="i" from = "1" to = #numItems#>
  <cfset temp = QuerySetCell(orderquery,
     "item_Id", #mydoc.order.items.item[i].
     XmlAttributes.id#, #i#)>
  <cfset temp = QuerySetCell(orderquery,
     "name", #mydoc.order.items.item[i].
     name.XmlText#, #i#)>
  <cfset temp = QuerySetCell(orderquery,
     "qty", #mydoc.order.items.item[i].
     quantity.XmlText#, #i#)>
  <cfset temp = QuerySetCell(orderquery,
     "unitPrice", #mydoc.order.items.item[i].
     unitprice.XmlText#, #i#)>
</cfloop>

Converts the XML document object into a query object.

Creates a query with columns for the item_id, name, qty, and unitPrice values for each item.

For each XML item entry in the mydoc.order.items entry, fills one row of the query with the item’s id attribute and the text in the name, quantity, and unitprice entries that the it contains.

<cfquery name="discountQuery"
      datasource="cfdocexamples">
    SELECT *
    FROM employee
    WHERE Emp_Id = #accountNum#
</cfquery>
<cfset drate = 0>
<cfif #discountQuery.RecordCount# is 1>
    <cfset drate = 10>
</cfif>

If the account number is the same as an employee ID in the cfdocexamples database Employee table, the query returns one record. and RecordCount equals 1. In this case, sets a discount rate of 10%. Otherwise, sets a discount rate of 0%.

<cfquery name="priceQuery" dbType="query">
    SELECT SUM(qty*unitPrice)
    AS totalPrice
    FROM orderquery
</cfquery>
<cfset discountPrice = priceQuery.totalPrice
    * (1 - drate/100)>

Uses a query of queries with the SUM operator to calculate the total cost before discount of the ordered items, then applies the discount to the price. The result of the query is a single value, the total price.

<cfxml variable="receiptxml">
 <receipt num = "34">
  <cfoutput>
   <price>#discountPrice#</price>
   <cfif drate GT 0 >
    <discountRate>#drate#</discountRate>
    </cfif>
  </cfoutput>
  <itemsFilled>
   <cfoutput query="orderQuery">
    <name>	#name# </name>
    <qty>   #qty# </qty>
    <price> #qty*unitPrice# </price>
   </cfoutput>
  </itemsFilled>
 </receipt>
</cfxml>

Creates an XML document object as a receipt. The receipt has a root element named receipt, which has the receipt number as an attribute. The receipt element contains a price element with the order cost and an itemsFilled element with one item element for each item.


Moving complex data across the web with WDDX

WDDX is an XML vocabulary for describing a complex data structure, such as an array, associative array (such as a ColdFusion structure), or a recordset, in a generic fashion. It lets you use HTTP to move the data between different application server platforms and between application servers and browsers. Target platforms for WDDX include ColdFusion, Active Server Pages (ASP), JavaScript, Perl, Java, Python, COM, Macromedia Flash, and PHP.

The WDDX XML vocabulary consists of a document type definition (DTD) that describes the structure of standard data types and a set of components for each of the target platforms to do the following:

  • Serialize the data from its native representation into a WDDX XML document or document fragment.
  • Deserialize a WDDX XML document or document fragment into the native data representation, such as a CFML structure.

This vocabulary creates a way to move data, its associated data types, and descriptors that allow the data to be manipulated on a target system, between arbitrary application servers.

Note: The WDDX DTD, which includes documentation, is located at
www.openwddx.org/downloads/dtd/wddx_dtd_10.txt.

WDDX is a valuable tool for ColdFusion developers, however, its usefulness is not limited to CFML. If you serialize a common programming data structure (such as an array, recordset, or structure) into WDDX format, you can use HTTP to transfer the data across a range of languages and platforms. Also, you can use WDDX to store complex data in a database, file, or even a client variable.

WDDX has two features that make it useful for transferring data in a web environment:

  • It is lightweight. The JavaScript used to serialize and deserialize data, including a debugging function to dump WDDX data, occupies less than 22K.
  • Unlike traditional client-server approaches, the source and target system can have minimal-to-no prior knowledge of each other. They only need to know the structure of the data that is being transferred.

WDDX was created in 1998, and many applications now expose WDDX capabilities. The best source of information about WDDX is www.openwddx.org. This site offers free downloads of the WDDX DTD and SDK and a number of resources, including a WDDX FAQ, a developer forum, and links to additional sites that provide WDDX resources.

This section includes the following topics:

  • Uses of WDDX
  • How WDDX works

Uses of WDDX

WDDX is useful for transferring complex data between applications. For example, you can use it to exchange data between a CFML application and a CGI or PHP application. WDDX is also useful for transferring data between the server and client-side JavaScript.

Exchanging data across application servers

WDDX is useful for the transfer of complex, structured data seamlessly between different application server platforms. For example, an application based on ColdFusion at one business could use cfwddx to convert a purchase order structure to WDDX. It could then use cfhttp to send the WDDX to a supplier running a CGI-based system.

The supplier could then deserialize the WDDX to its native data form, the extract information from the order, and pass it to a shipping company running an application based on ASP.

Transferring data between the server and browser

You can use WDDX for server-to-browser and browser-to-server data exchanges. You can transfer server data to the browser in WDDX format and convert it to JavaScript objects on the browser. Similarly, your application pages can serialize JavaScript data generated on the browser into WDDX format and transfer the data to the application server. You then deserialize the WDDX XML into CFML data on the server.

On the server you use the cfwddx tag to serialize and deserialize WDDX data. On the browser, you use WddxSerializer and WddxRecordset JavaScript utility classes to serialize the JavaScript data to WDDX. (ColdFusion installs these utility classes on your server as webroot/CFIDE/scripts/wddx.js.)

WDDX and web services

WDDX does not compete with web services. It is a complementary technology focused on solving simple problems of application integration by sharing data on the web in a pragmatic, productive manner at very low cost.

WDDX offers the following advantages:

  • It can be used by lightweight clients, such as browsers or the Macromedia Flash player.
  • It can be used to store complex data structures in files and databases.

Applications that take advantage of WDDX can continue to do so if they start to use web services. These applications could also be converted to use web services standards exclusively; only the service and data interchange formats--not the application model--must change.

How WDDX works

The following example shows how WDDX works. A simple structure with two string variables might have the following form after it is serialized into a WDDX XML representation:

<var name='x'>
    <struct>

        <var name='a'>
            <string>Property a</string>
        </var>
        <var name='b'>
            <string>Property b</string>
        </var>
    </struct>
</var>

When you deserialize this XML into CFML or JavaScript, the result is a structure that is created by either of the following scripts:

JavaScript

CFScript

x = new Object();
x.a = "Property a";
x.b = "Property b";

x = structNew();
x.a = "Property a";
x.b = "Property b";

Conversely, when you serialize the variable x produced by either of these scripts into WDDX, you generate the XML listed above.

ColdFusion provides a tag and JavaScript objects that convert between CFML, WDDX, and JavaScript. Serializers and deserializers for other data formats are available on the web. For more information, see www.openwddx.org.

Note: The cfwddx tag and the wddx.js JavaScript functions use UTF-8 encoding to represent data. Any tools that deserialize ColdFusion-generated WDDX must accept UTF-8 encoded characters. UTF-8 encoding is identical to the ASCII and ISO 8859 single-byte encodings for the standard 128 "7-bit" ASCII characters. However, UTF-8 uses a two-byte representation for "high-ASCII" ISO 8859 characters where the initial bit is 1.

WDDX data type support

The following sections describe the data types that WDDX supports. This information is a distillation of the description in the WDDX DTD. For more detailed information, see the DTD at www.openwddx.org.

Basic data types

WDDX can represent the following basic data types:

Data type | Description
Null | Null values in WDDX are not associated with a type such as number or string. The cfwddx tag converts WDDX Nulls to empty strings.
Numbers | WDDX documents use floating point numbers to represent all numbers. The range of numbers is restricted to +/-1.7E+/-308. The precision is restricted to 15 digits after the decimal point.
Date-time values | Date-time values are encoded according to the full form of ISO8601; for example, 2002-9-15T09:05:32+4:0.
Strings | Strings can be of arbitrary length and must not contain embedded nulls. Strings can be encoded using double-byte characters.

Complex data types

WDDX can represent the following complex data types:

Data type | Description
Array | Arrays are integer-indexed collections of objects of arbitrary type. Because most languages start array indexes at 0, while CFML array indexes start at 1, working with array indices can lead to nonportable data.
Structure | Structures are string-indexed collections of objects of arbitrary type, sometimes called associative arrays. Because some of the languages supported by WDDX are not case-sensitive, no two variable names in a structure can differ only in their case.
Recordset | Recordsets are tabular rows of named fields, corresponding to ColdFusion query objects. Only simple data types can be stored in recordsets. Because some of the languages supported by WDDX are not case-sensitive, no two field names in a recordset can differ only in their case. Field names must satisfy the regular expression [_A-Za-z][_.0-9A-Za-z]* where the period (.) stands for a literal period character, not "any character".
Binary | The binary data type represents strings (blobs) of binary data. The data is encoded in MIME base64 format.

Data type comparisons

The following table compares the basic WDDX data types with the data types to which they correspond in the languages and technologies commonly used on the web:

WDDX | CFML | XML Schema | Java | ECMAScript/ JavaScript | COM
null | N/A | N/A | null | null | VT_NULL
boolean | Boolean | boolean | java.lang.Boolean | boolean | VT_BOOL
number | Number | number | java.lang.Double | number | VT_R8
dateTime | DateTime | dateTime | java.lang.Date | Date | VT_DATE
string | String | string | java.lang.String | string | VT_BSTR
array | Array | N/A | java.lang.Vector | Array | VT_ARRAY | VT_VARIANT
struct | Structure | N/A | java.lang. Hashtable | Object | IWDDXStruct
recordset | Query object | N/A | coldfusion.run time.QueryTable | WddxRecordset | IWDDXRecordset
binary | Binary | binary | byte[] | WddxBinary | V_ARRAY | UI1

Time zone processing

Producers and consumers of WDDX packets can be in geographically dispersed locations. Therefore, it is important to use time zone information when serializing and deserializing data, to ensure that date-time values are represented correctly.

The cfwddx action=cfml2wddx tag useTimezoneInfo attribute specifies whether to use time zone information in serializing the date-time data. In the JavaScript implementation, useTimezoneInfo is a property of the WddxSerializer object. In both cases the default useTimezoneInfo value is True.

Date-time values in WDDX are represented using a subset of the ISO8601 format. Time zone information is represented as an hour/minute offset from Coordinated Universal Time (UTC); for example, "2002-9-8T12:6:26-4:0".

When the cfwddx tag deserializes WDDX to CFML, it automatically uses available time zone information, and converts date-time values to local time. In this way, you do not need to worry about the details of time zone conversions.

However, when the JavaScript objects supplied with ColdFusion deserialize WDDX to JavaScript expressions, they do not use time zone information, because in JavaScript it is difficult to determine the time zone of the browser.


Using WDDX

The following sections describe how you can use WDDX in ColdFusion applications. The first two sections describe the tools that ColdFusion provides for creating and converting WDDX. The remaining sections show how you use these tools for common application uses.

  • Using the cfwddx tag
  • Validating WDDX data
  • Using JavaScript objects
  • Converting CFML data to a JavaScript object
  • Transferring data from the browser to the server
  • Storing complex data in a string

Using the cfwddx tag

The cfwddx tag can do the following conversions:

From | To
CFML | WDDX
CFML | JavaScript
WDDX | CFML
WDDX | JavaScript

A typical cfwddx tag used to convert a CFML query object to WDDX looks like the following:

<cfwddx action="cfml2wddx" input="#MyQueryObject#" output="WddxTextVariable">

In this example, MyQueryObject is the name of the query object variable, and WddxTextVariable is the name of the variable in which to store the resulting WDDX XML. Note

For more information on the cfwddx tag, see CFML Reference.


Validating WDDX data

The cfwddx tag has a Validate attribute that you can use when converting WDDX to CFML or JavaScript. When you set this attribute to True, the XML parser uses the WDDX DTD to validate the WDDX data before deserializing it. If the WDDX is not valid, ColdFusion generates an error. By default, ColdFusion does not validate WDDX data before trying to convert it to ColdFusion or JavaScript data.

The IsWDDX function returns True if a variable is a valid WDDX data packet. It returns False otherwise. You can use this function to validate WDDX packets before converting them to another format. For example, you can use it instead of the cfwddx validate attribute, so that invalid WDDX is handled within conditional logic instead of error-handling code. You can also use it to pre-validate data that will be deserialized by JavaScript at the browser.


Using JavaScript objects

ColdFusion provides two JavaScript objects, WddxSerializer object and WddxRecordset object, that you can use in JavaScript to convert data to WDDX. These objects are defined in the file webroot/cfide/scripts/wddx.js.

CFML Reference describes these objects and their methods in detail. The example Transferring data from the browser to the server shows how you can use these objects to serialize JavaScript to WDDX.


Converting CFML data to a JavaScript object

The following example demonstrates the transfer of a cfquery recordset from a ColdFusion page executing on the server to a JavaScript object that is processed by the browser.

The application consists of four principal sections:

  • Running a data query
  • Including the WDDX JavaScript utility classes
  • Calling the conversion function
  • Writing the object data in HTML

The following example uses the cfdocexamples data source that is installed with ColdFusion:

<!--- Create a simple query --->
<cfquery name = "q" datasource ="cfdocexamples">
    SELECT Message_Id, Thread_id, Username, Posted
    FROM messages
</cfquery>

<!--- Load the wddx.js file, which includes the dump function --->
<script type="text/javascript" src="/CFIDE/scripts/wddx.js"></script>

<script>
    // Use WDDX to move from CFML data to JavaScript
    <cfwddx action="cfml2js" input="#q#" topLevelVariable="qj">

    // Dump the recordset to show that all the data has reached
    // the client successfully.
    document.write(qj.dump(true));
</script>

Note: To see how cfwddx Action="cfml2js" works, save this code under your webroot directory, for example in wwwroot/myapps/wddxjavascript.cfm, run the page in your browser and select View Source in your browser.


Transferring data from the browser to the server

The following example serializes form field data, posts it to the server, deserializes it, and displays the data. For simplicity, it only collects a small amount of data. In applications that generate complex JavaScript data collections, you can extend this basic approach very effectively. This example uses the WddxSerializer JavaScript object to serialize the data, and the cfwddx tag to deserialize the data.

To use the example:

  1. Save the file under your webroot directory, for example in wwwroot/myapps/ wddxserializedeserialze.cfm.
  2. Display http://localhost/myapps/wddxserializedeserialze.cfm in your browser.
  3. Enter a first name and last name in the form fields.
  4. Click Next.

    The name appears in the Names added so far box.

  5. Repeat steps 3 and 4 to add as many names as you wish.
  6. Click Serialize to serialize the resulting data.

    The resulting WDDX packet appears in the WDDX packet display box. This step is intended only for test purposes. Real applications handle the serialization automatically.

  7. Click Submit to submit the data.

    The WDDX packet is transferred to the server-side processing code, which deserializes it and displays the information.

<!--- load the wddx.js file --->
<script type="text/javascript" src="/CFIDE/scripts/wddx.js"></script>

<!--- Data binding code --->
<script>

    // Generic serialization to a form field
    function serializeData(data, formField) {
        wddxSerializer = new WddxSerializer();
        wddxPacket = wddxSerializer.serialize(data);
        if (wddxPacket != null) {
            formField.value = wddxPacket;
        }
        else {
            alert("Couldn't serialize data");
        }
    }
    // Person info recordset with columns firstName and lastName
    // Make sure the case of field names is preserved
    var personInfo = new WddxRecordset(new Array("firstName", "lastName"), true);

    // Add next record to end of personInfo recordset
    function doNext() {
        // Extract data
        var firstName = document.personForm.firstName.value;
        var lastName = document.personForm.lastName.value;

        // Add names to recordset
        nRows = personInfo.getRowCount();
        personInfo.firstName[nRows] = firstName;
        personInfo.lastName[nRows] = lastName;

        // Clear input fields
        document.personForm.firstName.value = "";
        document.personForm.lastName.value = "";

        // Show added names on list
        // This gets a little tricky because of browser differences
        var newName = firstName + " " + lastName;
        if (navigator.appVersion.indexOf("MSIE") == -1) {
            document.personForm.names[length] =
                new Option(newName, "", false, false);
        }
        else {
            // IE version
            var entry = document.createElement("OPTION");
            entry.text = newName;
            document.personForm.names.add(entry);
        }
    }
</script>

<!--- Data collection form --->
<form action="#cgi.script_name#" method="Post" name="personForm">

    <!--- Input fields --->
    Personal information<br>
    First name: <input type=text name=firstName><br>
    Last name: <input type=text name=lastName><br>
    <br>

    <!--- Navigation & submission bar --->
    <input type="button" value="Next" onclick="doNext()">
    <input type="button" value="Serialize"
    onclick="serializeData(personInfo, document.personForm.wddxPacket)">
    <input type="submit" value="Submit">
    <br><br>
    Names added so far:<br>
    <select name="names" size="5">
    </select>
    <br>

    <!--- This is where the WDDX packet will be stored --->
    <!--- In a real application this would be a hidden input field. --->
    <br>
    WDDX packet display:<br>
    <textarea name="wddxPacket" rows="10" cols="80" wrap="Virtual">
    </textarea>

</form>

<!--- Server-side processing --->
<hr>
<b>Server-side processing</b><br>
<br>
<cfif isdefined("form.wddxPacket")>
    <cfif form.wddxPacket neq "">

        <!--- Deserialize the WDDX data --->
        <cfwddx action="wddx2cfml" input=#form.wddxPacket#
        output="personInfo">

        <!--- Display the query --->
        The submitted personal information is:<br>
        <cfoutput query=personInfo>
            Person #CurrentRow#: #firstName# #lastName#<br>
        </cfoutput>
    <cfelse>
        The client did not send a well-formed WDDX data packet!
    </cfif>
<cfelse>
    No WDDX data to process at this time.
</cfif>


Storing complex data in a string

The following simple example uses WDDX to store complex data, a data structure that contains arrays as a string in a client variable. It uses the cfdump tag to display the contents of the structure before serialization and after deserialization. It uses the HTMLEditFormat function in a cfoutput tag to display the contents of the client variable. The HTMLEditFormat function is required to prevent the browser from trying to interpret (and throwing away) the XML tags in the variable.

<!--- Enable client state management --->
<cfapplication name="relatives" clientmanagement="Yes">

<!--- Build a complex data structure --->
<cfscript>
    relatives = structNew();
    relatives.father = "Bob";
    relatives.mother = "Mary";
    relatives.sisters = arrayNew(1);
    arrayAppend(relatives.sisters, "Joan");
    relatives.brothers = arrayNew(1);
    arrayAppend(relatives.brothers, "Tom");
    arrayAppend(relatives.brothers, "Jesse");
</cfscript>

A dump of the original relatives structure:<br>
<br>
<cfdump var="#relatives#"><br>
<br>

<!--- Convert data structure to string form and save it in the client scope --->
<cfwddx action="cfml2wddx" input="#relatives#" output="Client.wddxRelatives">

The contents of the Client.wddxRelatives variable:<br>
<cfoutput>#HtmlEditFormat(Client.wddxRelatives)#</cfoutput><br>

<!--- Now read the data from client scope into a new structure --->
<cfwddx action="wddx2cfml" input="#Client.wddxRelatives#" output="sameRelatives">
<br>
A dump of the sameRelatives structure generated from client.wddxRelatives<br>
<cfdump var="#sameRelatives#">
Previous


Using Web Services

Web services let you publish and consume remote application functionality over the Internet. When you consume web services, you access remote functionality to perform an application task. When you publish a web service, you let remote users access your application functionality to build it into their own applications.

This chapter describes how to consume and publish web services.

Contents

Web services

Working with WSDL files

Consuming web services

Publishing web services

Handling complex data types

Troubleshooting SOAP requests and responses
Next


Web services

Since its inception, the Internet has allowed people to access content stored on remote computers. This content can be static, such as a document represented by an HTML file, or dynamic, such as content returned from a Macromedia ColdFusion page or CGI script.

Web services let you access application functionality that someone created and made available on a remote computer. With a web service, you can make a request to the remote application to perform an action.

For example, you can request a stock quote, pass a text string to be translated, or request information from a product catalog. The advantage of web services is that you do not have to recreate application logic that someone else has already created and, therefore, you can build your applications faster.

Referencing a remote web service within your ColdFusion application is called consuming web services. Since web services adhere to a standard interface regardless of implementation technology, you can consume a web service implemented as part of a ColdFusion application, or as part of a .NET or Java application.

You can also create your own web services and make them available to others for remote access, called publishing web service. Applications that consume your web service can be implemented in ColdFusion MX or by any application that recognizes the web service standard.

Accessing a web service

In its simplest form, an access to a web service is similar to a function call. Instead of the function call referencing a library on your computer, it references remote functionality over the Internet.

One feature of web services is that they are self-describing. That means a person who makes a web service available also publishes a description of the API to the web service as a Web Services Description Language (WSDL) file.

A WSDL file is an XML-formatted document that includes information about the web service, including the following information:

  • Operations that you can call on the web service
  • Input parameters that you pass to each operation
  • Return values from an operation

Consuming web services typically is a two-step process:

  1. Parse the WSDL file of the web service to determine its interface.

    A web service makes its associated WSDL file available over the Internet. You must know the URL of the WSDL file defining the service. For example, you can access the WSDL file for the TemperatureService web service at the following URL:

    www.xmethods.net/sd/2001/TemperatureService.wsdl

    For an overview of WSDL syntax, see Working with WSDL files

  2. Make a request to the web service.

    The following example invokes an operation on the Temperature web service to retrieve the temperature in zip code 55987:

    <cfinvoke
  webservice="http://www.xmethods.net/sd/2001/TemperatureService.wsdl"
  method="getTemp"
  returnvariable="aTemp">
    <cfinvokeargument name="zipcode" value="55987"/>
</cfinvoke>
<cfoutput>The temperature at zip code 55987 is #aTemp#</cfoutput>

    For more information on consuming web services, see Consuming web services.

Basic web service concepts

You must be familiar with the underlying architecture of a web service provider in order to fully understand how web services work.

Note: This section contains an overview of the architecture of web services. For detailed information, consult one of the many web services books.

The following are three primary components of the web services platform:

  • SOAP (Simple Object Access Protocol)
  • WSDL (Web Services Description Language)
  • UDDI (Universal Description, Discovery, and Integration)

The following simple figure shows how the ColdFusion MX implementation of web services work:

Date information including tenths of seconds

The ColdFusion implementation of web services including SOAP support

The following sections describe the components shown in this figure.

Supporting web services with SOAP

SOAP provides a standard XML structure for sending and receiving web service requests and responses over the Internet. Usually you send SOAP messages using HTTP, but you also can send them using SMTP and other protocols. ColdFusion MX integrates the Apache Axis SOAP engine to support web services.

The ColdFusion Web Services Engine performs the underlying functionality to support web services, including generating WSDL files for web services that you create. In ColdFusion MX, to consume or publish web services does not require you to be familiar with SOAP or to perform any SOAP operations.

You can find additional information about SOAP in the W3C’s SOAP 1.1 note at www.w3.org/TR/SOAP/.

Describing web services with WSDL

A WSDL document is an XML file that describes a web service’s purpose, where it is located, and how to access it. The WSDL document describes the operations that you can invoke and their associated data types.

ColdFusion MX can generate a WSDL document from a web service, and you can publish the WSDL document at a URL to provide information to potential clients. For more information, see Working with WSDL files.

Finding web services with UDDI

As a consumer of web services, you want to know what web services are available. As a publisher of web services, you want others to be able to find information about your web services. Universal Description, Discovery and Integration (UDDI) provides a way for web service clients to dynamically locate web services that provide specific capabilities. You use a UDDI query to find service providers. A UDDI response contains information, such as business contact information, business category, and technical details, about how to invoke a web service.

Although ColdFusion MX does not directly support UDDI, you can manually register or find a web service using a public UDDI registry, such as the IBM UDDI Business Registry at https://www-3.ibm.com/services/uddi/protect/registry.html.

You can find additional information about UDDI at www.uddi.org/about.htm.


Working with WSDL files

WSDL files define the interface to a web service. To consume a web service, you access the service’s WSDL file to determine information about it. If you publish your application logic as a web service, you must create a WSDL file for it.

WSDL is a draft standard supported by the World Wide Web Consortium. You can access the specification at www.w3.org/TR/wsdl.

Creating a WSDL file

To publish a web service, you construct the service’s functionality and then create the WSDL file defining the service. In ColdFusion MX, you use components to create web services. ColdFusion automatically generates the WSDL file for a component that you use to produce a web service. For more information on creating web services, see Publishing web services.

For more information on components, see Building and Using ColdFusion Components.

Accessing web services using Macromedia Dreamweaver MX 2004

The Dreamweaver MX 2004 Components tab lets you view web services, including operation names, parameter names, and parameter data types.

To open the Components tab in the Dreamweaver MX 2004 and add a web service:

  1. Select Window > Components, or use Control+F7, to open the Components panel.
  2. In the Components panel, select Web Services from the drop-down list in the upper-left of the panel.
  3. Click the Plus (+) button.

    The Add Using WSDL dialog box appears.

  4. Specify the URL of the WSDL file.

After the web service is defined to Dreamweaver MX 2004, you can drag it onto a page to call it using the cfinvoke tag.

For more information on using Dreamweaver MX 2004, see its online Help system.

Note: The Web Services option is not available if you are running Dreamweaver MX 2004 on the Macintosh. However, you can still use web services by writing code manually.

Reading a WSDL file

A WSDL file takes practice to read. You can view the WSDL file in a browser, or you can use a tool such as Dreamweaver MX 2004, which contains a built-in utility for displaying WSDL files in an easy-to-read format.

The following example shows a WSDL file for the TemperatureService web service:

<?xml version="1.0"?>
<definitions name="TemperatureService" targetNamespace="http://www.xmethods.net/sd/TemperatureService.wsdl"  xmlns:tns="http://www.xmethods.net/sd/TemperatureService.wsdl"   xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/">
    <message name="getTempRequest">
        <part name="zipcode" type="xsd:string"/>
    </message>
    <message name="getTempResponse">
        <part name="return" type="xsd:float"/>
    </message>
    <portType name="TemperaturePortType">
        <operation name="getTemp">
            <input message="tns:getTempRequest"/>
            <output message="tns:getTempResponse"/>
        </operation>
    </portType>
    <binding name="TemperatureBinding" type="tns:TemperaturePortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="getTemp">
            <soap:operation soapAction=""/>
            <input>
                <soap:body use="encoded" namespace="urn:xmethods-Temperature" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </input>
            <output>
                <soap:body use="encoded" namespace="urn:xmethods-Temperature" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </output>
        </operation>
    </binding>
    <service name="TemperatureService">
        <documentation>Returns current temperature in a given U.S. zipcode  </documentation>
        <port name="TemperaturePort" binding="tns:TemperatureBinding">
            <soap:address location="http://services.xmethods.net:80/soap/servlet/rpcrouter"/>
        </port>
    </service>
</definitions>

The following are the major components of the WSDL file:

Component | Definition
definitions | The root element of the WSDL file. This area contains namespace definitions that you use to avoid naming conflicts between multiple web services.
types | (Not shown) Defines data types used by the service’s messages.
message | Defines the data transferred by a web service operation, typically the name and data type of input parameters and return values.
port type | Defines one or more operations provided by the web service.
operation | Defines an operation that can be remotely invoked.
input | Specifies an input parameter to the operation using a previously defined message.
output | Specifies the return values from the operation using a previously defined message.
fault | (not shown) Optionally specifies an error message returned from the operation.
binding | Specifies the protocol used to access a web service including SOAP, HTTP GET and POST, and MIME.
service | Defines a group of related operations.
port | Defines an operation and its associated inputs and outputs.

For additional descriptions of the contents of this WSDL file, see Consuming web services.


Consuming web services

ColdFusion MX provides a variety of methods for consuming web services. The method that you choose depends on your ColdFusion programming style and application.

The following table describes these methods:

Method | CFML operator | Description
CFScript | CreateObject() | Consumes a web service from within a CFScript block.
CFML tag | cfinvoke | Consumes a web service from within a block of CFML code.
CFML tag | cfobject | Consumes a web service from within a block of CFML code.

One important consideration is that all consumption methods use the same underlying technology and offer the same performance.

This section describes the following topics:

  • About the examples in this section
  • Passing parameters to a web service
  • Handling return values from a web service
  • Using cfinvoke to consume a web service
  • Using CFScript to consume a web service
  • Consuming web services that are not generated by Macromedia ColdFusion MX
  • Calling web services from a Macromedia Flash client
  • Catching errors when consuming web services
  • Handling inout and out parameters
  • Configuring web services in the ColdFusion MX Administrator
  • Data conversions between ColdFusion and WSDL data types
  • Consuming ColdFusion web services


About the examples in this section

The examples in this section reference the TemperatureService web service from XMethods. This web service returns the temperature for a given zip code. You can read the WSDL file for this web service in Reading a WSDL file.

The TemperatureService web service has one input parameter, a string that contains the requested zip code. It returns a float that contains the temperature for the specified zip code.


Passing parameters to a web service

The message and operation elements in the WSDL file contains subelements that define the web service operations and the input and output parameters of each operation, including the data type of each parameter. The following example shows a portion of the WSDL file for the TemperatureService web service:

<message name="getTempRequest">
    <part name="zipcode" type="xsd:string"/>
</message>
<message name="getTempResponse">
    <part name="return" type="xsd:float"/>
</message>
<portType name="TemperaturePortType">
    <operation name="getTemp">
        <input message="tns:getTempRequest"/>
        <output message="tns:getTempResponse"/>
    </operation>
</portType>

The operation name used in the examples in this section is getTemp. This operation takes a single input parameter defined as a message of type getTempRequest.

You can see that the message element named getTempRequest contains one string parameter: zipcode. When you call the getTemp operation, you pass the parameter as input.


Handling return values from a web service

Web service operations often return information back to your application. You can determine the name and data type of returned information by examining subelements of the message and operation elements in the WSDL file.

The following example shows a portion of the WSDL file for the TemperatureService web service:

<message name="getTempRequest">
    <part name="zipcode" type="xsd:string"/>
</message>
<message name="getTempResponse">
    <part name="return" type="xsd:float"/>
</message>
<portType name="TemperaturePortType">
    <operation name="getTemp">
        <input message="tns:getTempRequest"/>
        <output message="tns:getTempResponse"/>
    </operation>
</portType>

The operation getTemp returns a message of type getTempResponse. The message statement in the WSDL file defines the getTempResponse message as containing a single string parameter named return.


Using cfinvoke to consume a web service

This section describes how to consume a web service using the cfinvoke tag. With the cfinvoke tag, you reference the WSDL file and invoke an operation on the web service with a single tag.

The cfinvoke tag includes attributes that specify the URL to the WSDL file, the method to invoke, the return variable, and input parameters. For complete cfinvoke syntax, see CFML Reference.

Note: You can pass parameters to a web service using the cfinvokeargument tag or by specifying parameter names in the cfinvoke tag itself. For more information, see Passing parameters to methods using the cfinvoke tag.

To access a web service using cfinvoke:

  1. Create a ColdFusion page with the following content:
    <cfinvoke
  webservice="http://www.xmethods.net/sd/2001/TemperatureService.wsdl"
  method="getTemp"
  returnvariable="aTemp">
    <cfinvokeargument name="zipcode" value="55987"/>
</cfinvoke>
<cfoutput>The temperature at zip code 55987 is #aTemp#</cfoutput>
  2. Save the page as wscfc.cfm in your web root directory.
  3. View the page in your browser.

You can omit a parameter by setting the cfinvokeargument omit attribute to "yes". If the WSDL specifies that the argument is nillable, ColdFusion MX sets the associated argument to null. If the WSDL specifies minoccurs=0, ColdFusion MX omits the argument from the WSDL. However, CFC web services must still specify required="true" for all arguments.

You can also use an attribute collection to pass parameters. An attribute collections is a structure where each structure key corresponds to a parameter name and each structure value is the parameter value passed for the corresponding key. The following example shows an invocation of a web service using an attribute collection:

<cfscript>
    stArgs = structNew();
    stArgs.zipcode = "55987";
</cfscript>

<cfinvoke
  webservice="http://www.xmethods.net/sd/2001/TemperatureService.wsdl"
  method="getTemp"
  argumentcollection="#stArgs#"
  returnvariable="aTemp">
<cfoutput>The temperature at zip code 55987 is #aTemp#</cfoutput>

In this example, you create the structure in a CFScript block, but you can use any ColdFusion method to create the structure.


Using CFScript to consume a web service

The example in this section uses CFScript to consume a web service. In CFScript, you use the CreateObject function to connect to the web service. After connecting, you can make requests to the service. For CreateObject syntax, see CFML Reference.

After creating the web service object, you can call operations of the web service using dot notation, in the following form:

webServiceName.operationName(inputVal1, inputVal2, ... )

You can handle return values from web services by writing them to a variable, as the following example shows:

resultVar = webServiceName.operationName(inputVal1, inputVal2, ... );

Or, you can pass the return values directly to a function, such as the WriteOutput function, as the following example shows:

writeoutput(webServiceName.operationName(inputVal1, inputVal2, ...) );

To access a web service from CFScript:

  1. Create a ColdFusion page with the following content:
    <cfscript>
  ws = CreateObject("webservice",
    "http://www.xmethods.net/sd/2001/TemperatureService.wsdl");
  xlatstring = ws.getTemp("55987");
  writeoutput(xlatstring);
</cfscript>
  2. Save the page as wscfscript.cfm in your web root directory.
  3. View the page in your browser.

You can also use named parameters to pass information to a web service. The following example performs the same operation as above, except that it uses named parameters to make the web service request:

<cfscript>
  ws = CreateObject("webservice",
    "http://www.xmethods.net/sd/2001/TemperatureService.wsdl");
  xlatstring = ws.getTemp(zipcode = "55987");
  writeoutput("The temperature at 55987 is " & xlatstring);
</cfscript>


Consuming web services that are not generated by Macromedia ColdFusion MX

To consume a web service that is implemented in a technology other than ColdFusion MX, the web service must have one of the following sets of options:

  • rpc as the SOAP binding style and encoding as the encodingStyle
  • document as the SOAP binding style and literal as the encodingStyle

The following example shows a portion of the WSDL file for the TemperatureService web service:

<binding name="TemperatureBinding" type="tns:TemperaturePortType">
    <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="getTemp">
        <soap:operation soapAction=""/>
        <input>
            <soap:body use="encoded" namespace="urn:xmethods-Temperature" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
        </input>
        <output>
            <soap:body use="encoded" namespace="urn:xmethods-Temperature" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
        </output>
    </operation>
</binding>

The WSDL file for the TemperatureService web service is compatible with ColdFusion MX because it uses rpc as the binding style, and encoding as the encodingStyle.


Calling web services from a Macromedia Flash client

The Flash Remoting service lets you call ColdFusion pages from a Flash client, but it does not let you call web services directly. To call web services from a Flash client, you can use Flash Remoting to call a ColdFusion component that calls the web service. The Flash client can pass input parameters to the component, and the component can return to the Flash client any data returned by the web service.

For more information, see Using the Flash Remoting Service.


Catching errors when consuming web services

Web services might throw errors, including SOAP faults, during processing that you can catch in your application. If uncaught, these errors propagate to the browser.

To catch errors, you specify an error type of application to the ColdFusion cfcatch tag, as the following example shows:

<cftry>
    Put your application code here ...
    <cfcatch type="application">
        <!--- Add exception processing code here ... --->
    </cfcatch>
    ...
    <cfcatch type="Any">
        <!--- Add exception processing code appropriate for all other
exceptions here ... --->
    </cfcatch>
</cftry>

For more information on error handling, see Handling Errors.


Handling inout and out parameters

Some web services define inout and out parameters. You use out parameters to pass a placeholder for a return value to a web service. The web service then returns its result by writing it to the out parameter. Inout parameters let you pass a value to a web service and lets the web service return its result by overwriting the parameter value.

The following example shows a web service that takes as input an inout parameter containing a string and writes its results back to the string:

<cfset S="foo">
<cfscript>
    ws=createobject("webservice", "URLtoWSDL")
    ws.modifyString("S");
<cfscript>
<cfoutput>#S#</cfoutput>

Even though this web service takes as input the value of S, because you pass it as an inout parameter, you do not enclose it in number signs.

Note: ColdFusion MX supports the use of inout and out parameters to consume web services. However, ColdFusion MX does not support inout and out parameters when creating web services for publication.


Configuring web services in the ColdFusion MX Administrator

The ColdFusion MX Administrator lets you register web services so that you do not have to specify the entire WSDL URL when you reference the web service.

Note: The first time you reference a web service, ColdFusion MX automatically registers it in the Administrator.

For example, the following code references the URL to the TemperatureService WSDL file:

<cfscript>
  ws = CreateObject("webservice",
    "http://www.xmethods.net/sd/2001/TemperatureService.wsdl");
  xlatstring = ws.getTemp("55987");
  writeoutput(xlatstring);
</cfscript>

If you register the TemperatureService web service in the Administrator using (for example, the name wsTemp), you can then reference the web service as follows:

<cfscript>
  ws = CreateObject("webservice", "wsTemp");
  xlatstring = ws.getTemp("55987");
  writeoutput("wsTemp: " & xlatstring);
</cfscript>

Not only does this enable you to shorten your code, registering a web service in the Administrator lets you change a web service’s URL without modifying your code. So, if the TemperatureService web service moves to a new location, you only update the administrator setting, not your application code.

For more information, see the ColdFusion MX Administrator online Help.


Data conversions between ColdFusion and WSDL data types

A WSDL file defines the input and return parameters of an operation, including data types. For example, the TemperatureService web service contains the following definition of input and return parameters:

<message name="getTempRequest">
    <part name="zipcode" type="xsd:string"/>
</message>
<message name="getTempResponse">
    <part name="return" type="xsd:float"/>
</message>

As part of consuming web services, you must understand how ColdFusion MX converts WSDL defined data types to ColdFusion data types. The following table shows this conversion:

ColdFusion data type | WSDL data type
numeric | SOAP-ENC:double
boolean | SOAP-ENC:boolean
string | SOAP-ENC:string
array | SOAP-ENC:Array
binary | xsd:base64Binary
numeric | xsd:float
string | xsd:enumeration
date | xsd:dateTime
void (operation returns nothing) |
struct | complex type
query | tns1:QueryBean (Returned by CFCs)

For many of the most common data types, such as string and numeric, a WSDL data type maps directly to a ColdFusion data type. For complex WSDL data types, the mapping is not as straight forward. In many cases, you map a complex WSDL data type to a ColdFusion structure. For more information on handling complex data types, see Handling complex data types.


Consuming ColdFusion web services

Your application can consume web services created in ColdFusion. You do not have to perform any special processing on the input parameters or return values because ColdFusion handles data mappings automatically when consuming a ColdFusion web service.

For example, when ColdFusion publishes a web service that returns a query, or takes a query as an input, the WSDL file for that service lists its data type as QueryBean. However, a ColdFusion application consuming this web service can pass a ColdFusion query object to the function as an input, or write a returned QueryBean to a ColdFusion query object.

Note: For a list of how ColdFusion data types map to WSDL data types, see Data conversions between ColdFusion and WSDL data types.

The following example shows a ColdFusion component that takes a query as input and echoes the query back to the caller:

<cfcomponent>
    <cffunction name='echoQuery' returnType='query' access='remote'>
        <cfargument name='input' type='query'>
        <cfreturn #arguments.input#>
    </cffunction>
</cfcomponent>

In the WSDL file for the echotypes.cfc component, you see the following definitions that specify the type of the function’s input and output as QueryBean:

<wsdl:message name="echoQueryResponse">
  <wsdl:part name="echoQueryReturn" type="tns1:QueryBean"/>
</wsdl:message>
<wsdl:message name="echoQueryRequest">
  <wsdl:part name="input" type="tns1:QueryBean"/>
</wsdl:message>

For information on displaying WSDL, see Producing WSDL files.

Since ColdFusion automatically handles mappings to ColdFusion data types, you can call this web service as the following example shows:

<head>
<title>Passing queries to web services</title>
</head>
<body>
<cfquery name="GetEmployees" datasource="cfdocexamples">
    SELECT FirstName, LastName, Salary
    FROM Employee
</cfquery>

<cfinvoke
    webservice = "http://localhost/echotypes.cfc?wsdl"
    method = "echoQuery"
    input="#GetEmployees#"
    returnVariable = "returnedQuery">

<cfoutput>
    Is returned result a query? #isQuery(returnedQuery)# <br><br>
</cfoutput>

<cfoutput query="returnedQuery">
    #FirstName#, #LastName#, #Salary#<br>
</cfoutput>
</body>


Publishing web services

To publish web services for consumption by remote applications, you create the web service using ColdFusion components. For more information on components, see Building and Using ColdFusion Components.

This section describes the following topics:

  • Creating components for web services
  • Specifying data types of function arguments and return values
  • Producing WSDL files
  • Using ColdFusion components to define data types for web services
  • Publishing document-literal style web services
  • Securing your web services
  • Best practices for publishing web services

Creating components for web services

ColdFusion components (CFCs) encapsulate application functionality and provide a standard interface for client access to that functionality. A component typically contains one or more functions defined by the cffunction tag.

For example, the following component contains a single function:

<cfcomponent>
    <cffunction name="echoString" returnType="string" output="no">
        <cfargument name="input" type="string">
        <cfreturn #arguments.input#>
    </cffunction>
</cfcomponent>

The function, named echoString, echoes back any string passed to it. To publish the function as a web service, you must modify the function definition to add the access attribute and specify remote, as the following example shows:

<cffunction name="echoString" returnType="string" output="no" access="remote">

By defining the function as remote, ColdFusion includes the function in the WSDL file. Only those functions marked as remote are accessible as a web service.

The following list defines the requirements for how to create web services for publication:

  1. The value of the access attribute of the cffunction tag must be remote.
  2. The cffunction tag must include the returnType attribute to specify a return type.
  3. The output attribute of the cffunction tag must be set to No because ColdFusion converts all output to XML to return it to the consumer.
  4. The attribute setting required="false" for the cfargument tag is ignored. ColdFusion considers all parameters as required.


Specifying data types of function arguments and return values

The cffunction tag lets you define a single return value and one or more input parameters passed to a function. As part of the function definition, you include the data type of the return value and input parameters.

The following example shows a component that defines a function with a return value of type string, one input parameter of type string, and one input parameter of type numeric:

<cfcomponent>
    <cffunction name="trimString" returnType="string" output="no">
        <cfargument name="inString" type="string">
        <cfargument name="trimLength" type="numeric">
    </cffunction>
</cfcomponent>

As part of publishing the component for access as a web service, ColdFusion generates the WSDL file that defines the component where the WSDL file includes definitions for how ColdFusion data types map to WSDL data types. The following table shows this mapping:

ColdFusion data type | WSDL data type published
numeric | SOAP-ENC:double
boolean | SOAP-ENC:boolean
string | SOAP-ENC:string
array | SOAP-ENC:Array
binary | xsd:base64Binary
date | xsd:dateTime
guid | SOAP-ENC:string
uuid | SOAP-ENC:string
void (operation returns nothing) |
struct | Map
query | QueryBean
any | complex type
component definition | complex type

In most cases, consumers of ColdFusion web services can easily pass data to and return results from component functions by mapping their data types to the WSDL data types shown in the preceding table.

Note: Document-literal web services use XML schema data types, not SOAP-ENC data types. For more information, see Publishing document-literal style web services.

For ColdFusion structures and queries, clients might have to perform some processing to map their data to the correct type. For more information, see Publishing web services that use complex data types.

You can also define a data type in one ColdFusion component based on another component definition. For more information on using components to specify a data type, see Using ColdFusion components to define data types for web services.


Producing WSDL files

ColdFusion automatically creates a WSDL file for any component referenced as a web service. For example, if you have a component named echo.cfc in your web root directory, you can view its corresponding WSDL file by requesting the component as follows:

http://localhost/echo.cfc?wsdl

For example, you define a ColdFusion component as follows:

<cfcomponent>
    <cffunction
name = "echoString"
returnType = "string"
output = "no"
access = "remote">
        <cfargument name = "input" type = "string">
        <cfreturn #arguments.input#>
    </cffunction>
</cfcomponent>

Tip: If you register the component in Dreamweaver MX 2004, it appears in the Components tab of the Application panel.

Requesting the WSDL file in a browser returns the following:

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://ws"
  xmlns="http://schemas.xmlsoap.org/wsdl/"
  xmlns:apachesoap="http://xml.apache.org/xml-soap"
  xmlns:impl="http://ws"
  xmlns:intf="http://ws"
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:tns1="http://rpc.xml.coldfusion"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
  xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <!--WSDL created by Macromedia ColdFusion MX version 7,0,0,87956-->
  <wsdl:types>
    <schema targetNamespace="http://rpc.xml.coldfusion"
      xmlns="http://www.w3.org/2001/XMLSchema">
    <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
    <complexType name="CFCInvocationException">
      <sequence/>
    </complexType>
    </schema>
  </wsdl:types>
  <wsdl:message name="CFCInvocationException">
    <wsdl:part name="fault" type="tns1:CFCInvocationException"/>
  </wsdl:message>
  <wsdl:message name="echoStringResponse">
    <wsdl:part name="echoStringReturn" type="xsd:string"/>
  </wsdl:message>
  <wsdl:message name="echoStringRequest">
    <wsdl:part name="input" type="xsd:string"/>
   </wsdl:message>
   <wsdl:portType name="echo">
     <wsdl:operation name="echoString" parameterOrder="input">
       <wsdl:input message="impl:echoStringRequest" name="echoStringRequest"/>
       <wsdl:output message="impl:echoStringResponse"
                name="echoStringResponse"/>
       <wsdl:fault message="impl:CFCInvocationException" name="CFCInvocationException"/>
     </wsdl:operation>
   </wsdl:portType>
   <wsdl:binding name="echo.cfcSoapBinding" type="impl:echo">
     <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/
            http"/>
     <wsdl:operation name="echoString">
       <wsdlsoap:operation soapAction=""/>
       <wsdl:input name="echoStringRequest">
         <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/
                    encoding/" namespace="http://ws" use="encoded"/>
       </wsdl:input>
       <wsdl:output name="echoStringResponse">
         <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/
                    encoding/" namespace="http://ws" use="encoded"/>
       </wsdl:output>
       <wsdl:fault name="CFCInvocationException">
         <wsdlsoap:fault encodingStyle="http://schemas.xmlsoap.org/soap/
                    encoding/" name="CFCInvocationException" namespace=
                    "http://ws" use="encoded"/>
       </wsdl:fault>
     </wsdl:operation>
   </wsdl:binding>
   <wsdl:service name="echoService">
     <wsdl:port binding="impl:echo.cfcSoapBinding" name="echo.cfc">
       <wsdlsoap:address location="http://localhost:8500/ws/echo.cfc"/>
     </wsdl:port>
   </wsdl:service>
</wsdl:definitions>

To publish a web service:

  1. Create a ColdFusion page with the following content:
    <cfcomponent output="false">
    <cffunction
                name = "echoString"
                returnType = "string"
                output = "no"
                access = "remote">
        <cfargument name = "input" type = "string">
        <cfreturn #arguments.input#>
    </cffunction>
</cfcomponent>
  2. Save this file as echo.cfc in your web root directory.
  3. Create a ColdFusion page with the following content:
    <cfinvoke webservice ="http://localhost/echo.cfc?wsdl"
    method ="echoString"
    input = "hello"
    returnVariable="foo">

<cfoutput>#foo#</cfoutput>
  4. Save this file as echoclient.cfm in your web root directory.
  5. Request echoclient.cfm in your browser.

    The following string appears in your browser:

    hello

You can also invoke the web service using the following code:

<cfscript>
    ws = CreateObject("webservice", "http://localhost/echo.cfc?wsdl");
    wsresults = ws.echoString("hello");
    writeoutput(wsresults);
</cfscript>


Using ColdFusion components to define data types for web services

ColdFusion lets you define components that contain only properties. Once defined, you can use components to define data types for web services. The following code defines a component in the file address.cfc that contains properties that represent a street address:

<cfcomponent>
    <cfproperty name="AddrNumber" type="numeric">
    <cfproperty name="Street" type="string">
    <cfproperty name="City" type="string">
    <cfproperty name="State" type="string">
    <cfproperty name="Country" type="string">
</cfcomponent>

The following code defines a component in the file name.cfc that defines first and last name properties:

<cfcomponent>
    <cfproperty name="Firstname" type="string">
    <cfproperty name="Lastname" type="string">
</cfcomponent>

You can then use address and name to define data types in a ColdFusion component created to publish a web service, as the following example shows:

<cfcomponent>
    <cffunction
     name="echoName" returnType="name" access="remote" output="false">
            <cfargument name="input" type="name">
            <cfreturn #arguments.input#>
    </cffunction>

    <cffunction
     name="echoAddress" returnType="address" access="remote" output="false">
            <cfargument name="input" type="address">
            <cfreturn #arguments.input#>
    </cffunction>
</cfcomponent>

Note: If the component files are not in a directory under your web root, you must create a web server mapping to the directory that contains them. You cannot use ColdFusion mappings to access web services.

The WSDL file for the web service contains data definitions for the complex types name and address. Each definition consists of the elements that define the type as specified in the ColdFusion component file for that type. For example, the following example shows the definition for name:

<complexType name="name">
  <sequence>
    <element name="firstname" nillable="true" type="soapenc:string"/>
    <element name="lastname" nillable="true" type="soapenc:string"/>
  </sequence>
</complexType>

You can also specify an array of CFCs in the returnType attribute, as the following example shows:

<cfcomponent>
    <cffunction
     name="allNames" returnType="name[]" access="remote" output="false">
      <cfset var returnarray = ArrayNew(1)>
      <cfset var temp = "">
      <cfquery name="empinfo" datasource="cfdocexamples">
       SELECT firstname, lastname
       FROM employee
      </cfquery>
      <cfloop query="empinfo" >
       <cfobject component="name" name="tempname">
       <cfset tempname.Firstname = #empinfo.firstname#>
       <cfset tempname.Lastname = #empinfo.lastname#>
       <cfset temp = ArrayAppend(returnarray, tempname)>
     </cfloop>
     <cfreturn returnarray>
    </cffunction>
</cfcomponent>

When you invoke the web service, it returns an array of CFCs. Access the properties in the CFC by using dot notation, as the following example shows:

<cfinvoke webservice ="http://localhost:8500/ws/cfcarray.cfc?wsdl"
    method ="allNames"
    returnVariable="thearray">

<cfif IsArray(thearray)>
  <h1>loop through the employees</h1>
  <p>thearray has <cfoutput>#ArrayLen(thearray)#</cfoutput> elements.</p>
  <cfloop index="i" from="1" to="#ArrayLen(thearray)#">
   <cfoutput>#thearray[i].firstname#, #thearray[i].lastname# </cfoutput><br>
  </cfloop>
<cfelse>
  <h1>Error: thearray is not an array</h1>
</cfif>


Publishing document-literal style web services

In addition to RPC-oriented operations, for which consumers specify a method and arguments, ColdFusion also lets you publish web services using the document-literal style. When you use document-literal style, the WSDL for the web service tells the client to use XML schemas rather than RPC calling conventions.

In most cases, the publisher of a web services identifies it as document-literal or RPC style. To identify the type, open the WSDL document and find the soap:binding element and examine its style attribute, as the following example shows:

<wsdl:binding name="WeatherForecastSoap" type="tns:WeatherForecastSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />

In this example, the style is document-literal. You must further examine the WSDL to determine the methods you can call and the parameters for each method.

On the client side, the cfinvoke tag and other ColdFusion methods for calling web services handle this automatically. In most cases, no modifications are necessary. Similarly, when publishing CFCs as document-literal style web services, ColdFusion automatically creates and manages the appropriate WSDL.

To publish CFCs as document-literal style web services, specify cfcomponent style="document", along with the other attributes required for document-literal style web services. For example, ColdFusion MX publishes the following CFC using document-literal style:

<cfcomponent style="document" >
    <cffunction
      name = "getEmp"
      returntype="string"
      output = "no"
      access = "remote">
    <cfargument name="empid" required="yes" type="numeric">
    <cfset var fullname = "">
    <cfquery name="empinfo" datasource="cfdocexamples">
       SELECT emp_id, firstname, lastname
       FROM employee
       WHERE emp_id = <cfqueryparam cfsqltype="cf_sql_integer"
            value="#arguments.empid#">
    </cfquery>
    <cfif empinfo.recordcount gt 0>
       <cfset fullname = empinfo.lastname & ", " & empinfo.firstname>
    <cfelse>
       <cfset fullname = "not found">
    </cfif>
    <cfreturn #fullname#>
  </cffunction>
</cfcomponent>

The cfcomponent tag includes optional attributes that you can use to control the WSDL that ColdFusion generates. You can use these attributes to create meaningful WSDL attribute names, as the following example shows:

<cfcomponent style="document"
    namespace = "http://www.mycompany.com/"
    serviceportname = "RestrictedEmpInfo"
    porttypename = "RestrictedEmpInfo"
    bindingname = "myns:RestrictedEmpInfo"
    displayname = "RestrictedEmpInfo"
    hint = "RestrictedEmpInfo">

Tip: For complete control of the WSDL, advanced users can specify the cfcomponent wsdlFile attribute to use a predefined WSDL file.


Securing your web services

You can restrict access to your published web services to control the users allowed to invoke them. You can use your web server to control access to the directories containing your web services, or you can use ColdFusion security in the same way that you would to control access to any ColdFusion page.

Controlling access to component CFC files

To browse the HTML description of a CFC file, you request the file by specifying a URL to the file in your browser. By default, ColdFusion secures access to all URLs that directly reference a CFC file, and prompts you to enter a password upon the request. Use the ColdFusion RDS password to view the file.

To disable security on CFC file browsing, use the ColdFusion MX Administrator to disable the RDS password.

For more information, see Building and Using ColdFusion Components.

Using your web server to control access

Most web servers, including IIS and Apache, implement directory access protection using the basic HTTP authentication mechanism. When a client attempts to access one of the resources under a protected directory, and has not properly authenticated, the web server automatically sends back an authentication challenge, typically an HTTP Error 401 Access Denied error.

In response, the client’s browser opens a login prompt containing a username and password field. When the user submits this information, the browser sends it back to the web server. If authentication passes, the web server allows access to the directory. The browser also caches the authentication data as long as it is open, so subsequent requests automatically include the authentication data.

Web service clients can also pass the username and password information as part of the request. The cfinvoke tag includes the username and password attributes that let you pass login information to a web server using HTTP basic authentication. You can include these attributes when invoking a web service, as the following example shows:

<cfinvoke
    webservice = "http://some.cfc?wsdl"
    returnVariable = "foo"
    ...
    username="aName"
    password="aPassword">
<cfoutput>#foo#</cfoutput>

ColdFusion inserts the username/password string in the authorization request header as a base64 binary encoded string, with a colon separating the username and password. This method of passing the username/password is compatible with the HTTP basic authentication mechanism used by web servers.

The ColdFusion MX Administrator lets you predefine web services. As part of defining the web service, you can specify the username and password that ColdFusion includes as part of the request to the web service. Therefore, you do not have to encode this information using the cfinvoke tag. For information on defining a web service in the ColdFusion MX Administrator, see Configuring web services in the ColdFusion MX Administrator.

Using ColdFusion to control access

Instead of letting the web server control access to your web services, you can handle the username/password string in your Application.cfc or Application.cfm file as part of your own security mechanism. In this case, you use the cflogin tag to retrieve the username/password information from the authorization header, decode the binary string, and extract the username and password, as the following excerpt from an Application.cfc onRequestStart method shows:

<cflogin>
    <cfset isAuthorized = false>

    <cfif isDefined("cflogin")
        <!--- verify user name from cflogin.name and password from
cflogin.password using your authentication mechanism --->
        >
        <cfset isAuthorized = true>
    </cfif>
</cflogin>

<cfif not isAuthorized>
    <!--- If the user does not pass a username/password, return a 401 error.
        The browser then prompts the user for a username/password. --->
    <cfheader statuscode="401">
    <cfheader name="WWW-Authenticate" value="Basic realm=""Test""">
    <cfabort>
</cfif>

This example does not show how to perform user verification. For more information on verification, see Securing Applications.


Best practices for publishing web services

ColdFusion web services provide a powerful mechanism for publishing and consuming application functionality. However, before you produce web services for publication, you might want to consider the following best practices:

  1. Minimize the use of ColdFusion complex types, such as query and struct, in the web services you create for publication. These types require consumers, especially those consuming the web service using a technology other than ColdFusion, to create special data structures to handle complex types.
  2. Locally test the ColdFusion components implemented for web services before publishing them over the Internet.


Using request and response headers

ColdFusion MX includes a set of functions that enable your web service to get and set request and response headers. You use these functions to retrieve the response headers from a web service request and to create SOAP headers in a request that has the mustUnderstand attribute set to be True.

You typically use different functions in web services clients and in the web service CFC, itself:

In the client:

  • AddSOAPRequestHeader, called before the request to set a SOAP header.
  • GetSOAPResponseHeader, called after the request to retrieve a SOAP header.

In the web service CFC:

  • IsSOAPRequest, called to determine whether the CFC method is being called as a web service.
  • GetSOAPRequestHeader, called to retrieve a SOAP header set by the client.
  • AddSOAPResponseHeader, called to set a SOAP header that is returned to the client.

Note: When used in a CFC, you can only use these functions in CFC methods if they are being used as web services. Use the IsSOAPRequest function to determine whether the CFC method is being called as a web service.

The following example CFM page uses the AddSOAPRequestHeader, getSOAPRequest, and GetSOAPResponse functions:

<cfsavecontent variable="my_xml">
  <Request xmlns="http://www.oasis-open.org/asap/0.9/asap.xsd">
    <SenderKey>ss</SenderKey>
    <ReceiverKey>zz</ReceiverKey>
    <ResponseRequired>Yes</ResponseRequired>
    <RequestID>id</RequestID>
  </Request>
</cfsavecontent>
<cfset xml_obj = xmlparse(my_xml)>

<cfscript>
  ws = CreateObject("webservice", "http://localhost:8500/soapexamples/HeaderFuncs.cfc?WSDL");
  addSOAPRequestHeader(ws, "http://www.cfdevguide.com/", "testrequestheader", "#xml_obj#");
</cfscript>

<cfscript>
  ret=ws.showSOAPHeaders();
  inxml = getSOAPRequest(ws);
  outxml = getSOAPResponse(ws);
</cfscript>

<cfoutput>
<h2>Return Value</h2>
<!--- This is XML, so use HTMLCodeFormat. --->
The return value was #ret#
<h2>Complete Request XML</h2>
#htmlcodeformat(inxml)#
<h2>Complete Response XML</h2>
#htmlcodeformat(outxml)#
</cfoutput>

The following example CFC uses the IsSOAPRequest and AddSOAPResponseHeader functions:

<cfcomponent>
  <cffunction
     name = "showSOAPHeaders"
     returnType = "string"
     output = "no"
     access = "remote"
     hint="After calling this function, use GetSOAPRequest and GetSOAPResponse to view headers">
    <cfset var xml_obj = "">
    <cfset var ret = "">

    <cfif IsSOAPRequest()>
      <!--- Define a response header --->
      <cfsavecontent variable="response_xml">
         <ThisResponseHeader xmlns="http://www.cfdevguide.com">
           <CreatedDateTime><cfoutput>#now()#</cfoutput></CreatedDateTime>
           <ExpiresInterval>6000</ExpiresInterval>
         </ThisResponseHeader>
      </cfsavecontent>
      <cfset xml_obj = xmlparse(response_xml)>
      <!--- Add the response header --->
      <cfscript>
        addSOAPResponseHeader("http://www.cfdevguide.com/", "testresponseheader", "#xml_obj#");
        ret = "Invoked as a web service. Use GetSOAPRequest and GetSOAPResponse to view headers.";
      </cfscript>
    <cfelse>
      <cfset ret = "Not invoked as a web service">
    </cfif>
    <cfreturn ret>
  </cffunction>
</cfcomponent>


Handling complex data types

When dealing with web services, handling complex types falls into the following categories:

  • Mapping the data types of a web service to consume to ColdFusion data types
  • Understanding how clients will reference your ColdFusion data types when you publish a web service

This section describes both categories.

  • Consuming web services that use complex data types
  • Publishing web services that use complex data types

Consuming web services that use complex data types

The following table shows how WSDL data types are converted to ColdFusion data types:

ColdFusion data type | WSDL data type
numeric | SOAP-ENC:double
boolean | SOAP-ENC:boolean
string | SOAP-ENC:string
array | SOAP-ENC:Array
numeric | SOAP-ENC:float
binary | xsd:base64Binary
date | xsd:dateTime
void (operation returns nothing) |
structure | complex type

This table shows that complex data types map to ColdFusion structures. ColdFusion structures offer a flexible way to represent data. You can create structures that contain single-dimension arrays, multi-dimensional arrays, and other structures.

The ColdFusion mapping of complex types to structures is not automatic. You have to perform some processing on the data in order to access it as a structure. The next sections describe how to pass complex types to web services, and how to handle complex types returned from web services.

Passing input parameters to web services as complex types

A web service can take a complex data type as input. In this situation, you can construct a ColdFusion structure that models the complex data type, then pass the structure to the web service.

For example, the following excerpt from a WSDL file shows the definition of a complex type named Employee:

<s:complexType name="Employee">
 <s:sequence>
   <s:element minOccurs="1" maxOccurs="1" name="fname" type="s:string" />
   <s:element minOccurs="1" maxOccurs="1" name="lname" type="s:string" />
   <s:element minOccurs="1" maxOccurs="1" name="active" type="s:boolean" />
   <s:element minOccurs="1" maxOccurs="1" name="age" type="s:int" />
   <s:element minOccurs="1" maxOccurs="1" name="hiredate" type="s:dateTime" />
   <s:element minOccurs="1" maxOccurs="1" name="number" type="s:double" />
 </s:sequence>
</s:complexType>

The Employee data type definition includes six elements, the data type of each element, and the name of each element.

Another excerpt from the WSDL file shows a message definition using the Employee data type. This message defines an input parameter, as the following code shows:

<message name="updateEmployeeInfoSoapIn">
    <part name="thestruct" type="s0:Employee" />
</message>

A third excerpt from the WSDL file shows the definition of an operation, named updateEmployeeInfo, possibly one that updates the employee database with the employee information. This operation takes as input a parameter of type Employee, as the following code shows:

<operation name="updateEmployeeInfo">
    <input message="s0:updateEmployeeInfoSoapIn" />
</operation>

To call the updateEmployeeInfo operation, create a ColdFusion structure, initialize six fields of the structure that correspond to the six elements of Employee, and then call the operation, as the following code shows:

<!--- Create a structure using CFScript, then call the web service. --->
<cfscript>
    stUser = structNew();
    stUser.active = TRUE;
    stUser.fname = "John";
    stUser.lname = "Smith";
    stUser.age = 23;
    stUser.hiredate = createDate(2002,02,22);
    stUser.number = 123.321;

    ws = createObject("webservice", "http://somehost/EmployeeInfo.asmx?wsdl");
    ws.updateEmployeeInfo(stUser);
</cfscript>

You can use structures for passing input parameters as complex types in many situations. However, to build a structure to model a complex type, you have to inspect the WSDL file for the web service to determine the layout of the complex type. This can take some practice.

Handling return values as complex types

When a web service returns a complex type, you can write that returned value directly to a ColdFusion variable.

The previous section used a complex data type named Employee to define an input parameter to an operation. A WSDL file can also define a return value using the Employee type, as the following code shows:

<message name="updateEmployeeInfoSoapOut">
    <part name="updateEmployeeInfoResult" type="s0:Employee" />
</message>
<operation name="updateEmployeeInfo">
    <input message="s0:updateEmployeeInfoSoapIn" />
    <output message="s0:updateEmployeeInfoSoapOut" />
</operation>

In this example, the operation updateEmployeeInfo takes a complex type as input and returns a complex type as output. To handle the input parameter, you create a structure. To handle the returned value, you write it to a ColdFusion variable, as the following example shows:

<!--- Create a structure using CFScript, then call the web service. --->
<!--- Write the returned value to a ColdFusion variable. --->
<cfscript>
    stUser = structNew();
    stUser.active = TRUE;
    stUser.fname = "John";
    stUser.lname = "Smith";
    stUser.age = 23;
    stUser.hiredate = createDate(2002,02,22);
    stUser.number = 123.321;

    ws = createObject("webservice", "http://somehost/echosimple.asmx?wsdl");
    myReturnVar = ws.echoStruct(stUser);

</cfscript>

<!--- Output the returned values. --->
<cfoutput>
    <br>
    <br>Name of employee is: #myReturnVar.fname#  #myReturnVar.lname#
    <br>Active status: #myReturnVar.active#
    <br>Age:  #myReturnVar.age#
    <br>Hire Date: #myReturnVar.hiredate#
    <br>Favorite Number: #myReturnVar.number#
</cfoutput>

You access elements of the variable myReturnVar using dot notation in the same way that you access structure fields. If a complex type has nested elements, in the way a structure can have multiple levels of nested fields, you use dot notation to access the nested elements, as in a.b.c.d, to whatever nesting level is necessary.

However, the variable myReturnVar is not a ColdFusion structure. It is a container for the complex type, but has none of the attributes of a ColdFusion structure. Calling the ColdFusion function isStruct on the variable returns False.

You can copy the contents of the variable to a ColdFusion structure, as the following example shows:

<cfscript>
...
    ws = createObject("webservice", "http://somehost/echosimple.asmx?wsdl");
    myReturnVar = ws.echoStruct(stUser);

    realStruct = structNew();
    realStruct.active = #myReturnVar.active#;
    realStruct.fname = "#myReturnVar.fname#";
    realStruct.lname = "#myReturnVar.lname#";
    realStruct.age = #myReturnVar.age#;
    realStruct.hiredate = #myReturnVar.hiredate#;
    realStruct.number = #myReturnVar.number#;

</cfscript>

Calling IsStruct on realStruct returns True and you can use all ColdFusion structure functions to process it.

This example shows that ColdFusion variables and structures are useful for handling complex types returned from web services. To understand how to access the elements of a complex type written to a ColdFusion variable, you have to inspect the WSDL file for the web service. The WSDL file defines the API to the web service and will provide you with the information necessary to handle data returned from it.


Publishing web services that use complex data types

The two ColdFusion data types that do not map exactly to WSDL data types are struct and query. When you publish a ColdFusion web service that uses parameters of type struct or query, the consuming application needs to be able to handle the data.

Note: If the consumer of a ColdFusion web service is another ColdFusion application, you do not have to perform any special processing. ColdFusion correctly maps struct and query data types in the web service publisher with the consumer. For more information, see Consuming ColdFusion web services.

Publishing structures

A ColdFusion structure can hold an unlimited number of key-value pairs where the values can be of any ColdFusion data type. While it is a very useful and powerful way to represent data, it cannot be directly mapped to any XML data types defined in the SOAP 1.1 encoding and XML Schema specification. Therefore, ColdFusion structures are treated as a custom type and the complex type XML schema in WSDL looks like the following:

<complexType name="mapItem">
  <sequence>
    <element name="key" nillable="true" type="xsd:anyType"/>
    <element name="value" nillable="true" type="xsd:anyType"/>
  </sequence>
</complexType>
<complexType name="Map">
  <sequence>
    <element maxOccurs="unbounded" minOccurs="0" name="item" type="apachesoap:mapItem"/>
  </sequence>
</complexType>

This complex type defines a representation of a structure, where the structure keys and values can be any type.

In the WSDL mapping of a ColdFusion structure, each key-value pair in the structure points to the next element in the structure except for the final field, which contains a value. Use dot notation to access the key-value pairs.

Publishing queries

ColdFusion publishes query data types as the WSDL type QueryBean. The QueryBean data type contains two elements, as the following excerpt from a WSDL file shows:

<complexType name="QueryBean">
    <all>
        <element name="data" nillable="true" type="intf:ArrayOf_SOAP-ENC_Array" />
        <element name="ColumnList" nillable="true"
type="intf:ArrayOf_SOAP-ENC_string" />
    </all>
</complexType>

The following table describes the elements of QueryBean:

Element name | Description
ColumnList | String array that contains column names
data | Two-dimensional array that contains query data

The WSDL file for a QueryBean defines these elements as follows:

<complexType name="ArrayOf_SOAP-ENC_Array">
    <complexContent>
        <restriction base="SOAP-ENC:Array">
            <attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="SOAP-ENC:Array[]" />
        </restriction>
    </complexContent>
</complexType>
<complexType name="ArrayOf_SOAP-ENC_string">
    <complexContent>
    <restriction base="SOAP-ENC:Array">
        <attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="xsd:string[]" />
    </restriction>
    </complexContent>
</complexType>


Troubleshooting SOAP requests and responses

ColdFusion MX provides the following facilities for troubleshooting SOAP requests and responses:

  • The getSOAPRequest and getSOAPResponse functions.
  • The TCP monitor.

This section describes the following topics:

  • Viewing SOAP requests and responses
  • Using the TCP monitor

Viewing SOAP requests and responses

You can use the getSOAPRequest and getSOAPResponse functions to retrieve and display the XML passed to and from a web service. Although advanced users may use this information for custom functionality, you typically use these functions for debugging.

Use these functions in the following places:

  • GetSOAPRequest Clients call this function after the web service request; web service CFCs call this function in the web service CFC method.
  • GetSOAPResponse Clients call this function after the web service request completes; web service CFCs cannot use this method.

The following example uses the GetSOAPRequest and GetSOAPResponse functions in a web service client:

<cfscript>
 ws = CreateObject("webservice", "http://localhost:8500/soapexamples/tester.cfc?WSDL");
 addSOAPRequestHeader(ws, "http://mynamespace/", "username", "randy");
 ret = ws.echo_me("value");
</cfscript>

<cfset soapreq = GetSOAPRequest(ws)>
<h2>SOAP Request</h2>
<cfdump var="#soapreq#">

<cfset soapresp = GetSOAPResponse(ws)>
<h2>SOAP Response</h2>
<cfdump var="#soapresp#">
...

The following example uses the GetSOAPRequest function in a web service CFC method:

<cfcomponent displayName="testerdebug" hint="Test for underscores">

<cffunction access="remote" name="echo_me" output="false" returntype="string"
  displayname="Echo Test" hint="Header test">
  <cfargument name="in_here" required="true" type="string">
  <cfset var soapreq = "">

  <cfif IsSOAPRequest()>
    <cfset soapreq = GetSOAPRequest()>
    <cflog text="#soapreq#"
           log="APPLICATION"
           type="Information">
...

Using the TCP monitor

TCPMonitor is a swing-based application that lets you watch the request and response flow of HTTP traffic. You can also watch the request and response flow of SOAP traffic. TCPMonitor replaces the Sniffer service formerly used in Macromedia JRun.

To run TCPMonitor:

  • On Windows and Unix platforms, you can execute the TCPMonitor by launching the sniffer utility in the jrun_root/bin directory.

    The TCP Monitor main window appears.

TCPMonitor is a swing-based application that lets you watch the request and response flow of HTTP traffic. However, you can also use it to watch the request and response flow of SOAP traffic.

To run TCPMonitor:

  1. On Windows and Unix platforms, you can execute the TCPMonitor by launching the sniffer utility in the cf_root/bin (server configuration) or jrun_root/bin (multiserver configuration) directory.

    The TCP Monitor main window appears.

    Note: In the J2EE configuration, run the utility directly out of the JAR file by using the following command:

    java -cp cf_webapp_root/WEB-INF/cfusion/lib/axis.jar java org.apache.axis.utils.tcpmon [listening_port] [target_host] [target_port]
  2. Enter the values in the main window as described in the following table:

    Field

    Description

    Listen Port#

    Enter a local port number, such as 8123, to monitor for incoming connections. Instead of requesting the usual port on which your server runs, you request this port. TCPMonitor intercepts the request and forwards it to the Target Port.

    Listener

    Select Listener to use TCPMonitor as a sniffer service in JRun.

    Proxy

    Select Proxy to enable proxy support for TCPMonitor.

    Target Hostname

    Enter the target host to which incoming connections are forwarded.

    For example, if you are monitoring a service running on a local server, the hostname is localhost.

    Target Port#

    Enter the port number on the target machine to which TCPMonitor connects. For example, if you are monitoring a service running on your local ColdFusion server in the server configuration, the default port number is 8500.

    HTTP Proxy Support

    Select this check box only to configure proxy support for TCPMonitor.

    You can optionally specify the Listen Port#, Target Hostname and Target Port# values when invoking TCPMonitor on the command line. The following is the syntax for TCPMonitor:

    java org.apache.axis.utils.tcpmon [listening_port] [target_host] [target_port]
  3. To add this profile to your TCPMonitor session, click Add.

    A tab appears for your new tunneled connection.

  4. Select the new tab. If there are port conflicts, TCPMonitor alerts you in the Request panel.
  5. Request a page using the Listen Port defined in this TCPMonitor session. For example, if you entered 8123 for the Listen Port, enter the following URL in your browser:
    http://localhost:8123/

    TCPMonitor displays the current request and response information:

    For each connection, the request appears in the Request panel and the response appears in the Response panel. TCPMonitor keeps a log of all request-response pairs and lets you view any particular pair by selecting an entry in the top panel.

  6. To save results to a file for later viewing, click Save. To clear the top panel of older requests that you do not want to save, click Remove Selected and Remove All.
  7. To resend the request that you are currently viewing and view a new response, click Resend. You can edit the request in the Request panel before resending, and test the effects of different requests.
  8. To change the ports, click Stop, change the port numbers, and click Start.
  9. To add another listener, click the Admin tab and enter the values as described previously.
  10. To end this TCPMonitor session, click Close.
Previous


Integrating J2EE and Java Elements in CFML Applications

Next

Integrating J2EE and Java Elements in
CFML Applications

This chapter describes how to integrate J2EE elements, including JSP pages and servlets; JSP tags; and Java objects, including Enterprise JavaBeans (EJBs); into your ColdFusion application.

It does not explain J2EE concepts or how to program using Java or JSP. It does explain how to use existing Java and JSP elements in your ColdFusion applications.

Contents

About ColdFusion, Java, and J2EE

Using JSP tags and tag libraries

Interoperating with JSP pages and servlets

Using Java objects
Next


About ColdFusion, Java, and J2EE

Macromedia ColdFusion MX is built on a J2EE-compliant Java technology platform. This lets ColdFusion applications take advantage of, and integrate with, J2EE elements. ColdFusion pages can do any of the following:

  • Include JavaScript and client-side Java applets on the page.
  • Use JSP tags.
  • Interoperate with JSP pages.
  • Use Java servlets.
  • Use Java objects, including JavaBeans and Enterprise JavaBeans.

This section describes the following topics:

  • About ColdFusion and client-side JavaScript and applets
  • About ColdFusion and JSP
  • About ColdFusion and servlets
  • About ColdFusion and Java objects
  • About CFML variables and Java variables

About ColdFusion and client-side JavaScript and applets

ColdFusion pages, like HTML pages, can incorporate client-side JavaScript and Java applets. To use JavaScript, you write the JavaScript code just as you do on any HTML page. ColdFusion ignores the JavaScript and sends it to the client.

The cfapplet tag simplifies using Java client-side applets.

To use an applet on a ColdFusion page:

  1. Register the applet .class file in ColdFusion MX Administrator Java Applets Extensions page. (For information on registering applets, see the ColdFusion MX Administrator online Help.)
  2. Use the cfapplet tag to call the applet. The appletSource attribute must be the Applet name assigned in ColdFusion MX Administrator.

For example, ColdFusion includes a Copytext sample applet that copies text from one text box to another. The ColdFusion Setup automatically registers the applet in the Administrator. To use this applet, incorporate it on your page. For example:

<cfform action = "copytext.cfm">
    <cfapplet appletsource = "copytext" name = "copytext">
</cfform>


About ColdFusion and JSP

ColdFusion MX supports JSP tags and pages in the following ways:

  • Interoperates with JSP pages: ColdFusion pages can include or forward to JSP pages, JSP pages can include or forward to ColdFusion pages, and both types of pages can share data in persistent scopes.
  • Imports and uses JSP tag libraries: the cfimport tag imports JSP tag libraries and lets you use its tags.

ColdFusion pages are not JSP pages, however, and you cannot use most JSP syntax on ColdFusion pages. In particular you cannot use the following features on ColdFusion pages:

Include, Taglib, and Page directives Instead, you use CFML import tag to import tag libraries, and the include (or forward) method of the page context object returned by the ColdFusion GetPageContext function to include pages. For more information, see Using JSP tags and tag libraries and Interoperating with JSP pages and servlets.

Expression, Declaration, and Scriptlet JSP scripting elements Instead, you use CFML elements and expressions.

JSP comments Instead, you use CFML comments. (ColdFusion ignores JSP comments and passes them to the browser.)

Standard JSP tags Such as jsp:plugin, unless your J2EE server provides access to these tags in a JAR file. Instead, you use ColdFusion tags and the PageContext object.


About ColdFusion and servlets

Some Java servlets are not exposed as JSP pages; instead they are Java programs. You can incorporate JSP servlets in your ColdFusion application. For example, your enterprise might have an existing servlet that performs some business logic. To use a servlet, the ColdFusion page specifies the servlet by using the ColdFusion GetPageContext function.

When you access the servlet with the GetPageContext function, the ColdFusion page shares the Request, Application, and Session scopes with the servlet, so you can use these scopes for shared data.

ColdFusion pages can also access servlets by using the cfhttp tag, use the servlet URL in a form tag, or access an SHTML page that uses a servlet tag.

Note: The cfservlet tag, which provides access to servlets on JRun servers, is deprecated for ColdFusion MX.


About ColdFusion and Java objects

Java objects include the following:

  • Standard Java classes and methods that make up the J2EE API
  • Custom-written Java objects, including the following:
    • Custom classes, including JavaBeans
    • Enterprise JavaBeans

ColdFusion pages use the cfobject tag to access Java objects.

ColdFusion MX searches for the objects in the following order:

  1. The ColdFusion Java Dynamic Class Load directories:
    • Java archive (.jar) files in web_root/WEB-INF/lib
    • Class (.class) files in web_root/WEB-INF/classes

    ColdFusion reloads classes from these directories, as described in the next section, About class loading.

  2. The classpath specified on the JVM and Java Settings page in the ColdFusion MX Administrator.
  3. The default JVM classpath.

About class loading

ColdFusion dynamically loads classes that are either .class files in the web_root/WEB-INF/classes directory or in JAR files in the web_root/WEB-INF/lib directory. ColdFusion checks the time stamp on the file when it creates an object that is defined in either directory, even when the class is already in memory. If the file that contains the class is newer than the class in memory, ColdFusion loads the class from that directory.

To use this feature, make sure that the Java implementation classes that you modify are not in the general JVM classpath.

To disable automatic class loading of your classes, put the classes in the JVM classpath. Classes located on the JVM classpath are loaded once per server lifetime. To reload these classes, stop and restart ColdFusion MX.

Note: Because you put tag libraries in the web_root/WEB-INF/lib directory, ColdFusion automatically reloads these libraries if necessary when you import the library.

About GetPageContext and the PageContext object

Because ColdFusion pages are J2EE servlet pages, all ColdFusion pages have an underlying Java PageContext object. CFML includes the GetPageContext function that you can then use in your ColdFusion page.

The PageContext object exposes a number of fields and methods that can be useful in J2EE integration. In particular, it includes the include and forward methods that provide the equivalent of the corresponding standard JSP tags.

This chapter describes how to use the include and forward PageContext methods for calling JSP pages and servlets. It does not discuss the PageContext object in general. For more information on the object, see Java documentation. You can find the Javadoc description of this class at http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/PageContext.html.


About CFML variables and Java variables

Because ColdFusion variables are case-independent and Java variables are case-dependent, you must be careful about variable names. Use the following rules and guidelines when sharing data between ColdFusion and Java code, including JSP pages and servlets.

Rules

  • If you use mixed case variables, all variable names must be unique, independent of case. For example, you must not have two Java variables, MyVariable and MYVARIABLE. ColdFusion cannot distinguish between the two.
  • If you share Request scope variables between a CFML page and a JSP page or servlet, all shared Request scope variable names must be all-lowercase in the JSP page or servlet. Mixed case or all-uppercase variables will cause null pointer exceptions if CFML refers to these variables.
  • If you share Application or Session scope variables between a CFML page and a JSP page or servlet and use a named ColdFusion application (the common usage), the variables on the JSP page or servlet are case-independent.
  • If you share the Application or Session scope variables between a CFML page and a JSP page or servlet, and use an unnamed ColdFusion application, the variable names in the JSP page or servlet must be all lowercase.
  • When you specify a class name in the cfobject tag or CreateObject function, the name must be case-correct.

Guidelines

  • You can prevent problems by consistently using all-lowercase variable names.
  • In your CFML, use the same case as you do in your Java or JSP. Doing so does not change how the application works, but does help prevent confusion.


Using JSP tags and tag libraries

You can use JSP tags from any JSP tag library. For example, you can use any of the custom tags in the open-source Apache Jakarta Project Taglibs project tag libraries, located at http://jakarta.apache.org/taglibs/index.html. This project consists of a number of individual JSP custom tag libraries for purposes ranging from JNDI access to generating random text strings.

Using a JSP tag in a ColdFusion page

JSP pages use a standard set of tags, such as jsp:forward and jsp:include. You can also import custom JSP tag libraries into a JSP application. You can use both the standard JSP tags and custom JSP tags in ColdFusion pages, as the following sections describe.

Standard JSP tags and ColdFusion

ColdFusion tags provide equivalent features to most standard JSP tags. For example, the cfapplet tag provides the same service as the jsp:plugin tag, and cfobject tag lets you use JavaBeans, as does the jsp:usebean tag. Similarly, you do not use the jsp:getproperty tag because ColdFusion automatically gets properties when you reference them. Therefore, ColdFusion does not support the use of standard JSP tags directly.

However, two standard JSP tags provide functionality that is useful in ColdFusion pages: the forward and include tags invoke JSP pages and Java servlets. The PageContext object described in About GetPageContext and the PageContext object has forward and include methods that provide the same operations. For more information about using these methods see Accessing a JSP page or servlet from a ColdFusion page.

Using custom JSP tags in a ColdFusion page

Follow these steps to use a custom JSP tag on a ColdFusion page:

To use a custom tag:

  1. Put the tag library, consisting of the taglibname.jar file, and the taglibname.tld file, if one is supplied, in the web_root/WEB-INF/lib directory. The JSP custom tag library must be in this directory for you to use the cfimport tag.
  2. Restart ColdFusion.
  3. In the ColdFusion page that uses a JSP tag from the tag library, specify the tag library name in a cfimport tag; for example:
    <cfimport taglib="/WEB-INF/lib/random.jar" prefix="random">

    If the TLD file is not included in the JAR file, use the .tld suffix in place of the .jar suffix.

    Note: The cfimport tag must be on the page that uses the imported tag. You cannot put the cfimport tag in Application.cfm.

  4. Use the custom tag using the form prefix:tagName; for example:
    <random:number id="myNum" range="000000-999999" />

Note: You cannot use the cfsavecontent tag to suppress output of a custom JSP tag.

Example: using the random tag library

The following example uses the random tag library from the Apache Jakarta Taglibs project and calls the library’s number tag, which initializes a random number generator that uses a secure algorithm to generate a six-digit random number. You get a new random number each time you reference the variable randPass.random.

<cfimport taglib="/WEB-INF/lib/taglibs-random.jar" prefix="myrand">
<myrand:number id="randPass" range="000000-999999" algorithm="SHA1PRNG" provider="SUN" />
<cfset myPassword = randPass.random>
<cfoutput>
    Your password is #myPassword#<br>
</cfoutput>

For more information on the Jakarta random tag library and how to use its tags, see the documentation at the Apache Jakarta Taglibs project website, http://jakarta.apache.org/taglibs/index.html. The Taglibs project includes many open source custom tag libraries.


Interoperating with JSP pages and servlets

ColdFusion pages and JSP pages can interoperate in several ways:

  • ColdFusion pages can invoke JSP pages and servlets.
  • JSP pages can invoke ColdFusion pages.
  • ColdFusion pages, JSP pages, and servlets can share data in three scopes.

The following sections show how you can use these techniques.

  • Integrating JSP and servlets in a ColdFusion application
  • Examples: using JSP with CFML

Integrating JSP and servlets in a ColdFusion application

You can integrate JSP pages and servlets in your ColdFusion application. For example, you can write some application pages in JSP and write others in CFML. ColdFusion pages can access JSP pages by using the JSP include and forward methods to call the page. As with any web application, you can use href links in ColdFusion pages to open JSP pages.

The ability to use JSP lets you incorporate legacy JSP pages in your ColdFusion application, or conversely, use CFML to expand an existing JSP application using ColdFusion pages.

If you have a JSP page that must call a ColdFusion page, you also use a jsp:forward or jsp:include tag to call the ColdFusion page. For an example of calling a ColdFusion page from a JSP page, see Calling a JSP page from a ColdFusion page.

Accessing a JSP page or servlet from a ColdFusion page

To access a JSP page or servlet from a ColdFusion page, you use the GetPageContext function with the forward or the include method. For example, to include a JSP "Hello World" page in your ColdFusion application, use the following line:

GetPageContext().include("hello.jsp");

To pass parameters to the JSP page, include the parameters in the page URL.

For example, you might want to integrate an existing JSP customer response component into a new ColdFusion order processing application. The order processing application provides the order number, total cost, and expected shipping date, and the customer response component sends the response to the e-mail address on file for the particular customer number. The ColdFusion application might use the following CFScript code to call the response JSP page:

urlParams = "UID=#order.uid#&cost=#order.total#&orderNo=#order.orderNo#
&shipDate=#order.shipDateNo#"
getPageContext().forward(URLEncodedFormat("/responsegen/responsegen.jsp
?#urlParams#"));

To access a servlet that exposes the same functionality, you use the same code, although the URL would change. For example, to run a servlet called HelloWorldServlet, you put the servlet .java or .class file in the serverroot/WEB-INF/classes directory and refer to the servlet with the URL
/servlet/HelloWorldServlet.

Sharing data between ColdFusion pages and JSP pages or servlets

If an application includes ColdFusion pages and JSP pages or servlets, they can share data in the Request, Session and Application scopes. The following table lists the ways that you can access JSP pages with which you want to share the scope data:

Scope | Can share data using
Request | forward, include Note: Shared Request scope variable names in the JSP page or servlet must be all-lowercase.
Session | href, cfhttp, forward, include
Application | href, cfhttp, forward, include

Note: When you share data between ColdFusion pages and JSP pages, you must be careful about data type conversion issues. For more information, see Java and ColdFusion data type conversions.

To share session variables, you must specify J2EE session management in the ColdFusion MX Administrator. For more information on configuring and using J2EE Session scope management, see ColdFusion and J2EE session management.

For example, you could put the customer order structure used in the previous example in the Session scope. Then, you would not have to pass the order values as a set of parameters. Instead, the JSP pages could access the Session scope variables directly, and the ColdFusion page would only require a line like the following to call the JSP page:

getPageContext().forward(URLEncodedFormat("/responsegen/responsegen.jsp"));

For examples of using the Request, Session, and Application scopes to share data between ColdFusion pages and JSP pages, including samples of the appropriate JSP code, see the following section, Examples: using JSP with CFML.

Note: When running in the server configuration, ColdFusion MX also shares the Form scope when calling a JSP or servlet. In the J2EE configuration, however, sharing the Form scope is dependant on the J2EE application server. For example, Macromedia JRun shares the Form scope, IBM WebSphere does not. ColdFusion always shares the Request, Session, and Application scopes.

Accessing ColdFusion application and session variables in JSP pages

ColdFusion MX runs as a J2EE application on the J2EE application server. The J2EE application ServletContext is a data structure that stores objects as attributes. A ColdFusion Application scope is represented as an attribute named by the Application scope name. The attribute contains the scope values as a hash table. Therefore, you access ColdFusion Application scope variable in a JSP page or servlet using the following format:

((Map)application.getAttribute("CFApplicationName"))).get("appVarName")

Similarly, the ColdFusion Session scope is a structure within the J2EE session. Because ColdFusion MX identifies sessions by the application name. the session structure is contained in an attribute of the J2EE session that is identified by the application name. Therefore, you access ColdFusion session variables as follows:

((Map)(session.getAttribute("CFApplicationName"))).get("sessionVarName")

Unnamed ColdFusion Application and Session scopes

If you do not specify an application name in the This.name variable in the Application.cfc initialization code or by using the ColdFusion cfapplication tag, the application is unnamed, and the Application scope corresponds to the ColdFusion MX J2EE servlet context. ColdFusion MX, therefore, supports only a single unnamed application. If multiple cfapplication tags and Application.cfc files do not specify an application name, all pages in these applications share the servlet context as their Application scope.

All sessions of unnamed applications correspond directly to the J2EE application server’s session object. (If you do not use J2EE session variables, ColdFusion MX ensures that the J2EE session lasts at least as long as the session time-out.)

You access an Application scope variable from a ColdFusion unnamed application in a JSP page using the following format:

application.getAttribute("applicationVariableName")

You access Session scope variables in a ColdFusion unnamed application as follows:

session.getAttribute("sessionVariableName")

Note: When you use application and session variables for the unnamed ColdFusion application in JSP pages and servlets, the variable names must be case-correct. That is, the characters in the variable name must have the same case as you used when you created the variable in ColdFusion. You do not have to use case-correct application and session variable names for named ColdFusion applications.


Examples: using JSP with CFML

The following simple examples show how you can integrate JSP pages, servlets, and ColdFusion pages. They also show how you can use the Request, Application, and Session scopes to share data between ColdFusion pages, JSP pages, and servlets.

Calling a JSP page from a ColdFusion page

The following page sets Request, Session, and application variables and calls a JSP page, passing it a name parameter:

<cfapplication name="myApp" sessionmanagement="yes">
<cfscript>
Request.myVariable = "This";
Session.myVariable = "is a";
Application.myVariable = "test.";
GetPageContext().include("hello.jsp?name=Bobby");
</cfscript>

Reviewing the code

The following table describes the CFML code and its function:

Code

Description

<cfapplication name="myApp"
    sessionmanagement="yes">

Specifies the application name as myApp and enables session management. In most applications, this tag is in the Application.cfm page.

<cfscript>
    Request.myVariable = "This";
    Session.myVariable = "is a";
    Application.myVariable = "test.";

Sets ColdFusion Request, Session, and Application, scope variables. Uses the same name, myVariable, for each variable.

    GetPageContext().include
        ("hello.jsp?name=Bobby");
</cfscript>

Uses the GetPageContext function to get the current servlet page context for the ColdFusion page. Uses the include method of the page context object to call the hello.jsp page. Passes the name parameter in the URL.

The hello.jsp page is called by the ColdFusion page. It displays the name parameter in a header and the three variables in the remainder of the body.

<%@page import="java.util.*" %>
<h2>Hello <%= request.getParameter("name")%>!</h2>

<br>Request.myVariable: <%= request.getAttribute("myVariable")%>
<br>session.myVariable: <%= ((Map)(session.getAttribute("myApp"))).get("myVariable")%>
<br>Application.myVariable: <%= ((Map)(application.getAttribute("myApp"))).get("myVariable")%>

Reviewing the code

The following table describes the JSP code and its function (line breaks added for clarity):

Code

Description

<%@page import="java.util.*" %>

Imports the java.util package. This contains methods required in the JSP page.

<h2>Hello <%= request.getParameter
    ("name")%>!</h2>

Displays the name passed as a URL parameter from the ColdFusion page. The parameter name is case-sensitive,

Note: The getParameter request method cannot get all ColdFusion page request parameter values on some application servers. For example, on IBM WebSphere, you cannot use getParameter to get form fields.

<br>request.myVariable: <%= request.
    getAttribute("myvariable")%>

Uses the getAttribute method of the JSP request object to displays the value of the Request scope variable myVariable.

The JSP page must use all lowercase characters to refer to all request scope variables that it shares with CFML pages. You can use any case on the CFML page, but if you use mixed case to all uppercase on the JSP page, the variable will not get its value ColdFusion page.

<br>session.myVariable:
<%= ((Map)(session.getAttribute("myApp"))).
get("myVariable")%>

Uses the getAttribute method of the JSP session object to get the myApp object (the Application scope). Casts this to a Java Map object and uses the get method to obtain the myVariable value for display.

CFML pages and JSP pages share Session variables independent of the variable name case. The variable on the JSP page can have any case mixture and still receive the value from the ColdFusion page. For example, instead of myVariable, you could use MYVARIABLE or myvariable on this line.

<br>Application.myVariable: <%=
((Map)(application.getAttribute("myApp")))
.get("myVariable")%>

Uses the getAttribute method of the JSP myApp application object to obtain the value of myVariable in the Application scope.

CFML pages and JSP pages share Application variables independent of the variable name case. The variable on the JSP page can have any case mixture and still receive the value from the ColdFusion page. For example, instead of myVariable, you could use MYVARIABLE or myvariable on this line.

Calling a ColdFusion page from a JSP page

The following JSP page sets Request, Session, and application variables and calls a ColdFusion page, passing it a name parameter:

<%@page import="java.util.*" %>

<% request.setAttribute("myvariable", "This");%>
<% ((Map)session.getAttribute("myApp")).put("myVariable", "is a");%>
<% ((Map)application.getAttribute("myApp")).put("myVariable", "test.");%>

<jsp:include page="hello.cfm">
    <jsp:param name="name" value="Robert" />
</jsp:include>

Reviewing the code

The following table describes the JSP code and its function:

Code

Description

<%@page import="java.util.*" %>

Imports the java.util package. This contains methods required in the JSP page.

<% request.setAttribute("myvariable",
"This");%>

Uses the setAttribute method of the JSP request object to set the value of the Request scope variable myVariable.

The JSP page must use all lowercase characters to refer to all request scope variables that it shares with CFML pages. You can use any case on the CFML page, but if you use mixed case to all uppercase on the JSP page, the JSP page will not share it with the ColdFusion page.

<% ((Map)session.getAttribute("myApp"))
.put("myVariable", "is a");%>

Uses the getAttribute method of the JSP session object to get the myApp object (the Application scope). Casts this to a Java Map object and uses the set method to set the myVariable value.

CFML pages and JSP pages share Session variables independent of the variable name case. The variable on the JSP page can have any case mixture and still share the value with the ColdFusion page. For example, instead of myVariable, you could use MYVARIABLE or myvariable on this line.

<% ((Map)application.getAttribute
("myApp")).put("myVariable",
"test.");%>

Uses the getAttribute method of the JSP application object to get myApp object (the Application scope) and casts it to a Map object. It then sets the value of myVariable in the myApp application scope object.

CFML pages and JSP pages share Application variables independent of the variable name case. The variable on the JSP page can have any case mixture and still share the value with the ColdFusion page. For example, instead of myVariable, you could use MYVARIABLE or myvariable on this line.

<jsp:include page="hello.cfm">
     <jsp:param name="name" value="Robert" />
</jsp:include>

Sets the name parameter to Robert and calls the ColdFusion page hello.cfm.

The following hello.cfm page is called by the JSP page. It displays the Name parameter in a heading and the three variables in the remainder of the body.

<cfapplication name="myApp" sessionmanagement="yes">
<cfoutput>
<h2>Hello #URL.name#!</h2>
Request.myVariable: #Request.myVariable#<br>
Session.myVariable: #Session.myVariable#<br>
Application.myVariable: #Application.myVariable#<br>

</cfoutput>

Reviewing the code

The following table describes the CFML code and its function:

Code

Description

<cfapplication name="myApp"
sessionmanagement="yes">

Specifies the application name as myApp and enables session management. In most applications, this tag is in the Application.cfm page.

<cfoutput>
<h2>Hello #URL.name#!</h2>

Displays the name passed using the jsp:param tag on the JSP page. The parameter name is not case-sensitive.

Request.myVariable:
#Request.myVariable#<br>
Session.myVariable:
#Session.myVariable#<br>
Application.myVariable:
#Application.myVariable#<br>
</cfoutput>

Displays the Request.myVariable, Session. myVariable, and Application.myVariable values. Note that all variable names on CFML pages are case independent.


Using Java objects

You use the cfobject tag to create an instance of a Java object. You use other ColdFusion tags, such as cfset and cfoutput, or CFScript to invoke properties (attributes), and methods (operations) on the object.

Method arguments and return values can be any valid Java type; for example, simple arrays and objects. ColdFusion does the appropriate conversions when strings are passed as arguments, but not when they are received as return values. For more information on type conversion issues, see Java and ColdFusion data type conversions.

The examples in the following sections assume that the name attribute in the cfobject tag specified the value obj, and that the object has a property called Property, and methods called Method1, Method2, and Method3.

Note: The cfdump tag displays an object’s public methods and data.

  • Using basic object techniques
  • Creating and using a simple Java class
  • Java and ColdFusion data type conversions
  • Handling Java exceptions
  • Examples: using Java with CFML

Using basic object techniques

The following sections describe how to invoke Java objects.

Invoking objects

The cfobject tag makes Java objects available in ColdFusion MX. It can access any Java class that is available on the JVM classpath or in either of the following locations:

  • In a Java archive (.jar) file in web_root/WEB-INF/lib
  • In a class (.class) file in web_root/WEB-INF/classes

For example:

<cfobject type="Java" class="MyClass" name="myObj">

Although the cfobject tag loads the class, it does not create an instance object. Only static methods and fields are accessible immediately after the call to cfobject.

If you call a public non-static method on the object without first calling the init method, there ColdFusion makes an implicit call to the default constructor.

To call an object constructor explicitly, use the special ColdFusion init method with the appropriate arguments after you use the cfobject tag; for example:

<cfobject type="Java" class="MyClass" name="myObj">
<cfset ret=myObj.init(arg1, arg2)>

Note: The init method is not a method of the object, but a ColdFusion identifier that calls the new function on the class constructor. So, if a Java object has an init method, a name conflict exists and you cannot call the object’s init method.

To have persistent access to an object, you must use the init function, because it returns a reference to an instance of the object, and cfobject does not.

An object created using cfobject or returned by other objects is implicitly released at the end of the ColdFusion page execution.

Using properties

Use the following coding syntax to access properties if the object does either of the following actions:

  • Exposes the properties as public properties.
  • Does not make the properties public, but is a JavaBean that provides public getter and setter methods of the form getPropertyName() and setPropertyName(value). For more information, see the following Calling JavaBean get and set methods section.

To set a property:

<cfset obj.property = "somevalue">

To get a property:

<cfset value = obj.property>

Note: ColdFusion does not require that property and method names be consistently capitalized. However, you should use the same case in ColdFusion as you do in Java to ensure consistency.

Calling methods

Object methods usually take zero or more arguments. Some methods return values, while others might not. Use the following techniques to call methods:

  • If the method has no arguments, follow the method name with empty parentheses, as in the following cfset tag:
    <cfset retVal = obj.Method1()>
  • If the method has one or more arguments, put the arguments in parentheses, separated by commas, as in the following example, which has one integer argument and one string argument:
    <cfset x = 23>
<cfset retVal = obj.Method1(x, "a string literal")>

Note: When you invoke a Java method, the type of the data being used is important. For more information see Java and ColdFusion data type conversions.

Calling JavaBean get and set methods

ColdFusion can automatically invoke getPropertyName() and setPropertyName(value) methods if a Java class conforms to the JavaBeans pattern. As a result, you can set or get the property by referencing it directly, without having to explicitly invoke a method.

For example, if the myFishTank class is a JavaBean, the following code returns the results of calling the getTotalFish() method on the myFish object:

<cfoutput>
    There are currently #myFish.TotalFish# fish in the tank.
</cfoutput>

The following example adds one guppy to a myFish object by implicitly calling the setGuppyCount(int number) method:

<cfset myFish.GuppyCount = myFish.GuppyCount + 1>

Note: You can use the direct reference method to get or set values in some classes that have getProperty and setProperty methods but do not conform fully to the JavaBean pattern. However, you cannot use this technique for all classes that have getProperty and setProperty methods. For example, you cannot directly reference any of the following standard Java classes, or classes derived from them: Date, Boolean, Short, Integer, Long, Float, Double, Char, Byte, String, List, Array.

Calling nested objects

ColdFusion supports nested (scoped) object calls. For example, if an object method returns another object and you must invoke a property or method on that object, you can use the following syntax:

<cfset prop = myObj.X.Property>.

Similarly, you can use code such as the following CFScript line:

GetPageContext().include("hello.jsp?name=Bobby");

In this code, the ColdFusion GetPageContext function returns a Java PageContext object, and the line invokes the PageContext object’s include method.


Creating and using a simple Java class

Java is a strongly typed language, unlike ColdFusion, which does not enforce data types. As a result, there are some subtle considerations when calling Java methods. The following sections create and use a Java class to show how to use Java effectively in ColdFusion pages.

The Employee class

The Employee class has four data members: FirstName and LastName are public, and Salary and JobGrade are private. The Employee class has three overloaded constructors and a overloaded SetJobGrade method.

Save the following Java source code in the file Employee.java, compile it, and place the resulting Employee.class file in a directory that is specified in the classpath:

public class Employee {

public String FirstName;
public String LastName;
private float Salary;
private int JobGrade;

public Employee() {
    FirstName ="";
    LastName ="";
    Salary = 0.0f;
    JobGrade = 0;
}

public Employee(String First, String Last) {
    FirstName = First;
    LastName = Last;
    Salary = 0.0f;
    JobGrade = 0;
}

public Employee(String First, String Last, float salary, int grade) {
    FirstName = First;
    LastName = Last;
    Salary = salary;
    JobGrade = grade;
}

public void SetSalary(float Dollars) {
    Salary = Dollars;
}

public float GetSalary() {
    return Salary;
}

public void SetJobGrade(int grade) {
    JobGrade = grade;
}

public void SetJobGrade(String Grade) {
    if (Grade.equals("CEO")) {
        JobGrade = 3;
    }
    else if (Grade.equals("MANAGER")) {
        JobGrade = 2;
    }
    else if (Grade.equals("DEVELOPER")) {
        JobGrade = 1;
    }
}

public int GetJobGrade() {
    return JobGrade;
}

}

A CFML page that uses the Employee class

Save the following text as JEmployee.cfm:

<html>
<body>
<cfobject action="create" type="java" class="Employee" name="emp">
<!--- <cfset emp.init()> --->
<cfset emp.firstname="john">
<cfset emp.lastname="doe">
<cfset firstname=emp.firstname>
<cfset lastname=emp.lastname>
</body>

<cfoutput>
    Employee name is #firstname# #lastname#
</cfoutput>
</html>

When you view the page in your browser, you get the following output:

Employee name is john doe

Reviewing the code

The following table describes the CFML code and its function:

Code

Description

<cfobject action=create
    type=java class=Employee
    name=emp>

Loads the Employee Java class and gives it an object name of emp.

<!--- <cfset emp.init()> --->

Does not call a constructor. ColdFusion invokes the default constructor when it first uses the class; in this case, when it processes the next line.

<cfset emp.firstname="john">
<cfset emp.lastname="doe">

Sets the public fields in the emp object to your values.

<cfset firstname=emp.firstname>
<cfset lastname=emp.lastname>

Gets the field values back from emp object.

<cfoutput>
    Employee name is #firstname#
        #lastname#
</cfoutput>

Displays the retrieved values.

Java considerations

Keep the following points in mind when you write a ColdFusion page that uses a Java class object:

  • The Java class name is case-sensitive. You must ensure that the Java code and the CFML code use Employee as the class name.
  • Although Java method and field names are case-sensitive, ColdFusion variables are not case-sensitive, and ColdFusion does any necessary case conversions. As a result, the sample code works even though the CFML uses emp.firstname and emp.lastname; the Java source code uses FirstName and LastName for these fields.
  • If you do not call the constructor (or, as in this example, comment it out), ColdFusion automatically invokes the default constructor when it first uses the class.

Using an alternate constructor

The following ColdFusion page explicitly calls one of the alternate constructors for the Employee object:

<html>
<body>

<cfobject action="create" type="java" class="Employee" name="emp">
<cfset emp.init("John", "Doe", 100000.00, 10)>
<cfset firstname=emp.firstname>
<cfset lastname=emp.lastname>
<cfset salary=emp.GetSalary()>
<cfset grade=emp.GetJobGrade()>

<cfoutput>
    Employee name is #firstname# #lastname#<br>
    Employee salary #DollarFormat(Salary)#<br>
    Employee Job Grade #grade#
</cfoutput>

</body>
</html>

In this example, the constructor takes four arguments: the first two are strings, the third is a float, and the fourth is an integer.


Java and ColdFusion data type conversions

ColdFusion does not use explicit types for variables, while Java is strongly typed. However, ColdFusion data does use a number of underlying types to represent data.

Under most situations, when the method names are not ambiguous, ColdFusion can determine the data types that are required by a Java object, and often it can convert ColdFusion data to the required types. For example, ColdFusion text strings are implicitly converted to the Java String type. Similarly, if a Java object contains a doIt method that expects a parameter of type int, and CFML is issuing a doIt call with a CFML variable x that contains an integer value, ColdFusion converts the variable x to Java int type. However, ambiguous situations can result from Java method overloading, where a class has multiple implementations of the same method that differ only in their parameter types.

The following sections describe how ColdFusion handles the unambiguous situations, and how it provides you with the tools to handle ambiguous ones.

Default data type conversion

Whenever possible, ColdFusion automatically matches Java types to ColdFusion types.

The following table lists how ColdFusion converts ColdFusion data values to Java data types when passing arguments. The left column represents the underlying ColdFusion representation of its data. The right column indicates the Java data types into which ColdFusion can automatically convert the data:

CFML

Java

Integer

short, int, long (short and int might result in a loss of precision).

Real number

float double (float might result in a loss of precision.

Boolean

boolean

Date-time

java.util.Date

String, including lists

String

short, int, long, float, double, java.util.Date, when a CFML string represents a number or date.

boolean, for strings with the value Yes, No, True, and False (case-insensitive).

Array

java.util.Vector (ColdFusion Arrays are internally represented using an instance of a java.util.Vector object.)

ColdFusion can also map a CFML array to any of the following when the CFML array contains consistent data of a type that can be converted to the Java array’s data type: byte[], char[], boolean[], int[], long[], float[], double[], String[], or Object[]. When a CFML array contains data of different of types, the conversion to a simple array type might fail.

Structure

java.util.Map

Query object

java.util.Map

XML document object

Not supported.

ColdFusion component

Not applicable.

The following table lists how ColdFusion converts data returned by Java methods to ColdFusion data types:

Java | CFML
boolean/Boolean | Boolean
byte/Byte | String
char/Char | String
short/Short | Integer
int/Integer | Integer
long/Long | Integer
float/Float | Real Number
double/Double | Real Number
String | String
java.util.Date | Date-time
java.util.List | Comma-delimited list
byte[] | Array
char[] | Array
boolean[] | Array
String[] | Array
java.util.Vector | Array
java.util.Map | Structure

Resolving ambiguous data types with the JavaCast function

You can overload Java methods so a class can have several identically named methods. At runtime, the JVM resolves the specific method to use based on the parameters passed in the call and their types.

In the section The Employee class, the Employee class has two implementations for the SetJobGrade method. One method takes a string variable, the other an integer. If you write code such as the following, which implementation to use is ambiguous:

<cfset emp.SetJobGrade("1")>

The "1" could be interpreted as a string or as a number, so there is no way to know which method implementation to use. When ColdFusion encounters such an ambiguity, it throws a user exception.

The ColdFusion JavaCast function helps you resolve such issues by specifying the Java type of a variable, as in the following line:

<cfset emp.SetJobGrade(JavaCast("int", "1"))>

The JavaCast function takes two parameters: a string representing the Java data type, and the variable whose type you are setting. You can specify the following Java data types: boolean, int, long, float, double, and String.

For more information about the JavaCast function, see CFML Reference.


Handling Java exceptions

You handle Java exceptions just as you handle standard ColdFusion exceptions, with the cftry and cfcatch tags. You specify the name of the exception class in the cfcatch tag that handles the exception. For example, if a Java object throws an exception named myException, you specify myException in the cfcatch tag.

Note: To catch any exception generated by a Java object, specify java.lang.Exception for the cfcatch type attribute. To catch any Throwable errors, specify java.lang.Throwable in the cfcatch tag type attribute.

The following sections show an example of throwing and handling a Java exception.

For more information on exception handling in ColdFusion MX, see Handling Errors.

Example: exception-throwing class

The following Java code defines the testException class that throws a sample exception. It also defines a myException class that extends the Java built-in Exception class and includes a method for getting an error message.

The myException class has the following code. It throws an exception with a message that is passed to it, or if no argument is passed, it throws a canned exception.

//class myException
public class myException extends Exception
{
    public myException(String msg) {
        super(msg);
    }
    public myException() {
        super("Error Message from myException");
    }
}

The testException class contains one method, doException, which throws a myException error with an error message, as follows:

public class testException {
    public testException ()
    {
    }
    public void doException() throws myException {
        throw new myException("Throwing an exception from testException class");
    }
}

Example: CFML Java exception handling code

The following CFML code calls the testException class doException method. The cfcatch block handles the resulting exception.

<cfobject action=create type=java class=testException name=Obj>
<cftry>
    <cfset Obj.doException() >
    <cfcatch type="myException">
        <cfoutput>
            <br>The exception message is: #cfcatch.Message#<br>
        </cfoutput>
    </cfcatch>
</cftry>


Examples: using Java with CFML

The following sections show several examples of using Java objects in CFML. They include examples of using a custom Java class, a standard Java API class in a user-defined function, a JavaBean, and an Enterprise JavaBean (EJB).

Using a Java API in a UDF

The following example of a user-defined function (UDF) is functionally identical to the GetHostAddress function from the NetLib library of UDFs from the Common Function Library Project, www.cflib.org. It uses the InetAddress class from the standard Java 2 java.net package to get the Internet address of a specified host:

<cfscript>
function GetHostAddress(host) {
    // Define the function local variables.
    var iaddrClass="";
    var address="";
    // Initialize the Java class.
    iaddrClass=CreateObject("java", "java.net.InetAddress");
    // Get the address object.
    address=iaddrClass.getByName(host);
    // Return the address
    return address.getHostAddress();
}
</cfscript>
<cfoutput>#gethostaddress("macromedia.com")#</cfoutput>

Using an EJB

ColdFusion MX can use EJBs that are served by JRun 4.0 servers. The JRun server jrun.jar file must have the same version as the jrun.jar file in ColdFusion.

To call an EJB, you use cfobject type="Java" to create and call the appropriate objects. Before you can use an EJB you must do the following:

  1. Have a properly deployed EJB running on a J2EE server. The bean must be registered with the JNDI server.
  2. Have the following information:
    • Name of the EJB server
    • Port number of the JNDI naming service on the EJB server
    • Name of the EJB, as registered with the naming service
  3. Install the EJB home and component interface compiled classes on your ColdFusion web server, either as class files in the web_root/WEB-INF/classes directory or packaged in a JAR file the web_root/WEB-INF/lib directory.

Note: To use an EJB served by a JRUN server, your ColdFusion installation and the JRun server that hosts the EJB must have the same version of the jrun.jar file (located in cf_root\runtime\lib directory in ColdFusion).

Although the specific steps for using an EJB depend on the EJB server and on the EJB itself, they generally correspond to the following order.

To use an EJB:

  1. Use the cfobject tag to create an object of the JNDI naming context class (javax.naming.Context). You will use fields from this class to define the information that you use to locate the EJB. Because you only use fields, you do not initialize the object.
  2. Use the cfobject tag to create a java.util.Properties class object that will contain the context object properties.
  3. Call the init method to initialize the Properties object.
  4. Set the Properties object to contain the properties that are required to create an initial JNDI naming context. These include the INITIAL_CONTEXT_FACTORY and PROVIDER_URL properties. You might also need to provide SECURITY_PRINCIPAL and SECURITY_CREDENTIALS values required for secure access to the naming context. For more information on these properties, see the JNDI documentation.
  5. Use the cfobject tag to create the JNDI InitialContext (javax.naming. InitialContext) object.
  6. Call the init method for the InitialContext object with the Properties object values to initialize the object.
  7. Call the InitialContextext object’s lookup method to get a reference to the home interface for the bean that you want. Specify the JNDI name of the bean as the lookup argument.
  8. Call the create method of the bean’s home object to create a new instance of the bean. If you are using Entity beans, you typically use a finder method instead. A finder method locates one or more existing entity beans.
  9. Now you can use the bean’s methods as required by your application.
  10. When finished, call the context object’s close method to close the object.

The following code shows this process using a simple Java Entity bean on a JRun 4.0 server. It calls the bean’s getMessage method to obtain a message.

<html>
<head>
    <title>cfobject Test</title>
</head>

<body>
<H1>cfobject Test</H1>
<!--- Create the Context object to get at the static fields. --->
<CFOBJECT
    action=create
    name=ctx
    type="JAVA"
    class="javax.naming.Context">

<!--- Create the Properties object and call an explicit constructor--->
<CFOBJECT
    action=create
    name=prop
    type="JAVA"
    class="java.util.Properties">

<!--- Call the init method (provided by cfobject)
        to invoke the Properties object constructor. --->
<cfset prop.init()>

<!--- Specify the properties These are required for a remote server only --->
<cfset prop.put(ctx.INITIAL_CONTEXT_FACTORY, "jrun.naming.JRunContextFactory")>
<cfset prop.put(ctx.PROVIDER_URL, "localhost:2908")>
<!--- <cfset prop.put(ctx.SECURITY_PRINCIPAL, "admin")>
        <cfset prop.put(ctx.SECURITY_CREDENTIALS, "admin")>
 --->
<!--- Create the InitialContext --->
<CFOBJECT
    action=create
    name=initContext
    type="JAVA"
    class="javax.naming.InitialContext">

<!--- Call the init method (provided through cfobject)
        to pass the properties to the InitialContext constructor. --->
<cfset initContext.init(prop)>

<!--- Get reference to home object. --->
<cfset home = initContext.lookup("SimpleBean")>

<!--- Create new instance of entity bean.
        (hard-wired account number). Alternatively,
        you would use a find method to locate an existing entity bean. --->
<cfset mySimple = home.create()>

<!--- Call a method in the entity bean. --->
<cfset myMessage = mySimple.getMessage()>

<cfoutput>
    #myMessage#<br>
</cfoutput>

<!--- Close the context. --->
<cfset initContext.close()>

</body>
</html>

Using a custom Java class

The following code provides a more complex custom class than in the example Creating and using a simple Java class. The Example class manipulates integer, float, array, Boolean, and Example object types.

The Example class

The following Java code defines the Example class. The Java class Example has one public integer member, mPublicInt. Its constructor initializes mPublicInt to 0 or an integer argument. The class has the following public methods:

Method | Description
ReverseString | Reverses the order of a string.
ReverseStringArray | Reverses the order of elements in an array of strings.
Add | Overloaded: Adds and returns two integers or floats or adds the mPublicInt members of two Example class objects and returns an Example class object.
SumArray | Returns the sum of the elements in an integer array.
SumObjArray | Adds the values of the mPublicInt members of an array of Example class objects and returns an Example class object.
ReverseArray | Reverses the order of an array of integers.
Flip | Switches a Boolean value.
public class Example { public int mPublicInt; public Example() { mPublicInt = 0; } public Example(int IntVal) { mPublicInt = IntVal; } public String ReverseString(String s) { StringBuffer buffer = new StringBuffer(s); return new String(buffer.reverse()); } public String[] ReverseStringArray(String [] arr) { String[] ret = new String[arr.length]; for (int i=0; i < arr.length; i++) { ret[arr.length-i-1]=arr[i]; } return ret; } public int Add(int a, int b) { return (a+b); } public float Add(float a, float b) { return (a+b); } public Example Add(Example a, Example b) { return new Example(a.mPublicInt + b.mPublicInt); } static public int SumArray(int[] arr) { int sum=0; for (int i=0; i < arr.length; i++) { sum += arr[i]; } return sum; } static public Example SumObjArray(Example[] arr) { Example sum= new Example(); for (int i=0; i < arr.length; i++) { sum.mPublicInt += arr[i].mPublicInt; } return sum; } static public int[] ReverseArray(int[] arr) { int[] ret = new int[arr.length]; for (int i=0; i < arr.length; i++) { ret[arr.length-i-1]=arr[i]; } return ret; } static public boolean Flip(boolean val) { System.out.println("calling flipboolean"); return val?false:true; } }

The useExample ColdFusion page

The following useExample.cfm page uses the Example class to manipulate numbers, strings, Booleans, and Example objects. The JavaCast CFML function ensures that CFML variables convert into the appropriate Java data types.

<html>
<head>
    <title>CFOBJECT and Java Example</title>
</head>
<body>

<!--- Create a reference to an Example object --->
<cfobject action=create type=java class=Example name=obj>
<!--- Create the object and initialize its public member to 5 --->
<cfset x=obj.init(JavaCast("int",5))>

<!--- Create an array and populate it with string values,
        then use the Java object to reverse them. --->
<cfset myarray=ArrayNew(1)>
<cfset myarray[1]="First">
<cfset myarray[2]="Second">
<cfset myarray[3]="Third">
<cfset ra=obj.ReverseStringArray(myarray)>

<!--- Display the results --->
<cfoutput>
    <br>
    original array element 1: #myarray[1]#<br>
    original array element 2: #myarray[2]#<br>
    original array element 3: #myarray[3]#<br>
    after reverse  element 1: #ra[1]#<br>
    after reverse  element 2: #ra[2]#<br>
    after reverse  element 3: #ra[3]#<br>
    <br>
</cfoutput>

<!--- Use the Java object to flip a Boolean value, reverse a string,
        add two integers, and add two float numbers --->
<cfset c=obj.Flip(true)>
<cfset StringVal=obj.ReverseString("This is a test")>
<cfset IntVal=obj.Add(JavaCast("int",20),JavaCast("int",30))>
<cfset FloatVal=obj.Add(JavaCast("float",2.56),JavaCast("float",3.51))>

<!--- Display the results --->
<cfoutput>
    <br>
    StringVal: #StringVal#<br>
    IntVal: #IntVal#<br>
    FloatVal: #FloatVal#<br>
    <br>
</cfoutput>

<!--- Create a two-element array, sum its values,
        and reverse its elements --->
<cfset intarray=ArrayNew(1)>
<cfset intarray[1]=1>
<cfset intarray[2]=2>
<cfset IntVal=obj.sumarray(intarray)>
<cfset reversedarray=obj.ReverseArray(intarray)>

<!--- Display the results --->
<cfoutput>
    <br>
    IntVal1 :#IntVal#<br>
    array1: #reversedarray[1]#<br>
    array2: #reversedarray[2]#<br>
    <br>
</cfoutput><br>

<!--- Create a ColdFusion array containing two Example objects.
        Use the SumObjArray method to add the objects in the array
        Get the public member of the resulting object--->
<cfset oa=ArrayNew(1)>
<cfobject action=create type=java class=Example name=obj1>
<cfset VOID=obj1.init(JavaCast("int",5))>
<cfobject action=create type=java class=Example name=obj2>
<cfset VOID=obj2.init(JavaCast("int",10))>
<cfset oa[1] = obj1>
<cfset oa[2] = obj2>
<cfset result = obj.SumObjArray(oa)>
<cfset intval = result.mPublicInt>

<!--- Display the results --->
<cfoutput>
    <br>
    intval1: #intval#<br>
    <br>
</cfoutput><br>
</body>
</html>
Previous


Integrating COM and CORBA Objects in CFML Applications

Next

Integrating COM and CORBA Objects in
CFML Applications

This chapter describes how to use the cfobject tag to invoke COM (Component Object Model) or DCOM (Distributed Component Object Model) and CORBA (Common Object Request Broker) objects.

Contents

About COM and CORBA

Creating and using objects

Getting started with COM and DCOM

Creating and using COM objects

Getting started with CORBA

Creating and using CORBA objects

CORBA example
Next


About COM and CORBA

This section provides some basic information on COM and CORBA objects supported in Macromedia ColdFusion MX and provides resources for further inquiry.

About objects

COM and CORBA are two of the object technologies supported by ColdFusion MX. Other object technologies include Java and ColdFusion components. For more information on ColdFusion components see Building and Using ColdFusion Components.

An object is a self-contained module of data and its associated processing. An object is a building block that you can put together with other objects and integrate into ColdFusion code to create an application.

An object is represented by a handle, or name. Objects have properties that represent information. Objects also provide methods for manipulating the object and getting data from it. The exact terms and rules for using objects vary with the object technology.

You create instances of objects using the cfobject tag or the CreateObject function. You then use the object and its methods in ColdFusion tags, functions, and expressions. For more information on the ColdFusion syntax for using objects, see Creating and using objects.

About COM and DCOM

COM (Component Object Model) is a specification and a set of services defined by Microsoft to enable component portability, reusability, and versioning. DCOM (Distributed Component Object Model) is an implementation of COM for distributed services, which allows access to components residing on a network.

COM objects can reside locally or on any network node. COM is supported on Microsoft Windows platforms.

For more information on COM, go to the Microsoft COM website, www.microsoft.com/com.

About CORBA

CORBA (Common Object Request Broker Architecture) is a distributed computing model for object-oriented applications defined by the Object Management Group (OMG). In this model, an object is an encapsulated entity whose services are accessed only through well-defined interfaces. The location and implementation of each object is hidden from the client requesting the services. ColdFusion supports CORBA 2.3 on both Windows and UNIX.

CORBA uses an Object Request Broker (ORB) to send requests from applications on one system to objects executing on another system. The ORB allows applications to interact in a distributed environment, independent of the computer platforms on which they run and the languages in which they are implemented. For example, a ColdFusion application running on one system can communicate with an object that is implemented in C++ on another system.

CORBA follows a client-server model. The client invokes operations on objects that are managed by the server, and the server replies to requests. The ORB manages the communications between the client and the server using the Internet Inter-ORB Protocol (IIOP).

Each CORBA object has an interface that is defined in the CORBA Interface Definition Language (IDL). The CORBA IDL describes the operations that can be performed on the object, and the parameters of those operations. Clients do not have to know anything about how the interface is implemented to make requests.

To request a service from the server, the client application gets a handle to the object from the ORB. It uses the handle to call the methods specified by the IDL interface definition. The ORB passes the requests to the server, which processes the requests and returns the results to the client.

For information about CORBA, see the following OMG website, which is the main web repository for CORBA information: www.omg.com.


Creating and using objects

You use the cfobject tag or the CreateObject function to create a named instance of an object. You use other ColdFusion tags, such as cfset and cfoutput, to invoke the object’s properties and methods.

The following sections provide information about creating and using objects that applies to both COM and CORBA objects. The examples assume a sample object named "obj", and that the object has a property called "Property", and methods called "Method1", "Method2", and "Method3".

Creating objects

You create, or instantiate (create a named instance of) an object in ColdFusion with the cfobject tag or CreateObject function. The specific attributes or parameters that you use depend on the type of object you use, and are described in detail in Creating and using COM objects and Creating CORBA objects. The following examples use a cfobject tag to create a COM object and a CreateObject function to create a CORBA object:

<cfobject type="COM" action="Create" name="obj" class="sample.MyObject">
obj = CreateObject("CORBA", "d:\temp\tester.ior", "IOR", "Visibroker")

ColdFusion releases any object created by cfobject or CreateObject, or returned by other objects, at the end of the ColdFusion page execution.

Using properties

Use standard ColdFusion statements to access properties as follows:

  • To set a property, use a statement or cfset tag, such as the following:
    <cfset obj.property = "somevalue">
  • To get a property, use a statement or cfset tag, such as the following:
    <cfset value = obj.property>

As shown in this example, you do not use parentheses on the right side of the equation to get a property value.

Calling methods

Object methods usually take zero or more arguments. You send In arguments, whose values are not returned to the caller by value. You send Out and In,Out arguments, whose values are returned to the caller, by reference. Arguments sent by reference usually have their value changed by the object. Some methods have return values, while others might not.

Use the following techniques to call methods:

  • If the method has no arguments, follow the method name with empty parentheses, as in the following cfset tag:
    <cfset retVal = obj.Method1()>
  • If the method has one or more arguments, put the arguments in parentheses, separated by commas, as in the following example, which has one integer argument and one string argument:
    <cfset x = 23>
<cfset retVal = obj.Method1(x, "a string literal")>
  • If the method has reference (Out or In,Out) arguments, use double quotation marks (") around the name of the variable you are using for these arguments, as shown for the variable x in the following example:
    <cfset x = 23>
<cfset retVal = obj.Method2("x",  "a string literal")>
<cfoutput> #x#</cfoutput>

    In this example, if the object changes the value of x, it now contains a value other than 23.

Calling nested objects

ColdFusion supports nested (scoped) object calls. For example, if an object method returns another object, and you must invoke a property or method on that object, you can use the syntax in either of the following examples:

<cfset prop = myObj.X.Property>

or

<cfset objX = myObj.X>
<cfset prop = objX.Property>


Getting started with COM and DCOM

ColdFusion is an automation (late-binding) COM client. As a result, the COM object must support the IDispatch interface, and arguments for methods and properties must be standard automation types. Because ColdFusion is a typeless language, it uses the object's type information to correctly set up the arguments on call invocations. Any ambiguity in the object's data types can lead to unexpected behavior.

In ColdFusion, you should only use server-side COM objects, which do not have a graphical user interface. If your ColdFusion application invokes an object with a graphical interface in a window, the component might appear on the web server desktop, not on the user's desktop. This can take up ColdFusion server threads and prevent further web server requests from being serviced.

ColdFusion can call Inproc, Local, or Remote COM objects. The attributes specified in the cfobject tag determine which type of object is called.

This section describes the following topics:

  • COM requirements
  • Registering the object
  • Finding the component ProgID and methods


COM requirements

To use COM components in your ColdFusion application, you need at least the following items:

  • The COM objects (typically DLL or EXE files) that you want to use in your ColdFusion application pages. These components should allow late binding; that is, they should implement the IDispatch interface.
  • Microsoft OLE/COM Object Viewer, available from Microsoft at www.microsoft.com/com/resources/oleview.asp. This tool lets you view registered COM objects.

    Object Viewer lets you view an object's class information so that you can properly define the class attribute for the cfobject tag. It also displays the object’s supported interfaces, so you can discover the properties and methods (for the IDispatch interface) of the object.


Registering the object

After you acquire an object, you must register it with Windows for ColdFusion (or any other program) to find it. Some objects have setup programs that register objects automatically, while others require manual registration.

You can register Inproc object servers (.dll or .ocx files) manually by running the regsvr32.exe utility using the following form:

regsvr32 c:\path\servername.dll

You typically register Local servers (.exe files) either by starting them or by specifying a command line parameters, such as the following:

C:\pathname\servername.exe -register


Finding the component ProgID and methods

Your COM object supplier should provide documentation that explains each of the component's methods and the ProgID. If you do not have documentation, use either the ColdFusion cfdump tag or the OLE/COM Object Viewer to view the component’s interface.

Using the cfdump tag to view COM object interfaces

Effective with ColdFusion MX, the ColdFusion cfdump tag displays the following information about a COM object:

  • Public methods
  • Put properties
  • Get properties

The method and property information includes the parameter or property types and whether they are in, out, optional, or retval values. The cfdump tag output does not include the object’s ProgID.

Note: The dump header indicates the ColdFusion object class, which is coldfusion.runtime.com.ComProxy, and the COM object CLSID.

Using the OLE/COM Object Viewer

The OLE/COM Object Viewer installation installs the executable, by default, as \mstools\bin\oleview.exe. You use the Object Viewer to retrieve a COM object’s ProgID, as well as its methods and properties.

To find an object in the Object Viewer, it must be registered, as described in Registering the object. The Object Viewer retrieves all COM objects and controls from the Registry, and presents the information in a simple format, sorted into groups for easy viewing.

By selecting the category and then the component, you can see the ProgID of a COM object. The Object Viewer also provides access to options for the operation of the object.

To view an object's properties:

  1. Open the Object Viewer, as shown in the following figure, and scroll to the object that you want to examine.

    The OLE/COM object viewer

  2. Select and expand the object in the left pane of the Object Viewer.
  3. Right-click the object to view it, including the TypeInfo.

    If you view the TypeInfo, you see the object's methods and properties, as shown in the following figure. Some objects do not have access to the TypeInfo area, which is determined when an object is built and by the language used.

    The methods and properties of an object shown in the Object Viewer


Creating and using COM objects

You must use the cfobject tag or the CreateObject function to create an instance of the COM object (component) in ColdFusion before your application pages can invoke any methods or assign any properties in the component.

For example, the following code uses the cfobject tag to create the Windows CDO (Collaborative Data Objects) for NTS NewMail object to send mail:

<cfobject type="COM"
        action="Create"
        name="Mailer"
        class="CDONTS.NewMail">

The following line shows how to use the corresponding CreateObject function in CFScript:

Mailer = CreateObject("COM", "CDONTS.NewMail");

The examples in later sections in this chapter use this object.

Note: CDO is installed by default on all Windows NT and 2000 operating systems that have installed the Microsoft SMTP server. In Windows NT Server environments, the SMTP server is part of the Option Pack 4 setup. In Windows 2000 Server and Workstation environments, it is bundled with the operating system. For more information on CDO for NTS, see http://msdn.microsoft.com/library/default.asp?URL=/library/psdk/cdo/_olemsg_overview_of_cdo.htm.

The CDO for NTS NewMail component includes a number of methods and properties to perform a wide range of mail-handling tasks. (In the OLE/COM Object Viewer, methods and properties might be grouped together, so you could find it difficult to distinguish between them at first.)

The CDO for NTS NewMail object includes the following properties:

Body [ String ]
Cc  [ String ]
From  [ String ]
Importance  [ Long ]
Subject  [ String ]
To  [ String ]

You use these properties to define elements of your mail message. The CDO for NTS NewMail object also includes a send method which has a number of optional arguments to send messages.

This section describes the following topics:

  • Connecting to COM objects
  • Setting properties and invoking methods
  • General COM object considerations
  • Accessing Complex COM Objects using Java proxies
  • Using the Application Scope to improve COM performance


Connecting to COM objects

The action attribute of the cfobject tag provides the following two ways to connect to COM objects:

Create method (cfobject action="Create") Takes a COM object, typically a DLL, and instantiates it prior to invoking methods and assigning properties.

Connect method (cfobject action="Connect") Links to an object, typically an executable, that is already running on the server.

You can use the optional cfobject context attribute to specify the object context. If you do not specify a context, ColdFusion uses the setting in the Registry. The following table describes the context attribute values:

Attribute value | Description
InProc | An in-process server object (typically a DLL) that is running in the same process space as the calling process, such as ColdFusion.
local | An out-of-process server object (typically an EXE file) that is running outside the ColdFusion process space but running locally on the same server.
remote | An out-of-process server object (typically an EXE file) that is running remotely on the network. If you specify remote, you must also use the server attribute to identify where the object resides.


Setting properties and invoking methods

The following example, which uses the sample Mailer COM object, shows how to assign properties to your mail message and how to execute component methods to handle mail messages.

In the example, form variables contain the method parameters and properties, such as the name of the recipient, the desired e-mail address, and so on:

<!--- First, create the object --->
<cfobject type="COM"
    action="Create"
    name="Mailer"
    class="CDONTS.NewMail">

<!--- Second, use the form variables from the user entry form to populate a number
        of properties necessary to create and send the message. --->
<cfset Mailer.From = "#Form.fromName#">
<cfset Mailer.To = "#Form.to#">
<cfset Mailer.Subject = "#Form.subject#">
<cfset Mailer.Importance = 2>
<cfset Mailer.Body = "#Form.body#">
<cfset Mailer.Cc = "#Form.cc#">

<!--- Last, use the Send() method to send the message.
    Invoking the Send() method destroys the object.--->
<cfset Mailer.Send()>

Note: Use the cftry and cfcatch tags to handle exceptions thrown by COM objects. For more information on exception handling, see Handling runtime exceptions with ColdFusion tags.

Releasing COM objects

By default, COM object resources are released when the Java garbage collector cleans them. You can use the ReleaseCOMObject function to immediately release resources if an object is no longer needed.

Use the ReleaseCOMObject function to release COM objects that are launched as an external process, such as Microsoft Excel. The garbage collector might not clean these processes in a short time, resulting in multiple external processes running, which drains system resources.

If the COM object has an end method, such as a quit method that terminates the program, call this method before you call the ReleaseComObject function. If you use the ReleaseComObject function on an object that is in use, the object is prematurely released and your application will get exceptions.

Example

The following example creates a Microsoft Excel application object, uses it, then releases the object when it is no longer needed:

<h3>ReleaseComObject Example</h3>
<cfscript>
obj = CreateObject("Com", "excel.application.9");
//code that uses the object goes here
obj.quit();
ReleaseComObject(obj);
</cfscript>


General COM object considerations

When you use COM objects, consider the following to prevent and resolve errors:

  • Ensuring correct threading
  • Using input and output arguments
  • Understanding common COM-related error messages

The following sections describe these issues.

Ensuring correct threading

Improper threading can cause serious problems when using a COM object in ColdFusion. Make sure that the object is thread-safe. An object is thread-safe if it can be called from many programming threads simultaneously, without causing errors.

Visual Basic ActiveX DLLs are typically not thread-safe. If you use such a DLL in ColdFusion, you can make it thread-safe by using the OLE/COM Object Viewer to change the object’s threading model to the Apartment model.

If you are planning to store a reference to the COM object in the Application, Session, or Server scope, do not use the Apartment threading model. This threading model is intended to service only a single request. If your application requires you to store the object in any of these scopes, keep the object in the Both threading model, and lock all code that accesses the object, as described in Locking code with cflock.

To change the threading model of a COM Object:

  1. Open the OLE/COM Object Viewer.
  2. Select All Objects under Object Classes in the left pane.
  3. Locate your COM object. The left pane lists these by name.
  4. Select your object.
  5. Select the Implementation tab in the right pane.
  6. Select the Inproc Server tab, below the App ID field.
  7. Select the Threading Model drop down menu and select Apartment or Both, as appropriate.

Using input and output arguments

COM object method in arguments are passed by value. The COM object gets a copy of the variable value, so you can specify a ColdFusion variable without surrounding it with quotation marks.

COM object out method arguments are passed by reference. The COM object modifies the contents of the variable on the calling page, so the calling page can use the resulting value. To pass a variable by reference, surround the name of an existing ColdFusion variable with quotation marks. If the argument is a numeric type, assign the variable a valid number before you make the call. For example:

<cfset inStringArg="Hello Object">
<cfset outNumericArg=0>
<cfset result=myCOMObject.calculate(inStringArg, "outNumericArg")>

The string "Hello Object" is passed to the object's calculate method as an input argument. The value of outNumericArg is set by the method to a numeric value.

Understanding common COM-related error messages

The following table described some error messages you might encounter when using COM objects:

Error | Cause
Error Diagnostic Information Error trying to create object specified in the tag. COM error 0x800401F3. Invalid class string. | The COM object is not registered or does not exist.
Error Diagnostic Information Error trying to create object specified in the tag. COM error 0x80040154. Class not registered. | The COM object is not registered or does not exist. This error usually occurs when an object existed previously, but was uninstalled.
Error Diagnostic Information Failed attempting to find "SOMEMETHOD" property/method on the object COM error 0x80020006. Unknown name. | The COM object was instantiated correctly, but the method you specified does not exist.


Accessing Complex COM Objects using Java proxies

ColdFusion MX supports Java proxies to access COM objects. If you do not create Java proxies in advance, ColdFusion must dynamically discover the COM interface. This technique can have two disadvantages:

  • Dynamic discovery takes time and can reduce server performance with frequently used complex COM objects.
  • Dynamic discovery uses the IDispatcher interface to determine the COM object features, and might not handle some complex COM interfaces.

To overcome these problems, ColdFusion MX includes a utility, com2java.exe, that creates static Java stub proxy classes for COM objects. ColdFusion can use these Java stubs to access COM objects more efficiently than when it creates the proxies dynamically. Additionally, the com2java.exe utility can create stubs for features that the dynamic proxy generator might miss.

ColdFusion MX ships with pregenerated stubs for the Windows XP, Windows 2000, and Windows 97 editions of Microsoft Excel, Microsoft Word, and Microsoft Access. ColdFusion MX is configured to automatically use these stubs.

If you create Java stub files for a COM object, you continue to use the cfobject tag with a type attribute value of COM, or the CreateObject function with a first argument of COM, and you access the object properties and methods as you normally do for COM objects in ColdFusion.

Use the following steps to use the com2java.exe utility. This procedure uses Microsoft Outlook as an example.

To create Java stub files for COM objects:

  1. Configure your system as follows:
    1. Ensure that a JDK (Java Development Kit) is correctly installed, including proper configuration of the CLASSPATH and the command prompt PATH variable.
    2. Add CF_root\lib\jintegra.jar to your CLASSPATH.
  2. Make a new directory for the Java stub files; for example:
    mkdir C:\src\outlookXP

    This directory can be temporary. You add files from the directory to a ColdFusion JAR file.

  3. Run the CF_root\Jintegra\bin\com2java.exe program from a command line or the Windows Start Menu. A window appears.
    1. If a COM class implements multiple interfaces that define methods with the same names, click the Options button and clear the Implement interfaces that may conflict option. The generated Java stub classes do not implement the additional, conflicting, interfaces. You can still access the interfaces using the getAsXXX method that is generated. See the generated comments in the Java files.
    2. Click on the Select button.
    3. Select your COM object’s Type Library or DLL. For Microsoft Outlook in Windows XP, it is normally Program Files\Microsoft Office\Office10\MSOUTL.OLB.
    4. Enter a package name (for example, outlookXP) in the Java package field in the com2java dialog box. This package will contain all the classes for the Java stubs for the COM object.

      Note: Macromedia uses a package name that starts with coldfusion.runtime.com.com2java for the packages that contain the preinstalled Java stubs for Microsoft Excel, Microsoft Word, and Microsoft Access. For example, the name for the package containing the Microsoft Word XP Java stub classes is coldfusion.runtime.com.com2java.wordXP. This package name hierarchy results in the wordXP classes having a path inside the msapps.jar file of coldfusion\runtime\
      com\com2java\wordXP\className.class. Although this naming convention is not necessary, consider using a similar package naming convention for clarity, if you use many COM objects.

    5. Click the Generate Proxies button to display the File browser. Select the directory you created in step 2., and click the file browser OK button to generate the stub files.
    6. Click Close to close the com2java.exe utility.

    The files generated in your directory include the following:

    • A Java interface and proxy class for each COM interface
    • A Java class for each COM class
    • A Java interface for each ENUM (a set of constant definitions)
  4. Compile your Java code. In a command prompt, do the following:
    1. Make the directory that contains the Java stubs (in this example, C:\src\outlookXP) your working directory.
    2. Enter the following line:
      javac -J-mx100m -J-ms100m *.java

      The compiler switches ensure that you have enough memory to compile all the necessary files.

      Note: If you did not put jintegra.jar on your CLASSPATH in step 1b, add the switch
      -classpath:/cf_root/lib/jintegra.jar, where cf_root is the directory where ColdFusion is installed, to the command.
  5. Ensure that the ColdFusion server is not running. To stop the ColdFusion server, open the Services control panel, select ColdFusion MX application server, and click Stop.
  6. Add your .class files to the ColdFusion Microsoft application Java stubs file by doing the following:
    1. In the Windows Command prompt, make the parent directory of the directory that contains your class files your working directory. In this example, make c:\src your working director by entering cd .. in the Command prompt from step 4.
    2. Enter the following command:
          jar -uvf cf_root\lib\msapps.jar directoryName\*.class

      Where cf_root is the directory where ColdFusion MX is installed and directoryName is the name of the directory that contains the class files. For the OutlookXP example, enter the following line:

    jar -uvf C:\CFusionMX7\lib\msapps.jar outlookXP\*.class
  7. Update the cf_root /lib/neo-comobjmap.xml file by appending your object definition to the list. The object definition consists of the following lines:
    <var name="progID">
<string>PackageName.mainClass</string>
</var>

    Use the following values in these lines:

    ProgID The COM object’s ProgID, as displayed in the OLE/COM object viewer.

    PackageName The package name you specified in step 3c.

    mainClass The main class of the COM object. The main class contains the methods you invoke. For many Microsoft applications, this class is Application. In general, the largest class file created in step 4. is the main class.

    For example, to add outlookXP to neo-comobjmap.xml, add the lines in bold text above the
    </struct> end tag:

    <var name="access.application.9">
<string>coldfusion.runtime.com.com2java.access2k.Application</string>
</var>
<var name="outlook.application.10">
<string>outlookXP.Application</string>
</var>
</struct>

    In this example, outlook.application.10 is the ProgID of the Outlook COM object, outlookXP is the package name you specified in step 3c, and Application is the COM object’s main class.

  8. Restart the ColdFusion server: Open the Services control panel, select ColdFusion MX application server, and click the Start button.
  9. After you have installed the stubs, you can delete the directory you created in step 2., including all its contents.


Using the Application Scope to improve COM performance

The Java call to create a new COM object instance can take substantial time. As a result, creating COM objects in ColdFusion MX can be substantially slower than in ColdFusion 5. For example, on some systems, creating a Microsoft Word application object could take over one second using ColdFusion MX, while on the same system, the overhead of creating the Word object might be about 200 milliseconds.

Therefore, in ColdFusion MX, you can improve COM performance substantially if you can share a single COM object in the Application scope among all pages.

Use this technique only if the following are true:

  • The COM object does not need to be created for every request or session. (For session-specific objects, consider using the technique described in this section with the Session scope in place of the Application scope.)
  • The COM object is designed for sharing.

Because the object can be accessed from multiple pages and sessions simultaneously, you must also consider the following threading and locking issues:

  • For best performance, the object should be multithreaded. Otherwise, only one request can access the object at a time.
  • Lock the code that accesses and modifies common data. In general, you do not have to lock code that modifies a shared object’s data, including writable properties or file contents, if the data (as opposed to the object) is not shared by multiple requests. However, specific locking needs depend on the COM object’s semantics, interface, and implementation.
  • All cflock tags in the application that use an Application scope lock share one lock. Therefore, code that accesses a frequently used COM object inside an Application scope lock can become a bottleneck and reduce throughput if many users request pages that use the object. You might be able to avoid some contention by putting code that uses the COM object in named locks; you must put the code that creates the object in an Application scope lock.

Note: You can also improve the performance of some COM objects by creating Java stubs, as described in Accessing Complex COM Objects using Java proxies. Using a Java stub does not improve performance as much as sharing the COM object, but the technique works with all COM objects. Also, you must generate Java stubs to correctly access complex COM objects that do not properly make all their features available through the COM IDispatcher interface. Therefore, to get the greatest performance increase and prevent possible problems, use both techniques.

This section includes the following examples:

  • Example 1: Using the FileSystem object
  • Example 2: Using the Microsoft Word application object


Example 1: Using the FileSystem object

The following example uses the Microsoft FileSystem Scripting object in the Application scope. This code creates a user-defined function that returns a structure that consists of the drive letters and free disk space for all hard drives on the system.

<cfapplication name="comtest" clientmanagement="No" Sessionmanagement="yes">

<!--- Uncomment the following line if you must delete the object from the
Application scope during debugging. Then restore the comments.
This technique is faster than stopping and starting the ColdFusion server. --->
 <!--- <cfset structdelete(Application, "fso")> --->

<!--- The getFixedDriveSpace user-defined function returns a structure with
the drive letters as keys and the drive's free space as data for all fixed
drives on a system. The function does not take any arguments --->

<cffunction name="getFixedDriveSpace" returnType="struct" output=True>
    <!--- If the FileSystemObject does not exist in the Application scope,
    create it. --->
    <!--- For information on the use of initialization variables and locking in
        this code, see "Locking application variables efficiently" in Chapter 15,
        "Using Persistent Data and Locking" --->
    <cfset fso_is_initialized = False>
    <cflock scope="application" type="readonly" timeout="120">
        <cfset fso_is_initialized = StructKeyExists(Application, "fso")>
    </cflock>
    <cfif not fso_is_initialized >
        <cflock scope="Application" type="EXCLUSIVE" timeout="120">
            <cfif NOT StructKeyExists(Application, "fso")>
                <cfobject type="COM" action="create" class="Scripting.FileSystemObject"
                    name="Application.fso" server="\\localhost">
            </cfif>
        </cflock>
    </cfif>

    <!--- Get the drives collection and loop through it to populate the
        structure. --->
    <cfset drives=Application.fso.drives()>
    <cfset driveSpace=StructNew()>
    <cfloop collection="#drives#" item="curDrive">
        <!--- A DriveType of 2 indicates a fixed disk --->
        <cfif curDrive.DriveType IS 2>
        <!--- Use dynamic array notation with the drive letter for the struct key
        --->
            <cfset driveSpace["#curDrive.DriveLetter#"]=curDrive.availablespace>
        </cfif>
    </cfloop>
    <cfreturn driveSpace>
</cffunction>

<!--- Test the function. Get the execution time for running the function --->
<cfset start = getTickCount()>
<cfset DriveInfo=getFixedDriveSpace()>
<h3>Getting fixed drive available space</h3>
<cfoutput>Execution Time: #int(getTickCount()-start)# milliseconds</cfoutput><br><br>
<cfdump label="Drive Free Space" var="#driveInfo#">


Example 2: Using the Microsoft Word application object

The following example uses the Microsoft Word application COM object in the Application scope to convert a Word document to HTML. This example works with Word 2000 as written. To work with Word 97, change "Val(8)" to "Val(10)".

This example uses an Application scope lock to ensure that no other page interrupts creating the object. Once the Word object exists, the example uses a named lock to prevent simultaneous access to the file that is being converted.

<cfapplication name="comtest" clientmanagement="No" Sessionmanagement="yes">
<!--- Uncomment the following line if you need to delete the object from the
Application scope --->
<!--- <cfset structdelete(Application, "MyWordObj")> --->

<!--- use the GetTickCount function to get a current time indicator, used for
        displaying the total processing time. --->
<cfset start = GetTickCount()>
<!--- If necessary, create the Word.application object and put it in the
        Application scope --->
<cfset WordObj_is_initialized = False>
<cflock scope="application" type="readonly" timeout=120>
    <cfset WordObj_is_initialized = StructKeyExists(application, "MyWordObj")>
</cflock>
<cfif not WordObj_is_initialized >
    <cflock scope="Application" type="exclusive" timeout="120">
        <cfif not StructKeyExists(application, "MyWordObj")>

<!--- First try to connect to an existing Word object --->
            <cftry>
                <cfobject type="com"
                    action="connect"
                    class="Word.application"
                    name="Application.MyWordobj"
                    context="local">
                <cfcatch>
<!--- There is no existing object, create one --->
                    <cfobject type="com"
                        action="Create"
                        class="Word.application"
                        name="Application.MyWordobj"
                        context="local">
                </cfcatch>
            </cftry>

            <cfset Application.mywordobj.visible = False>
        </cfif>
    </cflock>
</cfif>

<!--- Convert a Word document in temp.doc to an HTML file in temp.htm. --->
<!--- Because this example uses a fixed filename, multiple pages might try
    to use the file simultaneously. The lock ensures that all actions from
    reading the input file through closing the output file are a single "atomic"
    operation, and the next page cannot access the file until the current page
    completes all processing.
    Use a named lock instead of the Application scope lock to reduce lock contention. --->
<cflock name="WordObjLock" type="exclusive" timeout="120">
    <cfset docs = application.mywordobj.documents()>
    <cfset docs.open("c:\CFusionMX7\wwwroot\temp.doc")>
    <cfset converteddoc = application.mywordobj.activedocument>
    <!--- Val(8) works with Word 2000. Use Val(10) for Word 97 --->
    <cfset converteddoc.saveas("c:\CFusionMX7\wwwroot\temp.htm",val(8))>
    <cfset converteddoc.close()>
</cflock>

<cfoutput>
    Conversion of temp.htm Complete<br>
    Execution Time: #int(getTickCount()-start)# milliseconds<br>
</cfoutput>


Getting started with CORBA

The ColdFusion cfobject tag and CreateObject function support CORBA through the Dynamic Invocation Interface (DII). As with COM, the object's type information must be available to ColdFusion. Therefore, an IIOP-compliant Interface Repository (IR) must be running on the network, and the object's Interface Definition Language (IDL) specification must be registered in the IR. If your application uses a naming service to get references to CORBA objects, a naming service must also be running on the network.

ColdFusion loads ORB runtime libraries at startup using a connector, which does not tie ColdFusion customers to a specific ORB vendor. ColdFusion currently includes connectors for the Borland Visibroker 4.5 ORB. The source necessary to write connectors for other ORBs is available under NDA to select third-party candidates and ORB vendors

You must take several steps to configure and enable CORBA access in ColdFusion. For detailed instructions, see Installing and Using ColdFusion MX.

Note: When you enable CORBA access in ColdFusion, one step requires you to start the Interface Repository using an IDL file. This file must contain the IDL for all the CORBA objects that you invoke in ColdFusion applications on the server.


Creating and using CORBA objects

The following sections describe how to create, or instantiate, a CORBA object and how to use it in your ColdFusion application.

  • Creating CORBA objects
  • Using CORBA objects in ColdFusion
  • Handling exceptions

Creating CORBA objects

The cfobject tag and CreateObject functions create in ColdFusion a stub, or proxy object, for the CORBA object on the remote server. You use this stub object to invoke the remote object.

The following table describes the attributes you use in the cfobject tag to create a CORBA object:

Attribute

Description

type

Must be CORBA. COM is the default.

context

Specifies the CORBA binding method, that is, how the object is obtained, as follows:

  • IOR Uses a file containing the object's unique Interoperable Object Reference.
  • NameService Uses a naming service.

class

Specifies the information required for the binding method to access the object.

If you set the context attribute to IOR, The class attribute must be to the full pathname of a file containing the string version of the IOR. ColdFusion must be able to read this IOR file at all times, so make it local to the server or put it on the network in an accessible location.

If you set the context attribute to NameService, The class attribute must be a name delimited by forward slashes (/), such as MyCompany/Department/Dev. You can use period-delimited "kind" identifiers as part of the class attribute; for example, Macromedia.current/Eng.current/CF"

name

Specifies the name (handle) that your application uses to call the object's interface.

locale

(Optional) Identifies the connector configuration. You can omit this option if ColdFusion MX Administrator has only one connector configuration, or if it has multiple connector configurations and you want to use the one that is currently selected in the Administrator. If you specify this attribute, it must be an ORB name you specified in the CORBA Connector ORB Name field when you configured a CORBA connector in ColdFusion MX Administrator; for example, Visibroker.

For example, use the following CFML to invoke a CORBA object specified by the tester.ior file if you configured your ORB name as Visibroker:

<cfobject action = "create" type = "CORBA" context = "IOR"
class = "d:\temp\tester.ior" name = "handle" locale = "Visibroker">

When you use the CreateObject function to invoke this CORBA object, specify the name as the function return variable, and specify the type, class, context, and locale as arguments. For example, the following line creates the same object as the preceding cfobject tag:

handle = CreateObject("CORBA", "d:\temp\tester.ior", "IOR", "Visibroker")

For the complete cfobject and CreateObject syntax, see CFML Reference.

Using a naming service

Currently, ColdFusion can only resolve objects registered in a CORBA 2.3-compliant naming service.

If you use a naming service, make sure that its naming context is identical to the naming context specified in the property file of the Connector configuration in use, as specified in the ColdFusion MX Administrator CORBA Connectors page. The property file must contain the line "SVCnameroot=name" where name is the naming context to be used. The server implementing the object must bind to this context, and register the appropriate name.


Using CORBA objects in ColdFusion

After you create the object, you can invoke attributes and operations on the object using the syntax described in Creating and using objects. The following sections describe the rules for using CORBA objects in ColdFusion pages. They include information on using methods in ColdFusion, which IDL types you can access from ColdFusion, and the ColdFusion data types that correspond to the supported IDL data types.

  • Using CORBA interface methods in ColdFusion
  • Using IDL types with ColdFusion variables

Using CORBA interface methods in ColdFusion

When you use the cfobject tag or the CreateObject function to create a CORBA object, ColdFusion creates a handle to a CORBA interface, which is identified by the cfobject name attribute or the CreateObject function return variable. For example, the following CFML creates a handle named myHandle:

<cfobject action = "create" type = "CORBA" context = "IOR"
class = "d:\temp\tester.ior" name = "myHandle" locale="visibroker">
<cfset myHandle = CreateObject("CORBA", "d:\temp\tester.ior", "IOR", "visibroker")

You use the handle name to invoke all of the interface methods, as in the following CFML:

<cfset ret=myHandle.method(foo)>

The following sections describe how to call CORBA methods correctly in ColdFusion.

Method name case considerations

Method names in IDL are case-sensitive. However, ColdFusion is case-insensitive. Therefore, do not use methods that differ only in case in IDL.

For example, the following IDL method declarations correspond to two different methods:

testCall(in string a); // method #1
TestCall(in string a); // method #2

However, ColdFusion cannot differentiate between the two methods. If you call either method, you cannot be sure which of the two will be invoked.

Passing parameters by value (in parameters)

CORBA in parameters are always passed by value. When calling a CORBA method with a variable in ColdFusion, specify the variable name without quotation marks, as shown in the following example:

IDL | void method(in string a);
CFML | <cfset foo="my string"> <cfset ret=handle.method(foo)>

Passing variables by reference (out and inout parameters)

CORBA out and inout parameters are always passed by reference. As a result, if the CORBA object modifies the value of the variable that you pass when you invoke the method, your ColdFusion page gets the modified value.

To pass a parameter by reference in ColdFusion, specify the variable name in double-quotation marks in the CORBA method. The following example shows an IDL line that defines a method with a string variable, b, that is passed in and out of the method by reference. It also shows CFML that calls this method.

IDL | void method(in string a, inout string b);
CFML | <cfset foo = "My Initial String"> <cfset ret=handle.method(bar, "foo")> <cfoutput>#foo#</cfoutput>

In this case, the ColdFusion variable foo corresponds to the inout parameter b. When the CFML executes, the following happens:

  1. ColdFusion calls the method, passing it the variable by reference.
  2. The CORBA method replaces the value passed in, "My Initial String", with some other value. Because the variable was passed by reference, this modifies the value of the ColdFusion variable.
  3. The cfoutput tag prints the new value of the foo variable.

Using methods with return values

Use CORBA methods that return values as you would any ColdFusion function; for example:

IDL | double method(out double a);
CFML | <cfset foo=3.1415> <cfset ret=handle.method("foo")> <cfoutput>#ret#</cfoutput>


Using IDL types with ColdFusion variables

The following sections describe how ColdFusion supports CORBA data types. They include a table of supported IDL types and information about how ColdFusion converts between CORBA types and ColdFusion data.

IDL support

The following table shows which CORBA IDL types ColdFusion supports, and whether they can be used as parameters or return variables. (NA means not applicable.)

CORBA IDL type | General support | As parameters | As return value
constants | No | No | No
attributes | Yes (for properties) | NA | NA
enum | Yes (as an integer) | Yes | Yes
union | No | No | No
sequence | Yes | Yes | Yes
array | Yes | Yes | Yes
interface | Yes | Yes | Yes
typedef | Yes | NA | NA
struct | Yes | Yes | Yes
module | Yes | NA | NA
exception | Yes | NA | NA
any | No | No | No
boolean | Yes | Yes | Yes
char | Yes | Yes | Yes
wchar | Yes | Yes | Yes
string | Yes | Yes | Yes
wstring | Yes | Yes | Yes
octet | Yes | Yes | Yes
short | Yes | Yes | Yes
long | Yes | Yes | Yes
float | Yes | Yes | Yes
double | Yes | Yes | Yes
unsigned short | Yes | Yes | Yes
unsigned long | Yes | Yes | Yes
longlong | No | No | No
unsigned longlong | No | No | No
void | Yes | NA | Yes

Data type conversion

The following table lists IDL data types and the corresponding ColdFusion data types:

IDL type | ColdFusion type
boolean | Boolean
char | One-character string
wchar | One-character string
string | String
wstring | String
octet | One-character string
short | Integer
long | Integer
float | Real number
double | Real number
unsigned short | Integer
unsigned long | Integer
void | Not applicable (returned as an empty string)
struct | Structure
enum | Integer, where 0 corresponds to the first enumerator in the enum type
array | Array (must match the array size specified in the IDL)
sequence | Array
interface | An object reference
module | Not supported (cannot dereference by module name)
exception | ColdFusion throws an exception of type coldfusion.runtime.corba.CorbaUserException
attribute | Object reference using dot notation

Boolean data considerations

ColdFusion treats any of the following as Boolean values:

True | "yes", "true", or 1
False | "no", "false", or 0

You can use any of these values with CORBA methods that take Boolean parameters, as the following code shows:

IDL

module Tester
    {
    interface TManager
    {
        void testBoolean(in boolean a);
        void testOutBoolean(out boolean a);
        void testInoutBoolean(inout boolean a);
        boolean returnBoolean();
    }
}

CFML

<CFSET handle = CreateObject("CORBA", "d:\temp\tester.ior", "IOR", "") >
<cfset ret = handle.testboolean("yes")>
<cfset mybool = True>
<cfset ret = handle.testoutboolean("mybool")>
<cfoutput>#mybool#</cfoutput>

<cfset mybool = 0>
<cfset ret = handle.testinoutboolean("mybool")>
<cfoutput>#mybool#</cfoutput>

<cfset ret = handle.returnboolean()>
<cfoutput>#ret#</cfoutput>

Struct data type considerations

For IDL struct types, use ColdFusion structures. You can prevent errors by using the same case for structure key names in ColdFusion as you do for the corresponding IDL struct field names.

Enum type considersations

ColdFusion treats the enum IDL type as an integer with the index starting at 0. As a result, the first enumerator corresponds to 0, the second to 1, and so on. In the following example, the IDL enumerator a corresponds to 0, b to 1 and c to 2:

IDL

module Tester
{
    enum EnumType {a, b, c};
    interface TManager
    {
        void testEnum(in EnumType a);
        void testOutEnum(out EnumType a);
        void testInoutEnum(inout EnumType a);
        EnumType returnEnum();
    }
}

CFML

<CFSET handle = CreateObject("CORBA", "d:\temp\tester.ior", "IOR", "") >
<cfset ret = handle.testEnum(1)>

In this example, the CORBA object gets called with the second (not first) entry in the enumerator, a.

Double-byte character considerations

If you are using an ORB that supports CORBA later than version 2.0, you do not have to do anything to support double-byte characters. Strings and characters in ColdFusion will appropriately convert to wstring and wchar when they are used. However, the CORBA 2.0 IDL specification does not support the wchar and wstring types, and uses the 8-bit Latin-1 character set to represent string data. In this case, you cannot pass parameters containing those characters, however, you can call parameters with char and string types using ColdFusion string data.


Handling exceptions

Use the cftry and cfcatch tags to catch CORBA object method exceptions thrown by the remote server, as follows:

  1. Specify type="coldfusion.runtime.corba.CorbaUserException" in the cfcatch tag to catch CORBA exceptions.
  2. Use the cfcatch.getContents method to get the contents of the exception object.

The cfcatch.getContents method returns a ColdFusion structure containing the data specified by the IDL for the exception.

The following code example shows the IDL for a CORBA object that raises an exception defined by the PrimitiveException exception type definition, and the CFML that catches the exception and displays the contents of the object.

IDL

interface myInterface
{
    exception PrimitiveException
    {
        long l;
        string s;
        float f;
    };
    void testPrimitiveException() raises (PrimitiveException);
}

CFML

<cftry>
    <cfset ret0 = handle.testPrimitiveException()>
    <cfcatch type=coldfusion.runtime.corba.CorbaUserException>
        <cfset exceptStruct= cfcatch.getContents()>
        <cfdump var ="#exceptStruct#">
    </cfcatch>
</cftry>


CORBA example

The following code shows an example of using a LoanAnalyzer CORBA object. This simplified object determines whether an applicant is approved for a loan based on the information that is supplied.

The LoanAnalyzer CORBA interface has one method, which takes the following two in arguments:

  • An Account struct that identifies the applicant’s account. It includes a Person struct that represents the account holder, and the applicant’s age and income.
  • A CreditCards sequence, which corresponds to the set of credit cards the user currently has. The credit card type is represented by a member of the CardType enumerator. (This example assumes the applicant has no more than one of any type of card.)

The object returns a Boolean value indicating whether the application is accepted or rejected.

The CFML does the following:

  1. Initializes the values of the ColdFusion variables that are used in the object method. In a more complete example, the information would come from a form, query, or both.

    The code for the Person and Account structs is straightforward. The cards variable, which represents the applicant’s credit cards, is more complex. The interface IDL uses a sequence of enumerators to represent the cards. ColdFusion represents an IDL sequence as an array, and an enumerator as 0-indexed number indicating the position of the selected item among the items in the enumerator type definition.

    In this case, the applicant has a Master Card, a Visa card, and a Diners card. Because Master Card (MC) is the first entry in the enumerator type definition, it is represented in ColdFusion by the number 0. Visa is the third entry, so it is represented by 2. Diners is the fifth entry, so it is represented by 4. These numbers must be put in an array to represent the sequence, resulting in a three-element, one-dimensional array containing 0, 2, and 4.

  2. Instantiates the CORBA object.
  3. Calls the approve method of the CORBA object and gets the result in the return variable, ret.
  4. Displays the value of the ret variable, Yes or No.

    IDL

    struct Person
{
    long pid;
    string name;
    string middle;
    string last_name;
}

struct Account
{
    Person person;
    short age;
    double income;
}

double loanAmountl
enum cardType {AMEX, VISA, MC, DISCOVER, DINERS};

typedef sequence<cardType> CreditCards;

interface LoanAnalyzer
{
    boolean approve( in Account, in CreditCards);
}

    CFML

    <!--- Declare a "person" struct ---->
<cfset p = StructNew()>
<cfif IsStruct(p)>
    <cfset p.pid = 1003232>
    <cfset p.name = "Eduardo">
    <cfset p.middle = "R">
    <cfset p.last_name = "Doe">
</cfif>

<!---- Declare an "Account" struct --->
<cfset a = StructNew()>
<cfif IsStruct(a)>
    <cfset a.person = p>
    <cfset a.age = 34>
    <cfset a.income = 150120.50>
</cfif>

<!----- Declare a "CreditCards" sequence --->
<cfset cards = ArrayNew(1)>
<cfset cards[1] = 0>   <!--- corresponds to Amex --->
<cfset cards[2] = 2>   <!--- corresponds to MC --->
<cfset cards[3] = 4>   <!--- corresponds to Diners --->

<!---- Creating a CORBA handle using the Naming Service---->
<cfset handle = CreateObject("CORBA", "FirstBostonBank/MA/Loans",
"NameService") >

<cfset ret=handle.approve(a, cards)>
<cfoutput>Account approval: #ret#</cfoutput>

Previous


Sending and Receiving E-Mail

You can add interactive e-mail features to your ColdFusion applications using the cfmail and cfpop tags. This complete two-way interface to mail servers makes the Macromedia ColdFusion MX e-mail capability a vital link to your users.

Contents

Using ColdFusion with mail servers

Sending e-mail messages

Sample uses of the cfmail tag

Using the cfmailparam tag

Receiving e-mail messages

Handling POP mail
Next


Using ColdFusion with mail servers

Adding e-mail to your ColdFusion applications lets you respond automatically to user requests. You can use e-mail in your ColdFusion applications in many different ways, including the following:

  • Trigger e-mail messages based on users’ requests or orders.
  • Allow users to request and receive additional information or documents through e-mail.
  • Confirm customer information based on order entries or updates.
  • Send invoices or reminders, using information pulled from database queries.

ColdFusion offers several ways to integrate e-mail into your applications. To send e-mail, you generally use the Simple Mail Transfer Protocol (SMTP). To receive e-mail, you use the Post Office Protocol (POP) to retrieve e-mail from the mail server. To use e-mail messaging in your ColdFusion applications, you must have access to an SMTP server and/or a valid POP account.

In your ColdFusion application pages, you use the cfmail and cfpop tags to send and receive e-mail, respectively. The following sections describe how to use the ColdFusion e-mail features and show examples of these tags.


How ColdFusion sends mail

The ColdFusion implementation of SMTP mail uses a spooled architecture. If you select to spool mail on the Mail page in the ColdFusion MX Administrator, when an application page processes a cfmail tag, the messages that are generated are not sent immediately. Instead, they are spooled to disk and processed in the background. This architecture has two advantages:

  • End users of your application are not required to wait for SMTP processing to complete before a page returns to them. This design is especially useful when a user action causes more than a handful of messages to be sent.
  • Messages sent using cfmail are delivered reliably, even in the presence of unanticipated events like power outages or server crashes.

You can set how frequently ColdFusion MX checks for spooled mail messages on the Mail page in the ColdFusion MX Administrator. If ColdFusion is extremely busy or has a large existing queue of messages, however, delivery can occur after the spool interval.

Some ColdFusion MX editions have advanced spooling options that let you fine tune how ColdFusion sends mail. For more information, see Configuring and Administering ColdFusion MX.

Error logging and undelivered messages

ColdFusion logs all errors that occur during SMTP message processing to the file mail.log in the ColdFusion log directory. The log entries contain the date and time of the error as well as diagnostic information about why the error occurred.

If a message is not delivered because of an error, ColdFusion writes it to this directory:

  • In Windows: \CFusionMX7\Mail\Undelivr
  • On UNIX: /opt/coldfusionmx7/mail/undelivr

The error log entry that corresponds to the undelivered message contains the name of the file written to the UnDelivr (or undelivr) directory.

Note: To have ColdFusion try to resend a message that it could not deliver, move the message file from the Undelivr directory to the Spool directory.

For more information about the mail logging settings in the ColdFusion MX Administrator, see Configuring and Administering ColdFusion MX.


Sending e-mail messages

Before you configure ColdFusion to send e-mail messages, you must have access to an SMTP e-mail server. Also, before you run application pages that refer to the e-mail server, you can configure the ColdFusion MX Administrator to use the SMTP server. If you need to override the ColdFusion MX Administrator SMTP server setting for any messages, you can specify a new mail server in the server attribute of the cfmail tag.

To configure ColdFusion for e-mail:

  1. In the ColdFusion MX Administrator, select Server Settings > Mail.
  2. In the Mail Server box, enter the name or IP address of your SMTP mail server.
  3. (Optional) Change the Server Port and Connection Timeout default settings.
  4. Select the Verify Mail Server Connection check box to make sure ColdFusion can access your mail server.
  5. If your mail server does not use port 25, the default, SMTP port, change the Server Port default settings.
  6. Depending on your ColdFusion MX edition, the Mail page in the Administrator has additional options that you can use to configure and optimize ColdFusion mail behavior. Select these as appropriate.
  7. Click Submit Changes.

    ColdFusion saves the settings. The page displays a message indicating success or failure for connecting to the server.

ColdFusion MX Enterprise edition includes additional mail spooling and delivery features. For more information on these features, and for information on the Administrator’s mail settings, see Configuring and Administering ColdFusion MX.

Sending SMTP e-mail with the cfmail tag

The cfmail tag provides support for sending SMTP e-mail from within ColdFusion applications. The cfmail tag is similar to the cfoutput tag, except that cfmail outputs the generated text as an SMTP mail message rather than to a page. The cfmail tag supports all the attributes and commands that you use with cfoutput, including query. The following table describes basic cfmail tag attributes that you might use to send a simple email message. For a complete list of attributes, see the cfmail description in CFML Reference.

Attribute | Description
subject | The subject of the message.
from | The e-mail address of the sender.
to | The e-mail address of the recipient. Use a comma-delimited list to specify multiple recipients.
cc | (Optional) The e-mail address of a carbon copy recipient. The recipient’s address is visible to other recipients. Use a comma-delimited list to specify multiple cc recipients.
bcc | (Optional) The e-mail address of a blind carbon copy recipient. The recipient’s address is not visible to other recipients. Use a comma-delimited list to specify multiple bcc recipients.

To send a simple e-mail message:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Sending a simple e-mail</title>
</head>
<body>
<h1>Sample e-mail</h1>
<cfmail
    from="Sender@Company.com"
    to="#URL.email#"
    subject="Sample e-mail from ColdFusion MX">

This is a sample e-mail message to show basic e-mail capability.

</cfmail>
The e-mail was sent.

</body>
</html>
  2. Save the file as send_mail.cfm in the myapps directory under your web_root directory.
  3. Open your browser and enter the following URL:

    http://localhost:8500/myapps/send_mail.cfm?email=myname@mycompany.com

    (Replace myname@mycompany.com with your e-mail address.)

    The page sends the e-mail message to you, through your SMTP server.

Note: If you do not receive an e-mail message, check whether you have configured ColdFusion to work with your SMTP server; for more information, see Sending e-mail messages.

The cfmail tag has many options that let you customize your mail or control how it is sent. For a description of all attributes, including options to wrap mail text at a specified column, specify the mail character encoding, and specify the mail server, user name, and password, see the cfmail description in CFML Reference.

Sending HTML format e-mail

If you know all the mail recipients use mail applications that are capable of reading and interpreting HTML code in a mail message, you can use the cfmail tag to send an HTML message. The cfmail tag type="HTML" attribute informs the receiving e-mail client that the message contains embedded HTML tags that must be processed. For an example that sends HTML mail, see Including images in a message.

Sending multipart mail messages

The cfmailpart tag lets you create multipart mail messages, with each part having a different MIME type or character set. For example, if you do not know that all recipients can interpret HTML mail messages, you can send your message as a multipart mail with a text part and an HTML part. To do so use two cfmailpart tags, one with the HTML version of the message and one with the plain text message, as shown in the following example. To test this example, replace the To attribute value with a valid email address, save and run the page, and check the incoming email at the address you entered.

<cfmail from = "peter@domain.com" To = "paul@domain.com"
Subject = "Which version do you see?">
    <cfmailpart
        type="text"
        wraptext="74">
            You are reading this message as plain text, because your mail reader
            does not handle HTML text.
    </cfmailpart>>
    <cfmailpart
        type="html">
            <h3>HTML Mail Message</h3>
            <p>You are reading this message as <strong>HTML</strong>.</p>
            <p>Your mail reader handles HTML text.</p>
    </cfmailpart>
</cfmail>

Note: In the HTML version of the message, you must escape any number signs, such as those used to specify colors, by using two # characters; for example, bgcolor="##C5D9E5".


Sample uses of the cfmail tag

An application page containing the cfmail tag dynamically generates e-mail messages based on the tag’s settings. The following sections show some of the tasks that you can accomplish with cfmail:

  • Sending a mail message in which the data the user enters in an HTML form determine the recipient and contents
  • Using a query to send a mail message to a database-driven list of recipients
  • Using a query to send a customized mail message, such as a billing statement, to a list of recipients that is dynamically populated from a database

This section describes the following topics:

  • Sending form-based e-mail
  • Sending query-based e-mail
  • Sending e-mail to multiple recipients


Sending form-based e-mail

In the following example, the contents of a customer inquiry form submittal are forwarded to the marketing department. You could also use the same application page to insert the customer inquiry into the database. You include the following code on your form so that it executes when users enter their information and submit the form:

<cfmail
    from="#Form.EMailAddress#"
    to="marketing@MyCompany.com,sales@MyCompany.com"
    subject="Customer Inquiry">

A customer inquiry was posted to our web site:

Name: #Form.FirstName# #Form.LastName#
Subject: #Form.Subject#

#Form.InquiryText#
</cfmail>


Sending query-based e-mail

In the following example, a query (ProductRequests) retrieves a list of the customers who inquired about a product during the previous seven days. ColdFusion sends the list, with an appropriate header and footer, to the marketing department:

<cfmail
    query="ProductRequests"
    from="webmaster@MyCompany.com"
    to="marketing@MyCompany.com"
    subject="Widget status report">

Here is a list of people who have inquired about
MyCompany Widgets during the previous seven days:

<cfoutput>
#ProductRequests.FirstName# #ProductRequests.LastName# (#ProductRequests.Company#) - #ProductRequests.EMailAddress#&##013;
</cfoutput>

Regards,
The WebMaster
webmaster@MyCompany.com

</cfmail>

Reviewing the code

The following table describes the code:

Code

Description

<cfoutput>
#ProductRequests.FirstName#
#ProductRequests.LastName#
(#ProductRequests.Company#) -
#ProductRequests.EMailAddress#&##013;
</cfoutput>

Presents a dynamic list embedded within a normal cfmail message, repeating for each row in the ProductRequests query. Because the cfmail tag specifies a query, the cfoutput tag does not use a query attribute. The &##013; forces a carriage return between output records.


Sending e-mail to multiple recipients

In addition to simply using a comma-delimited list in the to attribute of the cfmail tag, you can send e-mail to multiple recipients by using the query attribute of the cfmail tag. The following examples show how you can send the same message to multiple recipients and how you can a customize each message for the recipient.

Sending a simple message to multiple recipients

In the following example, a query (BetaTesters) retrieves a list of people who are beta testing ColdFusion. This query then notifies each beta tester that a new release is available. The contents of the cfmail tag body are not dynamic. What is dynamic is the list of e-mail addresses to which the message is sent. Using the variable #TesterEMail#, which refers to the TesterEmail column in the Betas table, in the to attribute, enables the dynamic list:

<cfquery name="BetaTesters" datasource="myDSN">
    SELECT * FROM BETAS
</cfquery>

<cfmail query="BetaTesters"
    from="beta@MyCompany.com"
    to="#BetaTesters.TesterEMail#"
    subject="Widget Beta Four Available">

To all Widget beta testers:

Widget Beta Four is now available
for downloading from the MyCompany site.
The URL for the download is:

http://beta.mycompany.com

Regards,
Widget Technical Support
beta@MyCompany.com

</cfmail>

Customizing e-mail for multiple recipients

In the following example, a query (GetCustomers) retrieves the contact information for a list of customers. The query then sends an e-mail to each customer to verify that the contact information is still valid:

<cfquery name="GetCustomers" datasource="myDSN">
    SELECT * FROM Customers
</cfquery>

<cfmail query="GetCustomers"
    from="service@MyCompany.com"
    to="#GetCustomers.EMail#"
    subject="Contact Info Verification">

Dear #GetCustomers.FirstName# -

We'd like to verify that our customer
database has the most up-to-date contact
information for your firm. Our current
information is as follows:

Company Name: #GetCustomers.Company#
Contact: #GetCustomers.FirstName# #GetCustomers.LastName#

Address:
    #GetCustomers.Address1#
    #GetCustomers.Address2#
    #GetCustomers.City#, #GetCustomers.State# #GetCustomers.Zip#

Phone: #GetCustomers.Phone#
Fax: #GetCustomers.Fax#
Home Page: #GetCustomers.HomePageURL#

Please let us know if any of the above
information has changed, or if we need to
get in touch with someone else in your
organization regarding this request.

Thanks,
Customer Service
service@MyCompany.com

</cfmail>

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfquery name="GetCustomers"
datasource="myDSN">
    SELECT * FROM Customers
</cfquery>

Retrieves all data from the Customers table into a query named GetCustomers.

<cfmail query="GetCustomers"
    from="service@MyCompany.com"
    to="#GetCustomers.EMail#"
    subject="Contact Info
Verification">

Uses the to attribute of cfmail, the #GetCustomers.Email# query column causes one message to be sent to the address listed in each row of the query. Therefore, the mail body does not use a cfoutput tag.

Dear #GetCustomers.FirstName#
...
Company Name: #GetCustomers.Company#
Contact: #GetCustomers.FirstName#
#GetCustomers.LastName#

Address:
    #GetCustomers.Address1#
    #GetCustomers.Address2#
    #GetCustomers.City#,
#GetCustomers.State#
#GetCustomers.Zip#

Phone: #GetCustomers.Phone#
Fax: #GetCustomers.Fax#
Home Page: #GetCustomers.HomePageURL#

Uses other query columns (#GetCustomers.FirstName#, #GetCustomers.LastName#, and so on) within the cfmail section to customize the contents of the message for each recipient.


Using the cfmailparam tag

You use the cfmailparam tag to include files in your message or add a custom header to an e-mail message. You can send files as attachments or display them inline in the message. You nest the cfmailparam tag within the cfmail tag.

Attaching files to a message

You can use one cfmailparam tag for each attachment, as the following example shows:

<cfmail from="daniel@MyCompany.com"
    to="jacob@YourCompany.com"
    subject="Requested Files">

Jake,

Here are the files you requested.

Regards,
Dan

<cfmailparam file="c:\widget_launch\photo_01.jpg">
<cfmailparam file="c:\widget_launch\press_release.doc">

</cfmail>

You must use a fully qualified system path for the file attribute of cfmailparam. The file must be located on a drive on the ColdFusion server machine (or a location on the local network), not the browser machine.

Including images in a message

You can use the cfmailparam to include images from other files in an HTML message, as follows:

  1. Put a cfmailparam tag for each image following the cfmail start tag.
  2. In each cfmailparam tag, do the following
    • Set the file attribute to the location of the image.
    • Specify disposition="inline"
    • Set the contentID attribute to a unique identifier; for example, myImage1.
  3. In the location in your HTML where you want the message included, use an img tag such as the following:
    <img src="cid:myImage1">

The following example shows a simple mail message with an inline image. In this case, the image is located between paragraphs, but you could include it directly inline with the text. To test this example, replace the cfmail to parameter with a valid email address and change the file parameter to the path to a valid image.

<cfmail type="HTML"
        to = "Peter@myCo.com"
        from = "Paul@AnotherCo.com"
        subject = "Sample inline image">
    <cfmailparam file="C:\Inetpub\wwwroot\web.gif"
        disposition="inline"
        contentID="image1">
    <P>There should be an image here</p>
    <img src="cid:image1">
    <p> This text follows the picture</p>
</cfmail>

Adding a custom header to a message

When the recipient of an e-mail message replies to the message, the reply is sent, by default, to the address specified in the From field of the original message. You can use cfmailparam to provide a Reply-To e-mail address that tells the mail client to override the value in the From field. Using cfmailparam, the reply to the following example is addressed to widget_master@YourCompany.com:

<cfmail from="jacob@YourCompany.com"
    to="daniel@MyCompany.com"
    subject="Requested Files">
<cfmailparam name="Reply-To" value="widget_master@YourCompany.com">

Dan,
Thanks very much for the sending the widget press release and graphic.
I’m now the company’s Widget Master and am accepting e-mail at
widget_master@YourCompany.com.

See you at Widget World 2002!

Jake
</cfmail>

Note: You can combine the two uses of cfmailparam within the same ColdFusion page. Write a separate cfmailparam tag for each header and for each attached file.


Receiving e-mail messages

You create ColdFusion pages to access a Post Office Protocol (POP) server to retrieve e-mail message information. ColdFusion can then display the messages (or just header information), write information to a database, or perform other actions.

The cfpop tag lets you add Internet mail client features and e-mail consolidation to applications. Although a conventional mail client provides an adequate interface for personal mail, there are many cases in which an alternative interface to some mailboxes is advantageous. You use cfpop to develop targeted mail clients to suit the specific needs of a wide range of applications. The cfpop tag does not work with the other major e-mail protocol, Internet Mail Access Protocol (IMAP).

Here are three instances in which implementing POP mail makes sense:

  • If your site has generic mailboxes that are read by more than one person (sales@yourcompany.com), it can be more efficient to construct a ColdFusion mail front end to supplement individual user mail clients.
  • In many applications, you can automate mail processing when the mail is formatted to serve a particular purpose; for example, when subscribing to a list server.
  • If you want to save e-mail messages to a database.

Using cfpop with your POP server is like running a query on your mailbox contents. You set its action attribute to retrieve either headers (using the GetHeaderOnly value) or entire messages (using the GetAll value) and assign it a name value. You use the name to refer to the record set that cfpop returns, for example, when using cfoutput. To access a POP server, you also must define the server, username, and password attributes.

Note: If the cfpop tag encounters an error, such as an improperly formatted email message, when retrieving messages, it tries to ignore the error; it returns empty fields in the result structure and retrieves any available messages.

For more information on cfpop syntax and variables, see CFML Reference.

Using the cfpop tag

Use the following steps to add POP mail to your application.

To implement the cfpop tag in your application:

  1. Choose the mailboxes to access within your ColdFusion application.
  2. Determine which mail message components you must process: message header, message body, attachments, and so on.
  3. Decide whether you must store the retrieved messages in a database.
  4. Decide whether you must delete messages from the POP server after you retrieve them.
  5. Incorporate the cfpop tag in your application and create a user interface for accessing a mailbox.
  6. Build an application page to handle the output. Retrieved messages can include characters that do not display properly in the browser.

You use the cfoutput tag with the HTMLCodeFormat and HTMLEditFormat functions to control output to the browser. These functions convert characters with special meanings in HTML, such as the less than (<), greater than (>), and ampersand (&) symbols, into HTML-escaped characters, such as &lt;, &gt;, and &amp;. The HTMLCodeFormat tag also surrounds the text in a pre tag block.

The cfpop query variables

Like any ColdFusion query, each cfpop query returns variables that provide information about the record:

RecordCount The total number of records returned by the query.

ColumnList A list of the headings of the columns that are returned by the query

CurrentRow The current row of the query being processed by cfoutput or cfloop in a query-driven loop.

The query includes one variable that is not returned by the cfquery tag: the UID variable contains the unique identifier of the e-mail message file.

You can reference these properties in a cfoutput tag by prefixing the query variable with the query name in the name attribute of cfpop:

<cfoutput>
This operation returned #Sample.RecordCount# messages.
</cfoutput>


Handling POP mail

This section describes how to specify the message or messages that you want to get (or get information about) and provides an example of each of the following uses of POP mail:

  • Retrieving message headers
  • Retrieving messages
  • Retrieving messages and attachments
  • Deleting messages

Specifying the message or messages

For all cfpop actions, you can tel the tag to perform the action on all messages, or to do it on selected messages. To operate on all messages, for example to get all message headers, do not specify a messageNumber or UID attribute. To operate on specific messages, for example, to delete three selected messages, specify a messageNumber or UID attribute with a comma-delimited list of messages to act on.


Retrieving message headers

To retrieve message headers without getting the messages, specify action="GetHeaderOnly" in the cfpop tag. Whether you use cfpop to retrieve the header or the entire message, ColdFusion returns a query object that contains one row for each message in the specified mailbox. you specify the query object name in the cfpop tag name attribute. The query has the following fields:

  • date
  • from
  • header (A string with all the mail header fields, including those that have separate fields in the query object)
  • messageNumber (The sequential number of the message in the POP server; identical to the row number of the entry in the query object)
  • messageID (The mail header Message-ID field)
  • replyTo
  • subject
  • cc
  • to
  • UID (The mail header X-UID field)

The cfpop tag with the getHeaderOnly attribute retrieves any file attachments if you specify an attachmentPath attribute; otherwise, it does not get the attachments, and the attachmentfiles column contains empty strings.

To retrieve only the message header:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>POP Mail Message Header Example</title>
</head>

<body>
<h2>This example retrieves message header information:</h2>

<cfpop server="mail.company.com"
    username=#myusername#
    password=#mypassword#
    action="GetHeaderOnly"
    name="Sample">

<cfoutput query="Sample">
    MessageNumber: #HTMLEditFormat(Sample.messageNumber)# <br>
    To: #HTMLEditFormat(Sample.to)# <br>
    From: #HTMLEditFormat(Sample.from)# <br>
    Subject: #HTMLEditFormat(Sample.subject)# <br>
    Date: #HTMLEditFormat(Sample.date)#<br>
     Cc: #HTMLEditFormat(Sample.cc)# <br>
    ReplyTo: #HTMLEditFormat(Sample.replyTo)# <br><br>
</cfoutput>

</body>
</html>
  2. Edit the following lines so that they refer to valid values for your POP mail server, username, and password:
    <cfpop server="mail.company.com"
    username=#myusername#
    password=#mypassword#
  3. Save the file as header_only.cfm in the myapps directory under your web_root and view it in your web browser:

    This code retrieves the message headers and stores them in a cfpop record set called Sample. For more information about working with record set data, see Using Query of Queries.

The ColdFusion function HTMLEditFormat replaces characters that have meaning in HTML, such as the less than (<) and greater than (>) signs that can surround detailed e-mail address information, with escaped characters such as &lt; and &gt;.

In addition, you can process the date returned by cfpop with ParseDateTime, which accepts an argument for converting POP date/time objects into a CFML date-time object.

You can reference any of these columns in a cfoutput tag, as the following example shows:

<cfoutput>
    #ParseDateTime(queryname.date, "POP")#
    #HTMLCodeFormat(queryname.from)#
    #HTMLCodeFormat(queryname.messageNumber)#
</cfoutput>

For information on these ColdFusion functions, see CFML Reference.


Retrieving messages

When you use the cfpop tag with action="GetAll", ColdFusion returns the same columns as with getheaderonly, plus the following additional columns:

  • attachments (A tab-delimited list of attachment file names)
  • attachmentfiles (A tab-delimited list of paths to the attachment files retrieved to the local server, if any. You get the files only if you specify an attachmentpath attribute.)
  • body
  • htmlbody
  • textbody

If the message is multipart, the htmlbody and textbody fields contain the contents of the HTML and plain text parts, and the body field has the first part in the message. If the message has only one part, the body contains the message, and either the htmlbody or textbody field, depending on the message type, also has a copy of the message.

To retrieve entire messages:

  1. Create a ColdFusion page with the following content:
    <html>
<head><title>POP Mail Message Body Example</title></head>

<body>
<h2>This example adds retrieval of the message body:</h2>
<cfpop server="mail.company.com"
    username=#myusername#
    password=#mypassword#
    action="GetAll"
    name="Sample">

<cfoutput query="Sample">
    MessageNumber: #HTMLEditFormat(Sample.messageNumber)# <br>
    To: #Sample.to# <br>
    From: #HTMLEditFormat(Sample.from)# <br>
    Subject: #HTMLEditFormat(Sample.subject)# <br>
    Date: #HTMLEditFormat(Sample.date)#<br>
    Cc: #HTMLEditFormat(Sample.cc)# <br>
    ReplyTo: #HTMLEditFormat(Sample.replyTo)# <br>
    <br>
    Body:<br>
    #Sample.body#<br>
    <br>
    Header:<br>
    #HTMLCodeFormat(Sample.header)#<br>
    <hr>
    </cfoutput>

</body>

</html>
  1. Edit the following lines so that they refer to valid values for your POP mail server, username, and password:
    <cfpop server="mail.company.com"
    username=#myusername#
    password=#mypassword#
  2. Save the file as header_body.cfm in the myapps directory under your web_root and view it in your web browser:

This example does not use a CFML function to encode the body contents. As a result, the browser displays the formatted message as you would normally see it in a mail program that supports HTML messages.


Retrieving messages and attachments

When you use the cfpop tag with an attachmentpath attribute to specify the directory in which to store attachments, ColdFusion retrieves any attachment files from the POP server and saves them in the specified directory. The cfpop tag fills the attachmentfiles field with a tab-separated list of the locations of the attachment files. Use the cffile tag to delete these temporary files when they are no longer needed. ColdFusion MX creates the directory if it does not exist. (ColdFusion MX must have the appropriate rights on the system to create the directory.)

If a message has no attachments, the attachments and attachmentfiles columns contain empty strings.

Note: CFML does not provide a way to change the name of a mail attachment returned by cfpop before it tries to save the file. If the attachment name is invalid for the file system on which ColdFusion is running, the attachment cannot be saved.

To retrieve all parts of a message, including attachments:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>POP Mail Message Attachment Example</title>
</head>

<body>
<h2>This example retrieves message header,
body, and all attachments:</h2>

<cfpop server="mail.company.com"
    username=#myusername#
    password=#mypassword#
    action="GetAll"
    attachmentpath="c:\temp\attachments"
    name="Sample">

<cfoutput query="Sample">
    MessageNumber: #HTMLEditFormat(Sample.MessageNumber)# <br>
    To: #HTMLEditFormat(Sample.to)# <br>
    From: #HTMLEditFormat(Sample.from)# <br>
    Subject: #HTMLEditFormat(Sample.subject)# <br>
    Date: #HTMLEditFormat(Sample.date)# <br>
    Cc: #HTMLEditFormat(Sample.cc)# <br>
    ReplyTo: #HTMLEditFormat(Sample.ReplyTo)# <br>
    Attachments: #HTMLEditFormat(Sample.Attachments)# <br>
    Attachment Files: #HTMLEditFormat(Sample.AttachmentFiles)# <br>
    <br>
    Body:<br>
    #Sample.body# <br>
    <br>
    Header:<br>
    HTMLCodeFormat(Sample.header)# <br>
    <hr>
</cfoutput>

</body>
</html>
  2. Edit the following lines so that they refer to valid values for your POP mail server, username, and password:
    <cfpop server="mail.company.com"
    username=#myusername#
    password=#mypassword#
  3. Save the file as header_body_att.cfm in the myapps directory under your web_root and view it in your web browser:

Note: To avoid duplicate filenames when saving attachments, set the generateUniqueFilenames attribute of cfpop to Yes.


Deleting messages

Using the cfpop tag to delete a message permanently removes it from the server. By default, retrieved messages remain on the POP mail server. To delete the messages, set the action attribute of the cfpop tag to Delete. Specify use the messagenumber attribute to specify the messages to delete; omit the attribute to delete all the user’s messages from the server.

Note: Message numbers are reassigned at the end of every POP mail server communication that contains a delete action. For example, if you retrieve four messages from a POP mail server, the server returns the message numbers 1,2,3,4. If you delete messages 1 and 2 with a single cfpop tag, messages 3 and 4 are assigned message numbers 1 and 2, respectively.

To delete messages:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
<title>POP Mail Message Delete Example</title>
</head>

<body>
<h2>This example deletes messages:</h2>

<cfpop server="mail.company.com"
    username=#username#
    password=#password#
    action="Delete"
    messagenumber="1,2,3">

</body>
</html>
  2. Edit the following lines so that they refer to valid values for your POP mail server, username, and password:
    <cfpop server="mail.company.com"
    username=#username#
    password=#password#
  3. Save the file as message_delete.cfm in the myapps directory under your web_root and view the file in your web browser.
  4. Run the header_only.cfm page that you created to confirm that the messages have been deleted.

    Caution: When you view this page in your web browser, ColdFusion immediately deletes the messages from the POP server.
Previous


Interacting with Remote Servers

This chapter describes how Macromedia ColdFusion MX wraps the complexity of Hypertext Transfer Protocol (HTTP) and File Transfer Protocol (FTP) communications in a simplified tag syntax that lets you extend your site’s offerings across the web.

Contents

About interacting with remote servers

Using cfhttp to interact with the web

Creating a query object from a text file

Using the cfhttp Post method

Performing file operations with cfftp
Next


About interacting with remote servers

Transfer protocols are mechanisms for moving files and information from a source to one or more destinations. Two of the more popular protocols are the Hypertext Transfer Protocol (HTTP) and the File Transfer Protocol (FTP). ColdFusion has the cfhttp and cfftp tags that let you use these protocols to interact with remote servers.

The cfhttp tag lets you receive a web page or web-based file, just as a web browser uses HTTP to transport web pages. When you type a URL into a web browser, you make an HTTP request to a web server. With the cfhttp tag, you can display a web page, send variables to a ColdFusion or CGI application, retrieve specialized content from a web page, and create a ColdFusion query from a text file. You can use the Get or Post methods to interact with remote servers.

The cfftp tag takes advantage of FTP’s main purpose--transporting files. Unlike HTTP, FTP was not designed to interact with other servers for processing and interacting with data. After you establish an FTP connection with the cfftp tag, you can use it to upload, download, and manage files and directories.


Using cfhttp to interact with the web

The cfhttp tag, which lets you retrieve information from a remote server, is one of the more powerful tags in the CFML tag set. You can use one of two methods--Get or Post--to interact with a remote server using the cfhttp tag:

  • Using the Get method, you can only send information to the remote server in the URL. This method is often used for a one-way transaction in which cfhttp retrieves an object.
  • Using the Post method, you can pass variables to a ColdFusion page or CGI program, which processes them and returns data to the calling page. The calling page then appears or further processes the data that was received. For example, when you use cfhttp to Post to another ColdFusion page, that page does not appear. It processes the request and returns the results to the original ColdFusion page, which then uses the information as appropriate.

Using the cfhttp Get method

You use Get to retrieve files, including text and binary files, from a specified server. The retrieved information is stored in a special variable, cfhttp.fileContent. The following examples show several common Get operations.

To retrieve a file and store it in a variable:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Use Get Method</title>
</head>
<body>
<cfhttp
    method="Get"
    url="http://www.macromedia.com"
    resolveurl="Yes">
<cfoutput>
    #cfhttp.FileContent# <br>
</cfoutput>

</body>
</html>
  2. (Optional) Replace the value of the url attribute with another URL.
  3. Save the file as get_webpage.cfm in the myapps directory under your web_root and view it in the web browser.

    The browser loads the web page specified in the url attribute.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfhttp method="Get"
   url="http://www.macromedia.com"
   resolveurl="Yes">

Get the page specified in the URL and make the links absolute instead of relative so that they appear properly.

<cfoutput>
    #cfhttp.FileContent# <br>
</cfoutput>

Display the page, which is stored in the variable cfhttp.fileContent, in the browser.

To get a web page and save it in a file:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Use Get Method</title>
</head>
<body>

<cfhttp
    method = "Get"
    url="http://www.macromedia.com/software"
    path="c:\temp"
    file="macr_software.htm">
</body>
</html>
  2. (Optional) Replace the value of the url attribute with another URL and change the filename.
  3. (Optional) Change the path from C:\temp to a path on your hard drive.
  4. Save the page as save_webpage.cfm in the myapps directory under your web_root directory.
  5. Go to the specified path and view the file that you specified in a text editor (using the values specified in step 1, this is C:\temp\macr_software.htm).

    The saved file does not appear properly in your browser because the Get operation saves only the specified web page HTML. It does not save the frame, image, or other files that the page might include.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfhttp
method = "Get"
url="http://www.macromedia.com/software"
    path="c:\temp"
    file="macr_software.htm">

Get the page specified in the URL and save it in the file specified by the path and file attributes.

When you use the path and file attributes, ColdFusion ignores any resolveurl attribute. As a result, frames and other included files cannot appear when you view the saved page.

To get a binary file and save it:

  1. Create a ColdFusion page with the following content:
    <cfhttp
    method="Get"
    url="http://www.macromedia.com/macromedia/accessibility/images/spotlight.jpg"
    path="c:\temp"
    file="My_SavedBinary.jpg">
<cfoutput>
    #cfhttp.MimeType#
</cfoutput>
  2. (Optional) Replace the value of the url attribute with the URL of a binary file that you want to download.
  3. (Optional) Change the path from C:\temp to a path on your hard drive.
  4. Save the file as save_binary.cfm in the myapps directory under your web_root and open it in the web browser to view the MIME type.
  5. (Optional) Verify that the binary file now exists at the location you specified in the path attribute.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfhttp
method="Get"
url="http://www.macromedia.com/macromedia/accessibility/images/spotlight.jpg"
    path="c:\temp"
    file="My_SavedBinary.jpg">

Get a binary file and save it in the path and file specified.

<cfoutput>
    #cfhttp.MimeType#
</cfoutput>

Display the MIME type of the file.


Creating a query object from a text file

You can create a query object from a delimited text file by using the cfhttp tag and specifying method="Get" and the name attribute. This is a powerful method for processing and handling text files. After you create the query object, you can easily reference columns in the query and perform other ColdFusion operations on the data.

ColdFusion processes text files in the following manner:

  • You can specify a field delimiter with the delimiter attribute. The default is a comma.
  • If data in a field might include the delimiter character, you must surround the entire field with the text qualifier character, which you can specify with the textqualifier attribute. The default text qualifier is the double-quotation mark (").
  • The textqualifier="" specifies that there is no text qualifier. If you use textqualifier="""" (four " marks in a row), it explicitly specifies the double-quotation mark as the text qualifier.
  • If there is a text qualifier, you must surround all field values with the text qualifier character.
  • To include the text qualifier character in a field, use a double character. For example, if the text qualifier is ", use "" to include a quotation mark in the field.
  • The first row of text is always interpreted as column headings, so that row is skipped. You can override the file’s column heading names by specifying a different set of names in the columns attribute. You must specify a name for each column. You then use these new names in your CFML code. However, ColdFusion never treats the first row of the file as data.
  • When duplicate column heading names are encountered, ColdFusion adds an underscore character to the duplicate column name to make it unique. For example, if two CustomerID columns are found, the second is renamed "CustomerID_".

To create a query from a text file:

  1. Create a text file with the following content:
    OrderID,OrderNum,OrderDate,ShipDate,ShipName,ShipAddress
001,001,01/01/01,01/11/01,Mr. Shipper,123 Main Street
002,002,01/01/01,01/28/01,Shipper Skipper,128 Maine Street
  2. Save the file as text.txt in the myapps directory under your web_root.
  3. Create a ColdFusion page with the following content:
    <cfhttp method="Get"
    url="http://127.0.0.1/myapps/text.txt"
    name="juneorders"
    textqualifier="">

<cfoutput query="juneorders">
    OrderID: #OrderID#<br>
    Order Number: #OrderNum#<br>
    Order Date: #OrderDate#<br>
</cfoutput>
<!--- Now substitute different column names --->
<!--- by using the columns attribute --->
<hr>
Now using replacement column names<br>

<cfhttp method="Get"
    url="http://127.0.0.1/myapps/text.txt"
    name="juneorders"
    columns="ID,Number,ODate,SDate,Name,Address"
    textqualifier="">

<cfoutput query="juneorders">
    Order ID: #ID#<br>
    Order Number: #Number#<br>
    Order Date: #SDate#<br>
</cfoutput>
  4. Save the file as query_textfile.cfm in the myapps directory under your web_root and view it in the web browser.


Using the cfhttp Post method

Use the Post method to send cookie, form field, CGI, URL, and file variables to a specified ColdFusion page or CGI program for processing. For Post operations, you must use the cfhttpparam tag for each variable you want to post. The Post method passes data to a specified ColdFusion page or an executable that interprets the variables being sent and returns data.

For example, when you build an HTML form using the Post method, you specify the name of the page to which form data is passed. You use the Post method in cfhttp in a similar way. However, with cfhttp, the page that receives the Post does not, itself, display anything.

To pass variables to a ColdFusion page:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>HTTP Post Test</title>
</head>
<body>
<h1>HTTP Post Test</h1>
<cfhttp method="Post"
    url="http://127.0.0.1:8500/myapps/post_test_server.cfm">
    <cfhttpparam type="Cookie"
        value="cookiemonster"
        name="mycookie6">
    <cfhttpparam type="CGI"
        value="cgivar "
        name="mycgi">
    <cfhttpparam type="URL"
        value="theurl"
        name="myurl">
    <cfhttpparam type="Formfield"
        value="twriter@macromedia.com"
        name="emailaddress">
    <cfhttpparam type="File"
        name="myfile"
        file="c:\pix\trees.gif">
</cfhttp>
<cfoutput>
File Content:<br>
    #cfhttp.filecontent#<br>
Mime Type:  #cfhttp.MimeType#<br>
</cfoutput>
</body>
</html>
  2. Replace the path to the GIF file to a path on your server (just before the closing cfhttp tag).
  3. Save the file as post_test.cfm in the myapps directory under your web_root.

Note: You must write a page to view the variables. This is the next procedure.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfhttp method="Post"
    url="http://127.0.0.1:8500/myapps/post_test_	server.cfm">

Post an HTTP request to the specified page.

<cfhttpparam type="Cookie"
    value="cookiemonster"
    name="mycookie6">

Send a cookie in the request.

<cfhttpparam type="CGI"
    value="cgivar "
    name="mycgi">

Send a CGI variable in the request.

    <cfhttpparam type="URL"
        value="theurl"
        name="myurl">

Send a URL in the request.

<cfhttpparam type="Formfield"
    value="twriter@macromedia.com"
    name="emailaddress">

Send a Form field in the request.

<cfhttpparam type="File"
    name="myfile"
    file="c"\pix\trees.gif">

Send a file in the request.

The </ cfhttp > tag ends the http request.

<cfoutput>
File Content:<br>
    #cfhttp.filecontent#<br>

Display the contents of the file that the page that is posted to creates by processing the request. In this example, this is the output from the cfoutput tag in server.cfm.

Mime Type:  #cfhttp.MimeType#<br>
</cfoutput>

Display the MIME type of the created file.

To view the variables:

  1. Create a ColdFusion page with the following content:
    <html>
<head><title>HTTP Post Test</title> </head>
<body>
<h1>HTTP Post Test</h1>
<cffile destination="C:\temp\"
    nameconflict="Overwrite"
    filefield="Form.myfile"
    action="Upload"
    attributes="Normal">
<cfoutput>
    The URL variable is: #URL.myurl# <br>
    The Cookie variable is: #Cookie.mycookie6# <br>
    The CGI variable is: #CGI.mycgi#. <br>
    The Formfield variable is: #Form.emailaddress#. <br>
    The file was uploaded to #File.ServerDirectory#\#File.ServerFile#.
</cfoutput>
</body>
</html>
  2. Replace C:\temp\ with an appropriate directory path on your hard drive.
  3. Save the file as post_test_server.cfm in the myapps directory under your web_root.
  4. View post_test.cfm in your browser and look for the file in C:\temp\ (or your replacement path).

Reviewing the code

The following table describes the code and its function:

Code

Description

<cffile destination="C:\temp\"
    nameconflict="Overwrite"
    filefield="Form.myfile"
    action="Upload"
    attributes="Normal">

Write the transferred document to a file on the server. You send the file using the cfhttpparam type="File" attribute, but the receiving page gets it as a Form variable, not a File variable. This cffile tag creates File variables, as follows.

<cfoutput>

Output information. The results are not displayed by this page. They are passed back to the posting page in its cfhttp.filecontent variable.

The URL variable is: #URL.myurl# <br>

Output the value of the URL variable sent in the HTTP request.

The Cookie variable is: #Cookie.mycookie# <br>

Output the value of the Cookie variable sent in the HTTP request.

The CGI variable is: #CGI.mycgi# <br>

Output the value of the CGI variable sent in the HTTP request.

The Form variable is:
#Form.emailaddress#. <br>

Output the Form variable sent in the HTTP request. You send the variable using the type="formField" attribute but the receiving page gets it as a Form variable.

The file was uploaded to #File.ServerDirectory#\#File.
ServerFile#.
</cfoutput>

Output the results of the cffile tag on this page. This time, the variables really are File variables.

To return results of a CGI program:

The following code runs a CGI program search.exe on a website and displays the results, including both the MIME type and length of the response. The search.exe program must expect a "search" parameter.

<cfhttp method="Post"
        url="http://www.my_favorite_site.com/search.exe"
        resolveurl="Yes">
    <cfhttpparam type="Formfield"
        name="search"
        value="Macromedia ColdFusion">
</cfhttp>
<cfoutput>
    Response Mime Type: #cfhttp.MimeType#<br>
    Response Length: #len(cfhttp.filecontent)# <br>
    Response Content: <br>
        #htmlcodeformat(cfhttp.filecontent)#<br>
</cfoutput>


Performing file operations with cfftp

The cfftp tag lets you perform tasks on remote servers using File Transfer Protocol (FTP). You can use cfftp to cache connections for batch file transfers when uploading or downloading files.

Note: To use cfftp, you must select the Enable ColdFusion Security option on the Sandbox Security page in the Security area in the ColdFusion MX Administrator. (In the Standard Edition, select Security > Basic Security.)

For server/browser operations, use the cffile, cfcontent, and cfdirectory tags.

Using cfftp involves two major types of operations: connecting, and transferring files. The FTP protocol also provides commands for listing directories and performing other operations. For a complete list of attributes that support FTP operations and additional details on using the cfftp tag, see CFML Reference.

To open an FTP connection and retrieve a file listing:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>FTP Test</title>
</head>

<body>
<h1>FTP Test</h1>
<!--- Open ftp connection --->
<cfftp connection="Myftp"
    server="MyServer"
    username="MyUserName"
    password="MyPassword"
    action="Open"
    stoponerror="Yes">

<!--- Get the current directory name. --->
<cfftp connection=Myftp
    action="GetCurrentDir"
    stoponerror="Yes">

<!--- output directory name --->
<cfoutput>
    The current directory is:  #cfftp.returnvalue#<p>
</cfoutput>

<!--- Get a listing of the directory. --->
<cfftp connection=Myftp
    action="listdir"
    directory="#cfftp.returnvalue#"
    name="dirlist"
    stoponerror="Yes">
<!--- Close the connection.--->
<cfftp action="close" connection="Myftp">
<p>Did the connection close successfully?
    <cfoutput>#cfftp.succeeded#</cfoutput></p>

<!--- output dirlist results --->
<hr>
<p>FTP Directory Listing:</p>

<cftable query="dirlist" colheaders="yes" htmltable>
    <cfcol header="<B>Name</b>" TEXT="#name#">
    <cfcol header="<B>Path</b>" TEXT="#path#">
    <cfcol header="<B>URL</b>" TEXT="#url#">
    <cfcol header="<B>Length</b>" TEXT="#length#">
    <cfcol header="<B>LastModified</b>"
    TEXT="#DateFormat(lastmodified)#">
    <cfcol header="<B>IsDirectory</b>"
        TEXT="#isdirectory#">
</cftable>
  2. Change MyServer to the name of a server for which you have FTP permission.
  3. Change MyUserName and MyPassword to a valid username and password.

    To establish an anonymous connection, enter "anonymous" as the username and an e-mail address (by convention) for the password.

  4. Save the file as ftp_connect.cfm in the myapps directory under your web_root and view it in the web browser.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfftp connection="Myftp"
    server="MyServer"
    username="MyUserName"
    password="MyPassword"
    action="Open"
    stoponerror="Yes">

Open an FTP connection to the MyServer server and log on as MyUserName. If an error occurs, stop processing and display an error. You can use this connection in other cfftp tags by specifying the Myftp connection.

<cfftp connection=Myftp
    action="GetCurrentDir"
    stoponerror="Yes">
<cfoutput>
    The current directory is:  #cfftp.returnvalue#<p>
</cfoutput>

Use the Myftp connection to get the name of the current directory; stop processing if an error occurs.

Display the current directory.

<cfftp connection=Myftp
    action="ListDir"
    directory="#cfftp.returnvalue#"
    name="dirlist"
    stoponerror="Yes">

Use the Myftp connection to get a directory listing. Use the value returned by the last cfftp call (the current directory of the connection) to specify the directory to list. Save the results in a variable named dirlist (a query object). Stop processing if there is an error.

<cfftp action="close" connection="Myftp">
<p>Did the connection close successfully?
    <cfoutput>#cfftp.succeeded#</cfoutput></p>

Close the connection, and do not stop processing if the operation fails (because you can still use the results). Instead, display the value of the cfftp.succeeded variable, which is Yes if the connection is closed, and No if the operation failed.

<cftable query="dirlist"       colheaders="yes" htmltable>
  <cfcol header="<B>Name</b>"
    TEXT="#name#">
  <cfcol header="<B>Path</b>"
    TEXT="#path#">
  <cfcol header="<B>URL</b>"
    TEXT="#url#">
  <cfcol header="<B>Length</b>"
    TEXT="#length#">
  <cfcol header="<B>LastModified</b>"
        TEXT="#DateFormat(lastmodified)#">
  <cfcol header="<B>IsDirectory</b>"
    TEXT="#isdirectory#">
</cftable>

Display a table with the results of the ListDir FTP command.

After you establish a connection with cfftp, you can reuse the connection to perform additional FTP operations until either you or the server closes the connection. When you access an already-active FTP connection, you do not need to re-specify the username, password, or server. In this case, make sure that when you use frames, only one frame uses the connection object.

Note: For a single simple FTP operation, such as GetFile or PutFile, you do not need to establish a connection. Specify all the necessary login information, including the server and any login and password, in the single cfftp request.

Caching connections across multiple pages

The FTP connection established by cfftp is maintained only in the current page unless you explicitly assign the connection to a variable with Application or Session scope.

Assigning a cfftp connection to an application variable could cause problems, since multiple users could access the same connection object at the same time. Creating a session variable for a cfftp connection makes more sense, because the connection is available to only one client and does not last past the end of the session.

Example: caching a connection

<cflock scope="Session" timeout=10>
<cfftp action="Open"
    username="anonymous"
    password="me@home.com"
    server="ftp.eclipse.com"
    connection="Session.myconnection">
</cflock>

In this example, the connection cache remains available to other pages within the current session. You must enable session variables in your application for this approach to work, and you must lock code that uses session variables. For more information on locking, see Using Persistent Data and Locking.

Note: Changing a connection’s characteristics, such the retrycount or timeout values, might require you to re-establish the connection.

Connection actions and attributes

The following table shows the available cfftp actions and the attributes they require when you use a named (that is, cached) connection. If you do not specify an existing connection name, you must specify the username, password, and server attributes.

.
Action | Attributes | Action | Attributes
Open | none | Rename | existing new
Close | none | Remove | server item
ChangeDir | directory | GetCurrentDir | none
CreateDir | directory | GetCurrentURL | none
ListDir | name directory | ExistsDir | directory
RemoveDir | directory | ExistsFile | remotefile
GetFile | localfile remotefile | Exists | item
PutFile | localfile remotefile |  |

Previous


Managing Files on the Server

The cffile, cfdirectory, and cfcontent tags handle browser and server file management tasks, such as uploading files from a client to the web server, viewing directory information, and changing the content type that is sent to the web browser. To perform server-to-server operations, use the cfftp tag, described in Performing file operations with cfftp.

Contents

About file management

Using cffile

Using cfdirectory

Using cfcontent
Next


About file management

Macromedia ColdFusion MX lets you access and manage the files and directories on your ColdFusion server. The cffile tag has several attributes for moving, copying, deleting, and renaming files. You use the cfdirectory tag to list, create, delete, and rename directories. The cfcontent tag lets you define the MIME (Multipurpose Internet Mail Extensions) content type that returns to the web browser.


Using cffile

You can use the cffile tag to work with files on the server in several ways:

  • Upload files from a client to the web server using an HTML form
  • Move, rename, copy, or delete files on the server
  • Read, write, or append to text files on the server

You use the action attribute to specify any of the following file actions: upload, move, rename, copy, delete, read, readBinary, write, and append. The required attributes depend on the action specified. For example, if action="write", ColdFusion expects the attributes associated with writing a text file.

Note: Consider the security and logical structure of directories on the server before allowing users access to them. You can disable the cffile tag in the ColdFusion MX Administrator. Also, to access files that are not located on the local ColdFusion MX system, ColdFusion services must run using an account with permission to access the remote files and directories.

This section describes the following topics:

  • Uploading files
  • Moving, renaming, copying, and deleting server files
  • Reading, writing, and appending to a text file


Uploading files

File uploading requires that you create two files:

  • An HTML form to specify file upload information
  • An action page containing the file upload code

The following procedures describe how to create these files.

To create an HTML file to specify file upload information:

  1. Create a ColdFusion page with the following content:
    <head><title>Specify File to Upload</title></head>
<body>
<h2>Specify File to Upload</h2>
<!--- the action attribute is the name of the action page --->
<form action="uploadfileaction.cfm"
        enctype="multipart/form-data"
        method="post">
    <p>Enter the complete path and filename of the file to upload:
    <input type="file"
            name="FiletoUpload"
            size="45">
    </p>
    <input 	type="submit"
            value="Upload">
</form>
</body>
  2. Save the file as uploadfileform.cfm in the myapps directory under your web_root and view it in the browser.

Note: The form will not work until you write an action page for it (see the next procedure).

Reviewing the code

The following table describes the code and its function:

Code

Description

<form action="uploadfileaction.cfm"
    enctype="multipart/form-data"
    method="post">

Create a form that contains file selection fields for upload by the user. The action attribute value specifies the ColdFusion template that will process the submitted form. The enctype attribute value tells the server that the form submission contains an uploaded file. The method attribute is set to post to submit a ColdFusion form.

<input type="file"
    name="FiletoUpload"
    size="45">

Allow the user to specify the file to upload. The file type instructs the browser to prepare to read and transmit a file from the user's system to your server. It automatically includes a Browse button to let the user look for the file instead of manually entering the entire path and filename.

The user can enter a file path or browse the system and select a file to send.

  1. Create a ColdFusion page with the following content:
    <html>
<head> <title>Upload File</title> </head>
<body>
<h2>Upload File</h2>

<cffile action="upload"
        destination="c:\temp\"
        nameConflict="overwrite"
        fileField="Form.FiletoUpload">

<cfoutput>
You uploaded #cffile.ClientFileName#.#cffile.ClientFileExt#
            successfully to #cffile.ServerDirectory#.
</cfoutput>

</body>
</html>
  2. Change the following line to point to an appropriate location on your server:
    destination="c:\temp\"

    Note: This directory must exist on the server.

  3. Save the file as uploadfileaction.cfm in the myapps directory under your web_root.
  4. View uploadfileform.cfm in the browser, enter a file to upload, and submit the form.

    The file you specified uploads.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cffile action="upload"

Output the name and location of the uploaded file on the client machine.

destination="c:\temp\"

Specify the destination of the file.

nameConflict="overwrite"

If the file already exists, overwrite it.

fileField="Form.FiletoUpload">

Specify the name of the file to upload. Do not enclose the variable in number signs.

You uploaded #cffile.ClientFileName#.#cffile.
ClientFileExt# successfully to
#cffile.ServerDirectory#.

Inform the user of the file that was uploaded and its destination. For information on cffile scope variables, see Evaluating the results of a file upload.

Note: This example performs no error checking and does not incorporate any security measures. Before deploying an application that performs file uploads, ensure that you incorporate both error handling and security. For more information, see Securing Applications and Handling Errors.

This section describes the following topics:

  • Resolving conflicting filenames
  • Controlling the type of file uploaded
  • Setting file and directory attributesnumber
  • Evaluating the results of a file upload


Resolving conflicting filenames

When you save a file to the server, there is a risk that a file with the same name might already exist. To resolve this problem, assign one of these values to the nameConflict attribute of the cffile tag:

Error (default) ColdFusion stops processing the page and returns an error. The file is not saved.

Skip Allows custom behavior based on file properties. Neither saves the file nor returns an error.

Overwrite Overwrites a file that has the same name as the uploaded file.

MakeUnique Generates a unique filename for the uploaded file. The name is stored in the file object variables serverFile and serverFileName. You can use this variable to record the name used when the file was saved. The unique name might not resemble the attempted name. For more information on file upload status variables, see Evaluating the results of a file upload.


Controlling the type of file uploaded

For some applications, you might want to restrict the type of file that is uploaded. For example, you might not want to accept graphic files in a document library.

You use the accept attribute to restrict the type of file that you allow in an upload. When an accept qualifier is present, the uploaded file’s MIME content type must match the criteria specified or an error occurs. The accept attribute takes a comma-separated list of MIME data names, optionally with wildcards.

A file’s MIME type is determined by the browser. Common types, such as image/gif and text/plain, are registered in the browser.

Note: Current versions of Microsoft Internet Explorer and Netscape support MIME type associations. Other browsers and earlier versions might ignore these associations.

ColdFusion saves any uploaded file if you omit the accept attribute or specify "*/*". You can restrict the file types, as demonstrated in the following examples.

The following cffile tag saves an image file only if it is in the GIF format:

<cffile action="Upload"
    fileField="Form.FiletoUpload"
    destination="c:\uploads\"
    nameConflict="Overwrite"
    accept="image/gif">

The following cffile tag saves an image file only if it is in GIF or JPEG format:

<cffile action="Upload"
    fileField="Form.FiletoUpload"
    destination="c:\uploads\"
    nameConflict="Overwrite"
    accept="image/gif, image/jpeg">

Note: If you receive an error similar to "The MIME type of the uploaded file (image/jpeg) was not accepted by the server", enter accept="image/jpeg" to accept JPEG files.

This cffile tag saves any image file, regardless of the format:

<cffile action="Upload"
    fileField="Form.FiletoUpload"
    destination="c:\uploads\"
    nameConflict="Overwrite"
    accept="image/*">


Setting file and directory attributes

In Windows, you specify file attributes using the cffile attributes attribute. In UNIX, you specify file or directory permissions using the mode attribute of the cffile or cfdirectory tag.

Windows

In Windows, you can set the following file attributes:

  • Hidden
  • Normal
  • ReadOnly

To specify several attributes in CFML, use a comma-separated list for the attributes attribute; for example, attributes="ReadOnly,Hidden". If you do not use the attributes attribute, the file’s existing attributes are maintained. If you specify any other attributes in addition to Normal, the additional attribute overrides the Normal setting.

UNIX

In UNIX, you can individually set permissions on files and directories for each of three types of users--owner, group, and other. You use a number for each user type. This number is the sum of the numbers for the individual permissions allowed. Values for the mode attribute correspond to octal values for the UNIX chmod command:

  • 4 = read
  • 2 = write
  • 1 = execute

You enter permissions values in the mode attribute for each type of user: owner, group, and other in that order. For example, use the following code to assign read permissions for everyone:

mode=444

To give a file or directory owner read/write/execute permissions and read only permissions for everyone else:

mode=744


Evaluating the results of a file upload

After a file upload is completed, you can retrieve status information using file upload status variables. This status information includes data about the file, such as its name and the directory where it was saved.

You can access file upload status variables using dot notation, using either file.varname or cffile.varname. Although you can use either the File or cffile prefix for file upload status variables, cffile is preferred; for example, cffile.ClientDirectory. The File prefix is retained for backward compatibility.

Note: File status variables are read-only. They are set to the results of the most recent cffile operation. If two cffile tags execute, the results of the first are overwritten by the subsequent cffile operation.

The following table describes the file upload status variables that are available after an upload:

Variable | Description
attemptedServerFile | Initial name that ColdFusion uses when attempting to save a file; for example, myfile.txt. (see Resolving conflicting filenames).
clientDirectory | Directory on the client’s system from which the file was uploaded.
clientFile | Full name of the source file on the client’s system with the file extension; for example, myfile.txt.
clientFileExt | Extension of the source file on the client’s system without a period; for example, txt (not .txt).
clientFileName | Name of the source file on the client’s system without an extension; for example, myfile.
contentType | MIME content type of the saved file; for example, image for image/gif.
contentSubType | MIME content subtype of the saved file; for example, gif for image/gif.
dateLastAccessed | Date that the uploaded file was last accessed.
fileExisted | Indicates (Yes or No) whether the file already existed with the same path.
fileSize | Size of the uploaded file.
fileWasAppended | Indicates (Yes or No) whether ColdFusion appended the uploaded file to an existing file.
fileWasOverwritten | Indicates (Yes or No) whether ColdFusion overwrote a file.
fileWasRenamed | Indicates (Yes or No) whether the uploaded file was renamed to avoid a name conflict.
fileWasSaved | Indicates (Yes or No) whether ColdFusion saved the uploaded file.
oldFileSize | Size of the file that was overwritten in the file upload operation. Empty if no file was overwritten.
serverDirectory | Directory where the file was saved on the server.
serverFile | Full name of the file saved on the server with the file extension; for example, myfile.txt.
serverFileExt | Extension of the file saved on the server without a period; for example, txt (not .txt).
serverFileName | Name of the file saved on the server without an extension; for example, myfile.
timeCreated | Date and time the uploaded file was created.
timeLastModified | Date and time of the last modification to the uploaded file.


Moving, renaming, copying, and deleting server files

With cffile, you can create application pages to manage files on your web server. You can use the tag to move files from one directory to another, rename files, copy a file, or delete a file.

The examples in the following table show static values for many of the attributes. However, the value of all or part of any attribute in a cffile tag can be a dynamic parameter.

Action

Example code

Move a file

<cffile action="move"
    source="c:\files\upload\KeyMemo.doc"
    destination="c:\files\memo\">

Rename a file

<cffile action="rename"
    source="c:\files\memo\KeyMemo.doc"
    destination="c:\files\memo\OldMemo.doc">

Copy a file

<cffile action="copy"
    source="c:\files\upload\KeyMemo.doc"
    destination="c:\files\backup\">

Delete a file

<cffile action="delete"
    file="c:\files\upload\oldfile.txt">

This example sets the ReadOnly flag bit for the uploaded file:

<cffile action="Copy"
    source="c:\files\upload\keymemo.doc"
    destination="c:\files\backup\"
    attributes="ReadOnly">

Note: Ensure you include the trailing slash (\) when you specify the destination directory. Otherwise, ColdFusion treats the last element in the pathname as a filename. This only applies to copy actions.


Reading, writing, and appending to a text file

In addition to managing files on the server, you can use cffile to read, create, and modify text files. As a result, you can do the following things:

  • Create log files. (You can also use cflog to create and write to log files.)
  • Generate static HTML documents.
  • Use text files to store information that can be incorporated into web pages.

Reading a text file

You can use cffile to read an existing text file. The file is read into a local variable that you can use anywhere in the application page. For example, you could read a text file and then insert its contents into a database, or you could read a text file and then use one of the string replacement functions to modify the contents.

To read a text file:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Read a Text File</title>
</head>

<body>
Ready to read the file:<br>
<cffile action="read"
    file="C:\inetpub\wwwroot\mine\message.txt"
    variable="Message">

<cfoutput>
    #Message#
</cfoutput>
</body>
</html>
  2. Replace C:\inetpub\wwwroot\mine\message.txt with the location and name of a text file on the server.
  3. Save the file as readtext.cfm in the myapps directory under your web_root and view it in the browser.

Writing a text file on the server

You can use cffile to write a text file based on dynamic content. For example, you could create static HTML files or log actions in a text file.

To create a form in to capture data for a text file:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Put Information into a Text File</title>
</head>

<body>
<h2>Put Information into a Text File</h2>

<form action="writetextfileaction.cfm" method="Post">
    <p>Enter your name: <input type="text" name="Name" size="25"></p>
    <p>Enter the name of the file: <input type="text" name="FileName" size="25">.txt</p>
    <p>Enter your message:
    <textarea name="message"cols=45 rows=6></textarea>
    </p>
    <input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
  2. Save the file as writetextfileform.cfm in the myapps directory under your web_root.

Note: The form will not work until you write an action page for it (see the next procedure).

To write a text file:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>Write a Text File</title>
</head>
<body>
<cffile action="write"
    file="C:\inetpub\wwwroot\mine\#Form.FileName#.txt"
    output="Created By: #Form.Name#
#Form.Message# ">
</body>
</html>
  2. Modify the path C:\inetpub\wwwroot\mine\ to point to a path on your server.
  3. Save the file as writetextfileaction.cfm in the myapps directory under your web_root.
  4. View the file writetextfileform.cfm in the browser, enter values, and submit the form.

    The text file is written to the location you specified. If the file already exists, it is replaced.

Appending a text file

You can use cffile to append additional text to the end of a text file; for example, when you create log files.

To append a text file:

  1. Open the writetextfileaction.cfm file.
  2. Change the value for the action attribute from write to append so that the file appears as follows:
    <html>
<head>
    <title>Append a Text File</title>
</head>
<body>
<cffile action="append"
    file="C:\inetpub\wwwroot\mine\message.txt"
    output="Appended By: #Form.Name#">
</body>
</html>
  3. Save the file as writetextfileaction.cfm in the myapps directory under your web_root.
  4. View the file in the browser, enter values, and submit the form.

    The appended information displays at the end of the text file.


Using cfdirectory

Use the cfdirectory tag to return file information from a specified directory and to create, delete, and rename directories. When listing directory contents or deleting a directory, you can optionally use the recurse attribute to access or delete all subdirectories.

As with cffile, you can disable cfdirectory processing in the ColdFusion MX Administrator. For details on the syntax of this tag, see CFML Reference.

Returning file information

When you use the action="list" attribute setting, cfdirectory returns a query object as specified in the name attribute. The name attribute is required when you use the action="list" attribute setting. This query object contains result columns that you can reference in a cfoutput tag, using the value specified in the name attribute:

name Directory entry name.

directory Directory containing the entry.

size Directory entry size.

type File type: File or Dir.

dateLastModified Date an entry was last modified.

attributes (Windows only) File attributes, if applicable.

mode (UNIX only) The octal value representing the permissions setting for the specified directory.

Note: ColdFusion supports the ReadOnly and Hidden values for the attributes attribute for cfdirectory sorting.

Depending on whether your server is on a UNIX system or a Windows system, either the Attributes column or the Mode column is empty. Also, you can specify a filename in the filter attribute to get information on a single file.

The following procedure describes how to create a ColdFusion page in which to view directory information.

To view directory information:

  1. Create a ColdFusion page with the following content:
    <html>
<head>
    <title>List Directory Information</title>
</head>

<body>
<h3>List Directory Information</h3>
<cfdirectory
    directory="c:\inetpub\wwwroot\mine"
    name="mydirectory"
    sort="size ASC, name DESC, datelastmodified">

<table cellspacing=1 cellpadding=10>
<tr>
    <th>Name</th>
    <th>Size</th>
    <th>Type</th>
    <th>Modified</th>
    <th>Attributes</th>
    <th>Mode</th>
</tr>
<cfoutput query="mydirectory">
<tr>
    <td>#mydirectory.name#</td>
    <td>#mydirectory.size#</td>
    <td>#mydirectory.type#</td>
    <td>#mydirectory.dateLastModified#</td>
    <td>#mydirectory.attributes#</td>
    <td>#mydirectory.mode#</td>
</tr>
</cfoutput>
</table>

</body>
</html>
  2. Modify the path C:\inetpub\wwwroot\mine so that it points to a directory on your server.
  3. Save the file as directoryinfo.cfm in the myapps directory under your web_root and view it in the browser:

    Results of viewing directoryinfo.cfm in a browser.


Using cfcontent

The cfcontent tag downloads files from the server to the client. You can use this tag to set the MIME type of the content returned by a ColdFusion page and, optionally, define the filename of a file to be downloaded by the current page. By default, ColdFusion returns a MIME content type of text/html so that a web browser renders your template text as a web page.

As with cffile and cfdirectory , you can disable cfcontent processing in the ColdFusion MX Administrator.

About MIME types

A MIME type is a label that identifies the contents of a file. the browser uses the MIME type specification to determine how to interact with the file. For example, the browser could open a spreadsheet program when it encounters a file identified by its MIME content type as a spreadsheet file.

A MIME content type consists of "type/subtype" format. The following are common MIME content types:

  • text/html
  • image/gif
  • application/pdf

Changing the MIME content type with cfcontent

You use the cfcontent tag to change the MIME content type that returns to the browser along with the content generated from your ColdFusion page.

The cfcontent tag has one required attribute, type, which defines the MIME content type returned by the current page.

To change the MIME content type with cfcontent:

  1. Create an HTML page with the following content:
    <h1>cfcontent_message.htm</h1>

<p>This is a <em>test message</em> written in HTML.</p>
<p>This is the <em>second paragraph</em> of the test message.
As you might expect, it is also written in HTML.</p>
  2. Save the file as cfcontent_message.htm in the myapps directory under your web_root.

    This HTML file will be called by the ColdFusion file that you write in steps 3 through 7.

  3. Create a ColdFusion page with the following content:
    <html>
<head>
<title>cfcontent Example</title>
</head>

<body>
<h3>cfcontent Example</h3>

<cfcontent
    type = "text/html"
    file = "C:\CFusionMX7\wwwroot\myapps\cfcontent_message.htm"
    deleteFile = "No">
</body>
</html>
  4. If necessary, edit the file = line to point to your myapps directory.
  5. Save the file as cfcontent.cfm in the myapps directory under your web_root and view it in the browser.

    The text of the called file (cfcontent_message.htm) displays as normal HTML, as shown in the following figure:

    Text of the called file in a browser.

  6. In cfcontent.cfm, change type = "text/html" to type = "text/plain".
  7. Save the file and view it in the browser (refresh it if necessary).

    The text displays as unformatted text, in which HTML tags are treated as text:

    Unformatted HTML text.

The following example shows how the cfcontent tag can create an Excel spreadsheet that contains your data.

To create an Excel spreadsheet with cfcontent:

  1. Create a ColdFusion page with the following content:
    <!--- Use cfsetting to block output of HTML
outside of cfoutput tags. --->
<cfsetting enablecfoutputonly="Yes">

<!--- Get employee info. --->
<cfquery name="GetEmps" datasource="cfdocexamples">
    SELECT * FROM Employee
</cfquery>

<!--- Set content type. --->
<cfcontent type="application/msexcel">

<!--- Suggest default name for XLS file. --->
<!--- "Content-Disposition" in cfheader also ensures
relatively correct Internet Explorer behavior. --->
<cfheader name="Content-Disposition" value="filename=Employees.xls">

<!--- Format data using cfoutput and a table.
        Excel converts the table to a spreadsheet.
        The cfoutput tags around the table tags force output of the HTML when
        using cfsetting enablecfoutputonly="Yes" --->
<cfoutput>
    <table cols="4">
        <cfloop query="GetEmps">
            <tr>
                <td>#Emp_ID#</td>
                <td>#FirstName#</td>
                <td>#LastName#</td>
            </tr>
        </cfloop>
    </table>
</cfoutput>
  2. Save the file as employees_to_excel.cfm in the myapps directory under your web_root and view it in the browser.

    The data appears in an Excel spreadsheet, as in the following figure:

    Data in an Excel spreadsheet.

Previous


Using Event Gateways

This chapter provides an introduction to Macromedia ColdFusion MX event gateways, and provides information on how to write applications that use these gateways. It also describes how to configure an event gateway for an application and how to deploy the application. The final sections of the chapter describe some of the event gateways and example applications that are provided with ColdFusion MX, and how to use them. Subsequent chapters describe how to write applications that use the instant messaging and SMS event gateway types that are provided with ColdFusion MX, and how to develop your own event gateways.

This chapter assumes that developers who write applications that use event gateways have a thorough knowledge of ColdFusion development concepts and practices, including ColdFusion components (CFCs). Developers who are writing applications for custom gateways that are not provided in ColdFusion MX must also know the details of the event gateway they are using and its requirements.

Note: ColdFusion MX Standard Edition does not support event gateways. In ColdFusion MX Developer Edition, some gateway types supplied with ColdFusion MX impose connection limitations.

Contents

About event gateways

Event gateway facilities and tools

Structure of an event gateway application

Configuring an event gateway instance

Developing an event gateway application

Deploying event gateways and applications

Using the CFML event gateway for asynchronous CFCs

Using the example event gateways and gateway applications

Next


About event gateways

ColdFusion event gateways are ColdFusion MX elements that let ColdFusion MX react to or generate external events or messages in an asynchronous manner. Event gateways let a ColdFusion application handle information that does not come through an HTTP request. For example, you can use event gateways to handle instant messages, short messages from mobile devices, or messages sent to a TCP/IP port.

The event gateway mechanism has the following major features:

  • ColdFusion MX event gateways do not require HTTP requests. ColdFusion developers can write ColdFusion MX gateway applications without using any CFM pages (just CFCs).
  • ColdFusion CFCs can use event gateways to listen for and respond directly to external events.
  • Event gateways operate asynchronously. A gateway typically gets a message and dispatches it for processing, without requiring or waiting for a response.
  • ColdFusion developers can create event gateways to handle any kind of event that a Java application can receive.

ColdFusion MX includes several product-level event gateways, such as a gateway for the XMPP (Extensible Messaging and Presence Protocol) instant messaging protocol. Macromedia also provides the source for several example gateways, such as a generalized socket gateway, that you can extend to handle your specific needs. You can also write your own gateways in Java to handle other event or messaging technologies supported by the Java runtime or by third-party providers, such as gateways for additional instant messaging protocols, gateways for specific ERP systems, or other protocols, such as NNTP.

This section describes the following topics:

  • Using event gateways
  • Event gateway terms and concepts
  • How event gateway applications work
  • About developing event gateway applications


Using event gateways

Because event gateways provide a generalized asynchronous messaging mechanism, you can use them with many kinds of event or messaging resources. For example, ColdFusion MX includes gateways (either product quality, or lighter weight example gateways) for communicating between ColdFusion applications and the following types of resources:

  • Mobile phones and other devices that support short messaging services (SMS)
  • XMPP or IBM Sametime Instant message clients
  • Java Sockets (which let your ColdFusion application communicate with TCP/IP-based devices and programs, such as Telnet terminal clients).
  • Java Messaging Service (JMS) resources, such as storefront sales order handling systems.

Event gateways are not limited to sending or receiving information using communications protocols. For example, ColdFusion MX includes an example event gateway that monitors changes to a directory and invokes a CFC method whenever the directory changes. ColdFusion MX also includes an event gateway that lets a CFML application "call" a CFC asynchronously and continue processing without getting a response from the CFC.

Just as you can create event gateways that serve many different event or messaging based technologies, you can write many kinds of applications that use them. Just a few examples of possible gateway uses include the following.

Server to client push examples

  • An application that sends an instant message (IM) or SMS text message to a person who can approve a purchase order, get a response, and mark the purchase order as approved or denied.
  • A bot that notifies users through their preferred messaging method (cell phone, instant messaging, or even e-mail) when watch list stock goes up, and offers to buy or sell the stock immediately.
  • An application that authenticates web users by sending them an SMS message that includes code that they must to enter into the browser in order to proceed.

Client to server examples

  • A menu-based SMS application that lets users get information from any of several web service data providers. ColdFusion MX includes a SMS menuing example int the gateways/cfc directory.
  • A instant messaging application that takes messages from users to technical support and assigns and directs the messages to the most available support staff member. The application could also log the user ID and session, and you could use ColdFusion MX to generate usage reports.
  • A directory lookup robot IM "buddy" that responds to messages chat contain an employee’s name with the employee’s phone number or buddy ID.

Server to serve examples

  • A JMS subsystem that publishes status updates that are consumed by business intelligence systems.
  • A system that monitors and publishes download events from a website.


Event gateway terms and concepts

This document uses the following terms when referring to event gateways:

Event A trigger that ColdFusion can receive from an external source. ColdFusion event gateways receive events.

Message The information provided by an event. In ColdFusion MX, a message is the data structure that the event gateway receives when an event is triggered.

Event gateway Java code that receives events and sends them to and from ColdFusion MX application code. This document uses the term event gateway, without the word type or instance, to refer to the general concept of a ColdFusion event gateway. Where the context makes the meaning obvious, the term can also refer to event gateway type or event gateway instance.

Event gateway type A specific event gateway implementation, represented by a Java class. Each event gateway type handles messages belonging to a particular a communications method or protocol, such as short message service (SMS), an instant messaging protocol, or Sockets. You generally have one event gateway type per communication protocol. You configure each event gateway type on the Gateway Types page in the Event Gateways area in the ColdFusion MX Administrator.

Event gateway instance A specific instance of an event gateway type class. You configure each event gateway instance on the ColdFusion MX Gateways page by specifying the event gateway type, an ID, the path to the event gateway application CFC that uses this instance, and a configuration file (if needed for the selected event gateway type). You can have multiple event gateway instances per event gateway type, for example, for different event gateway applications.

Event gateway application One or more CFCs and any supporting CFM pages that handle events from an event gateway instance and send messages using the event gateway instance. The event gateway application is not part of an event gateway instance, but the code that is responsible for processing event messages to and from the instance.

Event gateway listener Code in an event gateway that receives events from an event source and passes them to the ColdFusion MX gateway service for delivery to a CFML listener CFC.

Listener CFC A CFC that contains one or more methods that respond to incoming messages from one or more event gateway instances. Part of an event gateway application.

ColdFusion MX gateway service The part of ColdFusion that provides underlying support for event gateways, including a path between an event gateway instance and listener CFCs.


How event gateway applications work

The following diagram shows the architecture of ColdFusion event gateway applications:

Diagram shows the architecture of ColdFusion event gateway applications

How event gateways interact

Typically, a ColdFusion event gateway instance, a Java object, listens for events coming from an external provider. For example, a general socket event gateway listens for messages on an IP socket, and an SMS event gateway receives messages from an SMSC server.

Each event gateway instance communicates with one or more listener CFCs through the ColdFusion event gateway service. The listener CFCs receive CFEvent object instances that contain the messages, process them, and can send responses back to the event gateway, which can send the messages to the external resources.

Alternatively, a ColdFusion application can initiate a message by calling a ColdFusion function that sends the message to the event gateway. The event gateway then forwards the message to an external resource, such as an instant messaging server. A CFC in the application listens for any responses to the sent message.

Some event gateways can be one-way: they listen for a specific event and send it to a CFC, or they get messages from a ColdFusion function and dispatch it, but they do not do both. The example DirectoryWatcherGateway listens for events only, and the asynchronous CFML event gateway receives messages from CFML only. (You could even say that the directory watcher gateway doesn’t listen for events; it creates its own events internally by periodically checking the directory state.)

Event gateway structure

Java programmers develop ColdFusion event gateways by writing Java classes that implement the coldfusion.eventgateway.Gateway interface. ColdFusion event gateways normally consist of one or more threads that listen for events from an event provider, such as a Socket, an SMSC server, or some other source. The event gateway sends event messages to the ColdFusion event gateway service message queue, and provides a method that gets called when an event gateway application CFC or CFM page sends an outgoing message.

The event gateway class can also do the following:

  • Provide the ColdFusion application with access to a helper class that provides event gateway-specific services, such as buddy-list management or connection management.
  • Use a file that specifies configuration information, such as IP addresses and ports, passwords, and other ID information, internal time-out values, and so on.


About developing event gateway applications

ColdFusion application developers write applications that use event gateways. The person or company that provides the event gateway supplies gateway-specific information to the ColdFusion developer. This information must include the structure and contents of the messages that the ColdFusion application receives and sends to the event gateway, plus any information about configuration files or helper methods that the ColdFusion application might use.

The ColdFusion developer writes a CFC that listens for messages. Many event gateway types send messages to a listener CFC method named onIncomingMessage. A minimal event gateway application might implement only this single method. More complex event gateway types can require multiple CFC listener methods. For example, the ColdFusion XMPP IM event gateway sends user messages to the onIncomingMessage CFC method, but sends requests to add buddies to the onAddBuddyRequest CFC method.

Depending on the event gateway and application types, the event gateway application might include CFM pages or CFC methods to initiate outgoing messages. The application also might use an event gateway-specific GatewayHelper object to do tasks such as getting buddy lists in IM applications or getting a messaging server’s status.

The ColdFusion application developer also configures an event gateway instance in the ColdFusion MX Administrator, and possibly in a configuration file. The ColdFusion MX Administrator configuration information specifies the listener CFC that handles the messages from the event gateway and other standard event gateway configuration details. The configuration file, if required, contains event gateway type-specific configuration information.


Event gateway facilities and tools

ColdFusion MX provides a number of features and tools for developing and deploying event-handling applications, these including the following:

  • Standard event gateways.
  • Development tools and example code.
  • A gateway directory structure configured for use by custom event gateways and event gateway applications. This directory also contains the example code.
  • An event gateway-specific log file
  • Three pages in the ColdFusion MX Administrator for managing event gateways.


Standard event gateways

Macromedia provides several event gateways as part of ColdFusion MX. These event gateways support the following messaging protocols:

  • SMS (Short Message Service) A system designed for exchanging short, often text, messages with wireless devices, such as mobile phones or pagers. For detailed information on using the SMS event gateway, see Using the SMS Event Gateway.
  • XMPP (Extensible Messaging and Presence Protocol) An open, XML-based protocol for instant messaging. For detailed information on using the XMPP event gateway, see Using the Instant Messaging Event Gateways.
  • IBM Lotus Instant Messaging (commonly referred to as Lotus Sametime) The IBM product for real-time collaboration. For detailed information on using the Lotus Sametime event gateway, see Using the Instant Messaging Event Gateways.

ColdFusion MX also provides an event gateway, the CFML asynchronous event gateway, that lets a CFML application invoke a CFC method asynchronously. This event gateway does not follow the model of providing a mechanism for exchanging messages with resources outside of ColdFusion MX. Instead, it provides a one-way path for invoking CFCs when an application does not require (indeed, cannot receive) a return value from the CFC. For detailed information on using the CFML asynchronous event gateway, see Using the CFML event gateway for asynchronous CFCs.


Development tools and example code

ColdFusion MX provides the following tools and example code for developing your own event gateways and event gateway applications:

  • An SMS client (phone simulator) and a short message service center (SMSC) server simulator, for developing SMS applications without requiring an external SMS provider.
  • Four sample event gateways with source code:
    • A template for an empty event gateway that contains a skeleton on which you can build your own event gateways
    • A TCP/IP socket event gateway that listens on a TCP/IP port
    • A directory watcher event gateway that monitors changes to the contents of a directory
    • A Java Messaging Service (JMS) gateway that acts as a JMS consumer or producer.
  • Several sample applications, including the following:
    • A menu application that uses an inquiry-response drill-down menu to provide services such as weather reports and stock quotes.
    • A simple echo application that sends back the messages that it receives.
    • A temperature converter, an asynchronous logging application.
    • An application that returns employee phone number and other information.

    The chapters in this manual use these example applications.

  • Javadoc documentation for the Java interfaces and classes that you use to create gateways.

For more information on these examples, see Using the example event gateways and gateway applications.


The ColdFusion gateway directory

The ColdFusion MX installation includes a cf_root\WEB-INF\cfusion\gateway directory on J2EE configurations, or cf_root\gateway directory on server configurations. This directory contains all the code for ColdFusion example event gateways and example event gateway applications, and example configuration files for use by standard ColdFusion event gateways. You do not have to put your event gateways, event gateway application CFCs, or event gateway configuration files in this directory, but ColdFusion is configured to find event gateways and CFCs that you put there.

The following table lists the event gateway directory subdirectories, their purpose, and their initial contents. For more information on using the example event gateways and applications, see Using the example event gateways and gateway applications.

Directory

Purpose

cfc

Event gateway application CFCs. ColdFusion is installed with an Administrator Mapping between /gateway and this cfc directory.

cfc/examples

Code for the ColdFusion sample applications.

config

Configuration files for all ColdFusion event gateways, including standard ColdFusion MX event gateways, such as SMS, and example event gateways, such as the directory watcher event gateway.

doc/api

Javadoc for the Gateway, and GatewayHelper interfaces, and the CFEvent, GatewayServices, and GenericGateway classes that gateway developer use when writing gateways. This documentation is a subset of the information in the Gateway development interfaces and classes section in CFML Reference.

lib

Executable code for example and user-developed event gateway classes. The ColdFusion MX class loader includes this directory on its classpath and includes any JAR files that are in that directory on the class path. The examples.jar file in this directory contains the class files for the DirectoryWatcherGateway, EmptyGateway, and SocketGateway classes.

src/examples

Source code for the example event gateway classes that Macromedia provides. Includes the EmptyGateway.java file and the following subdirectories:

  • socket: Socket gateway source files
  • watcher: directory watcher gateway source files
  • JMS: JMS gateway source files


The eventgateway.log file

Event gateways provided with ColdFusion MX log event gateway errors and events to the cf_root\WEB-INF\cfusion\logs\eventgateway.log file on J2EE configurations, or the cf_root\logs\eventgateway.log file on server configurations. ColdFusion MX includes methods that let any event gateway use this file. This log file can be very useful in debugging event gateways and event gateway applications.


ColdFusion MX Administrator event gateway pages

The ColdFusion MX Administrator includes a Gateways section with three pages for managing event gateways:

  • Settings
  • Gateway types
  • Gateways

The Settings page lets you enable and disable support for event gateways, specify the number of threads that ColdFusion can devote to processing events, specify the maximum number events that ColdFusion can hold in its event queue (which holds events that are waiting to be processed) and start the SMS test server.

The Gateway Types page lets you add, remove, and configure event gateway types by specifying a name, a Java class, and startup timeout behavior.

Note: The gateway type name in the ColdFusion MX Administrator does not have to be the same as the gateway type that is used in the gateway Java code and the CFEvent data structure; however, you should use the same name in both places for consistency.

The Gateways page lets you add, remove, configure, start, and stop individual event gateway instances. You configure an event gateway instance by specifying a unique ID, the gateway type, one or more listener CFC paths, a configuration file (not required for all gateway types), and a startup mode (manual, automatic, or disabled).


Structure of an event gateway application

To develop an event gateway application, you create and use some or all of the following elements:

  • One or more listener CFCs that handle any incoming messages and send any necessary responses.
  • In some applications, ColdFusion pages that generate outgoing messages directly.
  • An event gateway instance configuration in the ColdFusion MX Administrator. This configuration might require a separate event gateway configuration file.
  • In some applications, a GatewayHelper object to provide access to additional features of the protocol or technology; for example, to manage instant messaging buddy lists.

This section describes the following topics:

  • The role of the listener CFC
  • The role of ColdFusion pages
  • The role of the ColdFusion MX Administrator
  • The role of the GatewayHelper object

The role of the listener CFC

All incoming event messages must be handled by one or more listener CFCs. You specify the listener CFCs when you configure an event gateway in the ColdFusion MX Administrator. You must specify at least one CFC in the administrator. Some gateway types can use more than one CFC. By default, the ColdFusion event gateway service delivers events by calling the CFC’s onIncomingMessage method.

The event gateway developer must inform the event gateway application developer of methods that the listener CFC must implement (may be only the onIncomingMessage method) and of the structure and contents of the event message data, contained in the CFEvent instance, that the listener CFC must handle. Outgoing messages have the same event message data structure as incoming messages.

Many gateways let the listener CFCs send a response by calling the cfreturn function, but ColdFusion MX does not require a return value. Listener CFCs can also use the SendGatewayMessage function, which provides more flexibility than the cfreturn tag.

The role of ColdFusion pages

ColdFusion MX CFM pages cannot receive event messages. However, they can send messages using an event gateway. Therefore, an event gateway application that initiates outgoing messages might use one or more SendGatewayMessage functions to send the messages. An application that sends an SMS message to notify users when a package ships, for example, could use the SendGatewayMessage function to send the notification.

The role of the ColdFusion MX Administrator

The Gateways page in the ColdFusion MX Administrator associates a specific event gateway instance with one or more listener CFCs that processes messages from the event gateway. It tells the ColdFusion event gateway service to send messages received by the event gateway to the listener CFC. It also lets you specify a configuration file for the event gateway instance and whether to start the event gateway instance (and therefore any responder application) when ColdFusion starts. For more information on using the Administrator, see ColdFusion MX Administrator event gateway pages and the ColdFusion MX Administrator online Help.

The role of the GatewayHelper object

A ColdFusion MX event gateway provides an information conduit: at its most basic, it receives and dispatches event messages. In some cases, however, an event gateway must provide additional functionality. An instant messaging event gateway, for example, needs to provide such services as managing buddies and providing status information. To support such use, an event gateway can enable access to a GatewayHelper object. The event gateway developer writes a Java class that provides the necessary utility routines as Java methods, and ColdFusion MX application developers can get an instance of the class by calling the CFML GetGatewayHelper method. The application calls the GatewayHelper object’s methods using normal ColdFusion MX object access techniques. The ColdFusion MX instant messaging event gateways and the example socket event gateway provide GatewayHelper objects.


Configuring an event gateway instance

Before you develop or deploy an event gateway application, you must use the ColdFusion MX Administrator to configure an event gateway instance that will handle the event messages. You specify the following information:

  • An event gateway ID to identify the specific event gateway instance. You use this value in the CFML GetGatewayHelper and SendGatewayMessage functions.
  • The event gateway type, which you select from the available event gateway types, such as SMS or Socket.
  • The absolute path to the listener CFC or CFCs that will handle incoming messages. If you have multiple listener CFCs, enter the paths separated by commas. You must specify absolute file paths, even if you put the CFCs in the ColdFusion MX gateway\cfc directory.
  • A configuration file, if required for this event gateway type or instance.
  • The event gateway start-up status; one of the following:

    Automatic Start the event gateway when ColdFusion starts.

    Manual Do not start the event gateway with ColdFusion, but allow starting it from the ColdFusion MX Administrator Event Gateways list.

    Disabled Do not allow the event gateway to start.


Developing an event gateway application

All event gateway applications handle information. They exchange event messages, and possibly other types of information, with other resources. Event gateway applications require a listener CFC to handle events that are sent to the event gateway. Event gateway applications can also use the following code elements:

  • SendGatewayMessage CFML functions to send messages from outside the listener CFC (or, optionally, from the CFC)
  • GatewayHelper objects
  • The eventgateway log file

The following sections provide an overview of how an application can send information:

  • Event gateway application models
  • Sending information to the event gateway
  • Developing event gateway listener CFCs
  • Sending a message using the SendGatewayMessage function
  • Using the GatewayHelper object
  • Using the event gateway error log file


Event gateway application models

Event gateway applications follow one or both of the following models:

  • Responder applications Where event messages from external sources initiate a response from a ColdFusion listener CFC
  • Initiator applications Where a ColdFusion application generates event messages to send out using the event gateway

Unlike other ColdFusion applications, responder applications are request-free. They do not have CFM pages, just CFCs, and they do not respond to HTTP requests. Instead, ColdFusion the event gateway service deliver the event messages directly to the listener CFC, and the CFC listener method returns any response directly to the event gateway service. Applications that allow mobile phone owners to get a news feed, check for text messages, or request other forms of information follow this model.

Initiator applications are similar to most ColdFusion applications. At some point, ColdFusion executes a CFM page in response to a request. (The request could be initiated by the ColdFusion MX Administrator Scheduled Tasks page.) ColdFusion sends a message to the event gateway when the application calls a CFML SendGatewayMessage function. An application that uses SMS to notify customers when orders have been shipped follows this model.


Sending information to the event gateway

A ColdFusion application can send an outgoing message to the event gateway in either of the following ways:

  • In a cfreturn tag in the listener CFC’s listener method
  • By calling the ColdFusion SendGatewayMessage function

The first method is useful to automatically respond to incoming messages. Some complex applications that respond to incoming messages might use the SendGatewayMessage function either in place or in addition to the return value.

Some event gateway types also use a GatewayHelper object to send information to external resources. For example, the ColdFusion MX XMPP and Lotus Sametime instant messaging event gateways provide a GatewayHelper object that can manage buddy lists, and set configuration and status information on the instant messaging server. For more information on the GatewayHelper object, see Using the GatewayHelper object. For more information on the instant messaging GatewayHelper object, see Sample IM message handling application.

The example code in Example event gateway CFC shows the use of a listener return value, and indicates how event gateways can require different data in the return structure to send equivalent messages.


Developing event gateway listener CFCs

The listener CFC responds to event gateway messages. The listener CFC uses, at a minimum, the following basic software elements:

  • One or more listener methods
  • CFEvent structures that contain the messages

Listener CFCs can use ColdFusion persistent scopes to store data that needs to be preserved over multiple CFC invocations or shared with other CFML elements.

Listener methods

The ColdFusion event gateway service calls one or more listener methods in the CFC to process incoming messages. The number of listener methods that you must write and their names depends on the event gateway. For example, the ColdFusion SMS event gateway requires a single listener method, which is typically named onIncomingMessage. (You can change the SMS event gateway listener method name in the event gateway configuration file.) The ColdFusion XMPP IM event gateway expects the listener CFC to have five methods: onIncomingMessage, onAddBuddyRequest, onAddBuddyResponse, onBuddyStatus, and onIMServerMessage. By default, if the event gateway does not specify the method name, ColdFusion calls the listener CFC’s onIncomingMessage method. For the sake of consistency, Macromedia recommends that any event gateway with a single listener method use the onIncomingMessage method.

The listener method does the following:

  1. Takes a single parameter, a CFEvent structure, described in the following section.
  2. Processes the contents of the instance as required by the application.
  3. Optionally, returns an outgoing message to the event gateway in a cfreturn tag. It can also send a message back to the event gateway by calling the ColdFusion SendGatewayMessage function.

The following code shows a listener CFC with an onIncomingMessage method that echoes a message back to the Socket event gateway that sent it. It contains the minimum code required to process an incoming message and respond to the sender using the socket gateway.

<cfcomponent displayname="echo" hint="echo messages from the event gateway">
    <cffunction name="onIncomingMessage" output="no">
        <cfargument name="CFEvent" type="struct" required="yes">
        <!--- Create a return structure that contains the message. --->
        <cfset retValue = structNew()>
        <cfset retValue.DestinationID = arguments.CFEvent.OriginatorID>
        <cfset retValue.MESSAGE = "Echo: " & arguments.CFEvent.Data.MESSAGE>
        <!--- Send the return message back. --->
        <cfreturn retValue>
    </cffunction>
</cfcomponent>

Other event gateways require different fields in the return structure. For example, to echo a message using the SMS event gateway, you use the following lines to specify the return value:

<cfset retValue.command = "submit">
<cfset retValue.sourceAddress = arguments.CFEVENT.gatewayid>
<cfset retValue.destAddress = arguments.CFEVENT.originatorid>
<cfset retValue.ShortMessage = "Echo: " & arguments.CFEvent.Data.MESSAGE>

The CFEvent structure

The ColdFusion event gateway service passes a CFEvent structure with information about the message event to the listener method. The following table describes the structure’s fields:

Field | Description
GatewayID | The event gateway that sent the event; the value is the ID of an event gateway instance configured on the ColdFusion MX Administrator Gateways page. If the application calls the SendGatewayMessage function to respond to the event gateway, it uses this ID as the function’s first parameter.
Data | A structure containing the event data, including the message. The Data structure contents depend on the event gateway type.
OriginatorID | The originator of the message. The value depends on the protocol or event gateway type. Many event gateways require this value in response messages to identify the destination of the response. Identifies the sender of the message.
GatewayType | The type of event gateway, such as SMS. An application that can process messages from multiple event gateway types can use this field. This value is the gateway type name that is specified by the event Gateway class. It is not necessarily the same as the gateway type name in the ColdFusion MX Administrator.
CFCPath | The location of the listener CFC. The listener CFC does not need to use this field.
CFCMethod | The listener method that ColdFusion invokes to process the event. The listener CFC does not need to use this field.
CFCTimeout | The time-out, in seconds, for the listener CFC to process the event request. The listener CFC does not need to use this field.

When a ColdFusion application responds to an event gateway message, or sends a message independently, it does not use a CFEvent structure. However, the ColdFusion event gateway service creates a Java CFEvent instance with the message data before calling the event gateway’s outgoingMessage method.

Using persistent scopes in listener CFCs

ColdFusion listener CFCs can use the Application, Client, and Session persistent scopes.

Because incoming event gateway messages are not associated with HTTP requests, ColdFusion uses different session and client IDs for interactions initiated by these events than for CFM Page requests, as follows:

Identifier | Structure
Session ID | gatewayType_gatewayID_originatorID
cfid | originatorID
cftoken | gatewayType_gatewayID
.

The gatewayID value is the event gateway ID that you set in the ColdFusion MX Administrator, and gatewayType and originatorID are the values that the event gateway sets in the CFEvent instance for an incoming message.

Application scope

The Application scope lets the CFC share data with any ColdFusion page or CFC that uses the same application name. This way, a listener CFC can use the same Application scope as CFML pages that might be used to send messages. Also, you can put multiple listener CFCs in a single directory and have them share an Application.cfc or Application.cfm file and application name.

As with all ColdFusion code, use the Application.cfc This.name variable or the cfapplication tag to set the application name. The listener CFC can use an Application.cfc or Application.cfm file if the CFC is in a directory that is in or under one of the following places:

  • the ColdFusion web root
  • a directory that is in the ColdFusion MX Administrator Mappings list.

The ColdFusion MX installer creates a mapping in the ColdFusion MX Administrator for the gateway\cfc directory.

Client scope

The Client scope can store long-term information associated with a message sender’s ID. For example, it can store information about an IM buddy.

To use Client variables across multiple connections, your gateway type must use the same client ID for all interactions with a particular client. For many technologies and gateways, such as the IM and SMS gateways, this is not an issue.

Note: To use Client scope variables with gateways, you must store the Client scope variables in a data source or the registry. You cannot store the variables in cookies, because gateways do not use cookies.

Session scope

The Session scope can store information required across multiple interactions. For example, an interactive IM or SMS application that uses a drill-down menu to select a service can store the information about the menu selections in the Session scope.

Event gateway sessions terminate when they time out. Because the identifiers for event sessions and clients differ from those used for request-driven sessions and clients, you cannot use the same Session or Client scope on a standard CFM page that sends an outgoing message and in a listener CFC that might handle an incoming response to that message.

For an example of using the Session scope, see the example Menu application in the gateway\cfc\examples\menu directory.

Note: ColdFusion cannot create a session if an initiator application uses a SendGatewayMessage method to start an interaction with a client, such as an SMS user. In this case, the sending code must keep track (for example, in a database) of the messages it sends and their destinations. When a response event arrives, it can look up the origniatorID to determine whether it was in response to an outgoing message.

Debugging event gateway CFCs

When an event gateway CFC responds to an event, it cannot display debugging information in the response page, as CFM pages do. As a result, many of the normal ColdFusion debugging techniques, including the cfdump tag, are not available. When you develop event gateway CFCs, you should consider the following debugging techniques:

  • Put trace variables in the Application scope. These variables persist, and you can specify an application name for your CFC, as described in Application scope. You can inspect the Application scope contents, including your trace variables, in any CFML page that has the same application name as your CFC.
  • Use cflog tags to help you trace any errors by logging significant events to a file. Also, carefully inspect the eventgateway.log and exceptions.log files that ColdFusion MX maintains. For more information on using the eventgateway.log file, see The eventgateway.log file.
  • You can simulate responses from CFCs to the event gateway by using the SendGatewayMessage function in a CFM page. The function’s message parameter should contain the information that the CFC would put in its return variable.
  • If you run ColdFusion MX from the command line, you can use the Java System.out.println method to write messages to the console window, as the following code shows:
    <cfscript>
    sys = createObject("java", "java.lang.System");
    sys.out.println("Debugging message goes here");
</cfscript>

Note: You do not have to restart the event gateway instance when you make changes to a CFC. ColdFusion MX automatically uses the updated CFC when the next event occurs.

Example event gateway CFC

The following code shows a temperature scale converter tool that can work with any of several event gateways: SMS, XMPP, Lotus Sametime, or the example Socket event gateway. Users enter a string that consists of the temperature scale (F, Fahrenheit, C, or Celsius), a comma, and a temperature on their device. The CFC converts Celsius to Fahrenheit or Fahrenheit to Celsius, and returns the result.

This example shows how a responder event gateway application can work, and illustrates how different event gateway types require different outgoing message formats:

<cfcomponent displayname="tempconverter" hint="Convert temperatures between
    Celsius and Fahrenheit">

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Standard error message giving the correct input format. --->
    <cfset var errormsg = "Please enter scale, integer where scale is F or C,
        for example:  F, 32">

    <!--- Get the message. --->
    <cfset data=cfevent.DATA>
    <cfset message="#data.message#">
    <!--- Where did it come from? --->
    <cfset orig="#CFEvent.originatorID#">

    <!--- Process the input, generate a message with the new temperature. --->
    <!--- Input format is: degrees, temperature. --->
    <cfif listlen(message) eq 2>
        <cfif (listgetat(message,1) IS "F") OR
                (listgetat(message,1) IS "Fahrenheit") OR
                (listgetat(message,1) IS "C") OR
                (listgetat(message,1) IS "Celsius")>
            <cfset scale=listgetat(message,1)>
            <cfif isNumeric(listgetat(message,2))>
                <cfset temperature=listgetat(message,2)>
                <cfswitch expression="#scale#">
                    <cfcase value="F, Fahrenheit">
                        <cfset retmsg = temperature & " degrees Fahrenheit is "
                            & (temperature-32.0) * (5.0/9.0) & " degrees Celsius">
                    </cfcase>
                    <cfcase value="C, Celsius">
                        <cfset retmsg = temperature & " degrees Celsius is "
                            &  (temperature * 9.0/5.0) + 32 & " degrees Fahrenheit">
                    </cfcase>
                </cfswitch>
            <cfelse>
                <cfset retmsg=errormsg>
            </cfif>
        <cfelse>
            <cfset retmsg=errormsg>
        </cfif>
    <cfelse>
        <cfset retmsg=errormsg>
    </cfif>

    <!--- Fill the return value as required for the event gateway type. --->
    <cfif arguments.CFEVENT.GatewayType is "Socket">
        <cfset retValue = structNew()>
        <cfset retValue.MESSAGE = retmsg>
        <cfset retValue.originatorID = orig>
    <cfelseif (arguments.CFEVENT.GatewayType is "Sametime") OR
            (arguments.CFEVENT.GatewayType is "XMPP")>
        <cfset retValue = structNew()>
        <cfset retValue.MESSAGE = retmsg>
        <cfset retValue.BuddyID = arguments.CFEVENT.DATA.SENDER>
        <cfset retValue.originatorID = orig>
    <cfelseif arguments.CFEVENT.GatewayType is "SMS">
        <cfset retValue = structNew()>
        <cfset retValue.command = "submit">
        <cfset retValue.sourceAddress = arguments.CFEVENT.gatewayid>
        <cfset retValue.destAddress = arguments.CFEVENT.originatorid>
        <cfset retValue.shortMessage = retmsg>
    </cfif>

    <!--- Send the return message back. --->
    <cfreturn retValue>

</cffunction>
</cfcomponent>


Sending a message using the SendGatewayMessage function

The SendGatewayMessage function has the following format:

SendGatewayMessage(gatewayID, messageStruct)

  • The gatewayID parameter must be the gateway ID specified in the ColdFusion MX Administrator for the event gateway instance that will send the message.
    •

  • The messageStruct parameter is a structure whose contents depends on the requirements of the event gateway’s outgoingMessage method, and possibly the recipient application. For example, in addition to any message, the structure might include a destination identifier.
    •

The CFEvent instance passed to the event gateway contains these two parameters in the GatewayID and Data fields; the remaining fields are empty.

The following example sends a message to a logging CFC, which logs information to a file. If the SendGatewayMessage function returns "OK", the example code displays a message. The code uses an instance of the asynchronous CFML event gateway named Asynch Logger. The props variable used in the messageStruct parameter has two entries, the destination file and the message to log.

<cfscript>
    status = "No";
    props = structNew();
    props.Message = "Replace me with a variable with data to log";
    status = SendGatewayMessage("Asynch Logger", props);
    if (status IS "OK") WriteOutput("Event Message ""#props.Message#"" has been sent.");
</cfscript>

Note: To see the code for the CFC that logs the information, see Using the CFML event gateway for asynchronous CFCs.


Using the GatewayHelper object

The ColdFusion GetGatewayHelper function tells ColdFusion to create and initialize a Java GatewayHelper object that provides event gateway-specific helper methods and properties. To use this function, the event gateway must implement a GatewayHelper class. For example, an instant messaging event gateway might make buddy list management methods available in a GatewayHelper object.

The ColdFusion GetGatewayHelper function takes a single parameter, the ID of the event gateway instance that provides the helper, and returns a GatewayHelper Java object. The parameter value must be the gateway ID for the instance that is specified in the ColdFusion MX Administrator. If you do not want to hard-code an ID value in the application (for example, if your listener CFC can respond to multiple event gateway instances), get the gateway ID from the CFEvent structure of the first incoming message.

The CFML code accesses the GatewayHelper object’s methods and properties using standard ColdFusion Java object access techniques, as described in Integrating J2EE and Java Elements in CFML Applications. For example, if an event gateway’s GatewayHelper class includes an addBuddy method that takes a single String parameter, you could use the following code to get the ColdFusion MX XMPP or Sametime gateway GatewayHelper object and add a buddy to the buddies list:

<cfscript>
    myHelper = GetGatewayHelper(myGatewayID);
    status = myHelper.addBuddy("jsmith23", "Jim Smith", "support");
</cfscript>


Using the event gateway error log file

When a standard ColdFusion MX event gateway encounters an error that does not prevent the event gateway from continuing to process, it logs it to the eventgateway.log file in the ColdFusion MX logs directory. Other event gateways can also to log information in this file, or to other application-specific files in the logs directory.

The standard ColdFusion MX event gateways log errors in interaction with any messaging server, errors in messages sent by the ColdFusion application, and recoverable errors in event gateway operation. The event gateways also log informational status messages for significant normal events, including event gateway initialization and restarts.

ColdFusion MX event gateway messages in the eventgateway.log file normally have the following format:

gatewayType (gatewayID) message body

When you are developing an event gateway application, you can use the ColdFusion Log viewer to inspect the eventgateway.log file and filter the display by using the gateway type and possibly the gateway ID as keywords. By selecting different severity levels, you can get a good understanding of errors and possible inefficiencies in your application and event gateway operation.


Deploying event gateways and applications

To deploy an event gateway application in a ColdFusion server, you must install your listener CFC and configure an gateway instance that uses the CFC.

To deploy an event gateway application

  1. Ensure that the ColdFusion MX Administrator is configured with the required event gateway type. If it is not, deploy the event gateway type as described in Deploying an event gateway.
  2. If the event gateway type requires a configuration file, ensure that there is a valid file in the gateway\config directory. Some event gateways might be designed to let multiple event gateway instances share a configuration file. Others might require a separate file for each event gateway instance.
  3. Install the event gateway application listener CFC and any other application components. ColdFusion MX provides a cf_root\gateways\cfc directory as a convenient location for these CFCs, and includes a mapping in the ColdFusion MX Administrator page for that directory. However, ColdFusion does not require you to install the listener CFC in this directory.
  4. Configure an event gateway instance on the Gateways page of the Event Gateways section in the ColdFusion MX Administrator, as described in Configuring an event gateway instance.


Using the CFML event gateway for asynchronous CFCs

The ColdFusion MX CFML event gateway lets CFML code send a message to CFC methods asynchronously. This event gateway lets you initiate processing by a CFC method without waiting for it to complete or return a value. Possible uses for asynchronous CFCs that you access using this event gateway include the following:

  • Reindexing a Verity collection with new information without delaying an application, for example, when a user uploads a new file
  • Logging information, particularly if there is significant amount of data to log
  • Running batch processes that might take a substantial amount of time to complete

Because asynchronous CFCs run independently of a request, they do not provide feedback to the user. You must save any results or error information to a file, data source, or other external resource.

By default, ColdFusion delivers the message to a CFC method named onIncomingMessage. You can specify any method name, however, in the SendGatewayMessage method’s data parameter.

CFML event gateway data structure

The structure that you use in the CFML SendGatewayMessage function can include two types of fields:

  • The structure can include any number of fields with arbitrary contents for use in by the CFC.
  • Several optional fields can configure how the gateway delivers the information to the CFC.

The CFML gateway looks for the following optional fields, and, if they exist, uses them to determine how it delivers the message. Do not use these field names for data that you send to your CFC method.

Field | Use
cfcpath | Overrides the CFC path specified in the ColdFusion MX Administrator. This field lets you use a single gateway configuration in the ColdFusion MX Administrator multiple CFCs.
method | Sets the name of the method to invoke in the CFC. The default method is onIncomingMessage. This field lets you use a single gateway configuration in the ColdFusion MXAdministrator for a CFC that has several methods.
originatorID | Sets the originatorID field of the CFEvent object that ColdFusion MX delivers to the CFC. The default value is CFMLGateway.
timeout | Sets the time-out, in seconds, during which the listener CFC must process the event request and return before ColdFusion gateway services terminates the request. The default value is the Timeout Request value set on the Server Settings page in the ColdFusion MX Administrator. Set this value if a request might validly take longer to process than the default timeout; for example, if the request involves a very long processing time.

Using the CFML gateway

The following procedure describes how to use an asynchronous CFC that has a single, onIncomingMessage method.

To use an asynchronous CFC:

  1. Create a CFC with an onIncomingMessage method. Put the CFC in an appropriate directory for your application. For example, you can put it in the cf_root\WEB-INF\cfusion\gateway\cfc directory on J2EE configurations, in the cf_root\gateway\cfc directory on server configurations, or in a subdirectory of these directories. ColdFusion MX is installed with mappings to these cfc gateway directories.

    The onIncomingMessage method must take a CFEvent structure that contains input information in its Data field, and processes the contents of the Data field as needed.

  2. Use the Gateways page in the ColdFusion MX Administrator to add an instance of the CFML event gateway type. Specify the following:
    • A unique Gateway ID.
    • The path to the CFC that you created in step 1.
    • The startup mode. Select Automatic startup mode to start the event gateway when ColdFusion MX starts up.
    • Do not specify a configuration file.
  3. Start the event gateway instance.
  4. Write CFML code that uses SendGatewayMessage functions to send messages in structures to the event gateway instance ID that you specified in step 2. The SendGatewayMessage function returns true if the gateway successfully queues the message in the ColdFusion MX Gateway Service; false, otherwise. It does not ensure that the CFC receives or processes the message.
  5. Run your CFML application.

Example: logging messages

The following asynchronous CFML event gateway CFC uses the cflog tag to log a message to a file in the ColdFusion MX logs directory. The CFC takes a message with the following fields:

  • file The name of the file in which to put the message. The default value is defaultEventLog.
  • type The cflog type attribute to use. The default value is info.
  • message The message text.
<cfcomponent>
    <cffunction name="onIncomingMessage" output="no">
        <cfargument name="CFEvent" type="struct" required="yes">
        <cfscript>
            if (NOT IsDefined("CFEvent.Data.file")) {
                CFEvent.Data.file="defaultEventLog"; }
            if (NOT IsDefined("CFEvent.Data.type")) {
                CFEvent.Data.type="info"; }
        </cfscript>
        <cflog text="#CFEvent.Data.message#"
             file="#CFEvent.Data.file#"
            type="#CFEvent.Data.type#"
            thread="yes"
            date="yes"
            time="yes"
            application="yes">
    </cffunction>
</cfcomponent>

The following minimal CFML page tests the event gateway:

Sending an event to the CFML event gateway that is registered in the
    ColdFusion MX Administrator as Asynch Logger.<br>
<cfscript>
    status = false;
    props = structNew();
    props.Message = "Replace me with a variable with data to log";
    status = SendGatewayMessage("Asynch Logger", props);
    if (status IS True) WriteOutput(’Event Message "#props.Message#" has been sent.’);
</cfscript>


Using the example event gateways and gateway applications

ColdFusion MX provides several example event gateways and applications in the cf_root\WEB-INF\cfusion\gateway directory on J2EE configurations or the cf_root\gateway directory on server configurations. These gateways provide example code that you can examine or use in developing your gateways. They are intended as examples only, and are not complete, product-quality, implementations.

This section describes the following topics:

  • Example event gateways
  • Menu example application


Example event gateways

The gateway\src\examples directory and its subdirectories include the sources for the example event gateways. Compiled versions are located in the gateway\lib\examples.jar file. The following sections briefly describe the event gateways and their functions. For more detailed information, see the code and comments in the files.

This section describes the following topics:

  • EmptyGateway
  • SocketGateway
  • DirectoryWatcherGateway
  • JMSGateway

EmptyGateway

The EmptyGateway.java file contains an event gateway template that you can use as a skeleton for creating your own event gateway. For more information on this class, and on creating new event gateways, see Creating Custom Event Gateways.

SocketGateway

The SocketGateway event gateway listens on a TCP/IP port. Therefore, you can use this gateway for applications that send and respond to messages using TCP/IP-based protocols such as Telnet, or for applications that send messages between sockets. For example, a simple gateway application that might respond to messages from a Telnet terminal client without supporting the full Telnet protocol.

Note: The ColdFusion MX Administrator uses Socket as the gateway type name for the SocketGateway class.

The SocketGateway.java file defines two classes: SocketGateway, the event gateway, and SocketHelper, a GatewayHelper class. The Source file is located in the gateway\src\examples\socket directory.

SocketGateway Listens on a TCP/IP port. This event gateway is multithreaded and can handle multiple clients simultaneously. It can send outgoing messages to existing clients, but cannot establish a link itself.

By default, the SocketGateway class listens on port 4445, but you can specify the port number in a configuration file. The file should contain a single line in the following format:

port=portNumber

SocketHelper A GatewayHelper class with the following methods:

  • getSocketIDs() returns an array containing the socket IDs of all Java sockets that are open. The event gateway opens a socket for each remote client.
  • killSocket(String socketid) Removes the specified socket. Returns a Boolean success indicator.

DirectoryWatcherGateway

The DirectoryWatcherGateway event gateway sends events to the listener CFC when a file is created, deleted, or modified in a directory. The watcher runs in a thread that sleeps for an interval specified in the configuration file, and when the interval has passed, checks for changes since the last time it was awake. If it finds added, deleted, or changed files, it sends a message to a listener CFC. You can configure separate CFCs for add, delete, and change events, or use a single CFC for all events. The source for this event gateway is located in the gateway/src/examples/watcher directory.

Note: The ColdFusion MX Administrator uses DirectoryWatcher as the gateway type name for the DirectoryWatcherGateway class.

Configuration file

This event gateway requires a configuration file, consisting of lines in the following format:

directory=C:/temp

Note: If you use backward slash characters (\) as directory separators in Windows the file paths, you must escape them by using double slashes, as in C:\\temp. You can use forward slashes (/) as the directory separator on all operating systems, including Windows.

The configuration file can have comment lines, preceded by a number sign (#). If you omit a property or comment it out, ColdFusion uses the default value. If you specify a property with no value, ColdFusion sets an empty property. The configuration file can define the following values:

Property | Req/Opt | Description
directory | Required | Path to the directory to watch.
recurse | Optional | Whether to check subdirectories. The default value is No.
extensions | Optional | Comma-delimited list of extensions to watch. The event gateway logs only changed files with these extensions. An asterisk (*) indicates all files. The default is all files.
interval | Optional | Number of milliseconds between the times that the event gateway checks the directory. The default value is 60 seconds.
addFunction | Optional | Name of the function to call when a file is added. The default value is onAdd.
changeFunction | Optional | Name of the function to call when a file is changed. The default value is onChange.
deleteFunction | Optional | Name of the function to call when a file is deleted. The default value is onDelete.

An example configuration file is located in the gateway\config\directory-watcher.cfg file.

CFC methods

When the directory contents change, the event gateway calls one of the following CFC listener methods, unless you change the names in the configuration file:

  • onAdd
  • onChange
  • onDelete

The CFEvent.Data field sent to the listener methods includes the following fields:

Field | Description
TYPE | Event type, one of ADD, CHANGE, DELETE.
FILENAME | Name of the file that was added, deleted, or changed.
LASTMODIFIED | The date and time that the file was created or modified. This field is not included if the file was deleted.

The event gateway supports multiple listener CFCs and sends the event messages to all listeners. The event gateway is one-way; it watches for events and dispatches event information to a CFC, but it does not accept return values from the CFC or input from SendGatewayMessage functions.

The directory watcher logs errors to the watcher.log file in the ColdFusion logs directory.

Example DirectoryWatcher application

The following code shows a simple directory watcher application. It enters a line in a log file each time a file is added, deleted, or changed in the directory specified in the configuration file. ColdFusion MX includes the date and time that a log entry is made. However, if the directory watcher monitors changes infrequently, for example once every minute or more, the time in the log entry might differ from the time a file was added or changed, so the information includes the time (but not date) for these actions.

<cfcomponent>
<cffunction name="onAdd" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <cfset data=CFEvent.data>
    <cflog file="MydirWatcher" application="No"
        text="ACTION: #data.type#;  FILE: #data.filename#;
        TIME: #timeFormat(data.lastmodified)#">
</cffunction>

<cffunction name="onDelete" output="no">
  <cfargument name="CFEvent" type="struct" required="yes">
  <cfset data=CFEvent.data>
  <cflog file="MydirWatcher" application="No"
      text=" ACTION: #data.type#;  FILE: #data.filename#">
</cffunction>

<cffunction name="onChange" output="no">
  <cfargument name="CFEvent" type="struct" required="yes">
  <cfset data=CFEvent.data>
  <cflog file="MydirWatcher" application="No"
        text=" ACTION: #data.type#;  FILE: #data.filename#;
        TIME: #timeFormat(data.lastmodified)#">
</cffunction>
</cfcomponent>

JMSGateway

The JMSGateway class acts as a Java Messaging Service consumer or producer. The source for this event gateway is located in gateway/src/examples/JMS. The gateway requires a configuration file, which is in gateway/config/jmsgateway.cfg. For full documentation of the configuration options, See the configuration file. The ColdFusion MX Administrator lists the compiled gateway (which is included in the gateway\lib\examples.jar file) on the Gateway Types page.

Note: The ColdFusion MX Administrator uses JMS as the gateway type name for the JMSGateway class.

Using the JMS Gateway as a consumer

The JMSGateway class creates a subscriber to the topic specified in the configuration file. The gateway consumes the following types of messages:

  • TextMessage
  • BytesMessage containing raw UTF-8 text

The gateway passes the contents of the message to the configured CFC in the event structure, as follows:

Field | Contents
data.id | Message correlation ID
data.msg | Text of the message
gatewayType | Gateway type: JMS
originatorID | Topic name from which the message was consumed

The listener CFC method must be named onIncomingMessage. If the CFC method does not send a message in response, it should return a structure containing a status field with a value of OK or EXCEPTION. (In this case, The gateway checks the return status field, but does not process these return values further.) To send a message, the CFC method must return a structure as documented in the following section.

Using the JMS Gateway as a producer

To send a JMS message, the return value of your CFC method or the second, messageStruct, parameter to the SendGatewayMessage function must be a structure with the following fields:

Field

Contents

status

Must be SEND.

topic

Name of the topic to publish the message to.

id

(Optional) The JMS correlation ID to associate with the message. The default is null.

message

Text of the message to publish.

asBytes

(Optional) How to publish the message:

  • If omitted, no, or false, send the message as text.
  • If any other value, send the message as byte-encoded UTF-8.

If you send the message in a SendGatewayMessage function, the function returns OK if the gateway sends the message, or EXCEPTION if it fails to send the message.


Menu example application

ColdFusion MX is installed with a menu-based responder application. The menu application is written to work with any of the standard ColdFusion MX event gateways (SMS, XMPP, and Sametime) and with the Socket example event gateway, and ColdFusion MX is preconfigured with an instance of the application that uses SMS, as follows:

  • The Gateways page in the ColdFusion MX Administrator includes a gateway instance for this application that uses the SMS gateway type.
  • The gateway/cfc/examples/menu directory and its subdirectories include the CFML for the application
  • The gateway/config/sms-test.cfg file is configured to use this application with the SMS client (phone simulator), and short message service center (SMSC) server simulator that are provided with ColdFusion MX.

The application presents users with a drill-down menu of tools that they can use, including a weather report, stock information, status and configuration information, and language tools such as a dictionary.

The code for this application is relatively complex and is distributed among 13 files. The following brief description provides an overview of how it works. To get a full understanding of how the application works, see the source code.

  • The top level, menu, directory contains two files: Application.cfm and main.cfc.
  • The Application.cfm file consists of a single cfapplication tag that enables session management and names the application. Session variables maintain the current state information of the session, such as the active menu, and so on.
  • The main.cfc file contains the master CFC; the event gateway configuration in ColdFusion MX Administrator uses it as the listener CFC. The main CFC file processes CFEvent structures from the event gateway. It does the following:
    1. Inspects the gatewayType field to determine the rest of the structure contents. This is necessary because different event gateways put the message in fields with different names.
    2. If a Session.menu variable does not exist, initializes the menu system. To do so, it calls methods in two other CFCs: menu and menunode. These two CFCs contain the menu system code.
    3. Calls the session.menu.process method to process the user’s input. This method can dispatch a message to an individual application for processing, if appropriate.
  • The apps directory contains several CFCs. Each file contains the code for a single application, such as the weather report or dictionary lookup (definition.cfc).

To use the menu application with the Socket event gateway:

  1. On the Gateway Settings page in the ColdFusion MX Administrator, click the Start SMS Test Server button.
  2. On the Gateways page in the ColdFusion MX Administrator, start the SMS Menu App - 5551212 event gateway by clicking the green play button (third button from the left in the Actions column). If the Status does not say Running after a few seconds, click Refresh to check that the server started.
  3. In the cf_root\WEB-INF\cfusion\bin directory on J2EE configurations or the cf_root\bin directory on server configurations, run the SMSClient.bat file (on Windows) or SMSClient.sh file (on UNIX or Linux) to start the SMS phone simulator. The simulator is preconfigured by default to "call" the default SMS event gateway configuration.
  4. Enter any character by typing or by using the mouse to click the simulator keypad, and press Enter on your keyboard or click Send on the simulator.
  5. The menu application responds with the top-level menu. Enter L for language tools such as a dictionary and thesaurus, S to get stock quotes or weather forecasts, or C to get information about the server. Press Enter on your keyboard or click Send on the simulator.
  6. The application displays a submenu. For example, if you select S in step 5, the options are Q for a stock quote, W for weather, or B to go back to the previous menu. Enter your selection.
  7. The application requests information such as a Zip code for the weather, stock symbol for a price, word for the dictionary, and so on. Enter and send the required information (or enter B to go back to the menu).
  8. The application gets and displays the requested information. Depending on the application, you might also be prompted to enter M to get more. Enter M (if there is more information available), another term, or B to return to the previous menu.
  9. Continue by entering menu items and detailed information requests.
  10. To exit, select File > Exit from the menu bar.

Previous


Using the Instant Messaging Event Gateways

This chapter describes how to develop an application that uses either of two instant message (IM) event gateway types provided with Macromedia ColdFusion MX: an IBM Lotus Sametime gateway, and an Extensible Messaging and Presence Protocol (XMPP) gateway. It briefly describes IM and the tools that ColdFusion MX provides for developing IM applications. It then describes how you can configure the IM event gateway and write and test applications that use the event gateway.

This chapter assumes that you are familiar with ColdFusion event gateway principles and programming techniques, as described in Using Event Gateways. It does not assume that you are familiar with instant messaging, but a basic knowledge is helpful.

Note: ColdFusion MX Standard Edition does not support event gateways.

Contents

About ColdFusion and instant messages

Configuring an IM event gateway

Handling incoming messages

Sending outgoing messages

Sample IM message handling application

Using the GatewayHelper object
Next


About ColdFusion and instant messages

ColdFusion includes two instant messaging gateway types: one for messaging using the XMPP protocol, and one for IBM Lotus Instant Messaging (Sametime). These gateway types use identical interfaces for sending and receiving messages and for managing the IM presence information and infrastructure. This chapter, therefore, refers to IM gateways, and only describes the two types where there are differences.

The ColdFusion IM gateways act as IM clients and let you do the following:

  • Send and receive instant messages.
  • Send and respond to buddy or friend requests and manage buddy/friend information.
  • Set and get status and other information.
  • Receive and handle messages from the IM server.

This section describes the following topics:

  • About XMPP
  • About IBM Lotus Instant Messaging (Sametime)
  • About IM application development and deployment
  • How the IM event gateway and provider interact

About XMPP

XMPP (Extensible Messaging and Presence Protocol) is an open, XML-based protocol for instant messaging. It is the core protocol of the Jabber Instant Messaging and Presence technology that is developed by the Jabber Software Foundation. As of November 2004, XMPP was defined by four Internet Engineering Task Force (IETF) specifications (RFCs), numbers 3920-3922. RFC 3920 covers the XMPP core, and 3921, covers instant messaging and presence. Numerous XMPP servers and clients are available. ColdFusion MX supports the IETF XMPP protocol.

The following websites provide additional information about the XMPP protocol:

  • Jabber Software Foundation: www.jabber.org/. This site includes information on available XMPP servers and clients.
  • IETF has copies of the internet standards for XMPP: www.ietf.org/rfc/.
  • The xmpp.org website was under development as of December 2004; at that time it included several useful links, including links to relevant specifications: www.xmpp.org/.

About IBM Lotus Instant Messaging (Sametime)

IBM Lotus Instant Messaging, commonly referred to as Lotus Sametime, is the IBM product for real-time collaboration. For more information about this product, see www.lotus.com/sametime.

About IM application development and deployment

The following sections introduce the ColdFusion IM application development tools and process, and discuss IM messaging providers.

ColdFusion MX IM gateway classes

ColdFusion provides the following instant messaging gateway classes:

XMPPGateway The class for the XMPP event gateway type

SAMETIMEGateway The class for the IBM Lotus Instant Messaging event gateway

You implement your IM application by configuring a gateway instance in ColdFusion MX Administrator that uses one of these gateway classes and creating a ColdFusion application that uses the gateway instance to communicate with an instant messaging server.

Application development and deployment process

The following is a typical process for developing and deploying an IM application:

  1. Design your application.
  2. Configure an IM event gateway instance to use an available XMPP or Lotus Sametime server.
  3. Write your CFCs, CFM pages, and any other application elements.
  4. Test your application using your XMPP or Lotus Sametime server and an appropriate client application.
  5. Deploy the application, as described in Deploying event gateways and applications.

How the IM event gateway and provider interact

Each IM event gateway instance has a single instant messaging ID. You must establish the ID and its related password on the IM server using server-specific tools, such as a standard instant messaging client. In ColdFusion MX, you set the ID, password, and other gateway-specific information in a gateway configuration file, and you create a gateway instance that uses this file.

When you start the gateway, it logs onto the IM server with the ID and password, and receives and sends the messages for the ID. The gateway sends incoming messages to a CFC, which you specify when you configure the gateway instance in the ColdFusion MX Administrator. The gateway passes outgoing messages from this CFC and from other CFML code to the IM server.

The IM event gateway also provides a number of helper methods for managing the gateway and its configuration information.


Incoming message handling

You write the following ColdFusion CFC methods to handle incoming messages and requests from the IM event gateway. These CFCs receive messages from the IM server and can respond to them by setting a return value.

CFC method | Message type
onIncomingMessage | Standard message from IM users.
onAddBuddyRequest | Requests from others to add the gateway ID to their buddy list.
onAddBuddyResponse | Responses from others to requests from your gateway to add them to your buddy lists. Also used by buddies to ask to be removed from your list.
onBuddyStatus | Presence status messages from other users.
onIMServerMessage | Error and status messages from the IM server.

For more information on these methods, see Handling incoming messages.

Outgoing message handling

Applications send outgoing instant messages using the CFML SendGatewayMessage method. Incoming message-handling CFC methods can also send messages, including responses to requests from others to add the ColdFusion gateway’s ID to their buddy list. For more information on sending messages, see Sending outgoing messages.

IMGatewayHelper methods

The ColdFusion IM gateway provides the IMGatewayHelper class, a gateway helper that you can access by calling the CFML GetGatewayHelper function. The IMGatewayHelper class has methods that let you do the following:

  • Get and set gateway configuration information and get gateway statistics
  • Get and set the gateway online presence status
  • Manage the gateway’s buddy list
  • Manage permissions for others to get information about the gateway status.

For more information on using GatewayHelper methods, including lists of all the methods, see Using the GatewayHelper object.


Configuring an IM event gateway

You provide IM-specific configuration information to the IM event gateway in a configuration file. You specify the configuration file location when you configure the IM event gateway instance in the ColdFusion MX Administrator. ColdFusion provides sample XMPP and Lotus Sametime event gateway configuration files in the cf_root\WEB-INF\cfusion\gateway\config directory on J2EE configurations, and cf_root\gateway\config directory on server configurations. The configuration file can have the following information.

Note: The default value in the table is the value the gateway uses if the configuration file omits the property, not the value in the default configuration files.

Property

Default value

Description

userID

none

(Required) The IM user ID to use to connect to the IM server.

password

none

(Required) Password for the user.

secureprotocol

none

XMPP only.

Required if you set securerequirement to true.

The protocol to use for secure communications. The following values are valid:

  • TSL
  • SSL

securerequirement

false

XMPP only.

Specifies whether the gateway must use secure communications. The following values are valid:

  • true
  • false

If this value is true, you must specify a secureprotocol value, and connections succeed only if a secure connection is established.

serverip

XMPP: jabber.org

Sametime: stdemo3.dfw.ibm.
com

Address of XMPP or Lotus Sametime server to which to send messages. Can be a server name or IP address.

serverport

XMPP: 5222

Sametime:1533

Port on the server to which to send the messages.

If the XMPP secureprotocol parameter is set to SSL, speechify 5223.

retries

-1

Integer number of times to retry connecting to the IM server on gateway startup or if the Gateway gets disconnected.

0 = do not to retry

-1 = try forever

retryinterval

5

Real number of seconds to wait between connection attempts. The minimum is 1 second.

onIncomingMessageFunction

onIncomingMessage

Name of CFC method to call to handle an incoming message. If you specify the property without a value, such as "onIncomingMessageFunction=", the gateway does not send this event to a CFC.

onAddBuddy
RequestFunction

onAddBuddy
Request

Name of CFC method to call to handle an incoming buddy request. If you specify the property without a value, the gateway does not send this event to a CFC.

onAddBuddy
ResponseFunction

onAddBuddy
Response

Name of CFC method to call to handle an incoming response to a buddy request sent by ColdFusion. If you specify the property without a value, the gateway does not send this event to a CFC.

onBuddyStatus
Function

onBuddyStatus

Name of CFC method to call to handle an incoming buddy status message, such as If you specify the property without a value, the gateway does not send this event to a CFC.

onIMServerMessage
Function

onIMServerMessage

Name of CFC method to call to handle an incoming message method. If you specify the property without a value, the gateway does not send this event to a CFC.

Note: If you do not have a CFC method to handle any of the event types, you must specify the corresponding property without a value. Use the following entry in the configuration file, for example, if you do not have a method to handle IMServerMessage events:
onIMServerMessageFunction=


Handling incoming messages

The IM event gateway handles five types of messages, and your CFC must implement a listener method for each message type. The following table describes the message-handling CFC methods and the messages they handle. It lists the default CFC method names; however, you can change the names in the gateway configuration file.

CFC method

Description

onIncomingMessage

Standard message from an IM user. The application processes the message body appropriately; for example, it could display the message in an interface window.

This method can return a response message to the sender.

onAddBuddyRequest

Request from another IM user to add your application’s IM ID to their buddy list. The CFC must determine whether to accept or reject the request, or to take no action. No action might be appropriate in cases where the request must be reviewed offline for approval and responses are sent at a later time.

The CFC returns a message with the decision as a command value and optionally a text message specifying the reason. If you accept the request, the requestor automatically gets added to the list of IDs that can get status information for the gateway. If you specify no action, ColdFusion does not respond.

onAddBuddyResponse

Response from another IM user to a request from the gateway to be added to their buddy list. The response message is accept or decline.

Your application can handle this response as appropriate; for example, to add or remove the ID from a list of message recipients.

This method does not return a value.

onBuddyStatus

Message indicating a gateway buddy’s status. Received when a buddy’s status changes; for example, from OFFLINE to ONLINE.

This method does not return a value.

onIMServerMessage

Status messages from the IM server, such as warning or error messages. The messages you might receive depend on the IM server that sends them. For information on the server messages, see the documentation for the IM server that your gateway instance uses.

This method does not return a value.

For detailed information on each method, including examples of their use, see IM Gateway CFC incoming message methods in CFML Reference. For an example that uses these functions, see Sample IM message handling application.


Sending outgoing messages

You use the SendGatewayMessage CFML function or the return value of a CFC listener method to send outgoing messages. The ColdFusion MX 7 IM gateway accepts the following outgoing message commands:

Command | Description
submit | (Default) Sends a normal message to another IM user.
accept | Accepts an add buddy request. Adds the buddy to the list of IDs that get your presence information and sends an acceptance message to the buddy ID.
decline | Declines an add buddy request and sends a rejection message to the buddy ID.
noact | Tells the gateway to take no action. The gateway logs a message that indicates that it took no action, and contains the gateway type, gateway ID, and buddy ID.

The message structure that you return in the gateway listener CFC function or use as the second parameter in the CFML SendGatewayMessage function can have the following fields. The table lists the fields and the commands in which they are used, and describes each field’s use.

Field | Commands | Description
buddyID | All | The destination user ID.
command | All | The command; if omitted, ColdFusion treats the message as a submit command.
message | submit | A text message to send to the destination user.
reason | accept, decline | A text description of the reason for the action or other message to send to the add buddy requestor.

In typical use, a ColdFusion application uses the accept, decline, and noact commands in the return value of the onAddBuddyRequest method, and uses the submit command (or no command, because submit is the default command) in SendGatewayMessage CFML functions and the return value of the onIncomingMessage CFC method.

The SendGatewayMessage CFML function can send any command, and might be used to send an accept or decline message. One possible use is in an application where someone must review all buddy requests before they are added. In this case, the onAddBuddyRequest CFC method could initially send a noact command in its return value, and save the request information in a database. Administrators could use a separate ColdFusion application to review the request information. This application could use the SendGatewayMessage function with an accept or decline command to act on the request and inform the requestor.

The following example onIncomingMessage method of a listener CFC echoes incoming IM messages to the message originator:

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <cfset retValue.MESSAGE = "echoing: " & CFEvent.DATA.message>
    <cfset retValue.BuddyID = arguments.CFEVENT.DATA.SENDER>
    <cfreturn retValue>
</cffunction>


Sample IM message handling application

The application described in this section consists of two CFCs: an employee phone directory lookup CFC that responds to an onIncomingMessage event, and a Gateway management CFC that responds to all other events. This example shows how an application can respond to events and send outgoing messages.

You can configure a gateway to use both CFCs by entering the paths to the two CFCs, separated by a comma, in the CFC Path field of the Add/Edit ColdFusion Event Gateways form on the Gateways page in the ColdFusion MX Administrator.

This section describes the following examples:

  • Phone directory lookup CFC
  • Status and request-handling CFC


Phone directory lookup CFC

The following CFC implements a simple employee phone directory lookup application. The user sends an instant message containing some part of the name to be looked up (a space requests all names). The onIncomingMessage response depends on the number matches.

  • If there is no match, the onIncomingMessage function returns a message indicating that there are no matches.
  • If there is one match, the function returns the name, department, and phone number.
  • If there are up to ten matches, the function returns a list of the names preceded by a number that the user can enter to get the detailed information.
  • If there are over ten matches, the function returns a list of only the first ten names. A more complex application might let the user get multiple lists of messages to provide access to all names.
  • If the user enters a number, and previously got a multiple-match list, the application returns the information for the name that corresponds to the number.

The following listing shows the CFC code:

<cfcomponent>
    <cffunction name="onIncomingMessage">
        <cfargument name="CFEvent" type="struct" required="YES">
        <!--- Remove any extra white space from the message. --->
        <cfset message =  Trim(arguments.CFEvent.data.MESSAGE)>
        <!--- If the message is numeric, a previous search probably returned a
            list of names. Get the name to search for from the name list stored in
            the Session scope. --->
        <cfif isNumeric(message)>
            <cfscript>
                if (structKeyExists(session.users, val(message))) {
                    message = session.users[val(message)];
                }
            </cfscript>
        </cfif>

        <!--- Search the database for the requested name. --->
        <cfquery name="employees" datasource="cfdocexamples">
            select FirstName, LastName, Department, Phone
            from Employees
            where 0 = 0
            <!--- A space indicates the user entered a first and last name. --->
            <cfif listlen(message, " ") eq 2>
                and FirstName like '#listFirst(message, " ")#%'
                and LastName like '#listlast(message, " ")#%'
            <!--- No space: the user entered a first or a last name. --->
            <cfelse>
                and (FirstName like '#listFirst(message, " ")#%'
                or LastName like '#listFirst(message, " ")#%')
            </cfif>
        </cfquery>

        <!--- Generate and  return the message.--->
        <cfscript>
            retrunVal = structNew();
            retrunVal.command = "submit";
            retrunVal.buddyID = arguments.CFEvent.data.SENDER;

            //No records were found.
            if (employees.recordCount eq 0) {
                retrunVal.message = "No records found for '#message#'";
            }
            //One record was found.
            else if (employees.recordCount eq 1) {
            // Whitespace in the message text results in bad formatting,
            // so the source cannot be indented.
                retrunVal.message = "Requested information:
#employees.firstName# #employees.lastName#
#employees.Department#
#employees.Phone#";
            }
            //Multiple possibilities were found.
            else if (employees.recordCount gt 1) {
                //If more than ten were found, return only the first ten.
                if (employees.recordCount gt 10)
                {
                    retrunVal.message = "First 10 of #employees.recordCount# records";
                }else{
                    retrunVal.message = "Records found: #employees.recordCount#";
                }
                // The session.users structure contains the found names.
                // The record key is a number that is also returned in front of the
                // name in the message.
                session.users = structNew();
                for(i=1; i lte min(10, employees.recordCount); i=i+1)
                {
                    // These two lines are formatted to prevent extra white space.
                    retrunVal.message = retrunVal.message & "
#i# - #employees.firstName[i]# #employees.lastName[i]#";
                    // The following two lines must be a single line in the source
                    session.users[i]="#employees.firstName[i]#
                        #employees.lastName[i]#";
                }
            }
            return retrunVal;
        </cfscript>
    </cffunction>
</cfcomponent>


Status and request-handling CFC

The following CFC handles all IM events, except onIncomingMessage. It maintains an Application scope buddyStatus structure that contains information on the gateway buddies. This structure limits the interactions that are needed with the IM server to get buddy and status information. The application also logs significant events, such as requests to add buddies and error messages from the IM server. In particular, it does the following:

  • The onBuddyStatus function updates the Application scope buddy status structure when the gateway gets an event message indicating that a buddy’s status has changed.
  • The onAddBuddyRequest function searches for the requested buddy’s name in a data source. If it finds a single instance of the name, it adds the buddy and updates the status in the Application scope buddyStatus structure. If it doesn’t find name, it declines the buddy request. If it finds multiple instances of the name, it tells the gateway to take no action. It also logs all actions.
  • The onAddBuddyResponse function adds the buddy to the Application scope buddy status structure if the buddy request is accepted, and sets the current status. It logs all responses.
  • The onIMServerMessage function logs all messages that it receives.

This example uses the IM_ID column of the Employees database of the cfdocexamples database that is included with ColdFusion MX 7. The entries in this column assume that you use an XMPP server "company." To run this example you must configure an XMPP server with this name and with clients with names in this database, or you must change the database entries to match IM server clients. You must also configure a gateway instance in the ColdFusion MX Administrator that uses this server.

The following listing shows the CFC code:

<cfcomponent>

<cffunction name="onBuddyStatus">
    <cfargument name="CFEvent" type="struct" required="YES">
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE">
        <cfscript>
        // Create the status structures if they don’t exist.
            if (NOT StructKeyExists(Application, "buddyStatus")) {
                Application.buddyStatus=StructNew();
            }
            if (NOT StructKeyExists(Application.buddyStatus, CFEvent.Data.BUDDYNAME)) {
                Application.buddyStatus[#CFEvent.Data.BUDDYNAME#]=StructNew();
            }
            // Save the buddy status and timestamp.
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].status=CFEvent.Data.BUDDYSTATUS;
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].timeStamp=CFEvent.Data.TIMESTAMP;
        </cfscript>
    </cflock>
</cffunction>

<cffunction name="onAddBuddyRequest">
    <cfargument name="CFEvent" type="struct" required="YES">
    <cfquery name="buddysearch" datasource="cfdocexamples">
        select IM_ID
        from Employees
        where IM_ID = '#CFEvent.Data.SENDER#'
    </cfquery>
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE">
        <cfscript>
            // If the name is in the DB once, accept; if it is missing, decline.
            // If it is in the DB multiple times, take no action.
            if (buddysearch.RecordCount IS 0) {
                action="decline";
                reason="Invalid ID";
            }
            else if (buddysearch.RecordCount IS 1) {
                action="accept";
                reason="Valid ID";
                //Add the buddy to the buddy status structure only if accepted.
                if (NOT StructKeyExists(Application,
                        "buddyStatus")) {
                    Application.buddyStatus=StructNew();
                }
                if (NOT StructKeyExists(Application.buddyStatus,
                        CFEvent.Data.SENDER)) {
                    Application.buddyStatus[#CFEvent.Data.SENDER#]=StructNew();
                }
                Application.buddyStatus[#CFEvent.Data.SENDER#].status=
                    "Accepted Buddy Request";
                Application.buddyStatus[#CFEvent.Data.SENDER#].timeStamp=
                    CFEvent.Data.TIMESTAMP;
                Application.buddyStatus[#CFEvent.Data.SENDER#].message=
                    CFEvent.Data.MESSAGE;
            }
            else {
                action="noact";
                reason="Duplicate ID";
            }
        </cfscript>
    </cflock>
    <!--- Log the request and decision information. --->
    <cflog file="#CFEvent.GatewayID#Status"
            text="onAddBuddyRequest; SENDER: #CFEvent.Data.SENDER# MESSAGE: #CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP# ACTION: #action#">
    <!--- Return the action decision. --->
    <cfset retValue = structNew()>
    <cfset retValue.command = action>
    <cfset retValue.BuddyID = CFEvent.DATA.SENDER>
    <cfset retValue.Reason = reason>
    <cfreturn retValue>
</cffunction>

<cffunction name="onAddBuddyResponse">
    <cfargument name="CFEvent" type="struct" required="YES">
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE">
        <cfscript>
            //Do the following only if the buddy accepted the request.
            if (NOT StructKeyExists(Application, "buddyStatus")) {
                Application.buddyStatus=StructNew();
                }
            if (#CFEVENT.Data.MESSAGE# IS "accept") {
                //Create a new entry in the buddyStatus record for the buddy.
                if (NOT StructKeyExists(Application.buddyStatus,
                        CFEvent.Data.SENDER)) {
                    Application.buddyStatus[#CFEvent.Data.SENDER#]=StructNew();
                }
                //Set the buddy status information to indicate buddy was added.
                Application.buddyStatus[#CFEvent.Data.SENDER#].status=
                    "Buddy accepted us";
                Application.buddyStatus[#CFEvent.Data.SENDER#].timeStamp=
                    CFEvent.Data.TIMESTAMP;
                Application.buddyStatus[#CFEvent.Data.SENDER#].message=
                    CFEvent.Data.MESSAGE;
            }
        </cfscript>
    </cflock>
    <!--- Log the information for all responses. --->
    <cflog file="#CFEvent.GatewayID#Status"
        text="onAddBuddyResponse; BUDDY: #CFEvent.Data.SENDER# RESPONSE: #CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP#">
</cffunction>

<cffunction name="onIMServerMessage">
    <!--- This function just logs the message. --->
    <cfargument name="CFEvent" type="struct" required="YES">
    <cflog file="#CFEvent.GatewayID#Status"
        text="onIMServerMEssage; SENDER: #CFEvent.OriginatorID# MESSAGE: #CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP#">
</cffunction>
</cfcomponent>


Using the GatewayHelper object

The CFML GetGatewayHelper function returns a GatewayHelper object with several methods that manage your gateway and buddy list. The GatewayHelper methods let you do the following:

  • Get and set gateway configuration information and get gateway statistics.
  • Get and set the gateway online status.
  • Manage the gateway’s buddy list
  • Manage permissions for others to get information about the gateway status.

The following sections briefly describe the class methods. For detailed information about each method, see IM Gateway GatewayHelper class methods in CFML Reference.

  • Gateway configuration information and statistics methods
  • Gateway online status methods
  • Gateway buddy management methods
  • Gateway permission management methods
  • GatewayHelper example


Gateway configuration information and statistics methods

The following table describes the methods that you can use to get and set configuration information and get gateway statistics:

Method | Description
getName | Returns the gateway’s user name.
getNickName | Returns the gateway’s display name (nickname).
getProtocolName | Returns the name of the instant messaging protocol (JABBER for XMPP, or SAMETIME).
numberOfMessagesReceived | Returns the number of messages received by the gateway since it was started.
numberOfMessagesSent | Returns the number of messages sent by the gateway since it was started.
setNickName | Sets the gateway’s display name (nickname).


Gateway online status methods

The following table describes the methods that you can use to get and set the gateway’s online availability status (presence information):

Method | Description
getCustomAwayMessage | Returns the gateway’s custom away message if it has been set by the setStatus method.
getStatusAsString | Returns the online status of the gateway.
getStatusTimeStamp | Returns the date/time that the gateway changed its online status.
isOnline | Returns True if the gateway is connected to the IM server; otherwise, returns false.
setStatus | Changes the gateway’s online status; for example, to away or idle.


Gateway buddy management methods

The following table describes the methods that you can use to manage the gateway’s buddy list:

Method | Description
addBuddy | Adds a buddy to the gateway’s buddy list and tells the IM server to send the gateway messages with the buddy’s online state.
getBuddyInfo | Gets information about the specified user from the buddy list, deny list, and permit list.
getBuddyList | Returns the gateway’s buddy list.
removeBuddy | Removes the specified user name from the gateway’s buddy list and tells the IM server to stop sending the gateway messages with the user’s online state.


Gateway permission management methods

The IM gateways can manage the information that other users can get about the gateway’s online status.

Note: XMPP permission management is included in the XMPP 1.0 specification, but several XMPP servers that were available at the time of the ColdFusion MX 7 release do not support permission management.

The following table describes the gateway permission management methods:

Method | Description
addDeny | Tells the IM server to add the specified user to the gateway’s deny list. If the permitMode is DENY_SOME, these users cannot receive messages on the gateway’s state.
addPermit | Tells the IM server to add the specified user to the server’s permit list. If the permitMode is PERMIT_SOME, these users receive messages on the gateway’s state.
getDenyList | Returns the list of users that the server has been told not to send state information to.
getPermitList | Returns the list of users that the server has been told to send state information to.
getPermitMode | Gets the gateway’s permit mode from the IM server. The permit mode determines whether all users can get the gateway’s online state information, or whether the server uses a permit list or a deny list to control which users get state information.
removeDeny | Removes the user from the gateway’s deny list.
removePermit | Removes the user from the gateway’s permit list.
setPermitMode | Sets the gateway’s permit mode on the IM server.


GatewayHelper example

This example lets you use the XMPP or SameTime GatewayHelper class to get and set status and other information, including managing buddy lists and view permissions lists.

<cfapplication name="gateway_tool" sessionmanagement="yes">

<!--- Set the gateway buddy name to default values.--->
<cfparam name="session.gwid" default="XMPP Buddy Manager">
<cfparam name="session.buddyid" default="hlichtin2@mousemail">

<!--- Reset gateway and buddy ID if form was submitted. --->
<cfif isdefined("form.submitbuddy")>
    <cfset session.buddyid=form.buddyid>
    <cfset session.gwid=form.gwid>
</cfif>

<!--- Display the current gateway and buddy ID. --->
<h3>Using the GatewayHelper</h3>
<!--- Form to display and reset gateway and Buddy ID. --->
<cfform action="#cgi.script_name#" method="post" name="changeIDs">
    Current buddy ID: <cfinput type="text" name="buddyid" value="#session.buddyid#"><br>
    Current gateway ID: <cfinput type="text" name="gwid" value="#session.gwid#"><br>
    <cfinput name="submitbuddy" value="Change gateway/buddy" type="submit">
</cfform>

<!--- When a buddy is set, display the links and forms to get and set
        information etc. Where form input is required, the form uses a GET method
        so all selections are represented by a url.cmd variable. --->

<cfoutput>
<h3>Select one of the following to get or set.</h3>
<ul>
    <li><a href="#cgi.script_name#?cmd=buddyinfo">buddyinfo</a>
    <li>LIST: <a href="#cgi.script_name#?cmd=buddylist">buddylist</a> |
        <a href="#cgi.script_name#?cmd=permitlist">permitlist</a> |
        <a href="#cgi.script_name#?cmd=denylist">denylist</a>
    <li>ADD: <a href="#cgi.script_name#?cmd=addbuddy">addbuddy</a> |
        <a href="#cgi.script_name#?cmd=addpermit">addpermit</a> |
        <a href="#cgi.script_name#?cmd=adddeny">adddeny</a>
    <li>REMOVE: <a href="#cgi.script_name#?cmd=removebuddy">removebuddy</a> |
        <a href="#cgi.script_name#?cmd=removepermit">removepermit</a> |
            <a href="#cgi.script_name#?cmd=removedeny">removedeny</a>
    <!--- NOTE: This list does not include OFFLINE because the gateway resets itself to online. --->
    <li>setStatus (XMPP):
        <cfloop list="ONLINE,AWAY,DND,NA,FREE_TO_CHAT" index="e">
            <a href="#cgi.script_name#?cmd=setstatus&status=#e#">#e#</a> |
        </cfloop>
    <li>setStatus (Sametime):
        <cfloop list="ONLINE,AWAY,DND,IDLE" index="e">
            <a href="#cgi.script_name#?cmd=setstatus&status=#e#">#e#</a> |
        </cfloop>
    <li>
        <form action="#cgi.script_name#" method="get">
            setStatus with CustomAwayMessage:
            <input type="hidden" name="cmd" value="setstatus2">
            <select name="status">
                <cfloop list="ONLINE,OFFLINE,AWAY,DND,IDLE,INVISIBLE,NA,OCCUPIED,FREE_TO_CHAT,ONPHONE,ATLUNCH,BUSY,NOT_AT_HOME,NOT_AT_DESK,NOT_IN_OFFICE,ON_VACATION,STEPPED_OUT,CUSTOM_AWAY" index="e">
                    <option value="#e#">#e#</option>
                </cfloop>
            </select>
            <input type="text" name="custommsg" value="(custom away massage)" size="30"/>
            <input type="submit"/>
        </form>
    <li>
        <form action="#cgi.script_name#" method="get">
            setNickName:
            <input type="hidden" name="cmd" value="setnickname">
            <input type="text" name="nickname" value="(enter nickname)">
            <input type="submit">
        </form>
--->
    <li>INFO: <a href="#cgi.script_name#?cmd=getname">getname</a> |
        <a href="#cgi.script_name#?cmd=getnickname">getnickname</a> |
        <a href="#cgi.script_name#?cmd=getcustomawaymessage">getcustomawaymessage</a> |
        <a href="#cgi.script_name#?cmd=getprotocolname">getprotocolname</a> |
        <a href="#cgi.script_name#?cmd=getstatusasstring">getstatusasstring</a> |
        <a href="#cgi.script_name#?cmd=isonline">isonline</a>
    <li>MESSAGE COUNT:
        <a href="#cgi.script_name#?cmd=numberofmessagesreceived">numberofmessagesreceived</a> |
        <a href="#cgi.script_name#?cmd=numberofmessagessent">numberofmessagessent</a>
    <li>RUNNING TIME: <a href="#cgi.script_name#?cmd=getsignontimestamp">getsignontimestamp</a> |
        <a href="#cgi.script_name#?cmd=getstatustimestamp">getstatustimestamp</a>
    <li>setPermitMode:
        <cfloop list="PERMIT_ALL,DENY_ALL,PERMIT_SOME,DENY_SOME,IGNORE_IN_LIST,IGNORE_NOT_IN_LIST"
                index="e"><a href="#cgi.script_name#?cmd=setpermitmode&mode=#e#">#e#</a> |
        </cfloop> <span class="note">doesn't work for XMPP</span>
    <li><a href="#cgi.script_name#?cmd=getpermitmode">getpermitmode</a>
    <li>setPlainTextMode:
        <cfloop list="PLAIN_TEXT,RICH_TEXT" index="e">
            <a href="#cgi.script_name#?cmd=setplaintextmode&mode=#e#">#e#</a> |
        </cfloop>
    <li><a href="#cgi.script_name#?cmd=getplaintextmode">getplaintextmode</a>
</ul>
</cfoutput>

<!--- The url.cmd value exists if one of the previous links or forms has been submitted, and identifies the type of request. --->
<cfoutput>
<cfif isdefined("url.cmd")>
    <!--- Get the GatewayHelper for the gateway. --->
    <cfset helper = getGatewayHelper(session.gwid)>
    <!--- Need to get the buddy list if requested the list or full buddy information. --->
    <cfswitch expression="#LCase(url.cmd)#">
        <cfcase value="buddylist,buddyinfo">
            <cfset ret=helper.getBuddyList()>
        </cfcase>
        <cfcase value="denylist">
            <cfset ret=helper.getDenyList()>
        </cfcase>
        <cfcase value="permitlist">
            <cfset ret=helper.getPermitList()>
        </cfcase>
        <cfcase value="addbuddy">
            <cfset ret=helper.addBuddy("#session.buddyid#",
                "#session.buddyid#", "")>
        </cfcase>
        <cfcase value="addpermit">
            <cfset ret=helper.addPermit("#session.buddyid#",
                "#session.buddyid#", "")>
        </cfcase>
        <cfcase value="adddeny">
            <cfset ret=helper.addDeny("#session.buddyid#",
                "#session.buddyid#", "")>
        </cfcase>
        <cfcase value="removebuddy">
            <cfset ret=helper.removeBuddy("#session.buddyid#", "")>
        </cfcase>
        <cfcase value="removepermit">
            <cfset ret=helper.removePermit("#session.buddyid#", "")>
        </cfcase>
        <cfcase value="removedeny">
            <cfset ret=helper.removeDeny("#session.buddyid#", "")>
        </cfcase>
        <cfcase value="setstatus">
            <cfset ret=helper.setStatus(url.status, "")>
        </cfcase>
        <cfcase value="setstatus2">
            <cfset ret=helper.setStatus(url.status, url.custommsg)>
        </cfcase>
        <cfcase value="getcustomawaymessage">
            <cfset ret=helper.getCustomAwayMessage()>
        </cfcase>
        <cfcase value="getname">
            <cfset ret=helper.getName()>
        </cfcase>
        <cfcase value="getnickname">
            <cfset ret=helper.getNickname()>
        </cfcase>
        <cfcase value="getprotocolname">
            <cfset ret=helper.getProtocolName()>
        </cfcase>
        <cfcase value="getsignontimestamp">
            <cfset ret=helper.getSignOnTimeStamp()>
        </cfcase>
        <cfcase value="getstatusasstring">
            <cfset ret=helper.getStatusAsString()>
        </cfcase>
        <cfcase value="getstatustimestamp">
            <cfset ret=helper.getStatusTimeStamp()>
        </cfcase>
        <cfcase value="isonline">
            <cfset ret=helper.isOnline()>
        </cfcase>
        <cfcase value="numberofmessagesreceived">
            <cfset ret=helper.numberOfMessagesReceived()>
        </cfcase>
        <cfcase value="numberofmessagessent">
            <cfset ret=helper.numberOfMessagesSent()>
        </cfcase>
        <cfcase value="setnickname">
            <cfset ret=helper.setNickName(url.nickname)>
        </cfcase>
        <cfcase value="setpermitmode">
            <cfset ret=helper.setPermitMode(url.mode)>
        </cfcase>
        <cfcase value="getpermitmode">
            <cfset ret=helper.getPermitMode()>
        </cfcase>
        <cfcase value="setplaintextmode">
            <cfset ret=helper.setPlainTextMode(url.mode)>
        </cfcase>
        <cfcase value="getplaintextmode">
            <cfset ret=helper.getPlainTextMode()>
        </cfcase>
        <cfdefaultcase>
            <cfset ret[1]="Error; Invalid command. You shouldn't get this.">
        </cfdefaultcase>
    </cfswitch>
    <br>
    <!--- Display the results returned by the called GatewayHelper method. --->
    <strong>#url.cmd#</strong><br>
    <cfdump var="#ret#">
    <br>
    <!--- If buddy information was requested, loop through buddy list to get
          information for each buddy and display it. --->
    <cfif comparenocase(url.cmd, "buddyinfo") is 0 and arraylen(ret) gt 0>
    <b>Buddy info for all buddies</b><br>
        <cfloop index="i" from="1" to="#arraylen(ret)#">
            <cfdump var="#helper.getBuddyInfo(ret[i])#" label="#ret[i]#"></cfloop>
    </cfif>
</cfif>
</cfoutput>
Previous


Using the SMS Event Gateway

This chapter describes how to develop an application that uses the short message service (SMS) event gateway type provided with Macromedia ColdFusion MX 7. It briefly describes SMS and the tools that ColdFusion MX 7 provides for developing SMS applications. It then describes how you can configure the SMS event gateway and write and test an application that uses the event gateway.

This chapter assumes that you are familiar with ColdFusion event gateway principals and programming techniques, as described in Using Event Gateways. It does not assume that you are familiar with SMS, but a basic knowledge would be helpful.

Note: ColdFusion MX Standard Edition does not support event gateways. ColdFusion MX Developer Edition limits connections so that each gateway can send messages to only a single SMS address.

Contents

About SMS and ColdFusion

Configuring an SMS event gateway

Handling incoming messages

Sending outgoing messages

ColdFusion MX SMS development tools
Next


About SMS and ColdFusion

Short Message Service (SMS) is a system designed for sending short, often text, messages to and from wireless devices, such as mobile phones or pagers. SMS is widely used in Europe and Asia and is becoming increasingly popular in the United States and elsewhere. Some uses for SMS include the following:

  • Performing banking transactions
  • Sending authentication codes, for example, to be used to access web resources
  • Voting, such as popularity voting for reality television shows
  • Initiating an action (such as a server reboot) and getting a response
  • Notifying users of events such as package shipments or restaurant table availability, or providing stock or weather alerts
  • Sending person-to-person text messages
  • Presenting interactive text-based menus on a cell phone
  • Providing cellular phone updates, such as direct download of logos
  • Providing telematics and mobile or remote wireless device applications, such as soda machines, vehicle tracking, smart gas pumps, and so on

SMS protocol features include, but are not limited to, the following:

  • Authentication verification is built in.
  • Communications can be secure.
  • Store and forward communication is performed in near real time.
  • Communications can be two-way and session-aware.
  • Mobile devices such as cell phones already include support; there is nothing to install on the client.

The following sections provide a very brief technical introduction to SMS and the procedures required to develop and implement an SMS ColdFusion application:

  • About SMS
  • About SMS application development and deployment
  • How the SMS event gateway and provider SMSC interact


About SMS

The following discussion simplifies SMS technology and describes only a typical use with a ColdFusion application. For a more complete discussion of SMS, see the publicly available literature, including the several books that discuss SMS.

In a ColdFusion SMS application, a mobile device such as a mobile phone communicates (via intermediate steps) with a message center, such as a short message service center (SMSC). For example, a mobile phone user calls a telephone number that the SMS provider has associated with your account; the SMSC gets the messages that are sent to this number. The SMSC can store and forward messages. A ColdFusion application can initiate messages to wireless devices, or it can respond to incoming messages from the devices.

The SMSC communicates with a ColdFusion SMS event gateway using short message peer-to-peer protocol (SMPP) over TCP/IP. Information is transferred by exchanging Protocol Data Units (PDUs) with structures that depend on the type of transaction, such as a normal message submission, a binary data submission, or a message intended for multiple recipients.

Because the SMSC is a store-and-forward server, it can hold messages that cannot be immediately delivered and try to deliver them when the receiving device is available. The time that a message is held on the server for delivery is configured by the SMSC provider. For example, AT&T Wireless saves messages for 72 hours; after that time, any undelivered messages are deleted. Your messages can request a different timeout (by specifying a ValidityPeriod field). The message can also use a registeredDelivery field to tell the SMSC to inform the you about whether and when the message is delivered.

SMS communication can be secure. Voice and data communications, including SMS message traffic between the SMSC and the mobile device is encrypted as part of the GSM standard. The mobile user's identity is also authenticated by the SMSC before the encrypted communication session begins. You must secure the communications between ColdFusion and the SMSC. Typically, you do this by using a secure hardware or software VPN connection around the SMPP connection.

The following figure shows the SMS path between mobile devices and ColdFusion gateways:

Relationship of SMS gateway instances, SMSCs, and mobile devices, showing how the role of the SMPP protocol and the wireless network.

Using the SMS event gateway, ColdFusion establishes a two-way (transceiver) connection to the SMSC of the telecommunications carrier or other SMPP account provider. The SMPP provider assigns an address for your account, and you associate an event gateway instance with the address. Addresses are normally telephone numbers, but carriers often support "short code" addresses that do not require a full 10-digit number. You also configure the gateway instance to communicate with the provider’s specified TCP/IP address using a system ID and a password.

Note: The ColdFusion MX SMS event gateway conforms to the SMPP 3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

A ColdFusion application can initiate and send messages to SMS-enabled devices by specifying the destination mobile device telephone number, or mobile devices can send messages to a ColdFusion listener CFC by using the gateway instance’s telephone number. Incoming messages include the sender’s number, so listener CFCs can respond to messages sent by mobile devices.


About SMS application development and deployment

The following sections introduce the ColdFusion SMS application development tools and process, and discuss SMS messaging providers:

  • ColdFusion MX SMS application tools
  • Application development and deployment process
  • About SMS providers

ColdFusion MX SMS application tools

ColdFusion provides the following tools for developing SMS applications:

SMSGateway The class for the SMS event gateway type

SMS test server A lightweight SMSC simulator

SMS client simulator A graphical interface for sending and receiving SMS messages with the SMS test server

You implement your SMS application by creating a ColdFusion application that uses an instance of the SMSGateway class to communicate with one or more SMSCs. You can use the SMS testing server and client simulator to test your application without requiring an outside SMS service provider.

Application development and deployment process

The following is a typical process for developing and deploying an SMS application::

  1. Design your application.
  2. Configure an SMS event gateway instance to use the ColdFusion MX SMS test server.
  3. Write your ColdFusion CFCs, CFM pages, and any other application elements.
  4. Test your application using the test server and client simulator.
  5. Establish an SMPP account with a telecommunications provider.
  6. Reconfigure your event gateway, or create a new event gateway instance, to use your telecommunications provider’s SMSC. Configure the gateway using the information supplied by your provider.
  7. Test your application using the telecommunications provider’s SMSC and target mobile devices.
  8. Make the application publicly available.

About SMS providers

Before you can deploy an SMS application, you must establish an account with a provider that supports SMPP 3.4 over TCP/IP. There are generally two kinds of providers:

  • Telecommunications carriers such as nation-wide cellular phone providers
  • Third-party SMPP aggregators

The type of provider and specific provider you use should depend on your needs and provider capabilities and price structures. Less expensive providers may have slower response times. Telecommunications carriers might be more expensive but might provide more throughput and faster SMPP response times.


How the SMS event gateway and provider SMSC interact

This section provides a brief overview of the interactions between the ColdFusion MX SMS event gateway and the SMPP provider’s SMSC. It is designed to help you to understand the basics of SMPP interactions, and defines the terms necessary to for you to understand gateway configuration and message handling. For more details, see the SMPP specification, which is available at www.smsforum.net/.

A typical interaction between an SMSC and a ColdFusion SMS event gateway instance consists of messages, or PDUs sent between the two entities, such as a mobile device and a ColdFusion MX event gateway instance (and therefore, and event gateway application). The following sections describe these interactions and how you handle them in ColdFusion MX.

This section describes the following topics:

  • Gateway binding
  • Incoming PDU handling
  • Outgoing message handling
  • Outgoing message synchronization and notification

Gateway binding

The event gateway must bind to the SMSC before they can communicate. The SMS event gateway instance initiates a binding by sending a bind_transceiver PDU to the SMSC, which includes the gateway’s ID and password. If the initial bind request fails, the gateway retries the bind at the rate specified by the gateway configuration file retry-interval value until either the bind is successful or the gateway reaches the maximum number of retries, specified by the retries configuration value. If the bind operation fails, ColdFusion logs an error to the eventgateway.log file, and you must restart the gateway instance in the ColdFusion MX Administrator to establish the connection.

Note: Some SMSCs can send a prohibited status in response to a bind request. If the gateway receives such a status response, it sets the retry interval to one minute and the maximum number of retries to 15. The SMS gateway detects SMPP 5.0-compliant and AT&T prohibited status responses.

When the SMSC accepts the bind request, it returns a bind_transceiver_resp PDU. The binding remains in effect until the gateway instance shuts down and sends an unbind PDU to the SMSC. Because the gateway binds as a transceiver, it can initiate messages to the SMSC, and the SMSC can send messages to it.

Incoming PDU handling

If the ColdFusion SMS event gateway gets an Unbind PDU from the SMSC, it sends an unbind_resp PDU to the SMSC, does a restart, and attempts to rebind to the SMSC.

When the event gateway receives an EnquireLink or any other request PDU from the SMSC, it sends a default response to the SMSC.

The gateway receives incoming messages from the SMSC in deliver _sm PDUs; it does not handle data_sm PDUs. Deliver_sm PDUs can contain user- or application-generated messages, or disposition responses for messages that the gateway has sent. The gateway extracts the short message field and source and destination addresses from the PDU, puts them in a CFEvent object, and sends the object to ColdFusion event gateway services for delivery to the listener CFC. For information on how the CFML application must handle these incoming messages, see Handling incoming messages.

Outgoing message handling

The gateway supports three types of outgoing messages from ColdFusion applications. The CFML sendGatewayMessage function or a listener CFC method cfreturn tag can specify the following commands:

submit Sends a submit_sm PDU with the message contents to the SMSC. This PDU sends a message to a single destination.

submitMulti Sends a submit_multi PDU with the message contents to the SMSC. This PDU sends a message to multiple destinations.

data Sends a data_sm PDU with the message contents to the SMSC. This is an alternative to the submit command, and is typically used by interactive applications such as those provided via a wireless application protocol (WAP) framework.

The SMS gateway lets you control the contents of all of the fields of these PDUs. For more information, see the documentation for the individual commands in Sending outgoing messages.

When you send a message, if the SMSC responds with a status that indicates that the message was rejected or not sent, ColdFusion MX logs information about the failure in the eventgateway.log file. If the SMSC indicates that the service type is not available (SMPP v5 ESME_RSERTYPUNAVAIL status or AT&T Serviced denied status), and the gateway configuration file transient-retry value is set to yes, the gateway also tries to resend the message.

Outgoing message synchronization and notification

The gateway and SMSC communicate asynchronously: the gateway does not wait for a response from the SMSC for one message before it sends another message. However, you can configure your gateway instance so that the CFML sendGatewayMessage function behaves asynchronously or synchronously.

  • In asynchronous mode, the function returns when the message is queued in ColdFusion gateway services.
  • In synchronous mode, the function waits until the SMSC receives the message and returns a message ID, or an error occurs.

For more information on configuring message synchronization and sending messages synchronously, see Controlling SMS message sending and response.


Configuring an SMS event gateway

You provide SMS-specific configuration information to the SMS event gateway in a configuration file. You specify the configuration file location when you configure the SMS event gateway instance in the ColdFusion MX Administrator. ColdFusion provides a sample SMS event gateway configuration file in cf_root\WEB-INF\cfusion\gateway\config\sms-test.cfg on J2EE configurations, and cf_root\gateway\config\sms-test.cfg on server configurations. The configuration file contents is describe in the following table.

Note: The following configuration information describes the configuration fields, but does not include detailed explanations of SMPP-specific terminology, listings of all valid values of properties that are defined in the SMPP specification, or explanations of how to select appropriate SMPP-specific values for your application. For further information, see documentation on the SMPP 3.4 protocol at www.smsforum.net/ and other publicly available documentation.

Note: Your SMS service provider might specify requirements for several of these configuration values. Consult the provider documentation.

Property

Default

Description

ip-address

IP address of the SMSC, as specified by the SMPP provider. For the ColdFusion SMS test server, you normally use 127.0.0.1.

port

0

Port number to bind to on the SMSC. The ColdFusion SMS test server uses port 7901.

system-id

Name that identifies the event gateway to the SMSC, as established with the SMPP provider. To connect to the ColdFusion SMS test server, the system-id must be cf.

password

Password for authenticating the event gateway to the SMSC. To connect to the ColdFusion SMS test server, the password must be cf.

source-ton

1

Type of Number (TON) of the source address, that is, of the address that the event gateway uses for outgoing messages, as specified in the SMPP specification. Values include 0, unknown; 1, international number; 2, national number.

source-npi

1

Numeric Plan Indicator (NPI) of the source address as specified in the SMPP specification. Values include 0, unknown; 1, ISDN.

source-address

empty string

Address (normally, a phone number) of the event gateway. Identifies the sender of outgoing messages to the SMSC.

addr-ton

1

TON for the incoming addresses that this event gateway serves.

addr-npi

1

NPI for the incoming addresses that this event gateway serves.

address-range

The range of incoming addresses (phone numbers) that remote devices can use to send messages to the event gateway instance; often, the same as the source-address.

message-rate

100

Integer or decimal value that specifies the number of messages the gateway is allowed to send to your service provider per second. 0 is unlimited.

mode

synchronous

Message transmission mode:

  • synchronous The gateway waits for the response from the server when sending a message. In this mode, the SendGatewayMessage CFML function returns the SMS messageID of the message, or an empty string if there is an error.
  • asynchronous The gateway does not wait for a response. In this mode, the SendGatewayMessage CFML function always returns an empty string.

network-retry

no

Gateway behavior when a network error occurs while trying to deliver a message:

  • yes The gateway queues the message for delivery when the gateway is able to rebind to the SMSC. Retrying is useful if the gateway is in asynchronous mode, where the CFML SendGatewayMessage function does not return an error.
  • no The gateway does not retry sending the message.

transient-retry

no

Gateway behavior when the SMSC returns an error that indicates a transient error, where it may be able to accept the message in the future:

  • yes The gateway attempts to resend the message. Retrying is useful if the gateway is in asynchronous mode, where the CFML SendGatewayMessage function does not return an error.
  • no The gateway does not retry sending the message.

cfc-method

onIncomingMessage

Listener CFC method for ColdFusion to invoke when the gateway gets incoming messages.

destination-ton

1

Default TON of addresses for outgoing messages.

destination-npi

1

Default NPI of addresses for outgoing messages.

service-type

empty string

Type of messaging service; can be empty or one of the following values: CMT, CPT, VMN, VMA, WAP, or USSD.

system-type

empty string

Type of system (ESME, External Short Message Entity ); used when binding to the SMSC. Some SMSCs might be able to send responses that are specific to a given type of ESME. Normally, should be set to SMPP.

receive-timeout

-1 (do not time out)

The time-out, in seconds, for trying to receive a message from the SMSC after it establishes a connection. To wait indefinitely until a message is received, set the receive-timeout to -1.

ping-interval

60

Number of seconds between EnquireLink messages that the event gateway sends to the server to verify the health of the connection.

retries

-1 (try forever)

Number of times to retry connecting to the SMSC to send a message before the gateway goes into a failed state. If the gateway is in a failed state, the getStatus method returns FAILED, and theColdFusion MX Administrator shows the gateway status as Failed. The gateway must be restarted before it can be used.

retry-interval

10

Number of seconds between connection retries.

You can also set the following values in each outgoing message: source-ton, source-npi, source-address, destination-ton, destination-npi, and service-type. The message field names differ from the configuration file property names.


Handling incoming messages

The SMS event gateway handles messages that are contained in deliver_sm PDUs. These PDUs request the gateway to deliver one of the following types of message:

  • A user- or application-generated text message
  • A message disposition response

Note: The SMS event gateway does not handle messages that are contained in data_sm PDUs.

The event gateway sends the object to event gateway services, which delivers it to the listener CFC. The CFEvent object that the listener CFC receives contains the following fields:

Field | Value
CfcMethod | Listener CFC method name
Data.dataCoding | Character set or the noncharacter data type of the message contents
Data.destAddress | Address to which the message was sent
Data.esmClass | Message type
Data.MESSAGE | Message contents
Data.messageLength | Length of the MESSAGE field
Data.priority | Message priority level, in the range 0-3
Data.protocol | GSM protocol; not used for other networks
Data.registeredDelivery | Requested type of delivery receipt or acknowledgement, if any
Data.sourceAddress | Address of the device that sent this message
GatewayType | Always SMS
OriginatorID | Address of the device that sent the message

For a detailed description of each field, see SMS Gateway incoming message CFEvent structure in CFML Reference.

The CFC’s listener method extracts the message from the Arguments.CFEvent.Data.MESSAGE field and acts on it as appropriate for the application. If necessary, the listener can use two fields to determine the required action:

  • CFEvent.Data.esmClass indicates the type of information in the MESSAGE field.
  • CFEvent.Data.registeredDelivery indicates whether the sender requested any type of delivery receipt or acknowledgement.

CFEvent.Data.esmClass field

The CFEvent.Data.esmClass field identifies whether the CFEvent.Data.Message field contains a message, or any of the following types of message disposition responses. For these responses, the CFEvent object Data.MESSAGE field contains the acknowledgment or receipt information.

SMSC Delivery Receipt An indication of the message’s final status, sent by the SMSC. The short message text includes the message ID of the original message, the number of messages sent and delivered (for messages sent to a distribution list), the date and time that the message was sent and delivered or otherwise disposed of, the message disposition, a network-specific error code (if available), and the first 20 bytes of the message. For details of the SMSC delivery receipt message structure, see Appendix B of the SMS 3.4 specification.

SME Delivery Acknowledgement An indication from the recipient device that the user has read the short message. Supported by TDMA and CDMA wireless networks only.

SME Manual/User Acknowledgement An application-generated reply message sent in response to an application request message. Supported by TDMA and CDMA wireless networks only.

Intermediate Delivery Notification A provider-specific notification on the status of a message that has not yet been delivered, sent during the SMSC retry lifetime for the message. Intermediate Notification support depends on the SMSC implementation and SMSC service provider. For more information, see your provider documentation.

When you send a message, you can request any combination of message disposition responses in the outgoing message’s registered_delivery parameter. If your application requests responses, the listener CFC must be prepared to handle these messages, as appropriate.

CFEvent.Data.registeredDelivery field

The CFEvent.Data.registeredDelivery field indicates whether the message sender has requested a receipt or acknowledgment. Your application can respond to a request for an SME Delivery Acknowledgement or an SME Manual/User Acknowledgement. (The other notification types are sent by the SMSC only.) For more information on these notification types, see the SMS 3.4 specification. Appendix B contains detailed information on the information that you must put in the shortMessage field of the returned acknowledgment message.

Incoming message handling example

The following example code is an SMS-only version of the echo.cfc example that is included in the ColdFusion MX gateway/cfc/examples directory. This example shows the minimal code needed to receive and respond to an SMS message.

<cfcomponent displayname="echo" hint="Process events from the test gateway and return echo">
<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Get the message --->
    <cfset data=cfevent.DATA>
    <cfset message="#data.message#">
    <!--- where did it come from? --->
    <cfset orig="#CFEvent.originatorID#">
    <cfset retValue = structNew()>
    <cfset retValue.command = "submit">
    <cfset retValue.sourceAddress = arguments.CFEVENT.gatewayid>
    <cfset retValue.destAddress = arguments.CFEVENT.originatorid>
    <cfset retValue.shortMessage = "echo: " & message>
    <!--- send the return message back --->
    <cfreturn retValue>
</cffunction>
</cfcomponent>


Sending outgoing messages

Your ColdFusion application can send submit, submitMulti, and data commands to the event gateway in an outgoing message. The following sections describe these commands in detail, followed by information on some of the more common options for sending messages.

  • The submit command
  • The submitMulti command
  • The data command


The submit command

To send a message to a single destination address in an SMPP SUBMIT_SM PDU, the structure used in the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method normally has the following fields:

Field | Contents
command | If present, the value must be "submit". If you omit this field, the event gateway sends a submit message.
shortMessage or messagePayload | The Message contents. You must specify one of these fields, but not both. The SMPP specification imposes a maximum size of 254 bytes on the shortMessage field, and some carriers might limit its size further. The messagePayload field can contain up to 64K bytes; it must start with 0x0424, followed by 2 bytes specifying the payload length, followed by the message contents.
destAddress | The address to which to send the message (required).
sourceAddress | The address of this application. You can omit this field if it is specified in the configuration file.

You can also set optional fields in the structure, such as a field that requests a delivery receipt. For a complete list of fields, see submit command in CFML Reference. For detailed descriptions of these fields, see the documentation for the SUBMIT_MULTI PDU in the SMPP3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

Note: To send long messages, you can separate the message into multiple chunks and use a submit command to send each chunk separately. In this case, a CFC would use multiple SendGatewayMessage functions, instead of the cfreturn function.

Example: Using the submit command in sendGatewayMessage function

The following example from a CFM page uses a sendGatewyMessage CFML function with a submit command to send an SMS messages that you enter in the form. This example uses the SMS gateway that is configured in the ColdFusion MX installation, and will send the message to the SMS client simulator.

<h3>Sending SMS From a Web Page Example</h3>
<cfif IsDefined("form.oncethrough") is "Yes">
    <cfif IsDefined("form.SMSMessage") is True AND form.SMSMessage is not "">
        <h3>Sending Text Message: </h3>
        <cfoutput>#form.SMSMessage#</cfoutput><br>
        <cfscript>
          /* Create a structure that contains the message. */
          msg = structNew();
          msg.command = "submit";
          msg.destAddress = "5551234";
          msg.shortMessage = form.SMSMessage;
          ret = sendGatewayMessage("SMS Menu App - 5551212", msg);
        </cfscript>
    </cfif>
    <hr noshade>
</cfif>
<!--- begin by calling the cfform tag --->
<cfform action="command.cfm" method="POST">
    SMS Text Message: <cfinput type="Text" name="SMSMessage" value="Sample text Message" required="No" maxlength="160">
<p><input type = "submit" name = "submit" value = "Submit">
<input type = "hidden" name = "oncethrough" value = "Yes">
</cfform>
</body>
</html>

For a simple example of a listener CFC uses the submit command to echo incoming SMS messages to the message originator, see Incoming message handling example.


The submitMulti command

To send a single text message to multiple recipients using an SMPP SUBMIT_MULTI PDU, the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method normally has the following fields:

Field | Contents
command | Must be "submitMulti".
shortMessage or messagePayload | The message contents. You must specify one of these fields, but not both. The SMPP specification imposes a maximum size of 254 bytes on the shortMessage field, and some carriers might limit its size further. The messagePayload field can contain up to 64K bytes; it must start with 0x0424, followed by 2 bytes specifying the payload length, followed by the message contents.
destAddress | A ColdFusion array of destination addresses (required). You cannot specify individual TON and NPI values for these addresses; all must conform to a single setting.
sourceAddress | The address of this application; you can omit this field if it is specified in the configuration file.

You can also set optional fields in the structure, such as a field that requests delivery receipts. For a complete list of fields, see submitMulti command in CFML Reference. For detailed descriptions of these fields, see the documentation for the SUBMIT_MULTI PDU in the SMPP 3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

Example: Using the submitMulti command in an onIncomingMessage method

The following example onIncomingMessage method sends a response that echoes an incoming message to the originator address, and sends a copy of the response to a second address. To test the example, run two instances of the ColdFusion SMS client application. Use the default phone number of 5551212 for the first, and set the second one to have a phone number of 555-1235. (Notice that the second phone number requires a hyphen (-).) Send a message from the first simulator, and the response will appear in both windows.

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Get the message. --->
  <cfset data=CFEvent.DATA>
  <cfset message="#data.message#">
    <!--- Create the return structure. --->
    <cfset retValue = structNew()>
    <cfset retValue.command = "submitmulti">
    <cfset retValue.sourceAddress = arguments.CFEVENT.gatewayid>
    <cfset retValue.destAddresses=arraynew(1)>
    <!--- One destination is incoming message originator;
                    get the address from CFEvent originator ID. --->
    <cfset retValue.destAddresses[1] = arguments.CFEvent.originatorid>
    <cfset retValue.destAddresses[2] = "555-1235">
    <cfset retValue.shortMessage = "echo: " & message>
<cfreturn retValue>
</cffunction>
</cffunction>


The data command

To send binary data to a single destination address in an SMPP DATA_SM PDU, the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method must have the following fields:

Field | Contents
command | Must be "data".
messagePayload | Message data. To convert data to binary format, use the ColdFusion MX toBinary function.
destAddress | Address to which to send the message.
sourceAddress | Address of this application; can be omitted if specified in the configuration file.

You can also set optional fields in the structure, such as a field that requests a delivery receipt. For a complete list of fields, see data command in CFML Reference. For detailed descriptions of these fields, see the documentation for the SUBMIT_MULTI PDU in the SMPP3.4 specification, which you can download from the SMS Forum at www.smsforum.net/.

Example: Using the data command

The following example onIncomingMessage method converts an incoming message to binary data, and sends the binary version of the message back to the originator address:

<cffunction name="onIncomingMessage" output="no">
    <cfargument name="CFEvent" type="struct" required="yes">
    <!--- Get the message. --->
  <cfset data=CFEvent.DATA>
  <cfset message="#data.message#">
    <!--- Create the return structure. --->
    <cfset retValue = structNew()>
    <cfset retValue.command = "data">
    <!--- Sending to incoming message originator; get value from CFEvent. --->
    <cfset retValue.destAddress = arguments.CFEvent.originatorid>
    <cfset retValue.messagePayload = tobinary(tobase64("echo: " & message))>
    <cfreturn retValue>
</cffunction>


Controlling SMS message sending and response

This section describes some of the more common options for sending messages, and how they affect your application. For information on other ways to configure outgoing message, see the SMPP specification.

This section describes the following topics:

  • Synchronization mode
  • Message disposition notification
  • Validity period


Synchronization mode

You can specify asynchronous or synchronous message mode in the gateway configuration file.

  • If you specify asynchronous mode, the sendGatewayMessage function returns an empty string when the message is submitted by the gateway to service code for sending to the SMSC. ColdFusion logs errors that might occur after this point, such as if a message sent by the gateway to the SMSC times out or if the gateway gets an error response; the application does not get notified of any errors.
  • If you specify synchronous mode (the default), the sendGatewayMessage function does not return until the gateway gets a response from the SMSC or the attempt to communicate times out. If the message is sent successfully, the function returns the SMPP message ID string. If an error occurs, the function returns an error string.

Use synchronous mode if your application must determine whether its messages reach the SMSC. Also use synchronous mode if the application requests return receipts.

Note: If you use synchronous mode and the SMSC returns the messgeID as a hexadecimal string, ColdFusion MX converts it automatically to its decimal value.

The following example is an expansion of Example: Using the submit command in sendGatewayMessage function. It checks for a nonempty return value and displays the message number returned by the SMS. This example uses the SMS gateway that is configured when ColdFusion MX is installed. If you change the gateway specified in the SendGatewayMessage function, make sure that you gateway’s configuration file specifies synchronous mode.

<h3>Sending SMS From a Web Page Example</h3>

<cfif IsDefined("form.oncethrough") is "Yes">
    <cfif IsDefined("form.SMSMessage") is True AND form.SMSMessage is not "">
         <h3>Sending a Text Message: </h3>
            <cfoutput>#form.SMSMessage#</cfoutput><br><br>

        <cfscript>
            /* Create a structure that contains the message. */
            msg = structNew();
            msg.command = "submit";
            msg.destAddress = "5551234";
            msg.shortMessage = form.SMSMessage;
            ret = sendGatewayMessage("SMS Menu App - 5551212", msg);
        </cfscript>
    </cfif>
    <cfif isDefined("ret") AND ret NEQ "">
        <h3>Text message sent</h3>
        <cfoutput>The Message Id is: #ret#</cfoutput>
        <br><br>
    </cfif>
    <hr noshade>
</cfif>

<!--- begin by calling the cfform tag --->
<cfform>
    SMS Text Message: <cfinput type="Text" name="SMSMessage"
        value="Sample text Message" required="No" maxlength="160">
    <p><input type = "submit" name = "submit" value = "Submit">
    <input type = "hidden" name = "oncethrough" value = "Yes">
</cfform>


Message disposition notification

You can request the SMSC to return a message disposition response to indicate the fate of your message. To request a delivery receipt, include a RegisteredDelivery field in the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method. This field can have the following values:

Value | Meaning
0 | (Default) Do not return delivery information.
1 | Return a receipt if the message is not delivered before the time-out.
2 | Return a receipt if the message is delivered or fails.

Some providers also support intermediate delivery notifications. For more information, see your provider’s documentation.

To use delivery notification, you must send your message using synchronous mode, so you get a message ID. Your incoming message routine must be able to handle the receipts as described in Handling incoming messages


Validity period

You can change the length of time that the SMSC keeps a message and tries to deliver it. (Often the default value is 72 hours.) For a message sent to an emergency worker, for example, you might want to specify a very short validity period (such as 15 minutes). To change this value, include a validityPeriod field in the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method. To specify a time period, use the following pattern: YYMMDDhhmmsst00R. In this pattern, t indicates tenths of seconds, and 00R specifies that this is a relative time period, not a date-time value. The time format 00001063000000R, for example, specifies a validity period of 0 years, 0 months, 1 day, 6 hours, 30 minutes.


ColdFusion MX SMS development tools

ColdFusion MX provides the following tools for developing SMS applications:

  • SMS test server
  • SMS client simulator

SMS test server

The CColdFusion MX SMS test server is a lightweight SMSC simulator that listens on TCP/IP port 7901 for SMPP connection requests from other SMS resources, such as ColdFusion MX SMS gateways or the SMS client simulator. The resource supplies a user name, password, and telephone number (address). The user name and password must correspond to a name and password in the simulator’s configuration file (described later in this section).

After the SMS test server establishes a connection, it listens for incoming messages and forwards them to the specified destination address, if the destination address also corresponds to an existing SMPP connection.

The SMS test server lets you develop SMS applications without having to use an external SMSC supplier such as a telecommunications provider. The server supports the ColdFusion SMS gateway submit and submitMulti commands. It also accepts, but does not deliver messages sent using the SMS gateway data command. It does not include any store and forward capabilities.

Start the SMS test server by clicking the Start SMS Test Server button on the Settings page in the Event Gateways area in the ColdFusion MX Administrator.

Note: The SMS test server does not automatically restart when you restart ColdFusion MX. You must manually restart the server if you restart ColdFusion MX.

The SMS test server reads the cf_root\WEB-INF\cfusion\lib\sms-test-users.txt file on J2EE configurations or cf_root\lib\sms-test-users.txt file on server configurations to get valid user names and passwords. ColdFusion MX includes a version of this file configured with several names and passwords. One valid combination is user name cf and password cf. You can edit this file to add or delete entries. The file must include a name and password entry for each user that will connect to the test server, and user entries must be separated by blank lines, as the following example shows:

name=cf
password=cf

name=user1
password=user1


SMS client simulator

The ColdFusion SMS client simulator is a simple External Short Message Entity (ESME) that simulates a (limited-function) mobile phone. It can connect to the SMS test server and exchange messages with it.

Note: On UNIX and Linux systems, the client simulator requires X-Windows.

Use the following procedure to use the simulator.

To use the SMS simulator:

  1. Ensure that you have started the SMS test server and configured and started an SMS event gateway instance in ColdFusion MX Administrator.
  2. Run SMSClient.bat in Windows or SMSClient.sh on UNIX or Linux. These files are located in the cf_root\WEB-INF\cfusion\bin directory on J2EE configurations and the cf_root\bin directory on server configurations.

    If you installed a pure Java version of ColdFusion MX, for example, on Apple OS X systems, enter the following command to start the simulator:

    java -jar cf_root/WEB-INF/cfusion/lib/smpp.jar
  3. A dialog box appears, requesting the server, port, username, password, and the phone number to use for this device. The simulator sends this phone number as the source address, and accepts SMS messages sent by the SMSC server to it using this number as the destination address.

    To connect to the SMS test server, accept the default values and specify an arbitrary phone number; you can also specify any username-password pair that is configured in the cf_root\WEB-INF\cfusion\lib\sms-test-users.cfg file or cf_root\lib\sms-test-users.cfg or file.

  4. Click Connect.
  5. The SMS device simulator client appears. In the Send SMS To field, enter a phone number in the address-range property specified in the configuration file of the SMS event gateway that you want to send messages to.
  6. Type a message directly into the message field (to the left of the Send button), or use the simulator keypad to enter the message.
  7. Click the Send button.

The client simulator has a Connection menu with options to connect and disconnect from the SMSC server, and to check the connection. The connection information appears in a status line at the bottom of the client.


Sample SMS application

The following CFC implements a simple employee phone directory lookup application. The user sends an message containing some part of the name to be looked up (a space requests all names). The onIncomingMessage response depends on the number matches.

  • If there is no match, the onIncomingMessage function returns a message indicating that there are no matches.
  • If there is one match, the function returns the name, department, and phone number.
  • If there are up to ten matches, the function returns a list of the names preceded by a number that the user can enter to get the detailed information.
  • If there are over ten matches, the function returns a list of only the first ten names. A more complex application might let the user get multiple lists of messages to provide access to all names.
  • If the user enters a number, and previously got a multiple-match list, the application returns the information for the name that corresponds to the number.

The following listing shows the CFC code:

<cfcomponent>
    <cffunction name="onIncomingMessage">
        <cfargument name="CFEvent" type="struct" required="YES">
        <!--- Remove any extra white space from the message. --->
        <cfset message =  Trim(arguments.CFEvent.data.MESSAGE)>
        <!--- If the message is numeric, a previous search probably returned a
            list of names. Get the name to search for from the name list stored in
            the Session scope. --->
        <cfif isNumeric(message)>
            <cfscript>
                if (structKeyExists(session.users, val(message))) {
                    message = session.users[val(message)];
                }
            </cfscript>
        </cfif>

        <!--- Search the database for the requested name. --->
        <cfquery name="employees" datasource="cfdocexamples">
            select FirstName, LastName, Department, Phone
            from Employees
            where 0 = 0
            <!--- A space indicates the user entered a first and last name. --->
            <cfif listlen(message, " ") eq 2>
                and FirstName like '#listFirst(message, " ")#%'
                and LastName like '#listlast(message, " ")#%'
            <!--- No space: the user entered a first or a last name. --->
            <cfelse>
                and (FirstName like '#listFirst(message, " ")#%'
                or LastName like '#listFirst(message, " ")#%')
            </cfif>
        </cfquery>

        <!--- Generate and  return the message.--->
        <cfscript>
            returnVal = structNew();
            returnVal.command = "submit";
            returnVal.sourceAddress = arguments.CFEVENT.gatewayid;
            returnVal.destAddress = arguments.CFEVENT.originatorid;

            //No records were found.
            if (employees.recordCount eq 0) {
                returnVal.shortMessage = "No records found for '#message#'";
            }
            //One record was found.
            else if (employees.recordCount eq 1) {
            // Whitespace in the message text results in bad formatting,
            // so the source cannot be indented.
                returnVal.shortMessage = "Requested information:
#employees.firstName# #employees.lastName#
#employees.Department#
#employees.Phone#";
            }
            //Multiple possibilities were found.
            else if (employees.recordCount gt 1) {
                //If more than ten were found, return only the first ten.
                if (employees.recordCount gt 10)
                {
                    returnVal.shortMessage = "First 10 of #employees.recordCount# records";
                }else{
                    returnVal.shortMessage = "Records found: #employees.recordCount#";
                }
                // The session.users structure contains the found names.
                // The record key is a number that is also returned in front of the
                // name in the message.
                session.users = structNew();
                for(i=1; i lte min(10, employees.recordCount); i=i+1)
                {
                    // These two lines are formatted to prevent extra white space.
                    returnVal.shortMessage = returnVal.shortMessage & "
#i# - #employees.firstName[i]# #employees.lastName[i]#";
                    // The following two lines must be a single line in the source
                    session.users[i]="#employees.firstName[i]# #employees.lastName[i]#";
                }
            }
            return returnVal;
        </cfscript>
    </cffunction>
</cfcomponent>

Previous


Creating Custom Event Gateways

This chapter describes how to create event gateways. It assumes you have a thorough knowledge of Java programming, including Java event-handling and thread-handling concepts, and of the technology to which you are providing the gateway, including the types of messages that you will handle. It also assumes that you have a thorough knowledge of Macromedia ColdFusion development concepts and practices, including ColdFusion components (CFCs).

Note: ColdFusion MX Standard Edition does not support event gateways.

Contents

Event gateway architecture

Event gateway elements

Building an event gateway

Deploying an event gateway
Next


Event gateway architecture

A ColdFusion event gateway listens for events and passes them to ColdFusion for handling by the application’s listener CFC or CFCs. It must implement the coldfusion.eventgateway.Gateway interface, and use the ColdFusion GatewayServices class. The following figure expands on the basic event handling architecture diagram to show how a ColdFusion event gateway works:

Structure of a gateway

Receiving messages The event gateway listener thread receives events from an external event source such as a socket or SMSC server, and calls the GatewayServices addEvent method to send a CFEvent instance to ColdFusion.

Sending messages The ColdFusion event gateway service calls the event gateway’s outgoingMessage method and passes it a CFEvent instance with the destination and message information. The event gateway forwards the message as appropriate to the external receiver.

The event gateway architecture is not limited to handling messages from external sources, such as SMS devices or IM clients. It can also be used to handle events that are internal to the local system or even the ColdFusion application. Also, a gateway does not have to implement two-way communications.

The sample directory watcher gateway provided with ColdFusion MX is an example of an internal, one way, gateway. It has a single thread that periodically checks a local directory and sends a message to a CFC when the directory contents change. This gateway does not support outgoing messages. (The code for this gateway is in the gateway/src/examples/watcher directory.)

Another internal gateway, the asynchronous CFML gateway, is provided as part of the ColdFusion product. Unlike most gateways, it does not have a listener thread. Its outgoingMessage method gets messages from CFML SendGatewayMessage functions, and dispatches them to a CFC onIncomingMessage method for handling. This gateway lets ColdFusion support request-free asynchronous processing. For more information on using this gateway, see Using the CFML event gateway for asynchronous CFCs.


Event gateway elements

The following sections describe the elements that you use to create and configure a gateway:

  • Gateway interface
  • GatewayServices class
  • CFEvent class
  • GatewayHelper class
  • Gateway configuration file
  • Gateway development classes

Note: The gateway interfaces and classes, with the exception of the GenericGateway class are fully documented in the Gateway development interfaces and classes section in CFML Reference. All interfaces and classes in this list, including the GenericGateway class, are documented in less detail in the Javadocs located in the ColdFusion MX gateways\docs directory. The Javadocs documentation lacks examples and does not have the detailed usage information that you find in CFML Reference.

Gateway interface

The ColdFusion event gateway must implement the coldfusion.eventservice.Gateway interface. The following table lists the interface method signatures:

Note: For detailed information on implementing each method, see Building an event gateway. For reference pages for these methods, see Gateway interface in CFML Reference.

Signature

Description

void setGatewayID(String id)

Sets the gateway ID that uniquely identifies the gateway instance. ColdFusion calls this method before it starts the event gateway, even if the gateway class constructor also sets the ID.

void setCFCListeners(String[] listeners)

Identifies the CFCs that listen for incoming messages from the event gateway. The array contains one or more paths to the listener CFCs. ColdFusion calls this method before it starts the event gateway, and if the configuration for a running event gateway changes.

GatewayHelper getHelper()

Returns a coldfusion.eventgateway.GatewayHelper class instance, or null. The GatewayHelper class provides event gateway-specific utility methods to CFML applications. ColdFusion calls this method when a ColdFusion application calls the GetGatewayHelper function.

String getGatewayID()

Returns the gateway ID.

int getStatus()

Gets the event gateway status. The interface defines the following status constants: STARTING, RUNNING, STOPPING, STOPPED, FAILED.

void start()

Starts the event gateway. Starts at least one thread for processing incoming messages. ColdFusion calls this method when it starts an event gateway.

void stop()

Stops the event gateway. Stops the threads and destroys any resources. ColdFusion calls this method when it stops an event gateway.

void restart()

Restarts a running event gateway. ColdFusion calls this method when the ColdFusion MX Administrator restarts a running event gateway.

String outgoingMessage (coldfusion. eventgateway.CFEvent cfmessage)

Handles a message sent by ColdFusion and processes it as needed by the gateway type to send a message. ColdFusion calls this method when a listener CFC’s listener method returns a CFEvent or when a ColdFusion application calls the SendGatewayMessage function. The CFML SendGatewayMessage function gets the returned String as its return value.


GatewayServices class

The Gateway class uses the coldfusion.eventgateway.GatewayServices class to interact with the ColdFusion event gateway services. This class has the following methods:

Signature

Description

GatewayServices getGatewayServices()

Static method that returns the GatewayServices object. Gateway code can call this method at any time, if required.

boolean addEvent (CFEvent msg)

Sends a CFEvent instance to ColdFusion for dispatching to a listener CFC. The event gateway uses this method to send all incoming messages to the application for processing. Returns False if the event is not added to the queue.

int getQueueSize()

Returns the current size of the ColdFusion event queue. This queue handles all messages for all gateways.

int getMaxQueueSize()

Returns the maximum size of the ColdFusion event queue, as set in the ColdFusion MX Administrator.

Logger getLogger()
Logger getLogger(String logfile)

Returns a ColdFusion Logger object that the event gateway can use to log information in the eventgateway.log log file (the default) or the specified log file.

The logfile attribute must be a file name without a file extension, such as mylogifile. ColdFusion MX puts the file in the ColdFusion logs directory and appends .log to the specified file name.

For information on using the logger object, see Logging events and using log files.


CFEvent class

The Gateway class sends and receives CFEvent instances to communicate with the ColdFusion listener CFC or application. The Gateway notifies ColdFusion of a message by sending a CFEvent instance in a GatewayServices.addEvent method. Similarly, the Gateway receives a CFEvent instance when ColdFusion calls the gateway’s outgoingMessage method.

The CFEvent class extends the java.util.Hashtable class and has the following methods to construct the instance and set and get its fields. (In CFML, you treat CFEvent instances as structures.)

Methods

Description

CFEvent(String gatewayID)

CFEvent constructor. The gatewayID parameter must be the value that is passed in the gateway constructor or set using the Gateway setGatewayID method.

void setGatewayType(String type)
String getGatewayType()

Identifies the type of event gateway, such as SMS. For the sake of consistency, use this name in the Type Name field when you add an event gateway type on the Gateway Types page in the ColdFusion MX Administrator.

void setData(Map data)
Map getData()

The event data; includes the message being passed to or from ColdFusion. The content of the field depends on the event gateway type. The Map keys must be strings.

Because ColdFusion is not case-sensitive, it converts the Map passed in the setData method to a case-insensitive Map. As a result, do not create entries in the data with names that differ only in case.

void setOriginatorID(String id)
String getOriginatorID()

Identifies the originator of an incoming message or the destination of an outgoing message. The value depends on the protocol or event gateway type.

void setCFCPath(String path)
String getCFCPath()

An absolute path to the application listener CFC that will process the event. By default, ColdFusion uses the first path configured for the event gateway instance on the Event Gateways page in the ColdFusion MX Administrator.

void setCFCMethod(String method)
String getCFCMethod()

The method in the listener CFC that ColdFusion calls to process this event. By default, ColdFusion invokes the onIncomingMessage method. For the sake of consistency, Macromedia recommends that any event gateway with a single listener not override this default. A gateway, such as the ColdFusion MX XMPP gateway, that uses different listener methods for different message types, uses this method to identify the destination method..

void setCFCTimeout(String seconds)
String getCFCTimeout()

The time-out, in seconds, for the listener CFC to process the event request. When ColdFusion calls the listener CFC to process the event, and the CFC does not process the event in the specified time-out period, ColdFusion terminates the request and logs an error in the application.log file. By default, ColdFusion uses the Timeout Request value set on the Server Settings page in the ColdFusion MX Administrator.

String getGatewayID()

The event gateway instance that processes the event. Returns the gateway ID that was set in the CFEvent constructor.


GatewayHelper class

ColdFusion MX includes a coldfusion.eventgateway.GatewayHelper Java marker interface. You implement this interface to define a class that provides gateway-specific utility methods to the ColdFusion application or listener CFC. For example, an instant messaging event gateway might use a helper class to provide buddy list management methods to the application.

The Gateway class must implement a getHelper method that returns the helper class or null (if the gateway does not need such a class).

ColdFusion applications call the GetGatewayHelper CFML function, which invokes gateway’s the getHelper method to get an instance of the helper class. The application can then call helper class methods using ColdFusion object dot notation.

The following code defines the SocketHelper class, the gateway helper for the SocketGateway class. It has an empty constructor and two public methods: one returns the socket IDs; the other closes a specified socket. These classes let an application monitor and end session connections.

public class SocketHelper implements GatewayHelper {
    public SocketHelper() {
    }
    public coldfusion.runtime.Array getSocketIDs () {
        coldfusion.runtime.Array a = new coldfusion.runtime.Array();
        Enumeration e = socketRegistry.elements();
        while (e.hasMoreElements()) {
            a.add(((SocketServerThread)e.nextElement()).getName());
         }
         return a;
     }
    public boolean killSocket (String socketid) {
        try
        {
            ((SocketServerThread)socketRegistry.get(socketid)).socket.close();
            ((SocketServerThread)socketRegistry.get(socketid)).socket = null;
            socketRegistry.remove(socketid);
            return true;
        }
        catch (IOException e) {
            return false;
        }
    }
}


Gateway configuration file

Gateways can use a configuration file to specify information that does not change frequently. For example, the ColdFusion SMS event gateway configuration file contains values that include an IP address, port number, system ID, password, and so on.

You can specify a configuration file path for each event gateway instance in the ColdFusion MX Administrator. ColdFusion passes the file path in the gateway constructor when it instantiates the event gateway. The configuration file format and content handling is up to you. It is the responsibility of the gateway class to parse the file contents and use it meaningfully.

One good way to access and get configuration data is to use the java.util.Properties class. This class takes an ISO8859-1 formatted input stream with one property setting per line. Each property name must be separated from the value by an equal sign (=) or a colon (:), as the following example shows:

ip-address=127.0.0.1
port=4445

The example SocketGateway event gateway uses this technique to get an optional port number from a configuration file. For an example of reading a properties file and using its data, see the code in Class constructor.


Gateway development classes

ColdFusion provides two classes that you can use as building blocks to develop your event gateway classes. Each corresponds to a different development methodology:

  • The coldfusion.eventgateway.GenericGateway class is an abstract class from which you can derive your gateway class.
  • The EmptyGateway class in the gateway\src\examples directory is a template gateway that you can complete to create your gateway class.

The GenericGateway class

ColdFusion MX includes a coldfusion.eventgateway.GenericGateway abstract class that implements many of the methods of ColdFusion Gateway interface and provides some convenience methods for use in your gateway class.

You can derive your gateway class from this class, which handles the basic mechanics of implementing a gateway, such as the getGatewayID and SetCFCListeners methods. Your derived class must implement at least the following methods:

  • startGateway (not start)
  • stopGateway (not stop)
  • outgoingMessage

Your derived gateway class also must implement the following:

  • If you support a configuration file, a constructor that takes a configuration file, and configuration loading routines.
  • If you use a gatewayHelper class, the getHelper method.
  • If the event source status can change asynchronously from the gateway, the getStatus method.

The example JMS gateway is derived from the generic gateway class. The gateway class JavaDocs in the gateway\docs directory provide documentation for this class. (The CFML Reference does not document this class.)

The EmptyGateway class

The gateway\src\examples\EmptyGateway.java file contains an event gateway template that you can use as a skeleton for creating your own event gateway. (The gateway directory is in the cf_root directory in the server configuration and the cf_root\WEB-INF-cfusion directory on J2EE configurations.) This file contains minimal versions of all methods in the coldfusion.eventgateway.Gateway interface. It defines a skeleton listener thread and initializes commonly used Gateway properties. The EmptyGateway source code includes comments that describe the additional information that you must provide to complete an event gateway class.


Building an event gateway

This section describes how to build an event gateway. To build a Gateway class, you can start with the EmptyGateway.java file as a template. (In the server configuration, this file is located in the cf_root/gateway/src/examples/ directory; in the J2EE configuration, the file is in the cf_root/WEB-INF/cfusion/gateway/src/examples/ directory.) This file defines a nonfunctional event gateway, but has the basic skeleton code for all Gateway class methods.

Wherever possible, the following sections use code based on the sample Socket event gateway to show how to implement event gateway features. (In the server configuration, this file is cf_root/gateway/src/examples/socket/SocketGateway.java; in the J2EE configuration, the file is cf_root/WEB-INF/cfusion/gateway/src/examples/socket/SocketGateway.java.)

This section describes the following topics:

  • Class constructor
  • Providing Gateway class service and information routines
  • Starting, stopping, and restarting the event gateway
  • Responding to incoming messages
  • Responding to a ColdFusion function or listener CFC
  • Logging events and using log files

Class constructor

An event gateway can implement any of the following constructors:

  • MyGateway(String gatewayID, String configurationFile)
  • MyGateway(String gatewayID)
  • MyGateway()

When ColdFusion MX starts, it calls the constructor for each event gateway instance that you configure in ColdFusion MX. (ColdFusion also calls the gateway Start method after the event gateway is instantiated.). ColdFusion first attempts to use the two-parameter constructor.

Because each event gateway instance must have a unique ID, ColdFusion provides redundant support for providing the ID. If the event gateway implements only the default constructor, ColdFusion provides the ID by calling the event gateway’s setGatewayID method.

If the event gateway does not implement the two-parameter constructor, it does not get configuration file information from ColdFusion.

The constructor normally calls the static GatewayServices.getGatewayServices method to access ColdFusion event gateway services. Although you need not do this, it is a good coding practice.

A minimal constructor that takes only a gateway ID might look like the following:

public MyGateway(String gatewayID) {
    this.gatewayID = gatewayID;
    this.gatewayService = GatewayServices.getGatewayServices();
}

The gateway constructor must throw a coldfusion.server.ServiceRuntimeException exception if there is an error that otherwise cannot be handled. For example, you should throw this exception if the event gateway requires a configuration file and cannot read the file contents.

If your gateway uses a configuration file, the constructor should load the file, even if the Start method also loads the file. You should do this because the constructor does not run in an independent thread, and ColdFusion can display an error in the ColdFusion MX Administrator of the file fails to load. If the Start method, which does run in a separate thread, fails to load the file, ColdFusion logs the error, but it cannot provide immediate feedback in the administrator.

The sample Socket event gateway has a single constructor that takes two parameters. It tries to load a configuration file. If you specify a configuration file in the ColdFusion MX Administrator, or the file path is invalid, it gets an IO exception. It then uses the default port and logs a message indicating what it did. The following example shows the Gateway constructor code and the loadProperties method it uses:

public SocketGateway(String id, String configpath)
{
    gatewayID = id;
    gatewayService = GatewayServices.getGatewayServices();
    // log things to socket-gateway.log in the CF log directory
    log = gatewayService.getLogger("socket-gateway");
    propsFilePath=configpath;
    try
    {
        FileInputStream propsFile = new FileInputStream(propsFilePath);
        properties.load(propsFile);
        propsFile.close();
        this.loadProperties();
     }
     catch (IOException e)
    {
        // Use default value for port and log the status.
        log.warn("SocketGateway(" + gatewayID + ") Unable to read configuration
            file '" + propsFilePath + "': " + e.toString() + ".  Using default port
            " + port + ".", e);
    }
}

private void loadProperties() {
    String tmp = properties.getProperty("port");
    port = Integer.parseInt(tmp);
}


Providing Gateway class service and information routines

Several gateway methods perform event gateway configuration services and provide event gateway information. The ColdFusion event gateway services call many of these methods to configure the event gateway by using information stored by the ColdFusion MX Administrator, and to get access to resources and information that are needed by event gateway services and applications. Some of these methods can also be useful in event gateway code. The following methods provide these services and information:

  • setCFCListeners
  • setGatewayID
  • getHelper
  • getGatewayID
  • getStatus

ColdFusion MX calls the setCFCListeners method with the CFC or CFCs that are specified in the ColdFusion MX Administrator when it starts a gateway. ColdFusion MX also calls the method in a running event gateway when the configuration information changes, so the method must be written to handle such changes. The setCFCListeners method must save the listener information so that the gateway code that dispatches incoming messages to gateway services can use the listener CFCs in setCFCPath methods.

ColdFusion MX calls the setGatewayID method when it starts a gateway. The getGatewayID method must return the value set by this method.

ColdFusion MX calls the getHelper method when an application calls the CFML GetGatewayHelper function.

The following code shows how the SocketGateway class defines these methods. To create a new gateway, modify the getHelper definition to return the correct class, or to return null if there is no gateway helper class. Most gateways do not need to change the other method definitions.

public void setCFCListeners(String[] listeners) {
    this.listeners = listeners;
}
public GatewayHelper getHelper() {
    // SocketHelper class implements the GatewayHelper interface.
    return new SocketHelper();
}
public void setGatewayID(String id) {
    gatewayID = id;
}
public String getGatewayID() {
    return gatewayID;
}
public int getStatus() {
    return status;
}


Starting, stopping, and restarting the event gateway

Because an event gateway uses at least one listener thread, it must have start, stop, and restart methods to control the threads. These methods must also maintain the status variable that the Gateway class getStatus method checks, and change its value among STARTING, RUNNING, STOPPING, STOPPED, and FAILED, as appropriate.

The start method

The start method initializes the event gateway. It starts one or more listener threads that monitor the gateway’s event source and respond to any messages it receives from the source.

The start method should return within a time-out period that you can configure for each event gateway type in the ColdFusion MX Administrator. If it does not, the ColdFusion MX Administrator has a Kill on Startup Timeout option for each gateway type. If you select the option, and a time-out occurs, the ColdFusion starter thread calls an interrupt on the gateway thread to try to kill it, and then exits.

Note: If the start method is the listener (for example, in a single-threaded gateway), the method does not return until the gateway stops. Do not set the Kill on Startup Timeout option in the ColdFusion MX Administrator for such gateways.

If the gateway uses a configuration file, the start method should load the configuration from the file. Doing so lets users change the configuration file and restart the gateway without restarting ColdFusion. Applications should also load the configuration file in the constructor; for more information, see Class constructor.

In the SocketGateway class, the start method starts an initial thread. (In a single-threaded Gateway, this would be the only thread.) When the thread starts, it calls a socketServer method, which uses the Java ServerSocket class to implement a multithreaded socket listener and message dispatcher. For more information on the listener, see Responding to incoming messages.

public void start()
{
    status = STARTING;
    listening=true;
    // Start up event generator thread
    Runnable r = new Runnable()
    {
        public void run()
        {
            socketServer();
        }
    };
    Thread t = new Thread(r);
    t.start();
    status = RUNNING;
}

The stop method

The stop method performs the event gateway shutdown tasks, including shutting down the listener thread or threads and releasing any resources. The following example shows the SocketGateway stop method:

public void stop()
{
    // Set the status variable to indicate that the server is stopping.
    status = STOPPING;
    // The listening variable is used as a switch to stop listener activity.
    listening=false;
    // Close the listener thread sockets.
    Enumeration e = socketRegistry.elements();
    while (e.hasMoreElements()) {
        try
        {
            ((SocketServerThread)e.nextElement()).socket.close();
        }
        catch (IOException e1)
        {
            // We don't care if a close failed.
            //log.error(e1);
        }
    }
    // Close and release the serverSocket instance that gets requests from the
    // network.
    if (serverSocket != null) {
        try
        {
            serverSocket.close();
        }
        catch (IOException e1)
        {
        }
        //Release the serverSocket.
        serverSocket = null;
    }
    // Shutdown succeeded; set the status variable.
    status = STOPPED;
}

The restart method

In most cases, you implement the restart method by calling the stop method and the start method consecutively, but you might be able to optimize this process for some services. The following code shows the SocketGateway class restart method:

public void restart() {
    stop();
    start();
}


Responding to incoming messages

One or more listener threads respond to incoming messages (events). The threads must include code to dispatch the messages to ColdFusion event gateway services, as follows:

  1. Create a CFEvent instance.
  2. Create a Map instance that contains the message and any other event gateway-specific information, and pass it to the CFEvent setData method.
  3. Call the CFEvent setOriginator method to specify the source of the message. (This is required if the ColdFusion application will send a response.)
  4. Call the CFEvent setGateWayType method to specify the event gateway type.
  5. Set any other CFEvent fields where the default behavior is not appropriate; for example, call the setCFCPath method to replace the default listener CFC. (For information on default CFEvent fields, see CFEvent class.)
  6. Call the gatewayService.addEvent method to dispatch the CFEvent instance to ColdFusion.
  7. Handle cases where the event is not added to the event gateway service queue (the addEvent method returns False).

If your application sends any messages to multiple listener CFCs, the gateway must create and configure a CFEvent instance and call the gatewayService.addEvent method to send the message to each separate listener CFC. The gateway’s setCFCListeners method must make the CFC paths available to the gateway for configuring the CFEvent instances.

If your ColdFusion server carries a heavy event gateway message load, the ColdFusion event gateway services event queue might reach the maximum value set in the ColdFusion MX Administrator. When this happens, the gatewayService.addEvent method returns False and fails. Your code can do any of the following:

  • Return a message to the sender to indicate that their message was not received.
  • Wait until the queue is available by periodically comparing the values returned by the GatewayService getQueueSize and getMaxQueueSize methods, and retry the addEvent method when the queue size is less than the maximum.
  • Log the occurrence using the logger returned by the GatewayService getLogger method. (For more information, see Logging events and using log files.)

The SocketGateway class implements the listener using a java.net.ServerSocket class object and SocketServerThread listener threads. (See the SocketGateway source for the SocketServerThread code.) When the listener thread gets a message from the TCP/IP socket, it calls the following processInput method to dispatch the message to ColdFusion. This method explicitly sets all required and optional CFEvent fields and sends the event to ColdFusion. If the addEvent call fails, it logs the error.

Note: Much of the processInput method code supports multiple listener CFCs. A gateway that uses only a single listener cfc, would require only the code in the latter part of this method.

private void processInput(String theInput, String theKey)
{
    // Convert listeners list to a local array
    // Protect ourselves if the list changes while we are running
    String[] listeners;
    int size = cfcListeners.size();
    if (size > 0)
    {
        // Capture the listeners list
        synchronized (cfcListeners)
        {
            listeners = new String[size];
            cfcListeners.toArray(listeners);
        }
    }
    else
    {
        // Create a dummy list
        listeners = new String[1];
        listeners[0] = null;
    }
    // Broadcast to all the CFC listeners
    // Send one message at a time with different CFC address on them
    for (int i = 0; i < listeners.length; i++)
    {
        String path = listeners[i];
        CFEvent event = new CFEvent(gatewayID);
        Hashtable mydata = new Hashtable();
        mydata.put("MESSAGE", theInput);
        event.setData(mydata);
        event.setGatewayType("SocketGateway");
        event.setOriginatorID(theKey);
        event.setCfcMethod(cfcEntryPoint);
        event.setCfcTimeOut(10);
        if (path != null)
            event.setCfcPath(path);
            boolean sent = gatewayService.addEvent(event);
        if (!sent)
            log.error("SocketGateway(" + gatewayID + ") Unable to put message on
                vent queue. Message not sent from " + gatewayID + ", thread " + theKey
                + ".  Message was " + theInput);
    }
}


Responding to a ColdFusion function or listener CFC

The ColdFusion event gateway services call the event gateway’s outgoingMessage method to handle messages generated when an event gateway application listener CFC’s listener method returns a message or any CFML code calls a SendGatewayMessage function. This method must send the message to the appropriate external resource.

The outgoingMessage method’s parameter is a CFEvent instance, containing the information about the message to send out. The CFEvent getData method returns a Map object that contains event gateway-specific information about the message, including any message text. All CFEvent instances received by the outgoingMessage contain information in the Data and GatewayID fields.

CFEvent instances returned from listener CFC onIncomingMessage methods include the incoming message’s originator ID and other information. However, a gateway that might handle messages from the ColdFusion SendGatewayMessage function cannot rely on this information being available, so it is good practice to require that all outgoing messages include the destination ID in the data Map.

The outgoingMessage method returns a String value. The CFML sendGatewayMessage function returns this value to the ColdFusion application. The returned string should indicate the status of the message. By convention, ColdFusion event gateway outgoingMessage methods return "OK" if they do not encounter errors and do not have additional information (such as a message ID) to return.

Because event messages are asynchronous, a positive return normally does not indicate that the message was successful delivered, only that the outgoingMessage method successfully handled the message. In some cases, however, it is possible to make the outgoingMessage method at least partially synchronous. The SMS gateway, for example, provides two outgoingMessage modes:

Asynchronous mode The outgoingMessage method returns when the message is queued internally for delivery to the messaging provider’s short message service center (SMSC)

Synchronous mode The method does not return until the message is delivered to the SMSC, or an error occurs.

This way, an SMS application can get a message ID for later use, such as to compare with a message receipt.

Example outgoingMessage method

The following outgoingMessage method is similar to the version in the SocketGateway class. It does the following:

  1. Gets the contents of a MESSAGE field of the Data Map returned by the CFEvent class getData method.
  2. Gets the destination from an outDestID field in the data Map.
  3. Uses the destination’s socket server thread to write the message.
    public String outgoingMessage(coldfusion.eventgateway.CFEvent cfmsg) {
    String retcode="ok";
    // Get the table of data returned from the event handler
    Map data = cfmsg.getData();
    String message = (String) data.get("MESSAGE");
    // Find the right socket to write to from the socketRegistry hashtable
    // and call the socket thread’s writeoutput method.
    // (Get the destination ID from the data map.)
    if (data.get("outDestID") != null)
        ((SocketServerThread)socketRegistry.get(data.get("outDestID"))).
                writeOutput(message);
    else {
        System.out.println("cannot send outgoing message. OriginatorID is not
            available.");
        retcode="failed";
        }
    return retcode;
}


Logging events and using log files

The GatewayServices.getLogger method returns an instance of the coldfusion.eventgateway.Logger class that you can use to log messages to a file in the ColdFusion logs directory. (You set this directory on the ColdFusion MX Administrator Logging Settings page.) The method can take no parameter, or one parameter:

  • The default GatewayServices.getLogger method uses the eventgateway.log file.
  • Optionally, you can specify a log filename, without the .log extension or directory path.

The following example tells ColdFusion to log messages from the gateway to the mygateway.log file in the ColdFusion logs directory:

coldfusion.eventgateway.Logger log =
    getGatewayServices().getLogger("mygateway");

The Logger class has the following methods, all of which take a message string. The method you use determines severity level that is set in the log message.

  • info
  • warn
  • error
  • fatal

You can also pass these methods an exception instance as a second parameter. When you do this, CColdFusion MX puts the exception information in the exception.log file in the ColdFusion MX logs directory.

You can use these methods to log any messages that you find appropriate. If you use the default eventgateway.log file, however, remember that it is used by all ColdFusion MX standard gateways, and might be used by other gateways. As a result, you should limit the messages that you normally log to this file to infrequent normal occurrences (such as gateway startup and shutdown) or errors for which you want to retain data.

ColdFusion MX uses the following format for the message text, and your application should follow this pattern:

GatewayType (Gateway ID) Message

The SMS event gateway, for example, includes the following exception catching code, which logs a general exception messages and the exception name in the eventgateway.log file, and also (automatically) logs the exception in the exceptions.log file:

catch(Exception e)
{
    logger.error("SMSGateway (" + gatewayID + ") Exception while processing
incoming event: " + e, e);
}

Note: When you are developing an event gateway application, you can use the ColdFusion Log viewer to inspect your log files and the standard ColdFusion MX log files, including the eventgateway.log file and exception.log file. You can use the viewer to filter the display, for example, by selecting different severity levels, or searching for keywords.


Deploying an event gateway

To deploy an event gateway, you deploy and event gateway type and configure one or more event gateway instances.

To deploy a event gateway type in ColdFusion:

  1. Compile your Gateway class and put it in a JAR file along with any other required classes.

    Note: The ColdFusion MX class loader includes the gateway \lib directory on its classpath and includes any JAR files that are in that directory on the class path.

  2. Put the JAR file in the cf_root\WEB-INF\cfusion\gateway\lib directory on J2EE configurations or the cf_root\gateway\lib directory on server configurations. This directory is on the ColdFusion classpath.
  3. Ensure that ColdFusion event gateway services are enabled on the ColdFusion MX Administrator Data & Services > Event Gateway > Settings page.
  4. On the ColdFusion MX Administrator Data & Services > Event Gateways page, click the Manage Gateway Types button to display the Gateway Types page.
  5. On the Add/Edit ColdFusion Event Gateway Types form, enter a type name (for example, SMS for the SMS event gateway), a description, and the full Java class name (for example, coldfusion.eventgateway.sms.SMSGateway for the SMS event gateway). If appropriate, change the Startup Timeout settings from the default values.
  6. Click the Add Type button to deploy the event gateway type in ColdFusion.

The following procedure describes how to configure an event gateway instance that uses the gateway type.

To configure an event gateway instance

  1. If you have just finished deploying the event gateway type, click the Manage Gateway Instances button; otherwise, select Event Gateways > Gateway Instances in the ColdFusion MX Administrator.
  2. On the Add/Edit ColdFusion Event Gateways Instances form do the following:
    • Enter the instance name in the Gateway ID field
    • Select the event gateway type that you added from the Gateway Type drop-down list
    • Specify the paths to the listener CFC or CFCs that will handle the messages.
    • If the event gateway requires a configuration file, enter the path to the file in Gateway Configuration File field.
    • If you do not want the gateway to start up automatically when ColdFusion MX starts, change the Startup Mode selection to Manual or Disabled
  3. Click the Add Gateway Instance button.
  4. In the list of configured instances, click the start button (green triangle) on the gateway instance’s entry to start the instance.

Previous


Configuring and Administering ColdFusion MX

Configuring and Administering ColdFusion MX 7 is intended for anyone who needs to configure and manage their ColdFusion development environment.

This book contains the following chapters:

  • Introduction
  • Administering ColdFusion MX
  • Using the ColdFusion MX Administrator
  • Data Source Management
  • Web Server Management
  • Deploying ColdFusion Applications
  • Administering Security
  • Using Multiple Server Instances
  • Introducing Verity and Verity Tools
  • Indexing Collections with Verity Spider
  • Using Verity Utilities


Introduction

Configuring and Administering ColdFusion MX is intended for anyone who needs to configure and manage their ColdFusion development environment.

About Macromedia ColdFusion MX 7 documentation

The ColdFusion MX 7 documentation is designed to provide support for the complete spectrum of participants.

Documentation set

The ColdFusion MX 7 documentation set includes the following titles:

Book | Description
Installing and Using ColdFusion MX | Describes system installation and basic configuration for Microsoft Windows, Solaris, and Linux. www.macromedia.com/go/livedocs_cfmx7docs_installing
Configuring and Administering ColdFusion MX | Part I describes how to manage the ColdFusion environment, including connecting to your data sources and configuring security for your applications. Part II describes Verity search tools and utilities that you can use for configuring the Verity Search Server, as well as creating, managing, and troubleshooting Verity collections. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_configadmin.
ColdFusion MX Developer’s Guide | Describes how to develop your dynamic web applications, including retrieving and updating your data, and using structures and forms. This manual includes two volumes. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_dev.
Getting Started Building ColdFusion MX Applications | Contains an overview of ColdFusion features and application development procedures. This manual includes a tutorial that guides you through the process of developing a sample ColdFusion application. To see this manual online, go to www.macromedia.com/go/livedocs_cfmx7docs_gs.
CFML Reference | Provides descriptions, syntax, usage, and code examples for all ColdFusion tags, functions, and variables. This manual includes two volumes. To see this manual, go to www.macromedia.com/go/livedocs_cfmx7docs_cfml_reference.
CFML Quick Reference | Shows the syntax of ColdFusion tags, functions, and variables in a brief guide.

Viewing online documentation

All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable Document Format (PDF) files. Go to the documentation home page for ColdFusion MX on the Macromedia website: www.macromedia.com. In addition, you can view the documentation in LiveDocs, which lets you add comments to pages and view the latest comments added by Macromedia, by going to www.macromedia.com/go/livedocs_cfmx7docs.


Administering ColdFusion MX

This chapter presents an overview of Macromedia ColdFusion MX 7 configuration and administration tasks. Although you perform most ColdFusion MX administration tasks using the ColdFusion MX Administrator, you also manage databases, web server configurations, and the Verity Search Server.

Contents

About the ColdFusion MX Administrator

About web server administration

About Verity administration
Next


About the ColdFusion MX Administrator

The ColdFusion MX Administrator provides a browser-based interface for managing your ColdFusion environment. You can configure many settings to provide optimal levels of security and functionality. The available options are based on your edition of ColdFusion MX 7--Standard or Enterprise--as well as your configuration: server, multiserver, or J2EE. For more information on ColdFusion MX configurations, see About the ColdFusion MX 7 installation in Preparing to Install ColdFusion MX 7 in Installing and Using ColdFusion MX.

The default location for the ColdFusion MX Administrator login page is:

http://servername[:portnumber]/CFIDE/administrator/index.cfm

Where servername is the fully qualified domain name of your web server. Common values for servername are localhost or 127.0.0.1 (each refers to the web server on the local computer).

If you are using the ColdFusion built-in web server, include the port number as part of the servername. The default port number for the server configuration is 8500; for example, http://servername:8500/CFIDE/administrator/index.cfm. The default port number for the multiserver configuration is 8300. If you are using the J2EE configuration, include the port number used by the J2EE application server’s web server.

Tip: If you were using the built-in web server in a previous version and upgraded to ColdFusion MX 7, the installer automatically finds an unused port for the built-in web server (typically 8501).

If your ColdFusion MX Administrator is on a remote computer, use the Domain Name Services (DNS) name or Internet Protocol (IP) address of the remote host.

To access the ColdFusion MX Administrator, enter the password specified when you installed ColdFusion MX.

Tip: If you are running in a multihomed environment and have problems displaying the ColdFusion MX Administrator, see Web Server Management for configuration information.

For more information, see Using the ColdFusion MX Administrator.

About web server administration

ColdFusion MX applications require a web server to process ColdFusion Markup Language (CFML) pages. The server and multiserver configurations provide a built-in web server along with support for external web servers, such as Apache, IIS, and Sun ONE Web Server (formerly known as iPlanet).

For more information, see Web Server Management.

About Verity administration

ColdFusion MX includes Verity K2 Server search technology. Verity K2 Server is a high-performance search engine designed to process searches quickly in a high-performance, distributed system.

For more information, see Introducing Verity and Verity Tools.
Previous


Using the ColdFusion MX Administrator

This chapter explains the basic administration tasks, following the structure of the Macromedia ColdFusion MX Administrator sections. It also includes a brief description of each Administrator screen and a discussion of performing Administrator functionality programmatically through the Administrator application programming interface (API).

Contents

Initial administration tasks

Accessing user assistance

Server Settings section

Data & Services section

Debugging & Logging section

Extensions section

Event Gateways section

Security section

Packaging and Deployment section

Enterprise Manager section

Custom Extensions section

Administrator API
Next


Initial administration tasks

Immediately after you install ColdFusion MX, you might have to perform some or all of the administrative tasks described in the following table:

Task | Description
Establish database connections | ColdFusion applications require data source connections to query and write to databases. To create, verify, edit, and delete database connections, use the Data Sources page. For more information, see Data Source Management.
Specify directory mappings | Directory mappings redirect relative file paths to physical directories on your server. To specify server-wide directory aliases, use the Mappings page. For more information, see Mappings page.
Configure debugging settings | Debugging information provides important data about CFML page processing. To choose the debugging information to display, and to designate an IP address to receive debugging information, use the Debugging & Logging section. For more information, see Debugging Settings and Debugging IPs pages.
Set up e-mail | E-mail lets ColdFusion applications send automated e-mail messages. To configure an e-mail server and mail options, use the Mail Server page. For more information, see Mail Server page.
Change passwords | You might have to change the passwords that you set for the ColdFusion MX Administrator and RDS during ColdFusion MX installation. To change passwords, use the Security section. For more information, see CF Admin Password page and RDS Password page.
Configure Java settings | (Server configuration only) You might have to customize Java settings, such as classpath information, to meet the needs of your applications. To change Java settings, use the Java and JVM page. For more information, see Extensions section.
Restrict tag access | Some CFML tags might present a potential security risk for your server. To disable certain tags, use the Sandbox Security page. For more information, see Administering Security.


Accessing user assistance

You can obtain assistance from the ColdFusion MX Administrator in the following ways:

Online Help You access the context-sensitive online Help by clicking the question-mark icon on any ColdFusion MX Administrator page. The online Help has procedural and brief overview content for the ColdFusion MX Administrator page that you are viewing. This information appears in a new browser window and contains standard Contents, Index, and Search tabs.

Getting Started Experience Click the Getting Started link to open the Getting Started Experience, which provides descriptions of new features, code examples, and sample applications to help you learn about ColdFusion MX.

Documentation Click the Documentation link to access the entire ColdFusion MX documentation set online.

Tech notes Click the Tech Notes link to access the collection of articles about ColdFusion MX from the Macromedia website (www.macromedia.com).


Server Settings section

The Server Settings section lets you manage client and memory variables, mappings, charting, and archiving. You also configure e-mail and Java settings in this section.

The Server Settings section contains the following pages:

  • Settings page
  • Caching page
  • Client Variables page
  • Memory Variables page
  • Mappings page
  • Mail Server page
  • Charting Settings page
  • Java and JVM Settings page
  • ColdFusion Archives page
  • Settings Summary page


Settings page

The Settings page of the ColdFusion MX Administrator contains configuration options that you can set or enable to manage ColdFusion MX. These options can significantly affect server performance. The following table describes the options:

Option

Description

Maximum number of simultaneous requests

(not available in J2EE configuration)

Enter a number to limit simultaneous requests to ColdFusion MX. When the server reaches the limit, requests are queued and handled in the order received. Limiting the number of simultaneous requests can improve performance.

Timeout requests after n seconds

Select this option to prevent unusually lengthy requests from using up server resources. Enter a limit to the time that ColdFusion MX waits before terminating a request. Requests that take longer than the timeout period are terminated.

Use UUID for cftoken

Specify whether to use a universally unique identifier (UUID), rather than a random number, for a cftoken.

Enable HTTP status codes

Select this option to configure ColdFusion MX to set a status code of 500 Internal Server Error for an unhandled error. Disable this option to configure ColdFusion MX to set a status code of 200 OK for everything, including unhandled errors.

Enable Whitespace Management (not available in J2EE configuration)

Select this option to compress repeating sequences of spaces, tabs, and carriage return/linefeeds. Compressing whitespace can significantly compact the output of a ColdFusion page.

Enable Global Script Protection

Select this option to protect Form, URL, CGI, and Cookie scope variables from cross-site scripting attacks. Select this option if your application does not contain this type of protection logic.

Default CFFORM ScriptSrc Directory

Specify the default path (relative to the web root) to the directory that contains the cfform.js file. Developers reference this file in the ScriptSrc attribute of the cfform tag.

In a hosted environment, you might need to move the cfform.js file to a directory other than CFIDE.

Missing Template Handler

Specify a page to execute when ColdFusion MX cannot find a requested page. This specification is relative to the web root.

Note: If the user is running Microsoft Internet Explorer with "Show Friendly HTTP error messages" enabled in advanced settings (the default), Internet Explorer will only display this page if it contains more than 512 bytes.

Site-wide Error Handler

Specify a page to execute when ColdFusion MX encounters an error while processing a request. This specification is relative to the web root. When you define a site-wide error handler or missing template handler, ColdFusion MX does not log page not found errors and exceptions.

Note: If the user is running Internet Explorer with "Show Friendly HTTP error messages" enabled in advanced settings (the default), Internet Explorer will only display this page if it contains more than 512 bytes.


Caching page

The Caching page of the Administrator contains configuration options that you can set or enable to cache templates, queries, and data sources. These options can significantly affect server performance. The following table describes the settings:

Option | Description
Maximum number of cached templates | Select this option by entering a value that specifies the number of templates that ColdFusion MX caches. For best performance, set this to a value that is large enough to contain your application’s commonly accessed ColdFusion pages, yet small enough to avoid excessive reloading. You can experiment with a range of values on your development server; a suitable starting point is one page per MB of Java Virtual Machine (JVM) size.
Trusted cache | Select this option if you want ColdFusion MX to use cached templates without checking whether they changed. For sites that are not updated frequently, using this option minimizes file system overhead.
Save Class Files | Select this option to save to disk the class files generated by the ColdFusion bytecode compiler. During the development phase, it is typically faster if you disable this option.
Cache web server paths (not available in J2EE configuration) | Select this option to cache ColdFusion page paths for a single server. Clear this option if ColdFusion MX connects to a web server with multiple websites or multiple virtual websites.
Limit the maximum number of cached queries on the server to [n] queries | Select this option by entering a value to limit the maximum number of cached queries that the server maintains. Cached queries allow retrieval of result sets from memory rather than through a database transaction. Because queries reside in memory, and query result set sizes differ, you must provide a limit for the number of cached queries. You enable cached queries with the cachedwithin or cachedafter attributes of the cfquery tag.
Clear Template Cache Now | Empties the template cache. ColdFusion reloads templates into memory the next time they are requested and recompiles them if they have been modified.


Client Variables page

Client variables let you store user information and preferences between sessions. Using information from client variables, you can customize page content for individual users.

You enable client variable default settings in ColdFusion MX on the Client Variables page of the Administrator. ColdFusion MX lets you store client variables in the following ways:

  • In database tables

    Note: If your data source uses one of the JDBC drivers bundled with ColdFusion MX 7, ColdFusion MX can automatically create the necessary tables. If your data source uses the ODBC Socket or a third-party JDBC driver, you must manually create the necessary CDATA and CGLOBAL database tables.

  • As cookies in users’ web browsers
  • In the operating system registry

    Caution: Macromedia recommends that you do not store client variables in the registry because it can critically degrade performance of the server. If you do use the registry to store client variables, you must allocate sufficient memory and disk space.

You can override settings specified in the Client Variables page using the Application.cfc file or the cfapplication tag. For more information, see ColdFusion MX Developer’s Guide.

The following table compares the client variable storage options:

Storage type

Advantages

Disadvantages

Data source
  • Can use existing data source
  • Portable: not tied to the host system or operating system
  • Requires database transaction to read/write variables
  • More complex to implement

Browser cookies
  • Simple implementation
  • Good performance
  • Can be set to expire automatically
  • Client-side control
  • Users can configure browsers to disallow cookies
  • Cookie data is limited to 4 KB
  • Netscape Navigator allows only 20 cookies from one host; ColdFusion MX uses three cookies to store read-only data, leaving only 17 cookies available

System registry
  • Simple implementation
  • Good performance
  • Registry can be exported easily to other systems
  • Server-side control
  • Possible restriction of the registry’s maximum size limit in Windows in the Control Panel
  • Integrated with the host system: not practical for clustered servers
  • Not available for UNIX

Migrating client variable data

To migrate your client variable data to another data source, you should know the structure of the database tables that store this information. Client variables stored externally use two simple database tables, like those shown in the following tables:

CDATA Table
Column | Data type
cfid | CHAR(64), TEXT, VARCHAR, or equivalent
app | CHAR(64), TEXT, VARCHAR, or equivalent
data | MEMO, LONGTEXT, LONG VARCHAR, or equivalent
CGLOBAL Table
Column | Data type
cfid | CHAR(64), TEXT, VARCHAR, or equivalent
data | MEMO, LONGTEXT, LONG VARCHAR, or equivalent
lvisit | TIMESTAMP, DATETIME, DATE, or equivalent

Creating client variable tables

Use the following sample ColdFusion page as a model for creating client variable database tables in your own database. However, keep in mind that not all databases support the same column data type names. For the proper data type, see your database documentation.

Tip: The ColdFusion MX Administrator can create client variable tables for data sources that use one of the bundled JDBC drivers. For more information, see the online help.

Sample table creation page

<!---- Create the Client variable storage tables in a datasource.
This example applies to Microsoft Access databases. --->

<cfquery name="data1" datasource="#DSN#">
CREATE TABLE CDATA
(
    cfid char(20),
    app char(64),
    data memo
)
</cfquery>

<cfquery name="data2" datasource="#DSN#">
    CREATE UNIQUE INDEX id1
    ON CDATA (cfid,app)
</cfquery>

<cfquery name="global1" datasource="#DSN#">
CREATE TABLE CGLOBAL
(
    cfid char(20),
    data memo,
    lvisit date
)
</cfquery>

<cfquery name="global2" datasource="#DSN#">
    CREATE INDEX id2
    ON CGLOBAL (cfid)
</cfquery>

<cfquery name="global2" datasource="#DSN#">
    CREATE INDEX id3
    ON CGLOBAL (lvisit)
</cfquery>


Memory Variables page

You use the Memory Variables page of the ColdFusion MX Administrator to enable application and session variables server-wide. By default, application and session variables are enabled when you install ColdFusion MX. If you disable either type of variable in the Memory Variables page, you cannot use them in a ColdFusion application.

You can specify maximum and default timeout values for session and application variables. Unless you define a timeout value in an Application.cfc or Application.cfm file, application variables expire in two days. Session variables expire when user sessions end. To change these behaviors, enter new default and maximum timeout values on the Memory Variables page of the Administrator.

Note: Timeout values that you specify for application variables override the timeout values set in the Application.cfc or Application.cfm file.

You can also specify whether to use J2EE session variables. When you enable the J2EE session variables, ColdFusion creates an identifier for each session and does not use the CFToken or CFID cookie value. For more information, see ColdFusion MX Developer’s Guide.

Note: When using J2EE sessions, ensure that the session timeout, specified in the WEB-INF/web.xml session-timeout element is longer than the session timeout that you specify in the ColdFusion MX Administrator and longer than any sessiontimeout attribute specified in a cfapplication tag.


Mappings page

You use the Mappings page of the ColdFusion MX Administrator to add, update, and delete logical aliases for paths to directories on your server. ColdFusion mappings apply only to pages processed by ColdFusion MX with the cfinclude and cfmodule tags. If you save CFML pages outside of the web_root directory (or whatever directory is mapped to "/"), you must add a mapping to the location of those files on your server.

Assume that the "/" mapping on your server points to C:\CFusionMX7\wwwroot, but all your ColdFusion header pages reside in C:\2002\newpages\headers. In order for ColdFusion MX to find your header pages, you must add a mapping in the ColdFusion MX Administrator that points to C:\2002\newpages\headers (for example, add a mapping for /headers that points to C:\2002\newpages\headers). In the ColdFusion pages located in C:\CFusionMX7\wwwroot, you reference these header pages using /headers in your cfinclude and cfmodule tags.

Note: ColdFusion mappings are different from web server virtual directories. For information on creating a virtual directory to access a given directory using a URL in your web browser, consult your web server’s documentation.


Mail Server page

You use the Mail Server page of the ColdFusion MX Administrator to specify a mail server to send automated e-mail messages. ColdFusion MX supports the Simple Mail Transfer Protocol (SMTP) for sending e-mail messages and the Post Office Protocol (POP) for retrieving e-mail messages from your mail server. To use e-mail messaging in your ColdFusion applications, you must have access to an SMTP server and a POP account.

The ColdFusion MX Enterprise Edition supports mail server failover as well as additional mail delivery options.

The ColdFusion implementation of SMTP mail uses a spooled architecture. This means that when a cfmail tag is processed in an application page, the messages generated might not be sent immediately. If ColdFusion is extremely busy or has a large queue, delivery could occur after some delay.

Note: For more information about the cfmail tag, see Sending SMTP e-mail with the cfmail tag in Sending and Receiving E-Mail in ColdFusion MX Developer’s Guide.

Mail Server Settings area

The following table describes basic mail server settings:

Option

Description

Mail Server

Enter a valid mail server for sending dynamic SMTP mail messages in the text box. You can enter an Internet address, such as mail.company.com, or the IP address of the mail server, such as 127.0.0.1.

Verify Mail Server Connection

Select this option to verify that ColdFusion MX can connect to your specified mail server after you submit this form.

Whether or not you use this option, you should verify that your mail server connection works by sending a test message.

Server Port

Enter the number of the port on which the mail server is running. Contact your server administrator if you are unsure of the appropriate port number.

Backup Mail Servers (Enterprise Edition only)

Enter zero or more backup servers for sending SMTP mail messages. You can enter an Internet address, such as mail.company.com, or the IP address of the mail server, such as 127.0.0.1. Separate multiple servers with a comma.

If the mail server requires authentication, prepend the mail server with the username and password, as follows: username:password@mailserveraddress

To use a port number other than the default (25), specify mailserveraddress:portnumber

Maintain Connection to Mail Server

(Enterprise Edition only)

Select this option to keep mail server connections open after sending a mail message. Enabling this option can enhance performance when delivering multiple messages.

Connection Timeout (seconds)

Enter the number of seconds that ColdFusion MX should wait for a response from the mail server before timing out.

Mail Spool Settings area

The following table describes mail server spool settings:

Option | Description
Spool Interval (seconds) | Enter the interval, in seconds, at which you want the mail server to process spooled mail.
Mail Delivery Threads (Enterprise Edition only) | Enter the maximum number of simultaneous threads used to deliver spooled mail.
Spool mail messages for delivery (Memory spooling available for Enterprise Edition only) | Select this option to route outgoing mail messages to the mail spooler. If you disable this option, ColdFusion MX delivers outgoing mail messages immediately. In ColdFusion MX Enterprise Edition, you can spool messages to disk (slower, but messages persist across shutdowns) or to memory (faster, but messages do not persist). You can override this setting in the cfmail tag.
Maximum number of messages spooled to memory (Enterprise Edition only) | Enter the maximum number of messages ColdFusion MX will spool to memory before switching to disk spooling.

Mail Logging Settings area

Select preferences for handling mail logs, as described in the following table:

Option

Description

Error Log Severity

From the drop-down list box, select the type of SMTP-related error message to write to a log file. The options are the following:

  • Debug (contains Information, Warning, and Error)
  • Information (contains Warning and Error)
  • Warning (contains Error)
  • Error

Log all e-mail messages sent by ColdFusion MX

Select this option to save to a log file the To, From, and Subject fields of all e-mail messages.

ColdFusion MX writes sent mail and mail error logs to the following directories:

  • \CFusionMX7\logs (Windows server configuration)
  • /opt/coldfusionmx7/log (Solaris and Linux server configuration)
  • cf_webapp_root/WEB-INF/cfusion/logs (multiserver and J2EE configurations, all platforms)

The following table describes the e-mail log files:

Log | Description
mailsent.log | Records sent e-mail messages.
mail.log | Records general e-mail errors.

Mail Character Set Settings area

Select preferences for the default mail character set, as described in the following table:

Option | Description
Default CFMAIL CharSet | From the drop-down list box, select the default character set used by the cfmail tag. The default value is UTF-8. If the majority of your e-mail clients use a specific character set, you can use this setting to switch to that locale-specific character set. For example, Japanese mail is typically sent using the ISO-2022-JP character set.


Charting Settings page

The ColdFusion charting and graphing engine lets you produce highly customizable business graphics, in a variety of formats, using the cfquery tag. You use the Charting page in the Administrator to control characteristics of the engine.

The following table describes the caching and thread settings for the ColdFusion charting and graphing engine:

Option | Description
Cache Type | Set the cache type. Charts can be cached either in memory or to disk. Memory caching is faster, but more memory intensive.
Maximum number of images in cache | Specify the maximum number of charts to store in the cache. After the cache is full, if you generate a new chart, ColdFusion discards the oldest chart in the cache.
Max number of charting threads | Specify the maximum number of chart requests that can be processed concurrently. The minimum number is 1 and the maximum is 5. (Higher numbers are more memory-intensive.)
Disk cache location | When caching to disk, specify the directory in which to store the generated charts.


Font Management page

The Font Management page lets you review and define fonts for use with Macromedia FlashPaper and Acrobat PDF output formats. ColdFusion generates FlashPaper and PDF output through the cfdocument tag and through the cfreport tag, when used to call a report created with the ColdFusion Report Builder.

ColdFusion MX automatically registers Acrobat built-in fonts and fonts located in typical font locations (such as the Windows\fonts directory). However, if your server has additional fonts installed in nonstandard locations, you must register them with the ColdFusion MX Administrator so that the cfdocument and cfreport tags can locate and render PDF and FlashPaper reports.

This page contains the following sections:

Register New Font with ColdFusion Lets you browse to a directory that contains fonts, or select a specific font.

User Defined Fonts Displays the fonts that have been registered explicitly.

Current System Fonts Displays fonts stored in platform-specific system font directories.

For more information on font management, see the ColdFusion MX Administrator online Help. For more information on reporting in ColdFusion MX, see Creating Reports for Printing in ColdFusion MX Developer’s Guide.


Java and JVM Settings page

The Java and JVM Settings page lets you specify the following settings, which enable ColdFusion MX to work with Java:

Option | Description
Java Virtual Machine Path | The absolute file path to the location of the Java virtual machine (JVM) root directory. The default is cf_root/runtime/jre.
Minimum JVM Heap Size | The JVM initial heap size.
Maximum Memory Size | The JVM maximum heap size. The default value is 512 MB.
Class Path | The file paths to the directories that contain the JAR files used by ColdFusion MX. Specify either the fully qualified name of a directory that contains your JAR files or a fully qualified JAR filename. Use a comma to separate multiple entries.
JVM Arguments | The arguments to the JVM. Use a space to separate multiple entries (for example, -Xint -Xincgc).

Note: This page is available in the server configuration only.

Before ColdFusion saves your changes, it saves a copy of the current cf_root/runtime/bin/jvm.config file as jvm.bak. If your changes prevent ColdFusion from restarting, use the jvm.bak file to restore your system. For more information, see the online help.


Settings Summary page

The Settings Summary page shows all ColdFusion configuration settings. Click a group name to open that group’s Administrator section, where you can edit settings. This page is not enabled in the Standard Edition.


Data & Services section

The Data & Services section of the Administrator is the interface for ColdFusion MX, data sources, and Verity search and indexing features. The following table describes some common tasks that you can perform in the Data & Services section of the Administrator:

Task | Description
Create and manage JDBC data sources | The Data Sources page lets you establish, edit, and delete JDBC data source connections for ColdFusion MX. For more information, see Data Source Management.
Create and maintain Verity collections | The Verity Collections page lets you create and delete Verity collections and perform maintenance operations on collections that you create. For more information, see Verity Collections page.
Define mappings for web services | The Web Services page lets you produce and consume remote application functionality over the Internet. For more information, see Web Services page.

The Data & Services section contains the following pages:

  • Data Sources page
  • Verity Collections page
  • Verity K2 Server page
  • Web Services page

Data Sources page

The Data Sources page lets you create, edit, and delete JDBC data sources. Before you can use a database in a ColdFusion application, you must register the data source in the ColdFusion MX Administrator. For more information, see Data Source Management.

Verity Collections page

ColdFusion MX includes Verity, which provides indexing and searching technology to create, populate, and manage collections of indexed data that are optimized for fast and efficient site searches.

A collection is a logical group of documents and metadata about the documents. The metadata includes word indexes, an internal documents table of document field information, and logical pointers to the document files.

For more information about building search interfaces, see Building a Search Interface in ColdFusion MX Developer’s Guide.

ColdFusion lets you manage your collections from the Administrator. You can index, optimize, purge, or delete Verity collections that are connected to ColdFusion. You use the icons in the Actions column to perform the following actions:

Action | Description
Index | Analyzes the files in a collection and assembles metadata and pointers to the files.
Optimize | Reclaims space left by deleted and changed files by consolidating collection indexes for faster searching. You should optimize collections regularly.
Purge | Deletes all documents in a collection, but not the collection itself. Leaves the collection directory structure intact.
Delete | Deletes a collection.

The Verity Search Server must be running. If this page is unable to retrieve collections, ensure that the Verity Search Server is running. For more information, see Collections and the ColdFusion MX Verity architecture.

Verity K2 Server page

You can install Verity on a different host computer from the one ColdFusion MX is running on. If this is the case, you can configure the host that ColdFusion will use when it performs search operations. If you have purchased the Verity product, you may need to use advanced settings to configure the aliases and ports of the services that ColdFusion uses. You should not need to change these values if you are running with the ColdFusion installed version of Verity.

Web Services page

You can use web services to produce and consume remote application functionality over the Internet. The ColdFusion MX Administrator lets you register web services so that you do not have to specify the entire Web Services Description Language (WSDL) URL when you reference the web service. The first time you reference a web service, ColdFusion MX automatically registers it in the Administrator.

When you register a web service, you can shorten your code and change a web service’s URL without editing your code. For more information, see Using Web Services in ColdFusion MX Developer’s Guide.


Debugging & Logging section

The Debugging & Logging section contains the following pages:

  • Debugging Settings and Debugging IPs pages
  • Debugging IP Addresses page
  • Logging Settings page
  • Log Files page
  • Scheduled Tasks page
  • System Probes page
  • Code Compatibility Analyzer page
  • License Scanner page


Debugging Settings and Debugging IPs pages

You use the Debugging Settings and Debugging IPs pages to configure ColdFusion MX to provide debugging information for every application page requested by a browser. You specify debugging preferences using the pages as follows:

  • On the Debugging Settings page, select debugging output options. If debugging is enabled, the output appears in block format after normal page output.
  • On the Debugging IPs page, restrict access to debugging output. If a debugging option is enabled, debugging output is visible to all users by default.

Note: Enabling debugging affects performance. You should not enable debugging on a production server.

The Debugging Settings page provides the following debugging options:

Option

Description

Enable Robust Exception Information

Displays detailed information in the exceptions page, including the template’s physical path and URI, the line number and snippet, the SQL statement used (if any), the data source name (if any), and the Java stack trace.

Enable Debugging

Enables the ColdFusion debugging service.

Select Debugging Output Format

Controls debugging format. Select either of the following formats:

  • classic.cfm The format available in ColdFusion 5 and earlier. It provides a basic view and few browser restrictions.
  • dockable.cfm A dockable tree-based debugging panel. For details about the panel and browser restrictions, see the online Help.

Report Execution Times

Reports execution times that exceed a specified time limit.

General Debug Information

Show general information about the ColdFusion MX version, template, time stamp, user locale, user agent, user IP, and host name.

Database Activity

Shows the database activity for the SQL Query events and Stored Procedure events in the debugging output.

Exception Information

Shows all ColdFusion exceptions raised for the request in the debugging output.

Tracing Information

Shows trace event information in the debugging output. Tracing lets you track program flow and efficiency using the cftrace tag.

Timer Information

Shows output from the cftimer tag.

Variables

Displays information about parameters, URL parameters, cookies, sessions, and CGI variables in the debugging output.

Enable Performance Monitoring*

(Server configuration only)

Enables the standard NT Performance Monitor application to display information about a running server.

Enable CFSTAT*

(Server configuration only)

Shows performance information on platforms that do not support the NT Performance Monitor. For more information, see Using the cfstat utility.

* Restart ColdFusion MX after changing this setting.

Using the cfstat utility

The cfstat command-line utility provides real-time performance metrics for ColdFusion MX. Using a socket connection to obtain metric data, the cfstat utility displays the information that ColdFusion MX writes to the System Monitor without actually using the System Monitor application. The following table lists the metrics that the cfstat utility returns:

Metric abbreviation | Metric name | Description
Pg/Sec | Page hits per second | The number of ColdFusion pages processed per second. You can reduce this by moving static content to HTML pages.
DB/Sec | Database accesses per second | The number of database accesses per second made by ColdFusion MX. Any difference in complexity and resource load between calls is ignored.
CP/Sec | Cache pops per second | The number of ColdFusion template cache pops per second. A cache pop occurs when ColdFusion MX ejects a cached template from the template cache to make room for a new template.
Req Q'ed | Number of queued requests | The number of requests that are currently waiting for ColdFusion MX to process them. Lower values, which you can achieve with efficient CFML, are better.
Req Run'g | Number of running requests | The number of requests that ColdFusion MX is currently actively processing.
Req TO'ed | Number of timed out requests | The total number of ColdFusion requests that have timed out. Lower values, which you can achieve by aggressive caching, removing unnecessary dynamic operations and third-party events, are better.
AvgQ Time | Average queue time | A running average of the time, in milliseconds, that requests spend waiting for ColdFusion MX to process them. Lower values, which you can achieve with efficient CFML and enhanced caching, are better.
AvgReq Time | Average request time | A running average of the time, in milliseconds, that ColdFusion MX spends to process a request (including queued time). Lower values, which you can achieve with efficient CFML, are better.
AvgDB Time | Average database transaction time | A running average of the time that ColdFusion MX spends on database-related processing of ColdFusion requests.
Bytes In/Sec | Bytes incoming per second | The number of bytes that ColdFusion MX read in the last second (not an average).
Bytes Out/Sec | Bytes outgoing per second | The number of bytes that ColdFusion MX wrote in the last second (not an average).

Before you use the cfstat utility, ensure that you selected the Enable Performance Monitoring check box in the ColdFusion MX Administrator (on the Debugging & Logging > Debugging Settings page). If you select this check box, you must restart ColdFusion MX for this change to take effect.

cfstat options

The cf_root/bin directory contains the cfstat utility. From that directory, type cfstat and use the following switches:

Switch | Description | Comment
-n | Suppress column headers. | Useful for saving output to a file.
-s | Display output in a single line. | Display a single line and delay display of the first line so the cfstat utility can display meaningful values in the per-second counters.
# | Where # is an integer, display output every # seconds. | If you do not specify an integer, the cfstat utility returns one line. Specify this switch with or without the -s switch.

This example runs the cfstat utility and displays a new line every 20 seconds:

cfstat 20

Debugging IP Addresses page

You use the Debugging IP Addresses page to restrict debugging output to one or more IP addresses. You can add and remove IP addresses.

Note: If you do not specify IP addresses, and debugging options are active, ColdFusion MX displays debugging output for all users.


Logging Settings page

You use the Logging Settings page of the Administrator to change ColdFusion MX logging options. The following table describes the settings:

Option | Description
Log directory* | Specifies the directory to which error log files are written.
Maximum file size (kb) | Sets the maximum file size for log files. When a file hits this size, it automatically is archived.
Maximum number of archives | Sets the maximum number of log archives to create. When they reach this limit, files are deleted in the order of oldest to newest.
Log slow pages taking longer than [n] seconds | Logs the names of pages that take longer than the specified interval to process. Logging slow pages can help you diagnose potential problems or bottlenecks in your ColdFusion applications. Entries are written to the server.log file.
Log all CORBA calls | Logs all CORBA calls.
Enable logging for scheduled tasks | Logs ColdFusion Executive task scheduling.

* Restart ColdFusion MX after changing this setting.


Log Files page

The Log Files page lets you perform operations on log files, such as searching, viewing, downloading, archiving, and deleting.

Click on a Log File icon, located in the Actions column of the Available Log Files table, to search, view, download, archive, or delete a log file.

For more information, see the ColdFusion MX Administrator online Help.

The following table describes the ColdFusion MX log files:

Log file | Description
rdservice.log | Records errors that occur in the ColdFusion Remote Development Service (RDS). RDS provides remote HTTP-based access to files and databases.
application.log | Records every ColdFusion MX error reported to a user. Application page errors, including ColdFusion MX syntax, ODBC, and SQL errors, are written to this log file.
exception.log | Records stack traces for exceptions that occur in ColdFusion.
scheduler.log | Records scheduled events that have been submitted for execution. Indicates whether task submission was initiated and whether it succeeded. Provides the scheduled page URL, the date and time executed, and a task ID.
server.log | Records errors for ColdFusion MX.
customtag.log | Records errors generated in custom tag processing.
car.log | Records errors associated with site archive and restore operations.
mail.log | Records errors generated by an SMTP mail server.
mailsent.log | Records messages sent by ColdFusion MX.
flash.log | Records entries for Macromedia Flash Remoting.


Scheduled Tasks page

You use the Scheduled Tasks page to schedule the execution of local and remote web pages, to generate static HTML pages, send mail with the cfmail tag, update database tables, index Verity collections, delete temporary files, and any other batch-style processing. The scheduling facility is useful for applications that do not require user interactions or customized output. ColdFusion developers use this facility to schedule daily sales reports, corporate directories, statistical reports, and so on.

Information that is read more often than written is a good candidate for scheduled tasks. Instead of executing a query to a database every time the page is requested, ColdFusion MX renders the static page with information generated by the scheduled event. Response time is faster because no database transaction takes place.

You can run scheduled tasks once; on a specified date; or at a specified time, daily, weekly, or monthly; daily; at a specified interval; or between specified dates.

The Scheduled Task page lets you create, edit, and delete scheduled tasks. For more information, see the online help.


System Probes page

System probes help you evaluate the status of your ColdFusion applications. Like scheduled tasks, they access a URL at a specified interval, but they can also check for the presence or absence of a string in the URL. If the URL contents are unexpected, or if an error occurred while accessing the URL, the probe can send an e-mail alert to the address specified on the System Probes page. The probe can also execute a script to perform a recovery action, such as restarting the server. All probe actions are logged in the logs/probes.log file. The System Probes page also displays the status of each probe.

You use the buttons in the Actions column in the System Probes table to perform the following actions:

Action | Description
Edit | Lets you edit the probe.
Run | Runs the probe immediately, even if it was previously disabled.
Enable/Disable | Starts and stops the probe from automatically executing at its specified interval.
Delete | Deletes the probe.

Because probes run as scheduled ColdFusion tasks, they will not run if the server on which they are hosted crashes, or if the host web server crashes or otherwise does not respond.

System probes are available in ColdFusion MX Enterprise Edition only.


Code Compatibility Analyzer page

The Code Compatibility Analyzer page evaluates your ColdFusion pages for potential incompatibilities between ColdFusion MX 7 and ColdFusion Server 5. It reviews the CFML pages that you specify and informs you of any potential compatibility issues. Additionally, the Code Compatibility Analyzer detects unsupported and deprecated CFML features, and outlines the required implementation changes that ensure a smooth migration


License Scanner page

The License Scanner page searches the local subnet to find other running instances of ColdFusion MX 7. You can use this information to determine whether the ColdFusion instances within the subnet are licensed appropriately.

The ColdFusion MX Administrator uses universal datagram protocol (UDP) multicast to collect license and version information from all ColdFusion instances running within the subnet.


Extensions section

You use the Extensions section of the Administrator to configure ColdFusion MX to work with other technologies, such as Java and CORBA.

The Extensions section contains the following pages:

  • Java Applets page
  • CFX Tags page
  • Custom Tag Paths page
  • CORBA Connectors page


Java Applets page

The Java Applets page of the Administrator lets you register applets and edit and delete applet registrations. Before you can use Java applets in your ColdFusion applications, you must register them in the Java Applets page.

When your applet is registered with ColdFusion MX, using the cfapplet tag in your CFML code is very simple, because all parameters are predefined. Simply enter the applet source and the form variable name that you want to use.

Note: Parameters set with the cfapplet tag override parameters defined on the Java Applets page.

For more information, see the online help.


CFX Tags page

Before you can use a CFX tag in ColdFusion applications, you must register it. You use the CFX Tags page to register and manage ColdFusion custom tags built with C++ and Java.

You can build CFX tags in the following two ways:

  • Using C++ as a dynamic link library (DLL) on Windows or as shared objects (.so or .sl extension) on Solaris and Linux
  • Using Java interfaces defined in the cfx.jar file

For more information, see the online help.


Custom Tag Paths page

You use the Custom Tag Paths page of the Administrator to add, edit, and delete custom tag directory paths. The default custom tag path is under the installation directory. To use custom tags in another path, register the path on this Administrator page.

For more information, see the online Help.


CORBA Connectors page

You use the CORBA Connectors page to register, edit, and delete CORBA connectors. You must register CORBA connectors before you use them in ColdFusion applications. You must also restart the server when you finish configuring the CORBA connector.

ColdFusion MX loads object request broker (ORB) libraries dynamically using a connector, which does not restrict ColdFusion developers to a specific ORB vendor. The connectors depend on the ORB runtime libraries provided by the vendor. A connector for Borland Visibroker is embedded within ColdFusion MX. Make sure that the ORB runtime libraries are in cf_root/runtime/lib (server configuration) or cf_webapp_root/WEB-INF/cfusion/lib (multiserver and J2EE configurations).

The following table contains information about the libraries and connectors:

Operating System | Vendor | ORB | ColdFusion connector | ORB library
Windows NT and later | Borland | VisiBroker 4.5 | coldfusion.runtime.corba.VisibrokerConnector (embedded) | vbjorb.jar
Solaris | Borland | VisiBroker 4.5 | coldfusion.runtime.corba.VisibrokerConnector (embedded) | vbjorb.jar

The following lines are an example of a CORBA connector configuration for VisiBroker:

ORB Name							visibroker
ORB Class Name							coldfusion.runtime.corba.VisibrokerConnector
ORB Property File							c:\CFusionMX7\runtime\cfusion\lib\vbjorb.properties
Classpath							[blank]

ColdFusion includes the vbjorb.properties file, which contains the following properties that configure the ORB:

org.omg.CORBA.ORBClass=com.inprise.vbroker.orb.ORB
org.omg.CORBA.ORBSingletonClass=com.inprise.vbroker.orb.ORB
SVCnameroot=namingroot


Event Gateways section

The Event Gateways section of the Administrator lets you configure event gateway settings, gateway types, and gateway instances.

This Event Gateways section contains the following pages:

  • Event Gateway Settings page
  • Gateway Types page
  • Gateway Instances page

Event Gateway Settings page

The Event Gateway Settings page lets you configure settings for all event gateways, and start or stop the Short Message Service (SMS) test server. The following table describes the settings:

Option | Description
Enable ColdFusion Event Gateway Service | Specifies whether the service is enabled. Changing this setting restarts the service.
Event Gateway Processing Threads | Specifies the maximum number of threads used to execute ColdFusion functions when an event arrives. A higher number uses more resources, but increases event throughput.
Maximum Number of Events to Queue | Specifies the maximum number of events allowed on the event queue. If the queue length exceeds this value, gateway events will not be added to the processing queue.
Start/Stop SMS Test Server | Starts and stops the short message service (SMS) test server.

Gateway Types page

The Gateways Types pages lets you configure the types of gateways available on your system. After you configure a type, you can create any number of gateway instances of that type. The following table describes the event gateway types that ship with ColdFusion MX:

Gateway type

Description

CFML

Used to trigger asynchronous events from ColdFusion.

SMS

Used to send and receive SMS messages.

SAMETIME

Used to send and receive instant messages through Lotus SameTime.

XMPP

Used to send and receive instant messages through the Extensible Messaging and Presence Protocol (XMPP).

Samples

Sample gateway types, including the following:

  • DirectoryWatcher Watches a directory for file changes.
  • JMS Acts as a Java Messaging Service consumer or producer.
  • Socket Listens on a TCP/IP port.

Gateway Instances page

The Gateway Instances page lets you configure ColdFusion event gateway instances to direct events from various sources to ColdFusion components (CFCs) that you have written. The following table describes the settings:

Option

Description

Gateway ID

A name for the event gateway instance. You use this value in the ColdFusion GetGatewayHelper and SendGatewayMessage functions.

Gateway Type

The event gateway type.

CFC Path

The absolute path to the listener CFC that handles incoming messages.

Configuration File

(Optional) Configuration file, if required for the event gateway instance.

Startup Mode

The event gateway startup status, as follows:

  • Automatic Start the event gateway when ColdFusion starts.
  • Manual Do not start the event gateway with ColdFusion, but allow starting it from the Gateway Instances page.
  • Disabled Do not allow the event gateway to start.


Security section

The Security section of the Administrator lets you configure the security frameworks of ColdFusion MX.

For more information on security, see Administering Security.

The Security section contains the following pages:

  • CF Admin Password page
  • RDS Password page
  • Sandbox Security page

CF Admin Password page

You use the CF Admin Password page of the Administrator to enable and disable password-restricted access to the Administrator, and to change the Administrator password. You should restrict ColdFusion MX Administrator access to trusted users.

RDS Password page

You use the RDS Password page to enable and disable password-restricted RDS access to server resources from Macromedia Dreamweaver MX, Macromedia HomeSite+, or the ColdFusion Report Builder, and to change the RDS password.

Sandbox Security page

You use the Sandbox Security page (called Resource Security in the Standard Edition) to specify security permissions for data sources, tags, functions, files, and directories.

Sandbox security uses the location of your ColdFusion pages to determine functionality. A sandbox is a designated area (CFM files or directories that contain CFM files) of your site to which you apply security restrictions. By default, a subdirectory (or child directory) inherits the sandbox settings of the directory one level above it (the parent directory). If you define sandbox settings for a subdirectory, you override the sandbox settings inherited from the parent directory.

Use sandbox security to control access to the following:

  • Data sources
  • Tags
  • Functions
  • Files and directories
  • IP addresses and ports

Note: If you have enabled sandbox security and want to use the Administrator API, you must enable access to the CFIDE/adminapi directory.


Packaging and Deployment section

The Packaging and Deployment section of the Administrator lets you create and deploy CAR files and create J2EE EAR or WAR files that include an existing ColdFusion application and the ColdFusion runtime system

This Packaging and Deployment section contains the following pages:

  • ColdFusion Archives page
  • J2EE Archives page

ColdFusion Archives page

The ColdFusion Archives page includes tools that let you archive and deploy ColdFusion applications, configuration settings, data source information, and other types of information to back up your files quickly and easily. The complete list of archivable information includes the following:

  • Name and file location
  • Server settings
  • ColdFusion mappings
  • Data sources
  • Verity collections
  • Scheduled tasks
  • Event gateway instances
  • Java applets
  • CFX tags
  • Archive to do lists

After you archive the information, you can use the Administrator to deploy your web applications to the same ColdFusion MX server or to a ColdFusion MX server running on a different computer. Additionally, you can use these features to deploy and receive any ColdFusion archive file electronically.

The Archive Settings page lets you configure various archive system settings that apply to all archive and deployment operations. For more information, see the online help.

J2EE Archives page

The J2EE Archives page lets you create an enterprise application archive (EAR) file or web application archive (WAR) file that contains the following items:

  • The ColdFusion MX web application.
  • Server settings, such as data sources and custom tag paths.
  • Your application’s CFML pages, stored in the ColdFusion web application’s root directory.

With this EAR or WAR file, a J2EE administrator can deploy your ColdFusion MX application to a J2EE application server.

Tip: If you are creating a cluster of server instances when running the multiserver configuration, use this page to create the WAR or EAR file to be used when creating each of the servers in the cluster.

You can create a J2EE archive regardless of whether you are running ColdFusion MX in the server configuration or the J2EE configuration. However, you must be running the J2EE configuration to deploy an EAR or WAR file.


Enterprise Manager section

The Enterprise Manager section of the Administrator lets you create Macromedia JRun server instances with ColdFusion already deployed, register remote JRun server instances, and create clusters of JRun server instances.

Note: The Enterprise Manager section appears only if you install the multiserver configuration. It does not display in the server configuration. Nor does it display when running in a J2EE configuration (other than that deployed in the cfusion server of the multiserver configuration).

The Enterprise Manager section contains the following pages:

  • Instance Manager page
  • Cluster Manager page

Instance Manager page

The Instance Manager page lets you view the local and remote JRun servers that can be accessed by a cfusion server running in the multiserver configuration.

From this page you can access pages that define new, local, JRun servers and register existing JRun servers running on remote computers, as follows:

Add New Instance Create a new JRun server and automatically deploy a copy of the current ColdFusion MX application into that server. Alternatively, you can deploy ColdFusion MX applications packaged using the J2EE Archives page.

Register Remote Instance Define an existing remote JRun server to the Instance Manager for the purpose of adding these servers to a cluster. The remote JRun server instance need not be running when you define it to the Instance Manager, however, it must be running before you can add it to a cluster.

Cluster Manager page

The Cluster Manager page in ColdFusion MX Administrator lets you create and manage clusters of JRun servers, each containing the same ColdFusion MX application.


Custom Extensions section

You can extend the functionality of the ColdFusion MX Administrator by adding links to other web applications and sites. These links appear under the Custom Extensions section in the left navigation pane of the Administrator.

To extend the Administrator:

  1. Create a file that contains the HTML link code, followed by a <BR>, with a separate line for each link. Do not include other HTML code, such as <head> or <body> tags.

    The target attribute is required for each link; if you specify target="content", the page appears in the main pane of the Administrator. If you specify any other value for the target attribute, the page appears in a new window.

  2. Save this file as extensionscustom.cfm in the Administrator root directory (/CFIDE/administrator/).

For example, the following file adds links for Bowdoin College, Universidad Complutense de Madrid, and La Sapienza:

<a href="http://www.bowdoin.edu/" target="content">Bowdoin College</a><br>
<a href="http://www.http://www.ucm.es/" target="_blank">Universidad Complutense de Madrid</a><br>
<a href="http://www.uniroma1.it/" target="_blank">La Sapienza</a><br>

When you click a link, the page appears.


Administrator API

You can perform most ColdFusion MX Administrator tasks programmatically using the Administrator API. The Administrator API consists of a set of ColdFusion components (CFCs) that contain methods you call to perform Administrator tasks. For example, you use the setMSQL method of datasource.cfc to add a SQL Server data source.

The CFCs for the Administrator API are located in the cf_web_root/CFIDE/adminapi directory, and each CFC corresponds to an area of the ColdFusion MX Administrator, as the following table shows:

CFC | Description
administrator.cfc | Contains basic Administrator functionality, including login, logout, the Migration Wizard, and the Setup Wizard. You must call the login method before calling any other methods in the Administrator API.
base.cfc | Base object for all other Administrator API CFCs.
datasource.cfc | Add, modify, and delete ColdFusion data sources.
debugging.cfc | Manage debug settings.
eventgateway.cfc | Manage event gateways.
extensions.cfc | Manage custom tags, mappings, CFXs, applets, CORBA, and web services.
mail.cfc | Manage ColdFusion mail settings.
runtime.cfc | Manage runtime settings for fonts, cache, charts, configuration, and other settings.
security.cfc | Manage passwords, RDS, and sandbox security.
serverinstance.cfc | Start, stop, and restart JRun servers. This CFC only works when running the multiserver configuration.

The adminapi directory also contains an Application.cfm file and two subdirectories.

Note: If you are using sandbox security, you must enable access to the cf_web_root/CFIDE/adminapi directory to use the Administrator API.

There are two styles of methods in the Administrator API:

  • Method arguments When setting complex or varied values, the Administrator API uses method arguments.
  • Getting and setting simple values When setting simple values, such as true or false debug settings, the Administrator API uses get and set property methods.

To view the methods, method arguments, and documentation for the Administrator API CFCs, use the CFC Explorer. For example, to view datasource.cfc when running in the server configuration, open a browser to http://localhost:8500/CFIDE/adminapi/datasource.cfc.

To use the Administrator API:

  1. Instantiate administrator.cfc:
    <cfscript>
    // Login is always required.
    adminObj = createObject("component","cfide.adminapi.administrator");

    Tip: You can instantiate administrator.cfc and call the login method in a single line of code, as the following example shows:

    createObject("component","cfide.adminapi.administrator").login("admin");
  2. Call the administrator.cfc login method, passing the ColdFusion MX Administrator password or the RDS password:
    adminObj.login("admin");
  3. Instantiate the desired CFC:
    myObj = createObject("component","cfide.adminapi.debugging");
  4. Call the desired CFC method (this example enables debugging):
    myObj.setDebugProperty(propertyName="enableDebug", propertyValue="true");

Examples

The following example adds a SQL Server data source:

<cfscript>
    // Login is always required. This example uses two lines of code.
    adminObj = createObject("component","cfide.adminapi.administrator");
    adminObj.login("admin");

    // Instantiate the data source object.
    myObj = createObject("component","cfide.adminapi.datasource");

    // Create a DSN.
    myObj.setMSSQL(driver="MSSQLServer",
        name="northwind_MSSQL",
        host = "10.1.147.73",
        port = "1433",
        database = "northwind",
        username = "sa",
        login_timeout = "29",
        timeout = "23",
        interval = 6,
        buffer = "64000",
        blob_buffer = "64000",
        setStringParameterAsUnicode = "false",
        description = "Northwind SQL Server",
        pooling = true,
        maxpooledstatements = 999,
        enableMaxConnections = "true",
        maxConnections = "299",
        enable_clob = true,
        enable_blob = true,
        disable = false,
        storedProc = true,
        alter = false,
        grant = true,
        select = true,
        update = true,
        create = true,
        delete = true,
        drop = false,
        revoke = false );
</cfscript>

The following example adds the same SQL Server data source, but uses the argumentCollection attribute to pass all method arguments in a structure:

<cfscript>
    // Login is always required. This example uses a single line of code.
    createObject("component","cfide.adminapi.administrator").login("admin");

    // Instantiate the data source object.
    myObj = createObject("component","cfide.adminapi.datasource");

    // Required arguments for a data source.
    stDSN = structNew();
    stDSN.driver = "MSSQLServer";
    stDSN.name="northwind_MSSQL";
    stDSN.host = "10.1.147.73";
    stDSN.port = "1433";
    stDSN.database = "northwind";
    stDSN.username = "sa";

    // Optional and advanced arguments.
    stDSN.login_timeout = "29";
    stDSN.timeout = "23";
    stDSN.interval = 6;
    stDSN.buffer = "64000";
    stDSN.blob_buffer = "64000";
    stDSN.setStringParameterAsUnicode = "false";
    stDSN.description = "Northwind SQL Server";
    stDSN.pooling = true;
    stDSN.maxpooledstatements = 999;
    stDSN.enableMaxConnections = "true";
    stDSN.maxConnections = "299";
    stDSN.enable_clob = true;
    stDSN.enable_blob = true;
    stDSN.disable = false;
    stDSN.storedProc = true;
    stDSN.alter = false;
    stDSN.grant = true;
    stDSN.select = true;
    stDSN.update = true;
    stDSN.create = true;
    stDSN.delete = true;
    stDSN.drop = false;
    stDSN.revoke = false;

    //Create a DSN.
    myObj.setMSSQL(argumentCollection=stDSN);
</cfscript>
<!--- Optionally dump the stDSN structure. --->
<!---
<cfoutput>
<cfdump var="#stDSN#">
</cfoutput>
--->

Previous


Data Source Management

A data source is a complete database configuration that uses a JDBC driver to communicate with a specific database. In Macromedia ColdFusion MX 7, you must configure a data source for each database that you want to use. After you configure a data source, ColdFusion can then communicate with that data source through JDBC.

This chapter describes the configuration options for ColdFusion MX 7 data sources. For basic information on data sources and connecting to databases, see Getting Started Building ColdFusion MX Applications.

Contents

About JDBC

Adding data sources

Connecting to DB2 Universal Database

Connecting to Informix

Connecting to Microsoft Access

Connecting to Microsoft Access with Unicode

Connecting to Microsoft SQL Server

Connecting to MySQL

Connecting to ODBC Socket

Connecting to Oracle

Connecting to other data sources

Connecting to Sybase

Connecting to JNDI data sources
Next


About JDBC

JDBC is a Java Application Programming Interface (API) that you use to execute SQL statements. JDBC enables an application, such as ColdFusion MX 7, to interact with a variety of database management systems (DBMSs), without using interfaces that are database- and platform-specific.

The following table describes the four types of JDBC drivers:

Type

Name

Description

1

JDBC-ODBC bridge

Translates JDBC calls to ODBC calls, and sends them to the ODBC driver.

Advantages Allows access to many different databases.

Disadvantages The ODBC driver, and possibly the client database libraries, must reside on the ColdFusion server computer. Performance is slower than other JDBC driver types.

Macromedia does not recommend this driver type unless your application requires DBMS-specific features.

2

Native-API/partly Java driver

Converts JDBC calls to database-specific calls.

Advantages Better performance than Type 1 driver.

Disadvantages The vendor’s client database libraries must reside on the same computer as ColdFusion.

ColdFusion MX includes a type 2 driver for use with Microsoft Access Unicode databases.

3

JDBC-Net pure Java driver

Translates JDBC calls to the middle-tier server, which then translates the request to the database-specific native-connectivity interface.

Advantages No need for vendor’s database libraries to be present on client computer. Can be tailored for small size (faster loading).

Disadvantages Database-specific code must be executed in the middle tier.

ColdFusion MX includes an ODBC socket type 3 driver for use with Microsoft Access databases and ODBC data sources.

4

Native-protocol/all-Java driver

Converts JDBC calls to the network protocol used directly by the database.

Advantages Fast performance. No special software needed on the computer on which you run ColdFusion MX.

Disadvantages Many of these protocols are proprietary, requiring a different driver for each database.

ColdFusion MX includes type 4 drivers for many popular DBMSs; however, not all DBMSs are supported in ColdFusion MX Standard Edition.

JDBC drivers are stored in JAR files. For example, the JDBC drivers that are supplied with ColdFusion MX are in the macromedia_drivers.jar file. If you are using another JDBC driver, you must store it in the ColdFusion classpath. For example, cf_root/cfusion/lib (server configuration) or cf_webapp_root/WEB-INF/cfusion/lib (multiserver or J2EE configuration).

Supplied drivers

The following table lists the database drivers supplied with ColdFusion MX and where you can find more information about them:

Driver | Type | For more information
DB2 Universal Database | 4 | Connecting to DB2 Universal Database
DB2 OS/390 | 4 | Connecting to other data sources
Informix | 4 | Connecting to Informix
Microsoft Access | 3 | Connecting to Microsoft Access
Microsoft Access with Unicode support | 2 | Connecting to Microsoft Access with Unicode
Microsoft SQL Server | 4 | Connecting to Microsoft SQL Server
MySQL | 4 | Connecting to MySQL
ODBC Socket | 3 | Connecting to ODBC Socket
Oracle | 4 | Connecting to Oracle
Other |  | Connecting to other data sources
Sybase | 4 | Connecting to Sybase

To see a list of database versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf.

When running in the J2EE configuration, the ColdFusion MX Administrator also lets you configure a data source that connects to a JNDI data source. A Java Naming and Directory Interface (JNDI) data source is equivalent to a ColdFusion data source, except you define it using your J2EE application server. After it’s defined, ColdFusion MX applications use it as they would any data source. For information on defining a JNDI data source, see Connecting to JNDI data sources.


Adding data sources

In the ColdFusion MX Administrator, you configure your data sources to communicate with ColdFusion. After you add a data source to the Administrator, you access it by name in any CFML tag that establishes database connections; for example, in the cfquery tag. During a query, the data source tells ColdFusion which database to connect to and what parameters to use for the connection.

The ColdFusion MX Administrator organizes all the information about a ColdFusion MX server’s database connections in a single, easy-to-manage location. In addition to adding new data sources, you can use the Administrator to specify changes to your database configuration, such as relocation, renaming, or changes in security permissions.


Adding data sources in the Administrator

You use the ColdFusion MX Administrator to quickly add a data source for use in your ColdFusion applications. When you add a data source, you assign it a data source name (DSN) and set all information required to establish a connection.

Note: ColdFusion MX includes data sources that are configured by default. You do not need the following procedure to work with these data sources.

To add a data source:

  1. In the ColdFusion MX Administrator, select Data & Services > Data Sources.
  2. Under Add New Data Source, enter a Data Source Name; for example, MyTestDSN. The following names are reserved; you cannot use them for data source names:
    • service
    • jms_provider
    • comp
    • jms
  3. Select a Driver from the drop-down list box; for example, Microsoft SQL Server.
  4. Click Add.

    A form for additional DSN information appears. The available fields in this form depend on the driver that you selected.

  5. In the Database field, enter the name of the database; for example, Northwind.
  6. In the Server field, enter the network name or IP address of the server that hosts the database, and enter any required Port value; for example, the bullwinkle server on the default port.
  7. If your database requires login information, enter your Username and Password.

    Tip: The omission of required username and password information is a common reason why a data source fails to verify.

  8. (Optional) Enter a Description.
  9. (Optional) Click Show Advanced Settings to specify any ColdFusion specific settings; for example, to configure which SQL commands can interact with this data source.
  10. Click Submit to create the data source.

    ColdFusion MX automatically verifies that it can connect to the data source.

  11. (Optional) To verify this data source later, click the verify icon in the Actions column.

    Note: To check the status of all data sources available to ColdFusion MX, click Verify All Connections.

Specifying connection string arguments

The ColdFusion MX Administrator lets you specify connection string arguments for data sources. In the Advanced Settings page, use the Connection String field to enter name-value pairs separated by a semicolon. For more information, see the documentation for your database driver.

Note: As of ColdFusion MX, the cfquery connectstring attribute is not supported.

Guidelines for data sources

When you add data sources to ColdFusion MX, keep the following guidelines in mind:

  • Data source names should be all one word.
  • Data source names can contain only letters, numbers, hyphens, and the underscore character (_).
  • Data source names should not contain special characters or spaces.
  • Although data source names are not case-sensitive, you should use a consistent capitalization scheme.
  • Depending on the JDBC driver, connection strings and JDBC URLs might be case-sensitive.
  • Ensure that you use the Administrator to verify that ColdFusion MX can connect to the data source.
  • A data source must exist in the ColdFusion MX Administrator before you use it on an application page to retrieve data.


Connecting to DB2 Universal Database

This section discusses using the ColdFusion MX Administrator to define data sources for DB2 Universal Database (UDB). For information on defining data sources that work with DB2 for OS/390 or iSeries, see Connecting to other data sources. To see a list of DB2 versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf.

Note: DB2 UDB refers to all versions of DB2 running on Windows, UNIX, and Linux/s390 platforms.

Use the settings in the following table to connect ColdFusion MX to DB2:

Setting

Description

CF Data Source Name

The data source name (DSN) used by ColdFusion MX to connect to the data source.

Database

The name of the database.

Server

The name of the server that hosts the database that you want to use. If the database is local, enclose the word local in parentheses.

Port

The number of the TCP/IP port that the server monitors for connections.

Username

The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).

The user name must have CREATE PACKAGE privileges for the database, or the database administrator must create a package. Consult the database administrator when configuring this type of data source.

Password

The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).

Description

(Optional) A description for this connection.

Connection String

A field that passes database-specific parameters, such as login credentials, to the data source.

For UDB on the initial connection, specify DatabaseName, CreateDefaultPackage, ReplacePackage, and sendStringParametersAsUnicode (with no spaces), as the following example shows:

DatabaseName=SAMPLE;CreateDefaultPackage=TRUE;ReplacePackage=TRUE;
sendStringParametersAsUnicode=false

If the database uses Unicode, specify true for the sendStringParametersAsUnicode parameter.

For UDB on subsequent connections, specify DatabaseName and sendStringParametersAsUnicode (with no spaces), as the following example shows:

DatabaseName=SAMPLE;sendStringParametersAsUnicode=false

Your user ID must have CREATE PACKAGE privileges on the database, or your database administrator must create a package for you.

Limit Connections

Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.

Restrict Connections To

Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.

Maintain Connections

ColdFusion establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.

Max Pooled Statements

Enables reuse of prepared statements (that is, stored procedures and queries that use the cfqueryparam tag). Although you tune this setting based on your application, start by setting it to the sum of the following:

  • Unique cfquery tags that use the cfqueryparam tag
  • Unique cfstoredproc tags

Timeout (min)

The number of minutes that ColdFusion MX maintains an unused connection before destroying it.

Interval (min)

The time (in minutes) that the server waits between cycles to check for expired data source connections to close.

Disable Connections

If selected, suspends all client connections.

Login Timeout (sec)

The number of seconds before ColdFusion times out the data source connection login attempt.

CLOB

Select to return the entire contents of any CLOB/Text columns in the database for this data source. If unchecked, ColdFusion retrieves the number of characters specified in the Long Text Buffer setting. For UDB 7.1 and 7.2, there is a 32K limit on CLOBs.

BLOB

Select to return the entire contents of any BLOB/Image columns in the database for this data source. If unchecked, ColdFusion retrieves the number of characters specified in the BLOB Buffer setting. BLOBs are not supported on UDB 7.1 and 7.2.

LongText Buffer (chr)

The default buffer size, used if the CLOB option is not selected. The default value is 64000 bytes.

BLOB Buffer (bytes)

The default buffer size, used if the BLOB option is not selected. The default value is 64000 bytes.

Allowed SQL

The SQL operations that can interact with the current data source.


Connecting to Informix

To see a list of Informix versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf. Use the settings in the following table to connect ColdFusion MX to Informix data sources:

Setting

Description

CF Data Source Name

The data source name (DSN) used by ColdFusion MX to connect to the data source.

Database

The database to which this data source connects.

Informix Server

The name of the Informix database server to which you want to connect.

Server

The name of the server that hosts the database. If the database is local, enclose the word local in parentheses.

Port

The number of the TCP/IP port that the server monitors for connections.

Username

The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).

Password

The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).

Description

(Optional) A description for this connection.

Connection String

A field that passes database-specific parameters, such as login credentials, to the data source.

Limit Connections

Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.

Restrict Connections To

Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.

Maintain Connections

ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.

Max Pooled Statements

Enables reuse of prepared statements (that is, stored procedures and queries that use the cfqueryparam tag). Although you tune this setting based on your application, start by setting it to the sum of the following:

  • Unique cfquery tags that use the cfqueryparam tag
  • Unique cfstoredproc tags

Timeout (min)

The number of minutes that ColdFusion MX maintains an unused connection before destroying it.

Interval (min)

The time (in minutes) that the server waits between cycles to check for expired data source connections to close.

Disable Connections

If selected, suspends all client connections.

Login Timeout (sec)

The number of seconds before ColdFusion MX times out the data source connection login attempt.

CLOB

Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.

BLOB

Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.

LongText Buffer

The default buffer size, used if the CLOB option is not selected. The default value is 64000 bytes.

BLOB Buffer

The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.

Allowed SQL

The SQL operations that can interact with the current data source.


Connecting to Microsoft Access

Use the settings in the following table to connect ColdFusion MX to Microsoft Access data sources:

Setting | Description
CF Data Source Name | The data source name (DSN) used by ColdFusion MX to connect to the data source.
Database File | The file that contains the database.
System Database File | To secure access to the specified database file, click Browse Server to locate and enter a database that contains database security information. The system database is usually located in the same directory as the MDB file or in the windows\system32\system.mdw directory.
Use Default Username | If selected, ColdFusion MX does not pass a user name or password when requesting a connection. The Microsoft Access driver uses the default user name and password.
ColdFusion Username | The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
ColdFusion Password | The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Description | (Optional) A description for this connection.
Page Timeout | The number of milliseconds before a request for a ColdFusion page times out. The default is 600. If you observe excessive network activity when using this driver, increase the page timeout value.
Max Buffer Size | The size of the internal buffer, in kilobytes, that Access uses to transfer data to and from the disk. The default buffer size is 2048 KB. Specify an integer value divisible by 256.
Connection String | A field that passes database-specific parameters, such as login credentials, to the data source.
Default Username | The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
Default Password | The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Return Timestamp as String | Enable this setting if your application retrieves Date/Time data and then reuses it in SQL statements without applying formatting (using functions such as DateFormat, TimeFormat, and CreateODBCDateTime).
Limit Connections | Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.
Restrict Connections To | Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.
Maintain Connections | ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.
Timeout (min) | The number of minutes that ColdFusion MX maintains an unused connection before destroying it.
Interval (min) | The time (in minutes) that the server waits between cycles to check for expired data source connections to close.
Disable Connections | If selected, suspends all client connections.
Login Timeout (sec) | The number of seconds before ColdFusion MX times out the data source connection login attempt.
CLOB | Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.
BLOB | Select to return the entire contents of any BLOB/Image columns in the database for this data source. If unchecked, ColdFusion retrieves the number of characters specified in the BLOB Buffer setting.
LongText Buffer | The default buffer size, used if the CLOB option is not selected. The default value is 64000 bytes.
BLOB Buffer | The default buffer size, used if the BLOB option is not selected. The default value is 64000 bytes.
Allowed SQL | The SQL operations that can interact with the current data source.


Connecting to Microsoft Access with Unicode

Use the settings in the following table to connect ColdFusion MX to Microsoft Access with Unicode data sources (this is a Type 2 driver):

Setting | Description
CF Data Source Name | The data source name (DSN) used by ColdFusion MX to connect to the data source.
Database File | The file that contains the database.
Description | (Optional) A description for this connection.
ColdFusion Username | The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
ColdFusion Password | The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Page Timeout | The time (in tenths of a second) before a request for a ColdFusion page times out.
Max Buffer Size | The size of the internal buffer, in kilobytes, used by Microsoft Access to transfer data to and from the disk. Can be any integer value divisible by 256.
Connection String | A field that passes database-specific parameters, such as login credentials, to the data source.
Limit Connections | Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.
Restrict Connections To | Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.
Maintain Connections | ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.
Timeout (min) | The number of minutes that ColdFusion MX maintains an unused connection before destroying it.
Interval (min) | The time (in minutes) that the server waits between cycles to check for expired data source connections to close.
Disable Connections | If selected, suspends all client connections.
Login Timeout (sec) | The number of seconds before ColdFusion MX times out the data source connection login attempt.
CLOB | Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.
BLOB | Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.
LongText Buffer | The default buffer size, used if the CLOB option is not selected. The default value is 64000 bytes.
BLOB Buffer | The default buffer size, used if the BLOB option is not selected. The default value is 64000 bytes.
Allowed SQL | The SQL operations that can interact with the current data source.

Note: This driver uses the Microsoft Jet list of reserved words, including the word Last. For a complete list, see http://support.microsoft.com/?kbid=248738.


Connecting to Microsoft SQL Server

To see a list of SQL Server versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf. Use the settings in the following table to connect ColdFusion MX to Microsoft SQL Server:

Setting

Description

CF Data Source Name

The data source name (DSN) used by ColdFusion MX to connect to the data source.

Database

The database to which this data source connects.

Server

The name of the server that hosts the database that you want to use. If the database is local, enclose the word local in parentheses. If you are running SQL Server locally (or using MSDE), specify 127.0.0.1 for the

server name instead of the actual instance name.

Port

The number of the TCP/IP port that the server monitors for connections.

Username

The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).

Password

The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).

Description

(Optional) A description for this connection.

Connection String

A field that passes database-specific parameters, such as login credentials, to the data source.

Select Method

Determines whether server cursors are used for SQL queries.

  • The Direct method provides more efficient retrieval of data when you retrieve record sets in a forward-only direction and you limit your SQL Server connection to a single open SQL statement at a time. This is typical for ColdFusion applications.
  • The Cursor method lets you have multiple open SQL statements on a connection. This is not typical for ColdFusion applications, unless you use pooled statements.

Limit Connections

Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.

Restrict Connections To

Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.

Maintain Connections

ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.

String Format

Enable this option if your application uses Unicode data in DBMS-specific Unicode datatypes, such as National Character or nchar.

Max Pooled Statements

Enables reuse of prepared statements (that is, stored procedures and queries that use the cfqueryparam tag). Although you tune this setting based on your application, start by setting it to the sum of the following:

  • Unique cfquery tags that use the cfqueryparam tag
  • Unique cfstoredproc tags

Timeout (min)

The number of minutes that ColdFusion MX maintains an unused connection before destroying it.

Interval (min)

The time (in minutes) that the server waits between cycles to check for expired data source connections to close.

Disable Connections

If selected, suspends all client connections.

Login Timeout (sec)

The number of seconds before ColdFusion MX times out the data source connection login attempt.

CLOB

Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.

BLOB

Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.

LongText Buffer

The default buffer size, used if Enable Long Text Retrieval(CLOB) is not selected. The default value is 64000 bytes.

BLOB Buffer

The default buffer size, used if the BLOB option is not selected. The default value is 64000 bytes.

Allowed SQL

The SQL operations that can interact with the current data source.

Settings for the Northwind sample database

SQL Server ships with a sample database named Northwind. Establishing a connection to the Northwind database can help you learn ColdFusion MX while using a familiar database.

To establish a connection to the SQL Server Northwind database, you must set up the database int he SQL Server Enterprise manager and in the ColdFusion MX Administrator.

To set up the database in the SQL Server Enterprise manager:

  1. Expand the server group.
  2. Expand the server.
  3. Under the Security folder, right-click on Logins.
  4. Select New Login.
  5. Select Windows Authentication or SQL Server Authentication settings.
  6. Select the Northwind database, and specify the language.
  7. Ensure that the database server is using mixed authentication. While in Enterprise Manager, right click on the server, select Properties > Security and then select the Security tab. Ensure that the SQL Server and Windows radio button is clicked.
  8. Click OK.

To set up the database in the ColdFusion MX Administrator:

  1. Open the ColdFusion MX Administrator.
  2. Click Data & Services > Data Sources.
  3. Type northwind in the Data Source Name field, and select Microsoft SQL Server in the Driver drop-down list box.
  4. Click Add.
  5. Type Northwind in the Database Name field, 127.0.0.1 (or the database server IP address) in the Server field, and 1433 in the Port field.

    Note: Do not specify a user name or password when defining the data source.

  6. Save the data source.

Troubleshooting SQL Server connections

If you are having trouble establishing a connection to SQL Server, review the following considerations:

  • If you installed SQL Server using a server name other than the default, you must use your chosen domain\servername wherever there’s a reference to (local).

The following situations can cause a Connection Refused error:

  • If you specified authentication information in SQL Server, ensure that you have not defined a username and password in the ColdFusion data source.
  • You are running a connection-limited version of SQL Server and the request exceeds the limit for TCP/IP connections.

    You can prevent this exception by setting the Limit Connections and Restrict Connections To options in ColdFusion MX Administrator on the Advanced Settings page for the data sources, and specifying a number less than the SQL Server maximum.

  • SQL Server does not enable the TCP/IP protocol. This problem can happen when SQL Server is on the same computer as ColdFusion MX. To fix this problem, perform the following steps:
    1. In SQL Server Enterprise Manager, right-click on the name of your SQL Server and click Properties.
    2. Click Network Configuration and the General Tab.
    3. Move TCP/IP from the Disabled Protocols section to the Enabled Protocols section.
    4. Click OK.
    5. Restart the SQL Server services.
    6. Verify your data source.
  • If you have are having trouble connecting, consider using mixed-mode authentication for SQL Server (Windows and SQL) and removing the user name and password from the ColdFusion data source.


Connecting to MySQL

To see a list of MySQL versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf. Use the settings in the following table to connect ColdFusion MX to MySQL data sources:

Setting | Description
CF Data Source Name | The data source name (DSN) used by ColdFusion MX to connect to the data source.
Database | The database to which this data source connects.
Server | The name of the server that hosts the database that you want to use. If the database is local, enclose the word local in parentheses.
Port | The number of the TCP/IP port that the server monitors for connections.
Username | The user name that ColdFusion MX passes to the JDBC driver to connect to the data source, if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
Password | The password that ColdFusion MX passes to the JDBC driver to connect to the data source, if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Description | (Optional) A description for this connection.
Connection String | A field that passes database-specific parameters, such as login credentials, to the data source.
Limit Connections | Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.
Restrict Connections To | Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.
Maintain Connections | ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.
Timeout (min) | The number of minutes that ColdFusion MX maintains an unused connection before destroying it.
Interval (min) | The time (in minutes) that the server waits between cycles to check for expired data source connections to close.
Disable Connections | If selected, suspends all client connections.
Login Timeout (sec) | The number of seconds before ColdFusion MX times out the data source connection login attempt.
CLOB | Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.
BLOB | Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.
LongText Buffer | The default buffer size; used if Enable Long Text Retrieval(CLOB) is not selected. The default value is 64000 bytes.
BLOB Buffer | The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.
Allowed SQL | The SQL operations that can interact with the current data source.


Connecting to ODBC Socket

Use the settings in the following table to connect ColdFusion MX to ODBC Socket data sources (this is a Type 3 driver):

Setting | Description
CF Data Source Name | The data source name (DSN) used by ColdFusion MX to connect to the data source.
ODBC DSN | Select the ODBC DSN to which you want ColdFusion MX to connect.
Trusted Connection | Specifies whether to use domain user account access to the database. Only valid for SQL Server.
Username | The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
Password | The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Description | (Optional) A description for this connection.
Connection String | A field that passes database-specific parameters, such as login credentials, to the data source.
Return Timestamp as String | Enable this option if your application retrieves Date/Time data and then re-uses it in SQL statements without applying formatting (using functions such as DateFormat, TimeFormat, and CreateODBCDateTime).
Limit Connections | Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.
Restrict Connections To | Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.
Maintain Connections | ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.
Timeout (min) | The number of minutes that ColdFusion MX maintains an unused connection before destroying it.
Interval (min) | The time (in minutes) that the server waits between cycles to check for expired data source connections to close.
Disable Connections | If selected, suspends all client connections.
Login Timeout (sec) | The number of seconds before ColdFusion MX times out the data source connection login attempt.
CLOB | Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.
BLOB | Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.
LongText Buffer | The default buffer size; used if Enable Long Text Retrieval(CLOB) is not selected. The default value is 64000 bytes.
BLOB Buffer | The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.
Allowed SQL | The SQL operations that can interact with the current data source.


Connecting to Oracle

To see a list of Oracle versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf. Use the settings in the following table to connect ColdFusion MX to Oracle data sources:

Setting

Description

CF Data Source Name

The data source name (DSN) used by ColdFusion MX to connect to the data source.

SID Name

The Oracle System Identifier (SID) that refers to the instance of the Oracle database software running on the server. The default value is ORCL.

Server

The name of the server that hosts the database that you want to use. If the database is local, enclose the word local in parentheses.

Port

The number of the TCP/IP port that the server monitors for connections.

Username

The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).

Password

The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).

Description

(Optional) A description for this connection.

Connection String

A field that passes database-specific parameters, such as login credentials, to the data source.

Limit Connections

Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.

Restrict Connections To

Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.

Maintain Connections

ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.

Max Pooled Statements

Enables reuse of prepared statements (that is, stored procedures and queries that use the cfqueryparam tag). Although you tune this setting based on your application, start by setting it to the sum of the following:

  • Unique cfquery tags that use the cfqueryparam tag
  • Unique cfstoredproc tags

The default value is 300.

Timeout (min)

The number of minutes that ColdFusion MX maintains an unused connection before destroying it.

Interval (min)

The time (in minutes) that the server waits between cycles to check for expired data source connections to close.

Disable Connections

If selected, suspends all client connections.

Login Timeout (sec)

The number of seconds before ColdFusion MX times out the data source connection login attempt.

CLOB

Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.

BLOB

Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.

LongText Buffer

The default buffer size; used if Enable Long Text Retrieval (CLOB) is not selected. The default value is 64000 bytes.

BLOB Buffer

The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.

Allowed SQL

The SQL operations that can interact with the current data source.


Connecting to other data sources

Use the settings in the following table to connect ColdFusion MX to data sources through JDBC drivers that do not appear in the drop-down list of drivers:

Setting | Description
CF Data Source Name | The data source name (DSN) used by ColdFusion MX to connect to the data source.
JDBC URL | The JDBC connection URL for this data source.
Driver Class | The fully qualified class name of the driver. For example, com.inet.tds.TdsDriver. The JAR file that contains this class must be in a directory defined in the ColdFusion classpath.
Driver Name | (Optional) The name of the driver.
Username | The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
Password | The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Description | (Optional) A description for this connection.
Connection String | A field that passes database-specific parameters, such as login credentials, to the data source.
Limit Connections | Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.
Restrict Connections To | Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.
Maintain Connections | ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.
Timeout (min) | The number of minutes that ColdFusion MX maintains an unused connection before destroying it.
Interval (min) | The time (in minutes) that the server waits between cycles to check for expired data source connections to close.
Disable Connections | If selected, suspends all client connections.
Login Timeout (sec) | The number of seconds before ColdFusion MX times out the data source connection login attempt.
CLOB | Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.
BLOB | Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.
LongText Buffer | The default buffer size; used if Enable Long Text Retrieval (CLOB) is not selected. The default value is 64000 bytes.
BLOB Buffer | The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.
Allowed SQL | The SQL operations that can interact with the current data source.

For example, you can use the Other Data Sources option to define a data source for DB2 OS/390 or iSeries, using the following settings:

JDBC URL jdbc:datadirect:db2://dbserver:portnumber

Driver class macromedia.jdbc.MacromediaDriver

Driver name DB2

Username A user defined to the database

Password The password for the username

Connection string Specify one connection string for the first connection, and then modify it for use in subsequent connections, as follows:

  • On the initial connection, specify LocationName, CollectionId, CreateDefaultPackage, and sendStringParametersAsUnicode (with no spaces) as the following example shows:
    LocationName=SAMPLE;CollectionId=DEFAULT;CreateDefaultPackage=TRUE;
    sendStringParametersAsUnicode=false

    Note: If the database uses Unicode, specify true for the sendStringParametersAsUnicode parameter.

  • On subsequent connections, specify LocationName, CollectionId, and sendStringParametersAsUnicode, as the following example shows:
    LocationName=SAMPLE;CollectionId=DEFAULT;
    sendStringParametersAsUnicode=false

Note: DB2 OS/390 refers to all supported versions of DB2 on OS/390 and z/OS platforms; DB2 iSeries refers to all supported versions of DB2 on iSeries and AS/400.

For more information on DB2, see Connecting to DB2 Universal Database.


Connecting to Sybase

To see a list of Sybase versions that ColdFusion MX supports, go to www.macromedia.com/go/sysreqscf. Use the settings in the following table to connect ColdFusion MX to Sybase data sources:

Setting

Description

CF Data Source Name

The data source name (DSN) used by ColdFusion MX to connect to the data source.

Database

The database to which this data source connects.

Server

The name of the server that hosts the database that you want to use. If the database is local, enclose the word local in parentheses. This name must be either a fully qualified domain name (resolvable through DNS) or an IP address. It cannot be a netbios name (even if you are running NBT), or an alias you set up using the client connectivity wizard (both of these approaches worked in earlier ColdFusion versions).

Port

The number of the TCP/IP port that the server monitors for connections.

Username

The user name that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a user name (for example, in a cfquery tag).

Password

The password that ColdFusion MX passes to the JDBC driver to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).

Description

(Optional) A description for this connection.

Connection String

A field that passes database-specific parameters, such as login credentials, to the data source.

Select Method

Determines whether server cursors are used for SQL queries.

  • The Direct method provides more efficient retrieval of data when you retrieve record sets in a forward-only direction and you limit your Sybase connection to a single open SQL statement at a time. This is typical for ColdFusion applications.
  • The Cursor method lets you have multiple open SQL statements on a connection. This is not typical for ColdFusion applications, unless you use pooled statements.

Limit Connections

Specifies whether ColdFusion MX limits the number of database connections for the data source. If you enable this option, use the Restrict Connections To field to specify the maximum.

Restrict Connections To

Specifies the maximum number of database connections for the data source. To use this restriction, you must enable the Limit Connections option.

Maintain Connections

ColdFusion MX establishes a connection to a data source for every operation that requires one. Enable this option to improve performance by caching the data source connection.

Max Pooled Statements

Enables reuse of prepared statements (that is, stored procedures and queries that use the cfqueryparam tag). Although you tune this setting based on your application, start by setting it to the sum of the following:

  • Unique cfquery tags that use the cfqueryparam tag
  • Unique cfstoredproc tags

Timeout (min)

The number of minutes that ColdFusion MX maintains an unused connection before destroying it.

Interval (min)

The time (in minutes) that the server waits between cycles to check for expired data source connections to close.

Disable Connections

If selected, suspends all client connections.

Login Timeout (sec)

The number of seconds before ColdFusion MX times out the data source connection login attempt.

CLOB

Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.

BLOB

Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.

LongText Buffer

The default buffer size; used if Enable Long Text Retrieval(CLOB) is not selected. The default value is 64000 bytes.

BLOB Buffer

The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.

Allowed SQL

The SQL operations that can interact with the current data source.


Connecting to JNDI data sources

Use the settings in the following table to connect ColdFusion MX to JNDI data sources that have been defined for a J2EE application server (multiserver and J2EE configurations only):

Setting | Description
CF Data Source Name | The data source name (DSN) used by ColdFusion MX to connect to the data source.
JNDI Name | The JNDI location in which the J2EE application server stores the data source.
Username | The user name that ColdFusion MX passes to JNDI to connect to JNDI if a ColdFusion application does not supply a user name (for example, in a cfquery tag).
Password | The password that ColdFusion MX passes to JNDI to connect to the data source if a ColdFusion application does not supply a password (for example, in a cfquery tag).
Description | (Optional) A description for this connection.
JNDI Environment Settings | Specifies additional JNDI environment settings, if required by the JNDI data source. Use comma separated list of name/value pair. For example if you must specify a username and password to connect to JNDI, specify the following: SECURITY_PRINCIPAL="myusername",SECURITY_CREDENTIALS="mypassword"
CLOB | Select to return the entire contents of any CLOB/Text columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the Long Text Buffer setting.
BLOB | Select to return the entire contents of any BLOB/Image columns in the database for this data source. If not selected, ColdFusion MX retrieves the number of characters specified in the BLOB Buffer setting.
LongText Buffer | The default buffer size; used if Enable Long Text Retrieval (CLOB) is not selected. The default value is 64000 bytes.
BLOB Buffer | The default buffer size; used if the BLOB option is not selected. The default value is 64000 bytes.
Allowed SQL | The SQL operations that can interact with the current data source.

Note: The ColdFusion MX Administrator does not display the JNDI data source option when running in the server configuration.
Previous


Web Server Management

You can connect Macromedia ColdFusion MX to the built-in web server and to external web servers, such as Apache, IIS, and Sun ONE Web Server (formerly known as iPlanet). This chapter explores common scenarios, security, and multihosting.

The information in this chapter applies when running in the server configuration, in the multiserver configuration, and when deploying on Macromedia JRun in the J2EE configuration. (Some J2EE application servers include web server plug-ins that provide similar functionality.)

Contents

About web servers in ColdFusion MX

Using the built-in web server

Using an external web server

Web server configuration

Multihoming
Next


About web servers in ColdFusion MX

The web server is a critical component in your ColdFusion MX environment, and understanding how ColdFusion interacts with web servers can help you administer your site. ColdFusion MX provides the following web server options:

Built-in web server A lightweight, all-Java, HTTP 1.0 web server. Suitable for development but not intended for use in production applications. For more information, see Using the built-in web server.

External web server A customized web server connector module that forwards requests for ColdFusion pages from an external web server to ColdFusion MX. For more information, see Using an external web server.


Using the built-in web server

The ColdFusion MX server configuration is built on top of JRun, which includes the JRun web server (JWS), also called the built-in web server. Although not intended for use in a production environment, the built-in web server is particularly useful in the following cases:

Coexistence/transition The built-in web server lets you run a previous version of ColdFusion (using an external web server) and ColdFusion MX (using the built-in web server) on the same computer while you migrate your existing applications to ColdFusion MX.

Development If your workstation runs ColdFusion MX but does not run an external web server, you can still develop and test ColdFusion applications locally through the built-in web server.

All web servers listen on a TCP/IP port, which you can specify in the URL. By default, web servers listen for HTTP requests on port 80 (for example, http://www.macromedia.com and http://www.macromedia.com:80 are the same). Similarly, port 443 is the default port for HTTPS requests.

By default in the server configuration, the built-in web server listens on port 8500. For example, to access the ColdFusion MX Administrator through the built-in web server, specify http://servername:8500/CFIDE/administrator/index.cfm. In the multiserver configuration, the default port for the built-in web server is 8300.

Note: URLs are case-sensitive on UNIX operating systems.

If you enable the built-in web server during the installation process and the port is already in use, the installer automatically finds the next-highest available port and configures the built-in web server to use that port. To determine the port number used by the built-in web server, open the cf_root/runtime/servers/coldfusion/SERVER-INF/jrun.xml file in a text editor and examine the port attribute of the WebService service. In the multiserver configuration, the path is jrun_root/servers/cfusion/SERVER-INF/jrun.xml.

Note: When you install ColdFusion MX Enterprise Edition using the multiserver configuration, the installation wizard always configures the built-in web server, even if you select an external web server.

Keep in mind the following when using the built-in web server:

  • Whenever possible, you should choose to configure your external web server as part of the ColdFusion MX installation, except for the two cases mentioned at the beginning of this section (coexistence with a previous ColdFusion version and when there is no web server on the computer). If you select the built-in web server by mistake, you must run the Web Server Configuration Tool manually to configure your external web server after the installation. For information about the Web Server Configuration Tool, see Web server configuration.
  • The default web root when using the built-in web server is cf_root/wwwroot (server configuration) or jrun_root/servers/cfusion/cfusion-ear/cfusion-war (multiserver configuration). By default, the ColdFusion MX Administrator (CFIDE directory) is under this web root.
  • If you want the built-in web server to serve pages from a different web root directory, define a virtual mapping in the cf_root/wwwroot/WEB-INF/jrun-web.xml file (jrun_root/servers/cfusion/cfusion-ear/cfusion-war/WEB-INF/jrun-web.xml in the multiserver configuration), as the following example shows:
     <virtual-mapping>
   <resource-path>/*</resource-path>
   <system-path>C:/myApps/wwwroot</system-path>
 </virtual-mapping>

    Warning: If you have CFML pages under your external web server’s root, ensure that ColdFusion MX has been configured to serve these pages through the external web server. If you have not configured ColdFusion MX to use an external web server, your external web server will serve ColdFusion Markup Language (CFML) source code for ColdFusion pages saved under its web root.


Using an external web server

ColdFusion MX uses the JRun web server connector to forward requests from an external web server to the ColdFusion MX runtime system.

When a request is made for a CFM page, the connector on the web server opens a network connection to the JRun proxy service. The ColdFusion MX runtime system handles the request and sends its response back through the proxy service and connector. The web server connector uses web-server-specific plug-in modules, as the following table describes:

Web server

Connector details

Apache

The Web Server Configuration Tool adds the following elements to the Apache httpd.conf file:

  • A LoadModule directive defines the connector.
  • An AddHandler directive tells Apache to route requests for ColdFusion pages through the connector.

For Apache 1.3.x, the connection module is mod_jrun.so; for Apache 2.x, the connection module is mod_jrun20.so.

IIS

The Web Server Configuration Tool adds the following elements at either the global level (default) or website level:

  • An ISAPI filter (available on IIS 5 only).
  • Extension mappings that tell IIS to route requests for ColdFusion pages through the connector.

With IIS 5, the IIS connection module is jrun.dll. IIS 6 uses a connection module named jrun_iis6.dll and a helper DLL named jrun_iis6_wildcard.dll.

Sun ONE Web Server, including iPlanet and Netscape Enterprise Server (NES)

The Web Server Configuration Tool adds the following elements to Sun ONE Web Server configuration files:

  • obj.conf A PathCheck directive for the JRun filter and ObjectType directives to route requests for ColdFusion pages through the connector.
  • magnus.conf Init directives to load and initialize the connector.

In Windows, the Sun ONE Web Server connection module is jrun_nsapi.dll; on UNIX, the Sun ONE Web Server connection module is jrun_nsapi.so.

With iPlanet 4.x, the Web Server Configuration Tool places all settings in the obj.conf file.


Web server configuration

ColdFusion MX uses the Web Server Configuration Tool to configure an external web server with the modules and settings that the connector needs to connect to ColdFusion MX. You can run the Web Server Configuration Tool through either the command-line interface or the graphical user interface (GUI). In either case, the Web Server Configuration Tool configures your external web server to interact with a ColdFusion MX server.

This section describes the following topics:

  • Using GUI mode
  • Using the command-line interface
  • Configuration files

Using GUI mode

The Web Server Configuration Tool includes a GUI mode, which you can use to specify external web server configuration settings through a graphical interface.

Note: When you use the Web Server Configuration Tool in GUI mode, you must select the Configure Web Server for ColdFusion MX Applications check box.

To run the Web Server Configuration Tool in GUI mode:

  1. Open a console window.

    Tip: In Windows, you can start the Web Server Configuration Tool by selecting Start > Programs > Macromedia > ColdFusion MX 7 > Web Server Configuration Tool.

  2. Change to the cf_root/runtime/bin (server configuration) or jrun_root/bin (multiserver configuration) directory.
  3. Start the Web Server Configuration Tool using the wsconfig.exe (Windows) or wsconfig (UNIX) command.

    The Web Server Configuration Tool window appears.

  4. Click the Add button.
  5. Select the Configure Web Server for ColdFusion MX Applications check box.
  6. In the Server drop-down list box, select the server or cluster name that you want to configure. (Individual server names in a cluster do not appear. Clustering support is only available on the multiserver configuration.)

    Note: The server or cluster does not have to reside on the web server computer. In this case, enter the IP address or server name of the remote computer in the JRun Host field.

  7. In the Web Server Properties area, enter web-server-specific information, and click OK.
  8. (Optional) Move the CFIDE directory and other directories (such as cfdocs) from the built-in web server’s web root to your web server root directory. In addition, you can copy your application’s CFM pages from the built-in web server’s web root to your web server root directory.

    Note: When a page is requested, the web server connector first looks for the ColdFusion page in the cf_root/wwwroot (server configuration) or jrun_root/servers/cfusion/cfusion-ear/cfusion-war (multiserver configuration) directory, and then looks under the web server root. Alternatively, you can use the command-line interface and specify the -cfwebroot option.

  9. (Optional) The web server connector does not serve static content (such as HTML files and images) from the built-in web server’s root directory. If your ColdFusion web application has an empty context root (/) and you want to serve pages from the built-in web server’s root directory, you can create a web server mapping to the corresponding directory under the built-in web server.


Using the command-line interface

You can also run the Web Server Configuration Tool through a command-line interface.

To run the command-line interface:

  1. Open a console window.
  2. Change to the cf_root/runtime/bin (server configuration) or jrun_root/bin (multiserver configuration) directory.
  3. Execute the wsconfig.exe (Windows) or wsconfig (UNIX) command:
       wsconfig.exe [-options]
   ./wsconfig [-options]

The following table describes the options:

Option

Description

-ws

Specifies the web server, as follows:

  • IIS
  • Apache
  • SunOne
  • iPlanet
  • NES

The web server name you supply is not case-sensitive.

-dir

Specifies the path to the configuration directory (Apache conf or NES/iPlanet config).

-site

Specifies the IIS website name (case-sensitive). Specify All or 0 to configure the connector at a global level, which applies to all IIS websites.

-host

Specifies the ColdFusion server address. The default value is localhost.

-server

Specifies the ColdFusion server name.

-username

Specifies a username defined to the JRun server. The default value is guest account.

-password

Specifies a password that corresponds to -username. The default value is guest account.

-norestart

Specifies not to restart the web server.

-cluster

Specifies the JRun cluster name. Use this option to define a connection to a JRun cluster instead of a single server.

-l

Enables verbose logging for the connector.

-a

Enables native OS memory allocation.

-map .cfm,.cfc,.cfml,.cfr,
.cfswf,.jsp,.jws

Specifies the extension mappings list. (To use the web server connector with ColdFusion MX, you should specify .cfm,.cfc,.cfml,.cfr,.cfswf,.jsp,.jws.)

-filter-prefix-only

(IIS 5 only) Sets ignoresuffixmap=true in the jrun.ini file. This means that the connector module runs as an IIS extension.

-coldfusion

Ensures that the proper ColdFusion MX mappings are set (.cfm, .cfml, .cfc, .cfswf, .cfr, .jsp, .jws), and, if IIS, filter-prefix-only is implicitly specified.

Always use this option when configuring a web server for use with ColdFusion MX.

-upgrade

Upgrades existing configured connectors with newer modules from a newer wsconfig.jar file.

-service

Specifies the Apache Windows service name. The default value is Apache.

-bin

Specifies the path to the Apache server binary file (apache.exe in Windows, httpd on UNIX).

-script

Specifies the path to the Apache UNIX control script file (apachectl, but slightly different with certain Apache variants, such as Stronghold).

-v

Enables verbose output from the Web Server Configuration Tool.

-cfwebroot

Specifies the directory corresponding to cf_root/wwwroot. If you use this option, the Web Server Configuration Tool creates web server mappings for /CFIDE and /cfdocs, each of which points to the corresponding directories under cf_root/wwwroot. This option is useful in a multihoming or hosting environment where you want multiple applications to share the ColdFusion MX Administrator.

-list

Lists all configured web servers.

-list -host server-host

Lists all JRun servers on the specified host.

-remove

Removes a configuration. Requires the -ws and either the -dir or -site options.

-uninstall

Uninstalls all configured connectors.

-h

Lists all parameters.

Using the batch files and shell scripts

The ColdFusion MX server configuration includes batch files and shell scripts that implement typical command-line connector configurations. These files are in the cf_root/bin/connectors directory. For example, the IIS_connector.bat file configures all sites in IIS to site 0, which establishes a globally defined connector so that all sites inherit the filter and mappings.

If you use Apache or Sun ONE Web Server, use these files as prototypes, editing and saving them as appropriate for your site.

Command-line interface examples

This section provides examples of multiple use-cases for different web servers:

  • Configure a specific IIS site:
    cf_root/runtime/bin/wsconfig.exe -server coldfusion -ws iis -site "web31"
    -coldfusion -v

    On systems where all sites run ColdFusion, there is generally no need to configure an individual site.

  • Configure all existing IIS sites (ISPs):
    cf_root/runtime/bin/wsconfig.exe -server coldfusion -ws iis -site 0
    -coldfusion -cfwebroot C:\Inetpub\wwwroot -v

    The -cfwebroot option allows all sites to share the ColdFusion MX Administrator that runs under C:\Inetpub\wwwroot. This example does not automatically configure newly added sites after the first -site 0 run, but you can rerun with -site 0 at a later time, and the Web Server Configuration Tool configures new sites only.

  • Configure Apache on UNIX #1:
    cf_root/runtime/bin/wsconfig -server coldfusion -ws Apache
    -bin /opt/apache2/bin/httpd -script /opt/apache2/bin/apachectl
    -dir /opt/apache2/conf -coldfusion -v
  • Configure Apache on UNIX #2:
    cf_root/runtime/bin/wsconfig -server coldfusion -ws Apache
    -bin /usr/bin/httpd -script /usr/bin/httpd -dir /etc/httpd/conf
    -coldfusion -v
  • Configure Apache in Windows:
    cf_root/runtime/bin/wsconfig.exe -server coldfusion -ws apache -dir "c:\program files\apache group\apache2\conf" -coldfusion -v
  • Configure Netscape on UNIX:
    cf_root/runtime/bin/wsconfig -server coldfusion -ws nes
    -dir [path to config] -coldfusion -v
  • Configure Sun ONE Web Server on UNIX:
    cf_root/runtime/bin/wsconfig -server coldfusion -ws sunone
    -dir [path to config] -coldfusion -v


Configuration files

The Web Server Configuration Tool stores properties in configuration files, as follows:

IIS In the jrun.ini file, typically found in a subdirectory of the cf_root/runtime/lib/wsconfig (server configuration) or jrun_root/lib/wsconfig (multiserver configuration) directory. For IIS 5 only, it also defines filter and extension mappings in the IIS metabase.

Apache In the httpd.conf file, typically found in the apache_root/conf directory.

Sun ONE Web Server/iPlanet In the obj.conf and magnus.conf files, typically found in the ws_root/server-http-xxx/config directory.

The following table describes the web server connector properties in the web server configuration files. The web server connector uses these settings to help it find the ColdFusion server and know which servers to connect to.

Property | Description
bootstrap | Specifies the IP address and port on which the JRun server’s proxy service is listening for connector requests. JRun must also be configured to listen on this port and address combination, the ProxyService must be activated, and the JRun server must be running. Specify ipaddress:portnumber (for example, 127.0.0.1:51011).
serverstore | Specifies the full path and filename of the file that contains information for the associated JRun server. The connector creates this file automatically. The default filename is jrunserver.store.
verbose | Creates more detailed web server log file entries for the connector. Enabling this option can cause the web server’s log files to fill quickly. Specify true or false; the default value is false. In Apache and Sun ONE Web Server, the connector writes to the error log configured for the web server; on IIS, the connector writes to its own log in the related wsconfig subdirectory.
scriptpath | (IIS only) Points to the virtual /JRunScripts directory on the web server.
errorurl | (Optional) Specifies the URL to a file that contains a customized error message. This property is commented out by default. You must restart the web server after enabling this setting.
ssl | (Optional) Enables secure sockets layer (SSL) between the web server and the JRun server. You must set this setting to false.
apialloc | Enables native OS memory allocation rather than the web server’s allocator (for use on Solaris with Sun ONE, at the direction of Macromedia Support staff).
ignoresuffixmap | (IIS only) Forces the connector to use application mappings.
proxyretryinterval | Specifies the number of seconds to wait before trying to reconnect to an unreachable clustered server.
connecttimeout | Specifies the number of seconds to wait on a socket connect to a JRun server.
recvtimeout | Specifies the number of seconds to wait on a socket receive to a JRun server.
sendtimeout | Specifies the number of seconds to wait on a socket send to a JRun server.

Each time you run the Web Server Configuration Tool, it creates a new configuration file and directory. For example, the first time you run the tool in the server configuration, it creates files under cf_root/runtime/lib/wsconfig/1; the second time, it creates cf_root/runtime/lib/wsconfig/2; and so on. Each of these subdirectories contains the appropriate platform-specific connector module and web-server-specific supporting files.

Sample configuration files

To help describe the web server configuration file parameters, this section provides examples of connector-specific web server properties. These examples assume that JRun and the web server are on the same computer.

Apache configuration file

The following is a typical httpd.conf file for an installation of ColdFusion MX on the same computer as an Apache 2.0 web server:

# JRun Settings
LoadModule jrun_module "C:/CFusionMX7/runtime/lib/wsconfig/1/mod_jrun20.so"
<IfModule mod_jrun20.c>
    JRunConfig Verbose false
    JRunConfig Apialloc false
    JRunConfig Ssl false
    JRunConfig Ignoresuffixmap false
    JRunConfig Serverstore "C:/CFusionMX7/runtime/lib/wsconfig/1/jrunserver.store"
    JRunConfig Bootstrap 127.0.0.1:51011
    #JRunConfig Errorurl <optionally redirect to this URL on errors>
    #JRunConfig ProxyRetryInterval <number of seconds to wait before trying to reconnect to unreachable clustered server>
    #JRunConfig ConnectTimeout 15
    #JRunConfig RecvTimeout 300
    #JRunConfig SendTimeout 15
    AddHandler jrun-handler .jsp .jws .cfm .cfml .cfc .cfr .cfswf
</IfModule>

IIS configuration file

For IIS, the connector uses the jrun.ini file to initialize the jrun.dll file (jrun_iis6.dll on IIS 6). The following is a typical jrun.ini file:

verbose=false
scriptpath=/JRunScripts/jrun.dll
serverstore=C:/CFusionMX7/runtime/lib/wsconfig/1/jrunserver.store
bootstrap=127.0.0.1:51011
apialloc=false
ssl=false
ignoresuffixmap=true
#errorurl=<optionally redirect to this URL on errors>
#proxyretryinterval=<number of seconds to wait before trying to reconnect to unreachable clustered server>
#connecttimeout=<number of seconds to wait on a socket connect to a JRun server>
#recvtimeout=<number of seconds to wait on a socket receive to a JRun server>
#sendtimeout=<number of seconds to wait on a socket send to a JRun server>

Netscape, iPlanet, or Sun ONE configuration file

The following is a typical obj.conf file for Netscape, iPlanet, or Sun ONE Web Server:

Note: Java must be disabled for the virtual server class that contains the server configured for JRun.

...
<Object name="default">
AuthTrans fn="match-browser" browser="*MSIE*" ssl-unclean-shutdown="true"
NameTrans fn="pfx2dir" from="/mc-icons" dir="C:/Sun/WebServer6.1/ns-icons" name="es-internal"
NameTrans fn="pfx2dir" from="/manual" dir="C:/Sun/WebServer6.1/manual/https"
NameTrans fn="document-root" root="$docroot"
PathCheck fn="nt-uri-clean"
PathCheck fn="check-acl" acl="default"
PathCheck fn="find-pathinfo"
PathCheck fn=find-index index-names="index.jsp,index.html,home.html,index.cfm"
PathCheck fn="jrunfilter"
ObjectType fn=type-by-exp exp=*.jsp type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.jws type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.cfm type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.cfml type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.cfc type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.swf type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.mxml type="jrun-internal/ext"
ObjectType fn=type-by-exp exp=*.cfr type="jrun-internal/ext"
ObjectType fn="type-by-extension"
ObjectType fn="force-type" type="text/plain"
Service method=(GET|HEAD|POST) type="jrun-internal/*" fn="jrunservice"
Service method="(GET|HEAD)" type="magnus-internal/imagemap" fn="imagemap"
Service method="(GET|HEAD)" type="magnus-internal/directory" fn="index-common"
Service method="(GET|HEAD|POST)" type="*~magnus-internal/*" fn="send-file"
Service method="TRACE" fn="service-trace"
AddLog fn="flex-log" name="access"
</Object>
...

The following is a typical magnus.conf file for Netscape, iPlanet, or Sun ONE Web Server:

...
Init fn="load-modules" shlib="C:/CFusionMX7/runtime/lib/wsconfig/1/jrun_nsapi.dll" funcs="jruninit,jrunfilter,jrunservice"
Init fn="jruninit" serverstore="C:/CFusionMX7/runtime/lib/wsconfig/1/jrunserver.store" bootstrap="127.0.0.1:51011" verbose="true" apialloc="false" ssl="false" ignoresuffixmap="false" #errorurl="<optionally redirect to this URL on errors>" connecttimeout="15" recvtimeout="300" sendtimeout="15"


Multihoming

You typically use the Web Server Configuration Tool to configure a connection between the web server and ColdFusion server running on the same computer. However, you can use the web server connector to route requests to multiple virtual sites to a single ColdFusion server. This is known as multihoming.

In a multihomed environment, you have multiple virtual hosts (also known as virtual sites) connected to a single ColdFusion server. You might use these virtual hosts for separate applications, such as Human Resources (HR), payroll, and marketing, or for separate users in a hosting environment.

Note: You use web-server-specific methods to create separate virtual websites for each use.

Multihoming configuration tasks include the following:

Enabling access to the ColdFusion MX Administrator If any of the applications under a virtual host need to access the ColdFusion MX Administrator, you must create a web server mapping (Alias directive in Apache) for /CFIDE that points to the original CFIDE directory. Alternatively, you can copy the entire CFIDE directory to the virtual website.

Tip: You can also configure the web server using the command-line Web Server Configuration Tool -cfwebroot option, which allows access to the CFIDE directory under the specified web root.

Enabling access to the cfform.js file If you do not create a web server mapping for /CFIDE, and any of the applications under a virtual host use the cfform tag, you must enable the virtual host to find the JavaScript files under the CFIDE/scripts directory. To enable access to the these scripts, use one of the following options:

  • Copy the original_web_root/CFIDE/scripts directory to a CFIDE/scripts directory on your virtual host.
  • Modify all cfform tags to use the scriptsrc attribute to specify the location of the cfform.js file.

Disabling the cacheRealPath attribute To ensure that ColdFusion MX always returns pages from the correct server, ensure that Cache Web Server Paths is disabled in t‘he Caching page of the ColdFusion MX Administrator. (When you use the multiserver configuration, set the cacheRealPath attribute to false for the ProxyService in the jrun_root/servers/servername/SERVER-INF/jrun.xml file.)

The procedures you perform to enable multihoming differ for each web server:

  • IIS
  • Apache
  • Sun ONE Web Server, iPlanet, and Netscape

IIS

When you use IIS, you run the IIS Administrator to create additional websites and run the Web Server Configuration Tool. You store ColdFusion pages under the web root of each virtual website.

To connect multiple virtual sites on IIS to a single ColdFusion server:

  1. Use the IIS Administrator to create virtual websites, as necessary. The web root directory should enable read, write, and execute access. For more information, see your IIS documentation.
  2. Configure DNS for each virtual website, as described in your IIS documentation.
  3. Test each virtual website to ensure that HTML pages are served correctly.
  4. Run the Web Server Configuration Tool, as follows:
    • GUI Specify IIS for the Web Server and All from the IIS Web Site drop-down list box, and select the Configure Web Server for ColdFusion MX Applications check box.
    • Command line Specify the -site 0 and -cfwebroot options, as the following server configuration example shows:
      cf_root/runtime/bin/wsconfig.exe -ws iis -site 0
-cfwebroot cf_root/wwwroot -coldfusion -v
  5. Test each virtual website to ensure that ColdFusion pages are served correctly.

Apache

When you use Apache, you modify the apache_root/conf/httpd.conf file to create virtual hosts and run the Web Server Configuration Tool. You store ColdFusion pages under the web root of each virtual website.

To connect multiple Apache virtual hosts on a web server to a single ColdFusion server:

  1. Configure DNS for each virtual website, as described in your web server documentation.
  2. Open the apache_root/conf/httpd.conf file in a text editor and create virtual hosts, as necessary. For more information, see your Apache documentation. For example:
    ...
NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
    ServerAdmin admin@yoursite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs"
    ServerName SERVER02
    ErrorLog logs/error.log
</VirtualHost>
<VirtualHost 127.0.0.1>
    ServerAdmin admin@yoursite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs2"
    ServerName mystore
    ErrorLog logs/error-store.log
</VirtualHost>
<VirtualHost 127.0.0.1>
    ServerAdmin admin@yoursite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs3"
    ServerName myemployee
    ErrorLog logs/error-employee.log
</VirtualHost>
...
  3. Test each virtual host to ensure that HTML pages are served correctly.
  4. Run the Web Server Configuration Tool, as follows:
    • GUI Specify Apache for the Web Server, specify the directory that contains the httpd.conf file, and select the Configure Web Server for ColdFusion MX Applications check box.
    • Command line Specify -ws apache and the directory that contains the httpd.conf file, as the following example shows:
      cf_root/runtime/bin/wsconfig.exe -ws apache
-dir "c:\program files\apache group\apache2\conf"
-cfwebroot cf_root/wwwroot -coldfusion -v

      For additional UNIX command-line examples, see Using the command-line interface.

    The Web Server Configuration Tool updates the httpd.conf file. For a sample, see Apache.

  5. Restart Apache. You store ColdFusion files for each virtual host in the directory specified by the DocumentRoot directive.
  6. Test each virtual host to ensure that ColdFusion pages are served correctly.

Sun ONE Web Server, iPlanet, and Netscape

When you use Sun ONE Web Server version 6, you use the Server Administrator to create virtual servers and run the Web Server Configuration Tool. You store ColdFusion pages under the web root of each virtual server.

Note: For earlier versions of Sun ONE/iPlanet and Netscape Enterprise Server (NES), you must create separate server instances for each site and run the Web Server Configuration Tool once for each site.

To connect multiple Sun ONE Web Server virtual hosts to a single ColdFusion server:

  1. Using the Sun ONE Web Server Administrator, create virtual web servers for use by ColdFusion MX. For more information, see your Sun ONE Web Server documentation.
  2. Configure DNS for each virtual website, as described in your web server documentation.
  3. Test each virtual server to ensure that HTML pages are served correctly.
  4. Run the Web Server Configuration Tool, as follows:
    • GUI Specify Netscape Enterprise Server/Sun ONE for the web server, specify the directory that contains the obj.conf and magnus.conf files, and select the Configure Web Server for ColdFusion MX Applications check box.
    • Command line Specify -ws sunone and the directory that contains the obj.conf file, as the following example shows:
      cf_root/runtime/bin/wsconfig -ws sunone -dir [path to config]
-cfwebroot cf_root/wwwroot -coldfusion -v
  5. Test each virtual server to ensure that ColdFusion pages are served correctly.

Previous


Deploying ColdFusion Applications

This chapter describes the archive and deployment options available in Macromedia ColdFusion MX 7.

Contents

Archive and deployment options

Packaging applications in CAR files

Packaging applications in J2EE archive files

Using the cfcompile utility

Next


Archive and deployment options

ColdFusion MX 7 includes the following archive and deployment options.

ColdFusion archive files You can package your ColdFusion application’s pages, data sources and settings in a ColdFusion Archive (CAR) file. For more information, see Packaging applications in CAR files.

J2EE archives You can package your ColdFusion application as an Enterprise Application Archive (EAR) or Web Application Archive (WAR) file for easy deployment to a J2EE application server. For more information, see Packaging applications in J2EE archive files.

Cfcompile utility The cfcompile utility lets you precompile your application’s ColdFusion pages into Java class files. In addition you can compile ColdFusion pages to bytecode and save this bytecode in files with the CFM, CFC, or CFR extension. For more information, see Using the cfcompile utility.


Packaging applications in CAR files

CAR files let you archive and deploy website configuration information, files, and applications. Use this feature to deploy your website applications to another location or to back up your files quickly and easily. You manage CAR files using the Packaging & Deployment > ColdFusion Archives area of the ColdFusion MX Administrator.

Note: CAR file archiving and deployment is different from J2EE archiving and packaging through EAR and WAR files.

Perform the following steps when you archive and deploy site information:

  1. Create the archive definition.

    Identify the type of information to archive about a site. You can archive almost anything about the site, including directories, files, CFX tags, ColdFusion MX mappings, Verity collections, automated tasks, and server settings. Each archive definition that you create is assigned a name. You use this name each time you build or deploy its content.

  2. Build the archive.

    Select the name of the archive definition and specify a location to which you store the CAR file.

  3. Deploy the archive.

    Specify the location of the CAR file and the location to which you restore the contents.

Note: ColdFusion MX does not deploy Administrator and RDS passwords, nor does it unpack archives created in previous versions of ColdFusion.

For more information on creating, building, and deploying CAR files, see ColdFusion MX Administrator online Help.


Packaging applications in J2EE archive files

When running ColdFusion MX in the multiserver and J2EE configurations, you deploy the ColdFusion application, in enterprise application archive (EAR) or web application archive (WAR) format, on a J2EE application server. You then create your ColdFusion MX application, configuring resources (such as data sources), and storing CFM, CFC, and CFR files in the web application root or in the web server root. In earlier ColdFusion MX releases, your J2EE administrator had to redo each of these steps when deploying your ColdFusion application onto a production J2EE server.

The ColdFusion MX Administrator lets you create an EAR or WAR file that contains the entire application. This archive file contains the ColdFusion MX web application, settings for ColdFusion MX (such as data source definitions), and the CFM, CFC, and CFR files used by your application.

Tip: If you are using the multiserver configuration, you can combine J2EE archiving with the instance creation functionality of the ColdFusion MX Administrator Enterprise Manager. First, create an EAR file that contains your application and all of its settings, and then use that EAR file in the Create From EAR/WAR option of the Instance Manager. For more information on the Enterprise Manager, see Defining additional server instances.

Application packaging

The J2EE Archive feature lets you quickly create an archive file that a J2EE administrator can use to deploy your ColdFusion MX application.

To add a new archive definition and create an archive file:

  1. Open the ColdFusion MX Administrator.
  2. Specify a unique name for the archive file (no extension) in the Archive Name field.
  3. Click Add. The Add New Archive screen appears.
  4. Specify archive settings on the Add New Archive screen.
  5. Click Create. ColdFusion creates an EAR or WAR file in the specified application distribution directory.

The following table describes the settings you make when creating or modifying archive:

Setting

Description

Archive Type

Select EAR or WAR.

Context Root (EAR only)

Each J2EE web application running in a server is rooted at a unique base URL, called a context root (or context path). The J2EE application server uses the initial portion of the URL (that is, the portion immediately following http://hostname) to determine which web application services an incoming request.

For example, if you are running ColdFusion MX with a context root of cfmx, you display the Administrator using the URL http://hostname/cfmx/CFIDE/administrator/index.cfm. Most J2EE application servers allow one application in each server instance to use a forward slash (/) for the context root. The Remote Development Services (RDS) web application is not required if you use a context root of /.

Serial Number

Specifies a ColdFusion MX Enterprise Edition serial number. If you do not specify a valid ColdFusion MX Enterprise Edition serial number when creating the archive file, it is deployed as an Enterprise Edition evaluation version, which reverts to the Developer Edition after 30 days.

COM Support

If your application doesn’t use COM support, you can reduce the size of the archive file by omitting the supporting files.

Debugging

If the current ColdFusion MX server is running with debugging enabled, you can disable debugging in the application contained in the archive file.

Include CFML Source

You can optionally deploy Java bytecode instead of CFML source code. For more information, see Sourceless distribution.

ColdFusion MX Administrator

If your application does not require modification using the ColdFusion MX Administrator, you can reduce archive size and reduce security issues by omitting the Administrator files.

Data Sources

Specifies the data source definitions to include in the archive file.

Deployment considerations

Once the archive file is created, you deploy using standard ColdFusion MX J2EE configuration deployment techniques. For more information, see Installing an EAR file or WAR files in Installing the J2EE Configuration of Installing and Using ColdFusion MX.

Post-deployment considerations

Depending on your application, the resources that it uses, and the environment in which it is deployed, you may need to perform post-deployment configuration, as follows:

Mappings The ColdFusion mappings in the archived application refer to directories on the original computer. If those directories do not exist on the deployment computer, modify the ColdFusion mappings using the ColdFusion MX Administrator or the Administrator API.

Verity You must ensure that the Verity server settings on the original computer are appropriate for the deployment computer. If not, you must modify the Verity server settings using the ColdFusion MX Administrator or the Administrator API.

Serial number J2EE deployment is a ColdFusion MX Enterprise feature. To upgrade to the Enterprise Edition, enter a serial number using the ColdFusion MX Administrator or the Administrator API.

For more information on the Administrator API, see Administrator API.


Using the cfcompile utility

You can use the cfcompile utility for the following purposes:

Precompiling ColdFusion pages Precompile your application’s CFM pages into Java class files. At runtime, ColdFusion MX does not have to compile CFM pages.

Sourceless distribution Create CFM pages as Java bytecode. You can deploy these CFM pages instead of CFML source code.

The cfcompile utility is located in the cf_root/bin (server configuration) or cf_webapp_root/WEB-INF/cfusion/bin (multiserver and J2EE configuration) directory.

This section describes the following topics:

  • Precompiling ColdFusion pages
  • Sourceless distribution

Precompiling ColdFusion pages

You can use the cfcompile utility to precompile ColdFusion pages (CFM, CFC, and CFR files). This can enhance initial page loading time at runtime.

Use the following command to compile ColdFusion pages into Java classes:

cfcompile webroot [directory-to-compile]

The following table describes these parameters:

Parameter | Description
webroot | Fully qualified path to the web server root; for example, C:\Inetpub\wwwroot or C:\CFusionMX7\wwwroot.
directory-to-compile | Fully qualified path to the directory where the files to be compiled are located. This directory must be under the webroot directory. If not specified, all ColdFusion templates in the webroot directory are compiled.

Sourceless distribution

You can use the cfcompile utility with the -deploy option to create ColdFusion pages (CFM, CFC, and CFR files) that contain Java bytecode. You can then deploy the bytecode versions of the ColdFusion pages instead of the original CFML source code.

Use the following command to compile CFML files into bytecode format that you can deploy instead of CFML source code:

cfcompile -deploy webroot directory-to-compile output-directory

The following table describes these parameters:

Parameter | Description
webroot | Fully qualified path to the web server root; for example, C:\Inetpub\wwwroot or C:\CFusionMX7\wwwroot.
directory-to-compile | Fully qualified path to the directory where the files to be compiled are located. This directory must be under the webroot directory. This is required for the -deploy option.
output-directory | Fully qualified path to the directory to contain the compiled deployable files. This cannot be the same directory as the source directory.

After you run the cfcompile utility, perform the following steps:

  1. Back up your original CFML files
  2. Copy the generated bytecode CFML files to the original directory
  3. Deploy the application.

Tip: The J2EE Archive screen of the ColdFusion MX Administrator lets you create an EAR or WAR file that contains bytecode versions of your application’s CFML files.
Previous


Administering Security

This chapter describes configuration options for Macromedia ColdFusion MX security. You can secure a number of Macromedia ColdFusion MX 7 resources with password access and you can configure sandbox security.

Contents

About ColdFusion MX security

Using password protection

Using sandbox security
Next


About ColdFusion MX security

Security is especially important in web-based applications, such as those you develop in ColdFusion MX. ColdFusion developers and administrators must fully understand the security risks that could affect their development and runtime environments so they can enable and restrict access appropriately.

You implement development security by requiring a password to use the ColdFusion MX Administrator and a password for Remote Development Services (RDS), which allows developers to develop CFML pages remotely. You implement runtime security in your CFML pages and in the ColdFusion MX Administrator. ColdFusion MX has the following runtime security categories:

User security Programmatically determine the logged-in user and allow or disallow restricted functionality based on the roles assigned to that user. For more information about user security, see ColdFusion security features in Securing Applications in ColdFusion MX Developer’s Guide.

Sandbox security Using the ColdFusion MX Administrator, define the actions and resources that the ColdFusion pages in and below a specified directory can use.

Note: If you have the Enterprise Edition of ColdFusion MX, you can configure multiple security sandboxes. If you have the Standard Edition of ColdFusion MX, you can only configure a single security sandbox.

The Security area in the Administrator lets you do the following tasks:

  • Configure password protection for the ColdFusion MX Administrator. For more information, see ColdFusion MX Administrator password protection.
  • Configure password protection for RDS access. For more information, see RDS password protection.
  • Enable, disable, and customize ColdFusion security, on the Security > Sandbox Security page (called Resource Security page in the Standard edition). For more information, see Using sandbox security.


Using password protection

Password protection restricts access to the ColdFusion MX Administrator and to a ColdFusion server when you attempt access through RDS security.

ColdFusion MX Administrator password protection

Secure access to the ColdFusion MX Administrator is enabled by default. The password that you enter during installation is saved as the default. You are prompted to enter this password whenever you open the Administrator.

Password protection for accessing the Administrator helps guard against unauthorized modifications of ColdFusion MX, and Macromedia highly recommends using passwords. You can disable or change the Administrator password on the Security > CF Admin Password page.

RDS password protection

If you configured password protection for RDS access when you installed ColdFusion, you are prompted for the password when you attempt to access ColdFusion MX from Macromedia Dreamweaver MX 2004, Macromedia HomeSite+, or the ColdFusion Report Builder.

You can disable RDS or change the RDS password on the Security > RDS Password page.

Note: Disabling RDS also disables the applet that the ColdFusion MX Administrator uses in file-related dialog boxes.

If you use RDS security, you rely on web server and operating system security settings to set permissions for ColdFusion application and document directories.


Using sandbox security

Sandbox security (called Resource security in the Standard Edition) uses the location of your ColdFusion pages to control access to ColdFusion resources. A sandbox is a designated directory of your site to which you apply security restrictions. Sandbox security lets you specify which tags, functions, and resources (for example, files, directories, and data sources) can be used by ColdFusion pages located in and under the designated directory.

To use sandbox security in the multiserver and J2EE editions, the application server must be running a security manager (java.lang.SecurityManager) and you must define the following JVM arguments (for Macromedia JRun, this is the java.args line in the jrun_root/jvm.config file):

-Djava.security.manager
  -Djava.security.policy="cf_root/WEB-INF/cfusion/lib/coldfusion.policy"
  -Djava.security.auth.policy="cf_root/WEB-INF/cfusion/lib/neo_jaas.policy"

Note: Sandbox security is not enabled by default. You must enable it on the Security > Sandbox Security page before ColdFusion enforces the settings.

This section describes the following topics:

  • Using multiple sandboxes (Enterprise Edition only)
  • Resources that you can restrict
  • About directories and permissions
  • Adding a sandbox (Enterprise Edition only)
  • Configuring a sandbox

Using multiple sandboxes (Enterprise Edition only)

By default, a subdirectory of a sandbox inherits the settings of the directory one level above it. However, if you define a sandbox for a subdirectory, the subdirectory no longer inherits settings from the parent, completely overriding the parent directory’s sandbox settings. For example, consider the following directories:

C:\Inetpub\wwwroot
C:\Inetpub\wwwroot\sales
C:\Inetpub\wwwroot\rnd
C:\Inetpub\wwwroot\rnd\dev
C:\Inetpub\wwwroot\rnd\qa

If you define a sandbox for the wwwroot directory, the settings also apply to the sales and rnd directories. If you also define a sandbox for the rnd directory, the rnd sandbox settings also apply to the dev and qa directories; the wwwroot and sales directories maintain their original settings; and the rnd settings override the wwwroot directory settings for the rnd directory and its subdirectories.

This hierarchical arrangement of security permits the configuration of personalized sandboxes for users with different security levels. For example, if you are a web hosting administrator who hosts several clients on a ColdFusion shared server, you can configure a sandbox for each customer. This prevents one customer from accessing the data sources or files of another customer.

Resources that you can restrict

You can restrict the following resources:

Data Sources Restrict the use of ColdFusion data sources.

CF Tags Restrict the use of ColdFusion tags that manipulate resources on the server (or on an external server), such as files, the registry, Lightweight Directory Access Protocol (LDAP), mail, and the log.

CF Functions Restrict the use of ColdFusion functions that access the file system.

Files/Dirs Enable tags and functions in the sandbox to access files and directories outside of the sandbox.

Note: To use the Administrator API when sandbox security is enabled, you must allow access to the cf_web_root/CFIDE/adminapi directory.

Server/Ports Specify the servers, ports, and port ranges that the ColdFusion tags that call third-party resources can use.

For more information, see the Administrator online Help.

Note: When you run ColdFusion MX in the J2EE configuration on IBM WebSphere, the Files/Dirs and Server/Ports tabs are not enabled.

About directories and permissions

When you enable access to files outside of the sandbox, you specify the filename. When you enable access to directories outside of the sandbox, you specify directoryname\indicator, where indicator is a dash or asterisk, as follows:

  • A backslash followed by a dash (\-) lets tags and functions access all files in the specified directory, and recursively allows access to all files in subdirectories.
  • A backslash followed by an asterisk (\*) lets tags and functions access all files in the specified directory and also lets tags and functions access a list of subdirectories. However, this option denies access to files in any subdirectories.

You can also specify the actions that ColdFusion tags and functions can perform on files and directories outside the sandbox. The following table shows the relationship between the permissions of a file and a directory:

Permission | Effect on files | Effect on directories
Read | View the file | List all files in the directory
Write | Write to the file | Not applicable
Execute | Execute the file | Not applicable
Delete | Delete the file | Delete the directory


Adding a sandbox (Enterprise Edition only)

ColdFusion MX Enterprise Edition lets you define multiple security sandboxes.

To add a sandbox:

  1. Open the Security > Sandbox Security page in the ColdFusion MX Administrator.

    The Sandbox Security Permissions page appears.

  2. In the Add Security Sandbox box, enter the name of the new sandbox. This name must be either a ColdFusion mapping (defined in the Administrator) or an absolute path.
  3. Select New Sandbox from the drop-down list to create a sandbox based on the default sandbox, or select an existing sandbox to copy its settings to your new sandbox.
  4. Click Add.

    The new sandbox appears in the list of Defined Directory Permissions.


Configuring a sandbox

Before you begin security sandbox configuration, analyze your application and its usage to determine the tags, functions, and resources that it requires. You can then configure the sandbox to enable access to the required resources and disable use of the appropriate tags and functions. For example, if the applications in the sandbox do not use the cfregistry tag, you can safely disable it.

Note: In the Standard Edition, the Root Security Context is the only sandbox. There is no initial list of defined directory permissions.

To configure a sandbox:

  1. Open the Security > Sandbox Security page (Security > Resource Security page in the Standard Edition) in the ColdFusion MX Administrator.
  2. (Enterprise Edition only) In the list of Defined Directory Permissions, click the name or Edit icon for the directory.

    A page with several tabs appears. This is the initial page in the Standard Edition. The remaining steps describe the use of each tab.

  3. To disable a data source, in the left column of the Datasources tab, highlight the data source, and click the right arrow.

    By default, ColdFusion pages in this sandbox can access all data sources.

    Note: If <<ALL DATASOURCES>> is in the Enabled Datasources column, any data source that you add is enabled. If you move <<ALL DATASOURCES>> to the Disabled Datasources column, any new data source is disabled.

  4. Click the CFTags tab.
  5. To disable tags, in the left column of the CFTags tab, highlight the tags, and click the right arrow.

    By default, ColdFusion pages in this sandbox can access all listed tags.

  6. Click the CFFunctions tab.
  7. To disable functions, in the left column of the CFFunctions tab, highlight the functions, and click the right arrow.

    By default, ColdFusion pages in this sandbox can access all listed functions.

  8. Click the Files/Dirs tab.
  9. To enable files or directories, in the File Path box, enter or browse to the files or directories; for example, C:\pix. A file path that consists of the special token <<ALL FILES>> matches any file. For information on using the backslash-hyphen (\-) and backslash-asterisk (\*) wildcard characters, see About directories and permissions.
  10. Select the permissions.

    For example, select the Read check box to let ColdFusion pages in the mytestapps sandbox read files in the C:\pix directory.

  11. Click Add Files/Paths. When you edit an existing sandbox, this button reads Edit Files/Paths.

    The file path and its permissions appear in the Secured Files and Directories list.

  12. In the Secured Files and Directories list, verify that the file path is correct.

    The character after the backslash is important. For information, see About directories and permissions.

    Note: The Files/Dirs tab works together with the file-based permissions of the operating system. To restrict a user from browsing another user’s directory, you must use file-based permissions.

  13. Click the Server/Ports tab.
  14. To turn off default behavior (global access to all servers and ports), enter the IP addresses and port numbers that pages in this sandbox can connect to by using tags that access external resources (for example, cfmail, cfpop, cfldap, cfhttp, and so on). You can specify an IP address, a server name (such as www.someservername.com), or a domain name (such as someservername.com). You can optionally specify a port restriction.

    Note: This behavior differs from other tabs, such as CFTags, where you select items to disable. If you set any values in this tab, external-resource tags executed in this sandbox can access only the specified servers and ports.

    For example, to allow this sandbox access to 207.88.220.3 on ports 80 and lower, perform the following steps:

    1. In the IP Address field, enter 207.88.220.3.
    2. In the Port field, enter 80, and click This Port and Lower.

    Tip: To deny access by these ColdFusion tags to an entire site, enable access for a local resource, such as your local mail server, FTP server, and so on.

  15. Click Finish to save changes to the sandbox.
Previous


Using Multiple Server Instances

When you install Macromedia ColdFusion MX 7 Enterprise Edition using the multiserver configuration, you can use the ColdFusion MX Administrator to create multiple server instances. Deploying ColdFusion MX on multiple server instances lets you isolate individual applications and leverage clustering functionality.

Management of multiple server instances has changed significantly in ColdFusion MX 7:

ColdFusion MX Use a J2EE deployment, along with J2EE application server features to deploy the ColdFusion MX application on multiple instances of the J2EE application server.

ColdFusion MX 7 Use the ColdFusion MX Administrator in the multiserver configuration to create Macromedia JRun server instances and to automatically deploy the ColdFusion MX application on those instances. Additionally, you can combine the Administrator-driven server instance creation with the ColdFusion MX Administrator J2EE Archive feature to deploy a ColdFusion MX application that contains all of your application’s CFM files (including CFCs and CFRs), settings (including data source definitions), and the ColdFusion web application. For more information on J2EE Archive, see Packaging applications in J2EE archive files.

Note: Although the concepts and procedures explained in the ColdFusion MX documentation still apply, ColdFusion MX 7 incorporates multiple instance and cluster creation into the ColdFusion MX Administrator.

Contents

About multiple server instances

Defining additional server instances

Enabling application isolation

Enabling clustering for load balancing and failover

Defining remote server instances to the ColdFusion MX Administrator

Next


About multiple server instances

The ColdFusion MX Administrator lets you create server instances and clusters. Additionally, you can connect to remote JRun servers and add them to clusters.

Running multiple instances of ColdFusion MX has the following advantages:

Application isolation You deploy an independent application to each server instance. Each server instance has separate settings and, because each server instance runs in its own Java Virtual Machine (JVM), problems encountered by one application have no effect on other applications.

Clustering (load balancing and failover) You deploy the same application to each server instance and add the instances to a cluster. The web server connector optimizes performance and stability by automatically balancing load and by switching requests to another server instance when a server instance stops running.

This chapter describes features that are available only if you have installed the multiserver configuration. The multiserver configuration is a specialized J2EE configuration that installs JRun and deploys ColdFusion MX as an expanded Enterprise Application Archive (EAR) in the cfusion JRun server. The cfusion server is the only server that can create servers and clusters. The JRun instance creation and clustering options in the ColdFusion MX Administrator are not available in the server configuration, nor are they available in the J2EE configuration, even if you deploy on JRun.

Note: You can also manually deploy ColdFusion MX on multiple server instances, using your J2EE application server’s server creation and deployment facilities, as documented in the ColdFusion MX 6.1 documentation.

Expanded archive considerations

ColdFusion MX must run from an expanded directory structure. The Instance Manager expands the EAR or WAR file automatically and then deploys the expanded directory structure into the new server instance.

For more information on deploying ColdFusion MX in the J2EE configuration, see Installing and Using ColdFusion MX.

File location considerations

ColdFusion MX lets you store CFM pages either under the external web server root or under the ColdFusion web application root. The discussions in this chapter assume that you store your CFM pages under the ColdFusion web application root and that you specify a context root for your application. This is different from ColdFusion MX 6.1 documentation, which assumed that you stored CFM pages under the web server root.

If you use the web server connector to access pages under the ColdFusion web application root and your ColdFusion web application has an empty context root (this is the default), the connector does not automatically serve static content, such as HTML pages and image files. If this is the case, you must define web server mappings so that it can serve files from the ColdFusion web application root.

For more information on serving CFM pages from the web server root, see Web Server Management


Defining additional server instances

The multiserver configuration is a customized installation of JRun. JRun supports multiple server instances (also called JRun servers) running on the same computer. Each server instance runs in a separate JVM, which executes all ColdFusion pages for that instance.

You use the Instance Manager area of the ColdFusion MX Administrator to define and manage server instances. The Instance Manager only runs in the cfusion JRun server that is created as part of a multiserver configuration installation.

When you create a server instance with the Instance Manager, by default it deploys a copy of the cfusion server’s ColdFusion enterprise application, including data sources, mappings, and settings. Alternatively, you can create a new server instance and specify the location of an EAR or WAR file (created by the J2EE Archive page), which the Instance Manager uses as the basis for your new ColdFusion server instance.

Note: If you are running JRun 4, you can also create a server in the JRun Management Console (JMC) and deploy the ColdFusion application using JRun deployment functionality.

To define a server instance:

  1. Ensure that you have installed ColdFusion MX 7 using the multiserver configuration.
  2. Open the ColdFusion MX Administrator for the cfusion server in a browser (http://hostname:8300/CFIDE/administrator).
  3. Select Enterprise Manager > Instance Manager.
  4. Click Add New Instance.
  5. Specify the following in the Add New ColdFusion Server area:
    • Server name
    • (Optional) Directory that contains the server instance. The ColdFusion MX Administrator fills in the default automatically (jrun_root/servers/servername).
    • (Optional) Create from EAR/WAR. If you use the J2EE Packaging feature to create a J2EE archive file with your application’s files (including CFM, CFC, and CFR files) and data sources, use this field to specify the EAR or WAR filename and create a server instance with your application deployed automatically.
    • (Optional, Windows only) Specify whether to create a Windows service for the server instance and whether to define the Windows service with an auto restart recovery option.
  6. Click Submit.

    The ColdFusion MX Administrator creates a server instance with ColdFusion MX deployed in it and starts the server instance. The ColdFusion MX application that it deploys is based on the application archive file specified in the Create from EAR/WAR field or on the cfusion server instance (if you don’t specify an EAR or WAR file).

    Creating a JRun server instance and deploying the ColdFusion MX application can take a few minutes.

  7. Click Return to Instance Manager.

You can also start and stop the server instance using the JMC, the JRun Launcher, or the command line (jrun_root/bin jrun -start|-stop servername).


Enabling application isolation

You can create separate server instances, each with its own ColdFusion applications; each application then has its own ColdFusion and J2EE server resources. In this configuration, you typically have a single external web server with multiple server instances on one computer, and separate virtual hosts (or sites) for each server instance.

Note: Although this section describes using ColdFusion MX, other J2EE application servers provide equivalent capabilities, and most of the concepts apply when deploying the ColdFusion MX J2EE configuration on those J2EE servers.

Running independent applications this way has several advantages, including the following:

  • Errors at the levels of the ColdFusion application or the JRun server do not affect any other ColdFusion applications.
  • You can support multihomed servers, where a single web server supports multiple IP addresses or domain names, such as www.mycompany.com and services.anothercompany.com, each running from a separate web root. For more information, see Multihoming.
  • Individual applications can use different JVM configurations, or even different JVM implementations. This feature is particularly useful if one application requires a particularly large Java heap. To specify customized JVM options, start the JRun server instance from the command line using the -config option of the jrun command, which specifies a customized jvm.config file. This is explained in the "Starting and stopping JRun servers" section in Installing and Using ColdFusion MX.

Note: These instructions describe creating multiple server instances on a single computer. To create multiple server instances on separate computers, each computer requires a separate license of ColdFusion MX Enterprise Edition.

To achieve complete application isolation, you use web-server-specific functionality to create a separate website for each application. Web servers have different terminology for this concept. For example, in IIS, you define separate websites (available in Windows server editions only) and in Apache, you create multiple virtual hosts.

These instructions apply when running ColdFusion MX in the multiserver configuration. The principles apply when running ColdFusion MX on other J2EE application servers. However, not all J2EE application servers integrate with external web servers. For more information, see Multihoming.

These instructions assume that you deploy each application at a named context root, which enables users to access CFM pages by specifying http://hostname/context-root/pagename.cfm. If other web applications are running in the server instance, each web application must use a different context root.

For example, with a context root of cfmx, users access CFM pages by specifying http://hostname/cfmx/pagename.cfm. For more information on using a context root, see Installing and Using ColdFusion MX.

Note: Although cfmx is the context root, it does not relate to your web application directory structure.

To use multiple server instances for application isolation:

  1. Create a separate server instance using the instructions in Defining additional server instances. If you are using the built-in web server, proceed to step 6 in this procedure.
  2. Using your web-server-specific method, create a virtual website (or separate website) for the application.

    This is different for each web server; for more information, see Multihoming or consult your web server documentation.

  3. Test each virtual website to ensure that HTML pages are served correctly.
  4. Store your application’s ColdFusion files in the ColdFusion web application root (recommended for application portability) or the web root of the virtual website.
  5. Follow the instructions for your web server to configure the connection between your virtual website and the server instance. For more information, see Web server configuration for application isolation.
  6. Test your application.
  7. Repeat these steps for each server instance.


Web server configuration for application isolation

When you use multiple server instances for application isolation, the steps you perform to configure communication between the website and the server instance differ for each web server. This section contains the following sections:

  • Configuring application isolation in IIS
  • Configuring application isolation in Apache
  • Configuring application isolation in Sun ONE Web Server

Tip: To enhance performance when using an external web server with multiple server instances, place all static content (HTML files and images, for example) under the web server root directory or one of its subdirectories. Minimize the amount of static content served from ColdFusion web application root directory.

Configuring application isolation in IIS

When you use multiple virtual websites with multiple server instances under IIS, you define separate filters and mappings for each virtual website and server instance combination.

This section assumes that you already created server instances and virtual websites, as described in Enabling application isolation.

To configure multiple server instances for application isolation when using IIS:

  • Run the Web Server Configuration Tool multiple times, once for each virtual website, and specify a different site and server instance each time. Ensure that you select the Configure Web Server for ColdFusion MX Applications check box (GUI) or use the -coldfusion option (command-line). For more information on running the Web Server Configuration Tool, see Using an external web server.

Configuring application isolation in Apache

When you use multiple virtual hosts with multiple server instances under Apache, you edit the httpd.conf file manually.

This section assumes that you already created server instances and virtual websites, as described in Enabling application isolation.

To configure multiple server instances for application isolation when using Apache:

  1. Run the Web Server Configuration Tool once, specifying the location of the Apache httpd.conf file and any other required information. Ensure that you select the Configure Web Server for ColdFusion MX Applications check box (GUI) or use the -coldfusion option (command-line).
  2. The Web Server Configuration Tool creates a sequentially numbered subdirectory under jrun_root/lib/wsconfig. You can use the subdirectory created by the Web Server Configuration Tool for one of your virtual hosts, but you must create additional subdirectories for all other virtual hosts. For example, the first time you run the Web Server Configuration Tool, it creates jrun_root/lib/wsconfig/1; if you have two other virtual hosts, you must manually create two other directories (jrun_root/lib/wsconfig/mystore and jrun_root/lib/wsconfig/myemp in this example). These directories can be empty.
  3. Open the jrun_root/servers/servername/SERVER-INF/jrun.xml file for each of your server instances, locate the ProxyService service, ensure that the deactivated element is set to false, and note the value of the port element; for example:
    ...
<service class="jrun.servlet.jrpp.JRunProxyService" name="ProxyService">
  <attribute name="activeHandlerThreads">25</attribute>
  <attribute name="backlog">500</attribute>
  <attribute name="deactivated">false</attribute>
  <attribute name="interface">*</attribute>
  <attribute name="maxHandlerThreads">1000</attribute>
  <attribute name="minHandlerThreads">1</attribute>
  <attribute name="port">51002</attribute>
...
  4. Restart each of the modified JRun servers.
  5. Open the apache_root/conf/httpd.conf file in a text editor and find the VirtualHost directives. The settings added by the Web Server Configuration Tool are after the last </IfModule> directive, as the following example shows:
    ...
# JRun Settings
LoadModule jrun_module "C:/JRun4/lib/wsconfig/1/mod_jrun20.so"
<IfModule mod_jrun20.c>
    JRunConfig Verbose false
    JRunConfig Apialloc false
    JRunConfig Ssl false
    JRunConfig Ignoresuffixmap false
    JRunConfig Serverstore "C:/JRun4/lib/wsconfig/1/jrunserver.store"
    JRunConfig Bootstrap 127.0.0.1:51000
    #JRunConfig Errorurl <optionally redirect to this URL on errors>
    #JRunConfig ProxyRetryInterval <number of seconds to wait before trying to reconnect to unreachable clustered server>
    #JRunConfig ConnectTimeout 15
    #JRunConfig RecvTimeout 300
    #JRunConfig SendTimeout 15
    AddHandler jrun-handler .jsp .jws .cfm .cfml .cfc .cfr .cfswf
</IfModule>

NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
    ServerAdmin admin@mysite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs"
    ServerName SERVER02
    ErrorLog logs/error.log
</VirtualHost>
<VirtualHost 127.0.0.1>
    ServerAdmin admin@mysite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs2"
    ServerName mystore
    ErrorLog logs/error-store.log
</VirtualHost>
<VirtualHost 127.0.0.1>
    ServerAdmin admin@mysite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs3"
    ServerName myemployee
    ErrorLog logs/error-employee.log
</VirtualHost>
...
  6. For each VirtualHost directive that relates to a ColdFusion server instance, copy the entire IfModule mod_jrun20.c directive from its original location outside the VirtualHost directive to the last element in the VirtualHost directive.
  7. Delete the Apialloc, Ssl, Ignoresuffixmap, and AddHandler elements in the IfModule directive for each virtual host. Modify the Serverstore and Bootstrap elements to point to the appropriate proxy port (from the jrun.xml file) and jrun_root/lib/wsconfig/subdirectory/jrunserver.store file, which the web server connector creates automatically.
  8. In the original IfModule directive, remove or comment out the Serverstore and Bootstrap lines (comments start with #). The following example shows three virtual hosts, two of which are configured for ColdFusion MX:
    ...
# JRun Settings
LoadModule jrun_module "C:/JRun4/lib/wsconfig/1/mod_jrun20.so"
<IfModule mod_jrun20.c>
    JRunConfig Verbose false
    JRunConfig Apialloc false
    JRunConfig Ssl false
    JRunConfig Ignoresuffixmap false
    #JRunConfig Serverstore "C:/JRun4/lib/wsconfig/1/jrunserver.store"
    #JRunConfig Bootstrap 127.0.0.1:51020
     AddHandler jrun-handler .jsp .jws .cfm .cfml .cfc .cfr .cfswf
</IfModule>
NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
    ServerAdmin admin@mysite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs"
    ServerName RNIELSEN02
    ErrorLog logs/error.log
</VirtualHost>
<VirtualHost 127.0.0.1>
    ServerAdmin admin@mysite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs2"
    ServerName rnielsenstore
    ErrorLog logs/error-store.log
  <IfModule mod_jrun20.c>
    JRunConfig Verbose true
    JRunConfig Serverstore "C:/JRun4/lib/wsconfig/mystore/jrunserver.store"
    JRunConfig Bootstrap 127.0.0.1:51002
  </IfModule>
</VirtualHost>
<VirtualHost 127.0.0.1>
    ServerAdmin admin@mysite.com
    DocumentRoot "C:/Program Files/Apache Group/Apache2/htdocs3"
    ServerName rnielsenemployee
    ErrorLog logs/error-employee.log
  <IfModule mod_jrun20.c>
    JRunConfig Verbose true
    JRunConfig Serverstore "C:/JRun4/lib/wsconfig/myemp/jrunserver.store"
    JRunConfig Bootstrap 127.0.0.1:51003
  </IfModule>
</VirtualHost>
...
  9. Restart Apache.
  10. (Optional) Store the application’s ColdFusion files in your external web server root directory.
  11. Test the applications under each virtual host.

    Note: Remember that the web server connector doesn’t serve static content, such as HTML and images. Place these files under the web root or create a web server mapping to the ColdFusion web application root.

Configuring application isolation in Sun ONE Web Server

When using multiple virtual hosts with multiple server instances under Sun ONE Web Server, you create multiple Sun ONE Web Server instances, one for each ColdFusion server instance.

This section assumes that you have already created server instances, as described in Enabling application isolation.

To configure multiple server instances for application isolation when using Sun ONE Web Server:

  • Run the Web Server Configuration Tool multiple times, once for each Sun ONE Web Server server instance, and specify a different configuration directory and ColdFusion server instance each time. Ensure that you select the Configure Web Server for ColdFusion MX Applications check box (GUI) or use the -coldfusion option (command-line).


Enabling clustering for load balancing and failover

Load balancing is an enterprise-level feature in which the application server automatically alternates requests among the server instances in a cluster. Clustering also enables application servers to route requests to a running server instance when the original server instance goes down.

Note: These instructions apply only when you are running ColdFusion MX in the multiserver configuration. If you are running JRun4, you can also create clusters in the JMC.

You can get load balancing and failover by deploying identical ColdFusion applications and configurations to multiple server instances and adding the instances to a cluster. Each instance must have the same applications deployed and the same resources configured (such as data sources, Verity collections, and mappings). The web server connector optimizes performance and stability by automatically balancing load and by switching requests to another server instance when a server instance stops running.

Note: Because clustering uses Jini Network Technology, you must be connected to a network for clustering to work.

For maximum failover protection, use multiple computers in a cluster. However, you must purchase a separate ColdFusion MX Enterprise Edition license for each computer.

Note: If you set up and test multiple server instances while running the 30-day Trial version, the cluster might not continue to function appropriately when the Trial version reverts to the Developer version after 30 days.

To implement session failover for the server instances in a cluster, you must enable session replication for each server instance. Session replication coordinates session information in real-time among the server instances in a cluster. Enabling session replication lets JRun automatically route a request to a running server if the current server is unavailable.

Note: When a cluster uses session replication, session data is copied to other servers in the cluster each time it is modified. This can degrade performance if you store a significant amount of information in session scope. If you plan to store a significant amount of information in session scope, consider storing this information in client variables saved in a database.

To configure a cluster of server instances for load balancing and failover:

  1. Create your application and the data sources required for the application.
  2. Ensure that you have installed ColdFusion MX 7 using the multiserver configuration.
  3. Open the ColdFusion MX Administrator for the cfusion server in a browser (http://hostname:8300/CFIDE/administrator).
  4. Select Packaging & Deployment > J2EE Packaging.
  5. Use the J2EE Archives page to create an EAR file that contains the application, your application’s CFM pages, the required data sources, and other settings.
  6. Select Enterprise Manager > Instance Manager.
  7. Create server instances for the cluster as described in Defining additional server instances. Ensure that you use the Create from EAR/WAR field to specify the archive file that you just created.
  8. (Optional) Click the Register Remote Instance button to define existing remote server instances so that you can include them in the cluster. If you use a remote server, ensure that it contains the same application and settings as the local server instances.

    Note: A server can participate in only one cluster. When adding remote instances to a cluster, ensure that the instance is not already part of a cluster.

  9. Ensure that each server instance is started.

    Note: To administer a cluster, at least one member server instance must be running.

  10. Select Enterprise Manager > Cluster Manager.
  11. Name the cluster and click Add.

    The ColdFusion MX Administrator adds the cluster to the Configured Clusters area.

  12. Click the cluster name or the edit icon.

    The Edit Cluster screen appears.

  13. Use the arrow icons to add server instances to the cluster.
  14. (Optional) Enable session replication, and specify a cluster algorithm.

    Note: When you enable sticky sessions, the connector does not always route requests strictly based on the cluster algorithm. For more information, see Administrator online Help.

  15. Click Submit.
  16. Select Enterprise Manager > Instance Manager.
  17. Open the ColdFusion MX Administrator on each server instance using the CF Admin icon on the Instance Manager. Ensure that required resources (such as data sources and Verity collections) are defined appropriately. If you are using session replication, go to the Memory Variables page and enable J2EE sessions. You must do this for all server instances in the cluster. If J2EE sessions are not enabled in the ColdFusion MX Administrator, session replication does not function properly.

    Note: Session variables are the only memory variables that support session replication. In particular, ColdFusion components do not support session replication.

  18. For servers that are not on the same subnet, open the jrun_root/lib/security.properties file and add the IP addresses of the other JRun servers in the cluster to the jrun.trusted.hosts property.

    Note: This step is required only for servers that are not on the same subnet; it is not necessary if all servers are on the same subnet.

  19. Restart all JRun servers in the cluster.
  20. Run the Web Server Configuration Tool. Choose your website, but instead of choosing a single server instance, select the cluster. Ensure that you select the Configure Web Server for ColdFusion MX Applications check box (GUI) or use the -coldfusion option (command-line). For more information, see Web server configuration.
  21. Open each server instance’s SERVER-INF/jrun.xml file and ensure that the ProxyService deactivated attribute is set to false.
  22. (Optional) Store the application’s ColdFusion files in your external web server root directory.
  23. Test the application to ensure that load balancing and failover work as expected.


Defining remote server instances to the ColdFusion MX Administrator

You can use the Cluster Manager to add ColdFusion MX server instances running on other computers; however, you must first define them to the ColdFusion MX Administrator through the Add Remote Server Instance area of the Instance Manager page.

Note: To define a remote server instance, it must be running. You cannot start or stop servers remotely.

To define a remote server instance to ColdFusion:

  1. Open the ColdFusion MX Administrator for the cfusion server in a browser (http://hostname:8300/CFIDE/administrator).
  2. Select Enterprise Manager > Instance Manager.
  3. Specify the following in the Add Remote ColdFusion Instance area:
    • Server name
    • The IP address or DNS name of the remote host.
    • The remote port of the remote server. To determine the remote port, open the jrun_root/servers/servername/SERVER-INF/jndi.properties file and note the port number in the java.naming.provider.url property.
  4. Click Add Remote ColdFusion Server.
Previous


Introducing Verity and Verity Tools

This chapter provides an overview of the advanced Verity features included in Macromedia ColdFusion MX 7.

Contents

Collections and the ColdFusion MX Verity architecture

About Verity Spider (vspider)

About the Verity utilities
Next


Collections and the ColdFusion MX Verity architecture

ColdFusion MX includes Verity K2 Server search technology. Verity K2 Server is a high-performance search engine designed to process searches quickly in a high-performance, distributed system. The K2 search system has a client/server model. K2 client applications, such as ColdFusion server, provide users access to document indexes stored in Verity collections. K2 Server supports simultaneous indexing of distributed enterprise repositories, and handles hundreds of concurrent queries and users.

The Verity search system takes advantage of the latest advances in hardware and software technology, and provides the following features:

  • Multithreaded architecture
  • Support for Verity knowledge retrieval features, including topics
  • Continuous operation support
  • High scalability
  • Category support (also called parametric indexes)

Note: ColdFusion MX no longer uses VDK mode and K2 mode. All Verity processing now uses the K2 architecture. Additionally, ColdFusion MX no longer uses the neo-verity.xml file.

Because ColdFusion MX reads custom queries into memory, indexing a large query result set can cause a "Java out of memory" error or lead to excessive disk use on your computer if your ColdFusion MX Java Virtual Machine (JVM) memory allocation is too small. Manage ColdFusion JVM memory settings as follows:

Server configuration Through the -Xmx argument to the java.args parameter in the cf_root/runtime/bin/jvm.config file (for example, [-Xmx512m]).

Multiserver configuration Through the jrun_root/bin/jvm.config file.

J2EE configuration Through application server-specific methods.

Verity information storage

The Verity Search Server runs as a separate process from ColdFusion MX. This server controls all access to Verity collections, as the following figure shows:

This is a picture of the feature being described.

In the multiserver and J2EE configurations, multiple ColdFusion server instances all use the same Verity Search Server to access the same set of Collections.

ColdFusion MX uses different processes for Windows and UNIX, as follows:

Windows The ColdFusion MX 7 Verity Search Server service manages and controls configuration and services of a Verity K2 domain. This service starts three processes: k2server.exe, k2index.exe, and k2admin.exe.

UNIX The cf_root/bin/cfmxsearch control script (cf_webapp_root/WEB-INF/cfusion/bin/cfmxsearch in the multiserver configurations) starts and stops Verity. When you call this script with the start argument, it calls verity_root/k2/platform_dir/bin/k2adminstart with the appropriate user context and environment, which in turn starts up three processes: k2server, k2index, and k2admin. Calling the script with the stop argument calls the Verity k2adminstop script, which kills those three processes.

Note: When you use the J2EE configuration, you must install Verity separately. For more information, see Installing the Verity search server separately in Installing and Using ColdFusion MX.

You can install the Verity Search Server on a separate computer from ColdFusion MX. For more information, see Administrator online Help.

Tip: If no Verity collections appear in the ColdFusion MX Administrator, it probably means that the Verity Search Server process isn’t running.


About Verity Spider (vspider)

Verity Spider (vspider) lets you index web-based and file system documents throughout your enterprise, including dynamic content, and many application document formats, including Microsoft Office, WordPerfect, ASCII text, HTML, and PDF (Adobe Acrobat) documents. For more information, see Indexing Collections with Verity Spider.


About the Verity utilities

ColdFusion MX includes several Verity utilities to diagnose and manage your collections. These tools include the mkvdk, rcvdk, rck2, and vspider utilities.

The following table describes the relationship between the major Verity utilities and the corresponding cfcollection, cfsearch, and cfindex ColdFusion tags. The cfcollection tag operates on the entire collection; the cfindex tag operates on records within a collection. For more information, see Using Verity Utilities.

 | cfcollection |  |  |  | cfindex |  |  |  | cfsearch
utility | create | repair | delete | optimize | update | delete | purge | refresh | search
mkvdk | X | X |  | X | X | X | X | X |
rcvdk |  |  |  |  |  |  |  |  | X (file-system based)
rck2 |  |  |  |  |  |  |  |  | X (server-based)

ColdFusion MX OEM restrictions

ColdFusion MX includes a restricted version of the Verity Server, with restrictions in the following areas:

  • ColdFusion MX can only interact with one Verity Server at a time.
  • Verity Server has the following document search limits (limits are for all collections registered to Verity Server):
    • 10,000 documents for ColdFusion MX Developer Edition
    • 125,000 documents for ColdFusion MX Standard Edition
    • 250,000 documents for ColdFusion MX Enterprise Edition

    Note: Each row in a database table is considered a document.

    If you install a fully licensed version of Verity Server and you configure ColdFusion MX to use it, ColdFusion MX does not restrict document searches.

  • The Verity Spider that is included with ColdFusion MX is licensed for local host indexing only. Contact Verity Sales for licensing options regarding the use of the Verity Spider for remote host indexing.

Additionally, ColdFusion MX OEMs and ISVs have the following document search limits:

  • 5,000 documents for ColdFusion MX Developer Edition
  • 62,500 documents for ColdFusion MX Standard Edition
  • 125,000 documents for ColdFusion MX Enterprise Edition
Previous


Indexing Collections with Verity Spider

This chapter contains basic Verity Spider information and explains how to index documents on your website.

Contents

About Verity Spider

About Verity Spider syntax

Core options

Processing options

Networking options

Path and URL options

Content options

Locale options

Logging options

Maintenance options

Setting MIME types
Next


About Verity Spider

Verity Spider (vspider) enables you to index web-based and file system documents throughout your enterprise. Verity Spider lets you index more than two hundred of the most popular application document formats, including Microsoft Office, WordPerfect, ASCII text, HTML, SGML, XML and PDF (Adobe Acrobat) documents.

Another advantage of this method, is that the index created by vspider includes dynamic content. The cfindex tag and indexing a collection through the Macromedia ColdFusion MX Administrator do not include dynamic content.

The Verity Spider that is included with ColdFusion MX is licensed for websites that are defined and reside on the same machine on which ColdFusion MX is installed. Contact Verity Sales for licensing options regarding the use of Verity Spider for external websites.

This section describes the following topics:

  • Web standard support
  • Restart capability
  • State maintenance through a persistent store
  • Performance

Web standard support

Verity Spider supports key web standards used by Internet and intranet sites. Standard HREF links and frames pointers are recognized, so that navigation through them is supported. Redirected pages are followed so that the real underlying document is indexed. Verity Spider adheres to the robots exclusion standard specified in robots.txt files, so that administrators can maintain friendly visits to remote websites. HTTP Basic Authentication mechanism is supported so that password-protected sites can be indexed.

Restart capability

When an indexing job fails, or for some reason Verity Spider cannot index a significant number or type of URLs, you can now restart the indexing job to update the collection. Only those URLs that were not successfully indexed previously are processed.

State maintenance through a persistent store

Verity Spider stores the state of gathered and indexed URLs in a persistent store, which lets it track progress for the purposes of gracefully and efficiently restarting halted indexing jobs.

Performance

Spidering performance is greatly improved over previous versions, because of low memory requirements, flow control, and the help of multithreading and efficient Domain Name System (DNS) lookups.

Flow control

When indexing websites, Verity Spider distributes requests to web servers in a round-robin manner. This means that one URL is fetched from each web server in turn. With flow control, a faster website can finish before a slower one. The Verity Spider optimizes indexing on every web server.

Verity Spider adjusts the number of connections per server depending on the download bandwidth. When the download bandwidth from a web server falls below a certain value, Verity Spider automatically scales back the number of connections to that web server. There will always be at least one connection to a web server. When the download bandwidth increases to an acceptable level, Verity Spider reallocates connections (per the value of the -connections option, which is 4 by default). You can turn off flow control with the -noflowctrl option.

Multithreading

Verity Spider separates the gathering and indexing jobs into multiple threads for concurrence. Additionally, Verity Spider can create concurrent connections to web servers for fetching documents, and have concurrent indexing threads for maximum utilization. This translates to an overall improvement in throughput.

Efficient DNS lookups

Verity Spider minimizes DNS lookups, which means great improvements to spidering throughput. If spidering is limited by domain or host, then no DNS lookups are made on hosts that fall outside of that range. In earlier versions, DNS lookups were made on all candidate URLs.

Proxy handling efficiency

To allow for greater flexibility when dealing with indexing jobs that involve proxy servers and firewalls, use the following options:

-noproxy To reduce proxy checking for certain hosts

-proxyauth To authenticate on proxy servers


About Verity Spider syntax

Before you create an indexing task for a new collection, make copies of the relevant default style files to ensure that you have a set of template style files in a known, stable state.

Running multiple simultaneous Verity Spider jobs can cause performance problems for searches. This does not mean that you should never run indexing jobs when users might be searching, because your collections are available for searching even while indexing jobs are running. To optimize performance, try staggering your indexing jobs to avoid overloading your server.

This section contains the following discussions:

  • The Verity Spider command
  • Using a command file
  • Command-line option reference


The Verity Spider command

The vspider executable file, which starts the Verity Spider utility, is located in the platform/bin directory, as follows:

Server and multiserver configuration The vspider.exe (Window) or vspider (UNIX) file is located in cf_root/verity/k2/platform/bin (server configuration) or jrun_root/verity/k2/platform/bin (multiserver configuration) where platform is _nti40 for Windows, _solaris for Solaris, or _ilnx21 for Linux.

J2EE configuration The vspider.exe (Window) or vspider (UNIX) file is located in verity_root/k2/platform/bin where platform is _nti40 for Windows, _solaris for Solaris, or _ilnx21 for Linux.

At its most basic level, a Verity Spider command consists of the following:

vspider -initialize -collection coll [options]

Where -initialize is -start or -refresh (when starting points have changed), and -collection is required to provide a target for the Verity Spider, and [options] can be a near-limitless combination of the options described later in this chapter.

For example:

c:\cfusionmx7\verity\k2\_nti40\bin\vspider -common c:\cfusionmx7\verity\k2\common
-collection c:\new -start http://localhost -indinclude *

There are dependencies for other options, depending on the nature of the indexing task. The following are some examples:

  • To build a new collection, you must use -style.
  • To control how Verity Spider operates, including which documents it indexes, use some Verity Spider options.

If you do not run the Verity Spider executable from its default installation directory, you must include that directory in your path. This is because the Verity Spider executable depends on other files to run properly.

To use the vspider command on UNIX and Linux, the directory that contains the libvdk30.so file must be in your LD_LIBRARY_PATH variable. In the server configuration, this directory is cf_root/verity/k2/platform/bin; in the multiserver configuration, this directory is jrun_root/servers/cfusion/WEB-INF/cfusion/verity/k2/platform/bin. For example, in the server configuration on Linux, this directory is cf_root/verity/k2/_ilnx21/bin.


Using a command file

For simpler reuse and archiving of your indexing commands, use the -cmdfile option for abstraction. By using an ASCII text file to store a task’s options, you avoid the potential problem of using special characters in an option’s parameter value. For example, the -processbif option requires the use of "!*" and therefore any task using that option must also use the -cmdfile option.


Command-line option reference

The following sections describe the Verity Spider V 5.0 command-line options. Option names are case-sensitive.

-start

Specifies a starting point for an indexing job. You can specify multiple instances, or use multiple values in a single instance.

When you execute an indexing job from a command line, and you do not use a command file (with the -cmdfile option), you must URL-escape any special characters in the starting point. To URL-escape a special character, use "%hex-ASCII-character-number" in place of the character. For example, use /time%26/ instead of /time&/. This allows the operating system to properly process the command string.

If an indexing task halts, you can rerun the task as-is. The persistent store for the specified collection is read, and only those candidate URLs that are in the queue but not yet processed are parsed. Candidate URLs correspond to URLs of the following status, as reported by vsdb:

cand, used, inse, upda, dele, fail

Repository type | Starting point
Web | The URL or URLs from which Verity Spider is to begin indexing. Use other options, such as the -jumps option, to control how far from the starting point Verity Spider goes.
File | The starting directory or directories in which Verity Spider will start indexing. All subdirectories beneath the starting point will be indexed, unless you use the -pathlen option or any of the inclusion or exclusion criteria.

Note: By using the -start option with the -refresh option, you provide a starting point for Verity Spider and therefore do not need to use at least one of the following options: -host, -domain,
-nofollow, or -unlimited.

-refresh

Used for updating a collection, specifies that Verity Spider process only those documents that qualify, as follows:

  • They are new documents in the repository, and they qualify for indexing under the criteria.
  • They exist in the collection and are recorded in the Verity Spider persistent store with a status of done. If Verity Spider determines that these indexed documents have been updated in the repository, then they are retrieved again to be reparsed and reindexed. The document VdkVgwKey values do not change.
  • They are deleted in the collection. If Verity Spider determines that documents have been deleted from the repository, then they are also deleted from the persistent store and the collection. The exception to this rule is when you use the -nooptimize option with the
    -refresh option. In this case, any document deleted from the repository is marked for deletion in the collection. It will be removed from the collection and the persistent store when the next indexing task is run for the collection.

When you rerun an existing indexing job, Verity Spider automatically refreshes the collection. If you add or remove any of the starting points, however, you must manually specify the -refresh option to refresh existing documents.

Note: You can also use the -start option to provide a starting point for Verity Spider. If you do not use the -start option, use at least one of the following options: -host, -domain, or -nofollow. For further control, also see the -refreshtime option. If you do not use any constraint criteria, Verity Spider operates without limits and will likely index far more than you intended.


Core options

The following sections describe the Verity Spider core options.

-cmdfile

Syntax: -cmdfile path_and_filename

Specifies that Verity Spider reads command-line syntax from a file, in addition to the options passed in the command-line. This option includes the pathname to the file that contains the command-line syntax. The -cmdfile option circumvents command-line length limits.

The syntax for the command-file is:

option optional_parameters

For better readability, put each option and any parameters on a single line. Verity Spider can properly parse the lines.

Note: Macromedia strongly recommends that you take advantage of the abstraction offered by this option. This can greatly reduce user error in erroneously including or omitting options in subsequent indexing jobs.

-collection

Specifies the full path to the collection to create or update.

Note: You receive an error if you specify a filename with an extension of CLM. Meta collections are not supported.

-help

Displays Verity Spider syntax options.

-jobpath

Syntax: -jobpath path

Specifies the location of the Verity Spider databases and the indexing job-related files and directories.

The following are the job-related directories and their contents:

log All Verity Spider log files. For descriptions of the log files, see -loglevel.

bif Bulk insert files.

temp Web pages cached for indexing. You can also specify the temp directory using the
-temp option.

These directories are created for you under the last directory specified in path.

Path values must be unique for all indexing jobs. If you do not use the -jobpath option, Verity Spider creates a /spider/job directory within the collection. For multiple-collection tasks, the first collection specified is used.

Note: You cannot use multiple job paths for multiple simultaneous indexing tasks for the same collection. Only one indexing task at a time can run for a given collection.

-style

Syntax: -style path

Specifies the path to the style files to use when creating a new collection.

If the -style option is not specified, Verity Spider uses the default style files in cf_root/lib/common/style.

Note: You can safely omit the -style option when resubmitting an indexing job, as the style information will already be part of the collection. If you are using the -cmdfile option, you can leave it there.


Processing options

The following sections describe the Verity Spider processing options.

-abspath

Type: File system only

Generates absolute paths for files. Use this option when the document locations are not going to change, but the collection might be moved around.

When you index a web server's contents through the file system, use the -prefixmap option with the -abspath option to map the absolute file paths to URLs.

See also -prefixmap.

-detectdupfile

Type: File system only

Enables checksum-based detection of duplicates when indexing file systems.

By default, a document checksum is not computed on indexed files. By using the
-detectdupfile option, a checksum is computed based on the CRC-32 algorithm. The checksum combined with the document size is used to determine if the document is a duplicate.

-indexers

Syntax: -indexers num_indexers

Specifies the maximum number of indexing threads to run on a collection.

The default value is 2. Increasing the value for the -indexers option requires additional CPU and memory resources.

See also -maxindmem.

-license

Syntax: -license path_and_filename

Specifies the license file to use.

By default, the ind.lic file is used, from the verity_root/platform/bin directory.; where platform represents the platform directory.

-maxindmem

Syntax: -maxindmem kilobytes

Specifies the maximum amount of memory, in kilobytes, used by each indexing thread. Specify the number of threads with the -indexers option.

By default, each indexing thread uses as much memory as is available from the system.

-maxnumdoc

Syntax: -maxnumdoc num_docs

Specifies the maximum number of documents to download or submit for indexing. The value for num_docs does not necessarily correspond to the number of documents indexed. The following factors affect the actual number:

  • Whether the value of num_docs falls within a block of documents dictated by the
    -submitsize option. If it does, the entire block of documents must be processed.
  • Whether documents retrieved are actually indexed, because they are invalid or corrupt.

-mimemap

Syntax: -mimemap path_and_filename

Specifies a control file (simple ASCII text) that maps file extensions to MIME-types. This lets you make custom associations and override defaults.

The following is the format for the control file:

#file_ext_no_dot											mime-type
abc										 	application/word

-nocache

Type: Web crawling only

Used with the -noindex or -nosubmit options, this option disables the caching of files during website indexing. This has the effect of decreasing the demands on your disk space.

Normally, Verity Spider downloads URLs, then writes them to a bulk insert file and downloads the documents themselves. When indexing occurs, once the -submitsize option has been reached, the cached files are indexed and then deleted. If you use the -noindex option, the bulk insert file is submitted but not processed by Verity Spider, and so the documents are not deleted until indexing occurs. This will usually be mkvdk or collsvc, or you can use Verity Spider again with the -processbif option.

By using the -nocache option in conjunction with the -noindex or -nosubmit option, you avoid storing files locally. Files are downloaded only when indexing actually occurs.

See also -noindex.

-nodupdetect

Type: Web crawling only

Disables checksum-based detection of duplicates when indexing websites. URL-based duplicate detection is still performed.

By default, a document checksum is computed based on the CRC-32 algorithm. The checksum combined with the document size is used to determine if the document is a duplicate.

See also -followdup.

-noindex

Specifies that Verity Spider gathers document locations without indexing them. The document locations are stored in a bulk insert file (BIF), which is then submitted to the collection. This option is typically used in conjunction with a separate indexing process, such as mkvdk or collection servicers (collsvc). The BIF will be processed by the next indexing process run for the collection, whether it is Verity Spider, mkvdk, or collection servicers (collsvc).

Do not try to start Verity Spider and another process at the same time. You must allow Verity Spider time to generate enough work for the secondary indexing process. If you are using mkvdk, you can run it in persistent mode to ensure it will act upon work generated by Verity Spider.

Note: When you execute an indexing job for a collection and you use the -noindex option, the persistent store for the collection is not updated.

See also -nocache and -nosubmit.

For more information on the mkvdk utility, see Using the mkvdk utility.

-nosubmit

Specifies that Verity Spider gathers document locations without submitting them. The document locations are stored in a bulk insert file (BIF), which is not submitted to the collection. This option is typically used in conjunction with a separate indexing process, such as mkvdk or collection servicers (collsvc). You can also use Verity Spider again with the -processbif option. With an indexing process other than Verity Spider, you must specify the name and path for the BIF, because the collection has no record of it.

-persist

Syntax: -persist num_seconds

Enables the Verity Spider to run in persistent mode, checking for updates every num_seconds seconds until it is stopped.

While Verity Spider is running in persistent mode, there is no optimization. After Verity Spider is taken out of persistent mode, you need to perform optimization on the collection. For more information about using the mkvdk utility, see Using the mkvdk utility.

Note: Do not run more than one Verity Spider process in persistent mode. As the Verity Spider is a resource-intensive process, only run it in persistent mode with an interval of less than one day. For time intervals greater than twelve hours, use some form of scheduling. Some examples are cron jobs for UNIX, and the AT command for Windows server.

-preferred

Type: Web crawling only

Syntax: -preferred exp_1 [exp_n] ...

Specifies a list of hosts or domains that are preferred when retrieving documents for viewing. You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters. To use regular expressions, also specify the -regexp option. Use this option when you leave duplicate detection enabled and do not specify the -nodupdetect option.

When indexing, you might encounter a nonpreferred host first. In that case, documents are parsed and followed and stored as candidates. When duplicates are encountered on another server, which is preferred, the duplicate documents from the nonpreferred server are skipped. When documents are requested for viewing, they will be retrieved from the preferred server.

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

See also -regexp.

-prefixmap

Type: File system only

Syntax: -prefixmap path_and_filename

Specifies a control file (simple ASCII text) that maps file system paths to web aliases.

In conjunction with the -abspath option, this option is typically used to create a URL field that is the web equivalent of a file system path. File system indexing is faster than web crawling over the network. If you use the -prefixmap option to replace the file system path with the web URL, relative hyperlinks in the HTML pages are kept intact when returned in Verity search results.

The following is the format for the control file:

src_field src_prefix dest_field dest_prefix

If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

For example, to map the filepath /usr/pub/docs to http://web/~verity, use the following:

vdkvgwkey /usr/pub URL http://web/~verity

See also -abspath.

-processbif

Syntax: -processbif 'command_string !*'

Specifies a command string in which you can call a program or script that operates on BIFs generated by Verity Spider.

Due to the use of special characters, which represent the bulk insert file (BIF), you must run Verity Spider with a command file using the -cmdfile option.

For example, if you want to use a script called fix_bif to add customized information to BIF files, use the following command:

vspider -cmdfile filename

Where filename is the text-only command file that contains the following (along with any other necessary options):

-processbif 'fix_bif !*'

Your command file will include other options as well.

-regexp

Specifies the use of regular expressions rather than the default wildcard expressions for the following options: -exclude, -indexclude, -include, -indinclude, -skip, -indskip, -preferred, and -nofollow.

Wildcard expressions allow the use of the asterisk (*) for text strings, and the question mark (?) for single characters, as the following table shows:

Wildcard expression | Text string
a*t | although, attitude, audit
a?t | ant, art
file?.htm | files.htm, file1.htm, filer.htm
name?.* | names.txt, named.blank, names.ext

Regular expressions allow for more powerful and flexible matching of alphanumeric strings; for example, to match "ab11" or "ab34" but not "abcd" or "ab11cd," you could use the following regular expression:

^ab[0-9][0-9]$

The full extent to which regular expressions can be employed is beyond the scope of this description. For more information on regular expressions, refer to a book devoted to the subject.

-submitsize

Syntax: -submitsize num_documents

Specifies the number of documents submitted for indexing at one time. The default value is 128. The upper limit is 64,000.

Note: Although larger values mean more efficient processing by the indexer, smaller values allow more parallelism on multi-CPU systems. In the event of a halt during indexing, a smaller value means fewer documents will be lost.

If a halt occurs during indexing, the chunk of documents specified by the -submitsize option is lost because there is no transactional rollback for indexing and the documents are no longer in the queue for indexing. When you rerun the indexing task, Verity Spider can only continue with URLs and documents that are enqueued.

-temp

Syntax: -temp path

Specifies the directory for temporary files (disk cache). By default, the temp directory is under the job directory (optionally specified with the -jobpath option).

If you do not specify a value for this option, Verity Spider creates a /spider/temp directory within the collection. For multiple-collection tasks, the first collection specified is used.

Note: Make sure the location you specify contains enough disk space to handle the documents that are downloaded and held before indexing. The documents are deleted from the hard disk after they are indexed.

See also -jobpath, for specifying the location of all indexing job directories and files, one of which is the temp directory.


Networking options

The following sections describe the Verity Spider networking options.

-agentname

Type: Web crawling only

Syntax: -agentname string

Specifies the value for the agent name field that is part of the HTTP request. Since web servers can be configured to return different versions of the same page depending on the requesting agent, you can use the -agentname option to impersonate a browser client.

Use double-quotation marks if the name contains a space. Use the -cmdfile option if the agent name you want to use contains forbidden characters, such as slashes or backslashes.

-connections

Syntax: -connections num_connections

Specifies the maximum number of simultaneous socket connections to make to websites for indexing. Each connection implies a separate thread.

The default value is 6.

Note: The Verity Spider dynamic flow control makes the most use of all available connections when indexing websites. If you are indexing multiple sites, you might want to increase this number. Increasing the number of connections does not always help, because of such dependencies as your network connection and the capabilities of the remote hosts.

-delay

Type: Web crawling only

Syntax: -delay num_milliseconds

Specifies the minimum time between HTTP requests, in milliseconds. The default value is 0 milliseconds for no delay.

-header

Type: Web crawling only

Syntax: -header string

Specifies an HTTP header to add to the spidering request; for example:

-header "Referer: http://www.verity.com/"

Verity Spider sends some predefined headers, such as Accept and User-Agent, by default. Special headers are sometimes necessary to correctly index a site.

For example, earlier versions of Verity Spider did not support the Host header, which is needed for Virtual Host indexing. Also, a Proxy-authentication header was needed to pass a username and password to a proxy server. In the current version of Verity Spider, the Host header is supported by default, and the -proxyauth option is available for proxy server authentication. Therefore, the -header option is maintained only for backwards compatibility and possible future enhancements.

Note: Misuse of this option causes spider failure. If this happens, rerun the indexing task with modified -header values.

-hostcache

Syntax: -hostcache num_hostnames

Specifies the number of host names to cache to avoid DNS lookups. Without this option, the host cache continues to grow.

The default value is 256.

-noflowctrl

Type: Web crawling only

Disables round-robin indexing of websites with network flow control.

By default, Verity Spider uses round-robin indexing of websites to avoid overwhelming a web server and to improve indexing performance. Verity Spider connects to each web server in a round-robin manner, using up to the value for the -connections option. This means that one URL is fetched from each web server, in turn.

Note: Using the -noflowctrl option can result in a significant drop in performance.

-noproxy

Type: Web crawling only

Syntax: -noproxy name_1 [name_n] ...

Used in conjunction with the -proxy option, the -noproxy option specifies that Verity Spider directly access the hosts whose names match those specified. By default, when you specify the
-proxy option, Verity Spider first tries to access every host with the proxy information. To improve performance, use the -noproxy option for the hosts you know can be accessed without a proxy host. For the name variable, you can use the asterisk (*) wildcard for text strings; for example:

'*.verity.com'

You cannot use the question mark (?) wildcard, and the -regexp option does not let you use regular expressions.

In Windows, include double-quotation marks around the argument to protect the asterisk special character (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

Note: You must have valid Verity Spider licensing capability to use this option.

-proxy

Type: Web crawling only

Syntax: -proxy proxyhost:port

Specifies host and port for proxy server.

Note: You must have valid Verity Spider licensing capability to use this option.

See also -proxyauth for proxy servers that require authentication, and -noproxy for hosts that you know are accessible without having to go through a proxy server.

-proxyauth

Type: Web crawling only

Syntax: -proxyauth login:password

Specifies login information for proxy server connections that require authorization to get outside the firewall. Use this option in conjunction with the -proxy option.

Note: You must have valid Verity Spider licensing capability to use this option. Information Server V3.7 does not support retrieving documents for viewing through secure proxy servers. Do not use the -proxyauth option for indexing documents that are viewed through Information Server V3.7

-retry

Type: Web crawling only

Syntax: -retry num_retries

Specifies the number of times that Verity Spider should attempt to access a URL. Use the -retry option when it is likely that an unstable network connection will give false rejections.

The default value is 4.

-timeout

Type: Web crawling only

Syntax: -timeout num_seconds

Specifies the time period, in seconds, that Verity Spider should wait before timing out on a network connection and on accessing data. The data access value is automatically twice the value you specify for the network connection timeout.

The default value for the network connection time-out is 30 seconds, and therefore the default value for the data access time-out is 60 seconds.


Path and URL options

The following sections describe the Verity Spider path and URL options.

-auth

Syntax: -auth path_and_filename

Specifies an authorization file to support authentication for secure paths.

Use the -auth option to specify the authorization file. The file contains one record per line. Each line consists of server, realm, username, and password, separated by whitespace.

The following is a sample authorization file:

# This is the Authorization file for HTTP's Basic Authentication
#server   realm    username      password
doleary   MACR     my_username   my_password

-cgiok

Type: Web crawling only

Lets you index URLs containing query strings. That is, a question mark (?) followed by additional information. This typically means that the URL leads to a CGI or other processing program.

The return document produced by the web server is indexed and parsed for document links, which are followed and in turn indexed and parsed. However, if the web server does not return a page, perhaps because the URL is missing parameters that are required for processing in order to produce a page, nothing happens. There is no page to index and parse.

Example

The following is a URL without parameters:

http://server.com/cgi-bin/program?

If you include parameters in the URL to be indexed, as specified with the -start option, those parameters are processed and any resulting pages are indexed and parsed.

By default, a URL with a question mark (?) is skipped.

-domain

Type: Web crawling only

Syntax: -domain name_1 [name_n] ...

Limits indexing to the specified domain(s). You must use only complete text strings for domains. You cannot use wildcard expressions. URLs not in the specified domain(s) are not downloaded or parsed.

You can list multiple domains by separating each one with a single space.

Note: You must have the appropriate Verity Spider licensing capability to use this option. The Verity Spider that is included with ColdFusion MX is licensed for websites that are defined and reside on the same machine on which ColdFusion MX is installed. Contact Verity Sales for licensing options regarding the use of Verity Spider for external websites.

-followdup

Specifies that Verity Spider follows links within duplicate documents, although only the first instance of any duplicate documents is indexed.

You might find this option useful if you use the same home page on multiple sites. By default, only the first instance of the document is indexed, while subsequent instances are skipped. If you have different secondary documents on the different sites, using the -followdup option lets you get to them for indexing, while still indexing the common home page only once.

-followsymlink

Type: File system only

Specifies that Verity Spider follows symbolic links when indexing UNIX file systems.


-host

Type: Web crawling only

Syntax: -host name_1 [name_n] ...

Limits indexing to the specified host or hosts. You must use only complete text strings for hosts. You cannot use wildcard expressions.

You can list multiple hosts by separating each one with a single space. URLs not on the specified host(s) are not downloaded or parsed.

-https

Type: Web crawling only

Lets you index SSL-enabled websites.

Note: You must have the Verity SSL Option Pack installed to use the -https option. The Verity SSL Option Pack is a Verity Spider add-on available separately from a Verity salesperson.

-jumps

Type: Web crawling only

Syntax: -jumps num_jumps

Specifies the maximum number of levels an indexing job can go from the starting URL. Specify a number between 0 and 254.

The default value is unlimited. If you see extremely large numbers of documents in a collection where you do not expect them, consider experimenting with this option, in conjunction with the Content options, to pare down your collection.

-nodocrobo

Specifies to ignore ROBOT META tag directives.

In HTML 3.0 and earlier, robot directives could only be given as the file robots.txt under the root directory of a website. In HTML 4.0, every document can have robot directives embedded in the META field. Use this option to ignore them. Use this option with discretion.

-nofollow

Type: Web crawling only

Syntax: -nofollow "exp"

Specifies that Verity Spider cannot follow any URLs that match the exp expression. If you do not specify an exp value for the -nofollow option, Verity Spider assumes a value of "*", where no documents are followed.

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters. Always encapsulate the exp values in double-quotation marks to ensure that they are properly interpreted.

If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

To use regular expressions, also specify the -regexp option.

Earlier versions of Verity Spider did not allow the use of an expression. This meant that for each starting point URL, only the first document would be indexed. With the addition of the expression functionality, you can now selectively skip URLs, even within documents.

See also -regexp

-norobo

Type: Web crawling only

Specifies to ignore any robots.txt files encountered. The robots.txt file is used on many websites to specify what parts of the site indexers should avoid. The default is to honor any robots.txt files.

If you are re-indexing a site and the robots.txt file has changed, Verity Spider deletes documents that have been newly disallowed by the robots.txt file.

Use this option with discretion and extreme care, especially in conjunction with the -cgiok option.

See also -nodocrobo.

-pathlen

Syntax: -pathlen num_pathsegments

Limits indexing to the specified number of path segments in the URL or file system path. The path length is determined as follows:

  • The host name and drive letter are not included; for example, neither www.spider.com:80/ nor C:\ would be included in determining the path length.
  • All elements following the host name are included.
  • The actual filename, if present, is included; for example, /world.html would be included in determining the path length.
  • Any directory paths between the host and the actual filename are included.

Example

For the following URL, the path length would be four:

http://www.spider:80/comics/fun/funny/world.html
       <-1->          <2>  <-3-> <---4--->

For the following file system path, the path length would be three:

C:\files\docs\datasheets
    <-1-><-2-><---3--->

The default value is 100 path segments.

-refreshtime

Syntax: -refreshtime timeunits

Specifies not to refresh any documents that have been indexed since the timeunits value began.

The following is the syntax for timeunits:

n day n hour n min n sec

Where n is a positive integer. You must include spaces, and since the first three letters of each time unit are parsed, you can use the singular or plural form of the word.

If you specify the following:

-refreshtime 1 day 6 hours

Only those documents that were last indexed at least 30 hours and 1 second ago, are refreshed.

Note: This option is valid only with the -refresh option. When you use vsdb -recreate, the last indexed date is cleared.

-reparse

Type: Web crawling only

Forces parsing of all HTML documents already in the collection. You must specify a starting point with the -start option when you use the -reparse option.

You can use the -reparse option when you want to include paths and documents that were previously skipped due to exclusion or inclusion criteria. Remember to change the criteria, or there will be little for Verity Spider to do. This can be easy to overlook when you are using the
-cmdfile option.

-unlimited

Specifies that no limits are placed on Verity Spider if neither the -host nor the -domain option is specified. The default is to limit based on the host of the first starting point listed.

-virtualhost

Syntax: -virtualhost name_1 [name_n] ...

Specifies that DNS lookups are avoided for the hosts listed. You must use only complete text strings for hosts. You cannot use wildcard expressions. This lets you index by alias, such as when multiple web servers are running on the same host. You can use regular expressions.

Normally, when Verity Spider resolves host names, it uses DNS lookups to convert the names to canonical names, of which there can be only one per machine. This allows for the detection of duplicate documents, to prevent results from being diluted. In the case of multiple aliased hosts, however, duplication is not a barrier as documents can be referred to by more than one alias and yet remain distinct because of the different alias names.

Example

You can have both marketing.verity.com and sales.verity.com running on the same host. Each alias has a different document root, although document names such as index.htm can occur for both. With the -virtualhost option, both server aliases can be indexed as distinct sites. Without the -virtualhost option, they would both be resolved to the same host name, and only the first document encountered from any duplicate pair would be indexed.

Note: If you are using Netscape Enterprise Server, and you have specified only the host name as a virtual host, Verity Spider will not be able to index the virtual host site. This is because Verity Spider always adds the domain name to the document key.


Content options

The following sections describe the Verity Spider content options.

-casesen

Makes processing case-sensitive by specifying that the spider separately process keys that differ only in case. Use only for indexing UNIX servers.

-exclude

Syntax: -exclude exp_1 [exp_n] ...

Specifies that files, paths, and URLs matching the specified expression(s) will not be followed. If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters; for example:

'/my_doc*/year199?'

In Windows, include double-quotation marks around the argument to protect special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

To use regular expressions, also specify the -regexp option.

To specify a file, path, or URL that you want followed but not indexed, use the -indexclude option. For document types, use the -mimeexclude option instead; for example, specify
-mimeexclude application/pdf rather than -exclude *.pdf.

Note: When specifying a URL, you must use full, absolute paths using the same format that appears in the HTML hyperlink. If the link is relative, you must change it to absolute to use it with the -exclude option.

See also -regexp.

-include

Specifies that only those files, paths, and URLs that match the specified expression or expressions will be followed. If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters; for example:

'/my_doc*/year199?'

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

To use regular expressions, also specify the -regexp option.

If your starting points do not contain the specified -include expressions, nothing will be indexed. The -include option prevents Verity Spider from even following anything that does not match the specified expressions. You might want to use the -indinclude option instead. Where the -include option prevents Verity Spider from even following anything that does not match the specified expressions, the -indinclude option allows Verity Spider to follow what matches the specified expressions, while not indexing.

For document types, use the -mimeinclude option instead; for example, specify -mimeinclude text/html rather than -include *.htm.

Note: When specifying a URL, you must use full, absolute paths using the same format that appears in the HTML hyperlink. If the link is relative, you must change it to absolute to use it with the -include option.

See also -regexp.

-indexclude

Syntax: -indexclude exp_1 [exp_n] ...

Specifies that the files and paths in URLs that match the expressions are not indexed. They are, however, still followed. If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters; for example:

'/my_doc*/year199?'

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

To use regular expressions, also specify the -regexp option.

You would use this option to gather some documents, such as HTML tables of contents, to gain access to other documents for indexing.

Where the -exclude option prevents Verity Spider from even following anything that matches the specified expressions, the -indexclude option allows Verity Spider to follow anything while only skipping that which matches the specified expressions.

For document types, use the -indmimeexclude option instead.

Note: When specifying a URL, you must use full, absolute paths using the same format as appears in the HTML hyperlink. If the link is relative, you must change it to absolute to use it with -indexclude.

See also -regexp.

-indinclude

Syntax: -indinclude exp_1 [exp_n] ...

Specifies that only those files and paths in URLs that match the expressions be followed and indexed. If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters; for example:

'/my_doc*/year199?'

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

To use regular expressions, also specify the -regexp option.

Where the -include option prevents Verity Spider from even following anything that does not match the specified expressions, the -indinclude option allows Verity Spider to follow anything while only indexing that which matches the specified expressions.

Example

If you want to index all documents that include "search" in the URL at http://web.verity.com, you cannot use the following:

vspider -collection collname -start http://web.verity.com
    -include '*search*'

This is because the starting point does not match the -include option criteria. Instead, use the
-indinclude option to follow all documents (unless you have specified any of the exclude options) and index only those documents that match your criteria. Replace the -include option with the -indinclude option in the preceding example.

Note: When specifying a URL, you must use full, absolute paths using the same format that appears in the HTML hyperlink. If the link is relative, you must change it to absolute to use it with the
-indinclude option.

See also -regexp.

-indmimeexclude

Syntax: -indmimeexclude mime_1 [mime_n] ...

Specifies that only those MIME types that match the expressions be followed but not indexed.

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

Use this option to gather some documents, such as HTML tables of contents, to gain access to other documents for indexing. The -mimeexclude option, on the other hand, prevents specified documents from being followed at all. For the mime variable, you can include the asterisk (*) wildcard for text strings; for example:

'text/*'

You cannot use the question mark (?) wildcard, and the -regexp option does not let you use regular expressions.

-indmimeinclude

Syntax: -indmimeinclude mime_1 [mime_n] ...

Specifies that only those MIME types that match the expressions be followed and indexed.

The -mimeinclude option does not let you index desired documents if the starting URL is not followed. For the mime variable, you can include the asterisk (*) wildcard for text strings; for example:

'text/*'

In Windows, include double-quotation marks around the argument to protect the special character (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

You cannot use the question mark (?) wildcard, and the -regexp option does not allow you to use regular expressions.

Example

If you want to index all Word documents at http://web.verity.com, you cannot use:

vspider -collection collname -style style_dir -start
    http://web.verity.com -mimeinclude 'application/msword'

This is because the starting point does not match the -mimeinclude criteria. You can use the -indmimeinclude option to follow all documents (unless you have specified any of the exclude options) and index only those documents that match your criteria. Replace the -mimeinclude option with the -indmimeinclude option in the preceding example.

-indskip

Syntax: -indskip HTML_tag "exp"

Type: Web crawling only

Specifies that Verity Spider follow and parse links, but not index, any HTML document that contains the text of exp within the given HTML_tag. For multiple HTML_tag and exp combinations, use multiple instances of the -skip option.

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters; for example:

'/my_doc*/year199?'

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

To use regular expressions, also specify the -regexp option.

Example 1

To skip all HTML documents that contain the word "personnel" in the Title element, while still parsing those documents for links to other documents, use the following:

-indskip title "personnel"

Example 2

To avoid indexing directory listing pages, while still parsing the document and path links except for the link to the parent directory, use one of the following, depending on the web server being indexed:

  • For Netscape web servers, use the following:
    -indskip title "*Index of*"
-nofollow "*parent directory*"
  • For Microsoft Internet Information Server, use the following:
    -indskip a "*to parent directory*"
-nofollow "*parent directory*"

-maxdocsize

Syntax: -maxdocsize integer

Specifies the maximum size, in kilobytes, for documents to be indexed. Any documents larger than the value specified by the -maxdocsize option are ignored.

The default is to index documents of any size.

-metafile

Type: Web crawling only

Syntax: -metafile path_and_filename

Lets you use a text file to map custom meta tags to valid HTTP header fields. If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

This means that you can use your own meta tag, in the document, to replace what is returned by the web server, or to insert it if nothing is returned. Currently, the only header fields of real value are "Last-Modified" and "Content-Length." Future enhancements could allow for greater variety.

The following is the syntax for entries in the text file:

name Last-Modified y|n

or

name Content-Length y|n

Where y|n is an override flag, which can be yes or no.

Example

A mapping file for the -metafile option might include the following:

Doc_Last_Touched Last-Modified n
Doc_Size Content-Length y

If you use the y override flag, the value for the custom meta tag overrides the value for the valid field, even if both values are present and differ. This can be useful when the valid field value is always sent, but you want to specify your own value with a custom meta tag.

If you use the n override flag, the value for the custom meta tag is used only if there is no value for the valid field returned by the server. If a value for the valid field exists, it is given precedence.

Note: If you have several entries mapping to the same valid field, only the last entry takes effect.

-mimeexclude

Syntax: -mimeexclude mime_1 [mime_n] ...

Specifies MIME types that are neither followed nor indexed.

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

The default is to include all MIME types. For the mime variable, you can include the asterisk (*) wildcard for text strings; for example:

'text/*'

You cannot use the question mark (?) wildcard, and the -regexp option does not let you use regular expressions.

Use the -indmimeexclude option to allow Verity Spider to follow documents, without indexing them, to gain access to other desirable document types.

-mimeinclude

Syntax: -mimeinclude mime_1 [mime_n] ...

Specifies MIME types to be included.

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

The default is to include all MIME types. For the mime variable, you can include the asterisk (*) wildcard for text strings; for example:

'text/*'

You cannot use the question mark (?) wildcard, and the -regexp option does not let you use regular expressions.

-mindocsize

Syntax: -mindocsize integer

Specifies the minimum size, in kilobytes, for documents to be indexed. Any documents smaller than the value specified by the -mindocsize option are ignored.

The default is to index documents of any sizes.

-skip

Type: Web crawling only

Syntax: -skip HTML_tag "exp"

Specifies that Verity Spider not index any HTML document that contains the text of exp within the given HTML_tag. For multiple HTML_tag and exp combinations, use multiple instances of the -skip option.

You can use wildcard expressions, where the asterisk (*) is for text strings and the question mark (?) is for single characters; for example:

'/my_doc*/year199?'

In Windows, include double-quotation marks around the argument to protect the special characters, such as the asterisk (*). On UNIX, use single-quotation marks. This is only required when you run the indexing job from a command line. Quotation marks are not necessary within a command file (the -cmdfile option).

If you use backslashes, you must double them so that they are properly escaped; for example:

C:\\test\\docs\\path

To use regular expressions, also specify the -regexp option.

Example 1

To skip all HTML documents that contain the word "personnel" in the Title element, use the following:

-skip title "personnel"

Example 2

To skip all HTML documents that contain both the word "private" and the phrase "internal user" in any paragraph element, use the following:

-skip title "personnel"
-skip p "*internal use*"

See also -regexp.


Locale options

The following sections describe the Verity Spider locale options.

-charmap

Syntax: -charmap name

Specifies the character map to use. Valid values are 8859 or 850. The default value is 8859.

-common

Specifies the path to the Verity home directory, cf_root/verity/k2/common.

Note: This option is typically not needed, as long as the PATH environment variable is set correctly.

-datefmt

Syntax: -datefmt format

Specifies the Verity import date format to use. Valid values are MDY (the default), DMY, YMD, USA, and EUR. (For descriptions of these values, see Date format options.)

-language

Syntax: -language name

Specifies the Verity locale to use in indexing. This option is being replaced by the semantically consistent the -locale option, and is still supported for backwards compatibility.

-locale

Syntax: -locale name

Specifies the Verity locale to use in indexing, such as German (deutsch) or French (français). The default is English (english). This option is identical to the -language option.

-msgdb

Syntax: -msgdb path

Specifies the path to the ind.msg message database file.

If Verity Spider was installed properly, this option should be unnecessary. By default, the ind.msg message database file is read from the following directory:

cf_root/lib/platform/bin

Where platform represents the platform directory.


Logging options

The following sections describe the Verity Spider logging options.

-loglevel

Syntax: -loglevel [nostdout] argument

Specifies the types of messages to log. By default, messages are written to standard output and to various log files in the subdirectory named /log beneath the Verity Spider job directory. If you add nostdout to the -loglevel option, messages are not written to standard output. Log files, however, are still created.

The following table describes valid message types:

Message type | Description
information | Licensing information written to info.log. Included with all arguments.
warning | Warning messages written to warning.log. Included with all arguments.
error | Error messages written to error.log. Included with all arguments.
badkey | Messages regarding keys that could not be indexed due to invalid documents, written to badkey.log. Included with all arguments.
progress | Current state of a document key written to progress.log. Note that a key with a progress of "inserting" might be a badkey and therefore skipped, rather than an indexed key. Included with all arguments.
summary | Inserted, indexed, and ignored messages written to summary.log. Included with all arguments except skip.
skip | Skipped documents, with explanation, written to skip.log. Included with all arguments, except summary.
debug | Internal Verity Spider processing messages, such as enqueued, written to debug.log. Included with both debug and trace arguments.
trace | Internal Verity Spider processing messages written to debug.log. Included only with the trace argument.

Choose one of the following arguments to determine which message types are logged:

Loglevel arguments | Description
summary | Includes the following message types: information, warning, error, badkey, progress, summary Use this option only if you do not want skip type messages.
skip | Includes the following message types: information, warning, error, badkey, progress, skip Use this option only if you do not want summary type messages.
verbose | Includes the following message types: information, warning, error, badkey, progress, summary, skip
debug | Includes the following message types: information, warning, error, badkey, progress, summary, skip, debug Note: Only use this argument at the direction of Verity technical support or for troubleshooting indexing problems.
trace | Includes the following message types: information, warning, error, badkey, progress, summary, skip, debug, trace Note: Only use this argument at the direction of Verity technical support or for troubleshooting indexing problems.


Maintenance options

The following sections describe the Verity Spider maintenance options.

-nooptimize

Prevents Verity Spider from optimizing the collection, thus reducing processing overhead during indexing. Use this option sparingly, as it leaves the collection in less than optimum shape. The following are some examples of when you might want to use this option:

  • You want to manually perform custom optimization of the collection, using the mkvdk utility. By default, the Verity Spider optimization mimics the mkvdk actions of maxmerge and vdbopt. For more information on the mkvdk utility, see Verity Command-Line Indexing Reference and Using the mkvdk utility.
  • You are running multiple indexing jobs against a collection, and want to wait until they are all finished to optimize.

Generally, you should not leave a collection unoptimized for too long, as search times can slow significantly.

In brief, optimizing a collection means creating a small number of large partitions, which can greatly reduce search times.

-purge

Deletes document tables and index files in the collection, and cleans up the collection's persistent store. The collection is then fresh with its original style files, and is not deleted from the file system.

-repair

Specifies a failure-recovery mode for the collection, where the goal is to determine the causes of any errors, repair the errors (if possible), and restart a collection.

Although the Verity indexing engine always leaves the collection in a consistent, usable state, and no data can be lost or corrupted due to machine failures, it is possible for a process or event external to the Verity engine to corrupt one or more collections.

You can use the -repair option for constant failure-recovery operation, or you can run it selectively on collections that failed.


Setting MIME types

You can use the MIME type criteria options, -mimeinclude, -indmimeinclude, -mimeexclude, and -indmimeexclude, to include or exclude MIME types.

This section describes the following topics:

  • Syntax restrictions
  • MIME types and web crawling
  • Indexing unknown MIME types
  • Known MIME types for file system indexing

Syntax restrictions

When you specify MIME type criteria, keep in mind the restrictions described in the following sections.

Using the wildcard character (*)

The asterisk (*) wildcard character does not operate as a regular expression for the value of the MIME type criteria. Instead, you can only use it to replace the entire MIME type or MIME sub-type.

For example, the following value is a valid substitute for text/html:

text/*

The following value is NOT a valid substitute for text/html:

text/h*

Multiple parameter values

When you specify a series of parameter values for a single instance of one of the MIME type criteria, and you use-quotation marks, you must enclose each separate parameter value in single-quotation marks. For example:

-mimeinclude ’text/plain’ ’application/*’

If you enclose the entire sequence of parameter values, as follows:

-mimeinclude ’text/plain application/*’

Verity Spider considers the entire expression a single value.

You can also use multiple instances of the MIME type criteria, each with a single parameter value, where quotation marks are necessary only if you use the wildcard character (*). For example:

-mimeinclude text/plain
-mimeinclude ’application/*’.Setting MIME Types


MIME types and web crawling

When you index a website, Verity Spider evaluates your MIME type criteria against the "Content-Type" HTTP headers sent by the web server hosting that website. That web server passes along MIME type information based on its own internal tables.

When you encounter MIME types being dropped, make sure that the web server you are indexing has the necessary MIME type information. For information about specifying MIME types, see the documentation for your web server.

You can examine the indexing job’s log files for indications that files are being skipped due to MIME types. For example, a typical ASCII file you might want indexed is a log file (filename.log). Unless the web server understands that files with .LOG extensions are ASCII text, of MIME type text/plain, you will see in the indexing job log file that .LOG files are skipped because of MIME type, even if you use the following:

-mimeinclude ’text/*’


MIME types and file system indexing

When you index a file system, Verity Spider reads filenames and evaluates your MIME type criteria against an internal, compiled list of known MIME types and associated file extensions. You cannot edit this list. However, you can use the -mimemap option to create a custom MIME type mapping.

When you encounter MIME types being dropped, check whether Verity Spider recognizes that particular MIME type. For more information, see the table, Known MIME types for file system indexing.

You can examine the indexing job’s log files for indications that files are being skipped due to MIME types. For example, a typical ASCII file you might want indexed is a log file (filename.log). Since Verity Spider does not understand that files with .LOG extensions are ASCII text, of MIME type text/plain, you will see in the indexing job log file that .LOG files are skipped because of MIME type, even if you use the following:

-mimeinclude ’text/*’.Setting MIME Types

Indexing unknown MIME types

Whenever you find MIME types being dropped, or you know you will be indexing files whose extensions are not known to Verity Spider by default, use the -mimemap option to point to a file that contains your own custom mappings for file extensions and MIME types.

You can also use the regular expression ’*/*’ for your MIME type criteria; for example:

-mimeinclude ’*/*’

On either platform, you must include single-quotation marks for values that include wildcard characters.

Also use inclusion and exclusion criteria to finely control what is indexed, as follows:

  • If your list of file types to index is rather long, use exclusion criteria (-exclude, -indexclude, -mimeexclude, or -indmimeexclude) to exclude extensions you know you do not want to index; for example:
    -exclude ’*.exe’ ’*.com’
  • If the list of file types you want to index is relatively small, use inclusion criteria (-include, -indinclude, -mimeinclude, or -indmimeinclude) to specify them; for example:
    -include ’*.txt’ ’*.1st’ ’*.log’.Setting MIME Types

Known MIME types for file system indexing

The following table lists the MIME types that Verity Spider recognizes when indexing file systems:

Format | MIME type | Extension
HTML | text/html | htm, html
ASCII | text/plain | txt, text, pl, eml
ASCII, source files | text/plain | c, h, cpp, cxx
PDF | application/pdf | pdf
MS Word | application/msword | doc
MS Excel | application/vnd.ms-excel | xls
MS PowerPoint | application/vnd.ms-powerpoint | ppt
WordPerfect 5.1 | application/wordperfect5.1 | wpd
RTF | application/rtf | rtf
FrameMaker MIF | application/vnd.mif | mif
Applixware | application/applixware | aw
Zip files | application/zip | zip
Eudora mail | text/x-mbox | mbx
Previous


Using Verity Utilities

This chapter provides information about using Verity utilities to configure, maintain, and troubleshoot Verity collections.

Contents

Overview of Verity utilities

Using the mkvdk utility

Using the rck2 utility

Using the rcvdk utility

Using the didump utility

Using the browse utility

Using the merge utility
Next


Overview of Verity utilities

The following command-line utilities are included with Macromedia ColdFusion MX for performing a variety of operations on Verity collections:

Verity utility | Description | For more information
mkvdk | Create and maintain collections. | See Using the mkvdk utility.
rck2 | Search K2 Server collections. | See Using the rck2 utility.
rcvdk | Search collections and display documents. | See Using the rcvdk utility.
didump | View collection word lists. | See Using the didump utility.
browse | Browse documents table and search results. | See Using the browse utility.
merge | Combine collections. | See Using the merge utility.

Location of Verity utilities

The Verity command-line utilities are located in the following directories:

Server and multiserver configuration The utility files are located in cf_root/verity/k2/platform/bin (server configuration) or jrun_root/verity/k2/platform/bin (multiserver configuration), where platform is _nti40 for Windows, _solaris for Solaris, or _ilnx21 for Linux.

J2EE configuration The utility files are located in verity_root/k2/platform/bin, where platform is _nti40 for Windows, _solaris for Solaris, or _ilnx21 for Linux.


Using the mkvdk utility

The mkvdk utility is an indexing application, provided with other Verity utilities, that you can use to create and maintain collections. It is a command-line utility that you can use within other applications or shell scripts to provide more sophisticated scheduling and other capabilities.

The mkvdk executable file, which starts the mkvdk utility, is located in the platform/bin directory. For more information on the specific location of this directory, see Location of Verity utilities.

Note: To display a list of mkvdk command-line options, enter the following command:

mkvdk -help

This section describes the following topics:

  • The mkvdk utility syntax
  • Getting started with the Verity mkvdk utility
  • Collection setup options
  • General processing options
  • Date format options
  • Service-level keyword options
  • Message options
  • Document processing options
  • Bulk submit options
  • Collection maintenance options
  • Performance tuning options


The mkvdk utility syntax

The following is the basic syntax of the mkvdk command:

mkvdk -collection path [option] [dockey]

Multiple options and dockeys can be included, as needed. If dockey is a list of files, it should consist of an at sign (@) followed by the filename that contains a simple list of files (for example, @filelist). For more information about the options for the mkvdk utility, see Getting started with the Verity mkvdk utility.

The following operations occur when you use the mkvdk utility to create a new collection:

  1. New collection directories are created and the specified style files are copied to the style subdirectory.
  2. The style file settings are read and the required information is passed to the Verity search engine.
  3. The gateway is used to open the document files, which are parsed according to the settings in various style files.
  4. A new partition is created, which includes an index and an attribute table.
  5. Assist data is generated, which might include a spanning word list.

When problems occur during an operation, the mkvdk utility writes error messages to the system log file (sysinfo.log). You can direct error and other messages to the console by using the mkvdk command with the -outlevel option. You can direct messages to a file of your choice by using the -loglevel and -logfile options.

The log file contains the following fields:

  • Date
  • Time
  • Level
  • Code
  • Component
  • Description

You can use the log file to view details about what happens during the collection creation process. Use the mkvdk -loglevel command and specify the numeric identifier for the message level you want, as summarized in the following table:

Type | Number
Fatal | 1
Error | 2
Warning | 4
Status | 8
Info | 16
Verbose | 32
Debug | 64

To calculate the numeric parameter, add the numbers for the message types you want to include. The default for both -outlevel and -loglevel is 15, which selects fatal, error, warning, and status messages (1+2+4+8).


Getting started with the Verity mkvdk utility

The following is the basic mkvdk syntax:

mkvdk -collection path [option] [...] [filespec] [...]

Where:

  • Square brackets ( [ ] ) indicate optional items.
  • An ellipsis (...) indicates repetition of the previous item. Thus, [filespec] [...] indicates an optional series of filespec items.
  • filespec represents a document filename or a list of document filenames. If filespec is a list of files, it should consist of an at sign (@) followed by the filename containing the list (for example, @filelist).
  • The -collection path argument creates or opens a collection. This argument is required.

Numerous optional syntax options are listed below. All syntax options must precede the first filespec parameter.

Creating a collection

Creating a collection with the mkvdk utility involves setting up a collection directory structure and inserting documents into this structure. You can create a collection using the following steps.

To create a collection:

  1. Set up a collection using the following syntax:
    mkvdk -create -collection collectionname

    Where collectionname is the path to the collection directory. Running this command creates a collection directory that includes style files with configuration information.

  2. Insert documents using the following syntax:
    mkvdk -collection collectionname -bulk -insert filespec

    Where filespec is the name of a bulk insert file that specifies which documents to index and insert into the collection.


Collection setup options

The mkvdk utility has a variety of collection setup options, which the following table describes:

Option

Description

-create

Creates a collection in the specified collection directory. It creates the directory structure, determines the index contents and sets up the document’s table schema according to the style files used. If the specified collection already exists, the mkvdk utility exits rather than overwriting the existing collection.

-style dir

Specifies the style directory that contains the style files to use to create a collection. This option can only be used with the -create option. If you do not specify this option when you use the mkvdk utility to create a collection, the mkvdk utility uses the style files in the common/style directory.

-description desc

Sets the collection’s description. Enter alphanumeric text, such as "This collection contains electronic mail from ABC Company." Include the quotation marks.

-words

Builds the word list for all partitions in the collection.

Examples: setting up collections

The following examples show the commands for creating a collection and building the word list:

Creating a collection The following command creates a collection in path_2 using the style files in path_1, and submits and indexes the document(s) in filespec:

mkvdk -create -style path_1 -collection path_2 filespec

Building the word list The following command builds the word list in the collection residing in the path directory:

mkvdk -words -collection path


General processing options

The mkvdk utility provides a variety of general processing options, which the following table describes:

Option

Description

-collection path

Specifies the path of the collection to create or open. This option is required to execute the mkvdk utility.

-nolock

Turns off file locking. Locking is on by default.

-synch

Performs work immediately. If this option is not used, indexing work is done in the background, as time permits.

-about

Shows information about the collection, such as its description and the date when it was last modified.

-datapath path

Specifies the datapath to use to find documents that are added to the specified collection. All relative document paths are relative to this setting. If you do not set this option, the mkvdk utility looks for documents next to the collection directory.

-topicset path

Creates a topic index for the collection, based on the specified topic set, and stores it in the collection directory. This facilitates quick and efficient searches over the collection data when using topics.

-mode mode

Sets the indexing mode. Values are case-insensitive. The following are the valid settings:

  • Generic
  • FastSearch
  • NewsfeedIdx
  • NewsfeedOpt
  • BulkLoad
  • ReadOnly
  • Any custom mode defined in the style.plc file.

The default is Generic mode.

-common

Specifies the path of the Verity common directory. If you do not use this option, the Verity engine looks for the common directory in the directory containing the mkvdk executable, and then along the executable search path. The executable search path is determined by your operating system environment settings. It is the path used by the OS to find the programs you run.

-help

Displays the mkvdk utility syntax options.

-debug

Runs the mkvdk command in debugging mode.

-nooptimize

Prevents optimization by this instance of the mkvdk utility. Using this option turns off the service-level VdkServiceType_Optimize. The service types determine the type of work the Verity engine and its self-administration features will execute on a collection.

-nohousekeep

Prevents housekeeping by this instance of the mkvdk utility. Housekeeping includes deleting files that are no longer needed. Using this option turns off the service-level VdkServiceType_DBA. (Service types are described under
-nooptimize.)

-noindex

Prevents indexing by this instance of mkvdk. Documents are not inserted or deleted. Using this option turns off the service-level VdkServiceType_Index. (Service types are described under -nooptimize.)

-charmap name

Specifies the name of the character set to which to map all strings for your application. Set this to a character set that your system can display properly. Using the search engine with the English locale, the character set that any version of Windows displays is 8859. This is NOT the name of the character set of documents being indexed, it is only the name of the character set that your display can handle properly. (The character set of the document is set in the style.dft file using the /charmap option.)

Valid options are 850 and 8859. The default is no mapping.

-locale name

Specifies the name of the Verity locale to be used by the mkvdk utility. The locale name must correspond to the name of an existing locale directory, which must exist in the install_dir/common/locale directory. Valid options are english, deutsch, and francais. The default is english.

-datefmt format

Converts a date field value into Verity’s internal data representation. You can use this option in conjunction with the mkvdk options -extract (for the field extraction feature) and -bulk (for the bulk submit feature). The named format string identifies to the date parsing routines in what order dates are written when the date string only consists of a sequence of numbers (for example, 03/03/96). Valid options are described in Date format options. The default is MDY.

-servlev level

Specifies service level. The specifier, level, is a string consisting of keywords separated by hyphens, such as search-index-optimize. Valid keywords are described in Service-level keyword options.

Examples: processing documents

The following examples show the commands for processing documents.

Using the default options

By default, the mkvdk command submits and indexes documents specified in the command, and services the specified collection. The following command executes the default options:

mkvdk -collection path filespec

Servicing only

The following command performs servicing only. Use this command to only index submitted documents and service the collection:

mkvdk -collection path

Deleting documents from a collection

The following command deletes documents from a collection:

mkvdk -delete -collection path filespec

Bulk inserting or deleting

The following command specifies bulk insertion of a list of documents:

mkvdk -collection coll -bulk -insert filespec

Where filespec is the list of files to insert. Since insert is the default, the following command is equivalent to the preceding command:

mkvdk -collection coll -bulk filespec

The following command specifies bulk deletion of a list of documents:

mkvdk -collection coll -bulk -delete filespec

Where filespec is the list of files to delete. It can be the same file used to insert documents; the only difference is that -delete is specified instead of -insert (or no specification).


Date format options

The Verity engine supports many import date formats, including many textual date formats, and the numeric date formats listed in the following table:

Format variable | Description
MDY | Dates written as month-day-year (US format, the default)
DMY | Dates written as day-month-year (European format)
YMD | Dates written as year-month-day (ISO international format)
YDM | Dates written as year-day-month (Swedish format)
USA | Dates written in US format (the same as MDY)
EUR | Dates written in European format (the same as DMY)


Service-level keyword options

The following table describes the valid keywords for the -servlev keyword:

Keyword | Description
search | Enables search and retrieval
insert | Enables adding and updating documents
optimize | Enables opportunistic collection optimization
assist | Enables building of word list
housekeep | Enables housekeeping of unneeded files
delete | Enables document deletion
backup | Enables backup
purge | Enables background purging
repair | Enables collection repair
dataprep | Same as search-index-optimize-assist-housekeep
index | Same as insert-delete


Message options

The mkvdk utility provides a variety of messaging options, as described in the following table:

Option

Description

-quiet

Displays only fatal and error messages to the console. It overrides the
-outlevel setting. For a list of message types, see the table in The mkvdk utility syntax.

-outlevel (num)

Indicates which message types to display to the console. Valid values are determined by adding together the numbers that correspond to the desired message types. The default value is 15. For more information, see the table in The mkvdk utility syntax.

-logfile filename

Saves messages in the specified file.

-loglevel (num)

Indicates which message types to route to the optional log file. Valid values are determined by adding numbers together that correspond to the desired message types. The default value is 15. For more information, see the table in The mkvdk utility syntax.


Document processing options

The mkvdk utility provides a variety of document processing options, as the following table describes:

Option

Description

-extract

Extracts field values from documents, using the field extraction rules specified in the style.tde file.

-insert

Adds documents to the collection. This is the default option for the mkvdk command.

-update

Adds documents to the collection by replacing all previous information about the specified documents.

-delete

Marks the specified documents as deleted, and makes them unavailable for searches. To actually remove deleted documents from the collection’s internal documents table and word indexes, use the squeeze keyword (see About squeezing deleted documents).

-nosave

Specifies that a work list, which is generated by the mkvdk utility automatically when you use the -extract option, will not be saved in the collection directory in a file called worklist (in the Verity bulk submit file format). By default, the mkvdk utility saves the worklist in the worklist file.

-nosubmit

Specifies that a work list, which is generated by the mkvdk utility automatically when you use the -extract option, will not be submitted to the indexing engine and will be saved in the collection directory in a file called worklist (in the Verity bulk submit file format). This option allows the mkvdk utility to process field extraction separately from other indexing tasks.


Bulk submit options

The mkvdk utility provides a variety of bulk submit options, as described in the following table:

Option

Description

-bulk

Interprets filespec as a bulk submit file. You can use this option with the -insert, -update, and -delete options.

-offset num

Specifies the offset into a bulk submit file or files. If you specify multiple bulk submit files and use the -offset option, the offset is applied to all of the bulk submit files.

-numdocs num

Specifies the number of documents to insert or delete from the bulk insert file or files. If you specify multiple bulk insert or delete files and use the -numdocs option, the -numdocs setting is applied to all of the bulk insert or delete files.

-autodel

Deletes the bulk submit file or files when the bulk submission work is finished.

Using bulk insert and delete options

The bulk submit feature supports the insertion of documents and related field values into collections.

To use the bulk submit feature to populate fields:

  1. Define the fields in the style.sfl and style.ufl file, as appropriate.
  2. Create a bulk submit file that specifies the documents to insert and the field values for each document.
  3. Run the mkvdk utility using the -bulk option and specifying the bulk submit file or files.


Collection maintenance options

The mkvdk utility provides a variety of collection maintenance options, as described in the following table:

Option

Description

-backup dir

Backs up the collection into the specified directory. The backup does not include the tde subdirectory. The tde subdirectory is created by and for Topic Document Entry if Topic Document Entry is used to create or maintain the collection.

-repair

Repairs the collection, performed by an API call.

-purge

Waits the amount of time specified by the -purgewait option and then deletes all documents in the collection, but not the collection itself. It leaves the collection directory structure intact.

To specify a different wait period, use the -purgewait option instead of the
-purge option. If you do not use the -purgewait option, the default is 600 seconds.

-purgeback

Used with the -purge option, performs a purge in the background.

-purgewait sec

Specifies to the -purge option how many seconds to wait. If you do not specify sec, the default is 600.

-noservice

Prevents collection servicing, which includes indexing, by this instance of the mkvdk command, performed by an API call.

-persist

Services the collection repeatedly, at default intervals of 30 seconds. Use the
-sleeptime option to set a different interval.

-sleeptime sec

Specifies the interval between service calls when the mkvdk utility is run with the -persist option.

-optimize spec

Performs various optimizations on the collection, depending on the value of spec. The specifier, spec, is a string consisting of keywords separated by hyphens, such as maxmerge-squeeze-readonly. For valid keywords, see Optimization keywords.

-noexit

Windows only. Causes the I/O window to remain after the program is finished. By default, the window closes and the program exits, so that scripts calling the mkvdk utility do not hang.

Examples: maintaining collections

The following examples show the commands for maintaining a collection.

Repairing a collection

The following command automatically repairs a collection, or enables it after manual repairs:

mkvdk -repair -collection path

Backing up a collection

The following command backs up a collection to the specified directory:

mkvdk -backup path_1 -collection path_2

Deleting a collection

To delete a collection, use the appropriate command for your operating system. For example, to remove the collection directory structure and control files on a UNIX system, use the following command:

rm -r -collection_path

Purging a collection

The following command deletes all documents from a collection, but does not delete the collection itself:

mkvdk -purge -collection path

Purging a collection in the background

The following command purges the specified collection in the background:

mkvdk -purge -purgeback -collection path

Specifying persistent service

The following command runs the mkvdk command as a persistent process, so that servicing is performed repeatedly after num idle seconds:

mkvdk -persist -sleeptime num -collection path

Deleting a collection

The -purge option deletes all documents in a collection, but does not delete the collection itself. To delete a collection, use operating system commands, such as the rm command on UNIX, to remove the collection directory structure and control files.

Optimization keywords

The following table describes the optimization keywords for the -optimize option:

Keyword

Description

maxclean

Performs the most comprehensive housekeeping possible, and removes out-of-date collection files. Macromedia recommends this optimization only when you are preparing an isolated collection for publication. When using this type, if the collection is being searched, files sometimes get deleted too early, which can affect search results.

maxmerge

Performs maximal merging on the partitions to create partitions that are as large as possible. This creates partitions that can have up to 64000 documents in them.

readonly

Marks the collection as read-only and unchanged after the function call is done. This is appropriate for CD-ROM collections.

spanword

Creates a spanning word list across all the collection’s partitions. A collection consists of numerous smaller units, called partitions, each of which includes a word list. Optionally, a spanning word list can be built with an ngram index.

ngramindex

Builds an ngram index for the collection. An ngram index is designed to improve the search performance for queries with the <TYPO> and <WILDCARD> operators. An ngram index cannot be built without a spanning word list. You can build a spanning word list and ngram index in the same command, for example:

mkvdk -collection collname -optimize spanword -ngramindex

squeeze

Squeezes deleted documents from the collection. Squeezing deleted documents recovers space in a collection, and improves search performance. (For more information about squeeze, see About squeezing deleted documents.) Using this option invalidates the search results.

vdbopt

Configures the collection’s Verity databases (VDBs). Each collection consists of smaller units called VDBs. This keyword has the effect of linearizing the data in a VDB, and making the collection metadata contained in the VDB more streamlined. It also lets the VDB grow to a much larger size.

tuneup

Performs the same as combining the maxmerge, vdbopt, and spanword keywords.

publish

Performs the same as all of the optimization types combined. Use this keyword to optimize the collection for the best possible retrieval performance, such as for publication to a network on a server or on a CD-ROM.

About squeezing deleted documents

When a document is deleted from a collection, its space is not recovered. It is merely marked as deleted and not available for subsequent searches. Squeezing actually removes deleted documents from the collection’s internal documents table and word indexes, thus creating a smaller collection and reducing the collection’s disk space. A smaller collection has a more efficient structure that makes searching slightly faster and uses slightly less memory.

You can safely squeeze deleted documents for a collection at anytime, because the mkvdk utility ensures that the collection is available for searching and servicing through its self-administration features. The application does not need to temporarily disable a collection to squeeze deleted documents, because when a squeeze request is made, the mkvdk utility assigns a new revision code to the collection. After a squeeze has occurred, the next time the application accesses the collection, the Verity engine notifies the application that dramatic changes have been made, and points the application to the new collection data.

Squeezing deleted documents out of a collection is a significant update to the collection. If users are reviewing search results at the time when squeezing occurs, the search results might be invalidated after the squeeze operation.

About optimized Verity databases

The Verity database (VDB) is the fundamental storage mechanism responsible for supporting dynamic access to documents in collections. A VDB consists of simple tables with rows and columns that relate to each other by row position. VDB tables are not relational, and their architecture supports quick and efficient searching over textual data. A VDB consists of segments that are packed into a single file. One of the advantages of having one packed VDB file is optimized search performance. The fewer files that need to be opened during search processing, the faster the search performance.

The VDB optimization option optimizes the packing of a collection’s VDBs. When VDBs are built during normal indexing operations, the segments are not stored sequentially in the one-file VDB file system. As a result of VDB optimization, performance can be improved by reserializing the packed segments in the VDBs so that all segments are contiguous, and VDBs can grow in size. Optimized VDBs can grow up to 2 gigabytes in size, as opposed to the maximum 64 megabytes for an unoptimized one.

Using this option might degrade your indexing performance when certain indexing modes are set for the collection.


Performance tuning options

The mkvdk utility provides performance tuning options, as the following table describes:

Option

Description

-maxfiles num

Sets the maximum number of files that the mkvdk utility can have open at once. The default is 50.

-diskcache num

Sets the size of the mkvdk disk cache in kilobytes. The default is 128.


Using the rck2 utility

The rck2 command-line utility lets you search collections associated with a Verity server. The rck2 executable file, which starts the rck2 utility, is located in the platform/bin directory. For more information on the specific location of this directory, see Location of Verity utilities.

This section describes the following topics:

  • The rck2 syntax
  • The rck2 command options

The rck2 syntax

Use the following syntax to start rck2 from the command line:

rck2 -server <servername> -port <portno>

For example:

c:\cfusionmx7\verity\k2\_nti40\bin\rck2 -server localhost -port 9901.

The following table describes rck2 syntax elements:

Syntax element

Description

-server <servername>

The server name for K2 Server to which to attach. The server name is defined in the k2server.ini file. The rck2 utility searches the collections attached to this server.

-port <portno>

The port number where K2 Server (specified by -server) is running.

The rck2 command options

The following table describes rck2 command options:

rck2 command

Description

p <sortspec>

The sort specification for the search results. By default, results are sorted by Score. Multiple fields must be specified in a space-separated list using asc or desc to indicate ascending or descending order. For example: p score desc title asc

m <maxdocs>

The maximum number of documents to return in the results list.

c <collections>

The list of collections to search. Multiple collections must be specified in a space-separated list. For example: c coll1 coll2 coll3

f <fields>

The list of fields to retrieve. For example: f k2dockey title date

s <query text>

The query (or question) to be used to process the search. The query can be expressed as words and phrases separated by commas. Additionally, the query can include Verity query language, operators and modifiers.

g <collection>

Display collection information.

d <k2dockey>

Display fields for the K2 document key specified.

v <k2dockey>

Stream the document and display it with highlights.

r <docstart>

Display results starting with the first result in the results list. Fields specified using the f command are displayed. Docstart indicates the first result to be displayed. For example, r 10 displays results starting with the 10th document in the results list.

b <docstart>

Display results based on the last field selection.

i

Display information about K2 Server, including nodes and collections.

x <score precision>

Set score precision to 8- or 16-bit. By default, 16-bit precision is used.

h or ?

Display online Help for the rck2 command options.


Using the rcvdk utility

Using the Verity rcvdk utility, you can check the contents of a collection from the command line. The rcvdk utility lets you write a variety of queries, using words and phrases separated by commas and Verity query language. A viewing option lets you see document contents and highlights in a simple text display.

This section describes the following topics:

  • Starting rcvdk
  • Attaching to a collection using the rcvdk utility
  • Viewing results of the rcvdk utility


Starting rcvdk

To start the rcvdk utility on most systems, type the path and executable name at a command prompt. The following examples assume you have set your PATH variable, so you just have to enter rcvdk at a command prompt to run it.

For example:

c:\cfusionmx7\verity\k2\_nti40\bin\rcvdk /common = c:\cfusionmx7\verity\k2\common

When you start the rcvdk utility with no arguments, you get the following message, followed by the rcvdk prompt:

Type 'help' for a list of commands.
RC>

The help command produces the following list of available commands:

RC> help
Available commands:
search     s Search documents.
results    r Display search results.
clusters   c Display clustered search results.
view       v View document.
summarize  z Summarize documents.
attach     a Attach to one or more collections.
detach     d Detach from one or more collections.
quit       q Leave application.
about      Display VDK 'About' info
help       ? Display help text; 'help help' for details.
expert     x Toggle expert mode on/off.
RC>

You can enter the letter q at the RC prompt at any time to quit the application.


Attaching to a collection using the rcvdk utility

To search a collection, you first must attach to it using the attach (a) command. This command must include the pathname to a collection directory as an argument. After you press Return, the rcvdk utility reports whether the attach command was successful; for example:

RC>a /z/doc1/c/public/Collection/file_walking/collbldg/html
Attaching to collection:
/z/doc1/c/public/Collection/file_walking/collbldg/html
Successfully attached to 1 collection.
RC>

The rcvdk utility lets you attach to one or more collections. The specified collections remain attached until you detach from one or more collections using the detach (d) command.

Basic searching

To retrieve all documents, use the search (s) command without arguments. After you press Return, a search update message is produced, as follows:

RC>s
Search update: finished (100%). Retrieved: 85(85)/85.
RC>

The search results indicate that 85 of the total 85 documents in the collection were retrieved. If you specify a query argument, such as "universal filter," a subset of the total documents in the collection that contain the specified string is retrieved; for example:

RC>s universal filter
Search update: finished (100%). Retrieved: 18(18)/85.
RC>

In the message returned for the preceding search, the rcvdk utility indicates that 18 documents matched the query. You can perform more elaborate queries using the Verity query language, as shown in the following example:

RC>s universal filter <OR> filter.Troubleshooting and Maintenance Tools


Viewing results of the rcvdk utility

After you have attached to a collection and issued a search command successfully, you can view the results list and look at the retrieved documents. You can use the options in the following table:

Option | Description
r | Displays the results list, starting with the first document. A maximum of 24 documents are displayed.
r n | Displays the results list, starting with the nth document. A maximum of 24 documents are displayed.
v | Displays the first or next document in the results list. Highlights are indicated using reverse video, if possible. If not, double angle brackets are used, as in: >>universal<< >>filter<< To exit the document display, enter the letter q.
v n | Displays the nth document in the results list. To exit the document display, enter the letter q.

The following is the results list for the "universal filter" search. For each document, these fields are displayed by default: Number, Score, and VdkVgwKey.

RC> r
Retrieved: 18(18)/85
Number SCORE VdkVgwKey
1: 1.00 d:\search97\s97is\locale\english\doc\collbldg\08_cbg3.htm
2: 0.97 d:\search97\s97is\locale\english\doc\collbldg\11_cbg2.htm
3: 0.97 d:\search97\s97is\locale\english\doc\collbldg\08_cbg7.htm
4: 0.97 d:\search97\s97is\locale\english\doc\collbldg\08_cbg1.htm
5: 0.95 d:\search97\s97is\locale\english\doc\collbldg\cbgtoc.htm
6: 0.95 d:\search97\s97is\locale\english\doc\collbldg\08_cbg4.htm
7: 0.93 d:\search97\s97is\locale\english\doc\collbldg\cbgix.htm
8: 0.92 d:\search97\s97is\locale\english\doc\collbldg\08_cbg6.htm
9: 0.90 d:\search97\s97is\locale\english\doc\collbldg\08_cbg.htm
10: 0.90 d:\search97\s97is\locale\english\doc\collbldg\04_cbg1.htm
11: 0.90 d:\search97\s97is\locale\english\doc\collbldg\01_cbg1.htm
12: 0.87 d:\search97\s97is\locale\english\doc\collbldg\f_cbg.htm
13: 0.87 d:\search97\s97is\locale\english\doc\collbldg\08_cbg2.htm
14: 0.84 d:\search97\s97is\locale\english\doc\collbldg\06_cbg1.htm
15: 0.80 d:\search97\s97is\locale\english\doc\collbldg\part4.htm
16: 0.80 d:\search97\s97is\locale\english\doc\collbldg\f_cbg1.htm
17: 0.80 d:\search97\s97is\locale\english\doc\collbldg\11_cbg5.htm
18: 0.80 d:\search97\s97is\locale\english\doc\collbldg\08_cbg5.htm
RC>

The following table describes each of the default fields:

Field name | Description
Number | The rank of the document in the results list. The document with the highest score is ranked number 1.
Score | The score assigned to each retrieved document, based on its relevance to the query. For a NULL query, no scores are assigned, so the Score column in the results list is blank.
VdkVgwKey | The document key used by the Verity engine to manage the document. If the document is accessed through the file system, the primary key is a pathname. If the document is accessed through a web server, using HTTP, the primary key is a URL.

Displaying more fields

You can tell the rcvdk utility to display certain fields in the results list using the fields command, which is available in the expert mode. To go to the expert mode, enter x or expert at the RC prompt, then press Return.

All fields in a column are blank if the field is not defined for the collection’s schema in the documents table (in style.ddd, style.sfl, or style.ufl). A field in a document’s row is blank if the field was not populated by a gateway, bulk submit action, or filter.

Displaying a field

The fields command includes the field name and length to be displayed. When used, the fields command overrides the default Score and VdkVgwKey fields for the results list.

The search engine returns fields for the results list, so if you do a search, then go to expert mode to use the fields command, you must run the search again in order to see the results list with the fields you requested. For example:

RC> expert
Expert mode enabled
RC> fields title 20
RC> s universal filter
Search update: finished (100%). Retrieved: 18(18)/85.
RC> r
Retrieved: 18(18)/85
Number title
1: Using the Universal Filter
2: Using the Zone Filter
3: The Zone Filter
4: Overview
5: Table of Contents
6: Universal Filter Configuration Using the
7: Index
8: The PDF Filter
9: Document Filters and Formatting
10: Collection Style Summary
11: Collection Basics
12: Universal Filter Document Types
13: Using the style.dft File
14: Supported Field Types
15:
16: Recognized Document Types
17: Custom Zone Definitions
18: The KeyView Filter Kit
RC>

Displaying multiple fields

You can specify multiple fields with the fields command, as shown in the following example. The field order corresponds to the order of the columns, with the first field specified appearing in the second column. The first column is reserved for the rank order.

Rerun the search before you display the results list with the fields specified.

For example:

RC> fields score 5 title 40
RC> s universal filter
Search update: finished (100%). Retrieved: 18(18)/85.
RC>


Using the didump utility

Using the didump utility, you can view key components of the word index per partition. The word list is a list of all words indexed by the Verity engine; the zone list is a list of all zones; and the zone attribute list is a list of the zone attributes found by the Verity engine.

The didump executable, which starts the didump application, is located in the platform/bin directory. For more information on the specific location of this directory, see Location of Verity utilities.

For example:

c:\cfusionmx7\verity\k2\_nti40\bin\didump /common = c:\cfusionmx7\verity\k2\common
    -pattern llama
c:\new\parts\00000001.did

This section describes the following topics:

  • Viewing the word list with the didump utility
  • Viewing the zone list with the didump utility
  • Viewing the zone attribute list with the didump utility

Viewing the word list with the didump utility

You can view the contents of the word list for a partition by using the didump utility with the -words flag. The command-line syntax must include the -words flag and a pathname to a partition file, like the following:

didump -words /z/collbldg/html/parts/00000003.did

An alphabetical listing of the words in the word index displays, as follows:

didump - Verity, Inc. Version 2.5.0 (_nti31, Jul 7 1999)

Text             Size    Doc    Word
A                10      3      4
a                34      5      24
abbreviations    4       1      1
about            4       1      1
acronym          5       1      2
acronyms         4       1      1
actual           4       1      1
administrator    3       1      1
advance          3       1      1
all              8       2      3
also             9       2      4
Always           4       1      1
always           9       2      3
ampersand        4       1      1

The columns in the display indicate the following:

Size The number of bytes used by the Verity engine to store information about the word

Doc The number of unique documents in which the word appears

Word The total number of occurrences of a word for the partition

To view the occurrences of a specific word or pattern, enter a command using the -pattern option, as in the following example:

didump -pattern acronym 00000003.did

In this example, the didump utility displays information about the number of occurrences of the word acronym. You can display the individual occurrences of a word using the -verbose option.

Viewing the zone list with the didump utility

The zone list contains a list of the zones identified by the zone filter. You can search the zones listed using the Verity IN operator in a query. To view the contents of the zone list, use the didump utility with the -zones flag plus the pathname to a partition, like the following:

didump -zones /z/collbldg/html/parts/00000003.did

This partition is for a collection containing the Verity Collection Building Guide in HTML format. The Verity universal filter invoked the HTML filter by default, and indexed the documents using these zones.

didump - Verity, Inc. Version 2.5.0 (_solaris, Jul 07 1999)

ZoneName    Fmt    Size   Doc   Regions
A           Wct    10239  85    5016
ADDRESS     Array  34     1     1
BODY        Array  197    85    85
CAPTION     Wct    298    31    85
CODE        Wct    3868   66    1829
H1          Array  80     83    83
H2          Wct    646    53    212
H3          Wct    517    49    171
H4          Wct    128    8     47
HEAD        Array  70     85    85
HTML        Array  165    85    85
TITLE       Array  70     85    85

The columns in the display indicate the following:

Fmt The internal data format used to store the zone information.

Size The number of bytes used by the Verity engine to store information about the zone.

Doc The number of unique documents in which the zone appears

Region The total number of instances of a zone for the partition

Viewing the zone attribute list with the didump utility

The zone attribute list contains a list of the HTML attributes for the zones identified by the HTML zone filter. You can search the zone attributes listed using the Verity IN operator together with the WHEN operator in a query. To view the contents of the zone attributes list, use the didump utility with the -attributes flag plus the pathname to a partition, like the following:

didump -attributes /z/collbldg/html/parts/00000003.did

This partition is for a collection containing the Verity Collection Building Guide in HTML format.

didump - Verity, Inc. Version 2.5.0 (_solaris, Jul 9 1999)

Text                        Size   Doc   Word
href 01_cbg.htm             10     2     4
href 01_cbg.htm#282870      3      1     1
href 01_cbg.htm#282872      6      2     2
href 01_cbg1.htm            8      2     3
href 01_cbg1.htm#286513     7      2     2
href 01_cbg1.htm#286520     3      1     1
...

The columns in the display indicate the following:

Size The number of bytes used by the Verity engine to store information about the zone attribute

Doc The number of unique documents in which the zone attribute appears

Word The total number of occurrences of a zone attribute for the partition


Using the browse utility

A documents table is built for each partition in a collection. The documents table is used for field searching and for sorting search results. The fields within the documents table are defined by the following collection style files:

style.ddd Defines fields used internally by the Verity engine, identified by an initial underscore character (_).

style.sfl Defines standard fields (many of which are commented out to limit the size of the documents table).

style.ufl Defines custom fields that are not included in the style.sfl file.

The value of each field can be filled in from source documents or can be provided explicitly. If a field is blank, it has not been populated.

The browse utility executable, which starts the browse utility application, is located in the platform/bin directory. For more information on the specific location of this directory, see Location of Verity utilities.

For example:

c:\cfusionmx7\verity\k2\_nti40\bin\browse /common = c:\cfusionmx7\verity\k2\common
c:\my_collection\parts\0000001.ddd

This section describes the following topics:

  • Using menu options with the browse utility
  • Displaying fields

Using menu options with the browse utility

Use the following browse command to start the utility and display a set of menu options:

browse 00000003.ddd

The system displays the following menu of options available for the browse utility:

D:\VERITY\colltest\parts>browse 00000003.ddd
BROWSE OPTIONS
?) help
q) quit
c) Number of entries in field
_) Toggle viewing fields beginning with '_'
v) Toggle viewing selected fields
##) Display all fields in specified record number
Dispatch/Compound field options:
n) No dispatch
d) Dispatch
s) Dispatch as stream
Action (? for help):

Displaying fields

You can use several options to control the display of field information.

To display all the document fields:

  1. At the Action prompt, enter ##
  2. Press Return twice to display the fields for the first document record.
  3. Press Return to view the document fields for the next sequential record.

The following partial display of the results of the browse command includes internal fields, used by the Verity search engine. An internal field name starts with an underscore character (_).

50 Created              FIX-date ( 4) = 12-Jan-1998 01:52:27 pm
51 Modified             FIX-date ( 4) = 24-Sep-1997 02:40:26 pm
52 Size                 FIX-unsg ( 4) = 5381
53 DOC_OF               FIX-unsg ( 4) = 0
54 DOC_SZ               FIX-unsg ( 4) = 4294967295
55 DOC_FN_OF            FIX-unsg ( 4) = 436
56 DOC_FN_SZ            FIX-unsg ( 2) = 58
57 _CACHE_FN_OF         FIX-unsg ( 4) = 2922
58 _CACHE_FN_SZ         FIX-unsg ( 2) = 0
59 _ParentID_OF         FIX-unsg ( 4) = 354
60 _ParentID_SZ         FIX-unsg ( 2) = 46
61 Title_OF             FIX-unsg ( 4) = 2481
62 Title_SZ             FIX-unsg ( 2) = 15

You can eliminate the internal fields. To do this, type the underscore character, then press Return. If you enter an underscore character again, then press return, the internal fields are displayed.


Using the merge utility

The merge utility lets you combine multiple collections with identical schemas. This is useful for merging smaller collections built from different sources into one, large collection. Also, you can use the merge utility to break up the collection into smaller collections of a roughly uniform size.

Note: The Verity merge utility is available only in Windows.

Collections can be merged only if they have identical schemas. Collections can be merged if they have exactly the same set of style files (and style file entries).

Breaking up a large collection helps to optimize search performance, because it allows many applications to perform multiple concurrent search requests over the different collections. After breaking up a large collection, you can also discard older collections to reclaim limited disk storage space.

The merge executable, which starts the merge application, is located in the _nti40/bin directory. For more information on the specific location of this directory, see Location of Verity utilities.

For example:

c:\cfusionmx7\verity\k2\_nti40\bin\merge /common = c:\cfusionmx7\lib\common

To obtain help for the merge utility, enter the following command:

merge -help

Note: After running the merge utility, you must optimize the collection, using the mkvdk -optimize option.

This section describes the following topics:

  • Merging collections using the merge utility
  • Splitting collections using the merge utility

Merging collections using the merge utility

The following is the syntax for using the merge utility to merge multiple collections into a single collection:

merge <newCollection> <srcCollection1> <srcCollection2> [srcCollectionN]

The utility reads srcCollection1, srcCollection2 and so on and merges them into a single collection with the directory name given for newCollection If the directory name given for newCollection does not exist, it is created.

Splitting collections using the merge utility

The following is the syntax for using the merge utility to split a single large collection into smaller collections:

merge -split <srcCollection> <newCollection1> <newCollection2> [-number]

The merge utility reads srcCollection and splits it into roughly equal pieces, using the filenames given for newCollection1 and so on.

If you want to split a very large collection into a large number of new collections, you can use the following command, instead of explicitly naming each new collection:

merge -split -number newCollection srcCollection

The merge utility reads the collection identified by srcCollection and splits it into the number of segments specified by the -number option. The name of the first new collection is generated by appending the first two letters in the alphabet (aa) to the directory name given for newCollection. Each subsequent filename is generated by incrementing one of the appended letters (up to zz) for a maximum of 676 partitions. For example, if the value of -number is 3, and the value of newCollection is Collection1, the collections are named, Collection1aa, Collection1ab, and Collection1ac.

Note: The maximum length of the directory name given for newCollection is two characters less than the length allowed by the file system.
Previous


Trademarks and Acknowledgments

Trademarks

Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Flash Lite, Flex, Fontographer, FreeHand, Generator, HomeSite, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Breeze, Macromedia Flash, Macromedia M Logo and Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.

Third-Party Information

This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.

Copyright © 1997-2004 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without prior written approval of Macromedia, Inc.

Acknowledgments

Project Management: Randy Nielsen

Writing:

Editing:

Production Management: Patrice O’Neill

Media Design and Production: Adam Barnett, Aaron Begley, and John Francis

Special thanks to Ghandi

First Edition: January 2004

Macromedia, Inc.
600 Townsend St.
San Francisco, CA 94103


ColdFusion Documentation

Copyright © 1997-2004 Macromedia, Inc.
All rights reserved.
Trademarks and Acknowledgments