SAP How-to Guide User Interface
SAPUI5 Tutorial
Applicable Releases:
SAPUI5 v1.28 and higher
Version 1.0
July 2015
Data Binding in SAPUI5
Copyright 2015 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in any form
or for any purpose without the express permission of SAP AG. The
information contained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors
contain proprietary software components of other software vendors.
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered
trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p,
System p5, System x, System z, System z10, System z9, z10, z9, iSeries,
pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390,
OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power
Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER,
OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS,
HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex,
MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and
Informix are trademarks or registered trademarks of IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other
countries.
Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either
trademarks or registered trademarks of Adobe Systems Incorporated in
the United States and/or other countries.
Oracle is a registered trademark of Oracle Corporation.
UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open
Group.
Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame,
and MultiWin are trademarks or registered trademarks of Citrix Systems,
Inc.
HTML, XML, XHTML and W3C are trademarks or registered trademarks
of W3C, World Wide Web Consortium, Massachusetts Institute of
Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used
under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP
BusinessObjects Explorer, StreamWork, and other SAP products and
services mentioned herein as well as their respective logos are
trademarks or registered trademarks of SAP AG in Germany and other
countries.
Business Objects and the Business Objects logo, BusinessObjects,
Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other
Business Objects products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of Business
Objects Software Ltd. Business Objects is an SAP company.
Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere,
and other Sybase products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of Sybase, Inc.
Sybase is an SAP company.
All other product and service names mentioned are the trademarks of
their respective companies. Data contained in this document serves
informational purposes only. National product specifications may vary.
The information in this document is proprietary to SAP. No part of this
document may be reproduced, copied, or transmitted in any form or for
any purpose without the express prior written permission of SAP AG.
This document is a preliminary version and not subject to your license
agreement or any other agreement with SAP. This document contains
only intended strategies, developments, and functionalities of the SAP
product and is not intended to be binding upon SAP to any particular
course of business, product strategy, and/or development. Please note
that this document is subject to change and may be changed by SAP at
any time without notice.
SAP assumes no responsibility for errors or omissions in this document.
SAP does not warrant the accuracy or completeness of the information,
text, graphics, links, or other items contained within this material. This
document is provided without a warranty of any kind, either express or
implied, including but not limited to the implied warranties of
merchantability, fitness for a particular purpose, or non-infringement.
SAP shall have no liability for damages of any kind including without
limitation direct, special, indirect, or consequential damages that may
result from the use of these materials. This limitation shall not apply in
cases of intent or gross negligence.
The statutory liability for personal injury and defective products is not
affected. SAP has no control over the information that you may access
through the use of hot links contained in these materials and does not
endorse your use of third-party Web pages nor provide any warranty
whatsoever relating to third-party Web pages.
SAP How-to Guides are intended to simplify the product implement-
tation. While specific product features and procedures typically are
explained in a practical business context, it is not implied that those
features and procedures are the only approach in solving a specific
business problem using SAP NetWeaver. Should you wish to receive
additional information, clarification or support, please refer to SAP
Consulting.
Any software coding and/or code lines / strings (Code) included in this
documentation are only examples and are not intended to be used in a
productive system environment. The Code is only intended better explain
and visualize the syntax and phrasing rules of certain coding. SAP does
not warrant the correctness and completeness of the Code given herein,
and SAP shall not be liable for errors or damages caused by the usage of
the Code, except if such damages were caused by SAP intentionally or
grossly negligent.
Disclaimer
Some components of this product are based on Java. Any code change
in these components may cause unpredictable and severe malfunctions
and is therefore expressively prohibited, as is any decompilation of these
components.
Any Java Source Code delivered with this product is only to be used by
SAPs Support Services and may not be modified or altered in any way.
Document History
Document Version Description
1.00 First official release of this guide
Typographic Conventions
Type Style Description
Example Text Words or characters quoted
from the screen. These
include field names, screen
titles, pushbuttons labels,
menu names, menu paths,
and menu options.
Cross-references to other
documentation
Example text Emphasized words or
phrases in body text, graphic
titles, and table titles
Example text File and directory names and
their paths, messages,
names of variables and
parameters, source text, and
names of installation,
upgrade and database tools.
Example text User entry texts. These are
words or characters that you
enter in the system exactly as
they appear in the
documentation.
Variable user entry. Angle
brackets indicate that you
replace these words and
characters with appropriate
entries to make entries in the
system.
EXAMPLE TEXT Keys on the keyboard, for
example, F2 or ENTER.
Icons
Icon Description
Caution
Note or Important
Example
Recommendation or Tip
Table of Contents
Step 1: No Data Binding ...................................................................................................... 5
1.1. Preview .................................................................................................................... 5
1.2. ./index.html (New file) ............................................................................................... 6
Step 2: Creating a Model Object ......................................................................................... 7
2.1. Preview .................................................................................................................... 7
2.2. ./index.html ............................................................................................................... 8
Warning! ................................................................................................................... 8
Step 3: Making Model Object Data Available on the User Interface .................................. 9
3.1. Preview .................................................................................................................... 9
3.2. ./index.html ............................................................................................................... 9
3.3. Explanation ............................................................................................................. 10
Important ................................................................................................................ 10
Step 4: Two-Way Data Binding ......................................................................................... 11
4.1. Preview .................................................................................................................. 11
4.2. ./views/App.view.xml (New file in new folder)........................................................... 12
4.3. ./index.html ............................................................................................................. 12
4.4. Behaviour ............................................................................................................... 13
Explanation ............................................................................................................. 13
Important ................................................................................................................ 14
Step 5: One-way Data Binding .......................................................................................... 16
5.1. Preview .................................................................................................................. 16
5.2. ./index.html ............................................................................................................. 16
5.3. Data Binding With Other Model Types..................................................................... 17
5.4. Background ............................................................................................................ 17
Important! ............................................................................................................... 17
Step 6: Resource Models .................................................................................................. 18
6.1. Preview .................................................................................................................. 18
6.2. ./index.html ............................................................................................................. 19
6.3. ./i18n/i18n.properties (New file in new folder) .......................................................... 20
6.4. ./views/App.view.xml ............................................................................................... 20
Important ................................................................................................................ 20
Explanation ............................................................................................................. 21
Step 7: (Optional) Resource Bundles and Multiple Languages ...................................... 22
7.1. Preview .................................................................................................................. 22
7.2. ./i18n/i18n_de.properties (New file) ......................................................................... 22
7.3. Behaviour ............................................................................................................... 22
Be Careful With Language Determination!............................................................... 23
Step 8: Binding Paths Accessing Properties in Hierarchically Structured Models ..... 24
8.1. Preview .................................................................................................................. 24
8.2. ./index.html ............................................................................................................. 25
8.3. ./views/App.view.xml ............................................................................................... 25
8.4. ./i18n/i18n.properties .............................................................................................. 26
8.5. ./i18n/i18n_de.properties (Optional) ........................................................................ 26
Explanation ............................................................................................................. 26
Step 9: Formatting Model Property Values ...................................................................... 27
9.1. Preview .................................................................................................................. 27
9.2. ./controllers/App.controller.js (New file in new folder) ............................................... 28
Coding Style ........................................................................................................... 29
9.3. ./views/App.view.xml ............................................................................................... 30
9.4. ./i18n/i18n.properties .............................................................................................. 30
9.5. ./i18n/i18n_de.properties (Optional) ........................................................................ 31
Error Behaviour....................................................................................................... 31
Step 10: Improving the Application Structure.................................................................... 32
10.1. Preview .................................................................................................................. 32
10.2. ./index.html ............................................................................................................. 33
10.3. ./models/model.json (New file in new folder) ............................................................ 33
10.4. ./controllers/formatter.js........................................................................................... 34
10.5. ./controllers/App.controller.js ................................................................................... 35
10.6. ./views/App.view.xml ............................................................................................... 36
Error Behaviour....................................................................................................... 37
Step 11: Property Formatting Using Data Types ............................................................... 38
11.1. Preview .................................................................................................................. 38
11.2. ./models/model.json ................................................................................................ 39
11.3. ./views/App.view.xml ............................................................................................... 39
11.4. ./controllers/formatter.js........................................................................................... 40
11.5. ./i18n/i18n.properties .............................................................................................. 40
11.6. ./i18n/i18n_de.properties (Optional) ........................................................................ 40
Explanation and Warning ........................................................................................ 41
Currency Symbols are Locale Specific .................................................................... 41
The Browser's Locale May Not Be The Application Language ................................. 41
Behaviour ............................................................................................................... 42
Step 12: Validation Using the Message Manager............................................................... 43
12.1. Preview .................................................................................................................. 43
12.2. ./index.html ............................................................................................................. 44
Explanation ............................................................................................................. 44
Behaviour ............................................................................................................... 44
Step 13: Element Binding ................................................................................................... 45
13.1. Preview .................................................................................................................. 45
13.2. ./views/App.view.xml ............................................................................................... 46
13.3. ./models/model.json ................................................................................................ 46
13.4. ./controllers/formatter.js........................................................................................... 47
13.5. ./i18n/i18n.properties .............................................................................................. 48
13.6. ./i18n/i18n_de.properties......................................................................................... 48
Explanation ............................................................................................................. 48
Step 14: Expression Binding .............................................................................................. 50
14.1. Preview .................................................................................................................. 50
14.2. ./views/App.view.xml ............................................................................................... 51
14.3. ./models/model.json ................................................................................................ 51
Warning! ................................................................................................................. 52
Understanding Syntax Collisions ............................................................................. 52
Step 15: Aggregation Binding Using A Template .............................................................. 53
15.1. Preview .................................................................................................................. 53
15.2. ./views/App.view.xml ............................................................................................... 54
15.3. ./controllers/App.controller.js ................................................................................... 55
15.4. ./controllers/formatter.js........................................................................................... 55
15.5. ./i18n/i18n.properties .............................................................................................. 56
15.6. ./i18n/i18n_de.properties (Optional) ........................................................................ 56
15.7. ./models/Products.json (New file) ............................................................................ 57
Step 16: Aggregation Binding Using A Factory Function ................................................. 61
16.1. Preview .................................................................................................................. 61
16.2. ./views/App.view.xml ............................................................................................... 62
16.3. ./i18n/i18n.properties .............................................................................................. 63
16.4. ./i18n/i18n_de.properties (Optional) ........................................................................ 63
16.5. ./controllers/App.controller.js ................................................................................... 63
SAPUI5 Tutorial Data Binding
July 2015 1
Introduction In this tutorial, we will explain the concepts of data binding in SAPUI5.
Data binding is a declarative programming technique in which the properties of a Model-View-
Controller (MVC) Model are associated with (or bound to) the properties of UI elements in an MVC
View.
The use of data binding follows as a consequence of the SAPUI5's use of the MVC design pattern,
and within the context of this development framework, is the standard programming technique for
presenting model-based information on the screen.
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 2
Prerequisites and Preparation This tutorial assumes you have access to the SAP Web IDE: either by having an SAP HANA trial
account, or by having a customer account. If you have neither of these, then you can create a trial
account for free by visiting https://account.hanatrial.ondemand.com/
You have already completed the SAPUI5 Walkthrough tutorial currently available as a Beta version.
Initial Preparation for Tutorial Steps Under Local in your SAP Web IDE session, create a new folder called DataBinding.
Right-click on the new DataBinding folder and select New Cloud Connectivity Configuration.
This will create a file called neo-app.json. You do not need to edit the contents of this file, but
without it, your SAP Web IDE project will not be able to access the SAPUI5 libraries.
SAP Web IDE may also automatically create several other files such as .project.json,
.user.project.json and .sap-ui-cachebuster-info.json.
Do not edit or delete these files!
Testing the Developments Performed in each Tutorial Steps Once you have added the required coding for a tutorial step, select index.html file under the
DataBinding folder and press the Run button in the toolbar. This will start the Application
Preview in a new tab and you will be able to see your changes immediately.
If you do not see the expected changes in the application preview tab, then this is either because you
have not saved your changes, or some old information about the application is still in your browser's
cache. If browser caching becomes an issue with App Preview, simply open a private browsing
window to ensure you start from an empty cache.
Alternatively, if you see an empty or partially rendered screen, you should open your browser's
development tools to look in the JavaScript console for error message(s).
It is helpful to leave the Application Preview tab open. Then when you have completed the next step
of the tutorial, make sure that all your changes have been saved, and simply refresh the Application
Preview to see the changes.
SAPUI5 Tutorial Data Binding
July 2015 3
Increasing the Level of Logging Detail The normal approach to switching on SAPUI5 debug mode is to press Ctrl+Alt+Shift+P in the browser
window or tab that is running the SAPUI5 application.
This key combination brings up an information window in which you can check the "Use Debug
Sources" checkbox. This causes the app to restart in debugging mode.
However, if you find that this key combination does not work then it is probably because the error in
your coding has caused the SAPUI5 core to terminate and consequently, there is no SAPUI5 coding
running anymore to respond to the Ctrl+Alt+Shift+P keyboard event.
Therefore, under these circumstances and only under these circumstances, you can switch on
debug mode programmatically.
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 4
Warning!
This approach is only recommended in circumstances where the bug
in your coding causes the SAPUI5 core to terminate!
The reason is that since the following statements cause your app to run permanently in debug mode, it
is easy to forget that you've got this statement in your coding. This can potentially result in apps being
deployed to the production server with debug mode permanently switched on!
If you end up deploying an app to production that is hard-coded to run in debug mode then:
a) Don't come crying to SAP about it,
b) Examine why such an app passed unnoticed through your QA testing procedure, and
c) Consider why you think it necessary to have the SAPUI5 debug sources deployed on your
production server
In circumstances where your coding does not cause the SAPUI5 core to terminate, you should switch
on debug mode using the Ctrl+Alt+Shift+P approach because this activates debug mode only
temporarily. Only if this fails should you use the following code:
SAPUI5 Data Binding Tutorial // Set log level to maximum and explicitly switch on the debug flag jQuery.sap.log.setLevel(jQuery.sap.log.LogLevel["DEBUG"]); jQuery.sap.debug(true); // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { ...SNIP...
First, by adding dbg into the SAPUI5 core library name, the browser will directly load the debug
version of the SAPUI5 core library. On its own however, this is not quite sufficient to get SAPUI5 to
run in debug mode; we must also explicitly set the jQuery.sap.debug flag to true.
This tutorial assumes that if you want to switch on debug mode, you will do so temporarily using the
Ctrl+Alt+Shift+P approach.
tarunjHighlight
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 5
Tutorial Steps
Step 1: No Data Binding This exercise simply places some text on the screen using a standard sap.m.Text control.
The text displayed by this control is a hard coded part of the control's definition; therefore, this is not
an example of data binding!
1.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 6
1.2. ./index.html (New file) Under the DataBinding folder, create an index.html file and within it place the following code:
SAPUI5 Data Binding Tutorial // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { // Create a text UI element that displays a hardcoded text string new sap.m.Text({ text : "Hi, my name is Harry Hawk" }). addStyleClass("sapUiSmallMargin"). placeAt("content"); });
Since the value of text property of the sap.m.Text control has been hard-coded, it is unrelated to
any data that might exist within a model object. Therefore, this is an example of how data binding is
not used!
SAPUI5 Tutorial Data Binding
July 2015 7
Step 2: Creating a Model Object A model object is a container for the data upon which your application operates. The business data
within a model can be defined using various formats:
JavaScript Object Notation (JSON)
Extensible Markup Language (XML)
OData (covered in another tutorial)
Your own custom format (not covered in this tutorial)
There is also a special type of model object called a "Resource Model". This model type is used as a
wrapper object around a resource bundle file. The names of such files must end with ".properties"
and are used typically for holding language specific text.
When JSON, XML and Resource Models are created, all the data they contain is entirely loaded in a
single request (typically by requesting it from a web server). In other words, after the model's data has
been requested, the entire model is known to the SAPUI5 application. These models are known as
client-side models because once created, their data lives entirely within the client-side JavaScript
coding. Tasks such as filtering and sorting can be performed locally on the client.
An OData model however, is a server-side model. This means that whenever a SAPUI5 application
needs data from such a model, it must be requested on demand. Such a request will almost never
return all the data in the model, typically because this would be far more data than is required by the
client application. Consequently, tasks such as sorting and filtering should always be delegated to the
server.
In this tutorial, we will focus on JSON models since they do not require the presence of a backend
business system.
2.1. Preview
Although there is no visual difference between this screen shot and the previous one, the greeting text
has now been derived from a model object, rather than being hard-coded into the UI control's
definition.
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 8
2.2. ./index.html ...SNIP... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { // Create a new JSON model object var oModel = new sap.ui.model.json.JSONModel({ greetingText : "Hi, my name is Harry Hawk" }); // Assign the model object to the SAPUI5 core sap.ui.getCore().setModel(oModel); // Display a text element whose text is derived from the model object new sap.m.Text({ text : "{/greetingText}" }). addStyleClass("sapUiSmallMargin"). placeAt("content"); }); ...SNIP...
Inside the anonymous function passed to sap.ui.getCore().attachInit(), we perform two extra
tasks:
1. Create a new JSON model using a JSON literal object and store the resulting model object in
a local variable called oModel.
2. Set oModel to be the default model object within the entire SAPUI5 core.
In this example, the JSON model object has been bound to the core of SAPUI5 framework without
giving it a specific name. This action has two immediate consequences:
1. It makes the model object globally available to all other parts of the SAPUI5 application.
2. The call to the setModel function was made using only one parameter.
By omitting the second parameter to the setModel function, we have created an unnamed
model that automatically becomes the default model object for the whole of the SAPUI5 core.
Consequently, when we want to refer to any of the properties within this model, we can simply
state the path to the property name, without stating to which model the property belongs.
Next, the text property of the sap.m.Text UI control is set to the value "{/greetingText}". The curly
brackets enclosing some path name are known as the data binding syntax. In this case, we are
stating the UI control's text property will have its value derived from a property called greetingText in
the default model.
Warning! Normally, you would never hardcode a model object within your coding. Instead the data would typically be obtained from some backend business system.
In this case we have bound the model object to the SAPUI5 core. This has been done for simplicity, but is not considered good practice. Generally speaking, a model object holding business data is bound only to the view that displays the data. We will correct this situation later on in the tutorial.
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 9
Step 3: Making Model Object Data Available on the User Interface
Although there is no visible difference, the text on the screen is now derived from a mixture of sources.
3.1. Preview
3.2. ./index.html The line of code with the strikethrough should be deleted!
...SNIP... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { // Create a new JSON model object var oModel = new sap.ui.model.json.JSONModel({ greetingText : "Hi, my name is Harry Hawk" firstName : "Harry", lastName : "Hawk" }); // Assign the model object to the SAPUI5 core sap.ui.getCore().setModel(oModel); new sap.m.Text({ text : "Hi, my name is {/firstName} {/lastName}" }). addStyleClass("sapUiSmallMargin"). placeAt("content"); }); ...SNIP...
Notice now that the value of the sap.m.Text UI control's text property is composed from both model
data and static text.
SAPUI5 Tutorial Data Binding
July 2015 10
3.3. Explanation First, we created a JSON model object using the following code:
However, once created, the data in a model object is not yet of any use to UI Controls. Therefore, we
must perform a second step that makes the data in a model object accessible to UI controls. This
process is known as "data binding" and it handles the automatic transport of data between the model
object and the properties of UI Controls.
Therefore, the second line of code shown below is needed. The creation of a data binding instance
makes the data in a model object accessible to UI controls.
The data binding model instance provides UI Controls with a common interface to all model objects
irrespective of their underlying implementation type (JSON, XML, OData etc.)
The diagram above shows the simple case of a model having a single data binding instance; however,
it is possible for one model object to have multiple data binding instances.
Now that we have a means of transporting data between a model object and UI controls, we are able
to combine the data from the model with data derived from other sources; for instance, hardcoded into
the UI control's definition.
Important
For simplicity, we have set the model to the SAPUI5 core without specifying a name for the model
binding instance. This has two specific consequences:
1. By omitting a name parameter for the model binding instance, this particular model becomes
the default model. When subsequently accessing the properties in this model, there is no
need to identify the model explicitly.
2. The data in the default model is accessible by all other coding running within this instance of
the SAPUI5 core.
Generally speaking, you should not use the default model object within the SAPUI5 core for holding
business data. Instead, you should confine access to model data to only those units of coding that
actually need it.
Later on in this tutorial, we will correct this situation.
tarunjHighlight
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 11
Step 4: Two-Way Data Binding In the examples used so far, we have used a read-only field to display the value of a model property.
We will now change the user interface so that firstly, the first and last name fields are open for input
using sap.m.Input fields, and secondly, an additional check box control is used to enable or disable
both of these input fields.
This arrangement illustrates a feature known as "two-way data binding".
4.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 12
4.2. ./views/App.view.xml (New file in new folder) Now that the view needs to contain more UI controls, we will move the view definition out of the
index.html file and into an XML file.
Under the DataBinding folder, create a new folder called views. Within the new views folder, create
a file called App.view.xml. Paste in the following code:
This XML view will be identified by its resource name sap.ui.demo.db.view.App.
4.3. ./index.html The lines of code with the strikethrough should be deleted!
...SNIP... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { var oModel = new sap.ui.model.json.JSONModel({ firstName : "Harry", lastName : "Hawk", enabled : true, panelHeaderText : "Data Binding Basics" }); // Assign the model object to the SAPUI5 core sap.ui.getCore().setModel(oModel); // Display a text element whose text is derived // from the model object new sap.m.Text({ text : "Hi, my name is {/firstName} {/lastName}" }). addStyleClass("sapUiSmallMargin"). placeAt("content"); // Display the XML view called "App" new sap.ui.core.mvc.XMLView({ viewName : "sap.ui.demo.db.views.App" }). placeAt("content"); }); ...SNIP...
SAPUI5 Tutorial Data Binding
July 2015 13
The previous coding to assign a sap.m.Text field to the UI has been deleted, as it is no longer
needed.
The SAPUI5 bootstrap has a new parameter called data-sap-ui-resourceroots. This is where we
can associate a Java-style namespace with an actual directory in the file system. Although JavaScript
does not have any direct concept of namespaces, SAPUI5 treats the resource id in the same way that
the Java class loader identifies files by their Java namespace.
Once this association has been made, files can be identified by their resource name, rather than a
path name. In this case, we want all resources located in the same directory as index.html ("./") to be
identified by the namespace "sap.ui.demo.db".
Now, when the XML view is created, we can identify the file using the namespace
"sap.ui.demo.db.views.App". The "sap.ui.demo.db" part of the name is translated into "./", then
after that, the dots are translated into slashes to form a relative path name:
"sap.ui.demo.db.views.App" ./views/App.view.xml
Since we are explicitly creating an XML view, the file name given simply as "App" can be assumed to
end with ".view.xml".
4.4. Behaviour Refresh your Application Preview tab and switch the checkbox on and off. You will see that the input
fields are automatically enabled or disabled in response to the state of the checkbox.
It is clear that we have not written any coding to transfer data between the user interface and the
model, yet the Input UI Controls are enabled or disabled according to the state of the checkbox.
This behaviour is the result of the fact that all SAPUI5 models (except a Resource Model) implement
two-way data binding, and for JSON Models, two-data binding is the default behaviour.
Explanation
Three things are happening here:
1. Data binding allows the property of a UI control to derive its value from any suitable property in
a model object.
2. The purpose of a Data Binding Instance is to create an API that makes all model objects look
the same irrespective of how they have been implemented internally.
3. SAPUI5 automatically handles the transport of data both from the model to the UI control(s),
and back from the UI control(s) the model. This is called two-way data binding.
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 14
Important By default, the data binding mode (one-way or two-way) is a feature of the Model object, and is
unrelated to whether the bound UI Control property permits user input or not. Therefore, in the
diagram below, the use of single- or double-headed arrows indicates nothing more than the direction
of data flow between the model and the specific UI control.
Since a sap.m.Label control is read-only, in practice, data will only flow from the model to the control;
however, since a user can change the state of a sap.m.CheckBox control or a sap.m.Input control,
double-headed arrows are used to indicate that data entered by the user flows in both directions
between the model and the UI.
For simplicity, the following diagram shows only the data binding for the "Last name" label and input
field.
JSON Model
Data Binding
Model Instance
sap.m.Panel
sap.m.Label
text:%"Last%Name"
sap.m.Input
value:%"{/lastName}"enabled:%"{/enabled}"
sap.m.CheckBox
selected:%"{/enabled}"
SAPUI5 Tutorial Data Binding
July 2015 15
If you now switch off the sap.m.CheckBox control, two-way data binding ensures that the model is
updated. Then, by virtue of the fact that both of the sap.m.Input controls are bound to the model's
enabled property, these UI controls are immediately disabled.
JSON Model
Data Binding
Model Instance
sap.m.Panel
sap.m.Label
text:%"Last%Name"
sap.m.Input
value:%"{/lastName}"enabled:%"{/enabled}"
sap.m.CheckBox
selected:%"{/enabled}"
SAPUI5 Tutorial Data Binding
July 2015 16
Step 5: One-way Data Binding In contrast to the two-way data binding behaviour shown above, one-way data binding is also
possible. Here, data is transported in one direction only: from the model, through the data binding
instance to the consumer (usually the property of a UI control), but never in the other direction.
In this example, we will change the previous example to use one-way data binding. This will then
illustrate how the flow of data from the user interface back to the model can be switched off if required.
5.1. Preview
5.2. ./index.html Insert the single highlighted line immediately after the creation of the model object in index.html.
...SNIP... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { var oModel = new sap.ui.model.json.JSONModel({ firstName : "Harry", lastName : "Hawk", enabled : true, panelHeaderText : "Data Binding Basics" }); oModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneWay); // Assign the model object to the SAPUI5 core sap.ui.getCore().setModel(oModel); ...SNIP...
SAPUI5 Tutorial Data Binding
July 2015 17
Now, no matter what state the checkbox is in, the input fields remain open for input because one-way
data binding ensures that data flows only from the model to the UI, but never back again.
5.3. Data Binding With Other Model Types JSON and XML models use two-way data binding as their default behaviour (or binding mode).
However, by default, OData and Resource models use one-way data binding as the default.
Due to the fact that Resource models are designed to deliver static, language specific text to the user
interface, one-way data binding is the only possible behaviour for this model type.
OData models also support two-way data binding, but since an OData model is a server-side model
and not a client-side model, any change to the model data requires a server round trip before that
update can be considered complete. Therefore, two-way data binding for OData models must be
switched as required.
5.4. Background The data binding mode (one-way or two-way) is a property of the model object itself. Therefore,
unless you specifically alter it, a data binding model instance will always be created using the model
object's default data binding mode.
Should you wish to alter the data binding mode, then there are two particular ways of doing this:
1. Alter the model's default data binding mode. This is the approach used above.
2. Alter the data binding mode at the time the data binding instance is created. This change
applies only to the data binding instance being created. Any other data binding instances
created at a later point in time will continue to use the model object's default data binding
mode.
Important!
There are two important points to understand about alterations to a model object's data binding mode:
1. If you alter the default data binding mode of a model object (as in the example above), then
unless you explicitly say otherwise, all data binding instances created after that point in time
will use the altered data binding mode.
2. Altering a model object's default data binding mode has no effect on existing data binding
model instances. In other words, the alteration of a model object's data binding mode does
not alter the JavaScript prototype upon which the model object is defined.
tarunjHighlight
tarunjHighlight
tarunjHighlight
SAPUI5 Tutorial Data Binding
July 2015 18
Step 6: Resource Models As was mentioned in "Creating a Model Object" above, model objects can be defined in various
different formats such as JSON, XML or OData. These model formats are most often used to hold
either:
The data needed in order to do business (master data)
The data generated as a result of doing business (transactional data)
However, business applications also require a third type of data; namely, the language specific
(translatable) texts used as labels and descriptions on the user interface.
The example we used at the start of this tutorial was overly simplistic in that we stored language
specific text directly in a JSON model object. Generally speaking, unless language specific text is
derived directly from a backend system, then it is not good practice to place translatable text directly
into a model object.
So let's correct this situation by placing all translatable text (such as field labels) into a resource
bundle.
6.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 19
6.2. ./index.html ... SNIP ... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { var oModel = new sap.ui.model.json.JSONModel({ firstName : "Harry", lastName : "Hawk", enabled : true, panelHeaderText : "Data Binding Basics" }); oModel.setDefaultBindingMode(sap.ui.model.BindingMode.OneWay); // Assign the model object to the SAPUI5 core sap.ui.getCore().setModel(oModel); // Create a resource bundle for language specific texts var oResourceBundle = new sap.ui.model.resource.ResourceModel({ bundleName : "sap.ui.demo.db.i18n" }); // Assign the model object to the SAPUI5 core using the name "i18n" sap.ui.getCore().setModel(oResourceBundle, "i18n"); // Display the XML view called "App" new sap.ui.core.mvc.XMLView({ viewName : "sap.ui.demo.db.views.App" }). placeAt("content"); }); ...SNIP...
In the same way that the path to the XML view can be derived using the fully qualified namespace
"sap.ui.demo.db.views.App", so the path to the i18n file can be derived from the namespace
"sap.ui.demo.i18n.i18n".
Since we are creating a resource model, the file name is assumed to have the extension
".properties"; therefore this does not need to be stated.
The resource model is then attached to the SAPUI5 core using the model name "i18n".
SAPUI5 Tutorial Data Binding
July 2015 20
6.3. ./i18n/i18n.properties (New file in new folder) Within your DataBinding folder, create a new folder called i18n.
Within the new i18n folder, create a New file called i18n.properties and paste into it the following
text:
# Field labels firstName=First Name lastName=Last Name enabled=Enabled # Screen titles panelHeaderText=Data Binding Basics
The panelHeaderText property has been moved from the model object into the i18n resource
bundle, and also the field labels are no longer hard coded in the XML View. This is because all of
these text fields need to be translated.
Language specific text is stored in Resource Models and is formatted according to the Java
convention for resource bundle files.
6.4. ./views/App.view.xml
Modify the data binding for the panel header and the labels in App.view.xml to include the model
name. Notice that a "greater than" character separates the model name and the property name, and
that i18n property names must not start with a slash character!
Important
All binding paths are case-sensitive!
SAPUI5 Tutorial Data Binding
July 2015 21
Explanation
The diagram seen above in Step 0 can now be extended to include the Resource Model. For
simplicity, only the data binding for one Label UI Control is shown.
JSON Model
Data Binding
Model Instance
sap.m.Panel
sap.m.Label
text:%"{i18n>lastName}"
sap.m.Input
value:%"{/lastName}"enabled:%"{/enabled}"
sap.m.CheckBox
selected:%"{/enabled}"
Resource
Model
Data Binding
Model Instance
i18n
i18n.properties
SAPUI5 Tutorial Data Binding
July 2015 22
Step 7: (Optional) Resource Bundles and Multiple Languages
The reason we have resource bundles is to allow an app to run in multiple languages without the need
to change any coding. To demonstrate this feature, we will create a German version of the above app
in fact all we need to do is create a German version of the resource bundle file. No coding changes
are needed.
7.1. Preview
7.2. ./i18n/i18n_de.properties (New file) In the i18n folder, take a copy of the file i18n.properties and call it i18n_de.properties. Change
the English text to the following German text.
# Field labels firstName=Vorname lastName=Nachname enabled=Aktiviert # Screen titles panelHeaderText=Data Binding Grundlagen
7.3. Behaviour If it is not set already, change the default language of your browser to German. Now press refresh in
the Application Preview screen and the German text will be used automatically.
This works because SAPUI5 takes into account the language setting of your browser when calculating
which resource bundle file to open.
Assuming that your browser has been configured to use "Queen's English" (that is, en-GB, the English
spoken in England), then SAPUI5 will make an HTTP request for exactly this resource bundle.
SAPUI5 Tutorial Data Binding
July 2015 23
However, if the request returns an HTTP 404 (File not found), then SAPUI5 requests a less specific
version of the resource bundle.
The following search order is used:
1. Request an exact match of both language and region i18n_en_GB.properties
2. Request the exact language, but ignore the region i18n_en.properties
3. Request the default (non-language specific) resource bundle i18n.properties
Since English is the default language for most business applications, it is typical for the non-language
specific resource bundle i18n.properties to contain English text.
When you've finished this step, don't forget to change your browser back to its normal default
language!
Be Careful With Language Determination!
In this code sample, we have assumed that the language information defined in the browser can be
used to determine the language in which the particular business application should be run.
This assumption might prove to be false!
Particularly in multi-national organisations, it is common to find users that have their browser set to
their own local language (say French), but actually run all SAP business applications in the corporate
standard language (typically English). Therefore, the determination of the application language cannot
necessarily be determined from the browser's default language setting.
In a real world (I.E. complex) business scenario however, the language in which a business
application should run is usually determined by a process similar to the following:
1. Most corporations implement a single sign-on policy. Therefore, before a business application can be started, the user must have first been authenticated by an identity provider such as the
corporate LDAP.
2. Once authenticated, the identity provider will typically supply the client with user credentials. This information should include the business application language.
3. The browser's default language setting can then be ignored when determining the language in which the SAPUI5 app should be run.
Since this tutorial focuses on data binding, it is beyond the scope of this document to deal with such
issues in any further detail.
SAPUI5 Tutorial Data Binding
July 2015 24
Step 8: Binding Paths Accessing Properties in Hierarchically Structured Models
In Resource Models, we stated that the fields in a Resource Model are arranged in a flat structure; in
other words, there can be no hierarchy of properties; however, this is true only for Resource Models.
The properties within JSON and OData models almost always are arranged in a hierarchical structure.
Therefore, we should take a look at how to reference fields in a hierarchically structured model object.
8.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 25
8.2. ./index.html ... SNIP ... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { var oModel = new sap.ui.model.json.JSONModel({ firstName : "Harry", lastName : "Hawk", enabled : true, dateOfBirth : { day : 3, month : 8, year : 1987 } }); ... SNIP ...
The JSON model object now contains an additional sub-object called dateOfBirth. Within this object
are three properties: day, month and year.
8.3. ./views/App.view.xml
A new panel has been added to the XML view in which a new and pair of elements
have been created.
The element's text property is bound to the i18n Resource Bundle field dateOfBirth.
The element's text property is bound to three i18n properties: /dateOfBirth/day,
/dateOfBirth/month and /dateOfBirth/year.
The resulting date format is achieved by separating each one of these model property references with
a hard-coded slash character.
SAPUI5 Tutorial Data Binding
July 2015 26
8.4. ./i18n/i18n.properties # Field labels firstName=First Name lastName=Last Name enabled=Enabled dateOfBirth=Date of Birth # Screen titles panel1HeaderText=Data Binding Basics panel2HeaderText=Formatting
8.5. ./i18n/i18n_de.properties (Optional) # Field labels firstName=Vorname lastName=Nachname enabled=Aktiviert dateOfBirth=Geburtsdatum # Screen titles panel1HeaderText=Data Binding Grundlagen panel2HeaderText=Formatieren
The resource bundle files now contain new properties for the dateOfBirth and the panel header text
properties have been numbered.
Explanation In the XML view, inside the curly brackets for the element's binding path, notice that the first
character is a forward slash. This is required for binding paths that make absolute references to
properties in JSON models, but must not be used for Resource Models.
After the first forward slash character, the binding path syntax uses the object name(s) and the
property name separated by forward slash characters.
{/dateOfBirth/day}
As has been mentioned previously, all binding path names are case-sensitive.
SAPUI5 Tutorial Data Binding
July 2015 27
Step 9: Formatting Model Property Values The coding shown in the previous step is not very satisfactory for two reasons:
1. The day and month parts have not been formatted correctly (missing a leading zero)
2. The date is displayed using the hardcoded British and European format of DD/MM/YYYY
which may not be appropriate either for your business requirements or your country.
So in this step we will look at how model property values can be programmatically formatted according
to the requirements of your locale.
9.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 28
9.2. ./controllers/App.controller.js (New file in new folder) Within the DataBinding folder, create a new folder called controllers.
Within the new controllers folder, create a New file called App.controller.js and paste in the
following code:
sap.ui.define(["sap/ui/core/mvc/Controller"], function(Controller) { "use strict"; // ------------------------------------------------------------------------- var dateFormatter = function(pDay,pMonth,pYear,pInvalidDate) { // The Date function will validate the parameters for us, so there is no // need for defensive coding here. If any of the parameters to the Date // function are invalid, the Date function will return the string // "Invalid Date" var dt = new Date(pYear, pMonth - 1, pDay); // If the Date function evaluates to "Invalid Date", then return the // resource bundle text received in parameter pInvalidDate, else return // the date formatted according to the current locale return (dt.toString() === "Invalid Date") ? pInvalidDate : dt.toLocaleDateString(); }; // ------------------------------------------------------------------------- return Controller.extend("sap.ui.demo.db.controllers.App", { dateFormatter : dateFormatter }); });
We have created a new folder called controllers as a general location for all controller files used by
this app. At the moment, we have only one controller called App.controller.js; but in general, you
can have as many controllers as are appropriate for your application.
All SAPUI5 controllers have a standard structure, and are created by calling the sap.ui.define
function. This function is passed two parameters:
An array of object references
An anonymous function
The number and order of object references in the first array must match the number and order of
parameters to the anonymous function.
sap.ui.define then invokes the anonymous function passing in instances of however many objects
have been referenced in the first array. sap.ui.define then returns either:
A simple object containing your own custom methods
Or, an instance of the standard SAPUI5 controller that has been extended with whatever extra
functions you wish to add.
In our case, we have extended the standard controller with a single function called dateFormatter.
SAPUI5 Tutorial Data Binding
July 2015 29
Coding Style The dateFormatter function has been declared as a variable within the scope of the anonymous
function, and then App.controller.js returns an extended Controller object that references this
variable. This coding style is deliberate.
In the code sample shown below, an alternative structure is used. Here the dateFormatter function
is declared within scope of the object returned by the controller.
sap.ui.define(["sap/ui/core/mvc/Controller"], function(Controller) { "use strict"; // ------------------------------------------------------------------------- return Controller.extend("sap.ui.demo.db.controllers.App", { dateFormatter : function(...) { ... SNIP ... } }); });
Superficially, this appears to be a simpler (and therefore preferable) structure; however, you will
experience two distinct limitations. Any function defined within the scope of the returned object:
1. Must be very careful when using the JavaScript self reference this because it will be resolved
within the scope of the calling function and not within the scope of this controller.
Consequently, the meaning of this will vary depending on who is consuming the controller.
2. Will not be able to reference the other functions defined within the returned object.
Therefore, the dateFormatter function is declared as a variable within the scope of the anonymous
function and is referenced by the returned object. This means that this (and any other) function exists
within a closure created when the anonymous function terminates.
As we develop the coding within App.controller.js, we will be able both to create and share private
variables within the closure, but also the individual functions returned by this controller will be able to
reference each other.
Notice also the following things about the way in which the dateFormatter function has been coded:
1. Since JavaScript's built-in Date function validates the day, month or year parameters, there is
no need to write any defensive code to validate these parameters.
2. The month value must have 1 subtracted from it because (assuming it's a valid month)
JavaScript months are numbered from zero, not one.
SAPUI5 Tutorial Data Binding
July 2015 30
3. If any of the parameters turn out to invalid, the value returned by JavaScript's built-in Date
function will evaluate to "Invalid Date". In this case we return the language specific text
received in parameter pInvalidDate.
4. If, on the other hand, we were passed valid parameters, then a date string is returned in the
format of the current locale.
9.3. ./views/App.view.xml
The root XML element now has an extra property called controllerName. The value of this property
is a reference to the JavaScript controller we have just created. Without this reference, there would be
no relationship between the view and the controller and consequently, the UI control would not
be able to reference the dateFormatter function.
The text property of the element is now an entire object instead of a simple string value. In
this case, the object has two properties:
parts This is a JavaScript array in which each element is an object containing at least a path
property. The number and order of the elements in this array corresponds directly to the
number and order of parameters expected by the dateFormatter function.
formatter A reference to the function that receives the parameters listed in the parts array.
Whatever value is returned by the formatter function becomes the value displayed on
the screen.
9.4. ./i18n/i18n.properties ...SNIP... # Screen titles panel1HeaderText=Data Binding Basics panel2HeaderText=Formatting # Error messages invalidDate=Invalid Date Format
SAPUI5 Tutorial Data Binding
July 2015 31
9.5. ./i18n/i18n_de.properties (Optional) ...SNIP... # Screen titles panel1HeaderText=Data Binding Grundlagen panel2HeaderText=Formatieren # Error messages invalidDate=Ungltiges Datumsformat
Error Behaviour Now change the value of one of the dateOfBirth properties in the JSON model to a value you know
to be invalid. For instance:
dateOfBirth : { day : 3, month : "Octember", year : 1987 }
Save your changes and refresh the browser.
You will now see the invalid date format message.
When you've finished this test, don't forget to change the invalid date value back to a valid one!
SAPUI5 Tutorial Data Binding
July 2015 32
Step 10: Improving the Application Structure There are several issues with our little demo app that should be corrected before developing it any
further:
1. All the model objects are created within the index.html file.
2. Since the model objects have been set against the SAPUI5 core, they are globally available to
all applications running within this instance of the SAPUI5 framework.
In the case of a simple app such as the one in this tutorial, this is not an issue; however, in the
case of apps running within the Fiori Launchpad (FLP), the FLP acts as the parent container
within which all the available apps run. Under these circumstances, any model set against the
SAPUI5 core would be visible to both the FLP container and all the contained Fiori apps.
Therefore, in order to maintain the correct level of data separation between business apps, we
will confine the model object's visibility to the one view that consumes the data.
3. In a real-life app, you are likely to need multiple formatter functions and since the same
formatter will often be needed across multiple views, we create a single formatter JavaScript
file and place the dateFormatter function within it.
4. The number of parameters to the dateFormatter function can be reduced.
We need to adopt a better architecture because this will make the code cleaner and much easier to
understand during the maintenance phase.
10.1. Preview
The following changes have no visible effect on the user interface.
SAPUI5 Tutorial Data Binding
July 2015 33
10.2. ./index.html ... SNIP ... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { var oModel = new sap.ui.model.json.JSONModel({ firstName : "Harry", lastName : "Hawk", enabled : true, dateOfBirth : { day : 3, month : 8, year : 1987 } }); sap.ui.getCore().setModel(oModel); var oResourceBundle = new sap.ui.model.resource.ResourceModel({ bundleName : "sap.ui.demo.db.i18n" }); this.getCore().setModel(oResourceBundle, "i18n"); // Display the XML view called "App" new sap.ui.core.mvc.XMLView({ viewName : "sap.ui.demo.db.views.App" }). placeAt("content"); }); ... SNIP ...
Since we already have a controller associated with the XML view, the functionality to create model
objects no longer needs to be in the index.html file. From now on, the coding in index.html will do
nothing more than create an XML view and then inject it into the DOM.
10.3. ./models/model.json (New file in new folder) The data contained within the model object is now moved into a separate file.
Within the DataBinding folder, create a new folder called models.
Within the new models folder, create a New file called model.json and paste in the following code:
{ "firstName" : "Harry", "lastName" : "Hawk", "enabled" : true, "dateOfBirth" : { "day" : 3, "month" : 8, "year" : 1987 } }
SAPUI5 Tutorial Data Binding
July 2015 34
10.4. ./controllers/formatter.js sap.ui.define([], function() { "use strict"; // ------------------------------------------------------------------------- var dateFormatter = function(pDoB,pInvalidDate) { var oDoB = pDoB || {}; // The Date function will validate the parameters for us, so we can arbitrarily // create a new date without needing to do any parameter validation ourselves var dt = new Date(oDoB.year, oDoB.month - 1, oDoB.day); // If the Date function evaluates to "Invalid Date", then return the // resource bundle text received in parameter pInvalidDate, else return // the date formatted according to the current locale return (dt.toString() === "Invalid Date") ? pInvalidDate : dt.toLocaleDateString(); }; // ------------------------------------------------------------------------- return { dateFormatter : dateFormatter }; });
The dateFormatter function is moved into its own JavaScript file.
Instead of passing the individual day, month and year parameters to the dateFormatter function, we
now pass in the entire dateOfBirth object from which the formatter then extracts the required
properties.
This coding in this file is very similar to the coding of the SAPUI5 controller App.controller.js,
except for the following differences:
1. The first parameter to sap.ui.define is an empty array.
2. Consequently, the anonymous function passed as the second parameter receives no
parameters.
3. The object returned by the anonymous function is just a simple JavaScript object containing a
reference to the dateFormatter function, rather than an extension to a standard SAPUI5
controller.
4. Since the formatter.js file does not return an extended SAPUI5 controller, the file name
ends simply with .js and not .controller.js.
The subsequent steps of this tutorial will add further formatter functions to this file.
SAPUI5 Tutorial Data Binding
July 2015 35
10.5. ./controllers/App.controller.js sap.ui.define(["sap/ui/core/mvc/Controller", "sap/ui/demo/db/controllers/formatter"], function(Controller,Formatter) { "use strict"; // ---------------------------------------------------------------------- var initialise = function() { var oModel = new sap.ui.model.json.JSONModel(); oModel.loadData("./models/model.json"); this.getView().setModel(oModel); var oResourceBundle = new sap.ui.model.resource.ResourceModel({ bundleName : "sap.ui.demo.db.i18n.i18n" }); // Assign the resource model to the current view using the name "i18n" this.getView().setModel(oResourceBundle, "i18n"); }; // ------------------------------------------------------------------------- var dateFormatter = function(pDay,pMonth,pYear,pInvalidDate) { // The Date function will validate the parameters for us, so there is no // need for defensive coding here. If any of the parameters to the Date // function are invalid, the Date function will return the string // "Invalid Date" var dt = new Date(pYear, pMonth - 1, pDay); // If the Date function evaluates to "Invalid Date", then return the // resource bundle text received in parameter pInvalidDate, else return // the date formatted according to the current locale return (dt.toString() === "Invalid Date") ? pInvalidDate : dt.toLocaleDateString(); }; // ------------------------------------------------------------------------- return Controller.extend("sap.ui.demo.db.controllers.App", { onInit : initialise, formatter : Formatter dateFormatter : dateFormatter }); });
The coding to create the models has been moved from index.html into a function called
initialise. Then, in order to have this function called automatically, it is assigned to the controller's
onInit function. The SAPUI5 framework then ensures that function onInit is called at the start of
the controller's lifecycle.
Also, since we know that in the future, we will be using multiple formatter functions, we can simply
return a property called formatter that gives access to all the functions in the Formatter JavaScript
file. This will save us from having to update App.controller.js each time a new formatter is
created.
SAPUI5 Tutorial Data Binding
July 2015 36
10.6. ./views/App.view.xml
Since all the formatter functions are returned from App.controller.js via a single object called
formatter, the reference to the dateFormatter function must be modified to include this prefix.
SAPUI5 Tutorial Data Binding
July 2015 37
Error Behaviour As we did in the previous step, change one of the day, month or year values of dateOfBirth in the
file model.json to be a character string instead on an integer.
For instance:
"dateOfBirth" : { "day" : 3, "month" : "Septober", "year" : 1987 }
Again, once this test is complete, don't forget to correct the date value in the model object.
SAPUI5 Tutorial Data Binding
July 2015 38
Step 11: Property Formatting Using Data Types SAPUI5 provides a set of simple data types such as Boolean, Currency, Date and Float. These data
types can then be applied to UI controls in order to ensure firstly that the value presented on the
screen is formatted correctly, and secondly, if the field is open for input that the value entered by the
user conforms to the requirements of that data type.
We will now add a new field called "Sales to Date" and declare it to be of type "Currency".
11.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 39
11.2. ./models/model.json { "firstName" : "Harry", "lastName" : "Hawk", "enabled" : true, "dateOfBirth" : { "day" : 3, "month" : 8, "year" : 1987 }, "salesToDate" : 12345.6789, "currencyCode" : "EUR" }
Two new model properties are created called salesToDate and currencyCode.
11.3. ./views/App.view.xml ... SNIP ...
A new pair or and elements have been created for the salesToDate model
property.
The description property of the element has been bound to the currencyCode model
property and also assigned the getCurrencyCode formatter function. The purpose of the formatter
function is to calculate the correct currency symbol based on the combination of the currency code
and the current locale.
The value property of the element has been bound to the model properties salesToDate and
currencyCode. The {showMeasure: false} parameter switches off the display of the currency
symbol within the input field itself. This is not needed because it is being displayed using the
element's description property.
SAPUI5 Tutorial Data Binding
July 2015 40
11.4. ./controllers/formatter.js sap.ui.define([], function() { "use strict"; // Based on the language and region supplied from the browser, create a // Locale object from which a LocaleData object can then be created. // // * * * Warning * * * // It may not be safe to assume that you can determine the business // application's language based on the browser's default language. // // It is entirely possible that a user might have their browser set to // their native language (say French), but then perform all business // transactions in their company's business language (say English). // // In a real business scenario, the value held in variable sBrowserLocale // would typically be replaced with the application language supplied by // software such as your corporate identity provider or active directory // server. var sBrowserLocale = sap.ui.getCore().getConfiguration().getLanguage(); var oLocale = new sap.ui.core.Locale(sBrowserLocale); var oLocaleData = new sap.ui.core.LocaleData(oLocale); // ------------------------------------------------------------------------- var getCurrencySymbol = function(pCurrCode) { // Return the correct currency symbol for the given currency code as seen // from the perspective of the current locale. // If the currency code is not supplied, then default to Euros return oLocaleData.getCurrencySymbol(pCurrCode || "EUR"); }; ...SNIP... // ------------------------------------------------------------------------- return { dateFormatter : dateFormatter, getCurrencySymbol : getCurrencySymbol }; });
11.5. ./i18n/i18n.properties # Field labels firstName=Vorname lastName=Nachname enabled=Enabled dateOfBirth=Date of Birth salesToDate=Sales to Date ...SNIP...
11.6. ./i18n/i18n_de.properties (Optional) # Field labels firstName=Vorname lastName=Nachname enabled=Aktiviert dateOfBirth=Geburtsdatum salesToDate=Verkufe bis zum heutigen Datum ...SNIP...
SAPUI5 Tutorial Data Binding
July 2015 41
Explanation and Warning Please resist the temptation to hardcode currency symbol characters such as "", or "$" or "" into a
model object!
Also, you must definitely not place currency symbol characters into the i18n resource bundle
because this will break the formatter function!
The value displayed in a currency field is a composite value built from a currency value and a currency
symbol. If you then place a currency symbol into an i18n file, you create a conflict based on the
different data binding modes being used:
1. All JSON models use two-way data binding
2. All resource models use one-way data binding.
Therefore, if you create a currency field in which one part of the data (the currency value) is derived
from a model using two-way data binding and the other part of the data (the currency code) is derived
from model using one-way data binding, then the overall data binding for both values will be
downgraded to the lowest common binding method which is one-way data binding.
Consequently, if such a field is open for input, the one-way data binding will not only prevent the
currency value entered by the user from being written back to the model object, but it will also mean
that the formatter function will only be able to run once when the screen is first rendered.
Currency Symbols are Locale Specific
Apart from the technical reasons described above, there is a more important reason for not
hardcoding currency symbols. This is because certain countries have currencies that share the same
currency symbol and possibly even the same currency name, but are otherwise completely
independent currencies.
For instance, the currencies of Canada, Mexico and the US all use the dollar symbol "$" and are all (at
least colloquially) referred to as "dollars"; however, it would be ambiguous to display currency values
in American Dollars and Mexican Pesos together on the same screen using only the "$" symbol.
Therefore, SAPUI5 uses the standard Unicode Common Locale Data Repository in order to derive the
correct currency symbol for a given currency code and locale.
The coding in formatter.js ensures that from the perspective of a given locale, all currency symbols
are displayed correctly.
The Browser's Locale May Not Be The Application Language In order to create a sap.ui.core.Locale object, we need a language code. In this example we have
used the browser's default language which is typically a language code followed by a region code. For
example:
en-GB The English spoken in England (Queen's English, hurrah!)
de-AT The German spoken in Austria
As was mentioned in Step 7: above, we have assumed that the language information sent from the
browser can be used to determine the language in which this business application should be run.
This might not always be true for your business scenario!
SAPUI5 Tutorial Data Binding
July 2015 42
Behaviour This example has been designed to display the currency value in Euros. However, the following
combinations illustrate how SAPUI5 can calculate the correct currency symbol when a currency code
is displayed from the perspective of a particular locale.
This table shows the different currency symbols for a given combination of currency code and locale:
Currency
Locale
US Dollar
(USD)
Canadian Dollar
(CAD)
Mexican Peso
(MXN)
British English (en-GB) US$ CA$ MX$
Canadian English (en-CA) $ CA$ MX$
American English (en-US) $ CA$ MX$
Mexican Spanish (es-MX) USD CAD $
To see these changes, alter the currency code value in the JSON model, and the value of the
sBrowserLocale variable in formatter.js to one of the combinations seen above.
For instance, set the currency code to US Dollars and the locale to British English:
./models/model.json
... SNIP ... "salesToDate" : 12345.6789, "currencyCode" : "USD" }
./controllers/formatter.js
... SNIP ... // var sBrowserLocale = sap.ui.getCore().getConfiguration().getLanguage(); var sBrowserLocale = "en-GB"; var oLocale = new sap.ui.core.Locale(sBrowserLocale); var oLocaleData = new sap.ui.core.LocaleData(oLocale); ... SNIP ...
SAPUI5 Tutorial Data Binding
July 2015 43
Step 12: Validation Using the Message Manager So far, we have created a currency field that can do little more than format itself correctly.
The currency data type also has the ability to validate that user input conforms to the requirements of
a currency; however, data type validation functions are managed by the SAPUI5 core, which of itself
has no mechanism for reporting error messages back to the UI.
In this step, we will connect the entire view to a feature of the SAPUI5 core known as the Message
Manager. Once this connection has been made, any validation error messages generated by the
user's input will be passed from the SAPUI5 core to the Message Manager which in turn, will connect
them to the appropriate view and UI control that caused the error.
12.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 44
12.2. ./index.html ... SNIP ... // ------------------------------------------------------------------------ // Attach an anonymous function to the SAPUI5 'init' event sap.ui.getCore().attachInit(function () { new sap.ui.core.mvc.XMLView({ viewName : "sap.ui.demo.db.views.App" }). placeAt("content"); // Create view var oView = new sap.ui.core.mvc.XMLView({ viewName : "sap.ui.demo.db.views.App" }); // Register the view with the message manager sap.ui.getCore().getMessageManager().registerObject(oView, true); // Insert the view into the DOM oView.placeAt("content"); });
Explanation
The changes to the coding are minimal:
1. The XML view is now created as a named object called oView.
2. The view object oView is registered with the Message Manager in the SAPUI5 core.
3. Once registered, the XML view is then inserted into the DOM as before.
Behaviour
Enter a non-numeric value into the "Sales To Date" field and either press enter or tab to move the
focus to a different UI control. This action triggers either the onenter or onchange event and the
SAPUI5 core then executes the validation function belonging to the sap.ui.model.type.Currency
data type.
Now that the view has been registered with the Message Manager, any validation error messages will
be picked up by the Message Manager, which in turn checks its list of registered objects and passes
the error message back to the correct view for display.
Notice that the field in error will always have a red border:
However, the error message itself will only be displayed when that
particular field has focus:
SAPUI5 Tutorial Data Binding
July 2015 45
Step 13: Element Binding Up until now we have used examples in which a single model property is bound to a single UI control.
This is fine as far as it goes, but the problem is, it doesn't go very far particularly when we need to
write real-life business applications in which multiple occurrences of the same data structure need to
be displayed in UI controls such as lists or tables.
So now we will take the next step and look at element binding.
13.1. Preview
SAPUI5 Tutorial Data Binding
July 2015 46
13.2. ./views/App.view.xml ... SNIP ...
A new element has been inserted at the end of the XML view. This panel contains a
element in which a list of invoices will be displayed.
Within the element of the the number and numberUnit properties are
bound to a currency value and currency code exactly as was done in the previous step.
An has been created that adds an extra text field to each list item. The status
property belonging to each invoice item is translated from the single character "A", "B", or "C" into a
meaningful text message using the formatter function getStatusText.
13.3. ./models/model.json ... SNIP ... "salesToDate" : 12345.6789, "currencyCode" : "EUR", "invoices": [{ "ProductName": "Pineapple", "Quantity": 21, "ExtendedPrice": 87.2000, "ShipperName": "Fun Inc.", "ShippedDate": "2015-04-01T00:00:00", "Status": "A" }, { "ProductName": "Milk", "Quantity": 4, "ExtendedPrice": 9.99999, "ShipperName": "ACME", "ShippedDate": "2015-02-18T00:00:00", "Status": "B" }, {
SAPUI5 Tutorial Data Binding
July 2015 47
"ProductName": "Canned Beans", "Quantity": 3, "ExtendedPrice": 6.85000, "ShipperName": "ACME", "ShippedDate": "2015-03-02T00:00:00", "Status": "B" }, { "ProductName": "Salad", "Quantity": 2,
Top Related