ACFD9 Unit 5 Slides ()
Download
Report
Transcript ACFD9 Unit 5 Slides ()
Advanced
ColdFusion 9
Development
Replace with
a graphic
White Master
5.5” Tall & 4.3” Wide
Unit 5: Developing Advanced
GUI’s
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
1
Topics
Introducing ColdFusion AJAX functionality
Debugging ColdFusion AJAX Applications
Making Background Data Requests
Developing the User Interface
Working with Bind Expressions
Submitting Form Data Asynchronously
Using Special Text Input Fields
Working with <cfgrid>
Visualizing Data with Google Maps
Working with Video
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
2
Introducing ColdFusion AJAX Functionality
ColdFusion 9 supports a number of tags and functions to help you
quickly build powerful AJAX applications.
Direct hooks for integrating with Adobe Spry and making data requests
to components
Data binding, with only minimal knowledge of JavaScript
Some of the technology was licensed from third-parties
EXT-JS 3.0 (http://www.extjs.com)
Yahoo Interface Library (http://developer.yahoo.com/yui)
FCK Editor (http://www.fckeditor.net)
Google Maps (http://code.google.com)
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
3
ColdFusion 9 AJAX Features
A CFML-based tag abstration layer for creating AJAX applications
AJAX Debugger displaying background server communications and field binding activities.
Container tags that lay out or display content
Form elements that support data binding
A menu tag that creates hierarchical DHTML menus
User assistance features that provide tool tips, validation messages, and form completion
Facilities for styling AJAX compoents
Integration with Adobe Spry
Integration with Google Maps
A Flash-based media player, controllable from JavaScript, that plays multiple file formats
Background server requests through ColdFusion’s AJAX framework are
made to CFC methods with an access type of REMOTE
Data returned from remote methods can be automatically converted into
JavaScript Object Notation (JSON), XML (WDDX) or Plain text
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
4
Debugging ColdFusion AJAX Applications
ColdFusion 9 includes a built-in debugger that monitors background
server requests, reporting any errors that are encountered and enabling
you to easily view the data returned from the server.
Use Firebug or the Microsoft IE developer toolbar to view similar
information, inspect the document object model, and dump the contents
of complex javascript data structures.
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
5
Using the ColdFusion AJAX Logger
Since AJAX applications send data
requests to the server that are by
definition, invisible, ColdFusion 9
includes a built-in debugger that
monitors background server
requests, reporting any errors that
are encountered.
Enable the AJAX Debug log
window in the ColdFusion
Administrator
Pass the URL variable CFDEBUG
to the page running AJAX
components
The ColdFusion AJAX Logger will
appear right-justified on your page
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
6
The ColdFusion Logging API
ColdFusion.Log.debug()
ColdFusion.Log.dump()
ColdFusion.Log.error()
ColdFusion.Log.info()
<script language=”Javascript”>
var aData = [{lastname:”drucker”,firstname:”steve”}];
ColdFusion.Log.dump(aData);
</script>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
7
Using Firebug
Firebug is a free, open source plug-in for Firefox
Available from http://getfirebug.com
Very powerful and intuitive
Inspect and edit HTML
Tweak CSS
Visualize CSS metrics
Monitor network activity
DOM inspection
Logging
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
8
Using console.log()
You can output content to the Firebug console using the following
syntax:
console.log (“Hello World”);
You can pass as many arguments as you want to console.log and they
will be concatenated into a row as indicated here:
console.log(2,4,6,8,”foo”,bar);
You can pass any kind of object to console.log()
Complex data types will be displayed as hyperlinked elements,
functions, arrays, and objects
Clicking on a link inspects the data type using whichever Firebug tab is
appropriate
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
9
Inspecting JavaScript Objects
When you return data from the
server as part of an AJAX call, its
often helpful to inspect the data.
Use console.dir() to inspect
complex data types
console.dir() logs an interactive
listing of an object’s properties
Calling console.dirxml(element)
on any HTML or XML element
displays an interactive tree-based
XML outline
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
10
Walkthrough 1: Debugging AJAX Applications
Enable the ColdFusion AJAX Logger.
Use Firebug to inspect the contents of a JavaScript variable that
contains data returned from an AJAX request.
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
11
Making Background Data Requests
Use <cfsprydataset> to bind a cfc method result to a JavaScript variable
Use controls that natively support binding to a CFC method such as
<cftree> and <cfgrid>
Use <cfajaxproxy> to create a client-side JavaScript proxy for a CFC
and its methods
Use the <cfajaxproxy> tag to bind fields of ColdFusion AJAX form
controls as parameters to a specific CFC function, JavaScript function,
or HTTP request, and specify JavaScript functions to handle successful
or error results
This course will not cover <cfsprydataset> or the Adobe Spry SDK
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
12
Returning Data from Remote CFC Methods
Return data as either XML or in JavaScript Object Notation (JSON)
Use a ColdFusion function to convert your abstract data-type into either
XML or JSON inside your function and return the result as a string
serializeJSON()
deserializeJSON()
isJSON()
Use the RETURNFORMAT attribute of <cffunction> to specify the
encoding standard as Plain, WDDX, or JSON
Invoke the remote method by passing a url variable named
RETURNFORMAT with a value of Plain, WDDX, or JSON
Passing a url variable named RETURNFORMAT is preferred as it
enables the user of your service to choose whichever format is the
easiest for them to work with
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
13
Returning JSON Data
JSON deserializes into native JavaScript data types, making it easier to
parse than XML
JSON is less verbose than XML, and therefore takes less time to
download resulting in marginally faster execution, depending on the size
of the dataset being transferred
JSON is well-supported by all the popular AJAX libraries including EXTJS, jQuery, and Spry
<cfajaxproxy>, <cfgrid>, and <cftree> automatically instruct your remote
methods to encode ColdFusion data types as JSON
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
14
Example: Returning JSON Data
(test.cfc)
<cfcomponent>
<cffunction name="test"
access="remote" returntype="array">
<cfreturn ["A","B","C"]>
</cffunction>
</cfcomponent>
(test.cfm)
<a href=”test.cfc?method=test&returnformat=json”>
Click here to download the results as JSON
</a>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
15
Securing your AJAX Requests
Use the verifyclient=”yes” attribute of <cffunction> so that the service
can only be invoked via AJAX by other ColdFusion tags in your
application.
Enable a JSON Prefix
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
16
Using VerifyClient
Requires remote invocations of the page or calls to functions on the
page to include an encrypted security token.
Helps prevent security attacks where an unauthorized party attempts to
perform an action on the server
You must enable client management or session management in your
application for this feature to operate properly
Using this feature restricts the invocation of your CFC method to pages
that respond to client-side ColdFusion AJAX features
Client-side CF AJAX features automatically send the proper security
token
Using this feature prevents a remote function from being invoked as a
web service
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
17
Example: Using VerifyClient
<cfcomponent>
<cffunction name="test"
access="remote"
returntype="array"
verifyclient="true">
<cfreturn ["A","B","C"]>
</cffunction>
</cfcomponent>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
18
Using a JSON Prefix
Helps prevent JSON hijacking whereby a rogue site attempts to access
JSON content during the period from which you have left the site, but your
login credentials have not expired.
Prefixing your JSON with invalid JSON syntax prevents the rogue site’s
script from properly interpreting the JSON
ColdFusion’s AJAX tags automatically strips the JSON prefix before
evaluating your JSON data
If you are writing custom JavaScript that invokes a remote CFC method
using the returnformat=JSON URL parameter, you will need to add code to
strip the prefix before evaluating the JSON response
There are several ways to enable the JSON prefix:
In the ColdFusion Administrator (Server Settings > Settings)
In the Application.cfc
<cfset this.secureJSON = true>
<cfset this.secureJSONPrefix = “//”>
In the <cffunction> declaration:
<cffunction secureJSON=”true”
name=”r1” access=”remote”>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
19
Using <cfajaxproxy>
Allows you to register and invoke CFC methods in the background from
JavaScript.
Define a success handler that will receive a native Javascript data type
returned from your component methods
Define an error handler that executes if the specified component method
fails for any reason
Basic Syntax:
<cfajaxproxy
cfc = "CFC name"
jsclassname = "JavaScript proxy class name">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
20
Example: Using <cfajaxproxy>
(test.cfm)
<cfajaxproxy cfc="test" jsclassname="cfcTest">
<script language="JavaScript">
errorHandler = function(statusCode,statusMsg) {
alert(statusCode + ': ' + statusMsg)
}
successHandler = function(result){
alert(result);
}
getdata = function() {
/* instantiate CFC */
var remoteRequestObj = new cfcTest();
/* configure responders */
remoteRequestObj.setErrorHandler(errorHandler);
remoteRequestObj.setCallbackHandler(successHandler);
/* invoke method */
remoteRequestObj.echo("this is a test");
}
</script>
<cfform>
<cfinput type="button" name="btn"
value="Click Me" onClick="getdata()">
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
21
Walkthough 2: Making Background Requests with
<cfajaxproxy>
Secure a web service so that it may only be invoked by ColdFusion
code located on the same server
Use <cfajaxproxy> to build an AJAX proxy for the spell-check service
that you created in unit 3
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
22
Developing the User Interface
Container tags, such as dialog boxes and draggable windows
Form / Input tags that allow for data binding and a rich set of interactivity
Menu tags that create a x-browser DHTML hierarchical menu
User Assistance tags that support features like autosuggest. tooltips,
and progress bars
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
23
Using Container Tags
<cfdiv>
Defines an area of a page that can have its contents dynamically updated without the need for a page reload
By default, it outputs a <div> tag
Can be used to output any HTML tag that supports a closing component
<cfpod>
Creates an area, wrapped as a box, that includes an optional title bar
Has independent scroll bars
<cflayout>
Used to control the appearance of content nested in <cflayoutarea> tags
Content can be arranged into different formats
tabs / accordion
expanding/collapsing grid
horizontal / vertical scrolling regions
Use the fittowindow attribute to have the layout control automatically adjust to the window size
A Javascript API exists that enables you to programatically modify a layout - ColdFusion.Layout.methodname
<cflayoutarea>
Denotes virtual “pages” of information inside of a <cflayout>
Attribute usage varies depending on the type of <cflayout>
<cfwindow>
Creates a virtual “pop-up” window within the browser
A draggable, scrolling window that cannot be blocked by popup-blockers
API enables client-side creation - ColdFusion.Window.createWindow()
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
24
Using <cfdiv> to create a redraw region
The <cfdiv> tag creates an independent re-drawable area of the screen
By default, generates an HTML <div> tag along with Javascript functions
to dynamically replace its content
Content can be generated from a variety of sources
A Javascript function
A URL on the same server
A CFC method
Data typed into form fields on the same page
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
25
Example: Using <cfdiv>
<cfform>
Complete the sentence below:
<cfinput type="text"
name="modifier">
<cfinput type="submit"
name="btnsubmit">
</cfform>
My instructor is a
<cfdiv bind="{modifier@keyup}" tagName="span"> person
Note: You will learn about bind expressions later in this unit
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
26
Using <cfpod> to display web content in a dialog box
The <cfpod> tag allows you to wrap content in a box containing a title
bar
Unlike <cfwindow>, the boxes drawn by <cfpod> cannot be dragged at
runtime by the end-user
Pod content can be defined by either specifying a URL through it's
SOURCE attribute, or, alternatively by placing HTML/CFML between its
starting and ending tags
While <cfpod> does allow you to change its header and body styles, it
can only be positioned on screen through the use of the <cflayout> tag
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
27
Working with <cfpod> syntax
<cfpod source = "path"
bodyStyle = "CSS style specification"
headerStyle = "CSS style specification"
height = "number of pixels”
name = "string"
onBindError = "JavaScript function name"
title = "string"
width = "number of pixels"/>
or
<cfpod
bodyStyle = "CSS style specification"
headerStyle = "CSS style specification"
height = "number of pixels"
name = "string"
onBindError = "JavaScript function name"
title = "string"
width = "number of pixels">
pod contents
</cfpod>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
28
Using <cfajaximport>
If the SOURCE attribute of <cfpod> or any other container tag points to
a ColdFusion file that itself contains other ColdFusion AJAX-aware tags,
you must place a <cfajaximport> tag on the calling page
Use <cfajaximport> to specify the path to ColdFusion’s CFFORM
scriptSrc directory, if it is located somewhere other than
/CFIDE/scripts
<cfajaximport> also enables you to specify an alternative location for
the CSS files used in ColdFusion’s AJAX controls
The params attribute enables you to specify a Google Maps key
If you use a ColdFusion AJAX JavaScript function on a page that does
not otherwise import any AJAX JavaScript functions, use the
<cfajaximport> tag without any attributes import the base JavaScript
functions
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
29
<cfajaximport> syntax
<cfajaximport
cssSrc = "local URL path"
params = "parameters"
scriptSrc = "local URL path"
tags = "comma-delimited list">
Example:
<html>
<head><title></title></head>
<body>
<cfajaximport tags="cflayout-tab,cfform" >
<cfpod title="Edit Article"
source="cflayout.cfm" />
</body>
</html>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
30
Using <cflayout> to define tabs and collapsible sections
The <cflayout> tag creates a region on screen that can be configured as
one of several different types of layouts
Border
A box with a border and up to five layout areas. Layout areas can be set to be collapsible
and closeable
HBox
A horizontal box where all child components are stacked horizontally
VBox
A vertical box where all child components are arranged vertically
Tab
A tabbed display where each child component occupies the full width/height of the defined
layout area and the user can toggle the display of each
Accordion
Similar in functionality to a tabbed panel, it enables you to compress many fields into a
compact space.
The immediate children of a <cflayout> tag must be <cflayoutarea> tags or
nondisplay tags whose bodies contain one or more <cflayoutarea> tags at
the top level
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
31
Using <cflayout>
<cflayout
type="border|hbox|tab|vbox|accordion"
activeOnTop=”true|false”
align="center|justify|left|right”
fillHeight=”true|false”
fillWidth=”true|false”
fitToWindow=”true|false”
name="string"
padding="integer"
style="CSS style specification"
tabHeight="measurement"
tabPosition="top|bottom"
tabStrip=”true|false”
titleCollapse=”true|false”
width=”integer”
height=”integer”>
cflayoutarea tags
</cflayout>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
32
Using <cflayoutarea> to define virtual pages of a layout
A child tag of <cflayout>
Sets properties of semi-autonomous regions within the overall layout
Properties vary depending on layout type
Border
HBOX/VBOX
Tab
Accordion
See pages 5-19, 5-20 for attribute list
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
33
<cflayout> example
<cfform style="padding-top:0px; margin-top:0px;">
<cflayout type="tab“ name="CrimeRecord"
tabheight="300">
<cflayoutarea
name="CrimeDetails"
title="Crime Details">
Details of crime go here
</cflayoutarea>
<cflayoutarea title="Narrative"
name="Narrative">
Wysiwyg area for Narrative goes here
</cflayoutarea>
</cflayout>
<div align="center">
<cfinput type="submit“ name="btnSubmit"
value="Save">
</div>
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
34
Working with the <cflayout> JavaScript API
<cflayout> has a series of JavaScript functions that can be used to
programatically control layout areas through client-side scripting
The function names are case-sensitive
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
35
<cflayout> JavaScript API Functions
ColdFusion.Layout.collapseArea()
ColdFusion.Layout.selectTab()
ColdFusion.Layout.createTab()
ColdFusion.Layout.hideTab()
ColdFusion.Layout.disableTab()
ColdFusion.Layout.showTab()
ColdFusion.Layout.enableTab()
ColdFusion.Layout.hideAccordion()
ColdFusion.Layout.getBorderLayout()
ColdFusion.Layout.showAccordion()
ColdFusion.Layout.getTabLayout()
ColdFusion.Layout.selectAccordion()
ColdFusion.Layout.expandArea()
ColdFusion.Layout.collapseAccordion()
ColdFusion.Layout.showArea()
ColdFusion.Layout.expandAccordion()
ColdFusion.Layout.hideArea()
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
36
Example: <cflayout> JavaScript API
<script language="JavaScript">
function fnHelp() {
ColdFusion.Layout.createTab(
'CrimeRecord',
'help',
'Help',
'tabhelp.cfm',
{
inithide:false,
selected:true,
closable:true
}
)
}
</script>
<cfform style="padding-top:0px; margin-top:0px;">
<cflayout type="tab“ name="CrimeRecord” tabheight="300">
<cflayoutarea name="CrimeDetails” title="Crime Details">
Details of crime go here
</cflayoutarea>
<cflayoutarea title="Narrative" name="Narrative">
Wysiwyg area for Narrative goes here
</cflayoutarea>
</cflayout>
<div align="center">
<cfinput type="submit“ name="btnSubmit" value="Save">
<cfinput type="button" onClick="fnHelp()"
name="btnHelp" value="Help">
</div>
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
37
Using <cfwindow>
The <cfwindow> tag allows you to embed a draggable window into your
web page
Similar to <cfpod>, but supports additional features
Automatic centering on a page
Draggable
Modal
Closable
Resizable
You can specify initial position
Full JavaScript API
Impervious to popup blockers
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
38
Deploying <cfwindow>
<cfwindow
bodyStyle = "CSS style specification"
center="true|false"
closable="true|false"
draggable="true|false"
headerStyle = "CSS style specification"
height="number of pixels"
initShow="false|true"
minHeight="number of pixels"
minWidth="number of pixels"
modal="true|false"
name="string"
onBindError = "JavaScript function name"
refreshOnShow = "false|true"
resizable="true|false"
source="path"
title="string"
width="number of pixels"
x="numeric pixel coordinate"
y="numeric pixel coordinate">
window contents
</cfwindow>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
39
Using the <cfwindow> JavaScript API
ColdFusion.Window.show(‘name’);
ColdFusion.Window.onShow();
ColdFusion.Window.hide(‘name’);
ColdFusion.Window.onHide();
ColdFusion.Window.create();
ColdFusion.Window.getWindowObject();
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
40
Using <cfwindow>
<cfwindow
center="yes"
width="200"
height="150"
name="mywindow"
title="My First Window"
closable="true" draggable="true"
resizable="true" initshow="true"/>
<cfform>
<cfinput
type="button"
name=”btnShow”
value="Show"
onClick="ColdFusion.Window.show('mywindow')">
<cfinput
type="button"
name=”btnHide”
value="Hide"
onClick="ColdFusion.Window.hide('mywindow')">
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
41
Walkthrough 3: Using Layout Controls
Define a tabbed-based layout
Use the ColdFusion <cflayout>
API
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
42
Working with Bind Expressions
Enables you to create dependencies between form elements, client-side
recordsets, ColdFusion AJAX container elements, and information
fetched from background data requests
Bindings minimize the need to develop custom JavaScript
You cannot use a bind expression to bind to controls in a dynamically
loaded region (i.e. a <cflayoutarea> tag that specifies a SOURCE
attribute or a <cfselect> that specifies a QUERY attribute)
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
43
Working with Bind Expression Syntax
You can bind data to all AJAX-aware ColdFusion tags
The syntax varies, depending on the source of the data and the tag that
is using the expression
Type
Bind Expression Syntax
CFC Method
CFC:componentpath.functionName(params)
JavaScript function
javascript:functionName(params)
URL
url:URL?params
URL
URL?params
String / Field Concatenation
A string containing one or
more instances of a bind
parameter such as:
{firstname}.{lastname}@{domain}
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
44
Example: Bind Expressions
(test.cfc)
<cfcomponent>
<cffunction
name="echo"
access="remote"
returntype="string"
securejson="true" >
<cfargument name="myinput" type="string">
<cfreturn myinput>
</cffunction>
</cfcomponent>
(test.cfm)
<cfdiv
bind="cfc:test.echo('This is a test')" />
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
45
Binding Text Fields with the @modifier
Input field bindings are specified by placing the name of the field in curly
braces, i.e. a text field named myfield is represented in a bind
expression as {formname:myfield}, or simply {myfield}
Use the @keyup modifier to cause a binding to update as a user types
data into a dependent field
Use @click to cause a binding to update when a user clicks in a field
Without using the modifier, the binding updates when the cursor focus
changes to a different field
In the following example, the email field is updated as a user types into
either the firstname, lastname, or email fields:
Do not use @keyup with CFC bind expressions as it would trigger a
CFC request every time the user types a character into a bound field.
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
46
Example: Binding Textfields with the @modifier
<cfform>
First Name:<br />
<cfinput type="text" name="firstname"><br />
Last Name:<br >
<cfinput type="text" name="lastname"><br />
Domain:<br>
<cfinput type="text" name="domain"><br />
E-Mail:<br />
<cfinput type="text"
name="email“
bind="{firstname@keyup}.{lastname@keyup}@{domain@keyup}">
<br />
<cfinput name="btnSubmit" type="submit">
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
47
Example: Binding to a JavaScript Function
<html>
<head>
<script language="javascript">
emailAddress = function(firstname,lastname,domain) {
return (firstname.substring(0,1) +
lastname + '@' + domain);
}
</script>
</head>
<body>
<cfform>
First Name:<br />
<cfinput type="text" name="firstname"><br />
Last Name:<br />
<cfinput type="text" name="lastname"><br />
Domain:<br />
<cfinput type="text" name="domain"><br />
E-Mail:<br />
<cfinput type="text" name="email"
bind="javascript:emailAddress({firstname@keyup},{lastname@keyup},{domain@keyup})">
<br/>
<cfinput name="btnSubmit" type="submit">
</cfform>
</body>
</html>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
48
Binding to <cfselect>
Binding to text fields requires that your bind expression return a string
By default, bind expressions in a <cfselect> are used to populate its
OPTIONS array
To populate the select box options your bind expression must return a
two-dimensional array
The first element represents the VALUE attribute of the <option> tag
The second element represents the TEXT attribute of the <option> tag
There is no built-in support for specifying the SELECTED attribute of a
bound option
One strategy for specifying the SELECTED option of a select-one box is
to arrange your array so that the selected item is at array position zero
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
49
Example: Binding to <cfselect>
<script language=”JavaScript”>
getOffenses = function(offense) {
aData = new Array();
aData[0] = new Array();
/* set default option if necessary*/
if (offense == null || offense == '') {
offense = "Please Select";
}
/* set first option in array to selected item*/
aData[0][0] = offense;
aData[0][1] = offense;
/* Use <cfoutput> to cache options in browser */
<cfoutput query="qCrimeTypes">
aData[#currentrow#]=new Array();
aData[#currentrow#][0] = '#jsStringFormat(qCrimeTypes.offense)#';
aData[#currentrow#][1] = '#jsStringFormat(qCrimeTypes.offense)#';
</cfoutput>
/* remove selected item */
for (var i=1; i<aData.length; i++) {
if (aData[i][0] == offense)
aData.splice(i,1);
}
}
return aData;
}
</script>
...
<cfselect name="offense"
bind="javascript:getOffenses({mydataset.OFFENSE@click})“
bindonload="true" />
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
50
Using a Bind Expression with <cfajaxproxy>
You can configure <cfajaxproxy> to execute based on a change of form
data
This approach requires that you code less Javascript for event-driven
structures than the <cfajaxproxy> examples presented earlier in this unit
<cfajaxproxy> syntax using a bind expression uses the following syntax:
<cfajaxproxy
bind = "bind expression"
onError = "JavaScript function name"
onSuccess = "JavaScript function name">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
51
Example: <cfajaxproxy> with bind expression
<cfajaxproxy
bind="cfc:employee.getlastnamebyid({userid})"
onerror="errorHandler"
onsuccess="successHandler">
<script language="JavaScript">
errorHandler = function(statusCode,statusMsg) {
alert(statusCode + ': ' + statusMsg)
}
successHandler = function(result) {
document.forms[0].lastname.value = result;
}
</script>
<cfform>
Enter a user id:
<cfinput type="text" name="userid" value=""><br />
Last Name:
<cfinput type="text" name="lastname" value=""><br />
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
52
Walkthrough 4: Using Bind Expressions
Modify the data entry form from the prior walkthrough to make
background data requests and populate form fields
Use <cfajaxproxy> to connect to a remote CFC method
Use bind expressions to populate different types of form fields
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
53
Submitting Form Data Asynchronously
By default when a form is submitted the layout container that holds the form will be
overwritten by the result from the form's ACTION page
You can override this default behavior by using the ColdFusion 9 javascript method
ColdFusion.Ajax.submitForm()
The method sends your form data through the XMLHttpRequest() object, posting it to
whatever URL you wish
Note that you could also submit form data directly to ColdFusion CFC methods
through the <cfajaxproxy> technique discussed previously.
Use ColdFusion.Ajax.submitForm() to quickly AJAX-enable pre-existing forms
Due to a limitation in the underlying XMLHttpRequest() object, you are not be able
to post <input type="file"> fields
The content generated by the action page is returned to the callback handler function
-- so be sure to trim extraneous whitespace from your output
You will need to explicitly invoke CFFORM validation and/or code your own clientside validation routines
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
54
Using ColdFusion.Ajax.submitForm()
<script language="JavaScript">
ColdFusion.Ajax.submitForm(
formId,
URL
[
,callbackhandler
,errorhandler
,httpMethod
,asynch]
);
</script>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
55
Explicitly invoking CFFORM Validation
CFFORM validation is invoked by applying REQUIRED and VALIDATE
attributes to your <CFINPUT> tags.
ColdFusion.Ajax.submitForm() does not invoke the generated client-side
javascript validation functions
The name of the controller function is _CF_checkformname where
formname is the value of the name attribute assigned to your form
The validation function returns true if all fields comply with their
validation rules
You should pass the entire form as a Javascript object to the generated
form validation function as indicated here:
if (_CF_checkmyform(document.myform)) {
/* your form data passed! Now submit it! */
}
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
56
Retrieving Object/Attribute Values
Use the ColdFusion JavaScript API method
ColdFusion.getElementValue() in order to get the value of an attribute of
a bindable ColdFusion control
Supports most CF input widgets
cfgrid
cfinput (checkbox, datefield, file, hidden, radio, text)
cfselect
cftextarea
cftree
if (ColdFusion.getElementValue('offense') ==
{
alert("You must select an offense");
return;
}
'Please Select')
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
57
Building the Action Page
Whatevever content is output on the action page is returned to the
ColdFusion.Ajax.submitForm() success method
Submit your form variables for processing to a CFC method
Disable CF debugging output on the action page using
<cfsetting showdebugoutput=”false”>
Tightly control whitespace generation using
<cfsetting enablecfoutputonly=”true”>
The following example illustrates a typical action page which pases form
data to a CFC method and tightly controls the text output that is
transmitted to the ColdFusion.Ajax.submitForm() success handler:
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
58
Example: AJAX Action Page
<cfsetting showdebugoutput="no">
<cfsetting enablecfoutputonly="true">
<!--- write to db --->
<cfset cfcCrimeService =
createObject("#application.settings.cfcpath#crime").init(
application.googleMapKey,
form.id,
form.blocksiteaddress,
"Washington",
"DC",
0.1)>
<cfset cfcCrimeService.update(
form.offense,
'',
form.narrative,
form.reportdatetime
)>
<cfoutput>Record #form.id# Saved</cfoutput>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
59
Deploying ColdFusion.Ajax.submitForm()
See example, pages 5-41, 5-42
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
60
Walkthrough 5: Asynchronously Submitting Forms
Programatically trigger ColdFusion’s client-side form validation routines
Inspect the value of a <cfselect> box
Submit form data to an action page asynchrously using
ColdFusion.Ajax.submitForm()
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
61
Using Special Text Input Fields
ColdFusion 9 has a series of rich form controls that extend the native
functionality of a standard text field and textarea. These include the
following:
Autosuggest
Graphical Date Chooser
WYSIWYG Editor
The AJAX form controls are derived from the EXT-JS 3.0 framework
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
62
Using Autosuggest Text Fields
A variant on the standard <cfinput type="text"> field
The goal is to limit the number of characters a user must type in order to
select an item
As a user types into the field, a box with suggestions appears beneath it
The data that populates the selection list can be either statically
declared, or can be read dynamically from a ColdFusion component
method
Use the AUTOSUGGESTMINLENGTH attribute to reduce the number of
requests to the server and the amount of data that will be returned
The basic syntax for implementing an autosuggest box is the following:
<cfinput name="userName"
type="text"
autosuggest="Dave, Steve, Sue">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
63
Using Autosuggest with a limited data set
You can hardcode values into the AUTOSUGGEST attribute of <cfinput
type="text"> as indicated below
This method is best used when the data set is limited to fewer than one
hundred entries
<cfquery name="qs”
cachedwithin="#createtimespan(365,0,0,0)#">
select statename from state order by statename
</cfquery>
<cfform>
<div style="float: left“>Enter the State:</div>
<cfinput
name="statename"
type="text"
autosuggest="#valuelist(qs.statename)#">
<br /><br />
</cfform>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
64
Using Autosuggest with large data sets
There may be scenarios where, due to data volume, it is not practical to
specify the autosuggest data set as a comma delimited string
Use a bind expression whereby a user's input is passed in the
background to a ColdFusion component method
The CFC method must be defined with ACCESS="REMOTE"
The CFC method must return an array of strings
The typed text can be passed into the CFC method using the {cfautosuggestvalue}
bind parameter
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
65
Example: Using Autosuggest with large data sets
<!--- (cfc method) --->
<cffunction name="getCrimeIDs” access="remote“ returntype="array“
output="false">
<cfargument name="searchstring" type="String">
<cfset local.q = "">
<cfquery name="q" >
select id
from crime
where convert(id,char(10)) like
<cfqueryparam
cfsqltype="cf_sql_varchar"
value="#arguments.searchstring#%">
limit 0,10
</cfquery>
<cfreturn listToArray(valuelist(q.id))>
</cffunction>
<!--- front-end GUI --->
<cfinput
type="text”
name="id"
validate="numeric"
autosuggest="cfc:#application.settings.cfcpath#crimeservice.getCrimeIDs(
{cfautosuggestvalue})">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
66
Customizing Autosuggest Behavior
autosuggestBindDelay
autosuggestMinLength
delimiter
matchContains
maxResultsDisplayed
onBindError
showAutosuggestLoadingIcon
typeahead
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
67
Working with the DateField Selector
Like the autosuggest feature, the graphical date chooser is implemented
through the <cfinput> tag
Gives the user a date entry field with an expanding calendar from which
users select the date or dates
The user has the option to type in a date instead of using the gui
selector
You can customize the appearance of the calendar
Use the dayNames attribute to specify acomma-delimited list that sets the names of
the weekdays displayed in the calendar
The monthNames attribute controls the names of the months that appear in the
calendar. Specify as a comma delimited list.
The firstDayOfWeek attribute is an integer in the range 0-6 that specifies the first day
of the week in the calendar: 0 indicates Sunday; 6 indicates Saturday.
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
68
Example: Using the DateField Selector
<label for="reportdatetime">
Report Date:
</label>
<cfinput
type="datefield"
name="reportdatetime"
bind="{mydataset.REPORTDATETIME@click}"
required="yes"
validate="date" />
<br />
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
69
Using the WYSIWYG Editor
Implemented through the <cftextarea richtext=”yes”> tag
An abstraction layer for the CK Editor (www.ckeditor.com)
Highly configurable allowing you to potentially restrict functionality to
specific groups of users
Develop custom toolbars
Specify allowable styles
Enable its built-in spell checker
You cannot use the WYSIWYG editor if your ColdFusion server is
configured to process htm files
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
70
<cftextarea> attributes
Width
Height
fontFormats
fontSizes
MaxLength
BasePath
Skin
sourceForTooltip
Toolbar
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
71
Customizing the Editor Toolbar
You can define custom toolbars for the editor by modifying the
FCKConfig.Toolbarsets variable located in
/CFIDE/scripts/ajax/FCKEditor/fckconfig.js file as indicated below
Adding to the variable makes additional options available via the
TOOLBAR attribute of <cftextarea>
You will need to customize the editor in order to support uploading
media, including images and Flash
Additional developer documentation is available at
http://docs.cksource.com
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
72
Example: Customizing the Editor Toolbar
FCKConfig.ToolbarSets["MyCustomToolbar"] = [
['Bold',
'Italic',
'-',
'OrderedList',
'UnorderedList',
'-',
'Link',
'Unlink',
'-'
],
[
'Cut',
'Copy',
'Paste',
'-',
'Image',
'Flash',
'About'
]
];
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
73
Specifying Allowed WYSIWYG Styles
You can configure specific styles to be supported by the editor
Styles are defined using XML
Default styles are defined in /CFIDE/scripts/ajax/FCKEditor/fckstyles.xml
Create additional style definitions using the following syntax and link
them to <cftextarea> using the STYLESXML attribute
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
74
Example: Adding WYSIWYG Styles
<Styles>
<Style name="Image on Left" element="img">
<Attribute name="style"
value="padding: 5px; margin-right: 5px" />
<Attribute name="border" value="2" />
<Attribute name="align" value="left" />
</Style>
<Style name="Image on Right" element="img">
<Attribute name="style"
value="padding: 5px; margin-left: 5px" />
<Attribute name="border" value="2" />
<Attribute name="align" value="right" />
</Style>
<Style name="Custom Bold" element="span">
<Attribute name="style"
value="font-weight: bold;" />
</Style>
<Style name="Custom Italic" element="em" />
<Style name="Title" element="span">
<Attribute name="class" value="Title" />
</Style>
<Style name="Code" element="span">
<Attribute name="class" value="Code" />
</Style>
<Style name="Title H3" element="h3" />
<Style name="Custom Ruler" element="hr">
<Attribute name="size" value="1" />
<Attribute name="color" value="#ff0000" />
</Style>
</Styles>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
75
Using the <cftextarea richtext=”yes”> javascript API
You can programatically get and set the data in a <cftextarea> using the
following JavaScript methods:
ColdFusion.RichText.getEditorObject(editorID).GetHTML()
Retrieves the html contained by the WYSIWYG editor
ColdFusion.RichText.setValue(editorID, replacementHTML)
Replaces the contents of the WYSIWYG editor with the specified html
function fnReplace(formID,WYSWYGID,searchFor,replaceTerm)
{
var msgbox = document.forms['myform'][WYSIWYGID].id;
var html =
ColdFusion.RichText.getEditorObject(msgbox).GetHTML();
ColdFusion.RichText.setValue(msgbox,
html.replace(searchFor, replaceTerm));
}
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
76
Extending the WYSIWYG editor
Review the following lins that detail how to unlock hidden features of
<cftextarea>
Implementing Spell Checking and File Uploads in the WYSIWYG editor
http://www.rakshith.net/blog/?p=58
The CKEditor Documentation
http://docs.cksource.com/
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
77
Walkthrough 6: Implementing Rich Text Controls
Define and configure an autosuggest field as well as its associated
bindings
Define and configure a datefield control
Use <cftextarea> to invoke a CKEditor control
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
78
Working with <cfgrid>
<cfgrid type=”html”> is AJAX-enabled and can load data incrementally
from the server
Allows for client-side sorting of rows
Supports boolean column values (rendered as checkboxes)
Supports drop-down lists in columns (combobox)
Allows the user to choose from a datepicker from within date columns
Allows for row grouping
Supports a grid title
Expand/collapse functionality
Text fields can bind to grid data using bind=”{gridname.columnname}”
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
79
Deploying <cfgrid type=”html”> for use with large datasets
Working with <cfgrid> and large datasets involves incrementally fetching
“pages” of records from a ColdFusion component through a bind
expression.
Pagination Attributes:
bind
BindOnLoad
PageSize
PreservePageOnSort
StripeRowColor
StripeRows
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
80
Defining the Bind Expression
Pass four variables to the CFC method responsible for returning dynamic
data
{cfgridpage}
{cfgridpagesize}
{cfgridsortcolumn}
{cfgridsortdirection}
Example:
<cfgrid format="html"
name="incidentGrid"
collapsible="yes"
title="Crime Incidents"
bind="cfc:crimeservice.getForGrid({cfgridpage},{cfgridpagesize},{cfgridsortcolumn},{cfgridsortdirection})"
striperows="yes”
striperowcolor="cccccc"
width="450"
height="200"
pagesize="5"
autowidth="true"
colheaderbold="true">
<cfgridcolumn name="reportdatetime" type="date" width="50" header="Date">
<cfgridcolumn name="offense" type="combobox" header="Offense" width="50">
<cfgridcolumn name="blocksiteaddress" type="string_noCase" header="Address" width="220">
</cfgrid>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
81
Returning Query Data for a Grid
The CFC method access must equal REMOTE
The CFC method must return a STRUCT
The query data returned from the CFC must be returned through the
ColdFusion function QueryConvertForGrid()
QueryConvertForGrid() accepts the following arguments:
The query to be converted
The grid page number
The number of rows per page
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
82
Example: Returning Data for a Grid
<cffunction name="getforgrid" access="remote" returntype="struct" output="false">
<cfargument name="page">
<cfargument name="pageSize">
<cfargument name="gridsortcolumn">
<cfargument name="gridsortdirection">
<cfset local.q = "">
<cfif arguments.gridsortcolumn is "">
<cfset arguments.gridsortcolumn = "reportdatetime">
</cfif>
<cfif arguments.gridsortdirection is "">
<cfset arguments.gridsortdirection = "asc">
</cfif>
<cfquery name="q">
select blocksiteaddress,id, offense, narrative,
DATE_FORMAT(reportdatetime,'%m/%d/%Y') as reportdatetime
from crime
order by
<cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.gridsortcolumn#”>
<cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.gridsortdirection#">
</cfquery>
<cfreturn queryConvertForGrid (q,arguments.page,arguments.pagesize)>
</cffunction>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
83
Making a Grid Editable
<cfgrid> attributes:
Use the selectmode=”edit” attribute to render a grid editable
Use the delete=”yes” attribute to allow the users to delete rows
Use insert=”yes” to allow users to insert rows
Pass data from the grid to a ColdFusion component method by specifying a bind
expression in the onchange attribute of the grid
Date values must be in a supported format (i.e. mm/dd/yyyy)
Specify <cfgridcolumn> types
Boolean
Date
Combobox
Numeric
String_nocase
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
84
Example: Making a Grid Editable
<cfgrid
selectmode=”edit”
name=”crimegrid” ... >
<cfgridcolumn type="date"
name="reportdatetime"
width="50" header="Date">
<cfgridcolumn type="combobox"
values="#valuelist(qoffenses.offense)#"
name="offense"
header="Offense"
width="50" >
<cfgridcolumn
type="string_noCase"
name="blocksiteaddress"
header="Address“
width="220“>
</cfgrid>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
85
Example: Making a Grid Editable
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
86
Using <cfgrid selectmode=”edit”> Bind Parameters
The onchange bind expression should pass the following information to
the CFC method
{cfgridaction}
{cfgridrow}
{cfgridchanged}
<cfgrid
selectmode=”edit”
onChange="cfc:#application.settings.cfcpath#.crimeservice.setFromGrid(
{cfgridaction},
{cfgridrow},
{cfgridchanged})"
....
</cfgrid>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
87
Saving Data from a Grid
<cffunction
<cfargument
<cfargument
<cfargument
name="setFromGrid" access="remote" returntype="boolean" verifyclient="yes">
name="cfgridaction" required="yes" type="string" Hint="I, U or D">
name="cfgridrow" required="yes" type="struct">
name="cfgridchanged" required="yes" type="struct">
<cfswitch expression="#arguments.cfgridaction#">
<cfcase value="D">
<cfquery>
delete from crime where id =
<cfqueryparam cfsqltype="cf_sql_numeric" value="#arguments.cfgridrow.id#">
</cfquery>
</cfcase>
....
</cfswitch>
<cfreturn true>
</cffunction>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
88
Controlling a Grid using the JavaScript API
Use ColdFusion.Grid.getGridObject() to access the underlying Ext JS
library methods
ColdFusion.Grid.refresh() forces the grid to reload and redisplay data
ColdFusion.Grid.sort() programmatically sorts the grid
There is not a native method for updating a grid’s contents
The following method allows you to programmatically change the
contents of a grid control:
function gridSetElementValue(gridname,row,column,thevalue)
{
var objGrid = ColdFusion.Grid.getGridObject(gridname);
objRow = objGrid.store.data.items[row];
objRow.set(column,thevalue);
objGrid.view.refreshRow(row);
}
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
89
Determining the active row
The function must be declared within the <head> section of the page
You must use ColdFusion’s ajaxOnLoad() function to invoke the event
listener definition
<script language="Javascript">
var selectedRow = 0;
initGrid = function()
{
var grid = ColdFusion.Grid.getGridObject("incidentGrid");
grid.addListener("rowclick", function(objGrid, rowNumber, e){
selectedRow = rowNumber;
});
}
</script>
<cfset ajaxOnload("initGrid")>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
90
Walkthrough 7: Using <cfgrid>
Define an editable <cfgrid> control
Bind a grid to a ColdFusion remote method
Bind form fields to grid data
Transmit grid updates to ColdFusion for processing
Push data from form fields into a grid
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
91
Visualizing Data with Google Maps
Currently, ColdFusion supports
only embedding of Google maps
To generate a map, you must
provide a valid Google map API
key
You must specify a map center
position as either a
latitude/longitude or a valid street
address
End-users must be able to access
subdomains of google.com from
their web browsers and Javascript
must be enabled
You can attach custom events to
map markers
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
92
Acquiring a Google Maps Key
You must create a Google account in order to work with most of Google's API's
If you already have a GMail account, then you're ready to proceed
Sign up for a Google account at www.google.com/accounts/NewAccount
License keys are tied to both your Google account and the domain name where your
application will be hosted
Get a free license key at http://code.google.com/apis/maps/signup.html
Google Maps has specific licensing terms
There is no limit on the number of page views you may generate per day using the Maps API
There is a limit on the number of geocode requests per day
The Maps API does not include advertising
Your service must be freely accessible to end users
You may not alter or obscure the logos or attribution on the map
Maps should not be used to display illegal activity (such as locations to procure illicit drugs) or
reveal personal information
If your service is not freely accessible, you will need to contact Google to discuss paid-license
terms
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
93
Acquiring a Google Maps Key
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
94
Registering your Google Maps Key with ColdFusion
In the ColdFusion Administrator (Server Settings > Settings)
Set this.googlemapkey in the Application.cfc file
Use the <cfajaximport> tag
<cfajaximport params="#{googlemapkey='Map API Key'}#">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
95
Using <cfmap> and <cfmapitem>
<cfmap> dictactes the overall look and feel of the map
<cfmapitem> places map markers on the map
You can the center position by using either the centeraddress attribute
or the centerlatitude and centerlongitude attributes.
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
96
<cfmap> syntax
<cfmap
centeraddress="address"
centerlatitude="latitude in degrees"
centerlongitude="longitude in degrees"
collapsible="true|false"
continuouszoom="true|false"
doubleclickzoom="true|false"
height="integer"
hideborder=""
markerbind="bind expression"
markercolor="marker color"
markericon="icon path
"
markerwindowcontent="content"
name="name"
onerror="JavaScript function name"
onload="JavaScript function name"
overview="true|false"
scrollwheelzoom="true|false"
showallmarkers="true|false"
showcentermarker="true|false"
showmarkerwinodw=""true|false"
showscale="true|false"
tip="center property marker tips"
title="string"
type="map|satellite|hybrid|earth|terrain"
typecontrol="none|basic|advanced"
width="integer"
zoomcontrol="none|small|large|small3d|large3d"
zoomlevel="integer"
<!--- zero or more <cfmapitem> tags --->
<cfmapitem
address="address"
latitude="latitude in degrees"
longitude="longitude in degrees"
markercolor="marker color"
markericon="icon path
"
markerwindowcontent="content"
name="name of the map"
showmarkerwinodw=""true|false"
tip="marker tip" />
</cfmap>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
97
Example: Using <cfmap>
<cfmap centeraddress="#form.address# Washington, DC"
type="map"
width="400"
height="200"
typecontrol="basic"
zoomcontrol="small3d"
showcentermarker="true"
showmarkerwindow="true"
zoomlevel="17"
name="crimemap"
onload="resizeMap">
<cfloop query="qincidents">
<cfmapitem
latitude = "#qincidents.lat#"
longitude= "#qincidents.lng#"
markercolor="FF3030"
markerwindowcontent="<span class='map'>#qincidents.offense#<br
/>#qincidents.narrative#<br />#qincidents.reportdatetime#</span>">
</cfloop>
</cfmap>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
98
Controlling a <cfmap> with JavaScript
ColdFusion.Map.addEvent()
ColdFusion.Map.addMarker()
ColdFusion.Map.getLatitudeLongitude()
ColdFusion.Map.getMapObject()
ColdFusion.Map.setCenter()
ColdFusion.Map.setZoomLevel()
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
99
Example: Adding a Map Event Listener
ColdFusion.Map.addEvent("crimemap","click",function(overlay)
{
if (overlay != null)
{
var myPano =
new
GStreetviewPanorama(document.getElementById("streetview"),
{latlng:overlay.getLatLng()});
}
});
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
100
Walkthrough 8: Using <cfmap>
Use <cfmap> to instantiate a map
Plot data points on a map
Link the map to Google Street View
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
101
Working with Video
<cfmediaplayer>
Supports multiple formats
FLV
MP3
MP4
Progressive downloads and streamed content from a Flash Media
Server via RTMP
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
102
<cfmediaplayer> syntax
<cfmediaplayer
align="alignment option"
autoplay="true|false"
bgcolor="hexadecimal value"
hideborder="true|false"
hidetitle="true|false"
controlbar="true|false"
fullScreenControl="yes|no"
name="name"
onComplete="JavaScript function name"
onLoad="JavaScript function name"
onStart="JavaScript function name"
quality="low|high|medium"
source="source name"
style=="style specification"
height="integer"
width="integer"
wmode="window|opaque|transparent">
</cfmediaplayer>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
103
Styling the Media Player
Use the style attribute
<cfmediaplayer
name="myplayer"
style="bgcolor:EDC393; titletextcolor:C0C0C0;
titlebgcolor:EDC393; controlbarbgcolor:EDC393;
controlscolor:FFFFFF; progressbgcolor:DDDDDD;
progresscolor:A0B1D5; borderleft:20; borderright:20;
bordertop:10; borderbottom:13"
hideborder="false"
hideTitle=false
controlbar="true"
source="myfile.flv">
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
104
Using the <cfmediaplayer> JavaScript API
ColdFusion.Mediaplayer.resize()
ColdFusion.Mediaplayer.setMute()
ColdFusion.Mediaplayer.setSource()
ColdFusion.Mediaplayer.setVolume()
ColdFusion.Mediaplayer.startPlay()
ColdFusion.Mediaplayer.stopPlay()
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
105
Example: Using the <cfmediaplayer> JavaScript API
<script language=”JavaScript”>
function playVideo(url)
{
ColdFusion.Mediaplayer.setSource(‘mediaplayer’,url);
ColdFusion.Mediaplayer.startPlay(‘mediaplayer’);
}
</script>
<select
name="videourl“
onChange="playVideo(this.options[this.selectedIndex].value)”>
<option value="/acfd9/assets/video/sample1.flv">Camera 1</option>
<option value="/acfd9/assets/video/sample2.flv">Camera 2</option>
</select>
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
106
Walkthrough 9: Using <cfmediaplayer>
Use the <cfmediaplayer> tag to instantiate a media player
Use the <cfmediaplayer> JavaScript API to play selected videos
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
107
Summary
Use the ?debug url variable to help you troubleshoot ColdFusion-AJAX applications
ColdFusion supports four layout tags - <cfwindow>, <cfpod>, <cflayout>, and <cfdiv>
ColdFusion has a JavaScript API to programmatically manipulate layout controls on the client
Use the BIND attribute to link form fields with data from CFC methods, URL's, and JavaScript
Use the ColdFusion.Ajax.submitForm() method to post form data asynchronously
ColdFusion 9 supports several "rich form" controls
Message Box
Progress Bar
AutoSuggest
WYSIWYG
Grid
Tree
Datefield
Use <cfmap> to plot locations on a Google Map
You can extend the built-in functionality of AJAX controls by getting access to their underlying
JavaScript objects
Use <cfmediaplayer> to progressively download a video or stream one from a Flash Media Server
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
108
Unit Review
How do you enable debugging of a CF-AJAX application?
Describe the differences between <cfpod> and <cfwindow>
What kind of data structure must be returned from a cfc method bound to an autosuggest element?.
How can you create custom toolbars for the WYSIWYG editor?
How do you incrementally populate an HTML grid with data from a CFC method?
What information is required in order to plot a point on a Google Map?
You cannot attach special click handlers to a Google Map (true/false)?
Which video formats are supported by <cfmediaplayer>?
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
109
®
Copyright 2009 Adobe Systems Incorporated. All rights reserved. Adobe confidential.
1
110