| Flex 2 Developer's Guide > Flex Data Features > Formatting Data > Using formatters | |||
Adobe Flex formatters are components that you use to format data into strings. Formatters perform a one-way conversion of raw data to a formatted string. You typically trigger a formatter just before displaying data in a text field. Flex includes standard formatters that let you format currency, dates, numbers, phone numbers, and ZIP codes.
All Flex formatters are subclasses of the mx.formatters.Formatter class. The Formatter class declares a format() method that takes a value and returns a String value.
For most formatters, when an error occurs, an empty string is returned and a string describing the error is written to the formatter's error property. The error property is inherited from the Formatter class.
The following steps describe the general process for using a formatter:
format() method within the curly braces ({ }) syntax for binding data, and specify the value to be formatted as a parameter to the format() method.The following example formats a phone number that a user inputs in an application using the TextInput control:
<?xml version="1.0"?>
<!-- formatters\Formatter2TextFields.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Declare a PhoneFormatter and define formatting parameters.-->
<mx:PhoneFormatter id="phoneDisplay"
areaCode="415"
formatString="###-####" />
<!-- Declare the input control.-->
<mx:Label text="Enter 7 digit phone number (########):"/>
<mx:TextInput id="myTI"/>
<!-- Declare the control to display the formatted data.-->
<mx:TextArea text="{phoneDisplay.format(myTI.text)}"/>
</mx:Application>
In this example, you use the Flex PhoneFormatter class to display the formatted phone number in a TextArea control. The following example shows the output of this application:
You do not have to use a format() method within curly braces ({ }) of a binding data expression; you can call this method from anywhere in your application, typically in response to an event. The following example declares a DateFormatter with an MM/DD/YYYY date format. The application then writes a formatted date to the text property of a TextInput control in response to the click event of a Button control:
<?xml version="1.0"?>
<!-- formatters\FormatterDateField.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Declare a DateFormatter and define formatting parameters.-->
<mx:DateFormatter id="dateFormatter"
formatString="month: MM, day: DD, year: YYYY"/>
<mx:Label text="Enter date (mm/dd/yyyy):"/>
<mx:TextInput id="dob" text=""/>
<mx:Label text="Formatted date: "/>
<mx:TextInput id="formattedDate"
text=""
editable="false"/>
<!-- Format and update the date.-->
<mx:Button label="Format Input"
click="formattedDate.text=dateFormatter.format(dob.text);"/>
</mx:Application>
Flex 2.01