ADOBE® FLEX® 4 Tutorials

Last updated 3/21/2010

© 2010 Adobe Systems Incorporated. All rights reserved.
Copyright

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, 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 3/21/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 (Optional) Test the ColdFusion service Connect to the ColdFusion service Examine the generated code ............................................................... 5 ................................................................................. 6

..................................................................................... 9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Import the service into Flex and bind returned data to application components

Chapter 4: Creating PHP services for client applications Create a PHP class that implements a service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 (Optional) Test the PHP service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Import the service into Flex and bind returned data to application components

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) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Data management tutorial (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

you bind the data returned from the ColdFusion service to the Label item. 2 Specify HelloCF for the project name. The remote service returns only data.Last updated 3/21/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. 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. select File > New > Flex Project. separates client code from server code. you examine the generated code to see how Flex accesses the data returned from the service. Next. Finally. Create the application 1 In Flash Builder. Then. it dynamically embeds HTML code with returned data. You first create a Label item that displays static text. you create a ColdFusion service that returns a localized text string. . a server template mixes server code with client code. Flex. set Application Server Type to ColdFusion. When the client queries a database. In a traditional relationship. and specify ColdFusion Flash Remoting. however.

4 Click Finish. make sure that the Controls folder is open.Last updated 3/21/2010 FLEX TUTORIALS 2 Import a service and bind data to application components Specify project name and server type 3 Click Next. Scroll the controls to find the Label control. .mxml. 6 In the Components View. The Flash builder source editor opens to Hello. Verify your ColdFusion server configuration and click Validate Configuration. select Design to switch to Design mode of the editor. 5 If Design mode is not selected.

With the Label component selected. specify the following: Font Size Font Attribute Font Attribute 24 Bold Italic Select the font attributes . modify the appearance of the text. 9 In the Properties view. 8 Double-click the Label component.Last updated 3/21/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. Replace the default text with Hello.

Click the Run button to run the application. Run button .Last updated 3/21/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.

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.Last updated 3/21/2010 FLEX TUTORIALS 5 Import a service and bind data to application components The application runs in a web browser. 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: .

cfm.cfm in the same folder as HelloService. <cfinvoke component="HelloService" method="getLocalizedMessage" locale="es" returnvariable="message"/> <p> Result: <cfdump var="#message#"/> </p> 2 Save helloservicetest. Make sure to specify remote as the access type for the function. <cfinvoke component="HelloService" method="getLocales" returnvariable="locales"/> <p> Result: <cfdump var="#locales#"/> </p> Testing getLocalizedMessage("es"). and call the script from a web browser: .Last updated 3/21/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. (Optional) Test the ColdFusion service There are various ways to test the service before you access it from an application. helloservicetest.. Testing getLocales(). Use the cfdump tag to view the results.es.ne")/> <cfreturn codes> </cffunction> </cfcomponent> The function getMessage() is a service operation that client applications access.. that calls the service and displays the returned data in HTML. Use the cfinvoke tag to call the service.. 1 Create a ColdFusion script file..cfc.

ColdFusion displays detailed information about the error. You can also enable Robust Exception Information for the ColdFusion server to get detailed debugging output. enable debugging and logging. In the ColdFusion Administrator.cfm Using cfinvoke and cfdump If there is an error in the service.Last updated 3/21/2010 FLEX TUTORIALS 7 Import a service and bind data to application components http://localhost:8500/HelloCF/helloservicetest. 3 Add trace statements to the service. .

. Use Test Operation.cfc?method=getLocalizedMessage&locale=es Note: You can also test a service after importing the service into Flash Builder. For example. Call the script from a web browser to view the debugging output. which is available from the Data/Service view. .Last updated 3/21/2010 FLEX TUTORIALS 8 Import a service and bind data to application components Add ColdFusion trace statements as necessary to debug your service. You can also inspect the ColdFusion log files. . call getLocalizedMessage() with the parameter es: http://localhost:8500/HelloCF/HelloService..cfm: Testing getLocalizedMessage(). For example. add the following line in helloservicetest. Testing a service directly from a URL 4 Call a function in the service directly from a URL. <cfinvoke component="HelloService" method="getLocalizedMessage" locale="es" returnvariable="message"/> <p> Result: <cfdump var="#message#"/> </p> <cftrace category="getLocalizedMessage End" inline="yes" var="message" text="GetLocalizedMessage call has completed"> . .

Provide your credentials to log in to the ColdFusion database. 1 In Design mode of the MXML editor. Data Services View .mxml is open. connect to the ColdFusion service and bind the data returned from the service to the Label component.cfc you previously created. The Data Services View now displays your ColdFusion service. select Connect To Data/Service. From the Flash Builder Data menu. Flash Builder names the service HelloService.Last updated 3/21/2010 FLEX TUTORIALS 9 Import a service and bind data to application components Connect to the ColdFusion service In Flash Builder. 2 Select ColdFusion as the service type. Select service type 3 Click Browse and navigate to the HelloService. Click Next. make sure HelloCF. Importing a ColdFusion Service 4 Click Finish.

7 In the Bind to Data dialog. 8 Type “es” for the parameter value for getLocalizedMessage(). highlighting the parameter to getLocalizedMessage(). make sure that New Service Call is selected. 6 Select OK to replace the current text with the text returned from a service operation. Design mode showing data binding 9 Save and run the application. Switch to Design mode of the editor. For Operation select getLocalizedMessage. Click OK. . This view becomes useful when you configure types for data returned by a service call. you can bind to data from the context menu.Last updated 3/21/2010 FLEX TUTORIALS 10 Import a service and bind data to application components The Data Service View provides a picture of remote services. You can also select Bind to Data from the Flash Builder Data menu. select the Bind to Data button for the Label component. Select the operation for binding data Flash Builder switches the editor to Source mode. From the context menu. 5 Select the Label component in the design area. In addition to the Properties view. Flash Builder provides various ways to bind data to a selected component.

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. Examine the Label component in the HelloCF.Last updated 3/21/2010 FLEX TUTORIALS 11 Import a service and bind data to application components The Label component displays the message retrieved from the HelloService.mxml source code: <s:Label x="70" y="60" text="{getLocalizedMessageResult.” as in server templates. creationComplete calls an event handler that Flash Builder generated for the event. Flex also generates code when you bind operations to application components. Examine the generated code When you imported the ColdFusion service into a client application. Examine the code for the event handler. which is placed inside a Script block: . For this Label component. Event handlers Flex uses event handlers to trigger a service call.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. Just a description of the code generation. Flex code is not processed “top to bottom. Instead. There are no “steps” to this part of the tutorial. By default. applications built with Flex listen for events to trigger responses. Flex uses the creationComplete event on a component to trigger a service call. Flex generated client code that accessed the ColdFusion service.

the component calls the corresponding service operation over the network using the appropriate protocol.token = helloService. Examine the data binding for the Label component: <s:Label x="70" y="60" text="{getLocalizedMessageResult.faultString + '\n' + event.controls. Examine the generated service call and responder: <fx:Declarations> <s:CallResponder id="getLocalizedMessageResult"/> <helloservice:HelloService id="helloService" fault="Alert.fault. to trigger service calls.Last updated 3/21/2010 FLEX TUTORIALS 12 Import a service and bind data to application components <fx:Script> <![CDATA[ import mx. It passes the parameter “es”.fault. You can use other events. } ]]> </fx:Script> The creationComplete event handler calls the getLocalizedMessage() operation from the ColdFusion service. Service calls and responders When you add a service. Data binding Flex data binding allows you to assign the value of the lastResult attribute of a CallResponder to a user interface component. CallResponders allow service calls to operate asynchronously. Flex automatically updates the component. This class contains methods to call the getLocales().Alert. Flex binds the lastResult value to the text attribute of the Label component.lastResult}" fontWeight="bold" fontSize="24" fontStyle="italic" color="red" id="richEditableText" creationComplete="label_creationCompleteHandler(event)"/> . Flex uses curly braces {} to bind data to an attribute of a component. Flex creates a component containing methods that call the service operations. protected function label_creationCompleteHandler(event:FlexEvent):void { getLocalizedMessageResult. When the last result updates. import mx. Service calls are associated with CallResponders.events. identified by the getLocalizedMessageResult id. Data returned from a service call is placed in the lastResult attribute of the CallResponder. provides access to the returned data. The client application can continue to be responsive while the service call is being processed. and getLocalizedMessage operations of the service. The CallResponder.getLocalizedMessage("es").faultDetail)" showBusyCursor="true"/> </fx:Declarations> When you imported the HelloService service. In this example. such as a Click event on a button or a selectionChange event of a list. Flex created the HelloService class.FlexEvent.show(event. When you call one of the methods. which you specified earlier in the source code.

updates with the returned data. the creationComplete event fires. Code generation summary In summary. which is bound to the lastResult attribute. • The text attribute of the Label component. getLocalizedMessageResult. .lastResult. is automatically assigned as the text attribute for the Label component. calling a service operation.Last updated 3/21/2010 FLEX TUTORIALS 13 Import a service and bind data to application components The data returned to the CallResponder. Flash Builder generates code to access the imported service in the client application: • After Flex creates the Label component in the running application. • The data returned from the service call is placed in the lastResult attribute of the associated CallResponder.

which contains three tables.sql Use this file to import just the three tables into an existing database. add fb_tutorial_db as a data source.sql 3 (phpMyAdmin) From the phpMyAdmin home page. Download and install the Flash Builder tutorial database 1 Download Flash Builder Tutorial Database and unzip it into a temporary directory on your computer. Browse to the downloaded SQL file and import the database. which you can access from either a PHP or ColdFusion installation.sql Use this file to import the entire database into your MySQL installation.0. This file is provided in case you do not have privileges to create a database in your MySQL installation. employees. • fb_tutorial_db_tables. The tables in the database are departments. The downloaded ZIP file contains two SQL files: • fb_tutorial_db_full. 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. 4 (ColdFusion) In the ColdFusion Administrator.0.Last updated 3/21/2010 14 Chapter 2: Installing the Flash Builder tutorial database Several of the tutorials show how to access data returned from a database. It creates the fb_tutorial_db database. navigate to the Import page. and dept_emp.1 3306 . 2 (Command Line) Execute the following command from a terminal window for your operating system. The following table lists the settings for the data source using the default configuration for ColdFusion 8: Configuration Field ColdFusion Data Source Name Database Server Port Value fb_tutorial_db fb_tutorial_db 127. <MySQL_Install_Dir>/bin/mysql -u root -p < fb_tutorial_db_full. The tutorials use a MySQL database.

• Binding a CFC service operation to a Flex data control.cfc and place it in the books folder in your web root.Last updated 3/21/2010 15 Chapter 3: Creating ColdFusion services for client applications When you access a remote service. such as a DataGrid.cfc selects all the records from the Books table in the cfbookclub database. you can modify this tutorial to select records from any database you have access to. . Name it BookService. 2 In your favorite ColdFusion editor. 1 In your web root. However. This tutorial shows how to access a remote database and display retrieved records in a DataGrid. create the following CFC. This tutorial assumes that you have a local installation of ColdFusion 8 or ColdFusion 9 and the ColdFusion server is running. create a folder named books. The tutorial illustrates the following concepts: • Using a ColdFusion component (CFC) to implement service operations that query a database. you typically retrieve records from a database and display them in the client application. BookService. It lists the contents of the Books table in the database. Create a CFC that accesses a database This tutorial accesses the cfbookclub database that is provided with a ColdFusion installation. • Running the application and viewing the returned data in the DataGrid. • Sampling the data returned from a service operation to configure a data type for the returned data.

cfm in the books folder next to BookService. 3 From a web browser.Last updated 3/21/2010 FLEX TUTORIALS 16 Creating ColdFusion services for client applications <!--This sample service contains functions that illustrate typical service operations. ColdFusion returns an array of records from the database. accesses the Books table in the cfbookclub database. You can find more information at http://www.adobe. qAllBooks. This code is for prototyping only.Retrieve set of records and return them as a query or array. examine the code that calls the database: Flex expects data returned by the operation to be an object or an array of objects.cfm to test the CFC. Each object in the array corresponds to a retrieved record from the database. Authenticate the user prior to allowing them to call these methods.com/go/cf9_usersecurity ---> <cffunction name="getBooks" output="false" access="remote" returntype="any" > <!--.. containing values for each column in the record. (Optional) Test the service It is always a good idea to test a service before you access it from an application.cfc.cfc. 1 Create bookservicetest. <cfinvoke component="BookService" method="getBooks" returnvariable="books"/> <p> <cfdump var="#books#"/> 2 Save bookservicetest.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. The cfquery. run the script to test the service: . Testing getBooks(). This script uses cfdump to view the results of the service operation. ---> <!--..

cfm You can also test a service after importing the service into Flash Builder. it dynamically embeds HTML code with returned data. In a traditional relationship. . which is available from the Data/Service view. When the client queries a database. Use Test Operation. a server template mixes server code with client code.Last updated 3/21/2010 FLEX TUTORIALS 17 Creating ColdFusion services for client applications http://localhost:8500/books/bookservicetest. 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.

Name the project Books. separates client code from server code. Set the Application Server Type to ColdFusion.Last updated 3/21/2010 FLEX TUTORIALS 18 Creating ColdFusion services for client applications Flex. Click Next.mxml and opens the file in the MXML editor. Validate your configuration. 3 Set the output folder to the books folder containing the service. 2 Click Next. drag a DataGrid control to the design area. 5 From the context menu for the DataGrid. Flash builder creates Books. The DataGrid control is available under Controls in the Components view. click Yes to connect to a service. 7 In the Connect to Data/Service wizard. Select Design to open the editor in Design mode. . Enable Use Remote Object Access Service and select ColdFusion Flash Remoting. select ColdFusion. 4 In Design mode. 6 In the No Services Defined dialog. select New > Flex Project to create a ColdFusion server project. however. Flex binds the returned data to user interface components in the client application. The remote service returns only data. Click Finish. 1 In Flash Builder. select Bind to Data.

it accesses the database to create a value object. Click Finish. In this scenario. 13 In the Bind to Data dialog. Flash Builder uses client-side typing to define a custom data type for the returned data. Then from a user interface component. The properties of the custom data type are derived from the value object. The custom type Book provides access to each field of the record. Flash Builder does not have to configure the data type for returned data. such as those provided by LiveCycle Data Services.cfc you created previously. select Bind to Data. Provide authorization credentials as needed for your system. you connect to a service and specify the remote operation. Flash Builder introspects the service to determine the data and data types returned. Click Finish. You can view the properties of the data type before proceeding. Auto-Detect the Return Type is selected by default. With server-side typing. . getBooks() is the only operation available in the service. Click Next. BookService is the only service available in the Flex project. 12 Specify Book in the Array Of field to define a custom type for returned data. 9 Again. The Data Services View now displays the BookService. The Configure Return Type dialog displays the properties of the data type returned by the service. provide server -side typing. The BookService returns an array of records from the data service.Last updated 3/21/2010 FLEX TUTORIALS 19 Creating ColdFusion services for client applications Flash Builder provides multiple ways to connect to a data service. The Bind to Data dialog now opens with New Service Call selected. you first create the user interface. 10 In the Bind to Data dialog. Each record is a complex data type representing a database record for a book. The BookService service does not define the data type for returned data. click OK. from the context menu for the DataGrid. Some services. When Flash Builder configures a return type. 11 In the Configure Return Type dialog. Flex uses the return data type to access service operations. select Configure Return Type to define the data type for returned data. 8 Click Browse and navigate to the BookService.

Last updated 3/21/2010 FLEX TUTORIALS 20 Creating ColdFusion services for client applications Flash Builder binds the data returned from the service call to the DataGrid component. click Up to rearrange the order of the columns. It modifies the columns of the DataGrid. click Configure Columns and then do the following steps: a Select the ISSPOTLIGHT column. 14 Make sure the DataGrid is still selected. b Delete all columns except TITLE and GENRE. Click Delete to delete the column. d Rename the GENRE column to Genre. e With the GENRE column selected. . In the Properties view. binding the value returned for each Book property to a column in the DataGrid. Edit the Header Text field to rename the column Title. c Select the TITLE column.

grab the far left handle of the DataGrid and resize it to a more normal shape. Save and run the application.Last updated 3/21/2010 FLEX TUTORIALS 21 Creating ColdFusion services for client applications f Click OK. 15 In Design View. .

The principles of creating and testing PHP services can be applied to other service technologies. create another folder named services. create the following PHP file. These technologies include: • ColdFusion • PHP • HTML (REST-style) services • Web services (SOAP) After creating a service. For information on installing this database. Name the file EmployeeService. Place it in the PHPService/services folder. 1 In your web root. which implements EmployeeService. . it is a good idea to test the service before accessing it from a client application.php. see “Installing the Flash Builder tutorial database” on page 14. Create a PHP class that implements a service The service you create in this tutorial accesses the fb_tutorial_db database. Within that folder.Last updated 3/21/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. 2 In your favorite PHP editor. create a folder named PHPService.

$row->gender. $row->emp_no. $this->port ). var $port = "3306". mysqli_stmt_execute($stmt). mysqli_stmt_bind_result($stmt. */ class EmployeeService { var $username = "USERNAME". var $server = "localhost". while (mysqli_stmt_fetch($stmt)) { $rows[] = $row. } public function getEmployees() { $stmt = mysqli_prepare($this->connection. $this->username. $row->emp_no. $this->databasename. var $tablename = "employees". $row = new stdClass(). "SELECT * FROM $this->tablename"). $rows = array(). * * Authenticate users before allowing them to call these methods. $row->gender. $this->password. $this->throwExceptionOnError($this->connection). $row->hire_date). $row->first_name. $this->throwExceptionOnError(). var $databasename = "fb_tutorial_db". $row->hire_date). var $connection.Last updated 3/21/2010 FLEX TUTORIALS 23 Creating PHP services for client applications <?php /** * This sample service contains functions that illustrate typical service operations. */ /** * The constructor initializes the connection to database. $this->throwExceptionOnError(). var $password = "PASSWORD". Everytime a request is * received by Zend AMF. * This code is for prototyping only. $row->first_name. mysqli_stmt_bind_result($stmt. $row->last_name. . $row->birth_date. public function __construct() { $this->connection = mysqli_connect( $this->server. $row->last_name. $row->birth_date. } mysqli_stmt_free_result($stmt). an instance of the service class is created and then the * requested method is called.

examine the code that calls the database. • Call the database: $stmt = mysqli_prepare($this->connection. throw new Exception('MySQL Error . $row->birth_date. mysqli_error($link). This code implements a basic PHP call to a database to return a result set. "SELECT * FROM $this->tablename"). • Connecting to data: The code uses global variables and a constructor function that connects to the database server. */ private function throwExceptionOnError($link = null) { if($link == null) { $link = $this->connection. } if(mysqli_error($link)) { $msg = mysqli_errno($link) . 4 In EmployeeService. Prepares statements provide more security than a basic database query. Substitute your connection settings for the global variables. $row = new stdClass().'. $row->hire_date). mysqli_stmt_execute($stmt). mysqli_stmt_bind_result($stmt. $row->emp_no. The client application accesses the data service using these ActionScript classes. $row->first_name. $row->first_name.Last updated 3/21/2010 FLEX TUTORIALS 24 Creating PHP services for client applications mysqli_close($this->connection). while (mysqli_stmt_fetch($stmt)) { $rows[] = $row.php Note: Make sure that the filename corresponds to the name of the class implementing the PHP service. $row->hire_date). • Return the data as an array of rows: $rows = array(). $row->last_name. } } } ?> This PHP class contains functions that implement data service operations. $msg). ": " . } return $rows. $row->birth_date. . return $rows. mysqli_stmt_bind_result($stmt. $row->gender. 3 Save EmployeeService. Flash Builder introspects the service operations in the PHP class to create ActionScript classes in the client application.php. $row->emp_no.php at the following location: <Web Root>/PHPService/services/EmployeeService. This call uses prepared statements available with the MySQLi extension. $row->last_name. $row->gender. } /** * Utitity function to throw an exception if an error occurs * while running a mysql command.

and call the service from a web browser. var_dump($o->getemployees()). ?> </pre> 2 Save tester. 1 Create a PHP script file. returning an array of objects. $o = new EmployeeService(). Each object in the array corresponds to a retrieved record from the database.php in the same folder as EmployeeService. • Exception handling The code creates a utility function to catch exceptions. <pre> <?php include('EmployeeService. (Optional) Test the PHP service It is always a good idea to test a service before you access it from an application. that calls the service and displays the returned data. tester dumps records from the database: . The code uses bound results for the prepared statement.Last updated 3/21/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. tester. This call allows the values of the result to correctly be bound to expected values of the data. If the call is successful.php. containing values for each column in the record.php. The PHP code that handles the returned result set iterates through the result.php').

. which is available from the Data/Service view. Use Test Operation. PHP displays information to help locate the error. If there is an error in the service. Warning: mysqli_connect() [function.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. . .mysqli-connect]: (28000/1045): Access denied for user 'admin'@'localhost' (using password: YES) in C:\wamp2\www\PHP_Service\services\PHPservice. 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 3/21/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"]=> .

Flex. . The remote service returns only data. 2 Specify PHP_Service for the project name and set the Application Server Type to PHP. Here is the location previously specified: <Web Root>/PHPService/ 5 Click Finish. select File > New > Flex Project.php. Specify project name and server type Note: If you forget to set the application server type when you create the project. however. When the client queries a database. separates client code from server code. Use the location that already contains EmployeeService. 4 For Output Folder. 3 Click Next. a server template mixes server code with client code. Flex binds the returned data to user interface components in the client application.Last updated 3/21/2010 FLEX TUTORIALS 27 Creating PHP services for client applications In a traditional relationship. Verify your PHP configuration and click Validate Configuration. you can later specify the server type from the Project Properties page. Flash Builder suggests a default location for the output folder. it dynamically embeds HTML code with returned data. specify the PHPService folder you created previously. 1 In Flash Builder.

11 With the DataGrid selected. select Configure Return Type to define the data type for returned data. 13 In the Configure Return Type dialog. then from a user interface component. Click Next. . you first create the user interface. 12 In the Bind to Data dialog. Click Next. The Data Services View now displays the EmployeeService. Click Finish. Flash Builder provides multiple ways to connect to a data service. Drag the DataGrid control to the design area. 10 Click Browse and navigate to the PHPservice. 7 From the context menu for the DataGrid. Flex needs uses the return data type to access service operations. 8 In the No Services Defined dialog. select PHP. EmployeeService is the only service available in the Flex project. click Yes to connect to a service. again click the Data Provider button in the Properties view. if necessary. The EmployeeService returns a complex data type representing a database record for an employee. 6 Select Design to open the editor in Design mode. 9 In the New Flex Service wizard. Add a DataGrid control to the application: The DataGrid component is available under Data Controls in the Components view.Last updated 3/21/2010 FLEX TUTORIALS 28 Creating PHP services for client applications The Flash Builder source editor opens to PHP_Service. Auto-Detect the Return Type is selected by default. The path to the file is: <Web Root>/PHP_Service/services/EmployeeService. The EmployeeService service does not define the data type for returned data.php Click Finish.mxml. The Bind to Data dialog opens with New Service Call selected. The custom type Employee provides access to each field of the record. select Bind to Data. getEmployeess() is the only operation available in the service. Flash Builder prompts you to install or update the Zend Framework.php file you created previously. Flash Builder uses client-side typing to define a custom data type for the returned data. In this scenario. 14 Specify Employee for the name of the type. you can connect to a service and specify the remote operation.

click OK. You can view and modify the properties of the data type before proceeding. 18 Select File > Save to save the application file. delete all columns except emp_no. Click Finish. Click Delete to delete the column.Last updated 3/21/2010 FLEX TUTORIALS 29 Creating PHP services for client applications View the properties of the Employee data type returned by the service. When Flash Builder configures a return type. The properties of the custom data type are derived from the value object. f Click OK. click Configure Columns and then do the following steps: a Select the hire_date column. Then select Run > Run PHP_Service to run the application. d In the Header Text field. 16 Make sure the DataGrid is still selected. first_name. and last_name. Flash Builder binds the data returned from the service call to the DataGrid component. It modifies the columns of the DataGrid. c Select the emp_no column. rename the first_name and last_name columns. 15 In the Bind to Data dialog. In the Properties view. 17 With the DataGrid still selected. b Similarly. specify False for the editable property. binding the value returned for each Employee property to a column in the DataGrid. Click Up to move it to the first position. in the Properties view. it accesses the database to create a value object. . e Similarly. rename the emp_no column to ID.

.Last updated 3/21/2010 FLEX TUTORIALS 30 Creating PHP services for client applications The application runs in a web browser.

you typically do not retrieve all the records in a database with a single call. implement a data service that includes two operations with the following signatures: • • getItems_paged($startIndex. To use paging to retrieve records. This tutorial creates an application that uses paging to populate a DataGrid.Last updated 3/21/2010 31 Chapter 5: Manage the access of data through paging For various performance and network bottleneck issues. . Paging allows you to retrieve the records incrementally in sets. and only on an as needed basis. Data grid Create the remote service and import it into a Flex project 1 In your web root create a folder named PagingCF. see “Installing the Flash Builder tutorial database” on page 14. create the following CFC. Name the CFC PagingService. $numItems) count() Paging tutorial (ColdFusion) The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this database. PagingService.cfc contains the functions required by Flash Builder to implement paging. 2 In your favorite ColdFusion editor.cfc and place it in the PagingCF folder in your web root.

The LIMIT keyword is valid for MySQL database only.adobe.empCount> </cffunction> </cfcomponent> 3 In Flash Builder. 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. Name the project PagingCF and specify ColdFusion for the server technology as listed below. You can find more information at http://www. This code is for prototyping only.Last updated 3/21/2010 FLEX TUTORIALS 32 Manage the access of data through paging <cfcomponent output="false"> <!--This sample service contains functions that illustrate typical service operations.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" /> <!--. Authenticate the user prior to allowing them to call these methods. Click Next. • Application Server Type: ColdFusion • Enable Use Remote Object Access Service • Select ColdFusion Flash Remoting . create a Flex project.

select Connect to Data Service. Click Finish. Select ColdFusion and click Next.Last updated 3/21/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.cfc file you created in step 2. 5 From the Flash Builder Data menu. . 6 Click Browse and navigate to the PagingService.

Click Next. select Configure Return Type. 8 In the Configure Return Type dialog. Auto-Detect the Return Type is selected by default.Last updated 3/21/2010 FLEX TUTORIALS 34 Manage the access of data through paging 7 In the Flash Builder Data/Services view. 9 Specify values and types for the parameters to the getItems_paged() operation as described below. from the context menu for the getItems_paged() operation. Click Next: Argument startIndex numItems Argument Type Number Number Value 0 10 .

Flex uses custom data types to access and update complex data types returned from a server. from the context menu for the getItems_paged() operation. 12 In the Data/Services view. select Enable Paging. The Configure Return Type dialog displays the properties of the data type returned by the service. Click Finish. select emp_no and click Next. . Specify the count() operation from the drop-down list. leave the Page Size field blank. 13 In the Select Unique Identifier dialog. 11 Click Finish to configure the Employee return type.Last updated 3/21/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. 14 In the Confirm Paging dialog.

2 From the Components view. then in the Properties view specify false for the Editable attribute. This dialog allows you to specify a custom page size for an operation. drag a DataGrid component onto the Design Area and place it near the top. The DataGrid component is available under Data Controls. from the Data menu select Bind to Data. Click OK. select Design to open the editor in Design mode. 4 With the DataGrid component selected. 3 Make sure the DataGrid component is selected. For the PagingService. Flash Builder configures the page size to be 20 records. 5 In the Bind to Data operation. . Create an application and bind getItems_paged() to a DataGrid 1 If the MXML editor is in Source mode. select New Service Call. select the getItems_paged() operation.Last updated 3/21/2010 FLEX TUTORIALS 36 Manage the access of data through paging Note: By default.

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. see “Installing the Flash Builder tutorial database” on page 14. For information on installing this database. .Last updated 3/21/2010 FLEX TUTORIALS 37 Manage the access of data through paging Bind To Data 6 Save and run the file.

In the PagingPHP directory. var $connection. create a directory named services. $this->port). $this->throwExceptionOnError(). } public function count() { $stmt = mysqli_prepare($this->connection. . $this->password.php and save it in the services directory. var $tablename = "employees". var $port = "3306". var $server = "localhost". $this->username. var $password = "PASSWORD". Create the remote service and import it into a Flex project 1 In your web root create a folder named PagingPHP. <?php /** * This sample service contains functions that illustrate typical service operations. public function __construct() { $this->connection = mysqli_connect( $this->server. * This code is for prototyping only. $this->databasename. $this->throwExceptionOnError($this->connection). */ class PagingService { /* connection variables */ var $username = "USERNAME".Last updated 3/21/2010 FLEX TUTORIALS 38 Manage the access of data through paging This tutorial creates an application that uses paging to populate a DataGrid. 2 In your favorite PHP editor. create the following PHP file that implements the required paging functions. Name the file PagingService. var $databasename = "fb_tutorial_db". * * Authenticate users before allowing them to call these methods. "SELECT COUNT(*) AS COUNT FROM $this->tablename").

$row->hire_date). $this->throwExceptionOnError(). return $rec_count. } public function getItems_paged($startIndex. $row->hire_date). $this->throwExceptionOnError(). $row = new stdClass().Last updated 3/21/2010 FLEX TUTORIALS 39 Manage the access of data through paging mysqli_stmt_execute($stmt). while (mysqli_stmt_fetch($stmt)) { $rows[] = $row. $startIndex. $row->first_name. mysqli_stmt_fetch($stmt). $row->first_name. $rows = array(). $this->throwExceptionOnError(). $this->throwExceptionOnError(). mysqli_stmt_execute($stmt). $numItems). $rec_count). $row->emp_no. mysqli_close($this->connection). 'ii'. $row->gender. "SELECT * FROM $this->tablename LIMIT ?. $row->last_name. mysqli_stmt_bind_result($stmt. $row->gender. mysqli_stmt_free_result($stmt). ?"). $row->last_name. $row->emp_no. mysqli_stmt_bind_result($stmt. $numItems) { $stmt = mysqli_prepare($this->connection. mysqli_stmt_bind_result($stmt. mysqli_bind_param($stmt. . mysqli_close($this->connection). $this->throwExceptionOnError(). } mysqli_stmt_free_result($stmt). $row->birth_date. $row->birth_date.

} } } ?> 3 In PagingService. } /** * Utitity function to throw an exception if an error occurs * while running a mysql command. } if(mysqli_error($link)) { $msg = mysqli_errno($link) . . username.php. throw new Exception('MySQL Error . modify the connection variables to provide your server. and password for access to the fb_tutorial_db database. $msg).Last updated 3/21/2010 FLEX TUTORIALS 40 Manage the access of data through paging return $rows. ": " .'. mysqli_error($link). */ private function throwExceptionOnError($link = null) { if($link == null) { $link = $this->connection.

5 Specify the Web Root and Root URL for your system. Click Finish. click OK to install the Zend Framework. which includes Zend AMF. Click Next. 6 From the Flash Builder Data menu.Last updated 3/21/2010 FLEX TUTORIALS 41 Manage the access of data through paging 4 In Flash Builder. 7 Click Browse and navigate to the PagingService.php file you created in step 1. create a Flex project. is not installed on your system. . Click Finish. Validate your server settings and specify the PagingPHP directory for the Output Folder. Select PHP and click Next. Name the project PagingPHP and specify PHP for the server technology. If the Zend Framework. select Connect to Data Service.

Auto-Detect the Return Type is selected by default. Click Next. . Click Next: Argument startIndex numItems Argument Type int int Value 0 20 11 Specify Employee in the Array Of field toto define a custom type for returned data. 10 Specify values and types for the parameters to the getItems_paged() operation as described below. select Configure Return Type.Last updated 3/21/2010 FLEX TUTORIALS 42 Manage the access of data through paging 8 In the Flash Builder Data/Services view. 9 In the Configure Return Type dialog. from the context menu for the getItems_paged() operation.

14 In the Select Unique Identifier dialog. select emp_no and click Next. 12 Click Finish to configure the Employee return type. then in the Properties view specify false for the Editable attribute. The DataGrid component is available under Data Controls. 2 From the Components view. 3 Make sure the DataGrid component is selected. 13 In the Data/Services view. Create an application and bind getItems_paged() to a DataGrid 1 If the MXML editor is in Source mode. Specify the count() operation from the drop-down list. select Design to open the MXML editor in Design mode. . leave the Page Size field blank. drag a DataGrid component onto the Design Area and place it near the top. select Enable Paging.Last updated 3/21/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. from the context menu for the getItems_paged() operation. from the Data menu select Bind to Data. 4 With the DataGrid component selected. The Configure Return Type dialog displays the properties of the data type returned by the service. 15 In the Confirm Paging dialog. This dialog allows you to specify a custom page size for an operation. Note: By default. Flash Builder configures the page size to be 20 records. Click Finish.

. 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. select New Service Call. For the PagingService. select the get Items Paged() operation from the drop-down list.Last updated 3/21/2010 FLEX TUTORIALS 44 Manage the access of data through paging 5 In the Bind to Data operation. .

Last updated 3/21/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 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.

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.

Last updated 3/21/2010

FLEX TUTORIALS 46
Using data management to synchronize server updates

In this tutorial, you create an application that contains an editable DataGridthat displays 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 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. <!--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>

Last updated 3/21/2010

FLEX TUTORIALS 47
Using data management to synchronize server updates

<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 VALUE="#item.first_name#">, <CFQUERYPARAM VALUE="#item.last_name#">, <CFQUERYPARAM <CFQUERYPARAM <CFQUERYPARAM </cfquery> cfsqltype="CF_SQL_VARCHAR" cfsqltype="CF_SQL_VARCHAR" cfsqltype="CF_SQL_VARCHAR" VALUE="#item.gender#">, cfsqltype="CF_SQL_DATE" VALUE="#item.birth_date#">, cfsqltype="CF_SQL_DATE" VALUE="#item.hire_date#">)

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

7 In the Flash Builder Data/Services view. 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. 13 Select Use an Existing Data Type. Click Next. 8 In the Configure Return Type dialog. select Connect to Data/Service. By introspecting the getItem() operation.Last updated 3/21/2010 FLEX TUTORIALS 48 Using data management to synchronize server updates 5 From the Flash Builder Data menu. you can define the custom data type Employee. select emp_no and click Next. expand the Data Types node for EmployeeService and select the Employee data type. Click Next: Argument itemID Argument Type Number Value 10001 For getItem(). 6 Click Browse and navigate to the EmployeeService. select Configure Return Type. 12 In the Flash Builder Data/Services view. Select ColdFusion. 2 From the context menu for the Employee data type. Click Finish. Click Next. Auto-Detect the Return Type is selected by default. select Enable Data Management. 11 Click Finish to configure the Employee return type. Provide authorization credentials as needed for your system.cfc file you created in step 2. 3 In the Select Unique Identifier dialog. select Configure Return Type. 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. from the context menu for the getAllItems() operation. . Flash Builder requires a custom data type for data returned from the data service. Flex uses custom data types to access and update complex data types returned from a server. 9 Specify a value and type for the parameter to the getItem() operation as described below. Enable Data Management Features 1 In the Data/Services view. Select Employee from the Array Of drop-down list to specify an array of Employees. you supply a valid parameter corresponding to the key field for the database. from the context menu for the getItem() operation. Click Finish.

Create the application and add a DataGrid and Buttons 1 If the MXML editor is in Source mode.Last updated 3/21/2010 FLEX TUTORIALS 49 Using data management to synchronize server updates 4 In the Map Database Operations dialog. Click Finish. 2 From the Components view. 5 Double-click each button to edit their labels. Flash Builder generates client code that can update data using a combination of the mapped operations. specify the following properties: Property ID Editable Value dg true 4 Drag four Buttons to the Design Area. 3 In the Properties view. Provide the following Labels: . specify the following operations. drag a DataGrid component onto the Design Area and place it near the top. with the DataGrid selected. • Create (Add) Operation: createItem( • Get Item Operation: getItem( • Delete Operation: deleteItem ) ) ) • Update Operation: updateItem( ( ) Data management is now enabled for this operation. select Design to open the MXML editor in Design mode. lining them up beneath the DataGrid. The DataGrid component is available under Data Controls.

dg.first_name = "New". 01).birth_date = birthDate. e. var hireDate:Date = new Date(2000. 01). 7 (Optional) With the DataGrid selected. e. in the Properties view Click Configure Columns and do the following: 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. placing the cursor in the generated event handler. Select Generate Event Handler.verticalScrollPosition = dg. In Properties view.dataProvider. which you can then code to specify the service actions to take. Flash Builder generates stubs for event handlers. type the following: var e:Employee = new Employee().Last updated 3/21/2010 FLEX TUTORIALS 50 Using data management to synchronize server updates Label Add Delete Revert Save All Changes 6 In the Data/Services view. In the Bind to Data dialog. dg. var birthDate:Date = new Date(2000. 1 Select the Add button. near the On Click field of the Add button. 01.dataProvider. 01. click the icon. e.last_name = "New".gender = "M". e.length -1.addItem(e). Click OK. 2 In the event handler body. The MXML editor changes to Source View. . e. EmployeeService and getAllItems() are selected. select the getAllItems() operation and drop it onto the DataGrid.hire_date = hireDate.

DATA_MANAGER_EMPLOYEE). add an On Click event handler for the Delete button and specify the following code: employeeService.DATA_MANAGER_EMPLOYEE). . add the following lines of code: protected function dg_creationCompleteHandler(event:FlexEvent):void { employeeService.selectedItem. You can update employees in place in the DataGrid. the changes are updated on the server. add an On Click event handler for the Revert button with the following code: employeeService. Flash Builder content assist helps you view the available methods and values. Click the Revert button to undo any changes you made before you click Save All Changes.getDataManager(employeeService. import valueObjects.getDataManager(employeeService. When you click Save All Changes. getAllItemsResult.commit(). 6 Add an On click event handler for the Save All Changes button with the following code: employeeService.EmployeeService.revertChanges().getAllItems(). add the following import statement after the existing import statements: import services.DATA_MANAGER_EMPLOYEE). 4 In Design mode.deleteItemOnRemoveFro mFill=true.token = employeeService.emp_no).autoCommit=false.employeeservice. 8 Save the application and select Run > Run DataMgtCF. employeeService.Employee. 7 For the creationCompleteHandler() for the DataGrid. 3 In the Script block. 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. 5 Similarly.getAllItems().token = employeeService.deleteItem(dg. getAllItemsResult. } This code makes sure that deleted items can be reverted by selecting the Revert button.Last updated 3/21/2010 FLEX TUTORIALS 51 Using data management to synchronize server updates As you type.getDataManager(employeeService.

php and place it in the DataMgtPHP/services folder in your web root. When you add an employee. Within that folder. For information on installing this database. All the changes in the DataGrid are local until you select a Save All Changes button. create the following PHP file. When you add and delete employees. Click the Save All Changes button to write all changes to the database. the data management features take care of adding or removing the DataGrid rows. the Employee Number defaults to zero. create a folder named services. You can modify one or more records in place in the DataGrid. which implements a service. an Employee Number is generated. This default value is because the new employee has not been updated on the server. you create an application that contains an editable DataGrid that displays employee records. At that time. 2 In your favorite PHP editor. . In this tutorial. see “Installing the Flash Builder tutorial database” on page 14. the new employee is added to the server. and also add or delete selected records from the DataGrid. Name the file EmployeeService. When you click Save All Changes. Without data management enabled. which updates the database. you code the updates to the DataGrid yourself.Last updated 3/21/2010 FLEX TUTORIALS 52 Using data management to synchronize server updates You can add and delete employees. create a folder named DataMgtPHP. Data management tutorial (PHP) The application you create in this tutorial accesses the employee database that you previously downloaded and installed. Create the remote service and import it into a Flex project 1 In your web root.

mysqli_stmt_execute($stmt). public function __construct() { $this->connection = mysqli_connect( $this->server. } mysqli_stmt_free_result($stmt). "SELECT * FROM $this->tablename"). $row->first_name. $this->databasename. $row->hire_date). $row->birth_date. $this->username. $row->first_name. $row->hire_date). $row->gender. $password = "PASSWORD". } public function getEmployeesByID($itemID) { $stmt = mysqli_prepare($this->connection. $databasename = "fb_tutorial_db". mysqli_stmt_bind_result($stmt. $row->emp_no. $server = "localhost". $rows = array(). $this->throwExceptionOnError(). "SELECT * FROM $this->tablename where emp_no=?"). while (mysqli_stmt_fetch($stmt)) { $rows[] = $row. $this->throwExceptionOnError(). $this->throwExceptionOnError(). $tablename = "employees". $row->emp_no. $this->throwExceptionOnError($this->connection). $row->birth_date.Last updated 3/21/2010 FLEX TUTORIALS 53 Using data management to synchronize server updates <?php class EmployeeService { var var var var var var $username = "USERNAME". $row->last_name. $this->password. mysqli_close($this->connection). $port = "3306". return $rows. $row->gender. } public function getAllEmployees() { $stmt = mysqli_prepare($this->connection. . $row = new stdClass(). var $connection. $this->port ). mysqli_stmt_bind_result($stmt. $row->last_name.

mysqli_stmt_bind_result($stmt. $item->first_name. first_name=?. last_name=?. ?. $item>emp_no). $item->emp_no.Last updated 3/21/2010 FLEX TUTORIALS 54 Using data management to synchronize server updates mysqli_bind_param($stmt. mysqli_bind_param($stmt. $row->last_name. } public function updateEmployees($item) { $stmt = mysqli_prepare($this->connection. mysqli_stmt_execute($stmt). mysqli_stmt_execute($stmt). $this->throwExceptionOnError(). $this->throwExceptionOnError(). gender. gender=?. mysqli_stmt_free_result($stmt). $item->birth_date. $item->last_name. $item->gender. $this->throwExceptionOnError(). last_name. return $autoid. 'isssssi'. $item->last_name. ?. $this->throwExceptionOnError(). "UPDATE $this->tablename SET emp_no=?. $this->throwExceptionOnError(). $this->throwExceptionOnError(). ?. mysqli_close($this->connection). "INSERT INTO $this->tablename (emp_no. $row->hire_date). hire_date=? WHERE emp_no=?"). $row->birth_date. mysqli_bind_param($stmt. $item->birth_date. $this->throwExceptionOnError(). mysqli_stmt_execute($stmt). hire_date) VALUES (?. 'isssss'. $item->hire_date. $itemID). ?)"). $autoid = mysqli_stmt_insert_id($stmt). } } public function createEmployees($item) { $stmt = mysqli_prepare($this->connection. $item->hire_date). first_name. 'i'. mysqli_close($this->connection). if(mysqli_stmt_fetch($stmt)) { return $row. } else { return null. ?. } . birth_date=?. $item->emp_no. birth_date. $this->throwExceptionOnError(). $item->first_name. mysqli_stmt_free_result($stmt). $row->emp_no. $item->gender. $row->gender. $row->first_name.

create a Flex project. 4 In Flash Builder. Validate your server settings. user name. } } } ?> 3 Modify the connection variables to provide your server. Click Next: Argument itemID Argument Type int Value 10001 . } if(mysqli_error($link)) { $msg = mysqli_errno($link) . Click Next. select Configure Return Type. 10 Specify a value and type for the parameter to the getEmployeesByID() operation as described below.php file you created in step 2. ": " .php. $msg). select Connect to Data Service. you can define the custom data type Employee. Specify the DataMgtPHP directory for the Output Folder. throw new Exception('MySQL Error . $itemID). 5 Specify the Web Root and Root URL for your system. "DELETE FROM $this->tablename WHERE emp_no = ?").'. mysqli_close($this->connection). 9 In the Configure Return Type dialog. Select PHP. 'i'. Click Finish. Select EmployeeService. from the context menu for the getEmployeesbyID() operation. and password for access to the fb_tutorial_db database. */ private function throwExceptionOnError($link = null) { if($link == null) { $link = $this->connection. Click Next. Click Next. mysqli_error($link). Flash Builder requires a custom data type for data returned from the data service. Name the project DataMgtPHP and specify PHP for the server technology.Last updated 3/21/2010 FLEX TUTORIALS 55 Using data management to synchronize server updates public function deleteEmployees($itemID) { $stmt = mysqli_prepare($this->connection. Auto-Detect the Return Type is selected by default. mysqli_stmt_execute($stmt). mysqli_bind_param($stmt. By introspecting the getEmployeesbyID() operation. mysqli_stmt_free_result($stmt). } /** * Utitity function to throw an exception if an error occurs * while running a mysql command. 8 In the Flash Builder Data/Services view. Click Finish. 7 Click Browse and navigate to the EmployeeService. $this->throwExceptionOnError(). $this->throwExceptionOnError(). 6 From the Flash Builder Data menu.

int and 10001 are valid type and value for itemID. Select Use An Existing Type. 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. select Configure Return Type. Enable Data Management Features 1 In the Data/Services view. Click Finish. specify the following operations. 2 From the context menu for the Employee data type. Select Employee from the Array Of drop-down list. Click Next. Specify int for the type. select Enable Data Management. Click Finish.Last updated 3/21/2010 FLEX TUTORIALS 56 Using data management to synchronize server updates For getEmployeesByID(). 13 In the Flash Builder Data/Services view. 11 Specify Employee to define a custom type for returned data. 12 Click Finish to configure Employee as the return type. 14 In the Configure Return Type dialog. Specify void. select Configure Return Type. you supply a valid parameter corresponding to the key field for the database. • Create (Add) Operation: createEmployees • Get Item Operation: getEmployeesByID() • Update Operation: updateEmployees() ) . 16 Configure the parameter type and return type for deleteEmployees() as follows: a From the context menu for the deleteEmployees() operation. select emp_no. 15 Select Use an Existing Data Type. from the context menu for the getAllEmployees() operation. Flex uses custom data types to access and update complex data types returned from a server. Click Finish. b From the context menu for the deleteEmployees() operation. expand the Data Types node for EmployeeService and select the Employee data type. select Configure Input Type. 3 In the Select Identity Properties dialog. Auto-Detect the Return Type is selected by default. Click Next. 4 In the Map Database Operations dialog. Click OK.

with the DataGrid selected. Create the application and add a DataGrid and Buttons 1 If the MXML editor is in Source mode. The DataGrid component is available under Data Controls. drag a DataGrid component onto the Design Area and place it near the top. lining them up beneath the DataGrid. Data management is now enabled for this operation. 5 Double-click each button to edit their labels. Flash Builder generates client code that can update data using a combination of the mapped operations. select Design to open the MXML editor in Design mode 2 From the Components view. 3 In the Properties view. specify the following properties: Property ID Editable Value dg true 4 Drag four Buttons to the Design Area.Last updated 3/21/2010 FLEX TUTORIALS 57 Using data management to synchronize server updates • Delete Operation: deleteEmployees () Click Finish. Provide the following Labels: .

create an event handler to specify the action to take when the Button is clicked. e.dataProvider. placing the cursor in the generated event handler.dataProvider. which you can then code to specify the service actions to take. e.birth_date = "2000-01-01". select the getAllEmployees() operation and drop it onto the DataGrid. Select Generate Event Handler.hire_date = "2000-01-01". Rename and rearrange the columns. click the icon. In the Bind to Data dialog. e. e. in the Properties view click Configure Columns. In Properties view. Flash Builder generates stubs for event handlers. Click OK. near the On Click field of the Add button.addItem(e). type the following: var e:Employee = new Employee(). EmployeeService and getAllEmployees() are selected.length -1.verticalScrollPosition = dg. e. As you type. Generate and code event handlers for the Buttons For each Button. dg.first_name = "New". .gender = "M". The MXML editor changes to Source View. 7 (Optional) With the DataGrid selected. dg. Flash Builder content assist helps you view the available methods and values.Last updated 3/21/2010 FLEX TUTORIALS 58 Using data management to synchronize server updates Label Add Delete Revert Save All Changes 6 In the Data/Services view. 2 In the event handler body. 1 Select the Add button.last_name = "New".

When you click Save All Changes.Last updated 3/21/2010 FLEX TUTORIALS 59 Using data management to synchronize server updates 3 In the Script block.getAllItems(). 7 For the creationCompleteHandler() for the DataGrid.getDataManager(employeeService. import valueObjects.DATA_MANAGER_EMPLOYEE).deleteItemOnRemoveFro mFill=true. 6 Add an On click event handler for the Save All Changes button with the following code: employeeService.DATA_MANAGER_EMPLOYEE). add the following import statements after the existing import statements: import services. 4 In Design mode. 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.getDataManager(employeeService. getAllItemsResult.employeeservice. 5 Similarly. add an On Click event handler for the Revert button with the following code: employeeService. You can update employees in place in the DataGrid. add an On Click event handler for the Delete button and specify the following code: employeeService.commit(). add the following lines of code: protected function dg_creationCompleteHandler(event:FlexEvent):void { employeeService.token = employeeService. getAllEmployeesResult. 8 Save the application and select Run > Run DataMgtPHP.revertChanges().emp_no).EmployeeService.DATA_MANAGER_EMPLOYEE).getAllEmployees(). } This code makes sure that deleted items can be reverted by selecting the Revert button. Click the Revert button to undo any changes you made before you click Save All Changes.selectedItem.autoCommit=false.token = employeeService. employeeService.getDataManager(employeeService.deleteEmployees(dg.Employee. .

an Employee Number is generated. you code the updates to the DataGrid yourself. At that time. the data management features take care of adding or removing the DataGrid rows. When you click Save All Changes.Last updated 3/21/2010 FLEX TUTORIALS 60 Using data management to synchronize server updates You can add and delete employees. When you add and delete employees. the Employee Number defaults to zero. . Click the Save All Changes button to write all changes to the database. When you add an employee. Without data management enabled. the new employee is added to the server. This default value is because the new employee has not been updated on the server.

Sign up to vote on this title
UsefulNot useful