PROMO AGOSTO en CVOSOFT United States Of America: 💎Calidad, 🔥Bonificaciones, 🥶Precios Congelados y MÁS!

 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

🎓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

✒️+Comunidad Académica CVOSOFT

Continúe aprendiendo sobre el tema "El formateo de los campos" de la mano de nuestros alumnos.

SAP Senior

El formateo de los campos en SAPUI5 En SAPUI5, el formateo de campos es una práctica esencial para presentar datos de manera legible y comprensible en la interfaz de usuario. Se puede lograr mediante la aplicación de formateadores en las vistas XML o en funciones específicas en el controlador. En las vistas XML, las expresiones de enlace (binding) junto con formateadores permiten ajustar la apariencia de los datos directamente en la definición de la vista. Por ejemplo, puedes formatear un valor monetario para que se muestre con el formato correcto, como separadores de miles y decimales. Por otro lado, en el controlador, puedes realizar el formateo antes de asignar valores a los controles de la vista. Esto proporciona...

Acceder a esta publicación

Creado y Compartido por: Claudio Marcelo Hermann / Disponibilidad Laboral: FullTime

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

los formateadores son tecnicas que se utilizan para modificar el modo en que se presentan los datos del modelo en UI. El enlace de un modelo se puede mostrar en diferentes formatos en la interfaz usuario los formateadores son funciones javaScript especificadas en las vistas SAPUI5 Se recomienda tener los archivos formateadores en la carpeta model, dentro del formateador se usa el sap.ui.define para definir lo que devolvemos El enlace de Expresion las tecnicas de enlace de expresion nos permiten escribir logica simple dentro de la vista en si misma si necesidad de formateadoroes escribir funciones de formateador puede ser una sobrecarga para casos simples y en su lugar se puede usar el enlace de expresion

Acceder a esta publicación

Creado y Compartido por: Detriana Barrios / Disponibilidad Laboral: FullTime + Carta Presentación

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

formateadores de datos formatter vistas ABAP CDS expuestas como OData fecha flotante moneda booleano new Date showMeasure el enlace de expresión escape parts clase de formateador standard uso de formateadores en la vista ${products>UnitInStock} > 50 ? 'Success' : 'Error' showMeasure para mostrar la moneda

Acceder a esta publicación

Creado y Compartido por: Enrique Gomez

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Expert


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,...

Acceder a esta publicación

Creado y Compartido por: Jaime Eduardo Gomez Arango / Disponibilidad Laboral: FullTime + Carta Presentación

 


 

👌Genial!, estos fueron los últimos artículos sobre más de 79.000 publicaciones académicas abiertas, libres y gratuitas compartidas con la comunidad, para acceder a ellas le dejamos el enlace a CVOPEN ACADEMY.

Buscador de Publicaciones:

 


 

No sea Juan... Solo podrá llegar alto si realiza su formación con los mejores!