You are on page 1of 73

SAP How-to Guide

User Interface
SAPUI5 Tutorial

Data Binding in SAPUI5

Applicable Releases:
SAPUI5 v1.28 and higher

Version 1.0
July 2015

Copyright 2015 SAP AG. All rights reserved.

All other product and service names mentioned are the trademarks of

No part of this publication may be reproduced or transmitted in any form

their respective companies. Data contained in this document serves

or for any purpose without the express permission of SAP AG. The

informational purposes only. National product specifications may vary.

information contained herein may be changed without prior notice.

The information in this document is proprietary to SAP. No part of this

Some software products marketed by SAP AG and its distributors

document may be reproduced, copied, or transmitted in any form or for

contain proprietary software components of other software vendors.

any purpose without the express prior written permission of SAP AG.

Microsoft, Windows, Excel, Outlook, and PowerPoint are registered

This document is a preliminary version and not subject to your license

trademarks of Microsoft Corporation.

agreement or any other agreement with SAP. This document contains

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,

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.

OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS,

SAP assumes no responsibility for errors or omissions in this document.

HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex,

SAP does not warrant the accuracy or completeness of the information,

MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and

text, graphics, links, or other items contained within this material. This

Informix are trademarks or registered trademarks of IBM Corporation.

document is provided without a warranty of any kind, either express or

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.

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

Java is a registered trademark of Sun Microsystems, Inc.

business problem using SAP NetWeaver. Should you wish to receive

JavaScript is a registered trademark of Sun Microsystems, Inc., used

additional information, clarification or support, please refer to SAP

under license for technology invented and implemented by Netscape.

Consulting.

SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP

Any software coding and/or code lines / strings (Code) included in this

BusinessObjects Explorer, StreamWork, and other SAP products and

documentation are only examples and are not intended to be used in a

services mentioned herein as well as their respective logos are

productive system environment. The Code is only intended better explain

trademarks or registered trademarks of SAP AG in Germany and other

and visualize the syntax and phrasing rules of certain coding. SAP does

countries.

not warrant the correctness and completeness of the Code given herein,

Business Objects and the Business Objects logo, BusinessObjects,

and SAP shall not be liable for errors or damages caused by the usage of

Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other

the Code, except if such damages were caused by SAP intentionally or

Business Objects products and services mentioned herein as well as their

grossly negligent.

respective logos are trademarks or registered trademarks of Business

Disclaimer

Objects Software Ltd. Business Objects is an SAP company.

Some components of this product are based on Java. Any code change

Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere,

in these components may cause unpredictable and severe malfunctions

and other Sybase products and services mentioned herein as well as their

and is therefore expressively prohibited, as is any decompilation of these

respective logos are trademarks or registered trademarks of Sybase, Inc.

components.

Sybase is an SAP company.

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

Icons

Type Style

Description

Icon

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.

<Example
text>

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.

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

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-ViewController (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.

July 2015

SAPUI5 Tutorial Data Binding

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.

July 2015

SAPUI5 Tutorial Data Binding

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.

July 2015

SAPUI5 Tutorial Data Binding

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:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<title>SAPUI5 Data Binding Tutorial</title>
<script
id="sap-ui-bootstrap"
src="../resources/sap-ui-core-dbg.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"
>
</script>
<script>
// 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.

July 2015

SAPUI5 Tutorial Data Binding

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

July 2015

SAPUI5 Tutorial Data Binding

1.2. ./index.html (New file)


Under the DataBinding folder, create an index.html file and within it place the following code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<title>SAPUI5 Data Binding Tutorial</title>
<script
id="sap-ui-bootstrap"
src="../resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"
>
</script>
<script>
// -----------------------------------------------------------------------// 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");
});
</script>
</head>
<body class="sapUiBody" id="content">
</body>
</html>

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!

July 2015

SAPUI5 Tutorial Data Binding

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.

July 2015

SAPUI5 Tutorial Data Binding

2.2. ./index.html
...SNIP...
<script>
// -----------------------------------------------------------------------// 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");
});
</script>
...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.

July 2015

SAPUI5 Tutorial Data Binding

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...
<script>
// -----------------------------------------------------------------------// 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");
});
</script>
...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.

July 2015

SAPUI5 Tutorial Data Binding

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.

July 2015

10

SAPUI5 Tutorial Data Binding

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

July 2015

11

SAPUI5 Tutorial Data Binding

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:
<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
<Panel headerText="{/panelHeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="First Name" class="sapUiSmallMargin" />
<Input value="{/firstName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<Label text="Last Name" class="sapUiSmallMargin" />
<Input value="{/lastName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<CheckBox selected="{/enabled}" text="Enabled" />
</content>
</Panel>
</mvc:View>

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...
<script
id="sap-ui-bootstrap"
src="../resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"
data-sap-ui-resourceroots='{ "sap.ui.demo.db": "./" }'
>
</script>
<script>
// -----------------------------------------------------------------------// 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");
});
</script>
...SNIP...

July 2015

12

SAPUI5 Tutorial Data Binding

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.

July 2015

13

