4.5.2.3.1. Formatter
Warning

Formatter should be used with read-only components, such as Label, Table column and similar. Editable components values, for example, TextField, should be formatted using the Datatype mechanism.

In an XML-descriptor of a screen, a component’s formatter can be defined in a nested formatter element. The element has a single attribute:

  • class − the name of a class implementing a com.haulmont.cuba.gui.components.Formatter

If formatter’s constructor class has a org.dom4j.Element, parameter, then it will receive an XML element, describing this formatter. This can be used to parameterize a formatter instance. For example, using a formatted string. Particularly, DateFormatter and NumberFormatter classes in the platform can take the format string from the format attribute. Example of using the component:

<column id="date">
    <formatter class="com.haulmont.cuba.gui.components.formatters.DateFormatter" format="yyyy-MM-dd HH:mm:ss"/>
</column>

Additionally, DateFormatter class also recognizes a type attribute, which can have a DATE or DATETIME value. In this case, formatting is done using the Datatype mechanism using a dateFormat or a dateTimeFormat string respectively. For example:

<column id="endDate">
    <formatter class="com.haulmont.cuba.gui.components.formatters.DateFormatter" type="DATE"/>
</column>
Tip

If a formatter is implemented as an internal class, it should be declared with a static modifier and its name should be separated by "$" for loading, for example:

<formatter class="com.sample.sales.gui.OrderBrowse$CurrencyFormatter"/>

Formatter can be assigned to a component not only using a screen XML-descriptor , but also programmatically – by submitting a formatter instance into a setFormatter() component.

An example of declaring a custom formatter and using it to format values in a table column:

public class CurrencyFormatter implements Formatter<BigDecimal> {

    protected GeneralConfiguration generalConfiguration;
    protected Currency currentCurrency;

    public CurrencyFormatter(GeneralConfiguration generalConfiguration) {
        this.generalConfiguration = generalConfiguration;
        currentCurrency = generalConfiguration.getCurrency();
    }

    @Override
    public String format(BigDecimal value) {
        return currentCurrency.format(value);
    }
}
protected void initTableColumns() {
    Formatter<BigDecimal> currencyFormatter = new CurrencyFormatter(generalConfiguration);
    table.getColumn("totalPrice").setFormatter(currencyFormatter);
}