Client-side CFML (for mobile development)

This document describes the client-side CFML capabilities. Client-side CFML allows the development of client-side applications using CFML. Client-side CFML can be used to develop CF-based mobile applications wherein the CFML code in the application is converted to HTML/JavaScript by the ColdFusion Server.

Note:

Before you begin – To try out the examples provided in this document, you need to set up the ColdFusion mobile development environment. See Configuring the development environment.

<cfclient> is a tag introduced in ColdFusion 11 to support mobile development. This tag has been introduced to convert the CFML code that it encloses into JavaScript code. A ColdFusion developer can now develop mobile applications using CFML by leveraging the transformation functionality offered through the <cfclient> tag. So, you do not need know JavaScript to write mobile web applications.

Convert CFML into mobile applications
Convert CFML into mobile applications

History

ColdFusion (2018 release) Update 2:

  1. Introduced the following methods. As a user, you can write the logic for them.
    1. mobileServer
    2. validationCFC
  2. There are new options for mobile in ColdFusion Administrator. For more information, see Mobile settings.
  3. Support for additional functions and tags.

There is also a helper cfc , that is introduced in Update 2 of the 2018 release of ColdFusion

Even if you are an experienced JavaScript developer, <cfclient> can still be used to simplify the mobile application development as it abstracts the complexities involved in building a mobile application using JavaScript and HTML.

Note:

The CFML constructs to be executed at the client-side have to be embedded within the <cfclient> tag. Not all tags, functions, and CFML functionalities are supported for conversion to HTML/JavaScript. For the complete list of CFML tags and functions that <cfclient> tag supports, see Supported CFML language constructs and Supported CFML tags.

The rationale behind choosing to support only a certain set of tags and functions is to strengthen the relevance of CFML for client-side mobile application development.

How does the transformation work

Let us see how the regular <cfoutput> tag gets rendered on a browser.

Your ColdFusion code:

<cfoutput>Hello World</cfoutput>

What the browser gets from the ColdFusion Server:

Hello World

Let us revisit the Hello World <cfclient> example mentioned in the A customary hello world example section.

Now, if your ColdFusion code is:

<cfset myvar = “Hello World”>
<cfoutput>#myvar#</cfoutput>
</cfclient>

Check the source of the web page translated by ColdFusion Server. It will be pure JavaScript wrapped in an HTML page.

As you can infer, the CFML code available in the <cfclient> block gets converted to JavaScript. Though this example is simple, the translation works the same way for complex CFML code.

Supported CFML language constructs

The following CFML language constructs are supported in client-side CFML, which includes all the logical/conditional and flow constructs:

  • IF/ELSE/ELSEIF
  • WHILE/DO WHILE
  • CFLoop/CONTINUE/BREAK
  • SWITCH/CASE/DEFAULTCASE
  • TRY/CATCH/FINALLY
  • FOR
  • TERNARY OPERATOR
  • THROW
  • IMPORT
  • INCLUDE
  • ABORT
  • EXIT
  • FUNCTION/ARGUMENT/RETURN
  • FUNCTION INVOCATION
  • CUSTOM TAGS

Supported CFML tags

The following CFML tags are supported in client-side CFML:

  • cfset
  • cfoutput
  • cfinclude
  • cfscript
  • cfobject
  • cfinvoke
  • cfmodule
  • cfsavecontent
  • cfparam
  • cfproperty
  • cfcomponent
  • cfabort
  • cfexit
  • cfreturn
  • cfbreak
  • cfcontinue
  • cfquery
  • cfflush

Note that member functions are also supported in client-side CFML. The <cfparam> tag does not support device APIs.

Tags supported in ColdFusion (2018 release) Update 2

  • cfdbinfo
  • cfinsert
  • cfobjectcache
  • cfprocparam
  • cfprocresult
  • cfquery
  • cfqueryparam
  • cfstoredproc
  • cftransaction
  • cfupdate
  • cfdocument
  • cfdocumentitem
  • cfdocumentsection
  • cflog
  • cfprocessingdirective
  • cfprint
  • cfcollection
  • cfftp
  • cfindex
  • cfsearch
  • cfxml
  • cfdirectory
  • cffile
  • cflocation
  • cfpdf
  • cfpdfform
  • cfpdfformparam
  • cfpdfparam
  • cfpdfsubform
  • cffeed
  • cfimap
  • cfhttp
  • cfhttpparam
  • cfmail
  • cfmailparam
  • cfmailpart
  • cfpop
  • cfcache
  • cfcookie
  • cfschedule

