3.5.2.4.2. Formatter
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 acom.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>
By default, DateFormatter
displays the date and time in the server timezone. To show the current user’s timezone, set true
for the useUserTimezone
attribute of the formatter.
If a formatter is implemented as an internal class, it should be declared with a
|
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 Function<BigDecimal, String> {
@Override
public String apply(BigDecimal bigDecimal) {
return NumberFormat.getCurrencyInstance(Locale.getDefault()).format(bigDecimal);
}
}
@Inject
private GroupTable<Order> ordersTable;
@Subscribe
public void onInit(InitEvent event) {
Function currencyFormatter = new CurrencyFormatter();
ordersTable.getColumn("totalPrice").setFormatter(currencyFormatter);
}