Upload
nevin-paul
View
219
Download
0
Embed Size (px)
Citation preview
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
1/27
Adobe Developer Connection / Flex Developer Center/
Share on Facebook
Share o n Twitter
Share on LinkedIn
Flex
by Adobe
Modified
3 May 20 11
Page to ols
Modifying data in a database
Flex trial sample application
Search
Sign inMy cartMy shipmentsMy support
ProductsProducts SolutionsSolutions LearningLearning HelpHelp DownloadsDownloads CompanyCompany StoreStore
PDFmyURL.com
http://www.adobe.com/go/gnav_adobe_logo_en_ushttp://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://www.adobe.com/devnet/tagsearch.tsb.prod-_sl_flex_v_.tse.htmlhttp://www.adobe.com/devnet/flex/trial/examples/10_complex_app.html?trackingid=IOYQD#http://www.linkedin.com/http://twitter.com/http://www.facebook.com/sharer.phphttp://www.adobe.com/devnet/author_bios/adobe_logo.htmlhttp://www.adobe.com/devnet/flex.htmlhttp://www.adobe.com/devnet.htmlhttp://www.adobe.com/go/gnav_mysupport_en_ushttp://www.adobe.com/go/gnav_myshipments_en_ushttp://www.adobe.com/go/gnav_mycart_en_ushttp://www.adobe.com/cfusion/membership/index.cfm?loc=en_us&nl=1http://www.adobe.com/go/gnav_store_en_ushttp://www.adobe.com/go/gnav_company_en_ushttp://www.adobe.com/go/gnav_downloads_en_ushttp://www.adobe.com/go/gnav_help_en_ushttp://www.adobe.com/go/gnav_learning_en_ushttp://www.adobe.com/go/gnav_solutions_en_ushttp://www.adobe.com/go/gnav_products_en_ushttp://www.adobe.com/go/gnav_adobe_logo_en_us8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
2/27
Download the sample code and f iles (ZIP, 14. MB)
You can also view the f ull source code by right- clicking the Flex application and selecting View Source.
Explanation
This sample project shows you how to connect a Flex application to server-side data to retrieve, update,
add, and delete records in a database. To loo k at t he code, right-click on the SWF in the browser and
select View Source or download the sample files and view the source f iles in a text edito r or f ollow the
instructions to import the Flash Builder FXP.
Communicating with the server
Flex applications cannot connect directly to a remote database. Instead, they communicate with back-end
servers using either direct so cket connections o r more commonly, through HTTP. HTT P requests are
made to a remote data service written in your f avorite web language (PHP, ColdFusion, Java, or any ot her
server-s ide web technology) using one o f the Flex f ramework's remote procedure call APIs: HTT PService,
WebService, or RemoteObject. All three wrap Flash Player's HTTP connectivity, which in turn, uses the
browser's HTTP library.
With HTT PService, you make HTTP requests to JSP, PHP, CFM, or XML f iles; RESTf ul web services; or
other server f iles that returns text o ver HTTP. You specif y the endpoint URL, listener f unctions (t he
callback functions t o be invoked when the HTT PService request returns a successf ul or unsuccessf ul
response), and a data type for t he returned data (what type of data structure it sho uld be translated into
once received in the Flex application). You can specify t he data to be handled as raw t ext and ass igned to
a String variable or converted to XML, E4X, or plain old ActionScript objects . If you get back JSON, you
can use theAdobe Flex corelib package of classes to deserialize the JSON objects into ActionScript
objects. To make calls t o SOAP based web services, you can use the HTTPService API or t he more
specialized WebService API, which auto matically handles the serializat ion and deserializat ion of SOAP
formatted text to ActionScript data types and vice versa.
The third option for making remote procedure calls is to use the RemoteObject API. It makes a Flash
Remot ing request to a method of a server-s ide class (which can be a ColdFusion component) t hat
To view this co ntent, JavaScript must
be enabled, and you need the latest
version of the Adobe Flash Player.
This content requires Flash
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01https://github.com/mikechambers/as3corelib/http://download.macromedia.com/pub/developer/flex/trial/ftday10_complex_sample.ziphttp://www.adobe.com/go/getflashplayer/8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
3/27
returns binary Action Message Format (AMF) over HTT P. You specify an endpoint (which in this case is a
server-s ide Flash Remot ing class t o handle the remot ing request), a dest ination (the server- side class
that has t he methods you want to call), and listener f unctions to handle the responses. The data
translation between the client and server-s ide data types is handled automatically.
This sample project uses Flash Remot ing whose binary data transf er f ormat enables applications t o load
data up to 10 t imes f aster t han with t he more verbose, text- based formats such as XML, JSON, or SOAP.
To see a comparison of AMF to other text- based serializatio n technologies, see James Ward's Census
RIA Benchmark application.
Using Flash Remoting
Flash Remot ing is a combination of client and server-s ide functionality t hat to gether provides a call-and-
response model fo r accessing server-side objects f rom Flash Platf orm applications as if t hey were local
objects. It provides transparent data transf er between ActionScript and server-side data types, handling
the serialization into binary Action Message Format (AMF), deserialization, and data marshaling between
the client and the server.
Flash Remot ing uses client- side functionality built in to Flash Player and server-side f unctionality that
must be installed on the application server. Flash Remot ing is built in to s ome servers (like ColdFusionand Zend) but must be installed on o ther s ervers (as BlazeDS or LiveCycle Data Services o n Java EE
servers, WebORB or FluorineFX on .NET servers, the Z end Framework o r amfphp o n PHP servers, and
more).
Setting up the server
Let's s tart by taking a look at the server-side files.
ColdFusion
Flash Remoting is built in ColdFusion servers and litt le setup is necessary. You need to make sure that
Flash Remoting is enabled in the ColdFusion Administrator (Data & Services > Flex Integration > EnableFlash Remot ing support) and then in your ColdFusion components, specify an access o f remote f or the
functions you want to access from Flex applications. This sample project calls methods of
EmployeeService.cf c located in /wwwroo t/TestDrive/services/.
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://www.jamesward.org/census/8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
4/27
SELECT *FROM employees
The f iles for conf iguring Flash Remot ing files are located in /ColdFusion/wwwroot /WEB-INF/f lex/. The
main conf iguration f ile, services-conf ig.xml, defines channels to s pecify how communication should take
place between the client and server, including the proto col to use (f or example, AMF over HTT P or
HTTPS), the endpoints (the classes to handle and route the calls on the server), and other info rmation
for f inetuning the calls (like specifying if query columns names and st ructure keys should be translated
into ActionScript with lo wercase or uppercase property names). You set t he case by modifying the
tag as shown below.
true
true
true
The services-conf ig.xml f ile also includes a reference to the remot ing-conf ig.xml f ile, which is where you
can def ine dest inations, o r mappings to s pecific ColdFusion components yo u want to call from Flex.
(Aft er changes to t he configuration f iles, you must res tart t he server.) By default, remot ing-conf ig.xml
contains one default destination (with an id of ColdFusion) that has its source property set to a wildcard
so it can be used fo r any Flash Remot ing calls to any ColdFusion components.
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
5/27
*
To make a call fro m Flex with RemoteObject, you specif y a destination of ColdFusion and a so urce of
TestDrive.services.employeeService, t he f ully qualified name of the ColdFusion component that you want
to call fro m the webroot.
You can also add named destinations to remoting-conf ig. For example, you could create a destination
called employeeService that po ints to that same CFC:
TestDrive.services.EmployeeService
... and then when making calls f rom Flex, you would specify a dest ination of employeeService (instead of
ColFusion) and no source (because it is now included in the dest ination)
Java
To use Flash Remot ing with Java, you need to install an implementation of Flash Remoting on t he server.
Adobe provides the open-source BlazeDS or the commercial LiveCycle Data Services. This sample uses
BlazeDS and the BlazeDS files (JAR f iles and conf iguration f iles) are included in the Test Drive WAR file
along with the Java classes t o call f rom the Flex application. For more details, read the Flex and Java
technology overview and the architecture overview.
This sample project calls methods o f EmployeeService located in the testdrive webapp: /test drive/WEB-
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://www.adobe.com/devnet/flex/architecture.htmlhttp://www.adobe.com/devnet/flex/flex_java.htmlhttp://www.adobe.com/products/livecycle/dataservices/http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
6/27
INF/classes/services/. (The source f iles are also included fo r ref erence in /testdrive/webapps/WEB-
INF/src/services/.) It uses a typical assembler design pat tern and manipulates instances o f an Employee
data transf er object, which we will map to a co rresponding client- side ActionScript object f or pass ing data
back and fo rth between the client and server. To be called f rom Flex, the Java class must have a no
argument constructor.
package services;
import java.util.List;
import services.EmployeeDAO;
import services.Employee;
public class EmployeeService {
public EmployeeService() {
}
public List getEmployees() {
EmployeeDAO dao = new EmployeeDAO();
return dao.getEmployees();
}
//more methods...}
The f iles f or co nf iguring Flash Remoting f iles are located in /test drive/WEB-INF/f lex/. The main
conf iguration f ile, services-conf ig.xml, defines channels to specify how communication should take place
between the client and server, including the proto col to use (f or example, AMF over HTT P or HTTPS), the
endpoints (the classes to handle and route the calls on the server), and other information f or f inetuning
the calls.
The services-conf ig.xml f ile also includes a reference to the remot ing-conf ig.xml f ile, which is where youdefine dest inations, o r mappings to t he specific Java classes you want to call f rom Flex. Here is the
destination used f or the sample projects called employeeService:
services.EmployeeService
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
7/27
application
To make a call f rom Flex with RemoteObject, yo u specif y a dest ination of employeeService.
PHP
To use Flash Remot ing with PHP, you need to inst all an implementation of Flash Remoting on the server.
This sample uses the Zend Framework. You must install the f ramework and then create a PHP file (in this
sample, gateway.php) to use the f ramework and handle all the requests f rom Flex, including passing them
to the appropriate PHP classes, handling all the data trans lation and serialization, and more. If you use
the Create Data Service wizard in Flash Builder to create a data service to connect to a PHP class, the
Zend f ramework is automatically installed on your s erver (if it is not already) and gateway.php and an
amf -co nf ig.ini f ile created and placed on the server along with t he SWF. Although this sample does not
use service files created with the Flash Builder Data Service wizard, it does use the gateway.php and amf -
conf ig.ini files it creates. (The Flex Test Drive has a tutorial f or creating the service with the wizard.)
This sample project calls methods o f EmployeeService located in /htdocs/TestDrive/services/.
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
8/27
amf.directories[]=TestDrive/servicesc
To make a call from Flex with RemoteObject, you specify a dest ination of zend, an endpoint o f
gateway.php, and a so urce of EmployeeService, the name of the PHP class to call.
Creating a RemoteObject
Now that we've looked at the server-side files, let's see how to call them from Flex. The first step is to
define an instance of the RemoteObject class either in the Script block with ActionScript o r in the
Declarations tag with MXML; they are equivalent. The Declaration t ag provides a way to def ine non-visual
objects with MXML. (The green color o f the tag indicates it is a compiler tag asso ciated with compiler
instructions and not an instance of a class.)
Depending upon what s erver you are using, the RemoteObject will have slightly dif f erent propert ies
specified (the destination and poss ibly the source and/or endpoint). For ColdFusion and Java, the
endpoint is set dynamically using the services-conf ig.xml f ile and for Co ldFusion, a so urce needs to be
set if the default ColdFusion destination is used. After substituting the values f rom the constants set in
the Script block of the sample code, the RemoteObject t ag will look like one of these.
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
9/27
procedure calls, you register to listen fo rresult and fault events. Because a data service of ten has
multiple methods that can be called and they can be called at dif f erent t imes in the application, the
callback functions are usually specif ied on a per call basis instead of on the service object.
In this sample, a fault handler is specif ied fo r the RemoteObject but no result handler. This fault
handler will be used f or all service calls that do not have their own fault handler specif ied. The handler
uses t he Flex Alert component (which has a static show() method), t o display a popup with the fault
message. The FaultEvent object has a property called fault that is equal to an instance of the Faultclass that has properties faultString and faultDetail.
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
protected function employeeService_faultHandler(event:FaultEvent):void
{
Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail,"Error");
}
Note: Instead of using the RemoteObject class directly as in this s ample, you can also use Flash
Builder's Create Data Service wizard to create a data service and then call methods of a generated
service class t hat wraps the RemoteObject class . Flash Builder introspects the server-side class f ile and
creates a corresponding client-side class with the same operations. (For this introspection and code
generation to occur, RDS must be enabled on your server.) If t he server returns s tro ngly typed objects
(which is the case f or t he Java classes in this sample), ActionScript classes are created that map to the
corresponding objects manipulated by the methods of the class. If t he server returns general objects
(which is t he case f or t he PHP class and CFC in this sample), you can conf igure the data service to
create typed ActionScript objects whose properties match thos e fo r the general objects returned fro mthe server. Of course, you can also write your PHP classes and CFC methods to return st rongly typed
objects inst ead of general objects as well. Aft er creation, the data service, its methods , its argument
types, and its return t ypes are displayed in the Data/Services view and methods can be dragged and
dropped on components in the application t o add them. The Flex Test Drive tutorials create and use data
services created with the Flash Builder Data Service wizard.
Retrieving data
Next, let's loo k at the calls to the server. We want t o ret rieve the employee and department data o n
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://www.adobe.com/devnet/flex/testdrive.html8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
10/27
application st artup. To do this, you usually specify an event handler fo r the Application o bject's
initialize orcreationComplete events. Every Flex component has a series of events that are
broadcast as t he component is created, f rom the time it is instantiated until the time it is drawn on the
Flash Player drawing surf ace. The initialize event is broadcast after the component has been created
and all of its properties are set and those of its subobjects. creationComplete is broadcast later after
the component and all its subobjects also have sizes and positions. Use creationComplete if any of
the code references any sizes or pos itions.
In the sample code, a handler is specified f or the Application's initialize event:
... and inside the handler, the getEmployees() and getDepartments()methods of the service object are
called.
protected function init():void
{
getEmployeesResult.token = employeeService.getEmployees();
getDepartmentsResult.token = employeeService.getDepartments();
}
When this code is executed, Flash Player makes a call to the server. This happens asynchronously in the
background; the user can still interact with t he application.
When you make a service call, you need to specify what Flash Player should do when it gets a result o rerror back f rom the server. A fault handler was specif ied fo r the data service itself and will be used to
display errors ret urned from calls to any of it s operatio ns in a popup box.
Using call responders to specify callbacks
To handle successf ul results, CallResponder objects are declared for each of the calls.
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
11/27
(...)
These need to be asso ciated with the corresponding service call. When a service call is initiated, an
instance of the AsyncToken class is created. To associate t he CallResponder object with the service call,
you set the CallResponder's token property equal to the AsyncToken generated at t he time the service
call is made. When data is returned f rom the s erver, it is handled by that CallResponder.
getEmployeesResult.token=employeeService.getEmployees();
A CallResponder object has a lastResult property t hat automatically gets populated with the data when
it is returned to Flash Player f rom the server. It can be easily used by binding a contro l to it. In the
application, t he dataProvider property of a DataGrid component is bound to the lastResult property
of the getDepartmentsResult CallResponder object. Whenever the value of
getDepartmentsResult.lastResult changes, the DataGrid's dataProvider property is updated and
the DataGrid repopulates itself with the new data.
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
12/27
By default, one column is created fo r each of t he fields in the objects used to populate the DataGrid. You
contro l what properties t o display and in what order by sett ing the columns propert y equal to an ArrayList
of GridColumn objects . For each DataGridColumn object, you specify what property it should display
(dataField), the title for the column (headerText), its size, and more.
Using the CallResponderlastResult property works f ine if you just want t o bind the results t o a
component as shown here, but many times you will want to execute some code when the results are
returned. To do this, you register to list en fo r the result orfault events f or t he CallResponder. In the
sample, a result handler is registered fo r the getEmployeesResult CallResponder.
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
13/27
... which is equivalent to setting a public, bindable variable in ActionScript:
[Bindable]public var employees:ArrayCollection;
The dataProvider property of the empDg DataGrid is bound to this collection.
Inside this co llection, we want t o s to re st rongly typed, bindable Employee objects, not general Objects.
This way we will get code-hinting when manipulating these o bjects and co mpiler and runtime property and
property t ype checking. These objects will also be bindable, so if any of their propert ies change, an event
will be broadcast and any objects bound to it updated.
If you look in t he valueObjects f older, you will see an Employee class def inition.
package valueObjects
{
[Bindable]
//if server was returning typed objects like for java,
///[RemoteClass(alias="services.Employee")]
public class Employee
{
public var id:uint;
public var firstname:String;
public var lastname:String;
//other property declarations
public function Employee()
{
}
}
}
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
14/27
If the server-side class returns s tro ngly typed objects (as does the Java class in this s ample), you need
to include a RemoteClass metadata tag that maps this ActionScript class to t he corresponding class on
the server.
[RemoteClass(alias="services.Employee")]
This is the crucial information needed by Flash Player so it can map the server-side objects t o t he correct
client- side objects automatically. In this case, the getEmployeeResult_resultHandler() only needs to
populate the employees ArrayCollection with t he data returned f rom the server because the data has
already been translated to an ArrayCollection o f Employee objects.
protected function getEmployeesResult_resultHandler(event:ResultEvent):void
{
employees=event.result as ArrayCollection;}
The data returned f rom a server-side method call is sto red in the result property of the event object
that is passed to the result event handler. The employees variable is data t yped as an ArrayCollection
but the result property of the event object is data typed as a general Object, so you have to cast
event.result to an ArrayCollection to assign it to employees.
To see what types of ActionScript objects t he returned server-side data objects are converted to , place a
breakpoint inside the result handler and debug the application. You can also look at tables of the data
type mappings f orActionScript and Java,ActionScript and PHP, orActionScript and ColdFusion.
If Employee objects are not returned f rom the server (as is the case f or t he PHP class and CFC in this
sample), getEmployeesResult_resultHandler() needs to create this collection of Employee objects
manually. For PHP, you get an Array of Objects back from the server and for ColdFusion, an
ArrayCollection of Objects . To convert t he Objects into Employee objects , you need to loop through the
collection, creating a new Employee instance f or each item and populating its properties with the
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-79bc.htmlhttp://framework.zend.com/wiki/display/ZFPROP/Zend_Amf+-+Wade+Arnold#Zend_Amf-WadeArnold-TypeMappingTable/http://help.adobe.com/en_US/Flex/4.5/AccessingData/WS2db454920e96a9e51e63e3d11c0bf69084-7fda.html8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
15/27
corresponding properties o f the general Object, and then adding that Employee object to the collection.
You could explicitly write each property assignment:
emp.id=data[i].id;
emp.f irstname=data[i].f irstname;
emp.lastname=data[i].lastname;
//do the same fo r all properties
... but this co de instead uses the describeType() method ( in the f lash.utils package).describeType()returns an XML object t hat contains an accesso r element (which has name, access, type, and
declaredBy att ributes) f or each of o bject's properties. This is the ActionScript implementation o f
reflection.
For ColdFusion, t he getEmployeesResult_resultHandler() appears as shown here.
protected function getEmployeesResult_resultHandler(event:ResultEvent):void
{
var data:ArrayCollection=event.result as ArrayCollection;
for(var i:uint=0; i
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
16/27
protected function getEmployeesResult_resultHandler(event:ResultEvent):void
{
var data:ArrayCollection=new ArrayCollection(event.result as Array);
for(var i:uint=0; i
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
17/27
selectionChange="empDg_selectionChangeHandler(event)" ...>
Inside the selectionChange handler, you switch to the application's EmployeeDetails s tate:
protected function empDg_selectionChangeHandler(event:GridSelectionEvent):void{
currentState="EmployeeDetails";
}
... that includes a Form container that has o ne Label cont rol f or each of the employee object's properties.
(...)
The employee details will be displayed in the Label controls in the Form. A Flex Form container is purely a
layout container, helping to easily line up multiple cont rols t hat have labels in f ront of them; it has no
other purpose like in an HTML form. When you send data to t he server which we will look at next, yo u
specify explicity what objects to send; they have nothing to do with Form components.
Now that we have seen how to retrieve and display data from the server, let's look at how to modify this
data on the server, updating, adding, and deleting records in the database. You may want to go look at
your application server's class f ile (or CFC) now to f amiliarize yourself with the methods it contains
befo re looking at the code to call these methods. If you installed the files, you can look at t he source
code on your server. Otherwise, you can right-click the SWF in the browser, select View Source, and
browse to t he appropriate PHP class, Java class, or CFC.
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
18/27
Using the DataGrid to update data
One way to let users update the data is to make the DataGrid editable and then to send the changes to
the server. You make the DataGrid editable by setting its editable property to true and then registering
to listen for its gridItemEditorSessionSave event which is broadcast when the user makes changes t o
a cell value.
Inside the handler, you need to s end the modif ied Employee instance to the server: call the
updateEmployee() method and pass to it t he selected item in the DataGrid.
employeeService.updateEmployee(employee);
For ColdFusion, you need to modif y this s lightly. When you pass an object to a Flash Remoting request, it
is t reated as a gro up of named arguments and passed to the CFC method as individual arguments, no t
as a s ingle object argument. To actually pass a s ingle object as an argument, you must create an Object
instance with the name of the argument expected by the CFC, in this case an argument called item, and
pass that to the server-side method. The {} here are are an ActonScript short hand notation for creating
an Object; multiple name/value pairs would be separated by commas.
employeeService.updateEmployee({item:employee});
In this case, you're not going to do anything aft er the data is successf ully updated so you don't need to
specify a CallResponder to handle the results.
In this application, updates are sent to t he server every time the user changes data in one DataGrid cell. If
a lot o f changes are going to be made, you may want t o wait and submit all changes to t he server at
once.
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
19/27
Using a form to update data
Only some of the employee data is displayed in the DataGrid, so you may also want to provide a fo rm fo r
the user to modify all of the employee data.
When an employee is s elected and the EmployeeDetails st ate displayed, an update butt on is enabled.
When the user clicks this butt on, the application switches to its EmployeeUpdate state:
protected function updateBtn_clickHandler(event:MouseEvent):void{
currentState="EmployeeUpdate";
}
... that has a Form containing one TextInput contro l f or each of the employee properties that can be
updated.
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
20/27
When the user clicks t his button in the Form container, the employee object is updated with t he values the
user entered in the input controls and then passed to the data service's updateEmployee() method.
protected function button_clickHandler(event:MouseEvent):void
{
employee.lastname = lastnameTextInput.text;
employee.firstname = firstnameTextInput.text;
employee.title = titleTextInput.text;
//code to set the rest of the properties
if(employee.id==0){
//for Java and PHP
createEmployeeResult.token = employeeService.createEmployee(employee);
//for CF, createEmployeeResult.token =
employeeService.createEmployee({item:employee});
}
else{//for Java and PHP
updateEmployeeResult.token = employeeService.updateEmployee(employee);
//for CF, updateEmployeeResult.token =
employeeService.updateEmployee({item:employee});
}
}
Similar functio nionality will be used to add a new employee next, so this f unction has been written to
handle bot h cases. If an existing employee is being updated, employee.id will be non-zero, so the
server-side updateEmployee() method is called. Otherwise, the createEmployee()method is called. As
before, the code f or ColdFusion is slightly diff erent t o pass an object to a server-side method.
In this case, we do want to do something aft er the data has successf ully been sent to t he server, so a
new CallResponder is def ined with a result handler:
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
21/27
... and the service call assigned to the CallResponder's token property.
updateEmployeeResult.token=employeeService.updateEmployee(employee);
In the result handler, the application switches to its EmployeeDetails st ate and shows the details f or the
modif ied employee.
protected function updateEmployeeResult_resultHandler(event:ResultEvent):void
{
currentState="EmployeeDetails";
}
Using the form to add data
Similar code is used to add a new employee to the database. When an employee is selected, an add
butto n is enabled.
When the user clicks this butt on, the application switches to its EmployeeAdd state, which shows the
same fo rm as used to update an employee, but now the submit button is labeled Add instead of Update.
protected function addBtn_clickHandler(event:MouseEvent):void
{
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
22/27
currentState="EmployeeAdd";
employee=new Employee();
}
Using the form to add data
Similar code is used to add a new employee to the database. When an employee is selected, an add
butto n is enabled.
When the user clicks this butt on, the application switches to its EmployeeAdd state, which shows the
same fo rm as used to update an employee, but now the submit button is labeled Add instead of Update.
protected function addBtn_clickHandler(event:MouseEvent):void
{
currentState="EmployeeAdd";
employee=new Employee();
}
The employee object is also set equal to a new Employee instance (employee could currently contain the
employee selected in the DataGrid) so t he input cont rols in the Form container that are bound to it will all
be set to the Employee class's default values.
The same handler is called when the user clicks the butto n in the f orm:
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
23/27
... which populat es employee with the data from the input controls and now in this case, employee.id will
be zero so employee is passed to the data service's createEmployee() method.
protected function button_clickHandler(event:MouseEvent):void
{employee.lastname = lastnameTextInput.text;
employee.firstname = firstnameTextInput.text;
employee.title = titleTextInput.text;
//code to set the rest of the properties
if(employee.id==0){
//for Java and PHP
createEmployeeResult.token = employeeService.createEmployee(employee);
//for CF, createEmployeeResult.token =
employeeService.createEmployee({item:employee});
}else{
//for Java and PHP
updateEmployeeResult.token = employeeService.updateEmployee(employee);
//for CF, updateEmployeeResult.token =
employeeService.updateEmployee({item:employee});
}
}
To handle results, a new CallResponder is defined with a result handler:
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
24/27
createEmployeeResult.token=employeeService.createEmployee(employee);
After the data is added successfully to the database, the EmployeeDetails state is shown with the details
for this new employee.
protected function createEmployeeResult_resultHandler(event:ResultEvent):void
{
currentState="EmployeeDetails";
// more code
}
At this po int the new employee is saved in the database, but not in the collection o f data being displayed
in the DataGrid. You need to assign the newly generated id to employee and add employee to t he data
displayed in the DataGrid.
If you look in the TestDrive server-s ide service f ile, you will see that t he createEmployee() method
returns an integer equal to the id of the new employee inserted in the database. The data returned f rom
a server-side method call is stored in the result property of the event object t hat is passed to t he
result event handler. The id property o femployee is data typed as an integer and the result property
of the event object is data typed as a general Object, so you have to cast event.result to an integer to
set id equal to it.
employee.id=event.result as int;
You use the addItem() method to add the new employee to the employees ArrayCollection.
employees.addItem(employee);
PDFmyURL.com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.018/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
25/27
Note: In this example, you are writing code to update both the server-s ide data (s to red in the database)
and the client-side data (stored in the DataGrid dataProvider). Flash Builder also has a data
management f eature you can use to help synchronize client and server-s ide data.
Then, you select it in the DataGrid:
empDg.setSelectedIndex (employees.getItemIndex(employee));
... and then scroll to it so it is displayed:
empDg.ensureCellIsVisible(empDg.selectedIndex);
The result event handler f or adding an employee appears as s hown here.
protected function createEmployeeResult_resultHandler(event:ResultEvent):void
{
currentState="EmployeeDetails";
employee.id=event.result as int;
employees.addItem(employee);
empDg.setSelectedIndex(employees.getItemIndex(employee));
empDg.ensureCellIsVisible(empDg.selectedIndex);
}
Deleting data
The last t hing to look at is ho w to delete an employee fro m the database. The process is very similar to
thos e f or adding and updating. When an employee is selected, a delete butto n is enabled.
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
26/27
enabled.EmployeeAdd="false" includeIn="EmployeeAdd,EmployeeDetails,EmployeeUpdate"
label="Delete" enabled.EmployeeUpdate="true"/>
When the user clicks this button, the server-side deleteEmployee() method is called.
protected function deleteBtn_clickHandler(event:MouseEvent):void
{
deleteEmployeeResult.token = employeeService.deleteEmployee(employee.id);
}
To handle results, a new CallResponder is defined with a result handler:
8/6/2019 Www.adobe.com Devnet Flex Trial Examples 10 Complex App.html Trackingid=IOYQD
27/27
currentState="Employees";
}
Back to t op
+
This work is licensed under a Creative Commons Att ribution-Noncommercial-Share Alike 3.0 Unported
License. Permissions beyond the scope of this license, pertaining to the examples of code included within
this work are available atAdobe.
Copyright 2011 Adobe Systems Incorporated. All rights res erved.
Use o f this website signifies your agreement to the Terms of Use and Online Privacy Policy(updated 07-14-2009) .
SecurityContact AdobeReport piracyEULAsPermissions and trademarksCareersChoose your region
PDFmyURL com
http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://www.adobe.com/go/gfooter_privacy_policyhttp://www.adobe.com/go/gfooter_terms_of_usehttp://www.adobe.com/go/gfooter_careershttp://www.adobe.com/go/gfooter_permissions_trademarkshttp://www.adobe.com/go/gfooter_eulashttp://www.adobe.com/go/gfooter_report_piracyhttp://www.adobe.com/go/gfooter_contact_adobehttp://www.adobe.com/go/gfooter_securityhttp://www.adobe.com/go/gfooter_choose_regionhttp://www.adobe.com/communities/guidelines/ccplus/commercialcode_plus_permission.htmlhttp://creativecommons.org/licenses/by-nc-sa/3.0/http://www.adobe.com/communities/guidelines/ccplus/commercialcode_plus_permission.htmlhttp://creativecommons.org/licenses/by-nc-sa/3.0/http://www.adobe.com/devnet/flex/trial/examples/10_complex_app.html?trackingid=IOYQD#