Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection /

Exploring Rich Island development with Flex Builder – Part 3: Handling data and binding it to controls

by Trilemetry

Trilemetry
  • Trilemetry, Inc.

Content

  • Creating data in an ArrayCollection instance
  • Binding data to a DataGrid control
  • Binding data to Label and TextInput controls
  • Creating event handlers

Modified

3 August 2009

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
DataGrid Flex 3 Flex Builder 3

Requirements

Prerequisite knowledge

  • Part 1: Getting started
  • Part 2: Laying out and styling visual elements

User level

All

Required products

  • Flex Builder (Download trial)

Sample files

  • sap_ri_pt3_starter.zip (26 KB)
  • sap_ri_pt3_solution.zip (25 KB)

Welcome to Part 2 of this tutorial series. In this part, you use ActionScript to create an ArrayCollection instance and populate it with the data needed for the wagon assembly line. You use bindings to tie the ArrayCollection data to the Flex framework DataGrid control; when the data changes in the control it is immediately reflected in the associated colored bins. In Parts 7 and 8 you will replace this dummy data with data from the Web Dynpro application.

Note: Parts 1 through 6 focus on teaching Flex development to SAP developers. Part 7 teaches Flex developers how to create a Web Dynpro application. Parts 8 and 9 show both SAP and Flex developers how to integrate the Flex application as a Rich Island into the Web Dynpro application.

The ShopFloorBins application
Figure 1. The ShopFloorBins application

Creating data in an ArrayCollection instance

This tutorial introduces the following new variables:

  • _wagonInventory: The inventory data that populates the colored bins.
  • _wagonYellowWarningAmount: The minimum number of wagons that can be created, based on the available inventory, when a bin turns yellow.
  • _inventoryNeededForYellow: The number of parts needed in a bin to make the wagons for the _wagonYellowWarningAmount.
  • _wagonRedWarningAmount: The minimum number of wagons that can be created, based on available inventory, when you want the bin to turn red and the assembly line to stop.
  • _inventoryNeededForRed: The number of parts needed in the bin to make the wagons for the _wagonRedWarningAmount.

In Part 2, you created the wagon assembly line layout using MXML tags and CSS selectors. In this section, you use ActionScript to program the business logic for the application. First, you will create an ArrayCollection and populate it with data.

  1. After the opening Application tag, create a Script block.

    You will place all of your ActionScript code into an MXML Script block.

<mx:Script> <![CDATA[ ]]> </mx:Script>

The CDATA statement instructs the parser to not process the code as MXML.

  1. After the opening CDATA code, use the import statement to import the ArrayCollection class from the mx.collections package.

    The ArrayCollection class is a wrapper class for arrays that has additional functions to manipulate the array.

<mx:Script> <![CDATA[ import mx.collections.ArrayCollection; ]]> </mx:Script>
  1. After the import statement, declare a private variable named _wagonInventory and data type it to the ArrayCollection class.

    Note: It is customary to name private variables starting with an underscore. A private variable can only be accessed from within the class in which it is defined.

import mx.collections.ArrayCollection; private var _wagonInventory:ArrayCollection;
  1. After the variable, create a private function named populateData(), that takes no arguments and has a return type of void.

Note: A function is reusable code that only executes when triggered or called. The void return type means nothing is returned or sent back from the function to the calling code.

  1. Within the function, instantiate _wagonInventory as an ArrayCollection instance.

    Note: To instantiate means to create a new object, or instance, of the declared class.

_wagonInventory = new ArrayCollection();
  1. Using the addItem() method of the ArrayCollection class, add the following objects to the _wagonInventory variable:
private function populateData():void { _wagonInventory= new ArrayCollection(); _wagonInventory.addItem({Title:'TUBS', Quantity:120, Parts:1}); _wagonInventory.addItem({Title:'AXELS', Quantity:190, Parts:2}); _wagonInventory.addItem({Title:'WHEELS', Quantity:320,Parts:4}); _wagonInventory.addItem({Title:'HANDLES', Quantity:61,Parts:1}); _wagonInventory.addItem({Title:'BOXES', Quantity:400, Parts:1}); }

The Title key represents the name of the inventory bin and the Quantity key represents the amount of inventory in the bin. The Parts key represent the number of parts needed for each wagon; in other words, you need four wheels to create one wagon.

The curly braces in this context denote that the Title, Quantity, and Parts values comprise each object in an array. Remember that an ArrayCollection is a wrapper class for arrays.

  1. Save the file and run it.

You should not see any visual changes from Part 2.

Binding data to a DataGrid control