SAPUI5 Tutorial Data Binding

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.

sap.m.Panel
sap.m.CheckBox
selected:%"{/enabled}"

sap.m.Label
text:%"Last%Name"

sap.m.Input
value:%"{/lastName}"
enabled:%"{/enabled}"

Data Binding
Model Instance

JSON Model

July 2015

14

SAPUI5 Tutorial Data Binding

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.

sap.m.Panel
sap.m.CheckBox
selected:%"{/enabled}"

sap.m.Label
text:%"Last%Name"

sap.m.Input
value:%"{/lastName}"
enabled:%"{/enabled}"

Data Binding
Model Instance

JSON Model

July 2015

15

SAPUI5 Tutorial Data Binding

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...
<script>
// -----------------------------------------------------------------------// 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...

July 2015

16

SAPUI5 Tutorial Data Binding

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.

July 2015

17

SAPUI5 Tutorial Data Binding

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

July 2015

18

SAPUI5 Tutorial Data Binding

6.2. ./index.html
... SNIP ...
<script>
// -----------------------------------------------------------------------// 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");
});
</script>
...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".

July 2015

19

SAPUI5 Tutorial Data Binding

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
<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
<Panel headerText="{i18n>panelHeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>firstName}" class="sapUiSmallMargin" />
<Input value="{/firstName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<Label text="{i18n>lastName}" class="sapUiSmallMargin" />
<Input value="{/lastName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<CheckBox selected="{/enabled}" text="{i18n>enabled}" />
</content>
</Panel>
</mvc:View>

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!

July 2015

20

SAPUI5 Tutorial Data Binding

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.

sap.m.Panel
sap.m.CheckBox

sap.m.Label

sap.m.Input

selected:%"{/enabled}"

text:%"{i18n>lastName}"

value:%"{/lastName}"
enabled:%"{/enabled}"

Data Binding
Model Instance
i18n

Resource
Model

Data Binding
Model Instance

JSON Model

i18n.properties

July 2015

21

SAPUI5 Tutorial Data Binding

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.

July 2015

22

SAPUI5 Tutorial Data Binding

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.

July 2015

23

SAPUI5 Tutorial Data Binding

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

July 2015

24

SAPUI5 Tutorial Data Binding

8.2. ./index.html
... SNIP ...
<script>
// -----------------------------------------------------------------------// 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
<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
<Panel headerText="{i18n>panel1HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>firstName}" class="sapUiSmallMargin" />
<Input value="{/firstName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<Label text="{i18n>lastName}" class="sapUiSmallMargin" />
<Input value="{/lastName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<CheckBox selected="{/enabled}" text="{i18n>enabled}" />
</content>
</Panel>
<Panel headerText="{i18n>panel2HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>dateOfBirth}" />
<Text text="{/dateOfBirth/day}/{/dateOfBirth/month}/{/dateOfBirth/year}"
width="200px" class="sapUiSmallMargin" />
</content>
</Panel>
</mvc:View>

A new panel has been added to the XML view in which a new <Label> and <Text> pair of elements
have been created.
The <Label> element's text property is bound to the i18n Resource Bundle field dateOfBirth.
The <Text> 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.

July 2015

25

SAPUI5 Tutorial Data Binding

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

July 2015

26

SAPUI5 Tutorial Data Binding

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

July 2015

27

SAPUI5 Tutorial Data Binding

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.

July 2015

28

SAPUI5 Tutorial Data Binding

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.

July 2015

29

SAPUI5 Tutorial Data Binding

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
<mvc:View controllerName="sap.ui.demo.db.controllers.App"
xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
<Panel headerText="{i18n>panel1HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>firstName}" class="sapUiSmallMargin" />
<Input value="{/firstName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<Label text="{i18n>lastName}" class="sapUiSmallMargin" />
<Input value="{/lastName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<CheckBox selected="{/enabled}" text="{i18n>enabled}" />
</content>
</Panel>
<Panel headerText="{i18n>panel2HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>dateOfBirth}" />
<Text text="{parts: [{path: '/dateOfBirth/day'},
{path: '/dateOfBirth/month'},
{path: '/dateOfBirth/year'},
{path: 'i18n>invalidDate'}],
formatter: '.dateFormatter'
}"
width="200px" class="sapUiSmallMargin" />
</content>
</Panel>
</mvc:View>

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 <Text> UI control would not
be able to reference the dateFormatter function.
The text property of the <Text> 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

July 2015

30

SAPUI5 Tutorial Data Binding

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!

July 2015

31

SAPUI5 Tutorial Data Binding

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.

July 2015

32

SAPUI5 Tutorial Data Binding

10.2. ./index.html
... SNIP ...
<script>
// -----------------------------------------------------------------------// 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
}
}

July 2015

33

SAPUI5 Tutorial Data Binding

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.

July 2015

34

SAPUI5 Tutorial Data Binding

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.

July 2015

35

SAPUI5 Tutorial Data Binding

