You are on page 1of 71

ADOBE® FLEX® 4 Tutorials

© 2010 Adobe Systems Incorporated. All rights reserved.


Copyright

Adobe® Flex® 4 Tutorials.


Adobe, the Adobe logo, Flash, Flash Builder, Flex, Flex Builder and LiveCycle are either registered trademarks or trademarks of Adobe Systems Incorporated in
the United States and/or other countries. ActiveX and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States
and/or other countries. Apple and Macintosh are trademarks of Apple Inc., registered in the United States and other countries. Linux is a registered trademark
of Linus Torvalds. Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
Solaris is a registered trademark or trademark of Sun Microsystems, Inc. in the United States and other countries. All other trademarks are the property of their
respective owners.
This Work is licensed under the Creative Commons Attribution Non-Commercial 3.0 License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/
Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA.

Last updated 6/1/2010


iii

Contents
Chapter 1: Import a service and bind data to application components
Create the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Create a ColdFusion service that returns localized strings ............................................................... 5
(Optional) Test the ColdFusion service ................................................................................. 6
Connect to the ColdFusion service ..................................................................................... 9
Examine the generated code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Chapter 2: Installing the Flash Builder tutorial database


Download and install the Flash Builder tutorial database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Chapter 3: Creating ColdFusion services for client applications


Create a CFC that accesses a database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
(Optional) Test the service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Import the service into Flex and bind returned data to application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Chapter 4: Creating PHP services for client applications


Create a PHP class that implements a service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
(Optional) Test the PHP service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Import the service into Flex and bind returned data to application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Chapter 5: Manage the access of data through paging


