Preface – This post is part of the UI5 Programs series.
Table of Contents
What is a formatter in UI5?
A formatter in UI5 is a model that is created to store functions. Each function is used to format the data into a specific format. Generally, it is used to perform the following:
- Format Data to a specific type (dd/mm/yyyy or something else)
- Convert values from single character [‘X’, ”] to [Yes, No]
- Convert values from single characters to icons
- Format timestamp and time (DD.MM.YYYY:HH:MM:SS)
- Format Decimal (from 3 decimals to 2 decimals)
- Remove Decimal Zero (All zeroes after Decimal)
- Remove leading zeroes from the number
Guidelines for using formatter
Formatter is treated just like another function and thus has the same guidelines that are followed by other functions:
- A formatter should always return something back
- A formatter should have preconditions to fail-safe the formating
- A formatter should not return invalid data that can dump the View binding
- A formatter should use i18n for all its hard-coded texts
- A formatter should be placed in the Model folder with the name “formatter.js”
- A formatter should have comments before every function determining the input parameters and output data information
A blank formatter looks something like this:
sap.ui.define([], function() { "use strict"; return { // All your formatted functions like below /** * Returns Timestamp * @public * @param {string} sValue the number string to be timestamp formatted * @returns {string} sValue in DD-MM-YYYY: HH:MM:SS */ timestampUnit: function(sValue) { if (!sValue) { return ""; } var timestamp = new Date(sValue.seconds * 1000); return timestamp; }, }; });
Making formatter Global to the Entire App
To make your formatter Global to the entire app, you need to add it to the BaseController.js file. This will make it accessible to all other pages.
Adding formatter in Controller
To add a formatter to a controller file, you need to add it in the definition part and then make the field formatter global. The code is as below:
sap.ui.define([ "sap/ui/core/mvc/Controller", "YRR/YRR/model/formatter", ], function (Controller, formatter, ) { "use strict"; return BaseController.extend("YRR.YRR.controller.Main", { formatter: formatter, onInit: function () { } }); });
In the above code, you can see we defined the formatter and specified the exact location. And then, just above the onInit function, we have reassigned it to a global field.
Using formatter in Controller
Formatter functions are just like other functions and can be called or initiated with ‘this’ keywords.
this.formatter.getLocalTime(<pass your field here>)
In the above statement, this.formatter will call the formatter file. getLocalTime is the name of the function. <pass your fields here> is the placeholder for all the fields that your function ‘getLocalTime’ requires.
Using formatter in View
Passing one value in formatter
To pass a single value in formatter, we replace the text binding with formatter binding, as shown below:
<Text text="{ path : 'LineItem', formatter: '.formatter.removeZero' }"/>
In the above code, the path is the field name that is used for binding. And the formatter has the name of the formatter file followed by the function name.
Passing multiple values in formatter
<Text text="{ parts : [{path: 'OrdQty'},{path: 'QtyConversion'}], formatter: '.formatter.calculateMultiply' }"/>
In the above code, we have passed multiple values into our formatter using the object ‘parts’ which itself has multiple objects in the form of {path: ‘<field name>’}
Examples of Formatter
1. Get Local Time
getLocalTime: function(sValue) { if (sValue) { var dateString = sValue; var year = +dateString.substring(0, 4); var month = +dateString.substring(4, 6); var day = +dateString.substring(6, 8); var date = new Date(year, month - 1, day); var months = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; var todate = date.getDate(); var tomonth = date.getMonth(); var monthText = months[tomonth]; var toyear = date.getFullYear(); if (month < 10 && month > 0) { month = '0' + month.toString(); } if (todate < 10 && todate > 0) { todate = '0' + todate.toString(); } var original_date = todate + '.' + month + '.' + toyear; if (original_date == '30.0.1899') { return ''; } else { return original_date; } } else { return ""; } }
2. Remove Leading Zeros
removeZero: function(sValue) { if (sValue) { sValue = sValue.replace(/^0+/, ''); return sValue; } else { return ''; } }
3. Remove Decimal Zeros
removedecimalZero: function(sValue) { if (sValue) { sValue = parseInt(sValue); sValue = sValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); if (sValue == '0') { return '0'; } else { return sValue; } } else { return '0'; } }
4. Format Decimal Numbers
formatDecimal: function(sValue) { if (sValue) { if (sValue == '0.000') { return ''; } else { sValue = parseFloat(sValue).toFixed(2); return sValue; } } else { return ''; } }
5. Format Custom Icons
customIcon: function(sValue) { if (sValue === "X") { return 'sap-icon://message-success'; } else { return ''; } }
6. Formatting Currency
This formatting is for adding commas ‘,’ as per currency type, and adding currency signs with numbers.
currency: function(sValue) { if (sValue) { // Create our number formatter. var formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'SAR' }); return (formatter.format(sValue)); /* $2,500.00 */ } else { return ''; } },
7. Rounding a Number
roundNum: function(sValue) { if (sValue) { sValue = parseFloat(sValue).toFixed(2); sValue = Math.round(sValue); sValue = sValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); return sValue; } else { return ''; } },
0 Comments