Implementing and Using Formatter Functions

Objective

After completing this lesson, you will be able to implement and use formatter functions to convert model data into an external format.

Creating Formatter Functions

SAPUI5 provides two different options to convert model data to an external format for visual representation: data types and formatter functions.

While data types provide the possibility to format, parse and validate data, formatter functions allow one-way conversion only.

A formatter function has a single parameter, which is the value which needs to be formatted to an external representation.

A formatter function can be used not only to format a value, but also to do type conversion or calculate results from a given value.

Note

When using formatter functions, the binding is automatically switched to "one-way". So you can’t use a formatter function for "two-way" scenarios.

Formatter functions can be defined in a separate module or locally in a view controller.

Note

It is recommended to use a separate module file that groups the formatters and makes them globally available in the application.
Sample formatter.js code, as described in the following text.

The coding example in the figure Defining a Formatter Function shows the definition of a formatter function called classText. It is created in a separate module that is implemented in the formatter.js file. The classText formatter translates keys used in the model data into texts that are understandable to the user. For example, for the key value "Y", the text "Economy Class" is returned.

Using Formatter Functions

Sample code highlighting the formatter function, as described in the following text.

The figure, Using a Formatter Function, shows how a formatter function defined in a separate module can be used in an XML view.

To do this, it must first be ensured that the module containing the formatter function is loaded. This is achieved by requiring the formatter module by its module name in the <mvc:View> tag, as shown in the figure.

The loaded module is assigned to the alias formatter. The name of this alias is arbitrary, the crucial thing is that the alias can be used as a variable in the binding.

To specify the formatter function in the binding, the complex binding syntax is used. The model property to be formatted is specified via the path property, and the formatter function is assigned to the formatter property via the following syntax:

XML
1
<alias of the formatter module>.<name of the formatter function>.

So in the example, the content of the Class model property is passed to the classText formatter function . The string returned by this formatter function is then displayed on the UI via the Text control.

Note

In addition to custom formatter functions, you can also use predefined formatter functions for standard use cases, such as sap/base/strings/formatMessage.