Flash Remoting in over ten minutes

This tutorial will take a more in depth look at the functionality of Flash Remoting with ColdFusion MX. In this tutorial, we will learn how to retrieve and assign a recordSet from a database to a listBox component. We will learn how to retrieve the details of a specific record from the database based on our listBox selection. We will learn how to add our own entry into the database. We will learn how to delete an entry from the database. We will learn how to sort this list by date, with the option of sorting by name as well. 

This tutorial will take approximately one hour to complete. Source files are available for download at:

http://www.flashgoddess.com/tutorials/Remoting2.zip

SETUP:
You will need to have Flash Remoting installed for this tutorial. You will need CFMX Server installed. You will need Flash 6. You will need MS Access or SQL. If you are not sure how to set these up, please refer to the Flash Remoting in Ten Minutes tutorial on this site, as it covers these topic thoroughly.

NOTE ON MS SQL:

We did not cover how to setup MS SQL in our previous tutorial. Included in the zip package for this tutorial is a SQL script file. Please refer to the link below for instructions on how to use this script to setup your SQL database:

http://tutorial64.easycfm.com/ Thank you, Alex.

PART 1: THE BACKEND
For those of you familiar with my tutorials, or work practices, you will know I always build the backend first. 

We start by creating an Access database. I saved the file as myMovieDB.mdb. There is one table only in this database, called movieArchive. This table has four fields, ID which is an autonumber and our primary key, movieTitle which holds the title of our movie, movieDesc which is the brief description of our movie, and movieDate which is the time we inserted the record into the database.

In our ColdFusion Administrator, we setup a datasource called moviesDB, and point it to MovieDB.mdb. 

PART 2: Middleware
Continuing with my preferred process of working from backend to frontend, we create the ColdFusion Component (CFC) that we will use to handle all of the transactions between Flash and our database.

We setup our component, just as we did in the previous tutorial:

<cfcomponent hint="Provides all data about the movies.">

Then declare our first of many functions. There is one function to handle each different type of transaction we will be performing against our database. In the previous tutorial, we only had one function. Don?t be hesitant, as this tutorial follows the exact same logic and syntax as the previous. We are merely expanding our knowledge of how to use Remoting effectively in this tutorial.

The first thing we want to do is send all the records of the database back to Flash, so we can populate our listBox.

<cffunction name="MovieRecordSetProvider" hint="Returns an array to populate the listBox." returntype="query"
access=
"remote">
<!--- Query the database for story records --->
<CFQUERY NAME="listQuery" DATASOURCE="moviesDB">
    SELECT * 
    FROM movieArchive
    ORDER BY movieDate DESC
</CFQUERY>
<CFRETURN listQuery>
</cffunction>

That is where we finished off in our last tutorial. 

Now we are going to add some robust functionality to this project. Once our user selects an item from the listBox, we want to retrieve and return all the information in the database associated with that record.

<cffunction
    name=
"movieDetailProvider"
    hint=
"Returns the details of the selected movie."
    returntype=
"query"
    access=
"remote">
<cfargument name="movieID" type="numeric" required="true" default="0">
<CFQUERY NAME="detailQuery" DATASOURCE="moviesDB" MAXROWS="1">

    SELECT        *
    FROM           movieArchive
   
WHERE         ID = #arguments.movieID# 
</CFQUERY>
<CFreturn detailQuery>
</cffunction>

Again, the logic should seem almost identical to the previous function. The only that really changes is the use of arguments within the SQL statement. The argument #movieID# is actually sent to this function from Flash, and you will notice that in part three of this tutorial.

Now we add the ability to submit an entry to the database.

<cffunction name="movieSubmissionProvider" hint="Submits the movie with details to the database"
returntype=
"any" access="remote">
<cfargument name=
"title" type="any" required="true" default="0">
<cfargument name=
"review" type="any" required="true" default="0">
<cfquery name=
"doInsertSQL" datasource="moviesDB">
    INSERT INTO movieArchive(movieTitle, movieDesc, movieDate)
    values('#arguments.title#','#arguments.review#', #CreateODBCDateTime(Now())#);
</cfquery>
</cffunction>

Again, it follows the same type of format as before. We have added a couple of more arguments, passed from Flash, and also an interesting internal function within CFMX, namely #CreateODBCDateTime(Now())#. This command will insert the very minute we inserted the record into the database. This is helpful in our earlier function, MovieRecordSetProvider, as we are sorting by this value in our listBox.

Finally, we wish to be able to delete an entry from the database.

<cffunction name="movieDeleteProvider" hint="Delete the selected movie from the database." returntype="any"
access=
"remote">
<cfargument name=
"movieID" type="any" required="true" default="0">
<CFQUERY NAME=
"delQuery" DATASOURCE="moviesDB" MAXROWS="1">
    DELETE
   
FROM        movieArchive
    WHERE      ID = #arguments.movieID#
</CFQUERY>
</cffunction>
</cfcomponent>


Moving on!



PART 3: THE FLASH
A special note at this point. If instead of building a Flash front end, we built some sample ColdFusion pages, we could test our progress at this point to ensure everything works correctly. I have included a bonus file, testHarness.cfm, which I often use to test my functionality before I ever get to Flash. Always good to make sure it works before moving on. I won?t be going into the details of testHarness in this tutorial.

As always, we include the standard stored procedures we need for remoting.

#include "NetServices.as"
#include "Dataglue.as"

// uncomment this line when you want to use the NetConnect debugger
//#include "NetDebug.as" 


And we always include our customary link to Diaries of War?

warBut.useHandCursor = 0;
warBut.onRelease = function() {
getURL("http://www.diariesofwar.com", "_blank");
};


Next, we define the functions that will handle our user interaction events.

function movieListChanged() {
    myService.movieDetailProvider({movieID:movieSelector.getValue()});
    errormessage.text = "";
}

The preceding function is triggered whenever an item in the listBox is selected. It retrieves the selected value, and passes it as movieID to our CFFunction, which, as you remember, is waiting for that argument to be used against the database.

Next, we do the function that will submit the information we wish to be added to the database.

function movieAddReady() {
    myService.movieSubmissionProvider({title:movieTitle.text, review:movieDetail.text});
}

Again, the code should seem familiar, as we are building on preceding examples every time. We are passing the values of two text fields to our CFFunction, giving them the argument names of title and review.



Now we are going to pass the information of the record we wish to delete.

function movieDeleteReady() {
    myService.movieDeleteProvider({movieID:movieSelector.getSelectedItem().data});
}

Again, whichever item is selected in the listBox is passed as the movieID variable because that is the record we have chosen to delete.

Now onto to the functions that handle data coming in from the server.

This is the function that populates the listBox using DataGlue, our best friend in remoting.

function MovieRecordSetProvider_Result(result) {
    movieSelector.removeAll();
    DataGlue.bindFormatStrings(movieSelector, result, "#movieTitle#", "#ID#");
}

It receives the values of movieTitle and ID, binding those to the label and data fields of our listBox.

Next, we want to display the results of our detail query.

function movieDetailProvider_Result(result) {
    var detailRecord = result.getItemAt(0);
    movieDetail.text = detailRecord.movieDesc;
    movieTitle.text = detailRecord.movieTitle;
}

result is a keyword in remoting. We can always request that it be returned to us from the server. It can be anything from a singular value, to an array, to a recordSet. It is very versatile. In this case, we grab array, which will consist of the movieDesc field for that item, and the movieTitle field, and assign those values to the textfields we have setup in Flash.

We are almost done. What do we want to do when we have successfully added our new record to the database? Well, we want to update the list, and let the user know it was added. This function handles all of that easily.

function movieSubmissionProvider_Result() {
    errormessage.text = "Successfully entered.";
    myService.movieRecordSetProvider();
}

By the same logic, we should do the same when we have successfully deleted a record.

function movieDeleteProvider_Result(result) {
    errormessage.text = "Deleted successfully";
    movieTitle.text = movieDetail.text="";
    myService.movieRecordSetProvider();
}

We are done with our handling functions. Whew!

This next bit of code handles the Flash Remoting initialization, and is only run once.

if (inited == null) {
    // do this code only once
    inited = true;
    // set the default gateway URL (this is used only in authoring)
    NetServices.setDefaultGatewayUrl("http://localhost/flashservices/gateway");
    // connect to the gateway
    gateway_conn = NetServices.createGatewayConnection();
    // get a reference to a service
    myService = gateway_conn.getService("Remoting.transactions", this);
    myService.MovieRecordSetProvider();
}
stop();

And that?s it. We now have a complete application that can interact with a database in all of the basic ways we would require. I hope you had as much fun as I did. For an example of this in action, please visit the submissions section of www.wheniwas19.com And yes, there is more going on there than here, but it is still pretty cool.

About This Tutorial
Author: Marcus J. Dickinson
Skill Level: Intermediate 
 
 
 
Platforms Tested: CFMX
Total Views: 75,792
Submission Date: May 14, 2003
Last Update Date: June 05, 2009
All Tutorials By This Autor: 4
Discuss This Tutorial
  • I keep getting an error in the listBox, "undefined"???? I am seeing the movieTitle followed by "undefined". Anyone know why this happens? Thanks!

  • Thankyou Its been a great help

Advertisement


Website Designed and Developed by Pablo Varando.