So as I am sure you are aware, Flex 2 hit the ground running recently. Have you been kicking yourself for not getting a head start on learning? Well for all the people who thought it was just a fad, this tutorial is here to save the day. I hope by reading and working through this tutorial you will get a general but firm understanding of simple to advanced workings of Flex.
Dowload associated content "userManager.zip"
What is Flex? You might ask yourself. Flex is the most complete, powerful application development solution for creating and delivering cross-platform rich Internet applications (RIAs) within the enterprise and across the web. It enables the creation of expressive and interactive web applications that can reach virtually anyone on any platform. Enterprises can use Flex to quickly build and deploy applications that improve the user experience, boost the bottom line, and analyze data to enable better business decisions.
Okay, with out further ado, lets get cracking.
This tutorial will be broken up into 4 stages.
As with any IDE, learning to use the IDE takes big chunk of time when you are trying to teach yourself. In this stage you will learn how to create a basic Flex project. This basic Flex project will be the starting point of our over all end result. So, lets not skip this part.
Step 1: How will you connect to your data.
There are basically 3 ways you can connect to your data from Flex.
A. XML or Webservices
B. RemoteObjects
C. HttpService
For this tutorial we will be using option A, webservices. I would have liked to use RemoteObjects, but since this is written for the masses and since some people cannot update their CF server to Mystic we will be going with webservices.
Okay, enough of the background stuff, lets start this.
Start off by going to File > New > Flex Project. You will get a screen like the one in figure 1. As I said before we will be using Webservices, so go ahead and select Basic and click next.

Step 2: Naming your project.
Here is where we give our project a name. For this tutorial we will be using the project name userManager. You have one other option on this screen (figure 2). You can change the default location of where you would like to store your project. For this tutorial we will be using the default location of My Documents\Flex Builder\<project name>. Once you have given your project a name, click finish and your Flex project will be created.