In this section, you populate the DataGrid control on initialization of the application.

  1. Return to the ShopFloorBins.mxml file in Flex.
  2. Locate the opening Application tag.
  3. To the Application tag, add the initialize event that declares the event handler as the populateData() function.

    The initialize event is dispatched when a component and all of its children have been created, but before the component size has been determined. You will populate the data for the application during this phase of the component life cycle.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundGradientColors="[0xFFFFFF, 0xFFFFFF]" initialize="populateData()">
  1. Locate the code in the Script block where you declared the _wagonInventory private variable and make the variable bindable by using the [Bindable] metadata tag.

    Note: When you make a variable bindable, Flex generates a propertyChange event for the variable that will track when it has changed and will automatically update its value every where it is used.

[Bindable] private var _wagonInventory:ArrayCollection;
  1. Locate the DataGrid control.
  2. Add the dataProvider property with a value of _wagonInventory using the curly brace syntax that designates a binding.
<mx:DataGrid dataProvider="{_wagonInventory}"/>

The dataProvider property for a DataGrid control declares the Array, ArrayCollection, or XML data to display.

  1. Save the file and run it.

    Your application should appear as shown in Figure 2.

The DataGrid is populated with data from the ArrayCollection instance.
Figure 2. The DataGrid is populated with data from the ArrayCollection instance.

Binding data to Label and TextInput controls

In this section, you will populate the title and value in the bins.

  1. Locate the binTitle0 Label control and delete the text property value.
  2. Use the getItemAt()method of the ArrayCollection class and the binding curly braces to retrieve the 0 index Title value of the _wagonInventory data and assign it to the text property.
<mx:Label id="binTitle0" text="{_wagonInventory.getItemAt(0).Title}" textAlign="center" width="100" styleName="titleFont"/>
  1. Locate the binTitle1 Label control, delete the text property value and apply the same binding value using index 1.
  2. Locate the binTitle2 Label control, delete the text property value and apply the same binding value using index 2.
  3. Locate the binTitle3 Label control, delete the text property value and apply the same binding value using index 3.
  4. Locate the binTitle4 Label control, delete the text property value and apply the same binding value using index 4.
  5. Save the file and run it.

    Your application should appear as shown in Figure 3.

The bin titles are populated from the ArrayCollection instance.
Figure 3. The bin titles are populated from the ArrayCollection instance.
  1. Locate the binData0 TextInput control and delete the text property value.
  2. Use the getItemAt() method to retrieve the 0 index Quantity value of _wagonInventory and assign it to the text property.
<mx:TextInput id="binData0" text="{_wagonInventory.getItemAt(0).Quantity}".../>
  1. Locate the binData1 TextInput control, delete the text property value and apply the same binding value using index 1.
  2. Locate the binData2 TextInput control, delete the text property value and apply the same binding value using index 2.
  3. Locate the binData3 TextInput control, delete the text property value and apply the same binding value using index 3.
  4. Locate the binData4 TextInput control, delete the text property value and apply the same binding value using index 4.
  5. Save the file and run it.

    Your application should appear as shown in Figure 4.

The colored bins are populated with appropriate quantities from the ArrayCollection instance.
Figure 4. The colored bins are populated with appropriate quantities from the ArrayCollection instance.
  1. Locate the DataGrid control and add the editable property with a value of true.
<mx:DataGrid dataProvider="{_wagonInventory}" editable="true"/>
  1. Save the file and run it.
  2. Click the quantity value in the first row of the DataGrid control.
The quantity is highlighted.
Figure 5. The quantity is highlighted.
  1. Change the value to 3 and click Enter.

Figure 6 shows the change reflected in the bin.

The quantity changes in the Tubs colored bin when you change it in the DataGrid control
Figure 6. The quantity changes in the Tubs colored bin when you change it in the DataGrid control

Creating event handlers

In this section, you add a listener to the _wagonInventory ArrayCollection instance to change the bin color if the quantity is within a certain threshold range. The bin colors will be green, yellow, or red depending on the quantity value in the bin.

Adding the COLLECTION_CHANGE event listener

In this section, you will add a listener to _wagonInventory ArrayCollection to do additional processing when the data changes.

  1. After the last import statement in the Script block, import the CollectionEvent class from the mx.events package.
import mx.events.CollectionEvent;
  1. After the populateData() function, create another private function named startProduction() that takes no arguments and has a return type of void.
  2. Within the function, call the populateData() function.
  3. Next use the addEventListener() method of the ArrayCollection class to listen for changes in the _wagonInventory data. Listen for the CollectionEvent.COLLECTION_CHANGE event and handle it with the binColorHandler function.

    Note: You will create the binColorHandler() function later in this tutorial. Do not use the parentheses for the function in the second argument of the addEventListener() method. This is a reference to the function, not a call. Every time the data on the _wagonInventory collection changes, the listener will call the binColorHandler() function.

