Creating RIA with Adobe Flex framework

November 11, 2010

Adobe Flex

«»

Manipulating XML Data in Flex controls

In this section, we will see how to use XML as a data provider for various Flex controls. Flex provides a flexible API for dealing with various forms of XML data. We will also explore the various data types and the classes available in Flex for supporting XML for storing and retrieving data. Consider the following example,

Download Adobe Flex Example Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>
 
	<fx:Script>
		<![CDATA[
 
			private var employees:XML = 
				<employees>
					<employee id = "1">John</employee>
					<employee id = "2">David</employee>
					<employee id = "3">Steve</employee>
					<employee id = "4">Marcus</employee>
				</employees>;
 
			private function displayXmlHandler(event:Event): void{
 
				employeesTA.text = employees.toXMLString();
			}
 
			private function clearXmlHandler(event:Event): void{
 
				employeesTA.text = "";
			}
 
		]]>
	</fx:Script>
 
	<s:TextArea id = "employeesTA" x="274" y="159" width="304" height="163"/>
 
	<s:Button x="313" y="101" label="Display XML" click="displayXmlHandler(event)"/>
 
	<s:Button x="472" y="100" label="Clear XML" click="clearXmlHandler(event)"/>
 
 
</s:Application>

Upon running the above example, it will provide an UI similar to the following in the browser.

The point to be noted is that a variable of type ‘XML’ is declared for storing XML data. The UI for this applications contains a text area along with the two buttons. The button ‘Display XML’ when clicked will try to display the xml content into the text area. The button ‘Clear XML’ does the reverse, i.e. it clears the xml data stored on the text area. For supporting the displaying and clearing of XML text onto the textarea, we have added two event handlers when the buttons are clicked.

The above example is fairly simple and straightforward, however the power of xml lies when it can be used as a data provider for complex Flex controls such as Datagrid. Consider the following example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<fx:Declarations>
 
	</fx:Declarations>
 
	<fx:Script>
		<![CDATA[
			private var playersXmlData:XML =
				<players>
					<player id="SACHIN_TEN">
						<name>
							<firstName>Sachin</firstName>
							<lastName>Tendulkar</lastName>
						</name>
						<playingFor>India</playingFor>
						<ODI>320</ODI>
						<Runs>16000</Runs>
						<Rating>1</Rating>
					</player>
					<player id="BR_LARA">
						<name>
							<firstName>Brian</firstName>
							<lastName>Lara</lastName>
						</name>
						<playingFor>West Indies</playingFor>
						<ODI>200</ODI>
						<Runs>9000</Runs>
						<Rating>10</Rating>
					</player>
					<player id="RKY_PONTING">
						<name>
							<firstName>Ricky</firstName>
							<lastName>Ponting</lastName>
						</name>
						<playingFor>Australia</playingFor>
						<ODI>260</ODI>
						<Runs>12000</Runs>
						<Rating>7</Rating>
					</player>				
				</players>;
 
			private function getName(player:Object, column:DataGridColumn): String {
				var xml:XML = XML(player);
				return player.name.firstName + " "+ player.name.lastName;
			}
		]]>
	</fx:Script>
 
	<mx:Panel title="Players Information" width="662" height="244" x="116" y="144" 
			  id="playersInfo" backgroundColor="#DB5C5C" contentBackgroundColor="#0B2973" 
			  borderColor="#000000" fontSize="20" fontStyle="normal" fontWeight="bold">
		<mx:DataGrid id="playersGrid" dataProvider="{playersXmlData.player}"
					 height="199" width="100%" variableRowHeight="true" fontSize="20">
			<mx:columns>
				<mx:DataGridColumn headerText="Id" dataField="@id" 
					color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
				<mx:DataGridColumn headerText="Name" labelFunction="getName" 
					color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
				<mx:DataGridColumn headerText="Country" dataField="playingFor" 
					color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
				<mx:DataGridColumn headerText="Total ODI Matches" dataField="ODI" 
					color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
				<mx:DataGridColumn headerText="Total Runs in ODI" dataField="Runs" 
					color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
				<mx:DataGridColumn headerText="ICC Rating" dataField="Rating" 
					color="#010101" fontFamily="Arial" fontSize="17" wordWrap="true" fontWeight="bold"/>
			</mx:columns>
		</mx:DataGrid>
	</mx:Panel>
 
</s:Application>

The scripting block for this application contains the declaration of XML that contains various details of some players. Then after that we draw a panel using ‘mx:Panel’ element for holding the Grid component. We have expressed the title for the Panel through the attribute ‘title’. The data source for the grid component comes from the ‘players xml’ and hence the attribute ‘dataProvider’ is used to specify this. A data grid is expected to contain a series of columns with static information (in the form of heading) and dynamic information. These details are expressed through the elements ‘mx:columns’ and ‘mx:DataGridColumn’. For displaying the static header text we have used the attribute ‘headerText’.

We have used three different ways for extracting information from the XML in this example. The first way is for referring the attributes. For attributes, the attribute name has to be prefixed with ‘@’ symbol. For example, ‘id’ appears to be an attribute and the same has been referred as ‘@id’ in the dataField of the grid component. Referring child elements are straightforward, the child element name can appear directly in the dataField attribute. The final way for fetching information to be displayed is to have a special type of function that operates/aggregates data from the complex xml element. For example, in order to display the name of the player which appears as two child elements ‘firstName’ and ‘lastName’, we have define a function ‘getName()’ which returns the combined value of the child element ‘firstName’ and ‘lastName’. Note the first argument passed to the function is the current player object and the second argument is the column object. Within the implementation of the function, we have returned the player’s complete name by taking the first and the last name into consideration.

Formatting Data

In this section, we will see how to format the data before displaying it. Like Validators, Adobe Flex comes with a set of formatters that suits the basic needs. For example, it provides formatters for formatting numbers, currency, phone number, date etc. Have a look at the following code that makes use of the formatters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
 
	<fx:Declarations>
 
		<mx:NumberFormatter id="numberFormatter" useNegativeSign="true" precision="3"
			error="The format of the number is incorrect">			
		</mx:NumberFormatter>
 
		<mx:CurrencyFormatter id="currencyFormatter" currencySymbol="Rs " useNegativeSign="true"
			error="The format of currency is incorrect">			
		</mx:CurrencyFormatter>
 
		<mx:DateFormatter id="dateFormatter" error="Date format is incorrect" formatString="MM/DD/YYYY">			
		</mx:DateFormatter>
 
		<mx:PhoneFormatter id="phoneFormatter" error="Phone format is invalid" formatString="### - #### ####">			
		</mx:PhoneFormatter>
 
	</fx:Declarations>
 
	<fx:Script>
		<![CDATA[
 
			private var textXML:XML =
				<Data>
					<Number>-10.123243</Number>
					<Currency>803432.323</Currency>
					<Date>01/01/10 10:33</Date>
					<Phone>08041413131</Phone>
				</Data>;
 
		]]>
	</fx:Script>
 
	<s:Panel x="80" y="148" width="675" height="236" id="formatterId" title="Formatter Test">
		<s:Label text="Currency: Original Value -> {textXML.Currency}, Formatted Value -> {currencyFormatter.format(textXML.Currency)}"  
			x="7" y="24" height="30" fontWeight="bold" width="616"/>
		<s:Label text="Number: Original Value -> {textXML.Number}, Formatted Value -> {numberFormatter.format(textXML.Number)}"   
			x="10" y="62" height="28" width="613" fontWeight="bold"/>
		<s:Label text="Date: Original Value -> {textXML.Date}, Formatted Value -> {dateFormatter.format(String(textXML.Date))}"   
			x="10" y="121" height="28" width="613" fontWeight="bold"/>
		<s:Label text="Phone: Original Value -> {textXML.Phone}, Formatted Value -> {phoneFormatter.format(textXML.Phone)}"   
			x="10" y="157" height="28" width="613" fontWeight="bold"/>
	</s:Panel>
 
</s:Application>

Like the usage of validators, formatters are declared within the ‘fx:Declarations’ section. We have used ‘NumberFormatter’, ‘CurrencyFormatter’, DateFormatter’ and ‘PhoneFormatter’ for formatting numbers, currency, date and phone numbers respectively. Later on in the ‘fx:Script’ block, we have created some sample data to be formatted which were later referred in the UI components. Note that for performing the formatting operation, we have to call the format() method by passing in the data to be formatted. We have used the label component for displaying the value before formatting and the value that got modified after formatting. Running the above program will result in an output similar to the following.

Conclusion

In this article, we saw an introduction to the basic level of programming in Adobe Flex. The article initially started with explaining how to setup the Adobe Flex environment with the introduction to Adobe Flex Builder and Adobe Flash player plugins. Later on, it showed how to write a simple ‘Hello World’ application. Then the event handler mechanism along with process of validating data were discussed in detail. It was then followed by the usage of XML data along with the complex Grid components with respect to data binding. Finally the article concluded with the usage of Formatters for formatting data.

email

«»

Comments

comments