Paging tutorial (ColdFusion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Paging tutorial (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Chapter 6: Using data management to synchronize server updates


Data management tutorial (ColdFusion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Data management tutorial (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Last updated 6/1/2010


1

Chapter 1: Import a service and bind data


to application components
The relationship between client code and server code in Flex differs from the traditional relationship in a server
template.
In a traditional relationship, a server template mixes server code with client code. When the client queries a database,
it dynamically embeds HTML code with returned data.
Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned
data to user interface components in the client application.
This tutorial shows how to create a client application that imports a ColdFusion service. You first create a Label item
that displays static text. Next, you create a ColdFusion service that returns a localized text string. Then, you bind the
data returned from the ColdFusion service to the Label item. Finally, you examine the generated code to see how Flex
accesses the data returned from the service.

Create the application


1 In Flash Builder, select File > New > Flex Project.
2 Specify HelloCF for the project name, set Application Server Type to ColdFusion, and specify ColdFusion Flash
Remoting.

Last updated 6/1/2010


FLEX TUTORIALS 2
Import a service and bind data to application components

Specify project name and server type

3 Click Next. Verify your ColdFusion server configuration and click Validate Configuration.
4 Click Finish.
The Flash builder source editor opens to Hello.mxml.
5 If Design mode is not selected, select Design to switch to Design mode of the editor.
6 In the Components View, make sure that the Controls folder is open. Scroll the controls to find the Label control.

Last updated 6/1/2010


FLEX TUTORIALS 3
Import a service and bind data to application components

Label control in the Controls folder

7 Drag a Label component from the Components View to the design area.
8 Double-click the Label component. Replace the default text with Hello.
9 In the Properties view, modify the appearance of the text. With the Label component selected, specify the following:

Font Size 24

Font Attribute Bold

Font Attribute Italic

Select the font attributes

Last updated 6/1/2010


FLEX TUTORIALS 4
Import a service and bind data to application components

10 Click the Font color box and specify #ff0000 to change the text to Red.

Font color box

11 Save the file. Click the Run button to run the application.

Run button

Last updated 6/1/2010


FLEX TUTORIALS 5
Import a service and bind data to application components

The application runs in a web browser.

Create a ColdFusion service that returns localized


strings
Create a ColdFusion component (CFC) that can be accessed as a service by Flex over the Internet.
1 Create the following directory in your web root:
<CF Web Root>/HelloCF/

2 Code the following HelloService.cfc and place it in the HelloCF directory:

Last updated 6/1/2010


FLEX TUTORIALS 6
Import a service and bind data to application components

<cfcomponent>
<cffunction name="getMessage" access="remote" returntype="string">
<cfset message = "Hello from CF!">
<cfreturn message>
</cffunction>

<cffunction name="getLocalizedMessage" returnType="string" access="remote">


<cfargument name="locale" required="yes"/>

<cfswitch expression="#locale#">
<cfcase value="en">
<cfset message = "Hello from CF!"/>
</cfcase>
<cfcase value="es">
<cfset message = "Hola de CF!"/>
</cfcase>
<cfcase value="ne">
<cfset message = "Namaskar CF bata!"/>
</cfcase>
<cfdefaultcase>
<cfthrow message="Unknown locale code"/>
</cfdefaultcase>
</cfswitch>
<cfreturn message>
</cffunction>
<cffunction name="getLocales" returnType="array" access="remote">
<cfset codes = listToArray("en,es,ne")/>
<cfreturn codes>
</cffunction>
</cfcomponent>

The function getMessage() is a service operation that client applications access.


Make sure to specify remote as the access type for the function.

(Optional) Test the ColdFusion service


There are various ways to test the service before you access it from an application.
1 Create a ColdFusion script file, helloservicetest.cfm, that calls the service and displays the returned data in
HTML.
Use the cfinvoke tag to call the service.
Use the cfdump tag to view the results.
Testing getLocales()...
<cfinvoke component="HelloService" method="getLocales" returnvariable="locales"/>
<p> Result: <cfdump var="#locales#"/> </p>

Testing getLocalizedMessage("es")...
<cfinvoke component="HelloService" method="getLocalizedMessage" locale="es"
returnvariable="message"/>
<p> Result: <cfdump var="#message#"/> </p>

2 Save helloservicetest.cfm in the same folder as HelloService.cfc, and call the script from a web browser:

Last updated 6/1/2010


FLEX TUTORIALS 7
Import a service and bind data to application components

http://localhost:8500/HelloCF/helloservicetest.cfm

Using cfinvoke and cfdump

If there is an error in the service, ColdFusion displays detailed information about the error.

You can also enable Robust Exception Information for the ColdFusion server to get detailed debugging output.
3 Add trace statements to the service.
In the ColdFusion Administrator, enable debugging and logging.

Last updated 6/1/2010


FLEX TUTORIALS 8
Import a service and bind data to application components

Add ColdFusion trace statements as necessary to debug your service. For example, add the following line in
helloservicetest.cfm:

Testing getLocalizedMessage()...
<cfinvoke component="HelloService" method="getLocalizedMessage" locale="es"
returnvariable="message"/><p> Result: <cfdump var="#message#"/>
<cftrace category="getLocalizedMessage End" inline="yes" var="message"
text="GetLocalizedMessage call has completed">

Call the script from a web browser to view the debugging output. You can also inspect the ColdFusion log files.

Testing a service directly from a URL

4 Call a function in the service directly from a URL.


For example, call getLocalizedMessage() with the parameter es:
http://localhost:8500/HelloCF/HelloService.cfc?method=getLocalizedMessage&locale=es

Note: You can also test a service after importing the service into Flash Builder. Use Test Operation, which is available
from the Data/Service view.

Last updated 6/1/2010


FLEX TUTORIALS 9
Import a service and bind data to application components

Connect to the ColdFusion service


In Flash Builder, connect to the ColdFusion service and bind the data returned from the service to the Label
component.
1 In Design mode of the MXML editor, make sure HelloCF.mxml is open. From the Flash Builder Data menu, select
Connect To Data/Service.
2 Select ColdFusion as the service type. Click Next.

Select service type

3 Click Browse and navigate to the HelloService.cfc you previously created. Flash Builder names the service
HelloService.

Importing a ColdFusion Service

4 Click Finish. Provide your credentials to log in to the ColdFusion database.


The Data Services View now displays your ColdFusion service.

Data Services View

Last updated 6/1/2010


FLEX TUTORIALS 10
Import a service and bind data to application components

The Data Service View provides a picture of remote services. This view becomes useful when you configure types
for data returned by a service call.
5 Select the Label component in the design area. From the context menu for the Label component, select Bind to Data.
Select OK to replace the current text with the text returned from a service operation.
Flash Builder provides various ways to bind data to a selected component. In addition to the the context menu,
you can bind to data from Properties view. You can also select Bind to Data from the Flash Builder Data menu.
6 In the Bind to Data dialog, make sure that New Service Call is selected. For Operation select
getLocalizedMessage. Click OK.

Select the operation for binding data

Flash Builder switches the editor to Source mode, highlighting the parameter to getLocalizedMessage().
7 Type "es" for the parameter value for getLocalizedMessage(). Switch to Design mode of the editor.

Design mode showing data binding

8 Save and run the application.

Last updated 6/1/2010


FLEX TUTORIALS 11
Import a service and bind data to application components

The Label component displays the message retrieved from the HelloService.

Examine the generated code


When you imported the ColdFusion service into a client application, Flex generated client code that accessed the
ColdFusion service. Flex also generates code when you bind operations to application components.
There are three parts to the generated code:
• Event handler
• Service call and responder
• Data binding
This part of the tutorial walks you through the Flex code generated in the previous tutorial. There are no “steps” to this
part of the tutorial. Just a description of the code generation.

Event handlers
Flex uses event handlers to trigger a service call.
Flex code is not processed “top to bottom,” as in server templates. Instead, applications built with Flex listen for events
to trigger responses.
By default, Flex uses the creationComplete event on a component to trigger a service call.
Examine the Label component in the HelloCF.mxml source code:
<s:Label x="70" y="60"
text="{getLocalizedMessageResult.lastResult}"
fontWeight="bold" fontSize="24" fontStyle="italic"
color="#FF0000" id="label"
creationComplete="label_creationCompleteHandler(event)"/>

The creationComplete event fires after the application creates the component. For this Label component,
creationComplete calls an event handler that Flash Builder generated for the event. Examine the code for the event
handler, which is placed inside a Script block:

Last updated 6/1/2010


FLEX TUTORIALS 12
Import a service and bind data to application components

<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.controls.Alert;

protected function label_creationCompleteHandler(event:FlexEvent):void


{
getLocalizedMessageResult.token = helloService.getLocalizedMessage("es");
}

]]>
</fx:Script>

The creationComplete event handler calls the getLocalizedMessage() operation from the ColdFusion service. It
passes the parameter “es”, which you specified earlier in the source code.
You can use other events, such as a Click event on a button or a selectionChange event of a list, to trigger service
calls.

Service calls and responders


When you add a service, Flex creates a component containing methods that call the service operations. When you call
one of the methods, the component calls the corresponding service operation over the network using the appropriate
protocol.
Service calls are associated with CallResponders. Data returned from a service call is placed in the lastResult
attribute of the CallResponder. CallResponders allow service calls to operate asynchronously. The client application
can continue to be responsive while the service call is being processed.
Examine the generated service call and responder:
<fx:Declarations>
<s:CallResponder id="getLocalizedMessageResult"/>
<helloservice:HelloService id="helloService"
fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
showBusyCursor="true"/>
</fx:Declarations>

When you imported the HelloService service, Flex created the HelloService class. This class contains methods to call
the getLocales(), and getLocalizedMessage operations of the service.
The CallResponder, identified by the getLocalizedMessageResult id, provides access to the returned data.

Data binding
Flex data binding allows you to assign the value of the lastResult attribute of a CallResponder to a user interface
component. When the last result updates, Flex automatically updates the component.
Flex uses curly braces {} to bind data to an attribute of a component. In this example, Flex binds the lastResult value
to the text attribute of the Label component.
Examine the data binding for the Label component:
<s:Label x="70" y="60"
text="{getLocalizedMessageResult.lastResult}"
fontWeight="bold" fontSize="24" fontStyle="italic"
color="red" id="richEditableText"
creationComplete="label_creationCompleteHandler(event)"/>

Last updated 6/1/2010


FLEX TUTORIALS 13
Import a service and bind data to application components

The data returned to the CallResponder, getLocalizedMessageResult.lastResult, is automatically assigned as


the text attribute for the Label component.

Code generation summary


In summary, Flash Builder generates code to access the imported service in the client application:
• After Flex creates the Label component in the running application, the creationComplete event fires, calling a
service operation.
• The data returned from the service call is placed in the lastResult attribute of the associated CallResponder.
• The text attribute of the Label component, which is bound to the lastResult attribute, updates with the returned data.

Last updated 6/1/2010


14

Chapter 2: Installing the Flash Builder


tutorial database
Several of the tutorials show how to access data returned from a database. The tutorials use a MySQL database, which
you can access from either a PHP or ColdFusion installation.

Download and install the Flash Builder tutorial database


1 Download Flash Builder Tutorial Database and unzip it into a temporary directory on your computer.
The downloaded ZIP file contains two SQL files:
• fb_tutorial_db_full.sql

Use this file to import the entire database into your MySQL installation. It creates the fb_tutorial_db
database, which contains three tables. The tables in the database are departments, employees, and dept_emp.
• fb_tutorial_db_tables.sql
Use this file to import just the three tables into an existing database. This file is provided in case you do not have
privileges to create a database in your MySQL installation. See the ReadMe file for information on importing
this file.
You can install the database either from the command line or using the phpMyAdmin utility for MySQL databases.
2 (Command Line) Execute the following command from a terminal window for your operating system.
<MySQL_Install_Dir>/bin/mysql -u root -p < fb_tutorial_db_full.sql

3 (phpMyAdmin) From the phpMyAdmin home page, navigate to the Import page. Browse to the downloaded SQL
file and import the database.
4 (ColdFusion) In the ColdFusion Administrator, add fb_tutorial_db as a data source.
The following table lists the settings for the data source using the default configuration for ColdFusion 8:

Configuration Field Value

ColdFusion Data Source fb_tutorial_db


Name

Database fb_tutorial_db

Server 127.0.0.1

Port 3306

Last updated 6/1/2010


15

Chapter 3: Creating ColdFusion services


for client applications
When you access a remote service, you typically retrieve records from a database and display them in the client
application. This tutorial shows how to access a remote database and display retrieved records in a DataGrid.

The tutorial illustrates the following concepts:


• Using a ColdFusion component (CFC) to implement service operations that query a database.
• Binding a CFC service operation to a Flex data control, such as a DataGrid.
• Sampling the data returned from a service operation to configure a data type for the returned data.
• Running the application and viewing the returned data in the DataGrid.

Create a CFC that accesses a database


This tutorial accesses the cfbookclub database that is provided with a ColdFusion installation. It lists the contents of
the Books table in the database. However, you can modify this tutorial to select records from any database you have
access to.
This tutorial assumes that you have a local installation of ColdFusion 8 or ColdFusion 9 and the ColdFusion server is
running.
1 In your web root, create a folder named books.
2 In your favorite ColdFusion editor, create the following CFC. Name it BookService.cfc and place it in the books
folder in your web root.
BookService.cfc selects all the records from the Books table in the cfbookclub database.

Last updated 6/1/2010


FLEX TUTORIALS 16
Creating ColdFusion services for client applications

<!---
This sample service contains functions that illustrate typical service operations.
This code is for prototyping only.
Authenticate the user prior to allowing them to call these methods. You can find more
information at http://www.adobe.com/go/cf9_usersecurity
--->
<cffunction name="getBooks" output="false" access="remote" returntype="any" >
<!--- Retrieve set of records and return them as a query or array. --->
<!--- Add authorization or any logical checks for secure access to your data --->
<cfset var qAllBooks="">
<cfquery name="qAllBooks" datasource="cfbookclub">
SELECT * FROM Books
</cfquery>
<cfreturn qAllBooks>
</cffunction>

3 In BookService.cfc, examine the code that calls the database:


Flex expects data returned by the operation to be an object or an array of objects. Each object in the array
corresponds to a retrieved record from the database, containing values for each column in the record.
The cfquery, qAllBooks, accesses the Books table in the cfbookclub database. ColdFusion returns an array of
records from the database.

(Optional) Test the service


It is always a good idea to test a service before you access it from an application.
1 Create bookservicetest.cfm to test the CFC. This script uses cfdump to view the results of the service operation.
Testing getBooks()...
<cfinvoke component="BookService" method="getBooks" returnvariable="books"/>
<p> <cfdump var="#books#"/>

2 Save bookservicetest.cfm in the books folder next to BookService.cfc.


3 From a web browser, run the script to test the service:

Last updated 6/1/2010


FLEX TUTORIALS 17
Creating ColdFusion services for client applications

http://localhost:8500/books/bookservicetest.cfm

You can also test a service after importing the service into Flash Builder. Use Test Operation, which is available from
the Data/Service view.

Import the service into Flex and bind returned data to


application components
The relationship between client code and server code in Flex differs from the traditional relationship in a server
template.
In a traditional relationship, a server template mixes server code with client code. When the client queries a database,
it dynamically embeds HTML code with returned data.

Last updated 6/1/2010


FLEX TUTORIALS 18
Creating ColdFusion services for client applications

Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned
data to user interface components in the client application.
1 In Flash Builder, select New > Flex Project to create a ColdFusion server project. Name the project Books.
Set the Application Server Type to ColdFusion. Enable Use Remote Object Access Service and select ColdFusion
Flash Remoting.

2 Click Next. Validate your configuration.


3 Set the output folder to the books folder containing the service. Click Finish.
Flash builder creates Books.mxml and opens the file in the MXML editor.
Select Design to open the editor in Design mode.
4 In Design mode, drag a DataGrid control to the design area.
The DataGrid control is available under Controls in the Components view.
5 From the context menu for the DataGrid, select Bind to Data.
6 In the No Services Defined dialog, click Yes to connect to a service.
7 In the Connect to Data/Service wizard, select ColdFusion. Click Next.

Last updated 6/1/2010


FLEX TUTORIALS 19
Creating ColdFusion services for client applications

Flash Builder provides multiple ways to connect to a data service. In this scenario, you first create the user
interface. Then from a user interface component, you connect to a service and specify the remote operation.
8 Click Browse and navigate to the BookService.cfc you created previously. Click Finish.
Provide authorization credentials as needed for your system.
The Data Services View now displays the BookService.
9 Again, from the context menu for the DataGrid, select Bind to Data.
The Bind to Data dialog now opens with New Service Call selected.
BookService is the only service available in the Flex project.
getBooks() is the only operation available in the service.

10 In the Bind to Data dialog, select Configure Return Type to define the data type for returned data.
Flex uses the return data type to access service operations. The BookService service does not define the data type
for returned data. Flash Builder uses client-side typing to define a custom data type for the returned data.
Some services, such as those provided by LiveCycle Data Services, provide server-side typing. With server-side
typing, Flash Builder does not have to configure the data type for returned data.
11 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
Flash Builder introspects the service to determine the data and data types returned.
12 Specify Book in the Array Of field to define a custom type for returned data.
The BookService returns an array of records from the data service. Each record is a complex data type representing
a database record for a book. The custom type Book provides access to each field of the record.
The Configure Return Type dialog displays the properties of the data type returned by the service. Click Finish.
When Flash Builder configures a return type, it accesses the database to create a value object. The properties of
the custom data type are derived from the value object. You can view the properties of the data type before
proceeding.
13 In the Bind to Data dialog, click OK.

Last updated 6/1/2010


FLEX TUTORIALS 20
Creating ColdFusion services for client applications

Flash Builder binds the data returned from the service call to the DataGrid component. It modifies the columns of
the DataGrid, binding the value returned for each Book property to a column in the DataGrid.

14 Make sure the DataGrid is still selected. In the Properties view, click Configure Columns and then do the following
steps:
a Select the ISSPOTLIGHT column. Click Delete to delete the column.
b Delete all columns except TITLE and GENRE.
c Select the TITLE column. Edit the Header Text field to rename the column Title.
d Rename the GENRE column to Genre.
e With the GENRE column selected, click Up to rearrange the order of the columns.

Last updated 6/1/2010


FLEX TUTORIALS 21
Creating ColdFusion services for client applications

f Click OK.

15 In Design View, grab the far left handle of the DataGrid and resize it to a more normal shape. Save and run the
application.

Last updated 6/1/2010


22

Chapter 4: Creating PHP services for client


applications
You can create applications with Flex that access services from a wide variety of technologies. These technologies
include:
• ColdFusion
• PHP
• HTML (REST-style) services
• Web services (SOAP)
After creating a service, it is a good idea to test the service before accessing it from a client application.
The principles of creating and testing PHP services can be applied to other service technologies.

Create a PHP class that implements a service


The service you create in this tutorial accesses the fb_tutorial_db database. For information on installing this database,
see “Installing the Flash Builder tutorial database” on page 14.
1 In your web root, create a folder named PHPService. Within that folder, create another folder named services.
2 In your favorite PHP editor, create the following PHP file, which implements EmployeeService. Name the file
EmployeeService.php. Place it in the PHPService/services folder.

Last updated 6/1/2010


FLEX TUTORIALS 23
Creating PHP services for client applications

<?php
/**
* This sample service contains functions that illustrate typical service operations.
* This code is for prototyping only.
*
* Authenticate users before allowing them to call these methods.
*/
/**
* The constructor initializes the connection to database. Everytime a request is
* received by Zend AMF, an instance of the service class is created and then the
* requested method is called.
*/
class EmployeeService {
var $username = "USERNAME";
var $password = "PASSWORD";
var $server = "localhost";
var $port = "3306";
var $databasename = "fb_tutorial_db";
var $tablename = "employees";

var $connection;
public function __construct() {
$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port
);

$this->throwExceptionOnError($this->connection);
}
public function getEmployees() {

$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");


$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$rows = array();

mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,


$row->first_name, $row->last_name, $row->gender, $row->hire_date);

while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);
}