10.6. ./views/App.view.xml
<mvc:View controllerName="sap.ui.demo.db.controller.App"
xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
<Panel headerText="{i18n>panel1HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>firstName}" class="sapUiSmallMargin" />
<Input value="{/firstName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<Label text="{i18n>lastName}" class="sapUiSmallMargin" />
<Input value="{/lastName}" valueLiveUpdate="true" width="200px" enabled="{/enabled}" />
<CheckBox selected="{/enabled}" text="{i18n>enabled}" />
</content>
</Panel>
<Panel headerText="{i18n>panel2HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>dateOfBirth}" />
<Text text="{parts: [{path: '/dateOfBirth'},
{path: 'i18n>invalidDate'}],
formatter: '.formatter.dateFormatter'
}"
width="200px" class="sapUiSmallMargin" />
</content>
</Panel>
</mvc:View>

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.

July 2015

36

SAPUI5 Tutorial Data Binding

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.

July 2015

37

SAPUI5 Tutorial Data Binding

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

July 2015

38

SAPUI5 Tutorial Data Binding

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 ...
<Panel headerText="{i18n>panel2HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<Label text="{i18n>dateOfBirth}" />
<Text text="{parts: [{path: '/dateOfBirth'},
{path: 'i18n>invalidDate'}],
formatter: '.formatter.dateFormatter'
}"
width="200px" class="sapUiSmallMargin" />
<Label text="{i18n>salesToDate}" class="sapUiSmallMargin" />
<Input width="200px" enabled="{/enabled}"
description="{ path: '/currencyCode',
formatter: '.formatter.getCurrencySymbol'
}"
value="{ parts: [{path: '/salesToDate'},
{path: '/currencyCode'}],
type: 'sap.ui.model.type.Currency',
formatOptions: {showMeasure: false }
}" />
</content>
</Panel>
</mvc:View>

A new pair or <Label> and <Input> elements have been created for the salesToDate model
property.
The description property of the <Input> 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 <Input> 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 <Input>
element's description property.

July 2015

39

SAPUI5 Tutorial Data Binding

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

July 2015

40

SAPUI5 Tutorial Data Binding

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!

July 2015

41

SAPUI5 Tutorial Data Binding

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

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

Locale

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
var sBrowserLocale =
var oLocale
=
var oLocaleData
=
... SNIP ...

July 2015

= sap.ui.getCore().getConfiguration().getLanguage();
"en-GB";
new sap.ui.core.Locale(sBrowserLocale);
new sap.ui.core.LocaleData(oLocale);

42

SAPUI5 Tutorial Data Binding

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

July 2015

43

SAPUI5 Tutorial Data Binding

12.2. ./index.html
... SNIP ...
<script>
// -----------------------------------------------------------------------// 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");
});
</script>
</head>
<body class="sapUiBody" id="content">
</body>
</html>

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:

July 2015

44

SAPUI5 Tutorial Data Binding

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

July 2015

45

SAPUI5 Tutorial Data Binding

13.2. ./views/App.view.xml
... SNIP ...
</content>
</Panel>
<Panel headerText="{i18n>panel3HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<List headerText="{i18n>invoiceListTitle}" class="sapUiResponsiveMargin" width="auto"
items="{/invoices}">
<items>
<ObjectListItem
title="{Quantity} x {ProductName}"
number="{ parts: [{path: 'ExtendedPrice'},
{path: '/currencyCode'}],
type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false }
}"
numberUnit="{ path: '/currencyCode',
formatter: '.formatter.getCurrencySymbol' }">
<attributes>
<ObjectAttribute text="{ path: 'Status',
formatter: '.formatter.getStatusText' }"/>
</attributes>
</ObjectListItem>
</items>
</List>
</content>
</Panel>
</mvc:View>

A new <Panel> element has been inserted at the end of the XML view. This panel contains a <List>
element in which a list of invoices will be displayed.
Within the <ObjectListItem> element of the <List> the number and numberUnit properties are
bound to a currency value and currency code exactly as was done in the previous step.
An <ObjectAttribute> 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"
}, {

July 2015

46

SAPUI5 Tutorial Data Binding

"ProductName": "Canned Beans",


"Quantity": 3,
"ExtendedPrice": 6.85000,
"ShipperName": "ACME",
"ShippedDate": "2015-03-02T00:00:00",
"Status": "B"
}, {
"ProductName": "Salad",
"Quantity": 2,
"ExtendedPrice": 8.8000,
"ShipperName": "ACME",
"ShippedDate": "2015-04-12T00:00:00",
"Status": "C"
}, {
"ProductName": "Bread",
"Quantity": 1,
"ExtendedPrice": 2.71212,
"ShipperName": "Fun Inc.",
"ShippedDate": "2015-01-27T00:00:00",
"Status": "A"
}]
}

13.4. ./controllers/formatter.js
... SNIP ...
// ------------------------------------------------------------------------var getStatusText = function(sStatus) {
// As long as the status code can be found in the array containing the values
// "A", "B" and "C" (we don't care where), then we know the status code is valid
// and can then be used to derive the i18n key name.
// If not, we simply return the status code
return (["A","B","C"].indexOf(sStatus) > -1)
? this.getView().getModel("i18n").getProperty("status" + sStatus)
: sStatus;
};
// ------------------------------------------------------------------------return {
dateFormatter
: dateFormatter,
getCurrencySymbol : getCurrencySymbol,
getStatusText
: getStatusText
};
});

Array.indexOf() tests for membership in an array. Therefore, we can use this as a quick way to test
whether the supplied value belongs to a list of known values.
Each of our known values (A, B, or C) is listed as an array element, then we test whether
indexOf() returns a value greater than minus one. This is a simple test for membership, so as long
as indexOf() does not return -1, we dont care about exactly where in the array this element is found.
This is avoids the need to write a bulky switch or nested if statement.

July 2015

47

SAPUI5 Tutorial Data Binding

13.5. ./i18n/i18n.properties
# Screen titles
panel1HeaderText=Data Binding Basics
panel2HeaderText=Formatting
panel3HeaderText=Element Binding
# Invoice List
invoiceListTitle=Invoices
statusA=New
statusB=In Progress
statusC=Done
# Error messages
invalidDate=Invalid Date Format

13.6. ./i18n/i18n_de.properties
# Screen titles
panel1HeaderText=Data Binding Grundlagen
panel2HeaderText=Formatieren
panel3HeaderText=Element Binding
# Invoice List
invoiceListTitle=Rechnungen
statusA=Neu
statusB=Laufen
statusC=Abgeschlossen
# Error messages
invalidDate=Ungltiges Datumsformat

Explanation
In contrast to property binding, in which you bind the property of a UI control to a single property in a
model, element binding is where you bind a UI control to an entire object within a model (or possibly
even the entire model object itself).
Once the entire UI control has been bound to an object in the model, all the subordinate model objects
can be referenced using a relative binding path name: that is, when binding the property of a UI
Control, you only need use a relative binding path address.
Within the JSON model, we have a new array called invoices. Every element in the invoices array
must necessarily have the same structure.
"invoices": [{
"ProductName": "Pineapple",
"Quantity": 21,
"ExtendedPrice": 87.2000,
"ShipperName": "Fun Inc.",
"ShippedDate": "2015-04-01T00:00:00",
"Status": "A"
}, {
... SNIP ...
}]

July 2015

48

SAPUI5 Tutorial Data Binding

In the coding for the XML view, notice that the items parameter of the <List> element is bound to the
/invoices object in the JSON model. This means that every item displayed in this list will be drawn
from this array.
<List headerText="{i18n>invoiceListTitle}" class="sapUiResponsiveMargin" width="auto"
items="{/invoices}">
<items>
... SNIP ...
</items>
</List>

Now, from the perspective of the <ObjectListItem> within the <List> element, all data binding
references can assume that their binding path is relative to the /invoices object.
This means that none of the data binding references highlighted below need to start with a slash
character (because that would indicate an absolute binding reference).
<List headerText="{i18n>invoiceListTitle}" class="sapUiResponsiveMargin" width="auto"
items="{/invoices}">
<items>
<ObjectListItem
title="{Quantity} x {ProductName}"
number="{ parts: [{path: 'ExtendedPrice'},
{path: '/currencyCode'}],
type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false }
}"
numberUnit="{ path: '/currencyCode',
formatter: '.formatter.getCurrencySymbol' }">
<attributes>
<ObjectAttribute text="{ path: 'Status',
formatter: '.formatter.statusText' }"/>
</attributes>
</ObjectListItem>
</items>
</List>

July 2015

49

SAPUI5 Tutorial Data Binding

Step 14: Expression Binding


Expression binding allows you to display a value on the screen that has been calculated from values
found in some model object. As long as the computation is neither complex nor expensive, it can be
inserted directly into the data binding string.
In this example, we will change the colour of the price depending on whether it is above or below
some arbitrary threshold. The threshold value is also stored in the JSON model.

14.1. Preview

July 2015

50

SAPUI5 Tutorial Data Binding

14.2. ./views/App.view.xml
... SNIP ...
</content>
</Panel>
<Panel headerText="{i18n>panel3HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<List headerText="{i18n>invoiceListTitle}" class="sapUiResponsiveMargin" width="auto"
items="{/invoices}">
<items>
<ObjectListItem
title="{Quantity} x {ProductName}"
number="{ parts: [{path: 'ExtendedPrice'},
{path: '/currencyCode'}],
type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false }
}"
numberUnit="{ path: '/currencyCode',
formatter: '.formatter.getCurrencySymbol' }"
numberState="{= ${ExtendedPrice} > ${/priceThreshold} ? 'Error' : 'Success' }">
<attributes>
<ObjectAttribute text="{ path: 'Status',
formatter: '.formatter.getStatusText' }"/>
</attributes>
</ObjectListItem>
</items>
</List>
</content>
</Panel>
</mvc:View>

In the XML view, the <ObjectListItem> element within the <List> has had a new numberState
property added. The value of this property is a simple expression that will be evaluated for each item.
As a result of binding an expression to the numberState property, the error status (colour) of the price
field will change depending on the invoice value.

14.3. ./models/model.json
... SNIP ...
"salesToDate" : 12345.6789,
"priceThreshold" : 50,
"currencyCode" : "EUR",
"invoices": [{
"ProductName": "Pineapple",
... SNIP ...

The JSON model has a new property called priceThreshold added against which each invoice value
will be checked.

July 2015

51

SAPUI5 Tutorial Data Binding

Warning!
Look at the following two expressions:
numberState="{= ${ExtendedPrice} > ${/priceThreshold} ? 'Error' : 'Success' }">

numberState="{= ${ExtendedPrice} <= ${/priceThreshold} ? 'Success' : 'Error' }">

Can you see why one of these expressions will work, and the other will not?
Logically, both expressions are identical; yet the first one works, and the second does not: it produces
only an empty screen and an "Invalid XML" message in the browser's console
Hmmm, what's going on here?

Understanding Syntax Collisions


In order to understand why this situation occurs, you must understand how XML files are parsed.
When an XML file is parsed, certain characters have a special (that is, high priority) meaning to the
XML parser. When such characters are encountered, they are always interpreted to be part of the
XML definition itself and not part of any other content that might exist within the XML document. 1
As soon as the XML parser encounters one of these high-priority characters (in this case, a less-than
("<") character), it will always be interpreted as the start of a new XML tag irrespective of any other
meaning that character might have within the context of the SAPUI5 expression.
This is known as a syntax collision.
In this case the collision occurs between the syntax of XML and the syntax of the JavaScript-like
expression language used by SAPUI5.
Therefore, this statement fails because the less-than character is interpreted as the start of an XML
tag:
numberState="{= ${ExtendedPrice} <= ${/priceThreshold} ? 'Success' : 'Error' }">

This particular problem can be avoided in one of two ways, either:

Reverse the logic of the condition (use "greater than or equal to" instead of "less than"), or

Use the escaped value for the less-than character:

numberState="{= ${ExtendedPrice} &lt;= ${/priceThreshold} ? 'Success' : 'Error' }">

Since the use of an escaped character is not so easy to read, the preferred approach is (where
possible) to reverse the logic of the condition and use a greater-than character instead.
The ampersand ("&") character also has a high priority meaning to the XML parser. This character will
always be interpreted to mean "The start of an escaped character". So if you wish to use the Boolean
AND operator ("&&") in a condition, you must escape both ampersand characters.
"&&" "&amp;&amp;".

XML does allow for special characters such as greater than and ampersand, but only when contained inside a
CDATA section.

July 2015

52

SAPUI5 Tutorial Data Binding

Step 15: Aggregation Binding Using A Template


Conceptually, aggregation binding is very similar to element binding. Both allow a UI control to be
bound to some object within the model data, and both create a binding context within the scope of the
UI control that in turn, allows relative binding to be used by any and all child controls. The difference
is that aggregation binding will automatically create as many child UI controls as are needed to display
the data in the model object using one of the following two approaches:
1. Create a template UI control that is then cloned as many times as needed to display the data.
2. Use a factory function to generate the correct UI control based on the data received at
runtime.

15.1. Preview

July 2015

53

SAPUI5 Tutorial Data Binding

15.2. ./views/App.view.xml
... SNIP ...
<attributes>
<ObjectAttribute text="{ path: 'Status', formatter: '.getStatusText' }"/>
</attributes>
</ObjectListItem>
</items>
</List>
</content>
</Panel>
<Panel headerText="{i18n>panel4HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<List headerText="{i18n>productListTitle}" items="{products>/Products}">
<items>
<ObjectListItem title="{products>ProductName}"
number="{ parts: [{path: 'products>UnitPrice'},
{path: '/currencyCode'}],
type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false }
}"
numberUnit="{ path: '/currencyCode',
formatter: '.formatter.getCurrencySymbol' }">
<attributes>
<ObjectAttribute text="({products>QuantityPerUnit})" />
<ObjectAttribute title="{path: 'i18n>stockValue'}"
text="{parts: [{path: 'products>UnitPrice'},
{path: 'products>UnitsInStock'},
{path: '/currencyCode'}],
formatter: '.formatter.getStockValue' }" />
</attributes>
</ObjectListItem>
</items>
</List>
</content>
</Panel>
</mvc:View>

July 2015

54

SAPUI5 Tutorial Data Binding

15.3. ./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 oProductModel = new sap.ui.model.json.JSONModel();
oProductModel.loadData("./models/Products.json");
this.getView().setModel(oProductModel,"products");
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");
};
// ------------------------------------------------------------------------return Controller.extend("sap.ui.demo.db.controllers.App", {
onInit
: initialise,
formatter : Formatter
});
});

15.4. ./controllers/formatter.js
... SNIP ...
var sBrowserLocale
var oLocale
var oLocaleData
var oCurrency

=
=
=
=

sap.ui.getCore().getConfiguration().getLanguage();
new sap.ui.core.Locale(sBrowserLocale);
new sap.ui.core.LocaleData(oLocale);
new sap.ui.model.type.Currency(oLocaleData.mData.currencyFormat);

... SNIP ...


// ------------------------------------------------------------------------var getStockValue = function(fUnitPrice, iStockLevel, sCurrCode) {
return oCurrency.formatValue([fUnitPrice * iStockLevel,
getCurrencySymbol(sCurrCode)],"string");
};
// ------------------------------------------------------------------------return {
dateFormatter
: dateFormatter,
getCurrencySymbol : getCurrencySymbol,
getStatusText
: getStatusText,
getStockValue
: getStockValue
};
});

Notice that within function getStockValue, there is a call to another formatter function:
getCurrencySymbol. This reference would not be possible if each function within formatter.js
were declared directly within the returned object.

July 2015

55

SAPUI5 Tutorial Data Binding

15.5. ./i18n/i18n.properties
... SNIP ...
# Screen titles
panel1HeaderText=Data Binding Basics
panel2HeaderText=Formatting
panel3HeaderText=Element Binding
panel4HeaderText=Aggregation Binding
# Invoice List
invoiceListTitle=Invoices
statusA=New
statusB=In Progress
statusC=Done
# Error messages
invalidDate=Invalid Date Format
# Product list
productListTitle=Product List
stockValue=Current Stock Value

15.6. ./i18n/i18n_de.properties (Optional)


... SNIP ...
# Screen titles
panel1HeaderText=Data Binding Basics
panel2HeaderText=Formatting
panel3HeaderText=Element Binding
panel4HeaderText=Aggregation Binding
# Invoice List
invoiceListTitle=Rechnungen
statusA=Neu
statusB=Laufen
statusC=Abgeschlossen
# Error messages
invalidDate=Ungltiges Datumsformat
# Product list
productListTitle=Artikelliste
stockValue=Lagerbestand Wert

July 2015

56

SAPUI5 Tutorial Data Binding

15.7. ./models/Products.json (New file)


{ "Products": [ {
"ProductID": 1,
"ProductName": "Chai",
"SupplierID": 1,
"CategoryID": 1,
"QuantityPerUnit": "10 boxes x 20 bags",
"UnitPrice": "18.0000",
"UnitsInStock": 39,
"UnitsOnOrder": 0,
"ReorderLevel": 10,
"Discontinued": false
}, {
"ProductID": 2,
"ProductName": "Chang",
"SupplierID": 1,
"CategoryID": 1,
"QuantityPerUnit": "24 - 12 oz bottles",
"UnitPrice": "19.0000",
"UnitsInStock": 17,
"UnitsOnOrder": 40,
"ReorderLevel": 25,
"Discontinued": false
}, {
"ProductID": 3,
"ProductName": "Aniseed Syrup",
"SupplierID": 1,
"CategoryID": 2,
"QuantityPerUnit": "12 - 550 ml bottles",
"UnitPrice": "10.0000",
"UnitsInStock": 13,
"UnitsOnOrder": 70,
"ReorderLevel": 25,
"Discontinued": false
}, {
"ProductID": 4,
"ProductName": "Chef Anton's Cajun Seasoning",
"SupplierID": 2,
"CategoryID": 2,
"QuantityPerUnit": "48 - 6 oz jars",
"UnitPrice": "22.0000",
"UnitsInStock": 53,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}, {
"ProductID": 5,
"ProductName": "Chef Anton's Gumbo Mix",
"SupplierID": 2,
"CategoryID": 2,
"QuantityPerUnit": "36 boxes",
"UnitPrice": "21.3500",
"UnitsInStock": 0,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": true
}, {
"ProductID": 6,
"ProductName": "Grandma's Boysenberry Spread",
"SupplierID": 3,
"CategoryID": 2,
"QuantityPerUnit": "12 - 8 oz jars",

July 2015

57

SAPUI5 Tutorial Data Binding

"UnitPrice": "25.0000",
"UnitsInStock": 120,
"UnitsOnOrder": 0,
"ReorderLevel": 25,
"Discontinued": false
}, {
"ProductID": 7,
"ProductName": "Uncle Bob's Organic Dried Pears",
"SupplierID": 3,
"CategoryID": 7,
"QuantityPerUnit": "12 - 1 lb pkgs.",
"UnitPrice": "30.0000",
"UnitsInStock": 0,
"UnitsOnOrder": 0,
"ReorderLevel": 10,
"Discontinued": false
}, {
"ProductID": 8,
"ProductName": "Northwoods Cranberry Sauce",
"SupplierID": 3,
"CategoryID": 2,
"QuantityPerUnit": "12 - 12 oz jars",
"UnitPrice": "40.0000",
"UnitsInStock": 6,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}, {
"ProductID": 9,
"ProductName": "Mishi Kobe Niku",
"SupplierID": 4,
"CategoryID": 6,
"QuantityPerUnit": "18 - 500 g pkgs.",
"UnitPrice": "97.0000",
"UnitsInStock": 29,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": true
}, {
"ProductID": 10,
"ProductName": "Ikura",
"SupplierID": 4,
"CategoryID": 8,
"QuantityPerUnit": "12 - 200 ml jars",
"UnitPrice": "31.0000",
"UnitsInStock": 31,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}, {
"ProductID": 11,
"ProductName": "Queso Cabrales",
"SupplierID": 5,
"CategoryID": 4,
"QuantityPerUnit": "1 kg pkg.",
"UnitPrice": "21.0000",
"UnitsInStock": 22,
"UnitsOnOrder": 30,
"ReorderLevel": 30,
"Discontinued": false
}, {
"ProductID": 12,
"ProductName": "Queso Manchego La Pastora",

July 2015

58

SAPUI5 Tutorial Data Binding

"SupplierID": 5,
"CategoryID": 4,
"QuantityPerUnit": "10 - 500 g pkgs.",
"UnitPrice": "38.0000",
"UnitsInStock": 86,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}, {
"ProductID": 13,
"ProductName": "Konbu",
"SupplierID": 6,
"CategoryID": 8,
"QuantityPerUnit": "2 kg box",
"UnitPrice": "6.0000",
"UnitsInStock": 0,
"UnitsOnOrder": 0,
"ReorderLevel": 5,
"Discontinued": false
}, {
"ProductID": 14,
"ProductName": "Tofu",
"SupplierID": 6,
"CategoryID": 7,
"QuantityPerUnit": "40 - 100 g pkgs.",
"UnitPrice": "23.2500",
"UnitsInStock": 35,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}, {
"ProductID": 15,
"ProductName": "Genen Shouyu",
"SupplierID": 6,
"CategoryID": 2,
"QuantityPerUnit": "24 - 250 ml bottles",
"UnitPrice": "15.5000",
"UnitsInStock": 39,
"UnitsOnOrder": 0,
"ReorderLevel": 5,
"Discontinued": false
}, {
"ProductID": 16,
"ProductName": "Pavlova",
"SupplierID": 7,
"CategoryID": 3,
"QuantityPerUnit": "32 - 500 g boxes",
"UnitPrice": "17.4500",
"UnitsInStock": 29,
"UnitsOnOrder": 0,
"ReorderLevel": 10,
"Discontinued": false
}, {
"ProductID": 17,
"ProductName": "Alice Mutton",
"SupplierID": 7,
"CategoryID": 6,
"QuantityPerUnit": "20 - 1 kg tins",
"UnitPrice": "39.0000",
"UnitsInStock": 0,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": true

July 2015

59

SAPUI5 Tutorial Data Binding

}, {
"ProductID": 18,
"ProductName": "Carnarvon Tigers",
"SupplierID": 7,
"CategoryID": 8,
"QuantityPerUnit": "16 kg pkg.",
"UnitPrice": "62.5000",
"UnitsInStock": 42,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}, {
"ProductID": 19,
"ProductName": "Teatime Chocolate Biscuits",
"SupplierID": 8,
"CategoryID": 3,
"QuantityPerUnit": "10 boxes x 12 pieces",
"UnitPrice": "9.2000",
"UnitsInStock": 25,
"UnitsOnOrder": 0,
"ReorderLevel": 5,
"Discontinued": false
}, {
"ProductID": 20,
"ProductName": "Sir Rodney's Marmalade",
"SupplierID": 8,
"CategoryID": 3,
"QuantityPerUnit": "30 gift boxes",
"UnitPrice": "81.0000",
"UnitsInStock": 40,
"UnitsOnOrder": 0,
"ReorderLevel": 0,
"Discontinued": false
}]
}

July 2015

60

SAPUI5 Tutorial Data Binding

Step 16: Aggregation Binding Using A Factory Function


Now, instead of hardcoding a single template UI control, we will use a factory function to generate
different UI controls based on the data received at runtime. This approach is much more flexible and
allows complex or heterogeneous data to be displayed.

16.1. Preview

July 2015

61

SAPUI5 Tutorial Data Binding

16.2. ./views/App.view.xml
... SNIP ...
<attributes>
<ObjectAttribute text="{ path: 'Status', formatter: '.getStatusText' }"/>
</attributes>
</ObjectListItem>
</items>
</List>
</content>
</Panel>
<Panel headerText="{i18n>panel4HeaderText}" class="sapUiResponsiveMargin" width="auto">
<content>
<List id="ProductList" headerText="{i18n>productListTitle}" />
<List headerText="{i18n>productListTitle}" items="{products>/Products}">
<items>
<ObjectListItem title="{products>ProductName}"
number="{ parts: [{path: 'products>UnitPrice'},
{path: '/currencyCode'}],
type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false }
}"
numberUnit="{ path: '/currencyCode', formatter: '.getCurrencySymbol' }">
<attributes>
<ObjectAttribute text="({products>QuantityPerUnit})" />
<ObjectAttribute title="{path: 'i18n>stockValue'}"
text="{parts: [{path: 'products>UnitPrice'},
{path: 'products>UnitsInStock'},
{path: '/currencyCode'}],
formatter: '.getStockValue' }" />
</attributes>
</ObjectListItem>
</items>
</List>
</content>
</Panel>
</mvc:View>

The <List> XML element that previously held the product list is now reduced simply to a named, but
otherwise empty placeholder.
Without a factory function to populate it, this <List> would always remain empty.

