Archive for the 'Flex' Category

Add a database record with Flex 3 & Coldfusion

Continuing my work towards a very simple Flex 3/Coldfusion CRUD tutorial, I’ve completed my installment covering adding a new record to a database.  Lets go:

For starters, I am using the same Coldfusion Component I have used in all of my examples.  This time I have added a method called InsertEmployee to insert new records.  The complete CFC now looks like this:

<cfcomponent>
   <cfset dataSrc = “mydatasource”>

   <cffunction name=”InsertEmployee” access=”remote” returntype=”void” output=”no”>
      <cfargument name=”firstName” required=”yes” type=”string”>
      <cfargument name=”lastName” required=”yes” type=”string”>
      <cfargument name=”officePhone” required=”yes” type=”string”>
       <cfquery name=”addEmp” datasource=”#dataSrc#”>
         INSERT INTO employees (firstName, lastName, officePhone)
           VALUES (‘#firstName#’,'#lastName#’,'#officePhone#’)
      </cfquery>
   </cffunction>

   <cffunction name=”FindAll” access=”remote” returntype=”xml” output=”no”>
       <cfquery name=”getEmp” datasource=”#dataSrc#”>
         SELECT firstName, lastName, officePhone, id
           FROM employees
      </cfquery>
      <!— Convert Query to xml —>
      <cfprocessingdirective suppresswhitespace=”Yes”>
      <cfcontent type=”text/xml; charset=utf-8″>
      <cfxml variable=”xmlobject”> �
      <response>
         <data>
      <cfoutput query=”getEmp”>
         <row>
            <id>#id#</id>
            <firstName>#firstName#</firstName>
            <lastName>#lastName#</lastName>
            <officePhone>#officePhone#</officePhone>
          </row>
      </cfoutput>
         </data>
      </response>
      </cfxml>
      <!— Convert back to a string —>
      <cfset myvar=toString(xmlobject)>
      </cfprocessingdirective>
      <cfreturn myvar>
   </cffunction>
</cfcomponent> 

Now we just need our MXML application.  I’ve created a very simple form, nothing more.  It beings with our opening <mx:Application> tag followed by the actual form:

 <mx:Form width=”279” x=”24” y=”24>
<mx:HBox horizontalGap=”8>
  <mx:Label text=”First Name />
  <mx:TextInput id=”firstName/>
</mx:HBox>
<mx:HBox>
  <mx:Label text=”Last Name />
  <mx:TextInput id=”lastName/>
</mx:HBox>
<mx:HBox>
  <mx:Label text=”Office Phone/>
  <mx:TextInput id=”officePhone/>
</mx:HBox>
  <mx:Button label=”Submit” click=”clickHandler()”/>
</mx:Form>

Nothing special here, I’ve placed each Label and Textinput inside their own HBox only because that is now I saw it done someplace else.  Layout really means nothing for this example so lay it out however you want, you really only need the start and ending <mx:Form> tags and the <mx:TextInput> tags. 

Next we call our web service which is our Coldfusion CFC listed at the top of the article:

<mx:WebService id=”userRequest” wsdl=”http://brad.melendy.com/projects/webservice/employees.cfc?wsdl>
  <mx:operation name=”InsertEmployee” fault=”mx.controls.Alert.show(event.fault.faultString)”/>
</mx:WebService>

Notice that in this case, rather than passing the method name in the URL with the <mx:HTTPService> tag, I’m using the <mx:WebService> tag, passing the web service in WSDL format and telling it the method to execute in the <mx:operation> tag. 

The last step is our ActionScript:

<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function clickHandler():void {
userRequest.InsertEmployee(firstName.text, lastName.text, officePhone.text);
firstName.text =
"";
lastName.text =
"";
officePhone.text =
"";
Alert.show(
'Record Inserted!', 'Alert Box', mx.controls.Alert.OK);
}
]]>
</mx:Script>

 The only code library I import is mx.controls.Alert for my confirmation alert at the end of the script.  Then I simply call the InsertEmployee method from the userRequest object, passing the text from my three TextInput controls.  Next I blank out the contents of each TextInput and finally pop an alert that the record has been inserted.  The result produces this form:

This is very simple, there is no error trapping or validation as we are just demonstrating the act of getting a record from a Flex form into a database using Coldfusion as the server side platform.  You can see the results here:

Populate a Flex DataGrid from XML

This was the next step toward a FLEX crud application that I wanted to document.  I find that in addition to potentially helping others to learn, I retain much more when I spend the time to explain how these things are done.  So today, we will read the XML I produced using Coldfusion in my previous posting and display it in a Flex DataGrid control.  So lets get started. 

I’m going to assume you know how to start up Flex Builder and create a new Flex project or MXML application.  We have three core steps to populate our DataGrid;

  1. Call our XML document via the Flex HTTPService 
  2. Add our DataGrid control
  3. Write some ActionScript to pump the data from the HTTPService into the DataGrid

So get to a new MXML document and we’ll begin by adding our HTTPService after your opening <mx:Application> tag.  It should look like this:

 <mx:HTTPService result=”handleXML(event);” id=”xmlGet” resultFormat=”e4xurl=”http://brad.melendy.com/projects/webservice/employees.cfc?method=findAll/>         

I’m using the XML trailing slash notation because I don’t have any arguments to pass.  If I had arguments to send, I’d need to include them between opening and then a closing </HTTPService> tag.  Here we have only a result function (yet to be written), an id by which to reference the HTTPService (make up your own name), resultFormat which needs to be “e4x” and finally the URL.  e4x will give us all the pre-built functions Flex has for working with XML. The URL is straight forward enough.  In my case, I’m referencing a Coldfusion Component that generates XML on the fly from a database.  It could just as easily be a static XML document residing on a web server. 

Next, add your data grid control which will look like this:

<mx:DataGrid dataProvider=”{employeeInfo}” width=”400” height=”200” id=”employeeList” editable=”false” enabled=”true>
  <mx:columns>
    <mx:DataGridColumn headerText=”First Name” dataField=”firstName/>
    <mx:DataGridColumn headerText=”Last Name” dataField=”lastName/>
    <mx:DataGridColumn headerText=”Office Phone” dataField=”officePhone/>
  </mx:columns>
</mx:DataGrid> 

 Notice I already have a dataProvider.  It doesn’t yet exist, but I know that is what I am going to name it when I create it and I don’t really want to post duplicate lines of code save for one minor change.  I already know what my XML document looks like and that I have three elements, First, Last and Phone.  I tell it the width and height I want for my grid, it won’t be editable and it will be enabled.  So lets create the dataProvider employeeInfo we just referenced in our DataGrid.

At this point we need some action script to funnel the data from our XML to the DataGrid.  Lets examine the following code:

<mx:Script>
  <![CDATA[
  import mx.rpc.events.ResultEvent;
  [
Bindable]
  private var employeeInfo:XMLList;
  public function handleXML(event:ResultEvent): void
    {
      employeeInfo = event.result.data.row
as XMLList;
    }
  ]]>
</mx:Script>

Here we do several things, we import mx.rpc.events.ResultEvent as we need that for the HTTPService “result=” argument, which is how we instruct the service what action we want it to take once it has read in our XML.  Next we create a bindable private var employeeInfo of type XMLList.  In our only function called handleXML, we pass it the result from our HTTPService which is dealing with an XML formate “e4x” and will be held in employeeInfo as XMLList.  Now you see our dataProvider, employeeInfo of type XMLList. 

NOTE: you must know the names of the various nodes in your XML document so you can properly assign the node that has your records in it.  In this case, it is “data.row” making the complete assignment line, “employeeInfo = event.result.data.row as XMLList;”.

 Our last and final step is adding an argument to our opening <mx:Application> tag.  We need to use creationComplete=”" to tell our application what to do when it loads.  Here is what the <mx:Application> tag should look like:

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” viewSourceURL=”srcview/index.html” creationComplete=”xmlGet.send();”>

creationComplete will execute “xmlGet.send();” on application load.  In this case, xmlGet is the id of our HTTPService and we tell it to execute the existing send() method which tells it to get the XML in our URL.  The result agument of the HTTPService then calls the handleXML() function which finally creates the dataProvider for our DataGrid control.  The DataGrid control just waits for data to come in from the dataProvider and finally we get a nice grid of data:

The source code is available here.  This is a very simple example, but I wanted to break it down to a very low level.  Getting data and sticking it in a DataGrid is probably one of the most basic, yet most used tasks in Flex applications.  Next I’ll write up inserting data.

Playing with Flex Builder 3

So I recently downloaded Flex Builder 3 in an effort to broaden my horizons a bit. This is really my first exposure to Flex and I must say I’m pleasantly surprised with what it can do. However, there to is a dark side to this product. I found the number of well documented examples to learn from on the weak side. Being that the core of what I do with applications is create interfaces to databases, I wanted to do the same thing with Flex. I found an abysmal number of examples on the web and those I did find all seemed to have some kind of problem or another that wouldn’t work in my environment. In the end, I got the Adobe Coldfusion/Flex Data tutorial to work but there were mixed results.

It worked great from the get go on my localhost (Windows Vista with CF8/Apache/MySQL) but trying to deploy to a test Linux server failed badly in one instance and worked great on another (the difference being the version of Linux in use). It also worked well deployed on my shared host which runs on a Windows server with CF8/IIS. There were lots of steps I had to do over and over in the project setup of Flex Builder and of course you need to ensure your Coldfusion server is set to support Flash Remoting at the least. I will likely produce a step by step tutorial as time permits but for now the working example will have to do:

http://brad.melendy.com/projects/flex/DataTest4/DataTest4.html

You can right click the application and choose VIEW SOURCE to see exactly what it takes, the primary components are DataTest4.mxml, EmployeesCRUD.as and employees.cfc. Since Flex apps must get all their data from XML, the CFC acts as a middle man between the application and the database. I hope to begin a real application at work using Flex in the next couple months and I’ll try to document any technical pitfalls or discoveries here.