Accessibility

ColdFusion Article

 

Integrating Flex 2 with ColdFusion MX


CF Rune

Randy Nielsen

www.adobe.com

Created:
27 November 2006
User Level:
Beginner

In this article, you'll learn how to build a small application using Adobe Flex Builder 2 and ColdFusion MX. You'll build a simple application that reads names and e-mail addresses from a database and displays them to the user. The application also enables users to add user names and e-mail addresses to the database.

Requirements

To make the most of this article, you need to install the following software and files:

Flex Builder 2 (SDK included)

ColdFusion MX 7.0.2  (Includes connectivity for ColdFusion with Flex 2, installed on a local web server)

Note: By installing ColdFusion MX 7.0.2, you have easy access to ColdFusion components from within Flex. You also get a new version of Flash Remoting, the Flex Message Gateway, and the Flex Data Services assembler. For full details visit the ColdFusion MX 7 and Flex 2 product page.

ColdFusion Extensions for Flex Builder 2 (Already included in the download for Flex Builder 2)

Note: By installing Flex Builder 2, you also get ColdFusion Extensions (an included option with Flex Builder 2). The ColdFusion Extensions contain features such as a collection of powerful wizards that automatically generate code and applications, a Remote Development Services (RDS) module, and a Services Browser for web services and CFC introspection. For full information on the ColdFusion Extensions, visit the ColdFusion MX 7 and Flex 2 product page.

Prerequisite knowledge

Familiarity with simple ColdFusion development as well as some basic knowledge of XML.

Getting started

Download and install Flex Builder 2 if you haven't done so already. To start, you must create the database. I've called mine sample but you can call yours whatever you like.

Next, create a table that will hold the user data. For Microsoft Access, here is the column information:

Primary key Column name Data type
Yes userid AutoNumber
No username Text (255)
No emailaddress Text (255)

For MySQL, here is a SQL script you can use to create the table:

CREATE TABLE 'users' (
  'userid' int(10) unsigned NOT NULL auto_increment,
  'username' varchar(255) collate latin1_general_ci NOT NULL,
  'emailaddress' varchar(255) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  ('userid')
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=3 ;

Next, create the ColdFusion page that adds users and returns the XML that the Flex application will consume. The script is relatively simple and consists of 25 lines of code. Note the use of the cfqueryparam tag as a best practice to help verify user input:

<cfprocessingdirective pageencoding = "utf-8" suppressWhiteSpace = "Yes">
<cfif isDefined("username") and isDefined("emailaddress") and username NEQ "">
<cfquery name="addempinfo" datasource="cfdocexamples">
INSERT INTO users (username, emailaddress) VALUES (
<cfqueryparam value="#username#" cfsqltype="CF_SQL_VARCHAR" maxlength="255">,
<cfqueryparam value="#emailaddress#" cfsqltype="CF_SQL_VARCHAR" maxlength="255"> )
</cfquery>
</cfif>
<cfquery name="alluserinfo" datasource="cfdocexamples">
SELECT userid, username, emailaddress FROM users
</cfquery>
<cfxml variable="userXML">
<users>
<cfloop query="alluserinfo">
<cfoutput>
<user>
<userid>#toString(userid)#</userid>
<username>#username#</username>
<emailaddress>#emailaddress#</emailaddress>
</user>
</cfoutput>
</cfloop>
</users>
</cfxml>
<cfoutput>#userXML#</cfoutput>
</cfprocessingdirective>

Here is a quick explanation of the CFML code. The isDefined function is used to determine whether the emailaddress and username exist. If a user enters information for both of those, the cfquery tag adds the user to the database. After that, the page uses the CFXML tag to return a list of users in XML format.

Note: You cannot pass ColdFusion variables to Flex applications directly. You must encode them in XML first. By abstracting the user interface from the data retrieval, you can easily change how you display data. For example, you could use this same page to pass data to a mobile phone version of the same application. All you would need for that is to write the front end of the application; the back-end CFML would remain the same.

Up until now, everything should be familiar to you. You have a ColdFusion page and a database table. Now it's time to start building the interface to the application.

Building the user interface

Flex applications use a combination of ActionScript 3.0 and MXML. ActionScript is based on ECMAScript (similar to JavaScript), so it should be familiar to web developers. MXML is an XML-based layout engine for Flex applications. Essentially, you lay out the user interface using XML and script the user interface using ActionScript. The MXML for the interface is, again, very simple (only 26 lines):

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute" creationComplete="userRequest.send()">
   <mx:HTTPService id="userRequest" url="http://localhost:8500/returncfxml.cfm" useProxy="false" method="POST">
      <mx:request xmlns="">
         <username>{username.text}</username><emailaddress>{emailaddress.text}</emailaddress>
      </mx:request>
   </mx:HTTPService>
   <mx:Form x="22" y="10" width="493">
      <mx:HBox>
         <mx:Label text="Username"/>
         <mx:TextInput id="username"/>
      </mx:HBox>
      <mx:HBox>
         <mx:Label text="Email Address"/>
         <mx:TextInput id="emailaddress"/>
      </mx:HBox>
      <mx:Button label="Submit" click="userRequest.send()"/>
   </mx:Form>
   <mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.lastResult.users.user}">
      <mx:columns>
         <mx:DataGridColumn headerText="User ID" dataField="userid"/>
         <mx:DataGridColumn headerText="User Name" dataField="username"/>
      </mx:columns>
   </mx:DataGrid>
   <mx:TextInput x="22" y="292" id="selectedemailaddress" text="{dgUserRequest.selectedItem.emailaddress}"/>
</mx:Application>

Let's examine each line in detail. These are the first two lines of each Flex application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute" creationComplete="userRequest.send()">

The first line declares that this is an XML document. The second line declares that this is an Application, provides the namespace for MX components, declares the layout to be absolute (which means that you can position items to the exact x and y coordinates; other options are horizontal layouts or vertical layouts). Finally, creationComplete="userRequest.send()" specifies that on completion of loading the user interface, the application calls the function send() on the MXML element with the ID of userRequest.

The following section sets up HTTPService to send and receive data from the ColdFusion page you created:

<mx:HTTPService id="userRequest" url="http://localhost:8500/returncfxml.cfm" useProxy="false" method="POST">
      <mx:request xmlns="">
         <username>{username.text}</username><emailaddress>{emailaddress.text}</emailaddress>
      </mx:request>
   </mx:HTTPService>

In this section, you set the ID to userRequest and provide a URL to the ColdFusion page. You set the method of submit to POST (you could also use GET, but then you would have to change the variables in the ColdFusion page).

The request itself contains two variables: username and emailaddress. This code also sets the value for username to the text attribute of the element with ID username (username.text), and the value for the ColdFusion emailaddress variable is set to the text attribute of the element with ID emailaddress (emailaddress.text). The { and } brackets bind the variables to the value of the user interface elements.

To be clear, if you changed <username> to <user_name>, you would have to change the CFML isDefined function to isDefined("user_name"). If you change {username.text} to {user_name.text}, you must modify your MXML by changing the element with the ID of username to user_name.

Creating a form

Next, build a simple form:

<mx:Form x="22" y="10" width="493">
<mx:HBox>
      <mx:Label text="Username"/>
      <mx:TextInput id="username"/>
   </mx:HBox>
   <mx:HBox>
      <mx:Label text="Email Address"/>
      <mx:TextInput id="emailaddress"/>
   </mx:HBox>
   <mx:Button label="Submit" click="userRequest.send()"/>
</mx:Form>

Note that you can lay out the exact x and y coordinates of the form and set its exact width. Then two HBox controls surround a label and text input, allowing them to flow from left to right, one above the other. Finally, your Submit button appears at the end of the form. When a user clicks the button, the application calls the send() function of the element with ID userRequest (in this case, it is the HTTPService element).

Now that you have created the functionality that submits new entries to the database, how do you display them? Use the following code:

<mx:DataGrid id="dgUserRequest" x="22" y="128" dataProvider="{userRequest.result.users.user}">
      <mx:columns>
         <mx:DataGridColumn headerText="User ID" dataField="userid"/>
         <mx:DataGridColumn headerText="User Name" dataField="username"/>
      </mx:columns>
   </mx:DataGrid>
   <mx:TextInput x="22" y="292" id="selectedemailaddress" text="{dgUserRequest.selectedItem.emailaddress}"/>
</mx:Application>

In this case, you have a DataGrid component that populates itself with the XML from the userRequest HTTPService. You return an XML document. In this case, you bind the DataGrid component to the user elements in the XML document that is returned. The returning XML looks something like the following:

<users>
<user>
<userid>1</userid>
<username>Joe Schmoe</username>
<emailaddress>joe@schmoe.com</emailaddress>
</user>
<user>
<userid>2</userid>
<username>Betty Schmoe</username>
<emailaddress>betty@schmoe.com</emailaddress>
</user>
</users>

Note that you bind to the actual elements that are returned, not to the wrapper element around them.

The DataGrid component displays the user ID and user names of people in the database. I decided not to show the e-mail address in the DataGrid, but you could add another column with that information in it. Note that the columnName element needs to map directly to the XML elements. The DataGrid element will take care of allowing your users to sort and highlight the rows as they are selected—you don't need to do anything for that!

Finally, you have a TextInput element that shows the e-mail address of the selected user, dgUserRequest.selectedItem.emailaddress, and an XML tag that closes the application.

That's it. You have a simple Flex application that submits and retrieves XML data from a database, using ColdFusion MX as a back end.

Where to go from here

Experiment with more complicated applications using ColdFusion and Adobe Flex. In particular, consider using the Flex RemoteObject tag in conjunction with the Flash Remoting Update, as described in the documentation, Using ColdFusion MX with Flex 2 (PDF, 910 KB).

About the author

Randy Nielsen is the Adobe Flex and ColdFusion Editorial Manager. He has worked at Adobe since 1998 and has also worked at Sybase, Powersoft, and Cullinet.