July 2015

62

SAPUI5 Tutorial Data Binding

16.3. ./i18n/i18n.properties
... SNIP ...
# Error messages
invalidDate=Invalid Date Format
# Product list
productListTitle=Product List
stockValue=Current Stock Value
outOfStock=Out of Stock
discontinued=Product Discontinued
unitsInStock=Stock Level

16.4. ./i18n/i18n_de.properties (Optional)


... SNIP ...
# Error messages
invalidDate=Ungltiges Datumsformat
# Product list
productListTitle=Artikelliste
stockValue=Lagerbestand Wert
outOfStock=Nicht Vorrtig
discontinued=Produkt Eingestellt
unitsInStock=Lagerbestandsverlauf

16.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 productListFactory = function(sId, oContext) {
var oUIControl = null;
// Define the item description
var sDescription = oContext.getProperty("ProductName") +
" (" + oContext.getProperty("QuantityPerUnit") + ")";
// Is this item both out of stock *and* discontinued?
if (oContext.getProperty("UnitsInStock") === 0 &&
oContext.getProperty("Discontinued")) {
// Yup, so use a StandardListItem
oUIControl = new sap.m.StandardListItem(sId, {
icon
: "sap-icon://warning",
title
: sDescription,
info
: { path: "i18n>discontinued" },
infoState : "Error"
});
}
else {
// Nope, so we will create an ObjectListItem
oUIControl = new sap.m.ObjectListItem(sId, {
title
: sDescription,
number
: { parts: [{path: "products>UnitPrice"},

July 2015

63

SAPUI5 Tutorial Data Binding

{path: "/currencyCode"}],
type: "sap.ui.model.type.Currency",
formatOptions: {showMeasure: false}
},
numberUnit : { path: "/currencyCode",
formatter: Formatter.getCurrencySymbol }
});
// Is this item in stock?
if (oContext.getProperty("UnitsInStock") > 0) {
// First object attribute displays the current stock level
oUIControl.addAttribute(new sap.m.ObjectAttribute({
title : { path: "i18n>unitsInStock" },
text : { path: "products>UnitsInStock" }
}));
// Second object attribute displays the current stock value
oUIControl.addAttribute(new sap.m.ObjectAttribute({
title : { path: "i18n>stockValue" },
text : { parts: [{path: "products>UnitPrice"},
{path: "products>UnitsInStock"},
{path: "/currencyCode"}],
formatter: Formatter.getStockValue }
}));
// Has this product been discontinued?
if (oContext.getProperty("Discontinued")) {
// Yup, so we're selling off the last remaining stock items
// Set the status of the first attribute to "discontinued"
oUIControl.setFirstStatus(new sap.m.ObjectStatus({
text: { path: "i18n>discontinued" },
state: "Error"
}));
}
}
else {
// Nope, so this item is just temporarily out of stock
oUIControl.addAttribute(new sap.m.ObjectAttribute({
text : { path: "i18n>outOfStock" }
}));
}
}
return oUIControl;
};
// ---------------------------------------------------------------------var initialise = function() {
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData("./models/model.json");
this.getView().setModel(oModel);
var oProductModel = new sap.ui.model.json.JSONModel();
oProductModel.loadData("./models/Products.json");
this.getView().setModel(oProductModel,"products");
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");

July 2015

64

SAPUI5 Tutorial Data Binding

// Get a reference to the Product List using the XML element's id


var oProductList = this.getView().byId("ProductList");
// In addition to binding the "items" aggregation in the list to the
// Products array in the "products" model, the productListFactory function
// is also passed as a parameter
oProductList.bindAggregation("items", "products>/Products", productListFactory);
};
// ------------------------------------------------------------------------return Controller.extend("sap.ui.demo.db.controllers.App", {
onInit
: initialise,
formatter : Formatter
});
});

In the App controller, a new function called productListFactory has been created. The types of UI
Control returned from this factory function must be limited to those suitable for inclusion in the items
aggregation of a sap.m.List object. In this case, we will return either a StandardListItem or an
ObjectListItem using the following logic:
We decide which type of UI control to return by checking the current stock level and whether or not the
product has been discontinued. This creates four possible responses:
1. First, eliminate the minority case.
If the stock level is zero and the product has also been discontinued, then use a
StandardListItem with a warning icon and a "Product Discontinued" message in the status
property. All other possibilities will use an ObjectListItem.

2. Create an ObjectListItem then test for the majority case.


The product is in stock and has not been discontinued, so add two ObjectAttributes to the
ObjectListItem to display the current stock level and value.

3. The product is in stock but has also been discontinued, so we are simply selling off the last
remaining stock items. Therefore, in addition to the two ObjectAttributes added above,
use the status property of the first attribute to indicate that this product has been discontinued.

4. The product has not been discontinued but the stock level is zero, therefore we are
temporarily out of stock. In this case, add a single ObjectAttribute that displays the "Out of
Stock" message.

July 2015

65

www.sap.com/contactsap
www.sdn.sap.com/irj/sdn/howtoguide
s