DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 21.1 Creating Recordsets

21.1.1 Problem

You want to create and populate a recordset.

21.1.2 Solution

Return a recordset from Flash Remoting, or create a recordset using the constructor and populate it using the RecordSet.addItem( ) or RecordSet.addItemAt( ) methods.

21.1.3 Discussion

Most often, recordsets are returned to Flash movies from Flash Remoting. Recordsets cannot be meaningfully passed back to an application server portion of a Flash Remoting application. Therefore, it is rarely necessary to create recordsets with ActionScript. However, recordsets can be a convenient way of storing data, and with the DataGlue class, the data within a recordset can be used to populate many UI components.

The constructor function for recordsets requires an array of column names as a parameter, as follows:

// Make sure to include NetServices.as whenever you work with recordsets, although 
// for this simple example, including RecordSet.as would suffice.
#include "NetServices.as"

// Create a new recordset with three columns: COL0, COL1, and COL2.
rs = new RecordSet(["COL0", "COL1", "COL2"]);

Once you have created a recordset using the constructor, you can add records to it using the addItem( ) and addItemAt( ) methods. Both methods require a record object parameter. A record object is merely an object (an instance of the Object class) in which the property names match the column names of the recordset. The addItemAt( ) method differs from the addItem( ) method in that addItemAt( ) inserts a new record at a specific index within the recordset, while addItem( ) appends a record to the end of the recordset. Note that recordset indexes are zero-relative.

// Appends a record to the recordset.
rs.addItem({COL0: "val0", COL1: "val1", COL2: "val2"});

// Adds a record to the recordset at index 5.
rs.addItemAt(5, {COL0: "val0", COL1: "val1", COL2: "val2"});

Additionally, you can use the RecordSet.setField( ) method to alter a single column of an existing record within a recordset. The method takes three parameters: the index of the record, the column name, and the new value to assign.

#include "NetServices.as"

// Create a new recordset and fill it with three records.
rs = new RecordSet(["SHAPE", "COLOR"]);
rs.addItem({SHAPE: "square", COLOR: 0x00FF00});
rs.addItem({SHAPE: "circle", COLOR: 0xFF00FF});
rs.addItem({SHAPE: "triangle", COLOR: 0x0000FF});

// Change the COLOR column to 0x000000 in the record with index 2 (the third record).
rs.setField(2, "COLOR", 0x000000);
    [ Team LiB ] Previous Section Next Section