• No results found

Data Binding in SAPUI5

N/A
N/A
Protected

Academic year: 2021

Share "Data Binding in SAPUI5"

Copied!
73
0
0

Loading.... (view fulltext now)

Full text

(1)

SAPUI5 Tutorial

Applicable Releases:

SAPUI5 v1.28 and higher

Version 1.0

July 2015

(2)

© Copyright 2015 SAP AG. All rights reserved.

No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.

IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.

Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated in the United States and/or other countries.

Oracle is a registered trademark of Oracle Corporation.

UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.

Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc.

HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology.

Java is a registered trademark of Sun Microsystems, Inc.

JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer, StreamWork, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.

Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects Software Ltd. Business Objects is an SAP company.

All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. The information in this document is proprietary to SAP. No part of this document may be reproduced, copied, or transmitted in any form or for any purpose without the express prior written permission of SAP AG. This document is a preliminary version and not subject to your license agreement or any other agreement with SAP. This document contains only intended strategies, developments, and functionalities of the SAP® product and is not intended to be binding upon SAP to any particular course of business, product strategy, and/or development. Please note that this document is subject to change and may be changed by SAP at any time without notice.

SAP assumes no responsibility for errors or omissions in this document. SAP does not warrant the accuracy or completeness of the information, text, graphics, links, or other items contained within this material. This document is provided without a warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP shall have no liability for damages of any kind including without limitation direct, special, indirect, or consequential damages that may result from the use of these materials. This limitation shall not apply in cases of intent or gross negligence.

The statutory liability for personal injury and defective products is not affected. SAP has no control over the information that you may access through the use of hot links contained in these materials and does not endorse your use of third-party Web pages nor provide any warranty whatsoever relating to third-party Web pages.

SAP “How-to” Guides are intended to simplify the product implement-tation. While specific product features and procedures typically are explained in a practical business context, it is not implied that those features and procedures are the only approach in solving a specific business problem using SAP NetWeaver. Should you wish to receive additional information, clarification or support, please refer to SAP Consulting.

Any software coding and/or code lines / strings (“Code”) included in this documentation are only examples and are not intended to be used in a productive system environment. The Code is only intended better explain and visualize the syntax and phrasing rules of certain coding. SAP does not warrant the correctness and completeness of the Code given herein, and SAP shall not be liable for errors or damages caused by the usage of the Code, except if such damages were caused by SAP intentionally or grossly negligent.

Disclaimer

(3)

Document History

Document Version Description

(4)

Typographic Conventions

Type Style Description

Example Text Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options.

Cross-references to other documentation

Example text Emphasized words or

phrases in body text, graphic titles, and table titles

Example text File and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools.

Example text User entry texts. These are

words or characters that you enter in the system exactly as they appear in the

documentation.

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

Icons

Icon Description Caution Note or Important Example Recommendation or Tip

(5)

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

(6)

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

(7)

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

(8)

Introduction

In this tutorial, we will explain the concepts of data binding in SAPUI5.

Data binding is a declarative programming technique in which the properties of a Model-View-Controller (MVC) Model are associated with (or bound to) the properties of UI elements in an MVC View.

The use of data binding follows as a consequence of the SAPUI5's use of the MVC design pattern, and within the context of this development framework, is the standard programming technique for presenting model-based information on the screen.

(9)

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.

(10)

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.

(11)

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.

(12)

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!

(13)

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

(14)

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.

(15)

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.

(16)

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);

(17)

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.

(18)

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

(19)

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

(20)

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.

(21)

Important

By default, the data binding mode (one-way or two-way) is a feature of the Model object, and is unrelated to whether the bound UI Control property permits user input or not. Therefore, in the diagram below, the use of single- or double-headed arrows indicates nothing more than the direction of data flow between the model and the specific UI control.

Since a sap.m.Label control is read-only, in practice, data will only flow from the model to the control; however, since a user can change the state of a sap.m.CheckBox control or a sap.m.Input control, double-headed arrows are used to indicate that data entered by the user flows in both directions between the model and the UI.

For simplicity, the following diagram shows only the data binding for the "Last name" label and input field. JSON Model Data Binding Model Instance sap.m.Panel sap.m.Label text:%"Last%Name" sap.m.Input value:%"{/lastName}" enabled:%"{/enabled}" sap.m.CheckBox selected:%"{/enabled}"

(22)

If you now switch off the sap.m.CheckBox control, two-way data binding ensures that the model is updated. Then, by virtue of the fact that both of the sap.m.Input controls are bound to the model's enabled property, these UI controls are immediately disabled.

JSON Model Data Binding Model Instance sap.m.Panel sap.m.Label text:%"Last%Name" sap.m.Input value:%"{/lastName}" enabled:%"{/enabled}" sap.m.CheckBox selected:%"{/enabled}"

(23)

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

(24)

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.

(25)

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.

(26)

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.

(27)

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

(28)

Explanation

The diagram seen above in Step 0 can now be extended to include the Resource Model. For simplicity, only the data binding for one Label UI Control is shown.

JSON Model Data Binding Model Instance sap.m.Panel sap.m.Label text:%"{i18n>lastName}" sap.m.Input value:%"{/lastName}" enabled:%"{/enabled}" sap.m.CheckBox selected:%"{/enabled}" Resource Model Data Binding Model Instance “i18n” i18n.properties

(29)

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.

(30)

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.

(31)

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

(32)

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.

(33)

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}

(34)

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.

(35)

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.

(36)

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

(37)

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

(38)

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

...SNIP...

# Screen titles

panel1HeaderText=Data Binding Grundlagen

panel2HeaderText=Formatieren

# Error messages

invalidDate=Ungültiges 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.

(39)

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

(40)

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

(41)

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.

(42)

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.

(43)

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.

(44)

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 }

(45)

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

(46)

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.

References

Related documents

It is better for company to improve the job satisfaction and job performance activities because both of variables have significant influence on turnover

Favor you leave and sample policy employees use their job application for absence may take family and produce emails waste company it discusses email etiquette Deviation from

In Germany, these include subsidies to the hard coal industry; “eco-taxes” that are to increase energy taxes 10% during 2001–2004 (although, in late 2001, the chancellor’s

Previous studies have demonstrated that the phosphorylation of Ser675 and Ser552 in the C-terminus of at β-catenin promotes its nuclear accumulation and transcriptional

Key words: Ahtna Athabascans, Community Subsistence Harvest, subsistence hunting, GMU 13 moose, Alaska Board o f Game, Copper River Basin, natural resource management,

Na akcii sa zúčastnili dva modely – úplne nové Mondeo Hybrid a nový Focus s 1,5-litrovým motorom EcoBoost. Medzi vodičské návyky, ktoré inštruktori vštepo- vali

Dengan kata lain, q-SS memiliki potensi menghilangkan derau lebih baik pada SNR yang tinggi, dan dapat meminimumkan terjadinya distorsi pada sinyal ucapan ketika SNR