mysqli_stmt_free_result($stmt);

Last updated 6/1/2010


FLEX TUTORIALS 24
Creating PHP services for client applications

mysqli_close($this->connection);

return $rows;
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}

}
?>

This PHP class contains functions that implement data service operations. Flash Builder introspects the service
operations in the PHP class to create ActionScript classes in the client application. The client application accesses
the data service using these ActionScript classes.
3 Save EmployeeService.php at the following location:
<Web Root>/PHPService/services/EmployeeService.php

Note: Make sure that the filename corresponds to the name of the class implementing the PHP service.
4 In EmployeeService.php, examine the code that calls the database.
• Connecting to data:
The code uses global variables and a constructor function that connects to the database server.
Substitute your connection settings for the global variables.
• Call the database:
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
mysqli_stmt_execute($stmt);

This code implements a basic PHP call to a database to return a result set. This call uses prepared statements
available with the MySQLi extension. Prepares statements provide more security than a basic database query.
• Return the data as an array of rows:
$rows = array();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);
while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);
}
return $rows;

Last updated 6/1/2010


FLEX TUTORIALS 25
Creating PHP services for client applications

Flex expects data returned by the operation to be an object or an array of objects. The PHP code that handles
the returned result set iterates through the result, returning an array of objects. Each object in the array
corresponds to a retrieved record from the database, containing values for each column in the record.
The code uses bound results for the prepared statement. This call allows the values of the result to correctly be
bound to expected values of the data.
• Exception handling
The code creates a utility function to catch exceptions.

(Optional) Test the PHP service


It is always a good idea to test a service before you access it from an application.
1 Create a PHP script file, tester.php, that calls the service and displays the returned data.
<pre>
<?php
include('EmployeeService.php');
$o = new EmployeeService();
var_dump($o->getemployees());
?>
</pre>

2 Save tester.php in the same folder as EmployeeService.php, and call the service from a web browser.
If the call is successful, tester dumps records from the database:

Last updated 6/1/2010


FLEX TUTORIALS 26
Creating PHP services for client applications

array(999) {
[0]=>
object(stdClass)#4 (6) {
["emp_no"]=>
string(5) "10002"
["birth_date"]=>
string(10) "1964-06-02"
["first_name"]=>
string(7) "Bezalel"
["last_name"]=>
string(6) "Simmel"
["gender"]=>
string(1) "F"
["hire_date"]=>
string(10) "1985-11-21"
}
[1]=>
object(stdClass)#5 (6) {
["emp_no"]=>
string(5) "10003"
["birth_date"]=>
string(10) "1959-12-03"
["first_name"]=>
string(5) "Parto"
["last_name"]=>
string(7) "Bamford"
["gender"]=>
string(1) "M"
["hire_date"]=>
string(10) "1986-08-28"
}
[2]=>
object(stdClass)#6 (6) {
["emp_no"]=>
. . .

If there is an error in the service, PHP displays information to help locate the error.
Warning: mysqli_connect() [function.mysqli-connect]: (28000/1045):
Access denied for user 'admin'@'localhost' (using password: YES) in
C:\wamp2\www\PHP_Service\services\PHPservice.php on line 6

Access denied for user 'admin'@'localhost' (using password: YES)

You can also test a service after importing the service into Flash Builder. Use Test Operation, which is available from
the Data/Service view.

Import the service into Flex and bind returned data to


application components
The relationship between client code and server code in Flex differs from the traditional relationship in a server
template.

Last updated 6/1/2010


FLEX TUTORIALS 27
Creating PHP services for client applications

In a traditional relationship, a server template mixes server code with client code. When the client queries a database,
it dynamically embeds HTML code with returned data.
Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned
data to user interface components in the client application.
1 In Flash Builder, select File > New > Flex Project.
2 Specify PHP_Service for the project name and set the Application Server Type to PHP.

Specify project name and server type

Note: If you forget to set the application server type when you create the project, you can later specify the server type
from the Project Properties page.
3 Click Next. Verify your PHP configuration and click Validate Configuration.
4 For Output Folder, specify the PHPService folder you created previously.
Flash Builder suggests a default location for the output folder. Use the location that already contains
EmployeeService.php. Here is the location previously specified:

<Web Root>/PHPService/

5 Click Finish.

Last updated 6/1/2010


