Adobe Flex 3 Help

Extending a Formatter class

You can extend the Formatter class to create a custom formatter, or any formatter class. The example in this section extends the ZipCodeFormatter class by allowing an extra format pattern: "#####*####".

In this example, if the user omits a format string, or specifies the default value of "#####*####", the formatter returns the ZIP code using the format "#####*####". If the user specifies any other format string, such as a five-digit string in the form "#####", the custom formatter calls the format() method in the superclass ZipCodeFormatter class to format the data.

package myFormatters
{
    // formatters/myFormatter/ExtendedZipCodeFormatter.as
    import mx.formatters.Formatter
    import mx.formatters.ZipCodeFormatter
    import mx.formatters.SwitchSymbolFormatter

    public class ExtendedZipCodeFormatter extends ZipCodeFormatter {

        // Constructor
        public function ExtendedZipCodeFormatter() {
            // Call base class constructor. 
            super();
            // Initialize formatString.
            formatString = "#####*####";
        }

        // Override format().
        override public function format(value:Object):String {
            // 1. If the formatString is our new pattern, 
            // then validate and format it.

            if( formatString == "#####*####" ){

                if( String( value ).length == 5 )
                    value = String( value ).concat("0000");

                if( String( value ).length == 9 ){
                    var dataFormatter:SwitchSymbolFormatter = 
                        new SwitchSymbolFormatter();
                    return dataFormatter.formatValue( formatString, value );
                }
                else {
                    error="Invalid String Length";
                    return ""
                    }
                }

            // If the formatString is anything other than '#####*####, 
            // call super and validate and format as usual using 
            // the base ZipCodeFormatter.
            return super.format(value);
        }
    }   
}

Notice that the ExtendedZipCodeFormatter class did not have to define a formatString property because it is already defined in its base class, ZipCodeFormatter.

The following example uses this custom formatter in an application:

<?xml version="1.0" encoding="UTF-8"?>
<!-- formatters/FormatterZC.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:MyComp="myFormatters.*"> 

    <!-- Declare a formatter and specify formatting properties. -->
    <MyComp:ExtendedZipCodeFormatter id="ZipCodeFormat"/>

    <!-- Trigger the formatter while populating a string with data. -->
    <mx:TextInput width="220" 
        text="Your zipcode number is {ZipCodeFormat.format('123456789')}"/> 

</mx:Application>

The executing SWF file for the previous example is shown below: