I’m : a web and mobile developer based in the Manning Valley, Australia.

Extending Adobe Flex Formatters

Adobe Flex 3 has a few inbuilt formatters such as NumberFormatter and CurrencyFormatter. As part of the AdvancedDataGrid that I was building some of the source data (in JSON) had cost values of "n/a" when there was no cost and this had to be shown on screen. The original code was as follows:

<mx:AdvancedDataGridColumn dataField="Cost" headerText="Cost" textAlign="right">
    <mx:CurrencyFormatter currencySymbol="£" useNegativeSign="true" precision="2" />

If the CurrencyFormatter encounters any input that is not numeric, or cannot be converted to a number, it returns back an empty string. Not what I wanted at all and there seemed to be no way to force it to return the original value. A bit of googling turned up this blog post by Rae. Using that I put together this:

    import mx.formatters.CurrencyFormatter;

    public class MyCurrencyFormatter extends CurrencyFormatter
        public var retainStrings:Boolean = false;

        override public function format(value:Object):String
            if (retainStrings && super.format(value) == '') {
                return value as String;

            return super.format(value);

which in use looks something like this:

<mx:AdvancedDataGridColumn dataField="Cost" headerText="Cost" textAlign="right">
            <mx:VBox clipContent="false">
                    precision="2" />
                <mx:Label width="100%" text="{test.format( data['Cost'] ) }" />

Ideally I'd have liked to have something that did not require an item renderer by even according to the Adobe documentation on creating a custom formatter it seems that you have to use the renderers. I'll carry on searching incase something more appropriate shows up but for the time being this works well.