Flex 4 Tutorials
-
Upload
balakrishna -
Category
Documents
-
view
218 -
download
0
Transcript of Flex 4 Tutorials
-
8/7/2019 Flex 4 Tutorials
1/71
ADOBE FLEX 4 Tutorials
-
8/7/2019 Flex 4 Tutorials
2/71
Last updated 6/1/2010
Copyright 2010 Adobe Systems Incorporated. All rights reserved.
Adobe Flex 4 Tutorials.Adobe, the Adobe logo, Flash, Flash Builder, Flex, Flex Builder and LiveCycle are either registered trademarks or trademarks of Adobe Systems Incorporated inthe United States and/or other countries. ActiveX and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United Statesand/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 theirrespective owners.
This Work is licensed under the Creative Commons Attribution Non-Commercial 3.0 License. To view a copy of this license, visithttp://creativecommons.org/licenses/by-nc-sa/3.0/
Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA.
http://creativecommons.org/licenses/by-nc-sa/3.0/http://creativecommons.org/licenses/by-nc-sa/3.0/ -
8/7/2019 Flex 4 Tutorials
3/71
iii
Last updated 6/1/2010
Contents
Chapter 1: Import a service and bind data to application components
Create the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Create a ColdFusion service that returns localized strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
(Optional) Test the ColdFusion service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Connect to the ColdFusion service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Examine the generated code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Chapter 2: Installing the Flash Builder tutorial database
Download and install the Flash Builder tutorial database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Chapter 3: Creating ColdFusion services for client applications
Create a CFC that accesses a database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
(Optional) Test the service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Import the service into Flex and bind returned data to application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Chapter 4: Creating PHP services for client applications
Create a PHP class that implements a service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
(Optional) Test the PHP service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Import the service into Flex and bind returned data to application components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Chapter 5: Manage the access of data through paging
Paging tutorial (ColdFusion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Paging tutorial (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Chapter 6: Using data management to synchronize server updatesData management tutorial (ColdFusion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Data management tutorial (PHP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
-
8/7/2019 Flex 4 Tutorials
4/71
1
Last updated 6/1/2010
Chapter 1: Import a service and bind datato application components
The relationship between client code and server code in Flex differs from the traditional relationship in a server
template.
In a traditional relationship, a server template mixes server code with client code. When the client queries a database,
it dynamically embeds HTML code with returned data.
Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned
data to user interface components in the client application.
This tutorial shows how to create a client application that imports a ColdFusion service. You first create a Label item
that displays static text. Next, you create a ColdFusion service that returns a localized text string. Then, you bind the
data returned from the ColdFusion service to the Label item. Finally, you examine the generated code to see how Flexaccesses the data returned from the service.
Create the application
1 In Flash Builder, select File > New > Flex Project.
2 Specify HelloCF for the project name, set Application Server Type to ColdFusion, and specify ColdFusion Flash
Remoting.
-
8/7/2019 Flex 4 Tutorials
5/71
2FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
Specify project name and server type
3 Click Next. Verify your ColdFusion server configuration and click Validate Configuration.
4 Click Finish.
The Flash builder source editor opens to Hello.mxml.
5 If Design mode is not selected, select Design to switch to Design mode of the editor.
6 In the Components View, make sure that the Controls folder is open. Scroll the controls to find the Label control.
-
8/7/2019 Flex 4 Tutorials
6/71
3FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
Label control in the Controls folder
7 Drag a Label component from the Components View to the design area.
8 Double-click the Label component. Replace the default text with Hello.
9 In the Properties view, modify the appearance of the text. With the Label component selected, specify the following:
Select the font attributes
Font Size 24
Font Attribute Bold
Font Attribute Italic
-
8/7/2019 Flex 4 Tutorials
7/71
4FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
10 Click the Font color box and specify#ff0000 to change the text to Red.
Font color box
11 Save the file. Click the Run button to run the application.
Run button
-
8/7/2019 Flex 4 Tutorials
8/71
5FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
The application runs in a web browser.
Create a ColdFusion service that returns localizedstrings
Create a ColdFusion component (CFC) that can be accessed as a service by Flex over the Internet.
1 Create the following directory in your web root:
/HelloCF/
2 Code the following HelloService.cfc and place it in the HelloCF directory:
-
8/7/2019 Flex 4 Tutorials
9/71
6FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
The function getMessage() is a service operation that client applications access.
Make sure to specify remote as the access type for the function.
(Optional) Test the ColdFusion service
There are various ways to test the service before you access it from an application.
1 Create a ColdFusion script file, helloservicetest.cfm , that calls the service and displays the returned data in
HTML.
Use the cfinvoke tag to call the service.
Use the cfdump tag to view the results.
Testing getLocales()...
Result:
Testing getLocalizedMessage("es")...
Result:
2 Save helloservicetest.cfm in the same folder as HelloService.cfc , and call the script from a web browser:
-
8/7/2019 Flex 4 Tutorials
10/71
7FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
http://localhost:8500/HelloCF/helloservicetest.cfm
Using cfinvoke and cfdump
If there is an error in the service, ColdFusion displays detailed information about the error.
You can also enable Robust Exception Information for the ColdFusion server to get detailed debugging output.
3 Add trace statements to the service.
In the ColdFusion Administrator, enable debugging and logging.
-
8/7/2019 Flex 4 Tutorials
11/71
8FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
Add ColdFusion trace statements as necessary to debug your service. For example, add the following line in
helloservicetest.cfm :
Testing getLocalizedMessage()...
Result:
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
4Call a function in the service directly from a URL.For example, call getLocalizedMessage() with the parameter es:
http://localhost:8500/HelloCF/HelloService.cfc?method=getLocalizedMessage&locale=es
Note: You can also test a service after importing the service into Flash Builder. Use Test Operation, which is available
from the Data/Service view.
-
8/7/2019 Flex 4 Tutorials
12/71
9FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
Connect to the ColdFusion service
In Flash Builder, connect to the ColdFusion service and bind the data returned from the service to the Label
component.
1 In Design mode of the MXML editor, make sure HelloCF.mxml is open. From the Flash Builder Data menu, select
Connect To Data/Service.
2 Select ColdFusion as the service type. Click Next.
Select service type
3 Click Browse and navigate to the HelloService.cfc you previously created. Flash Builder names the service
HelloService.
Importing a ColdFusion Service
4 Click Finish. Provide your credentials to log in to the ColdFusion database.The Data Services View now displays your ColdFusion service.
Data Services View
-
8/7/2019 Flex 4 Tutorials
13/71
10FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
The Data Service View provides a picture of remote services. This view becomes useful when you configure types
for data returned by a service call.
5 Select the Label component in the design area. From the context menu for the Label component, select Bind to Data.
Select OK to replace the current text with the text returned from a service operation.
Flash Builder provides various ways to bind data to a selected component. In addition to the the context menu,
you can bind to data from Properties view. You can also select Bind to Data from the Flash Builder Data menu.
6 In the Bind to Data dialog, make sure that New Service Call is selected. For Operation select
getLocalizedMessage . Click OK.
Select the operation for binding data
Flash Builder switches the editor to Source mode, highlighting the parameter to getLocalizedMessage() .
7 Type "es" for the parameter value for getLocalizedMessage(). Switch to Design mode of the editor.
Design mode showing data binding
8 Save and run the application.
-
8/7/2019 Flex 4 Tutorials
14/71
11FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
The Label component displays the message retrieved from the HelloService.
Examine the generated code
When you imported the ColdFusion service into a client application, Flex generated client code that accessed the
ColdFusion service. Flex also generates code when you bind operations to application components.
There are three parts to the generated code:
Event handler
Service call and responder
Data binding
This part of the tutorial walks you through the Flex code generated in the previous tutorial. There are no steps to this
part of the tutorial. Just a description of the code generation.
Event handlers
Flex uses event handlers to trigger a service call.
Flex code is not processed top to bottom, as in server templates. Instead, applications built with Flex listen for events
to trigger responses.
By default, Flex uses the creationComplete event on a component to trigger a service call.
Examine the Label component in the HelloCF.mxml source code:
The creationComplete event fires after the application creates the component. For this Label component,
creationComplete calls an event handler that Flash Builder generated for the event. Examine the code for the event
handler, which is placed inside a Script block:
-
8/7/2019 Flex 4 Tutorials
15/71
12FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
import mx.events.FlexEvent;
import mx.controls.Alert;
protected function label_creationCompleteHandler(event:FlexEvent):void
{
getLocalizedMessageResult.token = helloService.getLocalizedMessage("es");
}
]]>
The creationComplete event handler calls the getLocalizedMessage() operation from the ColdFusion service. It
passes the parameter es, which you specified earlier in the source code.
You can use other events, such as a Click event on a button or a selectionChange event of a list, to trigger service
calls.
Service calls and responders
When you add a service, Flex creates a component containing methods that call the service operations. When you call
one of the methods, the component calls the corresponding service operation over the network using the appropriate
protocol.
Service calls are associated with CallResponders. Data returned from a service call is placed in the lastResult
attribute of the CallResponder. CallResponders allow service calls to operate asynchronously. The client application
can continue to be responsive while the service call is being processed.
Examine the generated service call and responder:
When you imported the HelloService service, Flex created the HelloService class. This class contains methods to call
the getLocales(), and getLocalizedMessage operations of the service.
The CallResponder, identified by the getLocalizedMessageResult id, provides access to the returned data.
Data binding
Flex data binding allows you to assign the value of the lastResult attribute of a CallResponder to a user interface
component. When the last result updates, Flex automatically updates the component.
Flex uses curly braces {} to bind data to an attribute of a component. In this example, Flex binds the lastResult value
to the text attribute of the Label component.
Examine the data binding for the Label component:
-
8/7/2019 Flex 4 Tutorials
16/71
13FLEX TUTORIALS
Import a service and bind data to application components
Last updated 6/1/2010
The data returned to the CallResponder, getLocalizedMessageResult.lastResult , is automatically assigned as
the text attribute for the Label component.
Code generation summaryIn summary, Flash Builder generates code to access the imported service in the client application:
After Flex creates the Label component in the running application, the creationComplete event fires, calling a
service operation.
The data returned from the service call is placed in the lastResult attribute of the associated CallResponder.
Thetext attribute of the Label component, which is bound to the lastResult attribute, updates with the returned data.
-
8/7/2019 Flex 4 Tutorials
17/71
14
Last updated 6/1/2010
Chapter 2: Installing the Flash Buildertutorial database
Several of the tutorials show how to access data returned from a database. The tutorials use a MySQL database, which
you can access from either a PHP or ColdFusion installation.
Download and install the Flash Builder tutorial database
1 Download Flash Builder Tutorial Databaseand unzip it into a temporary directory on your computer.
The downloaded ZIP file contains two SQL files:
fb_tutorial_db_full.sqlUse this file to import the entire database into your MySQL installation. It creates the fb_tutorial_db
database, which contains three tables. The tables in the database are departments, employees, and dept_emp.
fb_tutorial_db_tables.sql
Use this file to import just the three tables into an existing database. This file is provided in case you do not have
privileges to create a database in your MySQL installation. See the ReadMe file for information on importing
this file.
You can install the database either from the command line or using the phpMyAdmin utility for MySQL databases.
2 (Command Line) Execute the following command from a terminal window for your operating system.
/bin/mysql -u root -p < fb_tutorial_db_full.sql
3 (phpMyAdmin) From the phpMyAdmin home page, navigate to the Import page. Browse to the downloaded SQL
file and import the database.
4 (ColdFusion) In the ColdFusion Administrator, add fb_tutorial_db as a data source.
The following table lists the settings for the data source using the default configuration for ColdFusion 8:
Configuration Field Value
ColdFusion Data Source
Name
fb_tutorial_db
Database fb_tutorial_db
Server 127.0.0.1
Port 3306
http://www.adobe.com/go/learn_flex4_fb_tutorial_db/http://www.adobe.com/go/learn_flex4_fb_tutorial_db/http://www.adobe.com/go/learn_flex4_fb_tutorial_db/ -
8/7/2019 Flex 4 Tutorials
18/71
15
Last updated 6/1/2010
Chapter 3: Creating ColdFusion servicesfor client applications
When you access a remote service, you typically retrieve records from a database and display them in the client
application. This tutorial shows how to access a remote database and display retrieved records in a DataGrid.
The tutorial illustrates the following concepts:
Using a ColdFusion component (CFC) to implement service operations that query a database.
Binding a CFC service operation to a Flex data control, such as a DataGrid.
Sampling the data returned from a service operation to configure a data type for the returned data.
Running the application and viewing the returned data in the DataGrid.
Create a CFC that accesses a database
This tutorial accesses the cfbookclub database that is provided with a ColdFusion installation. It lists the contents of
the Books table in the database. However, you can modify this tutorial to select records from any database you have
access to.
This tutorial assumes that you have a local installation of ColdFusion 8 or ColdFusion 9 and the ColdFusion server is
running.
1 In your web root, create a folder named books.
2 In your favorite ColdFusion editor, create the following CFC. Name it BookService.cfc and place it in the books
folder in your web root.
BookService.cfc selects all the records from the Books table in the cfbookclub database.
-
8/7/2019 Flex 4 Tutorials
19/71
16FLEX TUTORIALS
Creating ColdFusion services for client applications
Last updated 6/1/2010
SELECT * FROM Books
3 In BookService.cfc , examine the code that calls the database:
Flex expects data returned by the operation to be an object or an array of objects. Each object in the array
corresponds to a retrieved record from the database, containing values for each column in the record.
The cfquery, qAllBooks, accesses the Books table in the cfbookclub database. ColdFusion returns an array of
records from the database.
(Optional) Test the service
It is always a good idea to test a service before you access it from an application.
1 Create bookservicetest.cfm to test the CFC. This script uses cfdump to view the results of the service operation.
Testing getBooks()...
2 Save bookservicetest.cfm in the books folder next to BookService.cfc .
3 From a web browser, run the script to test the service:
-
8/7/2019 Flex 4 Tutorials
20/71
17FLEX TUTORIALS
Creating ColdFusion services for client applications
Last updated 6/1/2010
http://localhost:8500/books/bookservicetest.cfm
You can also test a service after importing the service into Flash Builder. Use Test Operation, which is available from
the Data/Service view.
Import the service into Flex and bind returned data toapplication 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.
-
8/7/2019 Flex 4 Tutorials
21/71
18FLEX TUTORIALS
Creating ColdFusion services for client applications
Last updated 6/1/2010
Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned
data to user interface components in the client application.
1 In Flash Builder, select New > Flex Project to create a ColdFusion server project. Name the project Books.
Set the Application Server Type to ColdFusion. Enable Use Remote Object Access Service and select ColdFusionFlash Remoting.
2 Click Next. Validate your configuration.
3 Set the output folder to the books folder containing the service. Click Finish.
Flash builder creates Books.mxml and opens the file in the MXML editor.
Select Design to open the editor in Design mode.
4 In Design mode, drag a DataGrid control to the design area.
The DataGrid control is available under Controls in the Components view.
5 From the context menu for the DataGrid, select Bind to Data.
6 In the No Services Defined dialog, click Yes to connect to a service.
7 In the Connect to Data/Service wizard, select ColdFusion. Click Next.
-
8/7/2019 Flex 4 Tutorials
22/71
19FLEX TUTORIALS
Creating ColdFusion services for client applications
Last updated 6/1/2010
Flash Builder provides multiple ways to connect to a data service. In this scenario, you first create the user
interface. Then from a user interface component, you connect to a service and specify the remote operation.
8 Click Browse and navigate to the BookService.cfc you created previously. Click Finish.
Provide authorization credentials as needed for your system.
The Data Services View now displays the BookService.
9 Again, from the context menu for the DataGrid, select Bind to Data.
The Bind to Data dialog now opens with New Service Call selected.
BookService is the only service available in the Flex project.
getBooks() is the only operation available in the service.
10 In the Bind to Data dialog, select Configure Return Type to define the data type for returned data.
Flex uses the return data type to access service operations. The BookService service does not define the data type
for returned data. Flash Builder uses client-side typing to define a custom data type for the returned data.
Some services, such as those provided by LiveCycle Data Services, provide server-side typing. With server-side
typing, Flash Builder does not have to configure the data type for returned data.
11 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
Flash Builder introspects the service to determine the data and data types returned.
12 SpecifyBookin the Array Of field to define a custom type for returned data.
The BookService returns an array of records from the data service. Each record is a complex data type representing
a database record for a book. The custom type Book provides access to each field of the record.
The Configure Return Type dialog displays the properties of the data type returned by the service. Click Finish.
When Flash Builder configures a return type, it accesses the database to create a value object. The properties of
the custom data type are derived from the value object. You can view the properties of the data type before
proceeding.
13 In the Bind to Data dialog, click OK.
-
8/7/2019 Flex 4 Tutorials
23/71
20FLEX TUTORIALS
Creating ColdFusion services for client applications
Last updated 6/1/2010
Flash Builder binds the data returned from the service call to the DataGrid component. It modifies the columns of
the DataGrid, binding the value returned for each Book property to a column in the DataGrid.
14 Make sure the DataGrid is still selected. In the Properties view, click Configure Columns and then do the following
steps:
a Select the ISSPOTLIGHT column. Click Delete to delete the column.
b Delete all columns except TITLE and GENRE.
c Select the TITLE column. Edit the Header Text field to rename the column Title.
d Rename the GENRE column to Genre.
e With the GENRE column selected, click Up to rearrange the order of the columns.
-
8/7/2019 Flex 4 Tutorials
24/71
21FLEX TUTORIALS
Creating ColdFusion services for client applications
Last updated 6/1/2010
f Click OK.
15 In Design View, grab the far left handle of the DataGrid and resize it to a more normal shape. Save and run the
application.
-
8/7/2019 Flex 4 Tutorials
25/71
22
Last updated 6/1/2010
Chapter 4: Creating PHP services for clientapplications
You can create applications with Flex that access services from a wide variety of technologies. These technologies
include:
ColdFusion
PHP
HTML (REST-style) services
Web services (SOAP)
After creating a service, it is a good idea to test the service before accessing it from a client application.
The principles of creating and testing PHP services can be applied to other service technologies.
Create a PHP class that implements a service
The service you create in this tutorial accesses the fb_tutorial_db database. For information on installing this database,
see Installing the Flash Builder tutorial database on page 14.
1 In your web root, create a folder named PHPService. Within that folder, create another folder named services.
2 In your favorite PHP editor, create the following PHP file, which implements EmployeeService. Name the file
EmployeeService.php . Place it in the PHPService/services folder.
-
8/7/2019 Flex 4 Tutorials
26/71
23FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
-
8/7/2019 Flex 4 Tutorials
27/71
24FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
mysqli_close($this->connection);
return $rows;
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>
This PHP class contains functions that implement data service operations. Flash Builder introspects the service
operations in the PHP class to create ActionScript classes in the client application. The client application accesses
the data service using these ActionScript classes.
3 Save EmployeeService.php at the following location:
/PHPService/services/EmployeeService.php
Note:Make sure that the filename corresponds to the name of the class implementing the PHP service.
4 In EmployeeService.php , examine the code that calls the database.
Connecting to data:
The code uses global variables and a constructor function that connects to the database server.
Substitute your connection settings for the global variables.
Call the database:
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
mysqli_stmt_execute($stmt);
This code implements a basic PHP call to a database to return a result set. This call uses prepared statements
available with the MySQLi extension. Prepares statements provide more security than a basic database query.
Return the data as an array of rows:
$rows = array();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);
}
return $rows;
-
8/7/2019 Flex 4 Tutorials
28/71
25FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
Flex expects data returned by the operation to be an object or an array of objects. The PHP code that handles
the returned result set iterates through the result, returning an array of objects. Each object in the array
corresponds to a retrieved record from the database, containing values for each column in the record.
The code uses bound results for the prepared statement. This call allows the values of the result to correctly be
bound to expected values of the data.
Exception handling
The code creates a utility function to catch exceptions.
(Optional) Test the PHP service
It is always a good idea to test a service before you access it from an application.
1 Create a PHP script file, tester.php, that calls the service and displays the returned data.
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:
-
8/7/2019 Flex 4 Tutorials
29/71
26FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
array(999) {
[0]=>
object(stdClass)#4 (6) {
["emp_no"]=>
string(5) "10002"
["birth_date"]=>
string(10) "1964-06-02"
["first_name"]=>
string(7) "Bezalel"
["last_name"]=>
string(6) "Simmel"
["gender"]=>
string(1) "F"
["hire_date"]=>
string(10) "1985-11-21"
}
[1]=>
object(stdClass)#5 (6) {
["emp_no"]=>
string(5) "10003"
["birth_date"]=>
string(10) "1959-12-03"
["first_name"]=>
string(5) "Parto"
["last_name"]=>
string(7) "Bamford"
["gender"]=>
string(1) "M"
["hire_date"]=>
string(10) "1986-08-28"
}
[2]=>
object(stdClass)#6 (6) {["emp_no"]=>
. . .
If there is an error in the service, PHP displays information to help locate the error.
Warning: mysqli_connect() [function.mysqli-connect]: (28000/1045):
Access denied for user 'admin'@'localhost' (using password: YES) in
C:\wamp2\www\PHP_Service\services\PHPservice.php on line 6
Access denied for user 'admin'@'localhost' (using password: YES)
You can also test a service after importing the service into Flash Builder. Use Test Operation, which is available from
the Data/Service view.
Import the service into Flex and bind returned data toapplication components
The relationship between client code and server code in Flex differs from the traditional relationship in a server
template.
-
8/7/2019 Flex 4 Tutorials
30/71
27FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
In a traditional relationship, a server template mixes server code with client code. When the client queries a database,
it dynamically embeds HTML code with returned data.
Flex, however, separates client code from server code. The remote service returns only data. Flex binds the returned
data to user interface components in the client application.
1 In Flash Builder, select File > New > Flex Project.
2 Specify PHP_Service for the project name and set the Application Server Type to PHP.
Specify project name and server type
Note: If you forget to set the application server type when you create the project, you can later specify the server type
from the Project Properties page.
3 Click Next. Verify your PHP configuration and click Validate Configuration.
4 For Output Folder, specify the PHPService folder you created previously.
Flash Builder suggests a default location for the output folder. Use the location that already contains
EmployeeService.php . Here is the location previously specified:
/PHPService/
5 Click Finish.
-
8/7/2019 Flex 4 Tutorials
31/71
28FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
The Flash Builder source editor opens to PHP_Service.mxml .
6 Select Design to open the editor in Design mode. Add a DataGrid control to the application:
The DataGrid component is available under Data Controls in the Components view. Drag the DataGrid control to
the design area.
7 From the context menu for the DataGrid, select Bind to Data.
8 In the No Services Defined dialog, click Yes to connect to a service.
9 In the New Flex Service wizard, select PHP. Click Next.
Flash Builder provides multiple ways to connect to a data service. In this scenario, you first create the user
interface. Then from a user interface component, you can connect to a service and specify the remote operation.
10 Click Browse and navigate to the EmployeeService.php file you created previously.
The path to the file is:
/PHP_Service/services/EmployeeService.php
Click Finish. Flash Builder prompts you to install or update the Zend Framework, if necessary.
The Data Services View now displays the EmployeeService.
11 From the DataGrid context menu, again select Bind to Data.
The Bind to Data dialog opens with New Service Call selected.
EmployeeService is the only service available in the Flex project.
getEmployeess() is the only operation available in the service.
12 In the Bind to Data dialog, select Configure Return Type to define the data type for returned data.
Flex uses the return data type to access service operations. The EmployeeService service does not define the data
type for returned data. Flash Builder uses client-side typing to define a custom data type for the returned data.
13 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
14 SpecifyEmployee for the name of the type.
The EmployeeService returns a complex data type representing a database record for an employee. The custom type
Employee provides access to each field of the record.
-
8/7/2019 Flex 4 Tutorials
32/71
29FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
View the properties of the Employee data type returned by the service. Click Finish.
When Flash Builder configures a return type, it accesses the database to create a value object. The properties of
the custom data type are derived from the value object. You can view and modify the properties of the data type
before proceeding.
15 In the Bind to Data dialog, click OK.
Flash Builder binds the data returned from the service call to the DataGrid component. It modifies the columns of
the DataGrid, binding the value returned for each Employee property to a column in the DataGrid.
16 Make sure the DataGrid is still selected. In the Properties view, click Configure Columns and then do the following
steps:
a Select the hire_date column. Click Delete to delete the column.
b Similarly, delete all columns except emp_no, first_name, and last_name.
c Select the emp_no column. Click Up to move it to the first position.
d In the Header Text field, rename the emp_no column to ID.
e Similarly, rename the first_name and last_name columns.
f Click OK.
17 With the DataGrid still selected, in the Properties view, specify False for the editable property.
18 Select File > Save to save the application file. Then select Run > Run PHP_Service to run the application.
-
8/7/2019 Flex 4 Tutorials
33/71
30FLEX TUTORIALS
Creating PHP services for client applications
Last updated 6/1/2010
The application runs in a web browser.
-
8/7/2019 Flex 4 Tutorials
34/71
31
Last updated 6/1/2010
Chapter 5: Manage the access of datathrough paging
For various performance and network bottleneck issues, you typically do not retrieve all the records in a database with
a single call. Paging allows you to retrieve the records incrementally in sets, and only on an as needed basis.
To use paging to retrieve records, implement a data service that includes two operations with the following signatures:
getItems_paged($startIndex, $numItems)
count()
Paging tutorial (ColdFusion)
The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this
database, see Installing the Flash Builder tutorial database on page 14.
This tutorial creates an application that uses paging to populate a DataGrid.
Data grid
Create the remote service and import it into a Flex project
1 In your web root create a folder named PagingCF.
2 In your favorite ColdFusion editor, create the following CFC. Name the CFC PagingService.cfc and place it in
the PagingCF folder in your web root.PagingService.cfc contains the functions required by Flash Builder to implement paging.
-
8/7/2019 Flex 4 Tutorials
35/71
32FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
SELECT * FROM employees LIMIT #startIndex#, #numItems#
SELECT COUNT(emp_no) AS empCount FROM employees
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
-
8/7/2019 Flex 4 Tutorials
36/71
33FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
New project for ColdFusion
4 Validate your ColdFusion settings and specify the PagingCF directory for the Output Folder. Click Finish.
5 From the Flash Builder Data menu, select Connect to Data Service. Select ColdFusion and click Next.
6 Click Browse and navigate to the PagingService.cfc file you created in step 2. Click Finish.
-
8/7/2019 Flex 4 Tutorials
37/71
34FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
7 In the Flash Builder Data/Services view, from the context menu for the getItems_paged() operation, select
Configure Return Type.
8 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
9 Specify values and types for the parameters to the getItems_paged() operation as described below. Click Next:
Argument Argument Type Value
startIndex Number 0
numItems Number 10
-
8/7/2019 Flex 4 Tutorials
38/71
35FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
New project configuration
10 SpecifyEmployee in the Array Of field toto define a custom type for returned data.
Flex uses custom data types to access and update complex data types returned from a server.
The Configure Return Type dialog displays the properties of the data type returned by the service.
11 Click Finish to configure the Employee return type.
12 In the Data/Services view, from the context menu for the getItems_paged() operation, select Enable Paging.
13 In the Select Unique Identifier dialog, select emp_no and click Next.
14 In the Confirm Paging dialog, leave the Page Size field blank. Specify the count() operation from the drop-down
list. Click Finish.
-
8/7/2019 Flex 4 Tutorials
39/71
-
8/7/2019 Flex 4 Tutorials
40/71
37FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
Bind To Data
6 Save and run the file.
In the application, click in the DataGrid scroll bar or move the thumb of the scroll bar to observe the paging of data.
Paging tutorial (PHP)
The application you create in this tutorial accesses the employee database that you previously downloaded and
installed. For information on installing this database, see Installing the Flash Builder tutorial database on page 14.
-
8/7/2019 Flex 4 Tutorials
41/71
38FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
This tutorial creates an application that uses paging to populate a DataGrid.
Create the remote service and import it into a Flex project
1 In your web root create a folder named PagingPHP. In the PagingPHP directory, create a directory named
services.
2 In your favorite PHP editor, create the following PHP file that implements the required paging functions. Name
the file PagingService.php and save it in the services directory.
-
8/7/2019 Flex 4 Tutorials
42/71
39FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $rec_count);
$this->throwExceptionOnError();
mysqli_stmt_fetch($stmt);
$this->throwExceptionOnError();
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rec_count;
}
public function getItems_paged($startIndex, $numItems) {
$stmt = mysqli_prepare($this->connection,
"SELECT * FROM $this->tablename LIMIT ?, ?");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'ii', $startIndex, $numItems);
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name,
$row->gender, $row->hire_date);
while (mysqli_stmt_fetch($stmt)) {$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name,
$row->gender, $row->hire_date);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
-
8/7/2019 Flex 4 Tutorials
43/71
40FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
return $rows;
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>
3 In PagingService.php , modify the connection variables to provide your server, username, and password for
access to the fb_tutorial_db database.
-
8/7/2019 Flex 4 Tutorials
44/71
41FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
4 In Flash Builder, create a Flex project. Name the project PagingPHP and specify PHP for the server technology.
Click Next.
5 Specify the Web Root and Root URL for your system. Validate your server settings and specify the PagingPHP
directory for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data Service. Select PHP and click Next.
7 Click Browse and navigate to the PagingService.php file you created in step 1. Click Finish.
If the Zend Framework, which includes Zend AMF, is not installed on your system, click OK to install the Zend
Framework.
-
8/7/2019 Flex 4 Tutorials
45/71
42FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
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 SpecifyEmployee in the Array Of field to define a custom type for returned data.
Argument Argument Type Value
startIndex int 0
numItems int 20
-
8/7/2019 Flex 4 Tutorials
46/71
43FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
Flex uses custom data types to access and update complex data types returned from a server.
The Configure Return Type dialog displays the properties of the data type returned by the service.
12 Click Finish to configure the Employee return type.
13 In the Data/Services view, from the context menu for the getItems_paged() operation, select Enable Paging.
14 In the Select Unique Identifier dialog, select emp_no and click Next.
15 In the Confirm Paging dialog, leave the Page Size field blank. Specify the count() operation from the drop-down
list. Click Finish.
Note: By default, Flash Builder configures the page size to be 20 records. This dialog allows you to specify a custom
page size for an operation.
Create an application and bind getItems_paged() to a DataGrid
1 If the MXML editor is in Source mode, select Design to open the MXML editor in Design mode.
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 Make sure the DataGrid component is selected, then in the Properties view specifyfalse for the Editable attribute.
4 With the DataGrid component selected, from the Data menu select Bind to Data.
-
8/7/2019 Flex 4 Tutorials
47/71
44FLEX TUTORIALS
Manage the access of data through paging
Last updated 6/1/2010
5 In the Bind to Data operation, select New Service Call. For the PagingService, select the get Items Paged()
operation from the drop-down list,. Click OK.
6 Save and run the file.
In the application, click in the DataGrid scroll bar or move the thumb of the scroll bar to observe the paging of data.
-
8/7/2019 Flex 4 Tutorials
48/71
45
Last updated 6/1/2010
Chapter 6: Using data management tosynchronize server updates
Data management features allow you to synchronize adding, updating, and deleting of records in a database. Changes
you make in the client application are not written to the server until a commit method is called. You can call a revert
method to roll back changes made in the client application.
Additionally, data management helps synchronize your client application with the data on the service. Data
management features can automatically update user interface controls that display data retrieved from a service.
This tutorial shows how to use Flash Builder to implement data management. The tutorial illustrates how to
synchronize data on the server and with client application controls.
Data management service operations
Data management requires a data service that implements one or more operations with the following signatures:
createItem(item:CustomDatatype):int
deleteItem(itemID:Number):void
updateItem((item: CustomDatatype):void
getItem(itemID:Number): CustomDatatype
CustomDatatype is a data type representing complex data returned from the server. In server-side typing, the service
defines the custom data type. In client-side typing, use Flash Builder to introspect the service and configure the custom
data type.
Note: The required data management operation signatures listed in this tutorial are a subset of the signatures that can
be used. For a complete list of the operation signatures you can use, see Enabling data management.
Client-side and server-side typing
This tutorial illustrates both client-side typing and server-side typing. For this tutorial, the client application accesses
an Employee object from the data service. The Employee object contains fields, such as name and hire date, that define
an employee. With client-side typing, you use Flash Builder wizards to introspect the data on the server and define the
Employee data type in client code. With server-side typing, server code defines the Employee data type.
Both PHP and ColdFusion let you define custom data types in server code. Flash Builder recognizes the custom data
type during introspection of services. You do not have to walk through the wizard screens to configure the Employee
data type.
Whether you use server-side or client-side typing is a developer preference. Server-side typing can help enforce data
integrity on the server and simplify the Flash Builder workflow. Client-side typing simplifies the service coding while
using Flash Builder to define the custom data types.
Note: Flash Builder can generate sample server code from a database. The sample code generated by Flash Builder
illustrates client-side typing. See Generating a sample ColdFusion service from a database table and Generating a sample
PHP service from a database table.
-
8/7/2019 Flex 4 Tutorials
49/71
46FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
Data management tutorial (ColdFusion)
The application you create in this tutorial accesses the fb_tutorial_db database. For information on installing this
database, see Installing the Flash Builder tutorial database on page 14.
In this tutorial, you create an application that contains an editable DataGrid that displays employee records. You can
modify one or more records in place in the DataGrid. You can also add or delete selected records. All changes in the
DataGrid are local until you select a Save All Changes button that updates the database.
You can implement the service in this tutorial using client-side or server-side typing. The service is defined in
EmployeeService.cfc . If you use server-side typing, you define the Employee data type in a separate
Employee.cfc.
The server code in EmployeeService.cfc is basically the same in both versions. However, in the version that
implements server-side typing, the functions access the Employee data type defined in Employee.cfc.
Create the remote service and import it into a Flex project (client-side typing) on page 46
Create the remote service and import it into a Flex project (server-side typing) on page 49
Create the remote service and import it into a Flex project (client-side typing)
1 In your web root create a folder named DataMgtCF.
2 In your favorite ColdFusion editor, create the following CFC. Name the CFC EmployeeService.cfc and place it
in the DataMgtCF folder in your web root.
EmployeeService.cfc contains the functions required by Flash Builder to implement data management.
-
8/7/2019 Flex 4 Tutorials
50/71
47FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
SELECT * FROM employees
SELECT * FROM employees
WHERE emp_no =
INSERT INTO employees (first_name, last_name, gender, birth_date,hire_date)
VALUES (,
,
,
,
)
UPDATE employees SET birth_date = ,
-
8/7/2019 Flex 4 Tutorials
51/71
48FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
hire_date = ,
gender = ,
first_name = ,
last_name =
WHERE emp_no =
DELETE FROM employees
WHERE emp_no =
3 In Flash Builder, create a Flex project. Name the project DataMgtCF. Specify ColdFusion for the server technology
as listed below. Click Next.
Application Server Type: ColdFusion
Enable Use Remote Object Access Service
Select ColdFusion Flash Remoting
4 Validate your ColdFusion settings and specify the DataMgtCF folder for the Output Folder. Click Finish.
5 From the Flash Builder Data menu, select Connect to Data/Service. Select ColdFusion. Click Next.
6 Click Browse and navigate to the EmployeeService.cfc file you created in step 2. Click Finish.
Provide authorization credentials as needed for your system.
7 In the Flash Builder Data/Services view, from the context menu for the getItem() operation, select Configure
Return Type.
Flash Builder requires a custom data type for data returned from the data service. By introspecting thegetItem()
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:
For getItem(), you supply a valid parameter corresponding to the key field for the database. Number and 10001
are valid type and value for itemID
10 SpecifyEmployee in the Array Of field to define a custom type for returned data.
Flex uses custom data types to access and update complex data types returned from a server. getItem() returns
the fields of a record from the Employees table in the database
The Configure Return Type dialog displays the properties of the data type returned by the service.
Argument Argument Type Value
itemID Number 10001
-
8/7/2019 Flex 4 Tutorials
52/71
49FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
11 Click Finish to configure the Employee return type.
12 In the Flash Builder Data/Services view, from the context menu for the getAllItems() operation, select Configure
Return Type.
13 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.14 Select Use an Existing Data Type. Select Employee from the Array Of drop-down list to specify an array of
Employees. Click Finish.
Next:Enable Data Management Features on page 51
Create the remote service and import it into a Flex project (server-side typing)
1 In your web root create a folder named DataMgtCF.
2 In your favorite ColdFusion editor, create the following CFC. Name the CFC Employee.cfc and place it in the
DataMgtCF folder.
Employee.cfc defines the Employee data type that is returned by the service.
3 Now create EmployeeService.cfc and place it in the DataMgtCF folder alongside Employee.cfc.
EmployeeService.cfc contains the functions required by Flash Builder to implement data management.
SELECT * FROM employees
-
8/7/2019 Flex 4 Tutorials
53/71
50FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
SELECT * FROM employees
WHERE emp_no =
INSERT INTO employees (first_name, last_name, gender, birth_date,
hire_date)
VALUES (,
,
,
,
)
UPDATE employees SET birth_date = ,
hire_date = ,
gender = ,
first_name = ,
last_name =
WHERE emp_no =
DELETE FROM employees
WHERE emp_no =
-
8/7/2019 Flex 4 Tutorials
54/71
51FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
4 In Flash Builder, create a Flex project. Name the project DataMgtCF. Specify ColdFusion for the server technology
as listed below. Click Next.
Application Server Type: ColdFusion
Enable Use Remote Object Access Service Select ColdFusion Flash Remoting
5 Validate your ColdFusion settings and specify the DataMgtCF folder for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data/Service. Select ColdFusion. Click Next.
7 Click Browse and navigate to the EmployeeService.cfc file you created in step 2. Click Finish.
Provide authorization credentials as needed for your system.
Next:Enable Data Management Features on page 51
Enable Data Management Features
1 In the Data/Services view, expand the Data Types node for EmployeeService and select the Employee data type.2 From the context menu for the Employee data type, select Enable Data Management.
3 In the Select Unique Identifier dialog, select emp_id and click Next.
4 In the Map Database Operations dialog, specify the following operations. Click Finish.
Create (Add) Operation: createEmployee( )
Get Item Operation: getEmployee( )
Update Operation: updateEmployee( )
-
8/7/2019 Flex 4 Tutorials
55/71
52FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
Delete Operation: deleteEmployee ( )
Data management is now enabled for this operation. Flash Builder generates client code that can update data using
a combination of the mapped operations.
Next:Create the application and add a DataGrid and Buttons on page 52
Create the application and add a DataGrid and Buttons1 If the MXML editor is in Source mode, select Design to open the MXML editor in Design mode.
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 In the Properties view, with the DataGrid selected, specify the following properties:
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:
Property Value
ID dg
Editable true
Label
Add
-
8/7/2019 Flex 4 Tutorials
56/71
53FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
6 In the Data/Services view, select the getAllEmployees() operation and drop it onto the DataGrid.
In the Bind to Data dialog, EmployeeService and getAllEmployees() are selected. Click OK.
7 (Optional) With the DataGrid selected, in the Properties view Click Configure Columns and do the following:
Rename and rearrange the columns.
Next:Generate event handlers for the Buttons on page 53
Generate event handlers for the Buttons
Each Button requires an event handler to specify the action to take when the Button is clicked. Flash Builder generates
stubs for event handlers, which you can then code to specify the service actions to take.
1 Select the Add button. In Properties view, near the On Click field of the Add button, click the icon. Select Generate
Event Handler.
The MXML editor changes to Source View, placing the cursor in the generated event handler.
2 In the event handler body, specify the implementation for the event.
The data types differ slightly for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.Client-side typing:
Delete
Revert
Save All Changes
Label
-
8/7/2019 Flex 4 Tutorials
57/71
54FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
var e:Employee = new Employee();
var birthDate:Date = new Date(2000, 01, 01);
var hireDate:Date = new Date(2000, 01, 01);
e.first_name = "New";
e.last_name = "New";
e.birth_date = birthDate;
e.hire_date = hireDate;
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;
Server-side typing:
var e:Employee = new Employee();
var birthDate:Date = new Date(2000, 01, 01);
var hireDate:Date = new Date(2000, 01, 01);
e.fname = "New";
e.lname = "New";
e.bdate = birthDate;e.hdate = hireDate;
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;
3 In the Script block, add the following import statement after the existing import statements:
import services.employeeservice.EmployeeService;
import valueObjects.Employee;
4 In Design mode, add an On Click event handler for the Delete button.
The data types differ slight for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:
employeeService.deleteEmployee(dg.selectedItem.emp_no);
Server-side typing:
employeeService.deleteEmployee(dg.selectedItem.emp_id);
5 Similarly, add an On Click event handler for the Revert button with the following code:
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).revertChanges();
getAllEmployeesResult.token = employeeService.getAllEmployees();
6 Add an On click event handler for the Save All Changes button with the following code:
employeeService.commit();
7 For the creationCompleteHandler() for the DataGrid, add the following lines of code:protected function dg_creationCompleteHandler(event:FlexEvent):void
{
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).autoCommit=false;
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).deleteItemOnRemoveFro
mFill=true;
getAllItemsResult.token = employeeService.getAllItems();
}
-
8/7/2019 Flex 4 Tutorials
58/71
55FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
This code makes sure that deleted items can be reverted by selecting the Revert button.
8 Save the application and select Run > Run DataMgtCF.
You can update employees in place in the DataGrid. When you click Save All Changes, the changes are updated on
the server. The server is updated is because the data management feature calls the updateItem() operation to keep
the data synchronized between the client and the server.
Click the Revert button to undo any changes you made before you click Save All Changes.
You can add and delete employees. When you add and delete employees, the data management features take care
of adding or removing the DataGrid rows. Without data management enabled, you code the updates to the
DataGrid yourself.When you add an employee, the Employee Number defaults to zero. This default value is because the new employee
has not been updated on the server. When you click Save All Changes, the new employee is added to the server. At
that time, an Employee Number is generated.
Click the Save All Changes button to write all changes to the database.
Data management tutorial (PHP)
The application you create in this tutorial accesses the employee database that you previously downloaded and
installed. For information on installing this database, see Installing the Flash Builder tutorial database on page 14.
-
8/7/2019 Flex 4 Tutorials
59/71
56FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
In this tutorial, you create an application that contains an editable DataGrid that displays employee records. You can
modify one or more records in place in the DataGrid. You can also add or delete selected records. All changes in the
DataGrid are local until you select a Save All Changes button that updates the database.
You can implement the service in this tutorial using client-side or server-side typing. The service is defined in
EmployeeService.php . If you use server-side typing, you define the Employee data type in a separate Employee class
defined in EmployeeService.php.
The server code in EmployeeService.php is basically the same in both versions. However, in the version that
implements server-side typing, the functions access the Employee data type defined in the Employee class.
Create the remote service and import it into a Flex project (client-side typing) on page 56
Create the remote service and import it into a Flex project (server-side typing) on page 60
Create the remote service and import it into a Flex project (client-side typing)
1 In your web root, create a folder named DataMgtPHP. Within that folder, create a folder named services.
2 In your favorite PHP editor, create the following PHP file, which implements a service. Name the file
EmployeeService.php and place it in the DataMgtPHP/services folder in your web root.
-
8/7/2019 Flex 4 Tutorials
60/71
57FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
-
8/7/2019 Flex 4 Tutorials
61/71
58FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
mysqli_bind_param($stmt, 'i', $itemID);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $row->emp_no, $row->birth_date,
$row->first_name, $row->last_name, $row->gender, $row->hire_date);
if(mysqli_stmt_fetch($stmt)) {
return $row;
} else {
return null;
}
}
public function createEmployees($item) {
$stmt = mysqli_prepare($this->connection,
"INSERT INTO $this->tablename (birth_date,
first_name, last_name, gender, hire_date) VALUES (?, ?, ?, ?, ?)");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'sssss', $item->birth_date,
$item->first_name, $item->last_name, $item->gender, $item->hire_date);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$autoid = mysqli_stmt_insert_id($stmt);
mysqli_stmt_free_result($stmt);mysqli_close($this->connection);
return $autoid;
}
public function updateEmployees($item) {
$stmt = mysqli_prepare($this->connection,
"UPDATE $this->tablename SET emp_no=?, birth_date=?,
first_name=?, last_name=?, gender=?, hire_date=?
WHERE emp_no=?");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'isssssi', $item->emp_no, $item->birth_date,$item->first_name, $item->last_name, $item->gender, $item->hire_date, $item-
>emp_no);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}
-
8/7/2019 Flex 4 Tutorials
62/71
59FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
public function deleteEmployees($itemID) {
$stmt = mysqli_prepare($this->connection,
"DELETE FROM $this->tablename WHERE emp_no = ?");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'i', $itemID);
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>
3 Modify the connection variables to provide your server, user name, and password for access to the
fb_tutorial_db database.
4 In Flash Builder, create a Flex project. Name the project DataMgtPHP and specify PHP for the server technology.
Click Next.
5 Specify the Web Root and Root URL for your system. Validate your server settings. Specify the DataMgtPHP
directory for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data Service. Select PHP. Click Next.
7 Click Browse and navigate to the EmployeeService.php file you created in step 2. Select EmployeeService.php .
Click Finish.
8 In the Flash Builder Data/Services view, from the context menu for the getEmployeesbyID() operation, select
Configure Return Type.
Flash Builder requires a custom data type for data returned from the data service. By introspecting the
getEmployeesbyID() operation, you can define the custom data type Employee.
9 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
10 Specify a value and type for the parameter to the getEmployeesByID() operation as described below. Click Next:
Argument Argument Type Value
itemID int 10001
-
8/7/2019 Flex 4 Tutorials
63/71
60FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
For getEmployeesByID() , you supply a valid parameter corresponding to the key field for the database. int and
10001 are valid type and value for itemID.
11 SpecifyEmployee to define a custom type for returned data.
Flex uses custom data types to access and update complex data types returned from a server. getEmployeesByID() returns the fields of a record from the Employees table in the database
The Configure Return Type dialog displays the properties of the data type returned by the service.
12 Click Finish to configure Employee as the return type.
13 In the Flash Builder Data/Services view, from the context menu for the getAllEmployees() operation, select
Configure Return Type.
14 In the Configure Return Type dialog, Auto-Detect the Return Type is selected by default. Click Next.
15 Select Use an Existing Data Type. Select Employee from the Array Of drop-down list. Click Finish.
16 Configure the parameter type and return type for deleteEmployees() as follows:
a From the context menu for the deleteEmployees() operation, select Configure Input Types. Specify int for the
type. Click OK.
b From the context menu for the deleteEmployees() operation, select Configure Return Type. Select Use An
Existing Type. Specify void. Click Finish.
Next:Enable Data Management Features on page 64
Create the remote service and import it into a Flex project (server-side typing)
This release of Flash Builder uses PHP DocBlock comments to recognize server-side data type. The sample service in
this example shows how to use DocBlock comments to define a custom data type. The example also shows how to
specify a data type for function arguments and return values.
1 In your web root, create a folder named DataMgtPHP. Within that folder, create a folder named services.
2 In your favorite PHP editor, create the following PHP file, which implements a service. The service also contains
an Employee class that defines the Employee data type.
Name the file EmployeeService.php and place it in the DataMgtPHP/services folder in your web root.
-
8/7/2019 Flex 4 Tutorials
64/71
61FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
-
8/7/2019 Flex 4 Tutorials
65/71
62FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
* Returns all the rows from the table.
*
* Add authorization or any logical checks
* for secure access to your data
*
* @return Employee[]
*/
public function getAllEmployees() {
$stmt = mysqli_prepare($this->connection, "SELECT
employees.emp_no,
employees.birth_date,
employees.first_name,
employees.last_name,
employees.gender,
employees.hire_date
FROM $this->tablename");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->emp_id, $row->bdate,
$row->fname, $row->lname, $row->gender, $row->hdate);
while (mysqli_stmt_fetch($stmt)) {
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->emp_id, $row->bdate,
$row->fname, $row->lname, $row->gender, $row->hdate);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rows;
}
/**
* @param int $itemID
* @return Employee
*/
public function getEmployeesByID($itemID) {
$stmt = mysqli_prepare($this->connection,"SELECT * FROM $this->tablename where emp_no=?");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'i', $itemID);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $item->emp_no, $item->bdate,
$item->fname, $item->lname, $item->gender, $item->hdate);
-
8/7/2019 Flex 4 Tutorials
66/71
63FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
if(mysqli_stmt_fetch($stmt)) {
return $item;
} else {
return null;
}
}
/**
* @param Employee $item
* @return int
*/
public function createEmployees($item) {
$stmt = mysqli_prepare($this->connection,
"INSERT INTO $this->tablename (birth_date,
first_name, last_name, gender, hire_date) VALUES (?, ?, ?, ?, ?)");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'sssss', $item->bdate,
$item->fname, $item->lname, $item->gender, $item->hdate);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$autoid = mysqli_stmt_insert_id($stmt);
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $autoid;
}
/**
* @param Employee $item
*/
public function updateEmployees($item) {
$stmt = mysqli_prepare($this->connection,
"UPDATE $this->tablename SET emp_no=?, birth_date=?,
first_name=?, last_name=?, gender=?, hire_date=?
WHERE emp_no=?");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'isssssi', $item->emp_id, $item->bdate,$item->fname, $item->lname, $item->gender, $item->hdate, $item->emp_id);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}
-
8/7/2019 Flex 4 Tutorials
67/71
64FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
/**
* @param int $itemID
*/
public function deleteEmployees($itemID) {
$stmt = mysqli_prepare($this->connection,
"DELETE FROM $this->tablename WHERE emp_no = ?");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 'i', $itemID);
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
}
/**
* Utitity function to throw an exception if an error occurs
* while running a mysql command.
*/
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
3 Modify the connection variables to provide your server, user name, and password for access to the
fb_tutorial_db database.
4 In Flash Builder, create a Flex project. Name the project DataMgtPHP and specify PHP for the server technology.
Click Next.
5 Specify the Web Root and Root URL for your system. Validate your server settings. Specify the DataMgtPHP
directory for the Output Folder. Click Finish.
6 From the Flash Builder Data menu, select Connect to Data Service. Select PHP. Click Next.
7 Click Browse and navigate to the EmployeeService.php file you created in step 2. Select EmployeeService.php .
Click Finish.
Next:Enable Data Management Features on page 64
Enable Data Management Features
1 In the Data/Services view, expand the Data Types node for EmployeeService and select the Employee data type.
-
8/7/2019 Flex 4 Tutorials
68/71
65FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
2 From the context menu for the Employee data type, select Enable Data Management.
3 In the Select Identity Properties dialog, select emp_id. Click Next.
4 In the Map Database Operations dialog, specify the following operations. Click Finish.
Create (Add) Operation: createEmployees()
Get Item Operation: getEmployeesByID()
Update Operation: updateEmployees()
Delete Operation: deleteEmployees ()
Click Finish. Data management is now enabled for this operation. Flash Builder generates client code that can
update data using a combination of the mapped operations.
Next:Create the application and add a DataGrid and Buttons on page 66
-
8/7/2019 Flex 4 Tutorials
69/71
66FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
Create the application and add a DataGrid and Buttons
1 If the MXML editor is in Source mode, select Design to open the MXML editor in Design mode
2 From the Components view, drag a DataGrid component onto the Design Area and place it near the top.
The DataGrid component is available under Data Controls.
3 In the Properties view, with the DataGrid selected, specify the following properties:
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.
In the Bind to Data dialog, EmployeeService and getAllEmployees() are selected. Click OK.
7 (Optional) With the DataGrid selected, in the Properties view click Configure Columns. Rename and rearrange the
columns.
Next:Generate and code event handlers for the Buttons on page 67
Property Value
ID dg
Editable true
Label
Add
Delete
Revert
Save All Changes
-
8/7/2019 Flex 4 Tutorials
70/71
67FLEX TUTORIALS
Using data management to synchronize server updates
Last updated 6/1/2010
Generate and code event handlers for the Buttons
For each Button, create an event handler to specify the action to take when the Button is clicked. Flash Builder
generates stubs for event handlers, which you can then code to specify the service actions to take.
1 Select the Add button. In Properties view, near the On Click field of the Add button, click the icon. Select GenerateEvent Handler.
The MXML editor changes to Source View, placing the cursor in the generated event handler.
2 In the event handler body, specify the implementation for the event.
The data types differ slightly for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:
var e:Employee = new Employee();
e.first_name = "New";
e.last_name = "New";
e.birth_date = "2000-01-01";
e.hire_date = "2000-01-01";
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;
Server-side typing:
var e:Employee = new Employee();
e.fname = "New";
e.lname = "New";
e.bdate = "2000-01-01";
e.hdate = "2000-01-01";
e.gender = "M";
dg.dataProvider.addItem(e);
dg.verticalScrollPosition = dg.dataProvider.length -1;
3 In the Script block, add the following import statements after the existing import statements:
import services.employeeservice.EmployeeService;
import valueObjects.Employee;
4 In Design mode, add an On Click event handler for the Delete button.
The data types differ slightly for the client-side and server-side implementations. Make sure to use the correct code
for the event handler.
Client-side typing:
employeeService.deleteEmployees(dg.selectedItem.emp_no);
Server-side typing:
employeeService.deleteEmployees(dg.selectedItem.emp_id);
5 Similarly, add an On Click event handler for the Revert button with the following code:
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).revertChanges();
getAllEmployeesResult.token = employeeService.getAllEmployees();
6 Add an On click event handler for the Save All Changes button with the following code:
employeeService.commit();
7 For the creationCompleteHandler() for the DataGrid, add the following lines of code:
-
8/7/2019 Flex 4 Tutorials
71/71
68FLEX TUTORIALS
Using data management to synchronize server updates
protected function dg_creationCompleteHandler(event:FlexEvent):void
{
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).autoCommit=false;
employeeService.getDataManager(employeeService.DATA_MANAGER_EMPLOYEE).deleteItemOnRemoveFro
mFill=true;
getAllItemsResult.token = employeeService.getAllEmployees();
}
This code makes sure that deleted items can be reverted by selecting the Revert button.
8 Save the application and select Run > Run DataMgtPHP.
You can update employees in place in the DataGrid. When you click Save All Changes, the changes are updated onthe server. The server is updated because the data management feature calls the updateEmployees() operation to
keep the data synchronized between the client and the server.
Click the Revert button to undo any changes you made before you click Save All Changes.
You can add and delete employees. When you add and delete employees, the data management features take care
of adding or removing the DataGrid rows. Without data management enabled, you code the updates to the
DataGrid yourself.
When you add an employee, the Employee Number defaults to zero. This default value is because the new employee
has not been updated on the server. When you click Save All Changes, the new employee is added to the server. At
that time, an Employee Number is generated.
Cli k h S All Ch b i ll h h d b