flex_4_tutorials

46
Tutorials ADOBE ® FLEX 4 ® Prerelease - 5 October 2009

Transcript of flex_4_tutorials

Page 1: flex_4_tutorials

TutorialsADOBE® FLEX 4 ® ™

Prerelease - 5 October 2009

Page 2: flex_4_tutorials

Copyright© 2009 Adobe Systems Incorporated. All rights reserved.

Adobe® Flex® 4 Tutorials. Prerelease version.

This prerelease version of the Software may not contain trademark and copyright notices that will appear in the commercially available version of the Software.

Adobe, the Adobe logo, Flash, 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.

Prerelease - 5 October 2009

Page 3: flex_4_tutorials

iii

Contents

Chapter 1: Building a basic application

Create and run an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Correct coding errors and export the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Chapter 2: Creating ColdFusion services for client applications

Create a ColdFusion component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Test the ColdFusion service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Chapter 3: Creating PHP services for client applications

Create a PHP class that implements a service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Test the PHP service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Import the service into Flex and bind returned data to application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Chapter 4: Importing a Service into Flex

Import a service and bind returned data to application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Examine the generated code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Chapter 5: Querying a database

Listing records from a database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Chapter 6: Installing the tutorial database

Download and install the tutorial database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Chapter 7: Manage the access of data through paging

Paging (ColdFusion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Paging tutorial (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Chapter 8: Using data management to synchronize server updates

Data Management (ColdFusion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Data Management (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Prerelease - 5 October 2009

Page 4: flex_4_tutorials

1

Chapter 1: Building a basic application

When you create an application in Flash Builder, you first create a project file. The project file contains a default

MXML application which you can edit in either Design View or Source View of the Flash Builder source editor.

If there are errors in your code, Flash Builder flags them for easy access to the offending code.

After creating the application, export a release version of the application.

Create and run an application

The application you create contains a Label component that displays styled text.

1 In Flash Builder, select File > New > Flex Project.

2 Specify Hello for the project name.

3 Make sure that the following default settings are correctly specified:

4 Click Finish.

Flash Builder creates the project and opens an empty MXML application source file in Source View.

Flex projects always contain application source files. An MXML file is a source file providing an interface to an

application. The Flex project also contains compiled versions of the application, libraries, and other assets used by

the application.

5 Select Design.

Flash Builder switches to Design View.

Application Type Web

Flex SDK Version Use Default SDK

Application Server Type None/Other

Prerelease - 5 October 2009

Page 5: flex_4_tutorials

2FLEX 4 TUTORIALS

Building a basic application

6 In the Components View, make sure that the Controls folder is open. Scroll the controls to find the Label control.

7 Drag a Label component from the Components View to the editing area of Design View.

8 Make sure the Label component is still selected. In the Properties view, select the Text field and replace the default

text with Hello.

9 In the Properties view, modify the appearance of the text by specifying the following:

10 Select Source to switch to Source View.

A Label tag has been inserted into the MXML file. The Label tag contains attributes for the values you specified in

Design View.

11 Place the cursor after the last attribute in the Label tag. Type a space. Then begin typing col to add the color

attribute.

Font Size 24

Font Attribute Bold

Font Attribute Italic

Prerelease - 5 October 2009

Page 6: flex_4_tutorials

3FLEX 4 TUTORIALS

Building a basic application

A list of available attributes updates as you type. If you click an attribute in the list, documentation for the attribute

appears.

Double-click the color attribute and specify red.

12 Save the file, and then click the Run button to run the application.

Run button

The application runs in a web browser.

Correct coding errors and export the application

Introduce an error in an application. Then find and fix the error. Finally, export a release version of the application.

1 In the Hello.mxml file created in the previous procedure, delete the closing angle bracket in the Label tag.

Change /> to /.

2 Save the file.

When you save a file, Flash Builder automatically compiles the application. Flash Builder flags errors in the Package

Explorer and source code. Flash Builder lists errors in the Problems View.

Prerelease - 5 October 2009

Page 7: flex_4_tutorials

4FLEX 4 TUTORIALS

Building a basic application

The Problems View is now visible. Expand the Errors list to view the error. Double-click the error to go directly to

the source code.

3 Fix the error and click Save.

There are no errors listed in Problems View.

4 Select the Export Release Build button to create a release version of the application.

5 In the Export Release Build dialog box, select the Enable View Source check box. Accept the default settings. Click

Finish.

Prerelease - 5 October 2009

Page 8: flex_4_tutorials

5FLEX 4 TUTORIALS

Building a basic application

Flash Builder creates a bin-release folder and places the application and its assets in this folder. The application is

ready to be deployed.

During application development, Flash Builder compiles the application into a SWF file that contains debug

information. The default location for the SWF file is the bin-debug folder in your Flex project. You can export a

release version of the application, which does not contain the debug information. The default location for a release

version is the bin-release folder in your Flex project.

Prerelease - 5 October 2009

Page 9: flex_4_tutorials

6

Chapter 2: Creating ColdFusion 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 ColdFusion services can be applied to other service technologies.

Create a ColdFusion component

Create a ColdFusion component (CFC) that can be accessed as a service by Flex over the Internet.

1 Code the following CFC:

<cfcomponent> <cffunction name="getMessage" access="remote" returntype="string">

<cfset message = "Hello from CF!"> <cfreturn message>

</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.

2 Save the CFC as HelloService.cfc in your web root. Place it in a folder named HelloCF.

<CF Web Root>/HelloCF/HelloService.cfc

3 In HelloService.cfc, add operations that return localized messages and locales.

Prerelease - 5 October 2009

Page 10: flex_4_tutorials

7FLEX 4 TUTORIALS

Creating ColdFusion services for client applications

<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>

The getLocalizedMessage() function specifies an argument of type string. The getLocales() function returns

an array of strings.

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 getMessage()... <cfinvoke component="HelloService" method="getMessage" returnvariable="message"/> <p> Result: <cfdump var="#message#"/> </p> 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:

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

Prerelease - 5 October 2009

Page 11: flex_4_tutorials

8FLEX 4 TUTORIALS

Creating ColdFusion services for client applications

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.

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

helloservicetest.cfm:

Prerelease - 5 October 2009

Page 12: flex_4_tutorials

9FLEX 4 TUTORIALS

Creating ColdFusion services for client applications

Testing getMessage()... <cfinvoke component="HelloService" method="getMessage" returnvariable="message"/> <cftrace category="getMessage End" inline="yes" var="message" text="GetMessage 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

Testing a service directly from a URL

Prerelease - 5 October 2009

Page 13: flex_4_tutorials

10

Chapter 3: 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 tutorial database” on page 26.

1 In your web root, create a folder named PHP_Service. Within that folder, create another folder named services.

2 In your favorite PHP editor, create the following PHP class:

<?php class EmployeeService {

public function getEmployees() { $connection = mysqli_connect("localhost", "USER", "PASSWORD",

"fb_tutorial_db") or die(mysqli_connect_error());

$sql = "SELECT * FROM employees"; $result = mysqli_query($connection, $sql)

or die('Query failed: ' . mysql_error($connection));

$rows = array(); while ($row = mysqli_fetch_object($result)) {

$rows[] = $row; } return $rows;

}

} ?>

This is not an exercise in object-oriented programming with PHP. The PHP class contains functions that

implement data service operations. Flex introspects the service operations in the PHP class to create ActionScript

classes in the client application. The client application access the data service using these ActionScript classes.

3 Save the PHP file as EmployeeService.php and place it in the following location:

<Web Root>/PHP_Service/services/EmployeeService.php

Prerelease - 5 October 2009

Page 14: flex_4_tutorials

11FLEX 4 TUTORIALS

Creating PHP services for client applications

Note: Make sure the filename corresponds to the name of the class implementing the PHP service.

4 In EmployeeService.php, examine the code that makes a call to the database and that handles the data returned

by the operation.

• Call the database:

$sql = "SELECT * FROM employees"; $result = mysqli_query($connection, $sql)

or die('Query failed: ' . mysql_error($connection));

This is a basic PHP call to a database, returning a result set.

• Handle the data returned by the operation:

$rows = array(); while ($row = mysqli_fetch_object($result)) {

$rows[] = $row; } return $rows;

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.

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('PHP_Service.php'); $o = new PHP_Service(); 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:

Prerelease - 5 October 2009

Page 15: flex_4_tutorials

12FLEX 4 TUTORIALS

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)

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.

Prerelease - 5 October 2009

Page 16: flex_4_tutorials

13FLEX 4 TUTORIALS

Creating PHP 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 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 PHP_Service 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>/PHP_Service/

5 Click Finish.

The Flash builder source editor opens to PHP_Service.mxml.

Prerelease - 5 October 2009

Page 17: flex_4_tutorials

14FLEX 4 TUTORIALS

Creating PHP services for client applications

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 With the DataGrid selected, in the Properties view, click the Bind to Data button.

The Bind to Data button is next to the Data Provider field in the Properties view.

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 PHPservice.php file you created previously. Click Finish.

The path to the file is:

<Web Root>/PHP_Service/services/EmployeeService.php

The Data Services View now displays the EmployeeService.

11 With the DataGrid selected, again click the Data Provider button in the Properties view.

The Bind to Data dialog opens with New Service Call selected.

EmployeeService is the only service available in the Flex project.

getBooks() 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 needs to know 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. Click Finish.

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.

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.

Prerelease - 5 October 2009

Page 18: flex_4_tutorials

15FLEX 4 TUTORIALS

Creating PHP services for client applications

d In the Header Text field, rename the 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.

The application runs in a web browser.

Prerelease - 5 October 2009

Page 19: flex_4_tutorials

16

Chapter 4: Importing a Service into Flex

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. It also shows how to bind the

data returned from the service to a Flex user interface component. Finally, the tutorial examines the generated code.

Import a service and bind returned data to application components

This tutorial assumes that you have completed the earlier tutorials, “Building a basic application” on page 1, and

“Creating ColdFusion services for client applications” on page 6.

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.

Prerelease - 5 October 2009

Page 20: flex_4_tutorials

17FLEX 4 TUTORIALS

Importing a Service into Flex

Specify project name and server type

3 Click Next. Verify your ColdFusion server configuration and click Validate Configuration.

4 For Output Folder, specify the HelloCF folder you created previously for the Hello project.

Flash Builder suggests a default location of HelloCF-debug for the output folder. Use the location from the

previous tutorial that already contains HelloWorld.cfc.

5 Click Finish.

The Flash builder source editor opens to HelloCF.mxml.

6 Copy the Label component you created in Hello.mxml and paste it into HelloCF.mxml. Save and run

HelloCF.mxml.

You can copy the component from either Design View or Source View of the editor.

Running the HelloCF.mxml application gives the same results as Hello.mxml.

Prerelease - 5 October 2009

Page 21: flex_4_tutorials

18FLEX 4 TUTORIALS

Importing a Service into Flex

HelloCF application

7 In the Data Services View of Flash Builder, select Connect To Service.

Data Services View

8 Select ColdFusion as the service type and click Next.

Select service type

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

HelloService.

Prerelease - 5 October 2009

Page 22: flex_4_tutorials

19FLEX 4 TUTORIALS

Importing a Service into Flex

Importing a ColdFusion Service

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

The Data Services View now displays your ColdFusion service.

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.

11 Select Design to open Design View, and then select the RichEditableText component.

12 In the Properties view, select the Bind to Data button for the RichEditableText component.

Binding data to a component from the Property Inspector

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 Property Inspector,

you can bind to data from the context menu. You can also select Bind to Data from the Flash Builder Data menu.

13 In the Bind to Data dialog, make sure that New Service Call is selected. For Operation select getMessage. Click OK.

Prerelease - 5 October 2009

Page 23: flex_4_tutorials

20FLEX 4 TUTORIALS

Importing a Service into Flex

Select the operation for binding data

Design View showing data binding

14 Save and run the application.

The Text component displays the message retrieved from the HelloService.

Application accessing remote service

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

Prerelease - 5 October 2009

Page 24: flex_4_tutorials

21FLEX 4 TUTORIALS

Importing a Service into Flex

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 RichEditableText component in the HelloCF.mxml source code:

<s:RichEditableText x="70" y="60" text="{getMessageResult.lastResult}" fontWeight="bold" fontSize="24" fontStyle="italic" color="red" id="richEditableText" creationComplete="richEditableText_creationCompleteHandler(event)"/>

The creationComplete event fires after the application creates the component. For this RichEditableText

component, creationComplete calls an event handler that Flash Builder generated for the event. Examine the code

for the event handler, which is placed inside of a Script block:

<fx:Script> <![CDATA[

import mx.events.FlexEvent; import mx.controls.Alert;

protected function richEditableText_creationCompleteHandler(event:FlexEvent):void {

getMessageResult.token = helloService.getMessage(); }

]]>

</fx:Script>

The creationComplete event handler calls the getMessage operation from the ColdFusion service.

Other events, such as a Click event on a button or a selectionChange event of a list, can be used 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

invoke 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:

Prerelease - 5 October 2009

Page 25: flex_4_tutorials

22FLEX 4 TUTORIALS

Importing a Service into Flex

<fx:Declarations> <s:CallResponder id="getMessageResult"/> <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

invoke the getMessage(), getLocales(), and getLocalizedMessage operations of the service.

The CallResponder, identified by the getMessageResult 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 UI 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 RichEditableText component.

Examine the data binding for the RichEditableText component:

<s:RichEditableText x="70" y="60" text="{getMessageResult.lastResult}" fontWeight="bold" fontSize="24" fontStyle="italic" color="red" id="richEditableText" creationComplete="richEditableText_creationCompleteHandler(event)"/>

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

attribute for the RichEditableText component.

Code generation summary

In summary, Flash Builder generates code to access the imported service in the client application:

• After Flex creates the RichEditableText 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 RichEditableText component, which is bound to the lastResult attribute, updates with

the returned data.

Prerelease - 5 October 2009

Page 26: flex_4_tutorials

23

Chapter 5: Querying a database

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.

Listing records from 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 might

have access to.

1 In your favorite ColdFusion editor, create the following CFC.

This CFC selects all the records from the Books table in the cfbookclub database.

<cfcomponent> <cffunction name="getBooks" access="remote" returntype="query">

<cfquery name="qBooks" datasource="cfbookclub"> SELECT * FROM Books

</cfquery> <cfreturn qBooks>

</cffunction> </cfcomponent>

2 Save the CFC as BookService.cfc in your web root. Place it in a folder named books.

<CF Web Root>/books/BookService.cfc

3 Test the CFC before implementing it in an application.

It is always a good idea to test a service before importing it into a Flex project.

a Create the following ColdFusion script 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#"/>

b Save the script as bookservicetest.cfm in the books folder next to BookService.cfc.

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

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

4 In Flash Builder, create a ColdFusion server project and name it Books.

Prerelease - 5 October 2009

Page 27: flex_4_tutorials

24FLEX 4 TUTORIALS

Querying a database

Be sure to set the Application Server Type to ColdFusion. Enable Use Remote Object Access Service and select

ColdFusion Flash Remoting.

Set the output folder to the books folder containing the service.

5 In Design View, add a DataGrid control to the application.

The DataGrid component is available under Data Controls in the Components view.

6 With the DataGrid selected, in the Properties view, click the Bind to Data button.

The Bind to Data button is next to the Data Provider field in the Properties view.

7 In the No Services Defined dialog, click Yes to connect to a service.

8 In the New Flex Service wizard, select ColdFusion. 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.

9 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.

10 With the DataGrid selected, click the Data Provider button in the Properties view.

The Bind to Data dialog 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.

11 In the Bind to Data dialog, select Configure Return Type to define the data type for returned data.

Flex needs to know 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.

12 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.

13 Specify Book in the Array Of field to define a custom type for returned data. Click Finish.

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 and modify the properties of the data type before

proceeding.

14 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 Book property to a column in the DataGrid.

15 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.

Prerelease - 5 October 2009

Page 28: flex_4_tutorials

25FLEX 4 TUTORIALS

Querying a database

d Rename the GENRE column to Genre.

e With the GENRE column selected, click Down to rearrange the order of the columns.

f Click OK.

16 In Design View, resize the DataGrid to a more normal shape, then save and run the application.

Prerelease - 5 October 2009

Page 29: flex_4_tutorials

26

Chapter 6: Installing the tutorial database

Several of the tutorials show how to access data returned from a database. The tutorials use a MySQL database that is

available from either a PHP or ColdFusion installation.

Download and install the tutorial database

1 Download Flex Builder Tutorial Database and unzip it into a temporary directory on your computer.

The downloaded ZIP file contains two SQL files:

• fb_tutorial_db.sql

Use this file to import the entire database into your MySQL installation. It creates the fb_tutorial_db database

and the employees table.

• fb_tutorial_table.sql

Use this file to import just the employees table into an existing database. This file is provided in case you do not

have privileges to create a database in your MySQL installation. Refer to the README file for information on

importing this file.

2 Execute the following command from a terminal window for your operating system.

<MySQL_Install_Dir>/bin/mysql -u root -p < fb_tutorial_db.sql

3 (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:

4 (Optional) Verify the memory resources configuration in php.ini.

The fb_tutorial_db database contains a table with 1000 records. If the memory resources configuration in your

php.ini file are set too low, you might encounter problems accessing the database.

In the Resource Limits section of php.ini, modify the memory resources setting to ensure access to the database:

memory_limit = 128M

Configuration Field Value

CF Data Source Name fb_tutorial_db

Database fb_tutorial_db

Server 127.0.0.1

Port 3306

Prerelease - 5 October 2009

Page 30: flex_4_tutorials

27

Chapter 7: 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 (ColdFusion)

The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this

database, see “Installing the tutorial database” on page 26

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 favorite ColdFusion editor, create a ColdFusion service that implements the required paging functions.

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

<cfargument name="startIndex" type="numeric" required="true" /> <cfargument name="numItems" type="numeric" required="true" />

<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>

2 Save the CFC as PagingService.cfc in your web root. Place it in a folder named PagingCF.

Prerelease - 5 October 2009

Page 31: flex_4_tutorials

28FLEX 4 TUTORIALS

Manage the access of data through paging

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

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 1. Click Finish.

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:

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, specify the count() operation from the drop-down list. Click Finish.

You do not have to specify the number of records to retrieve for each page operation.

Create an application and bind getItems_paged() to a DataGrid

1 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.

5 In the Bind to Data operation, select New Service Call. For the PagingService, select the getItems_paged()

operation. 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.

Argument Argument Type Value

startIndex Number 0

numItems Number 10

Prerelease - 5 October 2009

Page 32: flex_4_tutorials

29FLEX 4 TUTORIALS

Manage the access of data through paging

Paging tutorial (PHP)

The application you create in this tutorial accesses the employee database that you previously downloaded and

installed.

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 favorite PHP editor, create a PHP service class that implements the required paging functions.

<?php class PagingService {

/* connection variables */ var $username = "root"; var $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();

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) {

Prerelease - 5 October 2009

Page 33: flex_4_tutorials

30FLEX 4 TUTORIALS

Manage the access of data through paging

$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);

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);

} }

} ?>

