View comments | RSS feed

Working with RecordSet objects

Using Flash Remoting MX, you can return RecordSet objects from application servers, manipulate the records in the RecordSet object, and display information from the records in a Flash application. Typically, application servers create record sets from the results of a database query. Some of the uses for RecordSet objects in ActionScript include the following:

About record sets

A record set is a two-dimensional data table. The rows of the table correspond to individual data records, such as the data for a particular product or employee. The columns of the table correspond to different fields of a record, such as an employee's title or a product color. The following table shows a sample record set structure:
lastName
firstName
emailAddress
telExt
Smith
Dave
dave.tomlin@macromedia.com
3456
Basham
Meredith
meredith.neville@macromedia.com
7890
Card
Sean
sean.carr@macromedia.com
1234
Randolph
Themis
themis.cripps@macromedia.com
5678
Sykes
Andrew
andrew.gruber@macromedia.com
9012

A RecordSet object represents a record set in Flash. It contains the following elements:

Note:   For information on pageable record sets, see "Delivering RecordSet data to Flash applications in ColdFusion MX".

Typically, service functions return RecordSet objects to your Flash application. However, you can also use ActionScript RecordSet methods to create and manage record sets directly in ActionScript. The ability to create a RecordSet object enables you to create custom client-side data structures for use in Flash UI Components. For more information on using RecordSet methods, see the following section, "RecordSet methods" .

You access record set rows using the row index, much like in an array. The first record is at index 0, the second record is at index 1, and so on. Record indexes are relative. If you insert a record into a record set, all the indexes of all records in the RecordSet object starting with the index at which you insert the new record get incremented by one.

RecordSet object records also have unique IDs that are never changed. If you insert a record in a RecordSet object, it gets a new unique ID and all other record IDs are unchanged. If you delete a record, its ID is deleted and is not reused. Flash Remoting MX uses this ID internally, and you cannot use it to access a record, but you can use the RecordSet.getItemID method to determine the ID for any record.

Note:   You cannot send RecordSet objects to the application server.

RecordSet methods

You can use the following methods to create and manage RecordSet objects
Method
Description
Constructor for RecordSet
Creates a new local RecordSet object.
RecordSet.addItem
Inserts a record into the RecordSet object.
RecordSet.addItemAt
Inserts a record into the RecordSet object at the specified index.
RecordSet.addView
Defines an object that will receive notifications when the RecordSet object changes.
RecordSet.filter
Creates a new RecordSet object that contains selected records from the original RecordSet object.
RecordSet.getColumnNames
Returns the names of all the columns of a RecordSet object.
RecordSet.getItemAt
Returns a record if the index is valid and the record is available.
RecordSet.getItemID
Returns the record ID of a record.
RecordSet.getLength
Returns the number of records in a RecordSet object.
RecordSet.getNumberAvailable
Returns the number of records that have been downloaded from the server.
RecordSet.isFullyPopulated
RecordSet.isLocal
Determine whether a RecordSet object is fully available on the client system. (Both methods are equivalent.)
RecordSet.removeAll
Removes all records from the RecordSet object.
RecordSet.removeItemAt
Removes the specified record from the RecordSet object.
RecordSet.replaceItemAt
Replaces a record at the specified index.
RecordSet.setDeliveryMode
Changes the delivery mode of a pageable record set from an application server.
RecordSet.setField
Replaces one field of a record with a new value.
RecordSet.sort
Sorts all the records using a comparison function that you specify as an argument to the method.
RecordSet.sortItemsBy
Sorts all records in the RecordSet object in ascending or descending order, according to the current locale's sorting order.

The following sections describe how you can use these methods to create and manage RecordSet objects in ActionScript code.

Using RecordSet methods and properties

The following sections describe how to use RecordSet methods to manage RecordSet objects.

Creating RecordSet objects

Most RecordSet objects are returned by service functions, so you do not typically have to create them. However, you can use the RecordSet object constructor to create a record set directly in ActionScript. For example, the following line creates a new RecordSet object with two columns: DepartmentID and DepartmentName. This RecordSet object does not contain any data:

myRecordSet = new RecordSet(["DepartmentID", "DepartmentName"]);

Getting values and information from RecordSet objects

The following sections describe how to get record set values and information.

Getting record set data values

To get a specific record in the RecordSet object, specify the record's 0-based index in the getItemAt method. For example, the following line gets the third record in a record set:

myRecord = myRecordSet.getItemAt(2);

To get the value of a specific field in a record, use the column name as a property of the record. For example, use the following line to get the value of the DepartmentName field of the fourth record in the RecordSet object named myRecordSet:

myDept = myRecordSet.getItemAt(3).DepartmentName;

Note:   Because the RecordSet object is a subclass of the ActionScript DataProvider class, you can also use RecordSet objects directly with any object that takes a DataProvider, such as the ComboBox Flash UI Component. For more information on using RecordSet objects with Flash UI components, see "Using Flash MX UI components with RecordSet objects".

Getting information about a RecordSet object

To get information about a RecordSet object, use the following methods:
Method
Description
RecordSet.getColumnNames
Returns an array of the names of the columns of a RecordSet object.
RecordSet.getItemID
Returns the record ID used internally by Flash Remoting MX to identify the record.
RecordSet.getLength
Returns the number of records in a RecordSet object.
RecordSet.getNumberAvailable
Returns the number of records that have been downloaded from the server.
RecordSet.isFullyPopulated
RecordSet.isLocal
Returns true if the RecordSet object was created locally using the New operator or if the record set was returned by a Flash Remoting service function and all the data in the record set has been returned from the server.
A RecordSet object must be fully populated before you can change its contents or use the RecordSet.filter method.
These two methods are currently equivalent.

In the following example, theRecordSet represents a RecordSet object:

//Get an array of the column names and convert it to a comma delmited list
columns = theRecordSet.getColumnNames().join();
//The total number of records in the RecordSet
recordcount = theRecordSet.getLength();
//The number of records that are currently available to the Flash client
recordsavail = theRecordSet.getNumberAvailable();
//Have all the records been returned? (Only true if recordcount == recordsavail)
allthere = theRecordSet.isFullyPopulated();

Changing record set data

After you download all records into the RecordSet object or create a new RecordSet object in ActionScript, you can use the RecordSet ActionScript class data-editing methods to insert, update, and remove records. Changes to the RecordSet object in the Flash application are not propagated back to the application server. To insert, update, or remove records in a database, you must call application server methods or pages using service functions.

Adding records to the RecordSet object

To add items to a RecordSet object, use the addItem or addItemAt methods. The addItem method adds a record at the end of the record set. The addItemAt method inserts a record at the specific index location; the indexes of all the other records in the RecordSet object are automatically incremented by one. For example, the following adds a single record at the beginning of the myRecordSet object:

var newRecord = {DepartmentID: "BA1EA7FF0-7D79-32D3-A9280050042189548",
    DepartmentName: "Technical Publications"};
myRecordSet.addItemAt(0, newRecord);

Removing records from the RecordSet object

To remove records from a RecordSet object, use the removeItemAt and removeAll methods. The removeItemAt method removes a record at a specific index location, and the removeAll method removes all records from the RecordSet object. For example, the following line removes the record at the first index location (0). The indexes of all the other records in the RecordSet object are automatically decremented by one:

theRecordSet.removeItemAt(0);

Replacing and renaming records in the RecordSet object

To replace a record in a RecordSet object, you use the replaceItemAt method. To replace a specific field in a record in a RecordSet object, use the setField method. For example, the following code replaces the contents of the third record in the theRecordSet RecordSet object with the contents of the newRecord variable. It then replaces the contents of the third record's DepartmentName field:

var newRecord = {DepartmentID: "BA1EA720-7D79-11D3-A9280050042189548",
  DepartmentName: "Complaints";
theRecordSet.replaceItemAt(2, newRecord);
theRecordSet.setField(2,"DepartmentName","Compliments");

Using notifications with RecordSet objects

You can notify any ActionScript object of changes in a RecordSet object's internal state. For example, if you associate a RecordSet object with a ListBox component, and the record set gets sorted into a different order, Flash can notify the ListBox component that the record order changed, so the ListBox component can redraw itself according to the new order.

Similarly, a RecordSet object can notify its associated ListBox component when all records arrive from the server. Then, if required, the ListBox can redraw itself to update its display.

Note:   Flash UI components such as ListBox incorporate notifications as a standard part of their use of the RecordSet ActionScript class. The addView method is only necessary if you need to receive notifications in your own ActionScript code, for example, if you create your own UI component.

To set up a notification event for an ActionScript object, use the RecordSet addView method and specify the object to notify when the RecordSet object changes. You can specify any object that receives change notifications in the addView method, as in the following example:

myRecordSet.addView(contact_grid);

In this example, the myRecordSet object represents a record set returned from Flash Remoting MX, and the addView method tells Flash Remoting MX to notify the contact_grid object whenever the theRecordSet object changes.

The object that receives the notification must include a modelChanged callback function to handle the notification. Whenever the RecordSet object changes, the modelChanged function gets called with a message object that consists of one or more entries, as follows:

The following table describes the event messages:
Message object
Description
{event: "sort"}
The RecordSet object has been sorted.
{event:"updateAll"}
The RecordSet object has changed in some way, such as a new view being added.
{event:"addRows", firstRow:xxx, lastRow:yyy}
Row numbers xxx through yyy have been added.
{event:"updateRows", firstRow:xxx, lastRow:yyy} 
Row numbers xxx through yyy have changed in some way.
{event:"allRows"}
All records have arrived from the server.
{event:"fetchrows", firstRow:xxx, lastRow:yyy}
Row numbers xxx through yyy have been requested from the server, but have not arrived yet.

The following example creates a modelChanged function that displays a trace message with the event type and sets it up as the callback handler for changes to the myRecordSet object:

function modelChanged(info)
{
  trace("Caught modelChanged event: " + info.event);
}

myRecordSet = new RecordSet(["DepartmentID", "DepartmentName"]);
myRecordSet.AddView(this);

Sorting and filtering record sets

The RecordSet class has methods for sorting an existing RecordSet object or creating a new RecordSet object from an existing one by applying a selection (filter) function.

Sorting record sets

To sort the records of a RecordSet object, use the sort and sortItemBy methods. The sortItemBy method performs an ascending (the default) or descending sort on the records in the RecordSet object. The sort method requires a comparison function as an argument, and uses that function to sort the records. The sort method can be substantially slower than the sortItemBy method.

Sorting a RecordSet object changes the order of the records in the object, but does not otherwise change the object. Subsequent getItemAt method calls return records according to the new order. After you sort a RecordSet object that was returned from an application, the object no longer reflects the order of the records on the server-side record set.

The following one-line example sorts the myRecordSet object according to the value of the DepartmentName field in descending order:

myRecordSet.SortItemsBy("DepartmentName", "DESC")

The following example shows how you can create a function that sorts the contents of a ListBox UI component:

function SortBy(sorter) 
{
  temp = sorter.getSelectedItem();
  sort_this = temp.data;
  theRecordSet.sortItemsBy(sort_this);
}

In this example, sorter represents a ListBox UI component in the Flash application. In the sortBy function, the getSelectedItem method returns the item selected in the ListBox. Next, the function assigns the selected item to the sort_this variable. Finally, the sortItemsBy method sorts the records according to the contents of the sort_this variable. For an example of using the sort method, see "RecordSet.sort".

Note:   For RecordSet objects containing 2,000 or fewer records, the sort method generally takes less than one second to finish on a Pentium 3 computer. The length of time to sort RecordSet objects increases rapidly as the number of records grows.

Filtering an existing RecordSet object to create a new RecordSet object

The filter method creates a filtered view of a RecordSet object that contains only records that conform to a set of rules specified by a selection (filter) function that you define. Unlike the sort method, the filter method creates a new RecordSet object. The original RecordSet object and its records remain unchanged.

The selection function that you define takes a record as the first argument, and can optionally take a second argument to use to determine how to select the records. The function must return a Boolean true or false value. Flash Remoting MX includes records for which the selection function returns true in the filtered RecordSet object. When you call the filter method, you pass it your selection function and, optionally, the value to use as the selection function's second argument.

The following example filters a RecordSet object to produce a new RecordSet object with records that have contact fields that start with a specific letter:

var mySelectionFunction = function(aRecord, letter) 
{
  return (aRecord.contact.charAt(0) == letter);
}
contact_grid.setDataProvider(myRecordSet.filter(mySelectionFunction, theLetter));

In this example:

Note:   For RecordSet objects that with 2,000 or fewer records, the filter method generally takes less than one second to finish on a Pentium 3 computer. The length of time to filter RecordSet objects increases rapidly as the number of records grows.

Delivering RecordSet data to Flash applications in ColdFusion MX

By default, Flash Remoting MX returns a RecordSet object to the Flash client in a single response when the application server finishes retrieving the data.

In ColdFusion MX, if you expect to return a large record set and the available data transmission speeds are slow, such as when using dial-up modem, you can choose to return a record set from the application server in increments. Incremental record sets are also known as pageable record sets.

When you use pageable record sets, the following events occur:

Flash Remoting MX can deliver pageable record set data to your application in three modes, as described in the following table:
Data delivery
modes

Description
ondemand
(default)
When you access a particular record using the getItemAt method, the RecordSet object requests the record from the server-side Flash Remoting RecordSet service.
page
When you use the getItemAt method to access a record, the RecordSet object fetches data one or more pages at a time.
You specify the number of records per page when you set the delivery mode. The default page size is 25 records.
You can also tell Flash Remoting MX to get, or prefetch, a number of pages of data that follow the page that contains the requested data. Flash Remoting MX will store these additional pages in the client if it has not already fetched them in a previous request. The default prefetch value is 0 (only get the page with the requested data).
For example, if you specify a page size of 15 records and a number of pages to prefetch of 3, Flash Remoting MX automatically fetches 45 records when you make your first request for a record in the data set. If you then request a record on the second page that was returned, Flash Remoting MX prefetches an additional 15 records.
fetchall
As a background activity, the RecordSet object fetches the entire contents of the record set from the server, starting when the service function that retrieves the record set on the application server returns.
You can specify a page size when you set the delivery mode to fetchall. Flash Remoting continues requesting one page at a time from the server until all pages have been returned. The default page size is 25 records.

You change a RecordSet object's delivery mode by calling the setDeliveryMode method, as in the following example:

if (config_panel.deliveryMode.getData() == "page") 
{
  theRecordSet.setDeliveryMode("page", contact_grid.getRowCount(), 1);
}
else if (config_panel.deliveryMode.getData() == "fetchall") 
{
  theRecordSet.setDeliveryMode("fetchall", 10);
}
else 
{
  theRecordSet.setDeliveryMode("ondemand");      
}

In this example, theRecordSet object represents the record set returned from Flash Remoting MX, and the config_panel object represents a Flash movie clip. Using the deliveryMode.getData method, the code evaluates the delivery mode specified by config_panel, and uses the setDeliveryMode method to set the mode of delivery for the theRecordSet object.

If the config_panel object specifies page mode, the setDeliveryMode method tells Flash Remoting MX to set the page size to the number of rows in the contact_grid movie clip and to prefetch one additional page beyond the page with the requested data, if it is not is not in memory.

If the config_panel object specifies fetchall mode, the setDeliveryMode method tells Flash Remoting MX to set the page size to 10 records and start getting the records, one page at a time (if they are not already on the client), until the entire record set has been fetched.

For all delivery modes, after a record is received from the application server, it is held inside the RecordSet object. Any subsequent getItemAt calls immediately return the record. Any getItemAt calls for records that the client has not yet received fetch the requested record as soon as possible and return a fetch pending message.

Using Flash MX UI components with RecordSet objects

Many Flash MX UI components can use RecordSet objects to provide both label and data information. These components use Flash DataProvider objects to supply the following information:

Objects that can use DataProvider objects are often referred to as data consumers Flash components that can be data consumers currently include the following:
Standard Flash UI components


FListBox
FComboBox
Flash UI Components Set 2


FTicker
FTreeNode
FTree


Charting Components


FBarChart
FPieChart
FLineChart


The Flash UI Components Set 2 and Charting components are downloadable from the Flash exchange at http://dynamic.macromedia.com/bin/MM/exchange/main.jsp?product=flash.) Additional UI objects might be available at the Macromedia Flash Exchange.

The following sections describe how to use the RecordSet objects with these components.

Using RecordSet objects directly

You can use RecordSet objects directly in the setDataProvider method of a data consumer component to specify that the RecordSet object provides the component's values.

The following example is a result handler for a getProductList service function that gets a single-column record set that contains product names. It populates a ListBox component with the returned RecordSet object's records:

function getProductList_Result (result)
{
    catalogListBox.setDataProvider(result);
}
catalogService.getProductList();

By default, each label value is a comma-delimited string that consists of the contents of one record's fields; the data values do not get set. However, you can use a RecordSet object directly in the setDataProvider method to provide both the list and data values if the record set has two columns and the column names are label and data. For example, the following SQL code produces a record set that, when passed to the preceding getProductList_Result function, populates the catalogListBox object with both label and data values:

SELECT COST_CENTER AS DATA, DESCRIPTION AS LABEL
     FROM EMPDB_DEPARTMENT 
     WHERE STATUS='Active'

Using DataGlue methods

The DataGlue methods, bindFormatStrings and bindFormatFunction, let you specify how a RecordSet object supplies the contents of both the data and value fields of a data consumer. The DataGlue methods provide substantial flexibility in formatting the contents of the labels and data, as follows:

The DataGlue methods do not make a copy of the DataProvider object. However, the data is fetched from the data provider as needed by the component.

Using the bindFormatStrings method

The bindFormatStrings method lets you freely format record fields and string data. For example, the following method uses values from two fields to generate the labels and from three fields to generate the data values:

DataGlue.bindFormatStrings (myComboBox, myRecordSet, "#parkname# (#parktype#)", "#city#, #state# #zipcode#");

In this example, myComboBox represents a ComboBox component in the Flash application, and myRecordSet represents the RecordSet object. The parkname, parktype, city, state, and zipcode variables represent record field names. The Flash application displays the parkname and parktype variables in the ComboBox. The city, state, and zipcode variables are returned when the user selects the record and ActionScript code uses a getValue, getSelectedItem, or similar, method.

Using the bindFormatFunction method

The bindFormatFunction method lets you call a function to format the data for your data consumer. Your function must take a record as its argument and return an object with the following format:

{label: labelValue, data: dataValue};

For example, the following formatting function takes a record that includes a parkname field. It converts the parkname text to all lowercase as the label, and uses the field's length as the data. The bindFormatFunction method uses the output of this function to populate a Flash UI component:

function myFormatFunction ( record )
{
  // the label is the parkname record field, translated to lowercase
  var theLabel = record.parkname.toLowerCase();
  
  // the data is the length of the parkname record field
  var theData = record.parkname.length;
  
  // return the label and value to the caller
  return {label: theLabel, data: theData};
}
//call the bindFormatFunction method
DataGlue.bindFormatFunction(dataView2, result, myFormatFunction);

Comments


fuluc said on Oct 4, 2002 at 12:37 PM :
You describe how to use pageable recordset with coldfusion MX.
What about .NET ou Java ?
Can we use pageable recordset or not. Nothing is explain.
sgilson102 said on Oct 8, 2002 at 1:09 PM :
Pageable recordsets are only a feature of ColdFusion MX. They are not supported for .NET and Java.

Stephen M. Gilson
Macromedia Documentation
freeuser said on Jun 6, 2003 at 3:23 PM :
Pageable Recordset support is now available in OpenAMF, www.openamf.org.

amfphp, www.amfphp.org is also working on adding Pageable Recordset support.
jrunrandy said on Oct 24, 2003 at 10:38 AM :
A better URL for the Flash Exchange is http://www.macromedia.com/go/fl_exchange
tahseen said on Nov 6, 2003 at 8:02 PM :
HI. I have a datagrid(editable) which gets populated by a recordset. Is there any way to update a recordset such that the Database gets updated at the same time? meaning the way we have a getItem method for a recordset..is there any updateItem or any such operation on a recordset available?

THanks
Bill K. said on Jan 8, 2004 at 8:50 AM :
I also would like to know how to take updates made to the recordset back to the database server. It says using application server methods, but there is no reference or place to start. Thanks
jrunrandy said on Jan 9, 2004 at 6:15 AM :
I think you need to call web service methods that update the database. Flash MX 2004 has functionality that makes this a little easier (although, to be honest, there's a fair amount of complexity on the server side). If you look at the article at http://www.macromedia.com/devnet/mx/flash/articles/time_entry.html you should get a pretty good idea of what's involved.
No screen name said on Mar 18, 2004 at 1:34 AM :
how can i pass a row of data from my java to the actionscipt dataset?
ryancameron said on Jun 23, 2004 at 5:39 PM :
Can you set up recordsets to be referred to as actual objects...parent.child.child etc. natively or do I have to parse through them and create my own objects based on their contents? So far Ive been parsing them into XML, because XML is far easier to use inside flash than a bunch of arrays or whatever, but ideally Id like to be able to go recordset.child1.childa.child.length = something
etc. Does this make sense? I guess what Im asking is can a recordset object ultimately replace and / or improve on XML objects and save me a bunch of parsing like XML does.
ledatica said on Jul 6, 2004 at 3:50 PM :
the dataglue.bindformatstrings method only works in actionscript 1.0. If I use the same in actionscriopt 2.0. I get an error that there is no such method. Is the method different in actionscript 2.0 ?
zebastien said on Oct 19, 2004 at 11:39 AM :
Hello,
the filtering feature is great; however how to directly fetch the index of an object in the provider without looping on all records ?
for instance I have my own model coupled to a server mbean that is an AS record set. this however decouples the resultset and its server image: I need to reimplement the "MVC" at least for the server notification to model part: I receive an event from my server and want to update the RecordSet so that the AS event is sent to the UIs that did register (addView). for instance I then need to find the index of the deleted item; it would be nice if we had an API to be able to do RecordSet.getItemIndex/ID(fieldName, fieldValue) otherwise I need to loop on all records and that always proved to kill my CPU and get the CPU usage popup on most browsers.
Thanks.
Sebastien.
zebastien said on Oct 19, 2004 at 11:59 AM :
you are mentioning the addView method but I can't find it anywhere in the AS2 remoting sources at this gives me compilation errors.
I did use
http://download.macromedia.com/pub/flashremoting/mx2004/components/actionscript_2.0/flashremoting_comp_sourcecode.zip
seb.

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flashremoting/mx/Using_Flash_Remoting_MX/UseASData6.htm