FLEX TUTORIALS 28
Creating PHP services for client applications

The Flash Builder source editor opens to PHP_Service.mxml.


6 Select Design to open the editor in Design mode. Add a DataGrid control to the application:
The DataGrid component is available under Data Controls in the Components view. Drag the DataGrid control to
the design area.
7 From the context menu for the DataGrid, select Bind to Data.
8 In the No Services Defined dialog, click Yes to connect to a service.
9 In the New Flex Service wizard, select PHP. Click Next.
Flash Builder provides multiple ways to connect to a data service. In this scenario, you first create the user
interface. Then from a user interface component, you can connect to a service and specify the remote operation.
10 Click Browse and navigate to the EmployeeService.php file you created previously.
The path to the file is:
<Web Root>/PHP_Service/services/EmployeeService.php

Click Finish. Flash Builder prompts you to install or update the Zend Framework, if necessary.
The Data Services View now displays the EmployeeService.
11 From the DataGrid context menu, again select Bind to Data.
The Bind to Data dialog opens with New Service Call selected.
EmployeeService is the only service available in the Flex project.
getEmployeess() is the only operation available in the service.

12 In the Bind to Data dialog, select Configure Return Type to define the data type for returned data.
Flex uses the return data type to access service operations. The EmployeeService service does not define the data
type for returned data. Flash Builder uses client-side typing to define a custom data type for the returned data.
13 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
14 Specify Employee for the name of the type.
The EmployeeService returns a complex data type representing a database record for an employee. The custom type
Employee provides access to each field of the record.

Last updated 6/1/2010


FLEX TUTORIALS 29
Creating PHP services for client applications

View the properties of the Employee data type returned by the service. Click Finish.
When Flash Builder configures a return type, it accesses the database to create a value object. The properties of
the custom data type are derived from the value object. You can view and modify the properties of the data type
before proceeding.
15 In the Bind to Data dialog, click OK.
Flash Builder binds the data returned from the service call to the DataGrid component. It modifies the columns of
the DataGrid, binding the value returned for each Employee property to a column in the DataGrid.
16 Make sure the DataGrid is still selected. In the Properties view, click Configure Columns and then do the following
steps:
a Select the hire_date column. Click Delete to delete the column.
b Similarly, delete all columns except emp_no, first_name, and last_name.
c Select the emp_no column. Click Up to move it to the first position.
d In the Header Text field, rename the emp_no column to ID.
e Similarly, rename the first_name and last_name columns.

f Click OK.
17 With the DataGrid still selected, in the Properties view, specify False for the editable property.
18 Select File > Save to save the application file. Then select Run > Run PHP_Service to run the application.

Last updated 6/1/2010


FLEX TUTORIALS 30
Creating PHP services for client applications

The application runs in a web browser.

Last updated 6/1/2010


31

Chapter 5: Manage the access of data


through paging
For various performance and network bottleneck issues, you typically do not retrieve all the records in a database with
a single call. Paging allows you to retrieve the records incrementally in sets, and only on an as needed basis.
To use paging to retrieve records, implement a data service that includes two operations with the following signatures:
• getItems_paged($startIndex, $numItems)

• count()

Paging tutorial (ColdFusion)


The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this
database, see “Installing the Flash Builder tutorial database” on page 14.
This tutorial creates an application that uses paging to populate a DataGrid.

Data grid

Create the remote service and import it into a Flex project


1 In your web root create a folder named PagingCF.
2 In your favorite ColdFusion editor, create the following CFC. Name the CFC PagingService.cfc and place it in
the PagingCF folder in your web root.
PagingService.cfc contains the functions required by Flash Builder to implement paging.

Last updated 6/1/2010


FLEX TUTORIALS 32
Manage the access of data through paging

<cfcomponent output="false">
<!---
This sample service contains functions that illustrate typical service operations.
This code is for prototyping only.
Authenticate the user prior to allowing them to call these methods. You can find more
information at http://www.adobe.com/go/cf9_usersecurity
--->
<cffunction name="getItems_paged" output="false" access="remote" returntype="any" >
<cfargument name="startIndex" type="numeric" required="true" />
<cfargument name="numItems" type="numeric" required="true" />
<!--- The LIMIT keyword is valid for MySQL database only, modify according to your database
--->
<cfset var qRead="">
<cfquery name="qRead" datasource="fb_tutorial_db">
SELECT * FROM employees LIMIT #startIndex#, #numItems#
</cfquery>

<cfreturn qRead>

</cffunction>

<cffunction name="count" output="false" access="remote" returntype="numeric" >

<cfquery name="qread" datasource="fb_tutorial_db">


SELECT COUNT(emp_no) AS empCount FROM employees
</cfquery>

<cfreturn qread.empCount>

</cffunction>
</cfcomponent>

3 In Flash Builder, create a Flex project. Name the project PagingCF and specify ColdFusion for the server technology
as listed below. Click Next.
• Application Server Type: ColdFusion
• Enable Use Remote Object Access Service
• Select ColdFusion Flash Remoting

Last updated 6/1/2010


FLEX TUTORIALS 33
Manage the access of data through paging

New project for ColdFusion

4 Validate your ColdFusion settings and specify the PagingCF directory for the Output Folder. Click Finish.
5 From the Flash Builder Data menu, select Connect to Data Service. Select ColdFusion and click Next.
6 Click Browse and navigate to the PagingService.cfc file you created in step 2. Click Finish.

Last updated 6/1/2010


FLEX TUTORIALS 34
Manage the access of data through paging

7 In the Flash Builder Data/Services view, from the context menu for the getItems_paged() operation, select
Configure Return Type.

8 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
9 Specify values and types for the parameters to the getItems_paged() operation as described below. Click Next:

Argument Argument Type Value

startIndex Number 0

numItems Number 10

Last updated 6/1/2010


FLEX TUTORIALS 35
Manage the access of data through paging

New project configuration

10 Specify Employee in the Array Of field toto define a custom type for returned data.
Flex uses custom data types to access and update complex data types returned from a server.
The Configure Return Type dialog displays the properties of the data type returned by the service.
11 Click Finish to configure the Employee return type.
12 In the Data/Services view, from the context menu for the getItems_paged() operation, select Enable Paging.
13 In the Select Unique Identifier dialog, select emp_no and click Next.
14 In the Confirm Paging dialog, leave the Page Size field blank. Specify the count() operation from the drop-down
list. Click Finish.

Last updated 6/1/2010


FLEX TUTORIALS 36
Manage the access of data through paging

Note: By default, Flash Builder configures the page size to be 20 records. This dialog allows you to specify a custom
page size for an operation.

Create an application and bind getItems_paged() to a DataGrid


1 If the MXML editor is in Source mode, select Design to open the editor in Design mode.
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 Make sure the DataGrid component is selected, then in the Properties view specify false for the Editable attribute.
4 With the DataGrid component selected, from the Data menu select Bind to Data.
5 In the Bind to Data operation, select New Service Call. For the PagingService, select the getItems_paged()
operation. Click OK.

Last updated 6/1/2010


FLEX TUTORIALS 37
Manage the access of data through paging

Bind To Data

6 Save and run the file.


In the application, click in the DataGrid scroll bar or move the thumb of the scroll bar to observe the paging of data.

Paging tutorial (PHP)


The application you create in this tutorial accesses the employee database that you previously downloaded and
installed. For information on installing this database, see “Installing the Flash Builder tutorial database” on page 14.

Last updated 6/1/2010


FLEX TUTORIALS 38
Manage the access of data through paging

This tutorial creates an application that uses paging to populate a DataGrid.

Create the remote service and import it into a Flex project


1 In your web root create a folder named PagingPHP. In the PagingPHP directory, create a directory named
services.

2 In your favorite PHP editor, create the following PHP file that implements the required paging functions. Name
the file PagingService.php and save it in the services directory.
<?php
/**
* This sample service contains functions that illustrate typical service operations.
* This code is for prototyping only.
*
* Authenticate users before allowing them to call these methods.
*/
class PagingService {
/* connection variables */
var $username = "USERNAME";
var $password = "PASSWORD";
var $server = "localhost";
var $port = "3306";
var $databasename = "fb_tutorial_db";
var $tablename = "employees";
var $connection;

public function __construct() {


$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port);

$this->throwExceptionOnError($this->connection);
}

public function count() {


$stmt = mysqli_prepare($this->connection,
"SELECT COUNT(*) AS COUNT FROM $this->tablename");
$this->throwExceptionOnError();

Last updated 6/1/2010


FLEX TUTORIALS 39
Manage the access of data through paging

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

mysqli_stmt_bind_result($stmt, $rec_count);
$this->throwExceptionOnError();

mysqli_stmt_fetch($stmt);
$this->throwExceptionOnError();

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

return $rec_count;
}

public function getItems_paged($startIndex, $numItems) {

$stmt = mysqli_prepare($this->connection,
"SELECT * FROM $this->tablename LIMIT ?, ?");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'ii', $startIndex, $numItems);


mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$rows = array();

mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,


$row->first_name, $row->last_name,
$row->gender, $row->hire_date);

while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name,
$row->gender, $row->hire_date);
}

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

Last updated 6/1/2010


FLEX TUTORIALS 40
Manage the access of data through paging

return $rows;
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}

}
?>

3 In PagingService.php, modify the connection variables to provide your server, username, and password for
access to the fb_tutorial_db database.

Last updated 6/1/2010


FLEX TUTORIALS 41
Manage the access of data through paging

4 In Flash Builder, create a Flex project. Name the project PagingPHP and specify PHP for the server technology.
Click Next.

5 Specify the Web Root and Root URL for your system. Validate your server settings and specify the PagingPHP
directory for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data Service. Select PHP and click Next.
7 Click Browse and navigate to the PagingService.php file you created in step 1. Click Finish.
If the Zend Framework, which includes Zend AMF, is not installed on your system, click OK to install the Zend
Framework.

Last updated 6/1/2010


FLEX TUTORIALS 42
Manage the access of data through paging

8 In the Flash Builder Data/Services view, from the context menu for the getItems_paged() operation, select
Configure Return Type.

9 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
10 Specify values and types for the parameters to the getItems_paged() operation as described below. Click Next:

Argument Argument Type Value

startIndex int 0

numItems int 20

11 Specify Employee in the Array Of field to define a custom type for returned data.

Last updated 6/1/2010


FLEX TUTORIALS 43
Manage the access of data through paging

Flex uses custom data types to access and update complex data types returned from a server.
The Configure Return Type dialog displays the properties of the data type returned by the service.
12 Click Finish to configure the Employee return type.
13 In the Data/Services view, from the context menu for the getItems_paged() operation, select Enable Paging.
14 In the Select Unique Identifier dialog, select emp_no and click Next.
15 In the Confirm Paging dialog, leave the Page Size field blank. Specify the count() operation from the drop-down
list. Click Finish.
Note: By default, Flash Builder configures the page size to be 20 records. This dialog allows you to specify a custom
page size for an operation.

Create an application and bind getItems_paged() to a DataGrid


1 If the MXML editor is in Source mode, select Design to open the MXML editor in Design mode.
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 Make sure the DataGrid component is selected, then in the Properties view specify false for the Editable attribute.
4 With the DataGrid component selected, from the Data menu select Bind to Data.

Last updated 6/1/2010


FLEX TUTORIALS 44
Manage the access of data through paging

5 In the Bind to Data operation, select New Service Call. For the PagingService, select the get Items Paged()
operation from the drop-down list,. Click OK.

6 Save and run the file.


In the application, click in the DataGrid scroll bar or move the thumb of the scroll bar to observe the paging of data.

Last updated 6/1/2010


45

Chapter 6: Using data management to


synchronize server updates
Data management features allow you to synchronize adding, updating, and deleting of records in a database. Changes
you make in the client application are not written to the server until a commit method is called. You can call a revert
method to roll back changes made in the client application.
Additionally, data management helps synchronize your client application with the data on the service. Data
management features can automatically update user interface controls that display data retrieved from a service.
This tutorial shows how to use Flash Builder to implement data management. The tutorial illustrates how to
synchronize data on the server and with client application controls.

Data management service operations


Data management requires a data service that implements one or more operations with the following signatures:
• createItem(item:CustomDatatype):int

• deleteItem(itemID:Number):void

• updateItem((item: CustomDatatype):void

• getItem(itemID:Number): CustomDatatype

CustomDatatype is a data type representing complex data returned from the server. In server-side typing, the service
defines the custom data type. In client-side typing, use Flash Builder to introspect the service and configure the custom
data type.
Note: The required data management operation signatures listed in this tutorial are a subset of the signatures that can
be used. For a complete list of the operation signatures you can use, see Enabling data management.

Client-side and server-side typing


This tutorial illustrates both client-side typing and server-side typing. For this tutorial, the client application accesses
an Employee object from the data service. The Employee object contains fields, such as name and hire date, that define
an employee. With client-side typing, you use Flash Builder wizards to introspect the data on the server and define the
Employee data type in client code. With server-side typing, server code defines the Employee data type.
Both PHP and ColdFusion let you define custom data types in server code. Flash Builder recognizes the custom data
type during introspection of services. You do not have to walk through the wizard screens to configure the Employee
data type.
Whether you use server-side or client-side typing is a developer preference. Server-side typing can help enforce data
integrity on the server and simplify the Flash Builder workflow. Client-side typing simplifies the service coding while
using Flash Builder to define the custom data types.
Note: Flash Builder can generate sample server code from a database. The sample code generated by Flash Builder
illustrates client-side typing. See Generating a sample ColdFusion service from a database table and Generating a sample
PHP service from a database table.

Last updated 6/1/2010


FLEX TUTORIALS 46
Using data management to synchronize server updates

Data management tutorial (ColdFusion)


The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this
database, see “Installing the Flash Builder tutorial database” on page 14.
In this tutorial, you create an application that contains an editable DataGrid that displays employee records. You can
modify one or more records in place in the DataGrid. You can also add or delete selected records. All changes in the
DataGrid are local until you select a Save All Changes button that updates the database.

You can implement the service in this tutorial using client-side or server-side typing. The service is defined in
EmployeeService.cfc. If you use server-side typing, you define the Employee data type in a separate
Employee.cfc.

The server code in EmployeeService.cfc is basically the same in both versions. However, in the version that
implements server-side typing, the functions access the Employee data type defined in Employee.cfc.
• “Create the remote service and import it into a Flex project (client-side typing)” on page 46
• “Create the remote service and import it into a Flex project (server-side typing)” on page 49

Create the remote service and import it into a Flex project (client-side typing)
1 In your web root create a folder named DataMgtCF.
2 In your favorite ColdFusion editor, create the following CFC. Name the CFC EmployeeService.cfc and place it
in the DataMgtCF folder in your web root.
EmployeeService.cfc contains the functions required by Flash Builder to implement data management.

Last updated 6/1/2010


FLEX TUTORIALS 47
Using data management to synchronize server updates

<!---
This sample service contains functions that illustrate typical service operations.
This code is for prototyping only.
Authenticate the user prior to allowing them to call these methods. You can find more
information at http://www.adobe.com/go/cf9_usersecurity
--->
<cfcomponent output="false">
<cffunction name="getAllItems" output="false" access="remote" returntype="any" >
<cfset var qAllItems="">
<cfquery name="qAllItems" datasource="fb_tutorial_db">
SELECT * FROM employees
</cfquery>
<cfreturn qAllItems>
</cffunction>

<cffunction name="getItem" output="false" access="remote" returntype="any" >


<cfargument name="itemID" type="numeric" required="true" />

<cfset var qItem="">


<cfquery name="qItem" datasource="fb_tutorial_db">
SELECT * FROM employees
WHERE emp_no = <CFQUERYPARAM CFSQLTYPE="CF_SQL_INTEGER"
VALUE="#ARGUMENTS.itemID#">
</cfquery>

<cfreturn qItem>
</cffunction>

<cffunction name="createItem" output="false" access="remote" returntype="any" >


<cfargument name="item" required="true" />

<cfquery name="createItem" datasource="fb_tutorial_db" result="result">


INSERT INTO employees (first_name, last_name, gender, birth_date,
hire_date)
VALUES (<CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR"
VALUE="#item.first_name#">,
<CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR"
VALUE="#item.last_name#">,
<CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.gender#">,
<CFQUERYPARAM cfsqltype="CF_SQL_DATE" VALUE="#item.birth_date#">,
<CFQUERYPARAM cfsqltype="CF_SQL_DATE" VALUE="#item.hire_date#">)
</cfquery>

<cfreturn result.GENERATED_KEY/>
</cffunction>

<cffunction name="updateItem" output="false" access="remote" returntype="void" >


<cfargument name="item" required="true" />

<cfquery name="updateItem" datasource="fb_tutorial_db">


UPDATE employees SET birth_date = <CFQUERYPARAM cfsqltype="CF_SQL_DATE"
VALUE="#item.birth_date#">,

Last updated 6/1/2010


FLEX TUTORIALS 48
Using data management to synchronize server updates

hire_date = <CFQUERYPARAM cfsqltype="CF_SQL_DATE" VALUE="#item.hire_date#">,


gender = <CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.gender#">,
first_name = <CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR"
VALUE="#item.first_name#">,
last_name = <CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.last_name#">
WHERE emp_no = <CFQUERYPARAM CFSQLTYPE="CF_SQL_INTEGER" VALUE="#item.emp_no#">
</cfquery>
</cffunction>

<cffunction name="deleteItem" output="false" access="remote" returntype="void" >


<cfargument name="itemID" type="numeric" required="true" />

<cfquery name="delete" datasource="fb_tutorial_db">


DELETE FROM employees
WHERE emp_no = <CFQUERYPARAM CFSQLTYPE="CF_SQL_INTEGER"
VALUE="#ARGUMENTS.itemID#">
</cfquery>
</cffunction>

</cfcomponent>

3 In Flash Builder, create a Flex project. Name the project DataMgtCF. Specify ColdFusion for the server technology
as listed below. Click Next.
• Application Server Type: ColdFusion
• Enable Use Remote Object Access Service
• Select ColdFusion Flash Remoting
4 Validate your ColdFusion settings and specify the DataMgtCF folder for the Output Folder. Click Finish.
5 From the Flash Builder Data menu, select Connect to Data/Service. Select ColdFusion. Click Next.
6 Click Browse and navigate to the EmployeeService.cfc file you created in step 2. Click Finish.
Provide authorization credentials as needed for your system.
7 In the Flash Builder Data/Services view, from the context menu for the getItem() operation, select Configure
Return Type.
Flash Builder requires a custom data type for data returned from the data service. By introspecting the getItem()
operation, you can define the custom data type Employee.
8 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
9 Specify a value and type for the parameter to the getItem() operation as described below. Click Next:

Argument Argument Type Value

itemID Number 10001

For getItem(), you supply a valid parameter corresponding to the key field for the database. Number and 10001
are valid type and value for itemID
10 Specify Employee in the Array Of field to define a custom type for returned data.
Flex uses custom data types to access and update complex data types returned from a server. getItem() returns
the fields of a record from the Employees table in the database
The Configure Return Type dialog displays the properties of the data type returned by the service.

Last updated 6/1/2010


FLEX TUTORIALS 49
Using data management to synchronize server updates

11 Click Finish to configure the Employee return type.


12 In the Flash Builder Data/Services view, from the context menu for the getAllItems() operation, select Configure
Return Type.
13 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
14 Select Use an Existing Data Type. Select Employee from the Array Of drop-down list to specify an array of
Employees. Click Finish.
Next:“Enable Data Management Features” on page 51

Create the remote service and import it into a Flex project (server-side typing)
1 In your web root create a folder named DataMgtCF.
2 In your favorite ColdFusion editor, create the following CFC. Name the CFC Employee.cfc and place it in the
DataMgtCF folder.

Employee.cfc defines the Employee data type that is returned by the service.

<cfcomponent>
<cfproperty name="emp_id" type="numeric">
<cfproperty name="bdate" type="date">
<cfproperty name="fname" type="string">
<cfproperty name="lname" type="string">
<cfproperty name="gender" type="string">
<cfproperty name="hdate" type="date">
</cfcomponent>

3 Now create EmployeeService.cfc and place it in the DataMgtCF folder alongside Employee.cfc.
EmployeeService.cfc contains the functions required by Flash Builder to implement data management.

<!---
This sample service contains functions that illustrate typical service operations.
This code is for prototyping only.
Authenticate the user prior to allowing them to call these methods. You can find more
information at http://www.adobe.com/go/cf9_usersecurity
--->
<cfcomponent output="false">
<cffunction name="getAllEmployees" output="false" access="remote"
returntype="Employee[]" >
<cfset var returnarray = ArrayNew(1)>
<cfset var temp = "">
<cfset var qAllEmployees="">
<cfquery name="qAllEmployees" datasource="fb_tutorial_db">
SELECT * FROM employees
</cfquery>
<cfloop query="qAllEmployees">
<cfobject component="Employee" name="tempname">
<cfset tempname.emp_id = #qAllEmployees.emp_no#>
<cfset tempname.fname = #qAllEmployees.first_name#>
<cfset tempname.lname = #qAllEmployees.last_name#>
<cfset tempname.gender = #qAllEmployees.gender#>
<cfset tempname.bdate = #qAllEmployees.birth_date#>
<cfset tempname.hdate = #qAllEmployees.hire_date#>
<cfset temp = ArrayAppend(returnarray, tempname)>
</cfloop>
<cfreturn returnarray>

Last updated 6/1/2010


FLEX TUTORIALS 50
Using data management to synchronize server updates

</cffunction>

<cffunction name="getEmployee" output="false" access="remote" returntype="Employee" >


<cfargument name="itemID" type="numeric" required="true" />

<cfset var qItem="">


<cfquery name="qItem" datasource="fb_tutorial_db">
SELECT * FROM employees
WHERE emp_no = <CFQUERYPARAM CFSQLTYPE="CF_SQL_INTEGER"
VALUE="#ARGUMENTS.itemID#">
</cfquery>

<cfreturn qItem>
</cffunction>

<cffunction name="createEmployee" output="false" access="remote" returntype="numeric" >


<cfargument name="item" type="Employee" required="true" />

<cfquery name="qCreateEmplyee" datasource="fb_tutorial_db" result="result">


INSERT INTO employees (first_name, last_name, gender, birth_date,
hire_date)
VALUES (<CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.fname#">,
<CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.lname#">,
<CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.gender#">,
<CFQUERYPARAM cfsqltype="CF_SQL_DATE" VALUE="#item.bdate#">,
<CFQUERYPARAM cfsqltype="CF_SQL_DATE" VALUE="#item.hdate#">)
</cfquery>

<cfreturn result.GENERATED_KEY/>
</cffunction>
<cffunction name="updateEmployee" output="false" access="remote" returntype="void" >
<cfargument name="item" type="Employee" required="true" />

<cfquery name="updateItem" datasource="fb_tutorial_db">


UPDATE employees SET birth_date = <CFQUERYPARAM cfsqltype="CF_SQL_DATE"
VALUE="#item.bdate#">,
hire_date = <CFQUERYPARAM cfsqltype="CF_SQL_DATE" VALUE="#item.hdate#">,
gender = <CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.gender#">,
first_name = <CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.fname#">,
last_name = <CFQUERYPARAM cfsqltype="CF_SQL_VARCHAR" VALUE="#item.lname#">
WHERE emp_no = <CFQUERYPARAM CFSQLTYPE="CF_SQL_INTEGER" VALUE="#item.emp_id#">
</cfquery>
</cffunction>

<cffunction name="deleteEmployee" output="false" access="remote" returntype="void" >


<cfargument name="itemID" type="numeric" required="true" />

<cfquery name="delete" datasource="fb_tutorial_db">


DELETE FROM employees
WHERE emp_no = <CFQUERYPARAM CFSQLTYPE="CF_SQL_INTEGER"
VALUE="#ARGUMENTS.itemID#">
</cfquery>
</cffunction>

</cfcomponent>

Last updated 6/1/2010


FLEX TUTORIALS 51
Using data management to synchronize server updates

4 In Flash Builder, create a Flex project. Name the project DataMgtCF. Specify ColdFusion for the server technology
as listed below. Click Next.
• Application Server Type: ColdFusion
• Enable Use Remote Object Access Service
• Select ColdFusion Flash Remoting
5 Validate your ColdFusion settings and specify the DataMgtCF folder for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data/Service. Select ColdFusion. Click Next.
7 Click Browse and navigate to the EmployeeService.cfc file you created in step 2. Click Finish.
Provide authorization credentials as needed for your system.
Next:“Enable Data Management Features” on page 51

Enable Data Management Features


1 In the Data/Services view, expand the Data Types node for EmployeeService and select the Employee data type.
2 From the context menu for the Employee data type, select Enable Data Management.

3 In the Select Unique Identifier dialog, select emp_id and click Next.
4 In the Map Database Operations dialog, specify the following operations. Click Finish.
• Create (Add) Operation: createEmployee( )

• Get Item Operation: getEmployee( )

• Update Operation: updateEmployee( )

Last updated 6/1/2010


FLEX TUTORIALS 52
Using data management to synchronize server updates

• Delete Operation: deleteEmployee ( )

Data management is now enabled for this operation. Flash Builder generates client code that can update data using
a combination of the mapped operations.
Next:“Create the application and add a DataGrid and Buttons” on page 52

Create the application and add a DataGrid and Buttons


1 If the MXML editor is in Source mode, select Design to open the MXML editor in Design mode.
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 In the Properties view, with the DataGrid selected, specify the following properties:

Property Value

ID dg

Editable true

4 Drag four Buttons to the Design Area, lining them up beneath the DataGrid.
5 Double-click each button to edit their labels. Provide the following Labels:

Label

Add

Last updated 6/1/2010


FLEX TUTORIALS 53
Using data management to synchronize server updates

Label

Delete

Revert

Save All Changes

6 In the Data/Services view, select the getAllEmployees() operation and drop it onto the DataGrid.
In the Bind to Data dialog, EmployeeService and getAllEmployees() are selected. Click OK.

7 (Optional) With the DataGrid selected, in the Properties view Click Configure Columns and do the following:
Rename and rearrange the columns.
Next:“Generate event handlers for the Buttons” on page 53

Generate event handlers for the Buttons


Each Button requires an event handler to specify the action to take when the Button is clicked. Flash Builder generates
stubs for event handlers, which you can then code to specify the service actions to take.
1 Select the Add button. In Properties view, near the On Click field of the Add button, click the icon. Select Generate
Event Handler.
The MXML editor changes to Source View, placing the cursor in the generated event handler.
2 In the event handler body, specify the implementation for the event.
The data types differ slightly for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:

Last updated 6/1/2010


FLEX TUTORIALS 54
Using data management to synchronize server updates

var e:Employee = new Employee();


var birthDate:Date = new Date(2000, 01, 01);
var hireDate:Date = new Date(2000, 01, 01);

e.first_name = "New";
e.last_name = "New";
e.birth_date = birthDate;
e.hire_date = hireDate;
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;

Server-side typing:
var e:Employee = new Employee();
var birthDate:Date = new Date(2000, 01, 01);
var hireDate:Date = new Date(2000, 01, 01);
e.fname = "New";
e.lname = "New";
e.bdate = birthDate;
e.hdate = hireDate;
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;

3 In the Script block, add the following import statement after the existing import statements:
import services.employeeservice.EmployeeService;
import valueObjects.Employee;

4 In Design mode, add an On Click event handler for the Delete button.
The data types differ slight for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:
employeeService.deleteEmployee(dg.selectedItem.emp_no);

Server-side typing:
employeeService.deleteEmployee(dg.selectedItem.emp_id);

5 Similarly, add an On Click event handler for the Revert button with the following code:
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).revertChanges();
getAllEmployeesResult.token = employeeService.getAllEmployees();

6 Add an On click event handler for the Save All Changes button with the following code:
employeeService.commit();

7 For the creationCompleteHandler() for the DataGrid, add the following lines of code:
protected function dg_creationCompleteHandler(event:FlexEvent):void
{
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).autoCommit=false;

employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).deleteItemOnRemoveFro
mFill=true;
getAllItemsResult.token = employeeService.getAllItems();
}

Last updated 6/1/2010


FLEX TUTORIALS 55
Using data management to synchronize server updates

This code makes sure that deleted items can be reverted by selecting the Revert button.
8 Save the application and select Run > Run DataMgtCF.

You can update employees in place in the DataGrid. When you click Save All Changes, the changes are updated on
the server. The server is updated is because the data management feature calls the updateItem() operation to keep
the data synchronized between the client and the server.
Click the Revert button to undo any changes you made before you click Save All Changes.
You can add and delete employees. When you add and delete employees, the data management features take care
of adding or removing the DataGrid rows. Without data management enabled, you code the updates to the
DataGrid yourself.
When you add an employee, the Employee Number defaults to zero. This default value is because the new employee
has not been updated on the server. When you click Save All Changes, the new employee is added to the server. At
that time, an Employee Number is generated.
Click the Save All Changes button to write all changes to the database.

Data management tutorial (PHP)


The application you create in this tutorial accesses the employee database that you previously downloaded and
installed. For information on installing this database, see “Installing the Flash Builder tutorial database” on page 14.

Last updated 6/1/2010


FLEX TUTORIALS 56
Using data management to synchronize server updates

In this tutorial, you create an application that contains an editable DataGrid that displays employee records. You can
modify one or more records in place in the DataGrid. You can also add or delete selected records. All changes in the
DataGrid are local until you select a Save All Changes button that updates the database.

You can implement the service in this tutorial using client-side or server-side typing. The service is defined in
EmployeeService.php. If you use server-side typing, you define the Employee data type in a separate Employee class
defined in EmployeeService.php.
The server code in EmployeeService.php is basically the same in both versions. However, in the version that
implements server-side typing, the functions access the Employee data type defined in the Employee class.
• “Create the remote service and import it into a Flex project (client-side typing)” on page 56
• “Create the remote service and import it into a Flex project (server-side typing)” on page 60

Create the remote service and import it into a Flex project (client-side typing)
1 In your web root, create a folder named DataMgtPHP. Within that folder, create a folder named services.
2 In your favorite PHP editor, create the following PHP file, which implements a service. Name the file
EmployeeService.php and place it in the DataMgtPHP/services folder in your web root.

Last updated 6/1/2010


FLEX TUTORIALS 57
Using data management to synchronize server updates

<?php

class EmployeeService {

var $username = "USERNAME";


var $password = "PASSWORD";
var $server = "localhost";
var $port = "3306";
var $databasename = "fb_tutorial_db";
var $tablename = "employees";

var $connection;

public function __construct() {


$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port
);

$this->throwExceptionOnError($this->connection);
}

public function getAllEmployees() {

$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");


$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$rows = array();

mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,


$row->first_name, $row->last_name, $row->gender, $row->hire_date);

while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);
}

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

return $rows;
}

public function getEmployeesByID($itemID) {

$stmt = mysqli_prepare($this->connection,
"SELECT * FROM $this->tablename where emp_no=?");
$this->throwExceptionOnError();

Last updated 6/1/2010


FLEX TUTORIALS 58
Using data management to synchronize server updates

mysqli_bind_param($stmt, 'i', $itemID);


$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,


$row->first_name, $row->last_name, $row->gender, $row->hire_date);

if(mysqli_stmt_fetch($stmt)) {
return $row;
} else {
return null;
}
}

public function createEmployees($item) {

$stmt = mysqli_prepare($this->connection,
"INSERT INTO $this->tablename (birth_date,
first_name, last_name, gender, hire_date) VALUES (?, ?, ?, ?, ?)");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'sssss', $item->birth_date,


$item->first_name, $item->last_name, $item->gender, $item->hire_date);
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$autoid = mysqli_stmt_insert_id($stmt);

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

return $autoid;
}

public function updateEmployees($item) {

$stmt = mysqli_prepare($this->connection,
"UPDATE $this->tablename SET emp_no=?, birth_date=?,
first_name=?, last_name=?, gender=?, hire_date=?
WHERE emp_no=?");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'isssssi', $item->emp_no, $item->birth_date,


$item->first_name, $item->last_name, $item->gender, $item->hire_date, $item-
>emp_no);
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}

Last updated 6/1/2010


FLEX TUTORIALS 59
Using data management to synchronize server updates

public function deleteEmployees($itemID) {

$stmt = mysqli_prepare($this->connection,
"DELETE FROM $this->tablename WHERE emp_no = ?");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'i', $itemID);


mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}

/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>

3 Modify the connection variables to provide your server, user name, and password for access to the
fb_tutorial_db database.

4 In Flash Builder, create a Flex project. Name the project DataMgtPHP and specify PHP for the server technology.
Click Next.
5 Specify the Web Root and Root URL for your system. Validate your server settings. Specify the DataMgtPHP
directory for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data Service. Select PHP. Click Next.
7 Click Browse and navigate to the EmployeeService.php file you created in step 2. Select EmployeeService.php.
Click Finish.
8 In the Flash Builder Data/Services view, from the context menu for the getEmployeesbyID() operation, select
Configure Return Type.
Flash Builder requires a custom data type for data returned from the data service. By introspecting the
getEmployeesbyID() operation, you can define the custom data type Employee.

9 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
10 Specify a value and type for the parameter to the getEmployeesByID() operation as described below. Click Next:

Argument Argument Type Value

itemID int 10001

Last updated 6/1/2010


FLEX TUTORIALS 60
Using data management to synchronize server updates

For getEmployeesByID(), you supply a valid parameter corresponding to the key field for the database. int and
10001 are valid type and value for itemID.
11 Specify Employee to define a custom type for returned data.
Flex uses custom data types to access and update complex data types returned from a server. getEmployeesByID()
returns the fields of a record from the Employees table in the database
The Configure Return Type dialog displays the properties of the data type returned by the service.
12 Click Finish to configure Employee as the return type.
13 In the Flash Builder Data/Services view, from the context menu for the getAllEmployees() operation, select
Configure Return Type.
14 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
15 Select Use an Existing Data Type. Select Employee from the Array Of drop-down list. Click Finish.
16 Configure the parameter type and return type for deleteEmployees() as follows:
a From the context menu for the deleteEmployees() operation, select Configure Input Types. Specify int for the
type. Click OK.
b From the context menu for the deleteEmployees() operation, select Configure Return Type. Select Use An
Existing Type. Specify void. Click Finish.
Next:“Enable Data Management Features” on page 64

Create the remote service and import it into a Flex project (server-side typing)
This release of Flash Builder uses PHP DocBlock comments to recognize server-side data type. The sample service in
this example shows how to use DocBlock comments to define a custom data type. The example also shows how to
specify a data type for function arguments and return values.
1 In your web root, create a folder named DataMgtPHP. Within that folder, create a folder named services.
2 In your favorite PHP editor, create the following PHP file, which implements a service. The service also contains
an Employee class that defines the Employee data type.
Name the file EmployeeService.php and place it in the DataMgtPHP/services folder in your web root.

Last updated 6/1/2010


FLEX TUTORIALS 61
Using data management to synchronize server updates

<?php
class Employee {
/**
* @var int
*/
var $emp_id;

/**
* @var string
*/
var $bdate;

/**
* @var string
*/
var $fname;

/**
* @var string
*/
var $lname;

/**
* @var string
*/
var $gender;

/**
* @var string
*/
var $hdate;
}

class EmployeeService {

var $username = "USERNAME";


var $password = "PASSWORD";
var $server = "localhost";
var $port = "3306";
var $databasename = "fb_tutorial_db";
var $tablename = "employees";

var $connection;

public function __construct() {


$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port
);

$this->throwExceptionOnError($this->connection);
}

/**

Last updated 6/1/2010


FLEX TUTORIALS 62
Using data management to synchronize server updates

* Returns all the rows from the table.


*
* Add authorization or any logical checks
* for secure access to your data
*
* @return Employee[]
*/
public function getAllEmployees() {

$stmt = mysqli_prepare($this->connection, "SELECT


employees.emp_no,
employees.birth_date,
employees.first_name,
employees.last_name,
employees.gender,
employees.hire_date
FROM $this->tablename");
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$rows = array();

mysqli_stmt_bind_result($stmt, $row->emp_id, $row->bdate,


$row->fname, $row->lname, $row->gender, $row->hdate);

while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_id, $row->bdate,
$row->fname, $row->lname, $row->gender, $row->hdate);
}

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

return $rows;
}

/**
* @param int $itemID
* @return Employee
*/
public function getEmployeesByID($itemID) {

$stmt = mysqli_prepare($this->connection,
"SELECT * FROM $this->tablename where emp_no=?");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'i', $itemID);


$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $item->emp_no, $item->bdate,
$item->fname, $item->lname, $item->gender, $item->hdate);

Last updated 6/1/2010


FLEX TUTORIALS 63
Using data management to synchronize server updates

if(mysqli_stmt_fetch($stmt)) {
return $item;
} else {
return null;
}
}

/**
* @param Employee $item
* @return int
*/
public function createEmployees($item) {

$stmt = mysqli_prepare($this->connection,
"INSERT INTO $this->tablename (birth_date,
first_name, last_name, gender, hire_date) VALUES (?, ?, ?, ?, ?)");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'sssss', $item->bdate,


$item->fname, $item->lname, $item->gender, $item->hdate);
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

$autoid = mysqli_stmt_insert_id($stmt);

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);

return $autoid;
}

/**
* @param Employee $item
*/
public function updateEmployees($item) {

$stmt = mysqli_prepare($this->connection,
"UPDATE $this->tablename SET emp_no=?, birth_date=?,
first_name=?, last_name=?, gender=?, hire_date=?
WHERE emp_no=?");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'isssssi', $item->emp_id, $item->bdate,


$item->fname, $item->lname, $item->gender, $item->hdate, $item->emp_id);
$this->throwExceptionOnError();

mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}

Last updated 6/1/2010


FLEX TUTORIALS 64
Using data management to synchronize server updates

/**
* @param int $itemID
*/
public function deleteEmployees($itemID) {

$stmt = mysqli_prepare($this->connection,
"DELETE FROM $this->tablename WHERE emp_no = ?");
$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'i', $itemID);


mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();

mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}

/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}

3 Modify the connection variables to provide your server, user name, and password for access to the
fb_tutorial_db database.

4 In Flash Builder, create a Flex project. Name the project DataMgtPHP and specify PHP for the server technology.
Click Next.
5 Specify the Web Root and Root URL for your system. Validate your server settings. Specify the DataMgtPHP
directory for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data Service. Select PHP. Click Next.
7 Click Browse and navigate to the EmployeeService.php file you created in step 2. Select EmployeeService.php.
Click Finish.
Next:“Enable Data Management Features” on page 64

Enable Data Management Features


1 In the Data/Services view, expand the Data Types node for EmployeeService and select the Employee data type.

Last updated 6/1/2010


FLEX TUTORIALS 65
Using data management to synchronize server updates

2 From the context menu for the Employee data type, select Enable Data Management.

3 In the Select Identity Properties dialog, select emp_id. Click Next.


4 In the Map Database Operations dialog, specify the following operations. Click Finish.
• Create (Add) Operation: createEmployees()
• Get Item Operation: getEmployeesByID()
• Update Operation: updateEmployees()
• Delete Operation: deleteEmployees ()

Click Finish. Data management is now enabled for this operation. Flash Builder generates client code that can
update data using a combination of the mapped operations.
Next:“Create the application and add a DataGrid and Buttons” on page 66

Last updated 6/1/2010


FLEX TUTORIALS 66
Using data management to synchronize server updates

Create the application and add a DataGrid and Buttons


1 If the MXML editor is in Source mode, select Design to open the MXML editor in Design mode
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 In the Properties view, with the DataGrid selected, specify the following properties:

Property Value

ID dg

Editable true

4 Drag four Buttons to the Design Area, lining them up beneath the DataGrid.
5 Double-click each button to edit their labels. Provide the following Labels:

Label

Add

Delete

Revert

Save All Changes

6 In the Data/Services view, select the getAllEmployees() operation and drop it onto the DataGrid.
In the Bind to Data dialog, EmployeeService and getAllEmployees() are selected. Click OK.

7 (Optional) With the DataGrid selected, in the Properties view click Configure Columns. Rename and rearrange the
columns.
Next:“Generate and code event handlers for the Buttons” on page 67

Last updated 6/1/2010


FLEX TUTORIALS 67
Using data management to synchronize server updates

Generate and code event handlers for the Buttons


For each Button, create an event handler to specify the action to take when the Button is clicked. Flash Builder
generates stubs for event handlers, which you can then code to specify the service actions to take.
1 Select the Add button. In Properties view, near the On Click field of the Add button, click the icon. Select Generate
Event Handler.
The MXML editor changes to Source View, placing the cursor in the generated event handler.
2 In the event handler body, specify the implementation for the event.
The data types differ slightly for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:
var e:Employee = new Employee();
e.first_name = "New";
e.last_name = "New";
e.birth_date = "2000-01-01";
e.hire_date = "2000-01-01";
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;

Server-side typing:
var e:Employee = new Employee();
e.fname = "New";
e.lname = "New";
e.bdate = "2000-01-01";
e.hdate = "2000-01-01";
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;

3 In the Script block, add the following import statements after the existing import statements:
import services.employeeservice.EmployeeService;
import valueObjects.Employee;

4 In Design mode, add an On Click event handler for the Delete button.
The data types differ slightly for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:
employeeService.deleteEmployees(dg.selectedItem.emp_no);

Server-side typing:
employeeService.deleteEmployees(dg.selectedItem.emp_id);

5 Similarly, add an On Click event handler for the Revert button with the following code:
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).revertChanges();
getAllEmployeesResult.token = employeeService.getAllEmployees();

6 Add an On click event handler for the Save All Changes button with the following code:
employeeService.commit();

7 For the creationCompleteHandler() for the DataGrid, add the following lines of code:

Last updated 6/1/2010


FLEX TUTORIALS 68
Using data management to synchronize server updates

protected function dg_creationCompleteHandler(event:FlexEvent):void


{
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).autoCommit=false;

employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).deleteItemOnRemoveFro
mFill=true;
getAllItemsResult.token = employeeService.getAllEmployees();
}

This code makes sure that deleted items can be reverted by selecting the Revert button.
8 Save the application and select Run > Run DataMgtPHP.

You can update employees in place in the DataGrid. When you click Save All Changes, the changes are updated on
the server. The server is updated because the data management feature calls the updateEmployees() operation to
keep the data synchronized between the client and the server.
Click the Revert button to undo any changes you made before you click Save All Changes.
You can add and delete employees. When you add and delete employees, the data management features take care
of adding or removing the DataGrid rows. Without data management enabled, you code the updates to the
DataGrid yourself.
When you add an employee, the Employee Number defaults to zero. This default value is because the new employee
has not been updated on the server. When you click Save All Changes, the new employee is added to the server. At
that time, an Employee Number is generated.
Click the Save All Changes button to write all changes to the database.

Last updated 6/1/2010

You might also like