2 Modify the connection variables to provide your server, username, and password for access to the fb_tutorial_db

database.

3 Save the service in the web root of your PHP installation, as described below.

• In your web root directory, create a directory named PagingPHP.

• In the PagingPHP directory, create a directory named services.

• Name the file PagingService.php and save it the services directory.

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

Click Next.

Prerelease - 5 October 2009

Page 34: flex_4_tutorials

31FLEX 4 TUTORIALS

Manage the access of data through paging

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.

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:

11 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.

12 Click Finish to configure the Employee return type.

13 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, specify the count() operation from the drop-down list. Click Finish

You do not have to specify the number of records to retrieve for each page operation.

Create an application and bind getItems_paged() to a DataGrid

1 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.

5 In the Bind to Data operation, select New Service Call, then select the get Items Paged() operation from the

drop-down list, and 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.

Argument Argument Type Value

startIndex int 0

numItems int 10

Prerelease - 5 October 2009

Page 35: flex_4_tutorials

32

Chapter 8: 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.

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.

Data Management (ColdFusion)

The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this

database, see “Installing the tutorial database” on page 26

In this tutorial, you create an application that contains an editable DataGrid displaying employee records. You can

modify one or more records in place in the DataGrid. You can also add or delete selected records from the DataGrid.

All the changes in the DataGrid are local until you select a Save All Changes button that updates the database.

Create the remote service and import it into a Flex project

1 In your favorite ColdFusion editor, create a ColdFusion service that implements the required data management

functions.

Prerelease - 5 October 2009

Page 36: flex_4_tutorials

33FLEX 4 TUTORIALS

Using data management to synchronize server updates

<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#">,

Prerelease - 5 October 2009

Page 37: flex_4_tutorials

34FLEX 4 TUTORIALS

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>

2 Save the service in the web root of your ColdFusion installation.

Name the file EmployeeService.cfc and place it in a directory named DataMgtCF.

3 In Flash Builder, create a Flex project. Name the project DataMgtCF 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

4 Validate your ColdFusion settings and specify the DataMgtCF 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 EmployeeService.cfc file you created in step 1. Click Finish.

7 In the Flash Builder Data/Services view, from the context menu for the getItem() operation, select Configure

Return Type.

Flash Builder needs to configure 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:

You need to supply valid parameters to the operation for Flash Builder to introspect the operation. 10002 is a valid

itemID.

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.

Argument Argument Type Value

itemID Number 10002

Prerelease - 5 October 2009

Page 38: flex_4_tutorials

35FLEX 4 TUTORIALS

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 Select Use an Existing Data Type. Select Employee from the Array Of drop-down list. Click Finish.

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_no and click Next.

