😎 Semana del Amigo 2x1 en CVOSOFT🤓 ¡IM-PER-DI BLE!

 X 

✒️SAP Fiori El formateo de los campos

SAP Fiori El formateo de los campos

SAP Fiori El formateo de los campos

1 | Working with Expressions and Data Formatters

When we link a property from a model to an SAPUI5 control, we might need to format the incoming data to display it differently on the screen.

Data formatting can include date and number formatting. These techniques allow us to link values (e.g., amount and currency) or display a completely different dataset based on predefined data.

For instance, in an SAPUI5 application, data is typically consumed from an SAP system. These transactional applications provide a refreshed look along with standard or customized functionality and can rewrite data back to the SAP system.

Hence, the OData services used in the application are created in NetWeaver with SAP ABAP as the main programming language. Similarly, ABAP CDS views can be exposed directly as OData and consumed in the application.

However, sometimes we need to display data differently from how the OData service returns it.

2 | Formatting Using Data Types

SAPUI5 provides four data types (date, float, currency, and boolean) to influence data formatting on a screen.

For example, a date property can be formatted to display as MM/DD/YYYY, and a currency value can be formatted to include a thousand separator.

Here is how we can format a date field in a view to display in the MM/dd/yyyy format:

value="{path:'/DoB', type: 'sap.ui.model.type.Date', formatOptions: { pattern: 'MM/dd/yyyy' }}"

Similarly, we can format a price property to show the currency and thousand separator by setting showMeasure to true:

value="{path:'/Price', type: 'sap.ui.model.type.Currency', formatOptions: { showMeasure: true }}"

3 | Custom Formatting

Formatters are techniques used to modify how model data is represented in the UI. The binding of a model can be displayed in different formats on the user interface.

Formatters are JavaScript functions specified in SAPUI5 views alongside the binding and implemented either in a controller or in a dedicated formatter JavaScript file to store all formatter functions. It is recommended to keep formatter files in the model folder and use sap.ui.define to define the returned values. We can have multiple functions in the file for different formatting tasks.

Consider a simple use case of using a formatter function to calculate age from the birth date:

  • Create a JS file for formatting.
  • Declare it in the view controller using sap.ui.define.
  • Access the formatter from the UI using the path to the model value and the formatter property with the method to execute.

// Formatter.js

sap.ui.define([], function() {
return {
calculateAge: function(birthDate) {
var ageDifMs = Date.now() - new Date(birthDate).getTime();
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
};
});

In the view controller:

sap.ui.define([
"sap/ui/core/mvc/Controller",
"path/to/Formatter"
], function(Controller, Formatter) {
"use strict";
return Controller.extend("namespace.controller.ViewName", {
formatter: Formatter,
onInit: function() {
// Initialization code
}
});
});

In the view:

<Text text="{ path: 'birthDate', formatter: '.formatter.calculateAge' }"/>

4 | Expression Binding

Expression binding allows writing simple logic directly in the view without needing formatters. For simple cases, writing formatter functions can be an overhead, and expression binding can be used instead.

Consider an example where you want to display different icons based on whether a person is a senior citizen:

<Icon src="{= ${age} >= 60 ? 'sap-icon://person-placeholder' : 'sap-icon://employee' }"/>

We can form complex expressions using binary logical operators, arithmetic operators, comparison operators, regular expressions (regex), etc. Refer to the SAPUI5 demo kit for comprehensive information.

In an XML view, an expression is written using the syntax {= expression }. The symbol $ is used to refer to a bound variable. For example:

<Text text="{= ${price} > 100 ? 'Expensive' : 'Affordable' }"/>

5 | Using Two Models in a View and Data Formatting

In scenarios where we need to format data using multiple models, we can create two JSON models: one for storing the currency type and another for the amounts.

In the manifest.json file, reference the JSON model as follows:

{
"sap.ui5": {
"models": {
"currency": {
"type": "sap.ui.model.json.JSONModel",
"uri": "path/to/currencyModel.json"
}
}
}
}

In the view controller, declare a JSON model in the init method and associate it with the view using setModel:

onInit: function() {
var oCurrencyModel = new sap.ui.model.json.JSONModel("path/to/currencyModel.json");
this.getView().setModel(oCurrencyModel, "currency");
}

In the view, use a special binding syntax for the number property of ObjectListItem:

<ObjectListItem
number="{ parts: [ {path: 'currency>/value'}, {path: 'price'} ],
formatter: '.formatter.combineCurrencyAndPrice' }"/>

This binding syntax uses "calculated fields," allowing multiple properties from different models to be bound to a single control property.

If we set showMeasure to false, we can hide the currency, which defaults to true:

<ObjectListItem number="{ path: 'price', type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false } }"/>

We can add an expression to validate a field and set an error state based on the field value:

<ObjectListItem numberState="{= ${unitsInStock} < 0 ? 'Error' : 'Success' }"/>


 

 

 


Sobre el autor

Publicación académica de Jaime Eduardo Gomez Arango, en su ámbito de estudios para la Carrera Consultor en SAP Fiori.

SAP Expert


Jaime Eduardo Gomez Arango

Profesión: Ingeniero de Sistemas y Computación - España - Legajo: SW34C

✒️Autor de: 149 Publicaciones Académicas

🎓Cursando Actualmente: Consultor en SAP Fiori

🎓Egresado de los módulos:

Disponibilidad Laboral: FullTime

Presentación:

Ingeniero de sistemas y computación con 8 años de experiencia el desarrollo frontend & backend (react/node) y en cloud (aws), actualmente desarrollando habilidades en sap btp, ui5, abap y fiori.

Certificación Académica de Jaime Gomez