Step 3: Hold your horses.
Okay, so you have a nice new project with that fresh project smell. But this is where we close Flex builder and move on to other tasks. I know, I know, you just got started and already it is being taken away. Know there is a method to the madness, and remember we are working on a 3 tier system here folks. So, we want to start back to front.
As with most web applications, you need to be able to store your data, so of course we will be using the old standby of a database. For this tutorial, I will be using MYsql.
Step 1: Create your database.
In this tutorial we will be using the database name userManager. Below you will find an SQL query to create your table and fields.
SET FOREIGN_KEY_CHECKS=0;
use userManager;
#----------------------------
# Table structure for users
#----------------------------
CREATE TABLE `users` (
`fld_userId` varchar(30) NOT NULL default ',
`fld_userLogin` varchar(20) default NULL,
`fld_userPass` varchar(30) default NULL,
`fld_userFirstName` varchar(50) default NULL,
`fld_userLastName` varchar(50) default NULL,
`fld_userEmail` varchar(255) default NULL,
`fld_userUrl` varchar(255) default NULL,
`fld_userSex` int(1) default NULL,
PRIMARY KEY (`fld_userId`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
#----------------------------
# No records for table users
#----------------------------
As stated previously we will be creating a webservice that will allow users to connect to our data. For this we will be creating a Coldfusion Component aka CFC.
Step 1: Server preparation.
As with most web applications, there is normally some amount of preparation you have to do in order to get your project off the ground. First we need to create a file called crossdomain.xml.
The crossdomain.xml file permits your compiled SWF to access your data source (CFC). You can find more info on this file on the Adobe website, www.adobe.com/go/14213
crossdomain.xml - copy the code below, and put it in your crossdomain.xml file. You can adjust the permissions, by placing your domain name
in the domain attribute. Remember, you can not access other domains if they do not have the permissions file. However, you can by pass this with a simple proxy via CF, ASPX, PHP, etc...
Your crossdomain.xml file, must reside in your document root. If your document root is /var/www/html/userManager/ You would place your crossdomain.xml
file, in your userManager folder. IE /var/www/html/userManager/crossdomain.xml
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Next we need to create our folder structure. In order to keep it simple, we will use a simple folder structure. In your document root create a new
directory called com. For example, if your document root was /var/www/html/userManager. We will be using this as our document root for the remainder of this tutorial.
Step 2: Data Source
Next we need to create a data source, for this tutorial we will be using the data source name cf_userMan
Step 3: Create our CFC.
This part is pretty straightforward and easy. First thing we need to do is create a new CFC. Start a new document in your favorite editor. In the document add the code below, and save it to your documentroot/com directory. Name the CFC UserManager. You should end up with something like.
<cfcomponent displayname="UserManager">
</cfcomponent>
Step 4: Add User Function
Now we are ready to get into some code. We are going to start off by creating our function in our CFC.
Here you can see we have a pretty simple function. The two main things that allow a Flex application to connect to a CFC are:
1. Access to the function must be remote.
2. The arguments you pass from Flex to your function must match exactly. This seems pretty straightforward, but a lot of developers make this simple mistake.
This is our first function in our webservice. From Flex we are passing 7 arguments, and these arguments are used to insert data into our database. Copy the code below into your UserManager.cfc. (make sure it is between your cfcomponet tags).
<!--- ADD A NEW USER FUNCTION --->
<cffunction name="Add_User" access="remote" returntype="string">
<!--- VARS PASSED FROM FLEX TO CFC --->
<cfargument name="login" required="yes" type="string" />
<cfargument name="pass" required="yes" type="string" />
<cfargument name="firstName" required="yes" type="string" />
<cfargument name="lastName" required="yes" type="string" />
<cfargument name="email" required="yes" type="string" />
<cfargument name="url" required="no" type="string" />
<cfargument name="sex" required="no" type="string" />
<!--- INSERTION QUERY --->
<cfquery name="AddUserQry" datasource="#application.dsn#">
insert into users (fld_userId, fld_userLoing, fld_userPass, fld_userFirstName, fld_userLastName, fld_userEmail, fld_userUrl, fld_userSex)
values
('#createUUID()#', '#arguments.login#', '#arguments.pass#', '#arguments.firstName#', '#arguments.lastName#', '#arguments.email#',
'#arguments.url#', '#arguments.sex#')
</cfquery>
<!--- CONFIRMATION MESSAGE --->
<cfset msg = "You have sucessfully added #arguments.firstName# #arguments.lastName# as a user">
<cfreturn msg />
</cffunction>
Step 5: Update User Function
Here we have our next function. In this function, we have a new argument being passed from our Flex application to our CFC. We are now passing the user's id from the Flex application to our CFC, we are using the id as a PK.
<!--- UPDATE A USER FUNCTION --->
<cffunction name="Edit_User" access="remote" returntype="string">
<!--- VARS PASSED FROM FLEX TO CFC --->
<cfargument name="id" required="yes" type="string" />
<cfargument name="login" required="yes" type="string" />
<cfargument name="pass" required="yes" type="string" />
<cfargument name="firstName" required="yes" type="string" />
<cfargument name="lastName" required="yes" type="string" />
<cfargument name="email" required="yes" type="string" />
<cfargument name="url" required="no" type="string" />
<cfargument name="sex" required="no" type="string" />
<!--- INSERTION QUERY --->
<cfquery name="EditUserQry" datasource="cf_userMan">
update users
set
fld_userLogin = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.login#" />,
fld_userPass = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.pass#" />,
fld_userFirstName = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.firstName#" />,
fld_userLastName = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.lastName#" />,
fld_userEmail = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.email#" />,
fld_userSex = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.sex#" />
where fld_userId = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.id#" />
</cfquery>
<!--- CONFIRMATION MESSAGE --->
<cfset msg = "You have sucessfully updated #arguments.firstName# #arguments.lastName#" />
<cfreturn msg />
</cffunction>
Step 6: User Delete Function
This next function is how we are going to remove users from the system. We only have one argument passed with this function, it is our pk id.
<!--- DELETE A USER FUNCTION --->
<cffunction name="Delete_User" access="remote" returntype="string" >
<cfargument name="id" required="yes" type="string" />
<cfquery name="DeleteUserQry" datasource="cf_userMan">
delete from users
where fld_userId = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.id#" />
</cfquery>
<cfreturn msg />
</cffunction>
Step 7: User Display Function
This function is a bit different then previous functions. In this function we are returning our data as a struct. Why do we do this is simply because it is the easiest and best way to display returned query objects within Flex. Again, we are only passing the id argument into this function.
<!--- DISPLAY USER INFO ON EDIT SCREEN --->
<cffunction name="Display_User" access="remote" returntype="struct" >
<cfargument name="id" required="yes" type="string" />
<cfquery name="DisplayUserQry" datasource="cf_userMan" >
select
fld_userId, fld_userLogin, fld_userPass, fld_userFirstName,
fld_userLastName, fld_userEmail, fld_userUrl, fld_userSex
from users
where fld_userId = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.id#" />
</cfquery>
<cfset userInfo = structNew()>
<cfscript>
userInfo['id'] = DisplayUserQry.fld_userId;
userInfo['login'] = DisplayUserQry.fld_userLogin;
userInfo['pass'] = DisplayUserQry.fld_userPass;
userInfo['firstName'] = DisplayUserQry.fld_userFirstName;
userInfo['lastName'] = DisplayUserQry.fld_userLastName;
userInfo['email'] = DisplayUserQry.fld_userEmail;
userInfo['url'] = DisplayUserQry.fld_userUrl;
userInfo['sex'] = DisplayUserQry.fld_userSex;
</cfscript>
<cfreturn userInfo />
</cffunction>
Step 8: User Search Function
The last function in our CFC is the user search function. In this function we are going to return the actual query object to Flex. We do not need to convert our query into a struct for this. You can use an Array of Structures to obtain the same results, but this is not required for this tutorial.
<!--- USER SEARCH --->
<cffunction name="Search_User" access="remote" returntype="query" >
<cfargument name="firstName" required="no" />
<cfargument name="lastName" required="yes" />
<cfquery name="SearchUserQry" datasource="cf_userMan">
select
fld_userFirstName, fld_userLastName
from users
where
fld_userLastName like '%#arguments.lastName#%'
<cfif arguments.firstName neq "">
and fld_userFirstName like '%#arguments.firstName#%'
</cfif>
</cfquery>
<cfreturn SearchUserQry />
</cffunction>
Stage 4: Lets write some Flex code
In this stage we are going to break the 5 operations into 5 simple steps. We are going to start with a simple load screen, then a simple search operation, then move on to a creation operation, then to our display/update operation and lastly we are going to write out delete operation.
Before we start to write any code we need to setup our file structure. In your project directory root, create a new folder called custom (fig 3). This is where we will store all the custom flex components that we will create in this stage. Inside the custom folder you just created, create another folder called as (fig 4). This is where we will store all our external action script files.


Step 1: In this step we are going to create a simple loading screen to handle all of our custom components. This screen will allow us to load all of our search screens, add user, edit user, and delete user screens.
So here we go. Starting off, we are going to open the Flex file we created at the start of this tutorial. Now that we have it open lets start modifying it.
This is our complete userManager.mxml file. In the mx:Application tag you will see the defined named spaces. These are qualified by the xmlns attribute. By default, we have the standard Adobe name space (xmlns:mx="http://www.adobe.com/2006/mxml"). This default xmlns allows you refer to more than one set of XML tags in the same XML document. Next, notice that there is another xmlns tag defined. This is our name space to our custom components that we will create further on in this tutorial (xmlns:custom="custom.*"). This will allow us to make custom tag calls with in the Flex application.
The last important thing to note is out first custom component call we will make. On line 3 we have a new tag to use, the tag uses the tag root custom which matches up with the name space we created in our Application tag.
This is all we will do with our userManager.mxml file. As far as we are concerned this file is complete.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:custom="custom.*" layout="absolute">
<custom:userSearch />
</mx:Application>
Step 2: User Search Operation
In this step we are going to write a complete user search screen from start to finish. Starting off we are going to create our layout of the screen. This includes our search inputs, buttons, and our display data grid.
Step 2a: Creating our first custom component - User Search
This step is the beginning of our Flex development. In this step we will create our user search screen. First we need to create a new Flex Component. To do this, go to file > new> MXML Component. This will bring up the screen you see in fig 5. Select the project UserManager, then select the folder custom. Name the file userSearch, change the based on drop down to Panel, leave the layout set to absolute and set the width and height to 100%.
Your New MXML Component screen show look like fig 6. Once this is done click okay, and you have just created your first Flex component.


Now that our component has been created, lets get into the fun stuff of building our first set of custom components. We will create forms, text inputs, buttons, and display data grids. This can be done in two ways. You can drag and drop your Flex components from the components panel(fig 7), or you can hand code the inputs.
####IMAGE HERE - Fig 7#####
As with our userManager.mxml file, you will notice that we have a lot of the same code here aside from the Application tag is replaced with the Panel tag. The panel tag allows us to create various form components, image components and other fun flex components in a easy to use and simple interface.
First thing we need to do is add a title to the panel, this will allow us to show the user what they are viewing. We are going to name our panel User Search.
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%" title="User Search">
</mx:Panel>
Now that we have our base display component created, we need to add some form in