4 In the Map Database Operations dialog, specify the following operations. Click Finish.

• Create (Add) Operation: createItem( item: Employee )

• Get Item Operation: getItem( itemID: Number )

• Update Operation: updateItem( item: Employee )

• Delete Operation: deleteItem ( itemID: Number )

Data management is now enabled for this operation. Flash Builder generates client code that can update data using

a combination of the mapped operations.

Create the application and add a DataGrid and Buttons

1 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:

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:

6 In the Data/Services view, select the getAllItems() operation and drop it onto the DataGrid.

7 With the DataGrid selected, in the Properties view Click Configure Columns and do the following:

• Select emp_no column. In the Data Binding area, deselect the editable check box.

emp_no is a key field that is automatically generated by the database.

Property Value

ID dg

Editable true

Label

Add

Delete

Revert

Save All Changes

Prerelease - 5 October 2009

Page 39: flex_4_tutorials

36FLEX 4 TUTORIALS

Using data management to synchronize server updates

• (Optional) Rename and rearrange the columns.

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. Then, for the On Click field of the Add button, click the Pencil icon and then select Generate

Event Handler.

The MXML editor changes to Source View, placing the cursor in the generated event handler.

2 In the Script block, add the following import statement:

import services.employeeservice.EmployeeService; import valueObjects.Employee;