private function startProduction():void { populateData(); _wagonInventory.addEventListener(CollectionEvent.COLLECTION_CHANGE, binColorHandler); }
  1. Locate the initialize property in the opening Application tag and change the value to startProduction().
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundGradientColors="[0xFFFFFF, 0xFFFFFF]" initialize="startProduction()">

Creating variables for inventory calculations

In this section, you will create new variables for the calculation of inventory.

  1. After the _wagonInventory variable, create a private variable named _wagonYellowWarningAmount and data type it to the uint class with a value of 50. This variable will be used to turn the bins yellow when they only have enough inventory to create 50 or fewer wagons.
private var _wagonYellowWarningAmount:uint = 50;
  1. Create another private variable named _wagonRedWarningAmount and data type it to the uint class with a value of 0 (zero).

    This variable will be used to turn a bin red, and stop the assembly line, when the bin does not have enough inventory to create any wagons.

  2. Create another private variable named _inventoryNeededForYellow and data type it to the uint class.

    This variable represents the number of parts needed in a bin to make the wagons for the _wagonYellowWarningAmount.

  3. Create another private variable named _inventoryNeededForRed and data type it to the uint class. This variable represents the number of parts needed in the bin to make the wagons for the _wagonRedWarningAmount.
private var _wagonYellowWarningAmount:uint = 50; private var _wagonRedWarningAmount:uint = 0; private var _inventoryNeededForYellow:uint; private var _inventoryNeededForRed:uint;

Creating the event handler for the COLLECTION_CHANGE listener

In this section, you create the event handler that is called when the ArrayCollection data changes. This function will determine the color for each bin based on the current inventory in the bin and the threshold values.

  1. After the startProduction() function, create a private function named binColorHandler() which takes one argument named event that is data typed to the CollectionEvent class. Set the argument's default value to null and the function's return type is void.

    Note: By setting a default value for the event argument, the function will still work when the value is not present.

private function binColorHandler(event:CollectionEvent = null):void { }
  1. Within the function, create a for loop to loop over the _wagonInventory ArrayCollection instance.
  2. In the for statement, create an iterant named x of type int with a value of 0 (zero).
  3. While x is less than _wagonInventory.length, iterate the loop using the x++ syntax.
private function binColorHandler(event:CollectionEvent = null):void { for (var x:int=0; x < _wagonInventory.length; x++) { } }

Within the for loop, assign the result of _wagonYellowWarningAmount multiplied by the _wagonInventory Parts value to _inventoryNeededForYellow. Use the getItemAt() function and pass x to retrieve the value from the ArrayCollection.

Note: In order to create 50 wagons to reach the yellow threshold, you will need a certain number of wagon parts per bin. For example, to create 50 wagons, you will need 4 wheel parts per wagon for a total of 200 wheels necessary. You will need 2 axels per wagon for a total of 100 axels for 50 wagons.

for (var x:int=0; x < _wagonInventory.length; x++) { _inventoryNeededForYellow = _wagonYellowWarningAmount * _wagonInventory.getItemAt(x).Parts; }
Next within the loop, assign the result of _wagonRedWarningAmount multiplied by the _wagonInventory Parts value to _inventoryNeededForRed. Use the getItemAt() function and pass x to retrieve the value from the ArrayCollection.

Note: Currently the _wagonRedWarningAmount is set to zero, which means you will need a minimum of zero parts to display a red bin. However, you will still create this calculation in case you later want to change the threshold value to another amount.

for (var x:int=0; x < _wagonInventory.length; x++) { _inventoryNeededForYellow = _wagonYellowWarningAmount * _wagonInventory.getItemAt(x).Parts; _inventoryNeededForRed = _wagonRedWarningAmount * _wagonInventory.getItemAt(x).Parts; }
  1. After the calculations, but still within the for statement, create a two-part conditional statement, testing first to see if the quantity in _wagonInventory is less than or equal to _inventoryNeededForRed or (double pipe ||) the _wagonInventory quantity is less than the _wagonInventory parts.

    Note: If the bin quantity on hand is less than or equal to the total inventory needed for the red threshold or if the bin quantity on hand is less than the parts needed for a wagon, the conditional statement is true. This means you do not have enough inventory left in this bin to create a wagon. This means the bin must change to red.

if ((_wagonInventory.getItemAt(x).Quantity <= _inventoryNeededForRed) || (_wagonInventory.getItemAt(x).Quantity < _wagonInventory.getItemAt(x).Parts)) { }
Inside the curly brackets of this part of the conditional statement, use the setStyle() function to set the backgroundColor to red (0xCC0000) for the current binCanvas container. Use this["binCanvas "+ x] for the dynamic instance.