Where client-side CFML differs from the server-side CFML

Though you can have any valid CFML code in the <cfclient> code block, there are behavioral restrictions on the CFML tags and constructs. Some of the behavioral restrictions are listed here:

  • The keys for  implicit  structure will be static. For instance, you cannot declare {“#a#”:”value”}. Also, {a:a} will become {‘a’:a}.
  • In the <cfinclude> tag, dynamic template name(##) is not supported:

<cfset x=“abc.cfm”>
<cfinclude template=“#x#”>
</cfclient>
  • This limitation is applicable for the <cfmodule> tag too.

  • Also, the <cfinclude> tag only supports files with extensions .cfm, .js, and .css.
  • The Boolean behavior differs in <cfclient>. For example, In ColdFusion, 0/1, true/false, ‘true’/ ’false ’, yes/no are all treated as Boolean. However, in <cfclient>, only true/false are Boolean.
  • In ColdFusion, x=“1” is still a number even with the quotes. However, <cfclient> treats this as a string. Ensure that you follow strict data types for the functions to avoid  abnormal  behavior.
  • In ColdFusion, <cfset x=“1a”> is a date but inside <cfclient> it is not. Note that <cfclient> follows JavaScript date format instead of ColdFusion date format.
  • In ColdFusion, <cfset x = 1/2> is 0 but inside <cfclient> it is 0.5.
  • ColdFusion server exceptions will not work on client side.
  • The format of the Date/Time/DateTime objects created by createDate, createTime, and createDateTime respectively differs from the server side CFML behavior. For instance, the following code:

<cfoutput>#CreateDateTime( 1776, 7, 4, 12, 59, 0)#</ cfoutput >

On server side, you will get the output:
{ts '1776-07-04 12:59:00'}

When you use parseDateTime on client side CFML, ensure that you pass the output obtained from the creatDateTime function as an argument to create the DateTime object.

The following code will not work because of the strict data types:

<cfset mytimespan = #createtimespan(2, 1, 16, 30)#>
<cfoutput>#date1 + mytimespan#</cfoutput>
<cfoutput>#DateFormat(date1 + mytimespan)#</cfoutput>

In the above example, timespan when added to datetime, becomes a string.

Note:

The DateFormat function does not work with Firefox and Internet Explorer. In Chrome, the function displays output correctly. A possible workaround is to use a function like createDateTime(2003,6,11,10,50,32) and pass the date object to dateFormat function.

  • Function naming convention – Functions supported by browser and PhoneGap will have server CFML syntax. For instance, FileXXX. The PhoneGap functions will follow the Object access approach. For instance, Camera.XXX.
  • Scopes available on  server  side is not supported on  client  side.
  • Argument Collection will not be supported for passing arguments.
  • arraySort function differs in the behavior when its numeric numbers like 0002, 00001, 1.0E+5 and the sort type is text.

anumeric = arrayNew(1);
anumeric[1] = 01;
anumeric[2] = 001;
anumeric[3] = 1;
anumeric[4] = 1.001;
anumeric[5] = 1.1;
anumeric[6] = 1.101;
anumeric[7] = 1.109;
anumeric[8] = 1.11;
anumeric[9] = 2;
anumeric[10] = 02;
anumeric[11] = 00002;
anumeric[12] = 20;
anumeric[13] = 50;
anumeric[14] = 1.0E+2;
anumeric[15] = 100;
anumeric[16] = 1000;
anumeric[17] = 1.0E+5;
</cfscript>
<cfset arraySort(anumeric, "text")>
<cfloop array="#anumeric#" index=i>
<cfoutput>#i#</cfoutput>
</cfloop>

Actual output for the above code:
1 1 1 1.001 1.1 1.101 1.109 1.11 100 100 1000 100000 2 2 2 20 50
Expected output for the above code:
00002 001 01 02 1 1.001 1.0E+2 1.0E+5 1.1 1.101 1.109 1.11 100 1000 2 20 50
This is because JavaScript represents 02, 002, 2 in the same way as '2' and hence differs in sort.

  • Duplicate function behavior for struct differs when the struct internally has a reference to another struct more than once. On server side, changing the value in the duplicated struct’s referred key will also change the values at other referred points. However, in the case of client side CFML, this does not happen.
<cfset str2 = {name: 'str2', value1: str1, value2: str1}>
<cfset str2dup = duplicate(str2)>
  • In the above example, if you change the value of str2dup.value1.value, on the server side,  value of str2dup.value2.value is also changed automatically as they both refers to same structure. But on client side, this is not the behavior.

  • On client side, calling a super function from an included CFM or CFC is not supported.
  • Positional arguments are not supported.

When you use the <cfoutput> tag inside the <cfclient> tag, the contents of the <cfoutput> tag is not immediately processed. Hence, you may encounter certain issues while using this code:

<cfoutput>
<div id="result"></div>
</cfoutput>
<cfset document.getElementById("result").innerHTML = "Hello">
<cfclient>

In this case, while the document.getElementById() statement is being invoked, cfoutput is not processed. Hence, you will not find an element with id "result", which will result in a runtime error.

In this case, you can directly write to the DOM, instead of using cfoutput:

<div id="myDiv"></div>
<cfclient>
<cfset document.getElementById("myDiv").innerHTML += "<div id=""result""></div>
<cfset document.getElementById("result")+="Hello">
</cfclient>

Or another workaround is to use flush explicitly after <cfoutput>:

<cfoutput>
<div id="result"></div>
</cfoutput>
<cfflush>
<cfset document.getElementById("result").innerHTML = "Hello">
<cfclient>

If you follow this approach, ensure that the HTML content in the cfoutput is well formed.

Client-side CFML and JavaScript

Important: The variable names and function names in CFML are case sensitive.

From CFML, when you are invoking JavaScript

  • Use the correct case for function name and variable name when referencing CFML functions and variables from CFML as client-side CFML is case sensitive.

From JavaScript, when you are invoking CFML:

  • Use the correct case for function name and variable name when referencing CFML functions and variables from JavaScript as client-side CFML is case sensitive.

Loading JavaScript files

You can load content of the JavaScript files in your ColdFusion code using the loadJSFile() function as shown in the following example:

{
function init ()
{
cfclient.loadJSFile("yourjsfile.js", function ()
{
alert("Script loaded");
});
}
}

You can also use <cfinclude> to load a JavaScript file.

Synchronous and asynchronous function calls

ColdFusion automatically determines whether a function call is synchronous or asynchronous. However, if you need to invoke an asynchronous function in a synchronous mode, you can use the invokeInSyncMode function. The function call just needs to be wrapped around with the invokeInSyncMode function call. For instance, invokeInSyncMode (myAsyncFunc(arg1,arg2)). See InvokeCFClientFunction.

Asynchronous behavior

As a ColdFusion developer, you have always been using synchronous programming models. However, programming client applications using JavaScript needs to follow an asynchronous model. Fortunately, ColdFusion does most of the synchronous to asynchronous translation automatically.

ColdFusion asynchronous programming model
ColdFusion asynchronous programming model

For instance, see the following script:

<cfscript>
try
{
//Your code that throws an exception
}
catch (e)
{
// This statement will be reached unlike
// in typical asynchronous model
}
</cfscript>

The ability to use asynchronous functions in <cfclient> through the ‘known’ synchronous model provides a lot of convenience while building mobile applications using ColdFusion.

Since ColdFusion automatically translates synchronous code to asynchronous code, exception handling becomes easier in client code.

The behavior of certain tags has been modified to support the asynchronous behavior. In the process, functionalities of some tags may differ. For instance, <cfloop> does not support the following features when used along with <cfclient>:

  • Looping over a COM collection
  • Looping over a date or time range
  • Looping over a directory

Helper CFC

component
{
public boolean function isauthorized(String accesstoken) {
               //Write logic for accesstoken validation
return true;
}

public boolean function validateparameters(Struct context){                                    
                            writedump(var=context,output='console');
return true;
}
                
}

Copy the helper cfc in the server. Name it appropriately. In a cfm , specify the path as follows:

<cfclientsettings  mobileserver='http://localhost:8500' enabledeviceapi="false" validationcfc='path for cfc'>

To use isauthorized , you must set the access token in the client side, as shown below:

localStorage.setItem("_cf_access_token" + "app2", myToken);

This token is then passed with each request which is made to server for the server tags used by the user.

You must also write the logic for validating the token in validation.cfc.

Here,

  • _cf_access_token is just a keyword.
  • app2 is the name of the app.
  • myToken is the token being stored. This token needs to be generated by the user/client. If you have your own custom implementation for login, after the login, set on the client side (browser/mobile app) using the code given below:

localStorage.setItem(“_cf_access_token” + appname, userToken)

  • isAuthorized: Checks if an access token is valid or not.
  • validateParameters : When the return value is false, the server call does not get executed. Returns an error that says parameter validation failed.

These methods return a boolean (either true or false). If you want to use only one of the two methods, you must also write the second method and return true.

Validation CFC

component
{
    public boolean function validateparameters(Struct context){
        // context.functionname
        // context.line
        // context.file
        // context[0] - Data object - Requires deserialization
        objectData = deserializeJSON(context[0])
        writeDump(var=context.functionname,output='console');
        writeDump(var=serializeJSON(objectData.ROWCOUNT),output='console');
        return true;
    }
}

CFM

<cfclientsettings  mobileserver='http://your-server:port-number/' 
       enabledeviceapi="false" 
       validationcfc="/usr/local/htdocs/validationFlow/_cfquery.cfc">
 <cfclient>
       <cfquery name="q1" type="server" datasource = "cfartgallery">
            select * from art
       </cfquery>
       <cfoutput>#serializeJSON(q1)#</cfoutput>         
       <cfoutput>Expected: Database Data</cfoutput>
</cfclient>

Support for ColdFusion Functions

You can start writing mobile applications in ColdFusion using existing data types and functions. The <cfclient> tag supports CFML data types and functions.

The following functions depict usage of data types and functions in your ColdFusion-based mobile projects.

Using CFML simple types

The following example shows the usage of simple data types:

<cfclient>
<cfset myVar1 = 1>
<cfset myVar2 = “hello”>
<cfset myVar3 = true>
</cfclient>

Using CFML structures

The following example shows the usage of simple structures:

<cfclient>
<cfset myStruct = structNew()>
<cfset myStruct.key1= “hello”>
<cfif structKeyExists(myStruct, “key1”)>
...
</cfif>
</cfclient>

Using CFML arrays

The following example shows the usage of arrays:

<cfclient>
<cfset myArray = arrayNew(1)>
<cfset myArray[1] = “hello”>
</cfclient>

Using CFML functions

The following example shows the usage of functions:

<cfclient>
<cfif arrayLen(myArray) gt 1 >
...
</cfif> 
<!--- using the math function--->
<cfset sum = arraySum(myArray) >


<!--- using the date/time function--->
<cfset currentDate = now() >


<!--- using the locale function--->
<cfset locale = getLocale() >
</cfclient>

List of all supported functions in ColdFusion (2018 release) Update 2

The following list shows all the supported Array functions in client-side CFML:

  • arraySlice
  • arrayAppend
  • arrayIsDefined
  • arrayAvg
  • arrayIsEmpty
  • arrayClear
  • arrayLen
  • arrayMax
  • arrayNew
  • arrayMin
  • arraySort
  • arrayDelete
  • arrayToList
  • arrayPrepend
  • isArray
  • arrayResize     
  • listToArray
  • arraySet        
  • arrayFind
  • arrayFindAll
  • arraySum
  • arraySwap
  • arrayFindNoCase
  • arrayFindAllNoCase

The following Array function is NOT supported:

  • arrayFilter (closure function)

The following list shows all the supported Structure functions in client-side CFML:

  • isStruct
  • structDelete
  • structAppend
  • structInsert
  • structClear
  • structIsEmpty
  • structCopy
  • structKeyExists
  • structCount
  • structNew
  • structFind
  • structUpdate
  • structFindKey
  • structFindValue
  • structGet
  • structKeyArray
  • structKeyList
  • structSort

The following list shows all the supported List functions in client-side CFML:

  • find
  • findNoCase
  • findOneOf
  • formatBaseN
  • lCase
  • left
  • len
  • listAppend
  • listChangeDelims
  • listContains
  • listContainsNoCase
  • listDeleteAt
  • listFind
  • listFindNoCase
  • listFirst
  • listGetAt
  • listInsertAt
  • listLast
  • listLen
  • listPrepend
  • listQualify
  • listRest
  • listSetAt
  • listSort
  • listToArray
  • listValueCount
  • listValueCountNoCase
  • replaceList
  • valueList

The following List function is NOT supported:

  • getClientVariablesList

The following String functions are supported:          

  • binaryEncode
  • binaryDecode  
  • charsetEncode
  • charsetDecode
  • toBase64
  • toBinary
  • toString
  • uRLDecode
  • uRLEncodeFormat
  • LSEuroCurrencyFormat
  • LSIsCurrency
  • LSIsNumeric
  • LSNumberFormat
  • LSParseCurrency
  • LSParseEuroCurrency
  • LSParseNumber

The following Regex functions are supported:

  • rEFind
  • rEMatch
  • rEFindNoCase
  • rEMatchNoCase
  • rEReplace
  • rEReplaceNoCase
  • rEEscape

The following decision functions are supported:

  • IIF
  • INT
  • IsBinary
  • IsCustomFunction
  • IsDDX
  • IsInstanceOF
  • IsJSON
  • IsObject
  • IsPDFArchive
  • IsPDFFile
  • IsPDFObject
  • IsSafeHTML
  • IsWDDX

The following transaction functions are supported:

  • TransactionCommit
  • TransactionRollback
  • TransactionSetSavePoint

The following Math function is NOT supported:

  • precisionEvaluate

The following Date functions are NOT supported:

  • createODBCDate
  • createODBCTime
  • createODBCDateTime
  • lSDateFormat
  • lSIsDate
  • lSParseDateTime
  • lSTimeFormat

The following utility functions are supported:

  • isBoolean
  • isDefined
  • decimalFormat
  • isNumeric
  • dollarFormat
  • isNull
  • htmlCodeFormat
  • isSimpleValue
  • htmlEditFormat
  • isValid
  • numberFormat
  • createUUID

The following file functions are supported:

  • DirectoryCopy
  • DirectoryCreate
  • DirectoryDelete
  • DirectoryExists
  • DirectoryList
  • DirectoryRename
  • GetDirectoryFromPath
  • FileAppend
  • FileClose
  • FileCopy
  • FileDelete
  • FileExists
  • FileGetMimeType
  • FileIsEOF
  • FileMove
  • FileOpen
  • FileRead
  • FileReadBinary
  • FileReadLine
  • FileSeek
  • FileSetAttribute
  • FileSetLastModified
  • FileSkipBytes
  • FileUpload
  • FileUploadAll
  • FileWrite
  • FileWriteLine
  • GetFileFromPath
  • GetFileInfo
  • IsFileObject

The following query functions are used:

  • QuerySort
  • QueryAddRow
  • QueryConvertForGrid
  • QueryEach
  • QueryAddColumn
  • QueryReduce
  • QuerySetCell
  • EntityToQuery
  • ORMExecuteQuery
  • IsQuery
  • QueryMap
  • QueryNew
  • QueryDeleteColumn
  • QueryGetRow
  • RemoveCachedQuery
  • QueryGetResult
  • QueryKeyExists
  • QueryDeleteRow
  • QueryExecute

Other supported functions:

  • Max
  • Min
  • Minute
  • NumberFormat
  • PreserveSingleQuotes
  • Quarter
  • QuotedValueList
  • Rand
  • Randomize
  • RandRange
  • Asc
  • BinaryDecode
  • BinaryEncode
  • BooleanFormat
  • Canonicalize
  • Ceiling
  • CharsetDecode
  • CharsetEncode
  • Chr
  • CreateObject
  • CreateUUID
  • DE
  • DecodeForHTML
  • DecodeFromURL
  • DecrementValue
  • Decrypt
  • DecryptBinary
  • Deserialize
  • DeserializeJSON
  • DollarFormat
  • EncodeForCSS
  • EncodeForDN
  • EncodeForHTML
  • EncodeForHTMLAttribute
  • EncodeForJavaScript
  • EncodeForLDAP
  • EncodeForURL
  • Encrypt
  • EncryptBinary
  • Evaluate
  • Exp
  • Find
  • FindNoCase
  • FindOneOf
  • Fix
  • Floor
  • GeneratePBKDFKey
  • GenerateSecretKey
  • GetApplicationMetadata
  • GetBaseTagData
  • GetBaseTagList
  • GetComponentMetadata
  • GetLocale
  • GetLocaleDisplayName
  • GetMetadata
  • GetMetricData
  • GetPrinterInfo
  • GetPrinterList
  • GetSystemFreeMemory
  • GetSystemTotalMemory
  • GetTickCount
  • GetTotalSpace
  • Hash
  • HMac

Support for custom tags

You have been using custom tags in ColdFusion for the past few releases of ColdFusion. Custom tags allowed you to extend CFML by adding your own tags to the ones shipped with ColdFusion. Custom tags can now be created in <cfclient> too. The following sections provide an overview of the supported features and restrictions while using custom tags for building mobile applications.

Note:

Application and Server mappings are also supported in custom tags.

Paths for custom tags

Custom tags are detected when they are made available in the following locations:

  • The custom tag available in the same directory as the calling page
  • The custom tag available in the cfusion /CustomTags directory
  • The custom tag available in sub-directories under the cfusion /CustomTags directory
  • The custom tag available in server/application mapped folders

Invoking custom tags

The custom tags can be invoked in the following ways:

  • Using the cf_<tagname>. For instance, by calling <cf_mytag>
  • Using the <cfmodule> tag. For instance, <cfmodule template="../cf_mytag.cfm">
    • Also, <cfmodule name=”tags.mytag”>
    • For the <cfimport> tag, we use the taglib to import the custom tags:
      • For instance, <cfimport prefix = “myTags” taglib = “/custom”>
      • The DOT(.) notation can be used to access custom tags available inside sub directories. For instance, use <cfmodule name = “tags.mytag”>

<cfimport> supports only path to custom tags and hence you cannot have JSP tag libraries.

Passing values

You can pass values to a custom tag using a name-value pair:

<cf_mytag myname=#myvalue#>

Also, multiple name-value pairs can be passed to a custom tag:

<cf_mytag myname1=#myvalue1# myname2=#myvalue2#>

To access the arguments passed to the custom tag, the custom tag CFM file can use the attributes scope as follows:

#attributes.myname1# and #attributes.myname2#

To send the data back to the calling page, the custom tag CFM file can use the Caller scope as follows:

<cfset caller.myname=#attributes.myname1# & " " & #attributes.myname2#>

You can also pass a struct to the custom tag:

<cfset args=structNew()>
<cfset args.x = "‐X‐">
<cfset args.y = "‐Y‐">
<cf_mytag arg1="value1" attributeCollection=#args# anotherarg="16">

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.

To determine if an end tag is specified, use the hasEndTag as follows:

<cfif thisTag.hasEndTag is 'false'>
<!‐‐‐ Abort the tag‐‐‐>
<cfabort />
</cfif>

To determine the tag execution mode, use the executionMode attribute. Three modes are supported:

  • Start mode – For processing the start tag
  • End mode – For processing the end tag
  • Inactive mode – For processing custom tags using nested tags
<cfif thisTag.executionMode is 'start'>
<!‐‐‐ Process start tag ‐‐‐>
<cfelseif thisTag.executionMode is 'end'>
<!‐‐‐ Process end tag ‐‐‐>
</cfif>

You can access the body text within the custom tag using the thisTag.generatedContent variable. You can modify this text during processing of the tag. The contents of the thisTag.generatedContent variables are returned to the browser as part of the tag’s output. The content 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.

See the following example:

<cfif thisTag.executionMode is 'end'>
<cfset thisTag.generatedContent ='<!‐‐#thisTag.generatedContent#‐‐>'>
</cfif>

The nested sub tag can pass its attributes to the parent tag. A sub tag can use cfassociate to communicate its attributes to the base/ancestor tag.

<cfassociate baseTag="tagName" dataCollection="collectionName">

The following code shows how you can access the subtag attributes in the base tag:

<cfparam Name='thisTag.assocAttribs' default=#arrayNew(1)#>

You can also access the ancestral data in the sub tag using the getBaseTagList() helper method as follows:

<cfset ancestorlist = getBaseTagList()>

The getBaseTagList() method returns a comma-delimited list of uppercase ancestor tag names, as a string. You can also use the getBaseTagData() method to return an object that contains all the variables of the nth ancestor.

Aborting custom tag processing

The <cfexit>/<cfabort> tag exits the page execution.

Deviation list for custom tags

The following list contains some known issues and deviations in  behavior  of the custom tags:

  • In <cfclient>, variables scope is supported. But you have to explicitly scope it.

Server-side CFML

Client-side CFML

caller.cfm

 

 

customtag.cfm

 

 

<cf_customtag value1="old_value">
<cfoutput>
#variables.old_value#
<cfoutput>
<cfoutput>
#old_value#
<cfoutput>

<cfset caller[attributes.value1]="new_value"/>

caller.cfm

 

 

customtag.cfm

 

 

<cfclient>
<cf_customtag value1="old_value" >
<cfoutput>#variables.old_value#<cfoutput>
</cfclient>

<cfset caller[attributes.value1]="new_value"/>

  • If you use the "#attributes.attributename#" syntax in the custom tag after an asynchronous call, you will see an unexpected behavior.

Server-side CFML

Client-side CFML

 

 

<>cfset divid = "#attributes.div_id#"

 

The above code will not work.
Use:

 

<cfset divid = "#attributes.div_id#">

<cfset divid = #attributes.div_id#>

 

Numeric values passed to the attributes in caller are passed as a string to the custom tags:

<cf_custom attr1="1">

In the above example, attr1 is converted to a number, if you are accessing the attribute in a numeric operation. However, it does not work in this manner for client-side custom tags. You need to use:

<cf_custom attr1=1>

Or:

<cfset x = 1>
<cf_custom attr1=#x#>
  • Type conversion is not handled in client custom tags.

  • Function  declared in the caller CFM is accessible in the custom tag (CFM) using the caller.functionname() on the server-side. However, this is not the behavior on the client side.

Server-side CFML

Client-side CFML

 

 

 

<cffunction name="func1">

<cfretrurn "Hello">

</cffunction>

<cf_custom>

<cfset caller.func1()>

 


The functions defined in the caller CFM are not available in the custom tags.

  • Using variables to pass the path of the included file does not work inside <cfclient>.

Server-side CFML

Client-side CFML

 

 

 

 

<cfset path="someCFM.cfm">

<cfinclude template=#path#>

This is not supported.

  • Passing the template/name (with <cfmodule>) attribute as a variable does not work with <cfclient>.

Server-side CFML

Client-side CFML

 

 

 

<cfset path="someCFM.cfm">

<cfmodule template=#path#>


This is not supported as we need to do the translation during the compile time itself.

  • Exception thrown in the custom tag template will not be handled by the exception handler defined in the caller CFM. If the custom tag name is wrong or if the included CFM name is wrong, in client-side CFML, you will get an exception during the compilation time itself.
Note:

Based on the location of the JavaScript file (specified in the <cfinclude> tag or using the <script> tag), the order of execution of statements differ.

Non-<cfclient> custom tags cannot be called from caller CFMs of <cfclient>. Also, a client-side custom tag cannot have server-side ColdFusion tags outside the <cfclient> tag. This is true for client-side included-CFMs too. For better debugging, do not add script blocks/link tags/style tags in the client-side custom tags. Always create a separate JavaScript file or a CSS file and add them using the <cfinclude> tag.

<cfinclude template="utils.js">
or
<cfinclude template="new.css">

This is applicable for client-side included CFMs too.

Support for CFC (Client-side and Server-side)

A client-side CFC can be written using the client=true attribute for a cfclient component. For instance, a client-side CFC can identify itself by having client=true along with other component attributes. See the following example:

component client=true
{
public function foo()
{
//some code here
}
}

<cfclient> communicates with the ColdFusion Server quite seamlessly so much so that you can create objects of a server component and call functions on that object just like how you do ColdFusion Server programming. The ColdFusion Server facilitates all the various interactions required between a mobile client and the server without any restrictions on the language.

See the following example:

<cfclient>
<!-- Create a JS proxy of server side component myCFC.cfc‐‐‐>
<cfset proxy = new app1.controls.myCFC(id)>


<!-- Update some data ‐‐‐>
<cfset proxy.setVar("myVar1")>
<cfset proxy.setProperties(someStructVar)>
</cfclient>

In the above example, you are calling a function on a remote CFC within the <cfclient> tag. The new operator creates a proxy to the server CFC. You can use the instantiated CFC object to invoke remote functions on that CFC.

Note that a server CFC is similar to any other CFC without the client attribute being set to true.

Calling a function to a remote CFC
Calling a function to a remote CFC

The <cfclient> tag allows the usage of CFCs just like any other CFML constructs. There are multiple ways of using CFCs in the <cfclient> block.

The following example shows a very simple usage:

<cfclient>
<cfset obj = new mycfc()>
<cfset obj1 = createObject(“component”,”mycfc”)>
</cfclient>

In the above example, mycfc.cfc can be a client-side CFC or a server-side CFC. As you can infer, CFCs can be created using createObject, new keyword, and cfinvoke techniques.

You can also use a CFC that extends functionalities from another CFC:

<cfclient>
<cfset obj = new mycfc()> 
<!--- mycfc extends mycfc1.cfc present in the same directory --->
<cfset result = obj.getResult() > 
<!--- getResult() function present in mycfc1.cfc and can be 
accessed from the extending classes --->
</cfclient>
Note:

Ensure that if mycfc.cfc is a client-side CFC, then mycfc1.CFC should also be a client-side CFC. This is applicable even for the server-side CFC if mycfc.cfc is a server-side CFC.

You can also use <cfimport> for importing mapped paths:

<cfimport path=“com.*” />
<cfset obj = new com.mycfc() /> 
<!--- mycfc present in directory mapped to com --->


You can also use functions within a CFC:
<cfclient>
<cfset obj = new mycfc() >
<cfset obj.foo() > 
<!--- invoke function on cfc instance --->
</cfclient>
Note:

Ensure that the function foo() is a remote function, if mycfc.cfc is a server-side CFC.

Support for database queries

You can start using the <cfquery> tag in client-side CFML just like how you are currently using it in server-side CFML code. Note that not all of the <cfquery> features are supported in this release. The support for database queries in client-side CFML is based on Web Database (Web SQL). So, this feature may not work on certain browsers. To check if your browser supports Web SQL, see this web page.

What is supported

The following list shows the extent of <cfquery> support available in client-side CFML:

  • The <cfquery> tag supports ONLY the following attributes:
    • name = "query name"
    • dataSource = "data source name"
    • result = "resultVar"

The result variable will contain sql, recordCount, columnList, and sqlparameters.

  • You can use the <cfloop> tag to iterate over the query. The <cfloop> tag will support query, startrow , and endrow attributes.
  • You can use the <cfqueryparams> tag for parameterized query.
  • In the <cfqueryparam> tag, only the value attribute is supported.
  • The queryparam attribute value can be provided through position parameters in an array using the queryExecute function:

             queryexecute (" sql ", queryparams , queryoptionsmap )

  • Note that serialization and deserialization of queries from client to server and server to client will be seamless.
  • You can use the isQuery function in client-side CFML to check if a variable is of query type.

What is NOT supported

The following features are not supported:

  • Performing query of queries.
  • In-memory query creation functions like QueryNew and QueryAddRow.

Usage example

The following example shows the basic usage of the <cfquery> tag in client-side CFML:

<div id="actual_1" class="async_actual">

<cfclient>

<cfquery datasource="cfds" >drop table if exists birthDates</cfquery>

<cfquery datasource="cfds" > 
CREATE TABLE if not exists birthDates( 
serialNo INTEGER PRIMARY KEY AUTOINCREMENT, 
firstname VARCHAR(20), lastname VARCHAR(20), dob TEXT) 
</cfquery>  
<!---Insert string. --->
<cfquery datasource="cfds" name="q1"> 
INSERT INTO birthDates(firstName, lastname,dob) VALUES('Jon', 'Doe', 'Mark')
</cfquery>

<cfset d1=createDate(1975, 12, 25)>

<cfset a=dateFormat(d1,"yyyy-mm-dd")>

<cfquery datasource="cfds" name="q2"> 
INSERT INTO birthDates(firstName, lastname, dob) VALUES('Jon', 'Doe', '#a#')
</cfquery>

<cfset d2=createDate(1980, 01, 01)>

<cfset b=dateFormat(d2, "yyyy-mm-dd")>

<cfquery datasource="cfds" name="q2"> 
INSERT INTO birthDates(firstName, lastname, dob) VALUES('Jon', 'Doe','#b#')
</cfquery>

<cfset d3=createDate(1985, 12, 27)>

<cfset c=dateFormat(d3, "yyyy-mm-dd")>

<cfquery datasource="cfds" name="q3"> 
INSERT INTO birthDates(firstName, lastname, dob) VALUES('Jon', 'Doe','#c#')
</cfquery> 


<cfset startRow="2">
<cfset endRow="4">

<cfquery datasource="cfds" name="q4" result="test"> 
SELECT * FROM birthDates where serialNo between <cfqueryparam value="#startRow#"> and <cfqueryparam value="#endRow#">
</cfquery>

<cfset write_to_div("actual_1", test.sql & "<br>" & test.recordCount & "<br>" & test.columnList)>

<cfloop query="q4"> 
<cfset write_to_div("actual_1", firstname & " " & lastname & ":" & dob &"<br>")> 
</cfloop>

</cfclient>

<script type="text/javascript">

function write_to_div(div_id,data_to_write)
{ 
document.getElementById(div_id).innerHTML+=data_to_write;
}

</script>

</div>

 Adobe

Get help faster and easier

New user?