3 In the event handler body, type the following:

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;

As you type, Flash Builder content assist helps you view the available methods and values.

4 Modify the DataGrid columns for birth_date and hire_date to add a date chooser:

<mx:DataGridColumn headerText="birth_date" editorDataField="selectedDate" dataField="birth_date" itemEditor="mx.controls.DateField"/>

<mx:DataGridColumn headerText="hire_date" editorDataField="selectedDate"

dataField="hire_date" itemEditor="mx.controls.DateField"/>

5 In Design mode, add an On Click event handler for the Delete button and specify the following code:

employeeService.deleteItem(dg.selectedItem.emp_no);

6 Similarly, add an On Click event handler for the Revert button with the following code:

employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).revertChanges();

7 Add an On click event handler for the Save All Changes button with the following code:

employeeService.commit();

8 Save the application and select Run > Run DataMgtCF.

You can update and delete selected employees in the DataGrid. You can also add new employees.

When you add an employee, the Employee Number defaults to zero. This 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 Revert button to undo any changes you made.

Click the Save All Changes button to write all changes to the database.

Prerelease - 5 October 2009

Page 40: flex_4_tutorials

37FLEX 4 TUTORIALS

Using data management to synchronize server updates

Data Management (PHP)

The application you create in this tutorial accesses the employee database that you previously downloaded and

installed.

In this tutorial, you create an application that contains an editable DataGrid displaying employee records. You can

modify one or more records in place in the DataGrid, and also add or delete selected records from the DataGrid. All

the changes in the DataGrid are local until you select a Save All Changes button, which updates the database.

Create the remote service and import it into a Flex project

1 In your favorite PHP editor, create a PHP service class that implements the required data management functions.

<?php class EmployeeService {

var $username = "root"; var $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);

Prerelease - 5 October 2009

Page 41: flex_4_tutorials

38FLEX 4 TUTORIALS

Using data management to synchronize server updates

}

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();

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 (emp_no, birth_date, first_name, last_name, gender, hire_date) VALUES (?, ?, ?, ?, ?, ?)");

$this->throwExceptionOnError();

mysqli_bind_param($stmt, 'isssss', $item->emp_no, $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=?

Prerelease - 5 October 2009

Page 42: flex_4_tutorials

39FLEX 4 TUTORIALS

Using data management to synchronize server updates

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);

}

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);

} }

} ?>

2 Modify the connection variables to provide your server, username, and password for access to the fb_tutorial_db

database.

3 Save the service in the web root of your PHP installation, as described below.

• In your web root directory, create a directory named DataMgtPHP.

• In the DataMgtPHP directory, create a directory named services.

• Name the file EmployeeService.php and save it in the services directory.

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

Click Next.

Prerelease - 5 October 2009

Page 43: flex_4_tutorials

40FLEX 4 TUTORIALS

Using data management to synchronize server updates

5 Specify the Web Root and Root URL for your system. Validate your server settings and specify the DataMgtPHP

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 EmployeeService.php file you created in step 1. Select EmployeeService.php and

click Finish.

8 In the Flash Builder Data/Services view, from the context menu for the getEmployeesbyID() operation, select

Configure Return Type.

Flash Builder needs to configure 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:

You need to supply valid parameters to the operation for Flash Builder to introspect the operation. 10002 is a valid

itemID.

11 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.

12 Click Finish to configure the Employee return type.

13 In the Flash Builder Data/Services view, from the context menu for the getAllItems() operation, select Configure

Return Type.

14 Configure the return type for the deleteEmployees(), specifying the parameter and type as described below. Click

Next and Finish.

15 Select Use an Existing Data Type. Select Employee from the Array Of drop-down list. Click Finish.

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_no and click Next.

4 In the Map Database Operations dialog, specify the following operations and click Finish.

• Create (Add) Operation: createEmployees( item: Employee )

• Get Item Operation: getEmployeesByID( itemID: Number )

• Update Operation: updateEmployees( item: Employee )

• Delete Operation: deleteEmployees ( itemID: Number )

Argument Argument Type Value

itemID int 10002

Argument Argument Type Value

itemID int 10001

Prerelease - 5 October 2009

Page 44: flex_4_tutorials

41FLEX 4 TUTORIALS

Using data management to synchronize server updates

Data management is now enabled for this operation. Flash Builder generates client code that can update data using

a combination of the mapped operations.

Create the application and add a DataGrid and Buttons

1 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:

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:

6 In the Data/Services view, select the getAllEmployees() operation and drop it onto the DataGrid.

7 With the DataGrid selected, in the Properties view Click Configure Columns and do the following:

• Select emp_no column. In the Data Binding area, deselect the editable check box.

emp_no is a key field that is automatically generated by the database.

• (Optional) Rename and rearrange the columns.

8 (Optional) Click Configure Columns to rename and rearrange the columns.

Generate and code event handlers for the Buttons

Each Button needs 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. Then, for the On Click field of the Add button, click the Pencil icon and then select Generate

Event Handler.

The MXML editor changes to Source View, placing the cursor in the generated event handler.

2 In the Script block, add the following import statement:

import services.employeeservice.EmployeeService; import valueObjects.Employee;

3 In the event handler body, type the following:

Property Value

ID dg

Editable true

Label

Add

Delete

Revert

Save All Changes

Prerelease - 5 October 2009

Page 45: flex_4_tutorials

42FLEX 4 TUTORIALS

Using data management to synchronize server updates

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;

As you type, Flash Builder content assist helps you view the available methods and values.

4 In Design mode, add an On Click event handler for the Delete button and specify the following code:

employeeService.deleteEmployees(dg.selectedItem.emp_no);

5 Similarly, add an On Click event handler for the Revert button with the following code:

employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).revertChanges();

6 Add an On click event handler for the Save All Changes button with the following code:

employeeService.commit();

7 Save the application and select Run > Run DataMgtPHP.

You can update and delete selected employees in the DataGrid. You can also add new employees.

When you add an employee, the Employee Number defaults to zero. This 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 Revert button to undo any changes you made.

Click the Save All Changes button to write all changes to the database.

Prerelease - 5 October 2009

Page 46: flex_4_tutorials

43

Prerelease - 5 October 2009