Note: The setStyle() function is used to change the style for a display element at runtime. The this keyword refers to the current scope and the ["binCanvas" + x] syntax builds the instance reference dynamically (binCanvas0, binCanvas1, and so on).

if (_wagonInventory.getItemAt(x).Quantity <= _inventoryNeededForRed || _wagonInventory.getItemAt(x).Quantity < _wagonInventory.getItemAt(x).Parts) { this["binCanvas" + x].setStyle("backgroundColor", 0xCC0000); }
  1. Add an else statement after the closing curly brace.
  2. Create a new conditional statement that tests if the quantity in _wagonInventory is greater than the _inventoryNeededForRed variable and (double ampersand &&) the quantity in _wagonInventory is less than or equal to the _inventoryNeededForYellow variable.

    Note: If the bin quantity on hand is greater than the total inventory needed for the red threshold and the bin quantity on hand is less than or equal the total inventory needed for the yellow threshold, then you have enough inventory to create a wagon, but you will fall within the yellow threshold.

if (...) { this["binCanvas"+x].setStyle("backgroundColor", 0xCC0000); } else if (_wagonInventory.getItemAt(x).Quantity > _inventoryNeededForRed && _wagonInventory.getItemAt(x).Quantity <= _inventoryNeededForYellow) { }
  1. Within the curly brackets of this part of the conditional statement, use the setStyle() function to set the backgroundColor to yellow (0xE5E006) for the dynamic instance of the current bin Canvas container.
else if (_wagonInventory.getItemAt(x).Quantity > _inventoryNeededForRed && _wagonInventory.getItemAt(x).Quantity <= _inventoryNeededForYellow) { this["binCanvas"+x].setStyle("backgroundColor", 0xE5E006); }
  1. Add an else statement after the else if statement and use the setStyle() function to set the backgroundColor to green (0x339933) for the dynamic instance of the current bin canvas container. If the available inventory does not fall within the red or yellow thresholds, the bin color should be green.

Your code should appear as follows:

if (...) { this["binCanvas"+x].setStyle("backgroundColor", 0xCC0000); } else if (...) { this["binCanvas"+x].setStyle("backgroundColor", 0xE5E006); } else { this["binCanvas"+x].setStyle("backgroundColor", 0x339933); }

Testing the application

In this section, you will change the quantity values to see the bin colors change.

  1. Save the file and run it.
  2. In the DataGrid control, change the quantity of the Handles to 49 and click Enter.

    You should see the handles bin turn yellow (see Figure 7).

The handles bin hits the yellow threshold.
Figure 7. The handles bin hits the yellow threshold.
  1. In the DataGrid control, change the quantity of any of the bins to 0 (zero) and click Enter.The associated bin will turn red. Figure 8 shows the TUBS bin and DataGrid quantity set to zero.
The quantity for tubs hits the red threshold.
Figure 8. The quantity for tubs hits the red threshold.

Where to go from here

In this tutorial you learned how to write ActionScript. You also created an ArrayCollection instance and bound its data to various Flex controls. Lastly, you added a listener to call an event handler that changed the inventory bin displays to red, yellow or green depending on the available inventory.

If you are interested in learning more about the topics in this tutorial, refer to the following resources:

  • Using ActionScript in Flex applications
  • About the import statement
  • Adding EventListeners with ActionScript (5:21)
  • Understanding variable scope
  • Class property attributes
  • About data binding
  • Using the Bindable metadata tag
  • About the initialize and creationComplete events
  • Using the DataGrid control and binding to data
  • Binding data between controls (5:48)
  • Displaying data in the DataGrid (6:35)
  • Adding EventListeners with ActionScript (5:21)
  • Using the setStyle() and getStyle() methods

In Part 4, you will learn how to create a custom component in MXML, create class properties with getter and setter functions and use the custom component within an application.

Exploring Rich Island development with Flex Builder

For your reference, here are all the parts in this series:

  • SAP developers: Build an interactive Flex application from scratch
    • Part 1: Getting started
    • Part 2: Laying out and styling visual elements
    • Part 3: Handling data and binding it to controls
    • Part 4: Creating a custom component
    • Part 5: Animating with ActionScript
    • Part 6: Synchronizing data in components
  • Flex developers: Create a Web Dynpro application
    • Part 7: Creating an SAP application
  • Flex and SAP developers: Create a working Rich Island
    • Part 8: Creating a Rich Island and handling data
    • Part 9: Communicating between a Rich Island and a Web Dynpro application
 

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement