Server-side CFML
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.
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.
ColdFusion (2018 release) Update 2:
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.
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.
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.
The following CFML language constructs are supported in client-side CFML, which includes all the logical/conditional and flow constructs:
The following CFML tags are supported in client-side CFML:
Note that member functions are also supported in client-side CFML. The <cfparam> tag does not support device APIs.
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:
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.
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.
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.
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.
<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.
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.
Important: The variable names and function names in CFML are case sensitive. |
From CFML, when you are invoking JavaScript
From JavaScript, when you are invoking CFML:
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.
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>:
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,
localStorage.setItem(“_cf_access_token” + appname, userToken)
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>
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.
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>
The following list shows all the supported Array functions in client-side CFML:
The following Array function is NOT supported:
The following list shows all the supported Structure functions in client-side CFML:
The following list shows all the supported List functions in client-side CFML:
The following List function is NOT supported:
The following String functions are supported:
The following Regex functions are supported:
The following decision functions are supported:
The following transaction functions are supported:
The following Math function is NOT supported:
The following Date functions are NOT supported:
The following utility functions are supported:
The following file functions are supported:
The following query functions are used:
Other supported functions:
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.
Application and Server mappings are also supported in custom tags.
Custom tags are detected when they are made available in the following locations:
The custom tags can be invoked in the following ways:
<cfimport> supports only path to custom tags and hence you cannot have JSP tag libraries.
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">
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:
<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.
The <cfexit>/<cfabort> tag exits the page execution.
The following list contains some known issues and deviations in behavior of the custom tags:
Server-side CFML |
Client-side CFML |
---|---|
caller.cfm
customtag.cfm
<cf_customtag value1="old_value"> <cfset caller[attributes.value1]="new_value"/> |
caller.cfm
customtag.cfm
<cfclient> <cfset caller[attributes.value1]="new_value"/> |
Server-side CFML |
Client-side CFML |
---|---|
<>cfset divid = "#attributes.div_id#" |
The above code will not work.
<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.
Server-side CFML |
Client-side CFML |
---|---|
<cffunction name="func1"> <cfretrurn "Hello"> </cffunction> <cf_custom> <cfset caller.func1()>
|
|
Server-side CFML |
Client-side CFML |
---|---|
<cfset path="someCFM.cfm"> <cfinclude template=#path#> |
This is not supported. |
Server-side CFML |
Client-side CFML |
---|---|
<cfset path="someCFM.cfm"> <cfmodule template=#path#> |
|
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.
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>
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>
Ensure that the function foo() is a remote function, if mycfc.cfc is a server-side CFC.
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.
The following list shows the extent of <cfquery> support available in client-side CFML:
The result variable will contain sql, recordCount, columnList, and sqlparameters.
queryexecute (" sql ", queryparams , queryoptionsmap )
The following features are not supported:
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>
See the server-side <cfquery> support.
Accéder à votre compte