Custom/Additional Javascript Functions can be defined inside a Javascript Control in the workbench. This can then be called from different execution points within the project. A function from a script created in a page can be called and executed from different pages. For example, defining a function and assigning it in the onLoad property of a Page or calling a script inside an Input Control when the value changes.
Inside the Javascript Editor, a set of Useful Functions is provided to further assist the developer.
A classic and advanced Javascript editors are available. By default the classic editor is activated and it can be switched to the advanced editor by going to the menu bar and selecting Settings--->Options-→Advanced Javascript Editor
Description | Sample |
---|---|
Prevent Refreshing Table Control | function init(){ |
Trigger action on select record in a table | oTable.attachSelect(function(evt){ function tableRowSelected(evt){ jQuery.sap.require("sap.m.MessageBox"); if(oResult.Result=="CC Exists"){ |
Set Max Length in an Input field | getControl("VendorNameId").setProperty("maxLength",40); |
Call oData from script | initModel("searchhelps","/sap/opu/odata/sap/ZFAB_TS_SERVICESN"); |
Bind Visibility Property | getControl("ApproverErrorId").getParent().bindProperty("visible","ApproverError"); |
Validate Email address - Input Field | validate email address function validateEmail(evt) { //Reference: https://emailregex.com/ var rexEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var lv_input = evt.getParameters().newValue; var validEmail = false; if (!lv_input.match(rexEmail)) { setControlState(evt.getSource().getId(), "Error", "'" + lv_input + "' is not a valid email address", true); } else { setControlState(evt.getSource().getId(), "None", "", false); validEmail = true; } setField("validEmail", validEmail); } |
Validate Phone number - Input field | function validatePhoneNumber(evt) { //Reference: https://digitalfortress.tech/tricks/top-15-commonly-used-regex/ var rexPhone = /^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/; var lv_input = evt.getParameters().newValue; var validPhone = false; if (!lv_input.match(rexPhone)) { setControlState(evt.getSource().getId(), "Error", "'" + lv_input + "' is not a valid phone number", true); } else { validPhone = true; setControlState(evt.getSource().getId(), "None", "", false); } setField("validPhone", validPhone); } |
Calling *SAP Search Help using JavaScript |
initModel("searchhelps","/sap/opu/odata/iqx/SERVICES_SRV"); var oPath = "/GenSearchHelp"; |
Scroll to an element in a page | getControl("ReviewAndSubmit").scrollToElement(getControl("1Employeeid")); "ReviewAndSubmit" is the page ID and "1Employeeid" is the element ID within the page |
Highlight fields in the table | //Add style var oTableData = getControl("dataTable"); for(var i in length){ var oRow = oTableData.getItems()[i]; controlPosition = 1; //Position of the field in the column oControl = oRow.getCells()[controlPosition]; oControl.addStyleClass("myErrorState"); } //Remove Style controlPosition = 1; //Position of the field in the column oControl = oRow.getCells()[controlPosition]; oControl.removeStyleClass("myErrorState"); |
Enable wrapping of label | Add in CSS: .sapMLabel { |
ABN Validation (Australia) | var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10, d11, tot, rem, ok; var str = '51 824 753 556'; var replaced = str.split(' ').join(''); str = replaced; d1 = str.substr(0,1); parseInt(d1); if ( d1 > 0 ) { d1 = d1 - 1; } d1 = d1 * 10; d2 = str.substr(1,1) * 1; d3 = str.substr(2,1) * 3; d4 = str.substr(3,1) * 5; d5 = str.substr(4,1) * 7; d6 = str.substr(5,1) * 9; d7 = str.substr(6,1) * 11; d8 = str.substr(7,1) * 13; d9 = str.substr(8,1) * 15; d10 = str.substr(9,1) * 17; d11 = str.substr(10,1) * 19; tot = d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + d9 + d10 + d11; rem = tot % 89; if ( rem === 0 ) { ok = 'true'; }else { ok = 'false'; } var d1,d2,d3,d4,d5,d6,d7,d8,d9,d10, d11, tot, rem, ok; var str = '51 824 753 556'; var replaced = str.split(' ').join(''); str = replaced; d1 = str.substr(0,1); parseInt(d1); if ( d1 > 0 ) { d1 = d1 - 1; } d1 = d1 * 10; d2 = str.substr(1,1) * 1; d3 = str.substr(2,1) * 3; d4 = str.substr(3,1) * 5; d5 = str.substr(4,1) * 7; d6 = str.substr(5,1) * 9; d7 = str.substr(6,1) * 11; d8 = str.substr(7,1) * 13; d9 = str.substr(8,1) * 15; d10 = str.substr(9,1) * 17; d11 = str.substr(10,1) * 19; tot = d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + d9 + d10 + d11; rem = tot % 89; if ( rem === 0 ) { ok = 'true'; }else { ok = 'false'; } |
Add custom headers in page | function onLoad() { var oPage = getControl("Page2"); } |
Reading parameters from the URL | Sample URL var UserReference = jQuery.sap.getUriParameters().get("UserReference"); |
Hide Back button on Review and Submit page | if (getField("CurrentStatus" == STATUS) { getControl("_view1–_navButton").setVisible(false); } |
Dynamically load 3rd party external lib from external | This helps loading external 3rd JS library when it is not available in FAB try { dateFns.isToday(new Date()); } catch (err) { new Promise(function (fnResolve, fnReject) { jQuery.sap.includeScript( "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js", "date_fns", fnResolve, fnReject); }).then(function () { console.log("date_fns js loaded!!!") }); } Since SAPUI5 version 1.58 onward, jQuery.sap.includeScript is deprecated, hence use the following instead: //Load function includeScript from module sap/ui/dom/includeScript var includeScript = sap.ui.require("sap/ui/dom/includeScript"); try { dateFns.isToday(new Date()); } catch (err) { new Promise(function(fnResolve, fnReject) { includeScript( "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js", "datefns_js", fnResolve, fnReject); }).then(function() { console.log("datefns_js is loaded!!!") }); } In case FAB form having Chart Container, should load external JS libs using requireJS: //declare for global variable of imported function; var dateFns; var Mustache; let loadLibPromise; //if requireJS is loaded. if (('require' in window)) { loadLibPromise = new Promise(function(resolve, reject) { requirejs.config({ paths: { "mustache_js": "https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.1/mustache.min", "date_fns": "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min" } }); resolve(); }); } else { //Otherwise, load requireJS and carry on. loadLibPromise = new Promise(function(resolve, reject) { sap.ui.require(["sap/ui/thirdparty/require"], function() { requirejs.config({ paths: { "mustache_js": "https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.1/mustache.min", "date_fns": "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min" } }); resolve(); }); }); } loadLibPromise.then(require(["mustache_js", "date_fns"], function(returnedFns1, returnedFns2) { console.log("mustache_js is loaded!") //assign loaded lib to global variable. Mustache = returnedFns1; dateFns = returnedFns2; })); |
Get all the model data fields | Call the inbuilt function fabGetData() to fetch all the model data fields. var getData = fabGetData(); |
Ternary Operator | Accepts 3 operands and acts as a shortcut to IF statements https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator |
Get the current page | var currentPage = _fab.byId("_app").getCurrentPage().getId() var currentPage = _fab.byId("_app").getCurrentPage().getId() You can compare it with getControl("YourPageName").getId() to check if its the same page you are doing validations on. |
Change the code while debugging to test | Add a line of code in the first script you use with the syntax //# sourceURL=some_name.js Eg: //# sourceURL=journal_upload.js This would open the journal_upload.js in runtime instead of the temporary application and enables the developer to change code on the fly to check while debugging. NOTE: This line of code has to be deleted before it is moved to production, as it gives a developer the ability to change code in the run-time. |