BuildSAPFioriUIsWithSAPUI5_v2

430
Build SAP Fiori UIs with SAPUI5 Fiori Advanced Development

description

BuildSAPFioriUIsWithSAPUI5_v2

Transcript of BuildSAPFioriUIsWithSAPUI5_v2

Page 1: BuildSAPFioriUIsWithSAPUI5_v2

Build SAP Fiori UIs with SAPUI5 Fiori Advanced Development

Page 2: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 3 Internal

Preparation Instructions

Bring your laptop. If you don’t have one, please ask your assistant for a pool laptop and make sure you are

maintained as an administrator. Alternative: ensure you can access your desktop remotely from a workstation in

the training room.

Install Chrome browser (recommended)

We will use Fiori productive Web IDE for practical parts: https://rde-

fiori.dispatcher.neo.ondemand.com/index.html (supported with Google Chrome and Firefox) – ensure you have

access (details on https://wiki.wdf.sap.corp/wiki/display/fiorisuite/Working+with+the+SAP+Web+IDE)

For the exercises, we will use services from Fiori Reference Applications. Please request your own user for

system QH3, Client 815 following the details described here:

https://wiki.wdf.sap.corp/wiki/display/refapps/Requesting+a+Reference+App+User

Page 3: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 4 Internal

Introduction Round

Introduce yourself to the class, stating:

Your name

Your JavaScript, UI5, Fiori experience

Your expectation(s) for this training

Page 4: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 5 Internal

Agenda

SAPUI5 Essentials

Fiori Design-Led Development

Fiori UI Architecture

Fiori UI Templates

OData Model/Databinding

Internationalization

Smart Controls

Navigation Concepts

Building your own UI5 Controls (Notepad Controls)

SAP Fiori Launchpad Application Developer Guide

Test-driven Development

Fiori Development Infrastructure

SAP Web IDE in detail

Fiori Reference Apps

UI Extensibility

Page 5: BuildSAPFioriUIsWithSAPUI5_v2

Learning Path

Page 6: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 7 Internal

Back-End Developer

Front-End Developer

0.0 S/4HANA Preparatory Trainings

Fiori Curriculum – Learning Path Overview

Product Owner

Quality Engineer

Manager

Scrum Master

Stay

Connected

0.0 S/4HANA ADVANCED Track

Ro

les

Fiori Back-End

Development Training

Online Education

0.0 S/4HANA BASIC Track

Learning Path HTML5

Fundamentals

Online Education

SAPUI5 Walkthrough

Online Education

Fiori Basic Training

Classroom Training (2 d)

Fiori Basic Training

Classroom Training (2 d)

Fiori Basic Training

Classroom Training (2 d)

Fiori Advanced

Development Classroom Training (4 d)

Additional Training

Material (Git/Gerrit)

Online and/or Classroom

Additional Training

Material

Online Education

Learning Path HTML5

Fundamentals

Online Education

SAPUI5 Walkthrough

Online Education

Fiori Curriculum Jam Group

Jam Group

Coming soon

Available

OData

Online Education

ABAP for SAP HANA

Online and/or Classroom

Page 7: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 8 Internal

Learning Path HTML5 Fundamentals

Product Owner, Quality Engineer, Manager, Front-End Developer, Back-End Developer

HTML5, JavaScript, CSS3, jQuery

Link to “Learning Path HTML5 Fundamentals”:

http://www.lynda.com/SharedPlaylist/e55aeecfad804868ae548ff77f933381

Page 8: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 9 Internal

SAPUI5 Walkthrough

Product Owner, Quality Engineer, Manager, Front-End Developer, Back-End Developer

• Introduction to all major development paradigms of SAPUI5

Model View Controller

Data Binding concepts

Navigation, extending controls, responsiveness

Testing features and built-in support tools

• Best practice for building apps with SAPUI5

Link to “SAPUI5 Walkthrough“ Jam Group:

https://jam4.sapjam.com/groups/about_page/00kUK9KKsby6oBVcyk5DBf

Page 9: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 10 Internal

OData – An introduction an Examples (1/2)

Developer, Development Architect, Product Owner

• Why do we need OData. This part provides you with a general overview of OData and the

benefits to SAP.

• A basic introduction to OData. After sharing our thoughts on why OData can be a helpful puzzle

piece to support SAP’s strategic goals, we will give you a basic introduction to OData.

• Structure of an OData service. In this section we explain the general structure of an OData

service and how data models are represented in the OData protocol.

• OData operations. Discussion of operations in OData, starting with read operations, and then

looking at create, update, delete, and other service operations.

• OData query language. We will finish with an introduction to the OData query language. Achieve

basic understanding for OData and why it is important to SAP

Link to “OData – An introduction an Examples“:

https://performancemanager5.successfactors.eu/sf/learning?bplte_company=SAP&_s.cr

b=kixvMHNzhL2UqTUiiOg/mjvDtcc%3d

Course No: 70196890

Page 10: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 11 Internal

OData Modeling – An outside in approach (2/2)

Developer, Development Architect, Product Owner

This eBook will provide you with best practice patterns for defining and modeling OData

Services

• Relation between Entity Relationship Models and OData

• The different model layers: Business Object -, Consumption - and OData Resource

Model

• How to define one single conceptual data model

• Short intro to the powerful Query Language

Achieve a basic understanding about how to model OData interfaces and what the

difference is compared to traditional back-end interface modeling

Link to “OData Modeling – An outside in approach“:

https://performancemanager5.successfactors.eu/sf/learning?bplte_company=SAP&_s.cr

b=kixvMHNzhL2UqTUiiOg/mjvDtcc%3d

Course No: 70211145

Page 11: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 12 Internal

ABAP Development on HANA – Classroom training (1/2)

Developers, Architects

• Optimization of classical ABAP in a HANA Context

• Performance Analysis Tools (Runtime Analysis/Profiling Perspective, Code Inspector,

SQL Monitor, SQL Performance Tuning Worklist)

• Performance Rules of ABAP for HANA

• Core Data Services in ABAP

• ABAP-managed Database Procedures

• Using ADBC (ABAP Data Base Connectivity) for native SQL

• Consuming HANA views and database procedures in ABAP

• Transporting HANA content via the ABAP stack

Link to “ABAP Development on HANA “:

https://performancemanager5.successfactors.eu/sf/learning?bplte_company=SAP&_s.cr

b=kixvMHNzhL2UqTUiiOg/mjvDtcc%3d

Course No: 70214721

Page 12: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 13 Internal

ABAP Development for SAP HANA – openSAP Course (2/2)

ABAP application developers / consultants, Development architects, anyone interested in

ABAP development for SAP HANA

Week 1:

Getting Started

Week 2:

ABAP Coding - Where to Optimize?

Week 3:

ABAP Coding - Ready, Set, Optimize!

Week 4:

Digging Deeper and Outlook

Link to “ABAP Development for SAP HANA “:

https://open.sap.com/courses/a4h1

Page 13: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 14 Internal

Fiori Basic Training

Product Owner, Quality Engineer, Manager, Front-End Developer, Back-End Developer

• UX Strategy

• Design Thinking

• Fiori Design

Guidelines

• Fiori Launchpad

• Architecture

• Application Types

• Basic Layouts

• Integration Aspects

Link to training material:

https://jam4.sapjam.com/groups/Prk7Nb7v6ZUNiuJxQui3wQ/documents/gZrmj90GCact

kifRG1M36z/slide_viewer

• Mobilizing

• SAP Web IDE

• Code-free SAPUI5

Introduction

• Introduction to OData

• Theme Designer

• Extensibility with SAPUI5

• UI Extensibility

• Data Extensibility

• Hybrid App Toolkit Add-On

• Fiori Extensions: Do’s and

Dont’s

• Reference Apps

• Building an App from a

Template

• Extending an Existing App

Page 14: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 15 Internal

Additional Training Material – A practical course on Git&Gerrit

Front-End Developer

This course makes you familiar with the basic principles of Git and the most-used

operations. It focuses on the background of Git, how it works internally before explaining

the operations Git supports. Moreover, it provides insight on how and why Git is different

compared to what developers are used in ABAP (please see a detailed description in

Success Map Learning)

Link to Success Map Learning

https://performancemanager5.successfactors.eu/sf/learning?destUrl=https%3a%2f%2fs

ap%2eplateau%2ecom%2flearning%2fuser%2fdeeplink%5fredirect%2ejsp%3flinkId%3d

ITEM%5fDETAILS%26componentID%3d70260258%26componentTypeID%3dCOURSE

%26revisionDate%3d1404129600000%26fromSF%3dY&company=SAP

Page 15: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 16 Internal

Fiori Advanced Development - Build SAP Fiori UIs with SAPUI5

Front-End Developer

• SAPUI5 Basics

• SAPUI5 in a Nutshell

• SAPUI5 Essentials

• Fiori UI Development

• Fiori Design-Led Development

• Fiori UI Architecture

• Fiori UI Templates

• OData Model/Databinding

• Internationalization

• SmartControls

• Navigation Concepts

• SAP Fiori Launchpad Application Developer Guide

• Building your own SAPUI5 Controls, Elements

(Notepad Controls)

• Additional Content

• Test-driven Development

• Fiori Development Infrastructure

• WebIDE in detail

• Fiori Reference Apps

• UI Extensibility

Link to training material:

https://jam4.sapjam.com/groups/Prk7Nb7v6ZUNiuJxQui3wQ/content?folder_id=wI7bP6

QjmCbUyNz3Ajw6Sm

Page 16: BuildSAPFioriUIsWithSAPUI5_v2

SAPUI5 Basics

Page 17: BuildSAPFioriUIsWithSAPUI5_v2

SAPUI5 in a Nutshell

Page 18: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 21 Internal

Trends in Web Development 2015

More websites – less coding. The manual coding

of websites by means of markup- and

programming language is waning.

Drweb.de

” The mobile, responsive web-design is still

a must have in 2015.

Drweb.de

About 42% of mobile application developers are using HTML, along with

JavaScript and CSS to build their apps.

Vision Mobile survey result from 2014

In 2015, websites will continue to be simplified, continue to put the focus on responsiveness

and dictate the way the user interacts with onpage content.

B2C

Open Source is leading the world.

InfoWorld

” Computing Everywhere. […] Gartner predicts an increased emphasis on

serving the needs of the mobile user in diverse contexts and environments.

Gartner

” Cloud is the new style of elastically scalable, self-

service computing, and both internal applications and

external applications will be built on this new style.

Gartner

Page 19: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 22 Internal

What is HTML5?

Third generation web content

HTML

• Static web pages

ITS, BSP, WDA JSP, WDJ

• Dynamic web content

• Server-side rendered

HTML5, SAPUI5

• Dynamic web content

• Client-side rendered

• Code on demand

• Data and UI separated

Page 20: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 23 Internal

Why HTML5?

Cross-platform Compatibility

Mobile Capabilities

SVG Maths Annotations

Drag & Drop

Web Sockets

Web Workers

Canvas

Web Messaging

“The Future of the Web is HTML5“ – Dean Hachamovitch, April 2010

Open Web Standard

Geolocation

Touch Event

Animation Timing

Media Capture

WAI ARIA

User Timing

Navigation Timing

Selectors RDFa

WOFF 1.0 CSS3

JavaScript

Indexed Database

Web GL

Multimedia Content Micro data

XMLHttpRequest2

Offline

Forms

File

HTML5 Markup

Asynchronous Processing

Interactivity

Multi-threading

Server Sent Event

Page 21: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 24 Internal

SAP UI Development Toolkit for HTML5 (SAPUI5) High-level overview

SAPUI5 is a client-side HTML5 rendering library including a rich set of controls and data-binding support to different models.

It combines new qualities like openness and flexibility with known SAP strengths like enterprise readiness and product

standard support.

Key Components

■ Runtime

Core (JS files, based on jQuery)

Control libraries (JS, CSS and image files)

■ Interactive documentation

■ Design-time (optional)

SAP contributes key elements of SAPUI5 to the Open Source community:

http://openui5.org http://sap.github.io/openui5

Page 22: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 25 Internal

SAPUI5 Key capabilities

■ Next-generation UX controls for desktop and mobile

■ Responsive design

■ Distinct features like OData support, localization and

calculated properties

■ Mock Server to mimic OData back-end calls

■ Comprehensive extensibility concept

■ Predefined themes

■ Compliant with all SAP product standards

■ Lightweight programming model

■ Compatible with major web browsers and devices*

■ Server-agnostic

■ Backwards compatible (release-independent component)

Available for free with OpenUI5

*for details please read the product availability matrix for SAPUI5

Page 23: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 26 Internal

Distinction Between SAP Fiori® and SAPUI5

SAP’s preferred way to build

the UI for SAP Fiori apps is

by using the SAPUI5 toolkit

or technology.

Concept

Role-

based Simple Responsive Coherent Delightful

Technology Design

Information

Architecture

Visual

Design Interaction

Patterns User Interface

Business Logic

SAP Fiori®

SAP’s intent to deliver consumer-

grade user experience to our

business transactions across

devices is represented by SAP Fiori.

Page 24: BuildSAPFioriUIsWithSAPUI5_v2

SAPUI5 Essentials Recap of SAPUI5 Essentials following the SAPUI5 Walkthrough tutorial

Page 25: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 29 Internal

SAPUI5 Demo Kit http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5-sdk-dist/

SAPUI5’s Demo Kit provides a comprehensive overview of

the SAPUI5 framework and consists of the following sections:

■ Developer Guide: Main documentation on SAPUI5

■ Controls: Samples with code snippets on how to use various

lib controls e.g. sap.ui.ux3, sap.ui.table, sap.ui.layout

■ Explored: A quick run through all major controls with

examples and code snippets

■ API Reference: Documentation of framework and control

APIs

■ Demo Apps: Some selected showcases

■ Icons: A quick run through all of SAPUI5’s built-in icons

■ Credits: List of 3rd party open source software from different

sources used by SAPUI5

■ Version Info: List of libraries along with their versions

Page 26: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 30 Internal

SAPUI5 Explored http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5-sdk-dist/explored.html

Filter

Release

Category

Controls

Available Samples

Control Metadata

Component

Properties

Aggregations

Methods

Preview

Shows the sample

page…

Source

Source (View,

Controller etc.)

Download

Setitngs

Theming

Compact Factor

Full-Screen

Page 27: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 31 Internal

SAPUI5 Test Suite http://veui5infra.dhcp.wdf.sap.corp:8080/uilib-sample/test-resources/testsuite/testframe.html

Test Navigation

All test cases

detected in the

current Demo Kit

version

Manually add

additional test

cases by entering

the URL

Settings

Theme used for

rendering

Render mode

Right-to-left (a.k.a.

RTL) support

Content

Shows the test

page…

Trace

SAPUI5

framework trace

(event etc.)

Control Tree

Select a node

Property

Properties of the

related control

selected in

Control Tree View

Change

properties

Advanced

Open in new

window

Change layout of

Test Suite

Device simulator

Edit in Snippix

Execute QUnit

Page 28: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 32 Internal

snippix - SAPUI5 Code Snippet Sharing http://veui5infra.dhcp.wdf.sap.corp:8080/snippix

Editor

SAPUI5 code editor

Syntax highlighting

Code completion

Preview

Preview of the

HTML page

Updates this

preview as you type

Detects JavaScript

errors

Start

Access a snippet

directly

(snippix/#92557)

Import arbitrary web

pages

(snippix?url=…)

Run your code in

preview

Save your snippet and

send to others as a

web link

Preview in New Tab

Allows debugging

Short lifecycle

Load Template

Offers several

templates as a

starting point

Advanced

List all available

snippets

Choose the SAPUI5

version to be used

Device simulator

Test Suite

Page 29: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 33 Internal

SAPUI5 Development Environment SAP Web IDE

It is equipped with the following features:

› Dynamic interactive features, code completion, wizards and

API reference support

› Instant preview and mock data support

› Jam-based team communication

› Revision control and source code management through Git

› User-centric customizability and session persistency

› Integrated deployment to ABAP and SAP HANA Cloud

Platform

› Extensible and modular architecture

Adding value by offering the following benefits:

› Develop once, deploy everywhere and run on any device

› Increased development efficiency

› Easy ramp up via SAP HANA Cloud Trial

› Designed for developers, business experts and designers

SAP Web IDE is a browser-based tool used to rapidly design, build, extend and deploy SAPUI5.

Page 30: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 34 Internal

SAPUI5 Development Environment Eclipse-based tooling*

These include features like:

› Wizards for application development

› Code completion and templates for SAPUI5

control-specific JavaScript and XML code

› SAPUI5 snippets as prepared HTML pages

› Quick Fixes to display the API reference

› Wizards for control development

› Application preview with embedded Jetty server

› Team provider for BSP repository

› Also available for SAP HANA Studio

The SAPUI5 development tools are Eclipse plug-ins which simplify the development process for

SAPUI5 applications and controls.

Prerequisite1: Eclipse Luna (4.4) or Kepler (4.3); Windows OS (XP, Vista, or 7), 32 or 64-Bit; JRE 1.6 or higher, 32 or 64-Bit (same as Eclipse)

1 as of March 2015, for details check the SAP Development Tools on Eclipse page *Eclipse-based tooling is in maintenance

Page 31: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 35 Internal

SAPUI5 Tutorials

SAPUI5’s Demo Kit provides a full set of tutorials

■ Learn how to develop applications with SAPUI5

■ Introducing you to all major development paradigms and

fundamental concepts of SAPUI5

■ SAPUI5 Walkthrough

■ Basic development paradigms

■ Basic structure of an application

■ Data-binding concepts

■ Navigation, extending controls, making an app responsive

■ Best practices for application development

■ Testing features

■ Code in Explored

Page 33: BuildSAPFioriUIsWithSAPUI5_v2

Step 1: Hello World!

Page 34: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 38 Internal

Basic HTML 5 Page Template

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<!-- Head Content -->

</head>

<body>

<!-- Body Content -->

</body>

</html>

Regarding charset, see e.g. http://webdesign.about.com/od/metatags/qt/meta-charset.htm

Page 35: BuildSAPFioriUIsWithSAPUI5_v2

Step 2: Bootstrapping

Page 36: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 40 Internal

SAPUI5 Bootstrap Initializing and loading SAPUI5 in an HTML5 template

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<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-resourceroots ='{ "sap.ui5.training": "./" }' > </script> </head> <body>

</body>

</html>

bootstrap

SAPUI5 apps load the SAPUI5 runtime with the bootstrap:

Page 37: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 41 Internal

Bootstrap

SAPUI5 Bootstrap Components loaded by the bootstrap

Control

SAPUI5

Libraries

SAPUI5

Core

jQuery

SAP jQuery Plug-ins

Event Resources Device Logger Utils

UI

Core Base Model

Theme Theme Library

Control Libraries

data-sap-ui-theme

data-sap-ui-libs

src

jQuery.UI

jQuery Mobile

Page 38: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 42 Internal

What is jQuery? https://jquery.com/

Browser Dependencies

■ Different stages of HTML(5) and CSS(3) implementations

■ Different implementations of event handling

■ Known browser bugs

■ Browsers support different sets of CSS selectors

Solution

■ Frameworks and toolkits provide an easy way to re-use code

■ Based on JavaScript

■ You don’t need to re-invent the wheel!

Page 39: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 43 Internal

Introduction to SAP Web IDE Accessing SAPUI5 resources in the SAP Web IDE application descriptor neo-app.json

To access SAPUI5 resources in your

HTML5 application, configure the location of

the SAPUI5 resources in the SAP Web IDE

application descriptor called neo-app.json.

This application descriptor must be located

in the root folder of the repository.

Use snapshot version to use the latest

nightly build version of the SAPUI5

resources, which is SAP internal only.

"routes": [ { "path": "/resources", "target": { "type": "service", "name": "sapui5", "version": "1.30.0", "entryPath": "/resources" }, "description": "SAPUI5 Resources" } ]

neo-app.json

"version": "snapshot",

SAP Web IDE Documentation -> Develop -> Developing

Applications -> Creating a Cloud Connectivity Configuration File

Page 40: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 44 Internal

Useful UI5 Core Functions

sap.ui.getCore() › Gets a core instance

sap.ui.getCore().byId(id) › Gets an instance of all SAPUI5 controls which were created with ID

› Can be used to access removed controls (even though the ID no

longer exists in the DOM)

› Do not use it within Fiori apps (see MVC in Fiori)

sap.ui.getCore().applyChanges() › Carries out and renders the changes for SAPUI5 controls

immediately, before the runtime would do it (use carefully and only

for testing)

sap.ui.getCore().getConfiguration() › Returns the configuration settings of the core

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8" />

<script src="resources/sap-ui-core.js"

id="sap-ui-bootstrap"

data-sap-ui-modules="sap.m.library"

data-sap-ui-theme="sap_bluecrystal">

</script>

<script>

sap.ui.getCore().attachInit(function () {

var btn = sap.m.Button({text:"Order Now"})

btn.placeAt("content"); }

</script>

</head>

<body class="sapUiBody" id="content"/>

</html>

Page 41: BuildSAPFioriUIsWithSAPUI5_v2

Steps 3-5: MVC

Page 42: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 46 Internal

SAPUI5 Runtime Main control libraries

sap.ui.layout: Library featuring layout

controls (screenshot: sap.ui.layout.Grid)

sap.m: Leading control library for mobile and

mixed scenarios, used for SAP Fiori

(screenshot: sap.m.ObjectHeader)

sap.ui.unified: Library featuring generic

controls (screenshot: sap.ui.unified.Shell)

sap.ui.ux3*: Library containing UX3 pattern

(screenshot: sap.ui.ux3.Shell)

sap.ui.table: Library featuring table controls

(screenshot: sap.ui.table.Table) sap.ui.commons*: Library for pure

desktop scenarios (screenshot:

sap.ui.commons.Panel)

As these libraries are in maintenance,

don’t use them in new Fiori apps!

Page 43: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 47 Internal

SAPUI5 Control Library View structure

Multiple libraries can be combined within one application:

DetailPage control

(sap.m.semantic)

ObjectHeader control

(sap.m)

SimpleForm control

(sap.ui.layout.form)

IconTabBar control

(sap.m)

Table control

(sap.m)

VerticalLayout control

(sap.ui.layout)

ProgressIndicator control

(sap.m)

SplitContainer control

(sap.m)

MasterPage control

(sap.m.semantic)

List control

(sap.m)

Page 44: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 48 Internal

Model View Controller

Data

View

Model Controller

user interaction

update

update

notify

data

binding

data

handling

SAPUI5 applications use the Model View Controller concept to separate the view logic from the

application logic and model definition

Page 45: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 49 Internal

SAPUI5 View Types For Fiori: ONLY XML views shall be used

View Types

Javascript ViewType.JS

JSON ViewType.JSON

XML ViewType.XML

HTML ViewType.HTML

Declarative

View

Javascript Code

Views

View Controllers

var view = sap.ui.view({id:"myXMLView",

viewName:"sap.ui5.training.view.myXMLView",

type: sap.ui.core.mvc.ViewType.XML}); view/myXMLView.view.xml

will look for file

under the resource path for namespace sap.ui5.training, as

defined in bootstrap

File Location Logic

Template ViewType.Template

Page 46: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 50 Internal

Example XML View sap.ui.core.mvc.ViewType.XML

<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc" xmlns:core="sap.ui.core" controllerName="sap.ui5.training.controller.myViewController"> <Page title="Title"> <content> <Button id="myXMLButton" text="Click Here" press="onPress"/> <core:Icon src="sap-icon://syringe"> <mvc:XMLView viewName="sap.ui5.training.view.myOtherXMLView"/> </content> </Page> </mvc:View>

XM

L V

iew

JS

var view = sap.ui.xmlview({

id :"myXMLView", viewName :"sap.ui5.training.view.myXMLView"

});

Default namespace (sap.m)

Namespace with alias (e.g. sap.ui.core)

Reference to the controller

Declarative definition of the root control

Declarative instantiation of a view

JS Code-based instantiation of a view

Call event handler in controller

Page 47: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 51 Internal

View Controllers

View Controllers › Controllers are written in Asynchronous Module

Definition (AMD) syntax

› Contain custom event handlers for the view

› These event handlers are prefixed with “on”

› Can contain event handlers which are called by

the SAPUI5 core framework

onInit(oEvent)

is called when the view is first instantiated

onBeforeRendering(oEvent),

is called just before the view is rendered

onAfterRendering(oEvent),

is called just after the view has been rendered (injected into the DOM)

onExit(oEvent), fired when the controller is destroyed and can be used to free up resources

sap.ui.define(['sap/ui/core/mvc/Controller'],

function(Controller) {

"use strict";

return Controller.extend("sap.ui.demo.wt.controller.App",{

onInit: function(oEvent){};

onBeforRendering: function(oEvent){};

onAfterRendering: function(oEvent){};

onExit: function(oEvent){};

onShowHello : function (oEvent) {

alert("Hello World");

}

});

});

Controller.js

Page 48: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 52 Internal

Know Your Browser

Document Object Model (DOM) is a platform-neutral and language-neutral interface that allows scripts

and programs to dynamically access and update the content, structure, and style of a document

A Document Object represents the HTML document that is displayed in that window

JavaScript can be used to access and manipulate the HTML DOM objects

JavaScript was formalized in the ECMAScript language standard and

is primarily used as part of a web browser

Browsers render the web page in there own

Document Object Model (DOM) implementation

and have their own Javascript engine

Page 49: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 53 Internal

IDs for Controls

Static unique IDs are used to identify and modify the controls within the controller during runtime.

IDs are either generated automatically or given as string constants by the application developer.

To avoid conflicts, all IDs in MVC views that are given as static strings inside the declarative views

(XML, HTML, JSON) are automatically prefixed with the view ID and '--'.

To avoid problems with other tools (for example automated UI tests (Selenium, One Page

Acceptance Test (OPA5) and xRay documentation), create stable IDs and don’t use IDs that are

generated automatically

If you want to modify the control with the ID <ID>, you can call the byId(<ID>) method on your

view to get the correct control directly. You do not have to handle the prefix on your own.

<mvc:View id="myView" controllerName="sample.App" xmlns="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"> ... <Icon id="myIcon" src="sap-icon://message-warning" > ... </mvc:View>

... var myIcon = this.getView().byId("myIcon"); // Don’t use // var myIcon = sap.ui.getCore().byId("myView--myIcon"); ... X

ML

Vie

w

JS

Page 50: BuildSAPFioriUIsWithSAPUI5_v2

Step 6: Modules

Page 51: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 55 Internal

sap.ui.define

Controllers are written in Asynchronous Module Definition (AMD) syntax

Use sap.ui.define to define a JavaScript module with its name, its dependencies and a module value or

factory

The first parameter sap.ui.define is an array of the required SAPUI5 libraries. These libraries can be loaded

asynchronously. The second parameter is the callback function when all required SAPUI5 libraries are loaded.

sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast"],

function(Controller, MessageToast ) {

"use strict";

return Controller.extend("sap.ui.demo.wt.controller.App",{

onInit: function(oEvent){};

onBeforRendering: function(oEvent){};

onAfterRendering: function(oEvent){};

onExit: function(oEvent){};

onShowHello : function (oEvent) {

MessageToast.show("Hello World"); }

});

});

Controller.js

Required libraries

Callback function

Page 52: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 56 Internal

Troubleshooting http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5-sdk-dist/docs/guide/6ec18e80b0ce47f290bc2645b0cc86e6.html

SAPUI5 Diagnostics CTRL + ALT + SHIFT + S

CTRL + ALT + SHIFT + P

Technical

SAPUI5 release

Bootstrap

parameter

Load modules

Load Debug

Sources

Control Tree

CTRL + ALT + SHIFT

+ Control

Properties

Binding infos

Export as XML

Debugging: https://www.youtube.com/watch?v=CmIXJldq8J4

http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5-sdk-dist/docs/guide/c9b0f8cca852443f9b8d3bf8ba5626ab.html

http://discover-devtools.codeschool.com/ (Chrome DevTools Code Scool)

Page 53: BuildSAPFioriUIsWithSAPUI5_v2

Step 7: Data Binding - Model

Introduction

Page 54: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 58 Internal

SAPUI5 Models

Introduction

Data

View

Model Controller

user interaction

update

update

notify

data

binding

data

handling

A model holds the data and provides methods to retrieve the data from the data source and to

set and update data. › An SAPUI5 application supports several different data

sources, like XML, JSON and OData.

› SAPUI5 supports data binding between Views and Models,

which is used to bind two data sources or information sources

together and to keep them in sync.

› Within SAPUI5, the way in which data binding is defined and

implemented within the UI controls is uniform and independent

of the respective data source.

› Within an SAPUI5 application, it is possible to use more than

one model for data binding to SAPUI5 controls.

› You can also create a custom model implementation for data

sources that are not yet covered by the framework or are

domain-specific. You can implement them by extending the

sap.ui.model.Model

Page 55: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 59 Internal

Data Binding Model types

Model

Client

Model

XML JSON Resource Message OData

OData

MetaData

Control

Server-Side Client-Side Helper

Device

Page 56: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 60 Internal

Model in client operation mode (Client-side Model) Example: JSON model

The JSON model can be used to bind UI controls to JavaScript object data.

It is a model intended for small datasets that are completely available on the client.

Usually a serialized JSON string is used as a data source.

By default, the JSON model supports two-way binding.

{ firstName: "John", lastName: "Smith" }

JSONModel UI Controls bind set data

JSON Data Model View

Dear John Smith John Smith

firstName lastName

Page 57: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 61 Internal

Creating a Model Instance Model instantiation

To use data binding in an SAPUI5 application, you first need to instantiate an appropriate model. This is done by the framework automatically when you specify models in the sap.ui5 part of the app

descriptor.

var oJSONModel = new sap.ui.model.json.JSONModel(sData);

var oXMLModel = new sap.ui.model.xml.XMLModel(sData);

var oODataModel = new sap.ui.model.odata.v2.ODataModel(sData, {});

{ ...

"sap.app":

{ ...

"dataSources":

{

"invoiceRemote":

{ "uri": “/services.odata.org/V2/Northwind/Northwind.svc/",

"type": "OData",

"settings": { "odataVersion": "2.0" }

}

}

},

...

"sap.ui5": {

...

"models":

{

"invoice" : {

"dataSource": "invoiceRemote"

}

}

}

}

App Descriptor: manifest.json

If the model isn’t specified in the app descriptor,

you can instantiate one by using an assign data to

your own model in the code. The constructor takes

the URL of the model data or the data itself as the

first parameter.

JS

Page 58: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 62 Internal

One-Way Binding Mode

In SAPUI5, DATA BINDING is used to bind SAPUI5 controls to a data model that holds the application data, so

that the controls are updated automatically whenever the model data is changed

One-way binding When one-way binding is used, only changes

to the data in the model will change the data in all

bound UI controls. If the data is changed in the control, the data in the model will remain unchanged. To change the data in

the model, you need to update this data by coding.

One-time binding

When one-time binding is used, only first setting

the data in the model will change the data in all

bound UI controls. If the data is changed in a control, the data in the model and other controls will remain unchanged. To

change the data in the model, you need to update this data by coding, but the bound controls will not change.

Two-way binding

When two-way-binding is used, the model data is updated

whenever the value of a bound control changes,

e.g. through user input.

Page 59: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 63 Internal

Setting Models

A model can be set to the core, component controller, a view or a UI control using the setModel(oModel) method

It is possible to set multiple models by specifying individual

names for the models, which are used to identify them

All controls and views will inherit the (named) models of

their parent. You can set models with the same name on

multiple UI controls, but this name must be unique on one

control. If you set a model with the same name, the original

model will be replaced by the new model and parent

models will be overruled

View

Controls (aggregation)

Controls (element level)

Controls (property level)

SAPUI5 Core

Component

Controller

C V A E P U Set Model to

Model can

be used by var oView = this.getView(); oView.setModel(oModel);

var oView = this.getView(); oView.setModel(oModel, "myModel");

Page 60: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 64 Internal

Binding Controls to the Model Primitive binding types

To retrieve data from the model for visualization on the UI, the controls have to be bound to the

model by means of a binding path.

For binding controls to the model, several primitive binding types exist:

Property binding allows properties of the control to get automatically initialized and updated from model

data.

Element binding allows you to bind elements to a specific object in the model data, which creates a

binding context and allows relative binding within the control and all of its children.

Aggregation binding can be used to automatically create child controls according to model data. This can

be done either by cloning a template control, or by using a factory function.

Page 61: BuildSAPFioriUIsWithSAPUI5_v2

Step 8: Translatable Texts

Page 62: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 66 Internal

i18n Resource Files

Resource files are used to store language-dependent texts and property values.

The files contain key/value pairs where the values are the language-dependent texts and the keys

are language-independent and used by the application to identify and access the corresponding

values.

A value can have a placeholder, entered between curly brackets, which will be replaced at runtime.

Special characters must be HTML-encoded.

shellTitle=Approve Requests masterTitle=Approve Requests ({0}) submit=Submit ok=OK submitDecision=Submit Decision msgDecisionQuestion=You have selected "{0}".

shellTitle=Antr\u00E4ge genehmigen masterTitle=Antr\u00E4ge genehmigen ({0}) submit=Best\u00E4tigen ok=Best\u00E4tigen submitDecision=Entscheidung best\u00E4tigen msgDecisionQuestion=Sie haben "{0}" ausgew\u00E4hlt.

i18n_de.properties i18n_en.properties

Page 63: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 67 Internal

I18n Resource Files Naming conventions

Resource files are a collection of *.properties files. All files are named

with the same base name, an optional suffix that identifies the language

contained in each file, and the fixed .properties extension. The language

suffixes are formed using SAPUI5 language codes.

By convention, a file without a language suffix should exist and contain

the raw untranslated texts in the developer's language. This file is used

if a more suitable language cannot be found.

When a localized text is needed, the application uses the SAPUI5 APIs to load the properties file

that matches the current language best. If no text can be found for this key, the next best matching

file is loaded and checked for the text. Finally, if no file matches, the raw file is loaded and checked.

i18n_en_US.properties

i18n.properties

Page 64: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 68 Internal

i18n Resource Bundle

Use the getResourceBundle method to get access to the Resource Bundle to access localized

texts.

Use the getText(skey,aParameters) method to access the texts by means of their key.

If a text has one or more placeholders, you can specify an array of strings using the second

parameter. These strings will then replace the placeholders in the text:

var oBundle = this.getModel("i18n").getResourceBundle();

var sText = oBundle.getText("Submit");

var sText = oBundle.getText("MasterTittle", ["12"]);

en_US: Submit de: Bestätigen

en_US: Approve Requests (12) de: Anträge genehmigen (12)

Page 65: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 69 Internal

i18n Resource Model Generic use

The Resource Model is a wrapper for i18n resource files that exposes the localized texts as a model for data

binding, just like other models.

You can instantiate the model in the app descriptor or

use sap.ui.model.resource.ResourceModel .

You instantiate the Resource Model with a bundleName.

This name is the SAPUI5 notation of a file location without

the suffix '.properties'. E.g. the file i18n.properties in

directory /i18n of project sap.ui5.training becomes sap.ui5.training.i18n.i18n.

You can now bind text just like other models.

Helper formatter function jQuery.sap.formatMessage can be used to replace placeholders in a Resource

Model.

var sBundleLocale = sap.ui.getCore().getConfiguration().getLanguage(); var sBundleName = "sap.ui5.training.i18n.i18n"; var oResourceModel = new sap.ui.model.resource.ResourceModel({ bundleNamel: sBundleName , bundleLocale: sBundleLocale}); oControl.setModel(oResourceModel,"i18n");

<Page title="{i18n>SHELL_TITLE}"> <content> <TextView text="({parts:[{path: 'i18n>MY_TEXT'},{path: '/appstatus'}], formatter: 'jQuery.sap.formatMessage'})"/> <Button id="myXMLButton" text="{i18n>MY_LABEL}" press=".onPress"/> </content> </Page>

Page 66: BuildSAPFioriUIsWithSAPUI5_v2

Steps 9-10: Component and

App Descriptor

Page 67: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 71 Internal

SAPUI5 Apps as Component

SAPUI5/Fiori apps are component-based and have

a component controller

App descriptor contains application-specific

configuration settings

SAPUI5 apps can have more than one model and

can use different model types

Model instantiation via app descriptor

SAPUI5 views are built with controls and can have

a view controller to handle events

Reusable view content can be

grouped in fragments

and can be reused in views

Different view types can be used

in one application

View

View

Controllers

Models

Component

Controller

Models Models

View View

View

Controllers

Fragments Controls Controls

Component

Container

Fiori Launchpad

Fiori App

app descriptor

Page 68: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 72 Internal

Create a New Component – Component.js

sap.ui.define([

'sap/ui/core/UIComponent'

], function(UIComponent) { "use strict";

return UIComponent.extend("samples.project.Component", {

metadata: {

manifest: "json"

},

/**

* The component is initialized by UI5 during the startup of the app and calls the init method

* once. The resource and application models to be set and the router to be initialized.

* @public

* @override

*/

init: function() {

// call the base component's init function

UIComponent.prototype.init.apply(this, arguments);

// put your code here

},

/**

* In this function, the rootView is initialized and stored.

* @public

* @override

* @returns {sap.ui.mvc.View} the root view of the component

*/

createContent: function() {

// call the base component's createContent function

var oRootView = UIComponent.prototype.createContent.apply(this, arguments);

// put your code here

return oRootView;

}

});

});

The component is named Component.js

The app descriptor file is named

manifest.json

Together with all assets of the app,

these files are located in the app folder

(root folder of the app) – Do not move to

any subfolder!

Component members:

› metadata: Simply defines a reference to

the app descriptor (manifest.json)

› init function: Called when the component

is initialized.

› createContent function: You can

optionally override the initialization of the

root view (root view defined in the app

descriptor)

Page 69: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 73 Internal

App Descriptor “Code” Document

“Code” Document

Descriptor for Applications,

Components, and Libraries aka “app

descriptor”

File called manifest.json

Contains all global application

settings and parameters e.g. the app

ID, name, version, used data sources

and SAPUI5 dependencies

Created with the application at

development, delivered within the

application and read-only after

delivery

Part of the Fiori Guidelines

Developer Guide: http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/#docs/guide/be0cf40f61184b358b5faedaec98b2da.html

Descriptor Migration: http://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/AdvancedTopics/Manifest

Page 70: BuildSAPFioriUIsWithSAPUI5_v2

Step 11: Pages and Panels

Page 71: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 76 Internal

A UI control is an object that defines the appearance and behavior of a screen area.

UI controls either inherit from core control class sap.ui.core.Control or from another control, in order

to inherit and extend its functionality.

A UI control typically has properties like "text" or "width" that modify the appearance or relate to the

data displayed by the UI control.

It can aggregate other UI controls. This means it is a sort of container or layout UI control when the

application can add the child controls to use - or a composite UI control if the UI control itself

decides what the child UI controls are and just reuses these available components.

It can also have associated UI controls that are not part or children of this UI control, but rather

loosely related.

A UI control can fire well-defined events. Typically, these have a meaning that relates to the

control's purpose and functionality and is on a semantically higher level than "click" or other

browser events. Examples would be search in sap.m.SearchField or expand in sap.m.Panel.

What is a UI Control?

Page 72: BuildSAPFioriUIsWithSAPUI5_v2

Step 13-14: Margins and

Paddings, CSS

Page 73: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 78 Internal

CSS Box Model

Each box has a content area (e.g. text, an image) and optional surrounding padding, border, or

margin areas.

The final width (or height) of an element is the sum of the margin, padding, border and the given

width (or height).

http://imagecss.com/

Page 74: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 79 Internal

Margin/Padding CSS Classes Features

As of SAPUI5 1.28, SAPUI5 libraries let you influence spacing in between controls and within containers by using predefined

CSS margin/padding classes.

Benefits

Consistent spacing around controls and

within containers across layouts

Related features in SAPUI5:

List of predefined CSS classes to add full,

single-sided, two-sided and responsive

margins, or remove margins

All predefined margin CSS classes support

right-to-left (RTL) languages

Predefined CSS classes to add (responsive)

or remove content padding

Page 75: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 80 Internal

Margin/Padding CSS Classes Responsiveness

Responsive padding for containers Responsive margin for controls

Use standard margin and padding classes of SAPUI5

Page 76: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 81 Internal

General CSS Recommendations

App-specific CSS for SAPUI5 HTML

Restrict that type of CSS to a minimum, use standard margin and padding classes of SAPUI5

CSS for SAPUI5 HTML is problematic (see SAPUI5 Compatibility Rules):

The internal SAPUI5 control DOM structure does not represent a stable contract

Only margins/paddings defined for the top level control container (added via addStyleClass(…)) are assumed to be

reliable

If, from a UX design perspective, an SAPUI5 control needs to be enhanced in your app context, contact your CoE in order

to discuss potential solutions:

Search for a UI alternative Include your UX Designer

Request an API-based extension from the SAPUI5 control provider

Think of using a complete own control implementation (control inheritance is not provided as a stable contract)

Ensure standard compatibility

BiDi Support for RTL languages

Ensure multi-theme support

Support Blue Crystal and High Contrast Black( HCB) themes

Support customer themes

Page 77: BuildSAPFioriUIsWithSAPUI5_v2

Steps 16-19: Dialogs and

Fragments

Page 78: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 83 Internal

Fragments Example XML fragment used by an XML view

<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" > <Page title="Title"> <content> <Button id="myXMLButton" text="Click Here" press=".onPress"></Button> </content> </Page> </core:FragmentDefinition>

XM

L

Fra

gm

en

t X

ML

Vie

w

An XML view

which calls an

XML fragment <mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc“ xmlns:core="sap.ui.core"> <core:Fragment fragmentName=" sap.ui5.training.view.myXMLFragment" type="XML" /> </mvc:View

Fragments are light-weight UI parts (UI subtrees) which can be reused, defined similar to views, but

do not have any controller or other behavior code involved. If any behavior such as event handlers is

needed, they should be used in a view and be able to connect to existing controllers of this view.

Page 79: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 84 Internal

Dialog as Fragment

Besides the use of fragments within a view, the result of an UI5 fragment instance is a dialog control

which can be used like any popup.

You can open this popup dialog by calling the open() method of the fragment.

var xmlDialog = sap.ui.xmlfragment( "sap.ui5.training.view.myXMLDialogFragment", oController);

this.getView().addDependent(xmlDialog);

xmlDialog.open();

JS

<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" > <Dialog title="My Dialog"> </Dialog> </core:FragmentDefinition>

XM

L

Fra

gm

en

t

Page 80: BuildSAPFioriUIsWithSAPUI5_v2

Step 20: Aggregation Binding

Page 81: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 86 Internal

Aggregation Binding

Aggregation binding is used to bind a dataset like multiple rows to a UI control that supports

aggregation, for example tables, lists or pulldown controls.

For this, you bind the collection using the bindAggregation(sPath, oTemplate) method of the

control. The UI template consists of at least one other UI control, which will be used as a repeated

list item.

Aggregations can only be bound to datasets defined in the model, that is, to multiple tags with the

same name in XML, to arrays in a JSON model, or a collection

in the OData model.

Dataset UI Template

+

{ company: { contact: [ { name: "Barbara", phone: "873" }, { name: "Gerry", phone: "734" }, { name: "Susan", phone: "275"} ] }}

=

UI Table

Page 82: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 87 Internal

Aggregation Binding Example

<Table id="idTable" items="{/company/contact}"> <columns> <Column> <Text text="Name" /> </Column> <Column> <Text text="Phone" /> </Column> </columns> <items> <ColumnListItem vAlign="Middle" type="Active"> <cells> <Text text="{name}" wrapping="false" /> <Text text="{phone}" /> </cells> </ColumnListItem> </items> </Table>

XM

L V

iew

Aggregation Binding to Items

UI Template Property Binding

Property Binding

Page 83: BuildSAPFioriUIsWithSAPUI5_v2

Step 21: Data Types

Page 84: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 89 Internal

Data Typing Data type process

01.05.2015 01-05-2015

Parse

Format

Validate

20150501

BACK-END FORMAT SAPUI5 MODEL FORMAT DISPLAY FORMAT

n/a

Data typing is important because the internal SAPUI5 model data format doesn’t have to be the

same format in the back-end system as the data format you want to present on the UI.

Data binding supports the definition of types which can be handed over when binding properties.

Bound properties with a defined type will automatically be formatted when displayed on the UI, input

values in UI controls are parsed and converted back to the defined type in the model.

Page 85: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 90 Internal

Data Typing Example data type events

... var oText = this.getView().byId("myInput"); sap.ui.getCore().attachValidationError(function(e){ var oElement = e.getParameter("element"); if (oElement.setValueState){ oElement.setValueState(sap.ui.core.ValueState.Error); }}); oText.attachValidationSuccess(function(e){ var oSource = e.getSource(); if (oSource.setValueState){ oSource.setValueState(sap.ui.core.ValueState.None); }}); oText.attachParseError(function(e){}); oText.attachFormatError(function(e){}); ...

React to all typed UI controls

React to the specifically-typed

UI control only

<Label text="Number" /> <Input id="myInput" value="{ path:'/number', type:'sap.ui.model.type.Float', formatOptions: { minIntegerDigits: 3 }, constraints:{ minimum:1000 } }"/>

Set validation constraints

Set formatting options

JS

XM

L V

iew

Page 86: BuildSAPFioriUIsWithSAPUI5_v2

Step 22: Expression Binding

Page 87: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 93 Internal

Expression Binding Simple example

The following example shows how you use the custom formatter function to map an XML view to an

expression binding in the XML view without any controller logic.

In previous approaches, you needed both an XML view and view controller logic:

When using expression binding, however, you only need the XML view and no controller logic:

<mvc:View controllerName="sample.App" xmlns="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"> ... <Icon src="sap-icon://message-warning" visible="{path:'status', formatter:'.myFormatter'}"> ... </mvc:View>

... myFormatter: function(sStatus) { return sStatus === "critical"; } ...

<mvc:View controllerName="sample.app" xmlns="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"> ... <Icon src="sap-icon://message-warning" visible="{= ${status} === 'critical' }"> ... </mvc:View> X

ML

Vie

w

JS

XM

L V

iew

Page 88: BuildSAPFioriUIsWithSAPUI5_v2

Step 23: Custom Formatters

Page 89: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 95 Internal

Calculated Fields

The calculated fields feature allows you to bind multiple properties in different models (parts) to

a single property of a control.

The application can access these values in a formatter function and can decide how they should

be processed or combined together:

<Text text="{ parts:[ {path: '/number'}, {path: '/unit'}], formatter: '.myFormatter'}" />

112 cm

112 CM

number unit

XM

L V

iew

myFormatter: function(iNumber, sUnit){ if (iNumber > 0) { return iNumber + " " + sUnit.toLowerCase(); } else { return ""; } }

JS

Page 90: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 96 Internal

Calculated Fields Extended binding syntax

The extended binding syntax can be used in XML views

It needs to be switched on first via the configuration flag xx-bindingSyntax="complex" or sap-ui-

compatVersion= "edge" within the bootstrap. For SAP Fiori launchpad, this is already configured.

You can also combine this extended syntax with formatters if you want to modify the values before

displaying:

<TextView text="Hello {firstname} {lastname} "/>

<TextView text="{parts: [{path:'i18n>helloMsg'},{path:'firstname'},{path:'lastname'}], formatter: 'jQuery.sap.formatMessage'}"/>

XML View

XML View

helloMsg=Hello {0} {1}! i18n.properties

Page 91: BuildSAPFioriUIsWithSAPUI5_v2

Steps 24-25: Filtering, Sorting,

Grouping

Page 92: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 98 Internal

Filtering

Binding results of an aggregation can be restricted using filters

like where clauses in an SQL statement.

An array of sap.ui.model.Filter can be used to build the

where clause. The filters support and and or operators.

sap.ui.model.FilterOperator can be used to assign a

property and the filter value. SAPUI5 supports various operators like

EQ, NE, LT, LE, GT, GE, BT, Contains, StartsWith and EndsWith.

Filter

<Table id="idTable" items="{ path:'/company/contact', filters:[ { path: 'name', operator: 'EQ', value1: 'Barbara', and: true },{ path: 'name', operator: 'EQ', value1: 'Susan', and: true } ] }"> ... </Table>

XM

L V

iew

Page 93: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 99 Internal

Binding results of an aggregation can be ordered using a sorting

like order by in an SQL statement.

An array of sap.ui.model.Sorter(sPath, bDescending?, vGroup) can be used to perform this sorting.

When building a sorter, you can specify the descending

parameter to define if the sort is descending (true) or ascending (false).

Grouping the sorted content can either be set to true to enable grouping based on the raw model

property value, or a function which calculates the group value out of the context.

Sorting

a

b

d

a

b

t

s

3

2

1

1

1

2

1

s

b

b

t

a

a

d

1

1

2

2

1

3

1

sort

<Table id="idTable" items="{ path:'/company/contact', sorter:{ path: 'name', descending: false, group: true } }"> ... </Table>

XM

L V

iew

Page 94: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 100 Internal

Filtering & Sorting Using getBinding Example for modifying filtering and sorting a table during runtime

oController.prototype._applyFilterSorter = function(){

var oView = this.getView();

var oTable = oView.byId("idTable");

var oBindingItems = oTable.getBinding("items");

var aFilters = [];

var oFilter = new sap.ui.model.Filter("LastName",

sap.ui.model.FilterOperator.EQ ,

'Eijpe');

aFilters.push(oFilter);

oBindingItems.filter(aFilters);

var oSorter = new sap.ui.model.Sorter("name", false ,false);

oBindingItems.sort(oSorter);

}

JS

Page 95: BuildSAPFioriUIsWithSAPUI5_v2

Steps 26-27: OData Model

Page 96: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 102 Internal

Introduction to OData OData - Open Data Protocol

Industry-standard protocol for creating and consuming data APIs

Based on core protocols like HTTP and open standards like XML and JSON

Enables provision of data services based on REST principles

Initiated by Microsoft, adopted by SAP, IBM and others

Data handling using URLs constructed with specific rules

Defines data formats representing resources like collections, entries, properties

Optimized for consuming data, also known as “ODBC of the web”

OData URL structure:

http://services.odata.org/Northwind/Northwind.svc/Customers?$top=3

Service Root URI Resource Path Query options

Page 97: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 103 Internal

Introduction to OData URI to access data

OData URI Results

Service

Document

<service_root_url> http://services.odata.org/Northwind/Northwind.svc/ http://services.odata.org/Northwind/Northwind.svc/?$format=json

Collection of entity sets, e.g. a list of available

tables in a service

EDMX /$metadata http://services.odata.org/Northwind/Northwind.svc/$metadata

Definitions of the schema, like entity type,

property type, associations, navigations

Entity Set /<entityset> http://services.odata.org/Northwind/Northwind.svc/Suppliers

http://services.odata.org/Northwind/Northwind.svc/Suppliers?$format=json

All entities of an entity set, e.g. all rows of a table

Entity /<entityset>(<key>=<value>,<key>=<value>) http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)

http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)?$format=json

Entity of an entity set, based on key fields

Property /<entityset>(<key>=<value>,<key>=<value>)/<property> http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)/CompanyName

http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)/CompanyName?$for

mat=json

Property of the entity, e.g. a field of a row

Page 98: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 104 Internal

OData Model in SAPUI5

The OData model enables binding of control

properties and aggregations to data from a remote

server

The complete dataset is stored on the server and

only the requested fields are transferred to the client

SAPUI5 supports multiple OData models, but the

Fiori Guidelines state you should use OData model

version 2 sap.ui.model.odata.v2.ODataModel

All SAPUI5 OData models are currently based on

OData specification version 2.0 (with support of

annotations from OData specification version 4.0)

UI5 Component

View

Controllers

Server-Side

Model

DB Data

Data Engine

OData specification version 2.0.

See http://www.odata.org/documentation/odata-version-2-0/

Page 99: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 105 Internal

OData Simple Query Language

OData specifies a simple yet powerful

query language that allows a client to

request arbitrary operations to server-

side datasets

The names of all query string

parameters defined by OData are

prefixed with a $ character

Operation Query Option SQL Equivalent

Filtering $filter Where clause

Projecting $select Field selection

Sorting $orderby Sort

Paging $top Up to .. rows

$skip -

Inlining $expand Innerjoin

Count $count Count(..)

$inlinecount -

Service Root URI Resource path Query options

<SAP OData Engine>/iwfnd/USERSERVICE/UserCollection?<query parameters>

List of (most important) Query options: http://www.odata.org/developers/protocols/uri-conventions#QueryStringOptions

Page 100: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 106 Internal

SAP Web IDE Back-End Routing in the Application Descriptor neo-app.json

HTML5 applications can connect to one or

multiple REST services.

The URL to the REST service is configured

in a destination.

The mapping between an application URL

and a destination is defined in the

application descriptor called

neo-app.json.

The application descriptor must be located

in the root folder of the repository.

Destinations are configured using the SAP

HANA Cloud Cockpit.

"routes": [ { "path": "/destinations/northwind", "target": { "type": "destination", "name": "northwind_service", "entryPath": "/destinations/northwind" }, "description": “Northwind" } ]

neo-app.json

Page 101: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 107 Internal

Mock Server http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/#docs/guide/69d3cbd4150c4ffb884e788f7f60fd93.html

sap.ui.define([ "sap/ui/core/util/MockServer" ],

function (MockServer) { "use strict";

var oMockServer;

return {

_sServiceUrl : "/sap/opu/odata/sap/EPM_REF_APPS_PROD_MAN_SRV/", // service url to mock

_sModulePath : "myproject.service", // module path containing metadata.xml

init : function () {

oMockServer = new MockServer({ rootUri: this._sServiceUrl });

// configure mock server with a delay

MockServer.config({

autoRespond : true,

autoRespondAfter : 1000

});

// simulate

var sPath = jQuery.sap.getModulePath(this._sModulePath);

oMockServer.simulate(sPath + "/metadata.xml", {

sMockdataBaseUrl : sPath,

bGenerateMissingMockData : true

});

// Start

oMockServer.start();

jQuery.sap.log.info("Running the app with mock data");

}

};

});

Isolates your app from the

backend

Simulates OData backend

calls with Sinon.JS

Transparent to data binding

Supports randomly

generated data (based on

the service metadata)

Supports mock data

provided in .JSON files (use

same module path as for

metadata.xml)

Each OData service needs

its own mock server

Can be extended with

additional calls to mock

function import calls

Page 102: BuildSAPFioriUIsWithSAPUI5_v2

Step 28: Unit Test with QUnit http://qunitjs.com/

Page 103: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 109 Internal

QUnit Example

QUnit.module("Calculator", {

setup : function() { // in the future beforeEach

this.calculator = new Calculator(); // Executed before each test case

},

teardown : function() {} // in the future afterEach

});

QUnit.test("show zero initially", function(assert) {

assert.equal(this.calculator.display(), 0);

});

QUnit.test("display entered digit", function(assert) {

this.calculator.press("1");

assert.equal(this.calculator.display(), 1);

});

Test Suite

Test Case

Arrange

Act

Assert

Page 104: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 110 Internal

Basic Assertion Toolkit

assert.ok(1, "1 should have been truthy");

assert.ok(!false, "!false should have been truthy");

assert.equal(1 + 1, 2, "1+1 should have equaled 2");

assert.equal(1, true, "1 should have been converted to true");

assert.strictEqual("there", "there");

assert.notEqual(Math.PI, 3.1415);

assert.notEqual({}, {});

assert.notStrictEqual(1, "1");

assert.deepEqual({}, {});

assert.deepEqual([1, 2], [1, 2]);

assert.notDeepEqual({ f : "this" }, { f : "that" });

assert.throws(function() {

"anna".reverse();

}, TypeError, "function should have thrown TypeError");

Page 105: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 111 Internal

Test Double

Stubs only provide return values for method calls (“indirect input”)

Mocks

additionally verify that expected methods are called with the right parameters (“indirect

output”)

Mocks allow to test and discover side effects

Caution! Tests can get fragile when mocks are too “strict”

Solution: dynamically created mocks using a mocking framework http://sinonjs.org/

Page 106: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 112 Internal

Sinon.JS Integration – Example: Stub

sap.ui.define([], function() {

"use strict";

return {

throwHeadOrTail: function() {

return Math.random() < 0.5 ?

"Head" : "Tail";

}

}

};

});

sap.ui.require(["myProject/model/utility", // module to test

"sap/ui/thirdparty/sinon", // Load Sinon into your test

"sap/ui/thirdparty/sinon-qunit"],

function(utility) { "use strict";

QUnit.module("Utility functions", {

setup: function() { },

teardown: function() { }

});

QUnit.test("should yield head", function(assert) {

// Arrange

// System under test

// Sinon.JS Stub - Provide indirect input

// Sinon.js functions part of the this object

var stub = this.stub(Math, "random");

stub.returns(0.3);

// Assert

assert.equal(utility.throwHeadOrTail(), "Head");

//Stubs are restored automatically after the test (Sandbox)

//stub.restore();

});

});

Module to test myProject/model/utility.js

Sinon.JS API

Spies: sinon.spy()

Stubs: sinon.stub()

Faking time: sinon.useFakeTimers() ……

Page 107: BuildSAPFioriUIsWithSAPUI5_v2

Step 29: Integration Test with

OPA http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/docs/guide/2696ab50faad458f9b4027ec2f9b884d.html

Page 108: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 114 Internal

sap.ui.require(["sap/ui/test/opaQunit"],

function () {"use strict";

module("My first Journey");

opaTest("Should press a Button", function (Given, When, Then) {

// Arrangements

Given.iStartMyApp();

//Actions

When.onTheAppPage.iPressOnTheButtonWithId(“myButton");

// Assertions

Then.onTheAppPage.theButtonWithIdShouldHaveTheText(“myButton“,“I got pressed“).

and.iTeardownMyAppFrame();

});

});

OPA5 Arrangements, Action, Assertions

OPA gives you the

following three objects:

Given = arrangements

When = actions

Then = assertions

Page 109: BuildSAPFioriUIsWithSAPUI5_v2

Steps 31-33: Routing and

Navigation

Page 110: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 116 Internal

Typical SAPUI5 Mobile Usage

Typical mobile application structure:

App with multiple screens

Master / Detail screens with split apps

Drilldown navigation

Edit and Display

Back and Forward navigation

Entries in Browser History

Deep Links

sap.m.App (sap.m.NavContainer) root control

sap.m.Page sap.m.Page

Animation between pages can be chosen

(show, slide, fade, flip)

Page 111: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 117 Internal

Inner-App Navigation

Component.js

Browser

Fiori App

App Descriptor "routing" : {

// The default values for every route

"config" : {

...

},

// Define routes and pattern

"routes" : {

...

},

// Define which view to load

"targets" : {

...

},

}

}

WorkList.view.xml

sap.m.Page

ObjectNotFound.view.xml

sap.m.Page

NotFound.view.xml

sap.m.Page

Object.view.xml

sap.m.Page

App.view.xml

sap.m.App

sap.m.routing.

Router

init

add created page

create create create

SAPUI5 navigation features:

sap.m.routing.Router - SAPUI5 router class to load the pages and update the URL (change/replace hash)

Routing configuration in the app descriptor

Navigation events

Animation between pages

(show, slide, fade, flip)

hash

index.html

Component

Container

Fiori Launchpad create

change/replace

Page 112: BuildSAPFioriUIsWithSAPUI5_v2

Step 35: Responsiveness and

Device Adaptation

Page 113: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 119 Internal

Multi-Device Support: Responsive vs. Adaptive https://ux.wdf.sap.corp/fiori-design/foundation/responsiveness-adaptiveness/

Responsive patterns and controls: SAPUI5 offers a variety of controls and patterns that automatically adjust to different form

factors (table, object header, filter bar, and so on – plus the compact vs. cozy form factor). The big advantage of responsive

design is the fact that apps can adjust to different device types without additional effort in coding and maintenance.

Adaptive design of apps: Ideally follow a mobile first design approach, where apps have to manually define different designs

for different form factors. This is more effort but allows more targeted support of device-specific use cases.

The mobile table (sap.m.Table) with its responsive behavior is able to collapse

columns into rows

Page 114: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 120 Internal

Content Density (Cozy and Compact) https://ux.wdf.sap.corp/fiori-design/foundation/cozy-compact/

To adapt to different interaction styles better, SAP Fiori apps need to support two different content densities:

When running on touch devices, the app should display all controls with dimensions that are big enough for finger tips. This is

called Cozy Content Density.

When running on mouse- and keyboard-enabled (non-touch) devices, the information density on the screen can be increased

by reducing control dimensions. This is called Compact Content Density.

Page 115: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 121 Internal

Size L (Large Size)

Size M (Medium Size)

Grid Layout https://ux.wdf.sap.corp/fiori-design/foundation/grid-layout/

SAP Fiori UI elements are based on a 1 x 1 rem (16 x 16 px) flexible layout grid system ( rem = ”root em” ).

The Responsive Grid (sap.ui.layout.form.ResponsiveGridLayout) positions UI elements in a 12-column flow layout. It can be

configured to display a variable number of columns depending on available screen size:

Size S (Small Size e.g.

Smartphones and

Dialogues)

1024 px 600 px

Page 116: BuildSAPFioriUIsWithSAPUI5_v2

Fiori UI Development

Page 117: BuildSAPFioriUIsWithSAPUI5_v2

Putting the User Experience First

Fiori Design-Led Development

Page 118: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 125 Internal

Fiori Design Principles

Responsive Simple Role-Based Coherent Delightful

All sizes, devices, versions, channels

Apps that speak the same language

Be smart and pro-active

De-composition into task-based

experience

1 user 1 use case 3 screens

SAP Fiori provides a consistent and holistic user experience for SAP software. By creating visually pleasing designs with a

strong focus on ease of use, the experience is intuitive and simple, across all devices. With effortless interaction patterns, the

SAP Fiori UX is designed for a powerful impact across your enterprise.

Page 119: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 126 Internal

The Design-Led Development Process

Design Workshop Product Definition Design and Implementation Implementation Production

Vision What are our market opportunities?

• Persona

• Use Case

• Point of View

• Scenario

• Mockups

• Mockups from First Design Gate

• Final Designs

• State of Implementation

• Final Implementation

• Final Designs

• User Definition

• Description of App Scope and Purpose

• Results of User Research

Deliverables

First Design

Gate

Direction Does the planned design follow the Fiori design principles?

Design Sign-Off

Commitment Is the final design feasible? Does it still follow Fiori design principles?

Second Design

Gate

Delivery Does the final product meet or exceed the final design?

Readiness Check

Selection What apps will we build?

End Users End Users End Users End Users Customers

Customer Sign-Off

Use Interaction Design Template to provide the Deliverables

Page 120: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 127 Internal

Timeline for the Design-Led Development Process

Readiness Check

First Design

Gate

Second Design

Gate

Design Sign-off

First Design Gate (mandatory)

Must be requested and successfully passed before Decision Point “Start of Development”

Design Sign-off (optional)

Should be requested after 1/3 of the available development time in the case of significant changes to the design that passed first Design Gate. Otherwise it is optional.

Second Design Gate (mandatory)

Must be requested and successfully passed one week before Development Close

Product Definition Design Workshop Design and Implementation Implementation Production

Customer Sign-off (mandatory)

The Fiori Customer Co-Innovation Forum will be scheduled after RTC

End Users End Users End Users End Users Customers

Customer Sign-Off

Page 121: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 128 Internal

5 Pillars of Successful Application Design

1. Apply the five Core Design Principles: Role-Based, Delightful, Coherent, Simple, Responsive.

2. Talk to your customer and know your end user.

3. Design as a collaborative process with User Research, Development and UX/UID by applying the

Design Thinking Methodology – fast iterations, immediate feedback.

4. Design your application based on the Fiori Design Guidelines.

5. Follow the Design-Led Development Process to rate the results that have been achieved together

and to protect the Fiori trademark.

Page 123: BuildSAPFioriUIsWithSAPUI5_v2

Fiori UI Architecture

Page 124: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 132 Internal

SAP Fiori – Architecture

Application Types

Transactional (AT1)

Insight to Action

Visual overview of a complex topic for

monitoring or tracking purposes

Search and Explore

View of essential information about an object

and contextual navigation between related

objects

Analytical incl. Smart Business

(AT2)

Fact Sheet & Contextual

Navigation (AT3)

Task-Based Access

Access to tasks like change, create, or entire

processes with guided navigation

* This is the current state of planning and may be changed by SAP at any time

Page 125: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 133 Internal

SAP Fiori – Architecture

Front-End Technology

HTML5 apps built on SAPUI5 library sap.m

Support for smartphones, tablets and desktop

by implementing responsive design patterns

Different content densities (formerly known as

“form factors”) and operating systems are

supported with a single code line

Apps are running in the FLP as UI components

Runtime data is retrieved through OData

services that are tailored to tightly fit the app

Apps could be developed based on specific

Scaffolding API (up to SAPUI5 1.30 release)

Page 126: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 134 Internal

SAP Fiori – Architecture

SoH vs S/4HANA

SAP Business Suite 4 SAP HANA (S/4HANA) SAP Business Suite on HANA (SoH)

Page 127: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 135 Internal

SAP Fiori – Architecture

ABAP Front-End Server

Lifecycle decoupling of UI apps from back end

Especially for apps that must also run on anyDB

Allow faster iterations for the UI apps

Allow changes to UI without the need for development

privileges in the back end

Add-on-based delivery enables fast release cycles

Single point of UI maintenance like browser

support or UI5 provisioning

Central place for theming and branding

Single place for configuration, personalization and Fiori shell services

Rule-based dispatching of requests in a multi-system landscape

(e.g. for approvals incl. aggregation)

Security considerations

Similar to an application-level gateway (ALG) with protocol switch and whitelisting (excl. search)

Admin for UI metadata does not need to have admin rights in the back end (data sensitivity)

Page 128: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 136 Internal

Fiori in Browser

Browser-based apps

Run on all devices

No installation required

Coherent UX across devices

SAP Fiori Client

Downloadable ‘native’ app

Pre-packaged with commonly used Cordova plug-ins for native device integration

Improved performance

Full-screen operation

Attachment viewing

Notification App Updates

Selected Mobile Platform Services can be used

Fiori Mobile with ‘Kapsel’ SDK

Custom packaged & branded app

Can be delivered through company

store

Native device integration

Offers App Administration & Reporting

Push notifications*

Offline application data*

Use additional SAP Mobile Platform

services

Mobile Platform required

ONE ACCESS

*requires adapting Fiori app

Desktop Mobile Only

SAP Fiori UX & Mobile

Page 129: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 137 Internal

SAP Fiori UX & Mobile Kapsel – SAP-Specific Plug-Ins for Cordova

The SAP Mobile SDK for running Fiori – and other browser-

based applications – in a container is called ‘Kapsel SDK’

Set of SAP-specific plug-ins for Apache Cordova

Fits cleanly within existing Cordova development

environments and processes

Not a forked version of Cordova

Includes plug-ins to make use of native mobile device

functionalities & enterprise readiness:

Secure onboarding, encrypted storage

Attachment handling & printing

Asset updates, support features

Page 130: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 138 Internal

Details https://wiki.wdf.sap.corp/wiki/display/fioritech/Fiori+Technology+Home

Fiori Architecture wiki https://wiki.wdf.sap.corp/wiki/display/fioritech/Architecture

Fiori Architecture Jam Group https://jam4.sapjam.com/groups/M3RLIMrYC212PELNnz7KDt

Fiori demo edition http://www.sap.com/Fiori-demo

Fiori-aaS project wiki https://wiki.wdf.sap.corp/wiki/display/FaaS/

S/4HANA Architecture https://wiki.wdf.sap.corp/wiki/pages/viewpage.action?pageId=1577443213

Offline enablement Offline Enablement for SAP Fiori – Guide for decision makers

A guide for developers is planned to be announced at the end of June

Further Information

Page 131: BuildSAPFioriUIsWithSAPUI5_v2

Fiori UI Development Guidelines -

Best Practice

Page 132: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 140 Internal

Fiori UI Development Guidelines https://wiki.wdf.sap.corp/wiki/display/fioritech/Development+Guideline+Portal

Following topics are essentially covered

Fiori Architecture and Fiori Application Types

Fiori UI Development Guidelines

Reuse components

Gateway OData Guidelines for Transactional Applications and

Concepts for stateless applications

Naming Conventions for Development Objects

Theming / CSS Usage

Performance

Security

Compatibility Guideline - Common patterns for compatibility

Extensibility - How to enable extensibility for fiori applications

Contains early draft status for current wave (content may change frequently).

Stable versions for previous waves are available in PDF format

Page 133: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 141 Internal

10 Golden Rules for Fiori Development https://wiki.wdf.sap.corp/wiki/display/fioritech/Golden+Rules+for+SAP+Fiori+Applications

SAP Fiori apps must have an approved UX design (GR-01)

SAP Fiori UIs are built with SAPUI5 (GR-02)

SAP Fiori apps are based on OData services (GR-03)

One SAP Fiori app - one OData service (GR-04)

SAP Fiori UIs and OData services must be defined in different software components (GR-05)

Every SAP Fiori app is defined by a set of metadata (GR-06)

No custom CSS is allowed for SAP Fiori apps (GR-07)

Every SAP Fiori app must run as a web app (GR-08)

Every SAP Fiori app must run in the SAP Fiori Launchpad (GR-09)

Every SAP Fiori app must run on mobile devices along the native app paradigm (GR-10)

Page 134: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 142 Internal

Special Development Guidelines

Special Development Guidelines S/4HANA (OnPremise/Cloud)

https://wiki.wdf.sap.corp/wiki/display/fioritech/Special+Development+Guidelines+for+S4H • S/4HANA Frontend

• S/4HANA Gateway

• S/4HANA Backend

Special Development Guidelines SoH (Suite on HANA)

https://wiki.wdf.sap.corp/wiki/display/fioritech/Special+Development+Guidelines+for+SoH • Frontend (AT1, AT2, AT3)

• Gateway

• EhP Backend

Fiori@BusinessSuite

https://wiki.wdf.sap.corp/wiki/display/fiorisuite/Development+Guidelines

SAPUI5 Developer Guide

http://veui5infra.dhcp.wdf.sap.corp:8080/sapui5-sdk-dist/#docs/guide/99ac68a5b1c3416ab5c84c99fefa250d.html

UI5 Code Development Conventions and Guidelines

https://github.com/SAP/openui5/blob/master/docs/guidelines.md

ESLint Rules

http://eslint.org/docs/rules/

Page 135: BuildSAPFioriUIsWithSAPUI5_v2

Freestyle, Patterns &

Smart Templates

Page 136: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 146 Internal

Solution Principles

Typical transactional app with draft. 30:70 distribution change for light

transactional (70:30) or heavy transactional (10:90) applications

Smart Controls

Templates

UI Vocabulary

Application

Infrastructure

Metadata

30% Frontend

70% Backend

UX Patterns

1. Smart Controls. Enrichment of UI5 controls by adding metadata support.

Controls can also be used in freestyle apps.

2. Templates. Provisioning of UI templates using smart controls. UI-

vocabulary-driven dynamic assembly of UI templates implementing

predefined Patterns. Templates can be used as a test environment for

data model / draft objects and Customizing UIs.

3. Standardized UI Vocabulary via OData Annotations to define application

layout & interaction. Vocabulary can also be used in other applications,

e.g. Smart Business.

4. Application Infrastructure and draft objects. Draft objects can also be used

for freestyle apps.

5. Metadata via DDIC/CDS. Metadata is used e.g. for smart controls and

generic analytical apps.

Simplification Approach

■ Define a common pattern.

■ Optimize technology & tools for identified patterns.

■ Ensure components can be used separately and still provide benefit

Manual

Smart

Templates

Page 137: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 147 Internal

2014 2015

Jan

Feb

Mar

Apr

May

June

Juli

SAP Fiori UX Development Efficiency

Smart Controls

SAPUI5 Flexibility & Core Extensions

Back-end Programming Model

SAP Web IDE WYSIWYG

One efficient E2E programming model from persistency to the UI

UI Programming Model with smart templates, smart controls & metadata

SAP Web IDE with Tools & Wizards, Code Editors, Unit testing, Templates, Collaboration via GIT

Efficient back-end programming model including Draft Infrastructure, Error Message Handling,

Stateless Locking, Value Help, Field Control, URL Handling, Draft-enabled Business Configuration, Central

Settings, Tracing & Logging, Long Message Texts

Smart Templates

UX / Project One (1st aspects)

SAPUI5 Freestyle templates

App Descriptor / SAPUI5 Flexibility

Smart Templates Pilots

Scaffolding (deprecated)

Fiori Programming Model

Scaffolding API (internal)

SAP Web IDE Fiori Templates

Fiori@BusinessSuite Guidelines

Page 138: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 148 Internal

SAP Fiori UX Development Efficiency Freestyle, Patterns & Smart Templates

UI5 Freestyle

Smart Templates unleashed

Based on templates + breakout capabilities + individual refinements

Smart Templates on rails

Strictly based on predefined

floor plans/patterns, no breakouts!

Only working with fully guideline-conform

enabled oData services

Capabilitie

s E

ffic

iency

UI Flexibility Smart templates will enable us to

build 80% of the UIs with only 20% of

our effort. This will free up our capacity

for the UIs that really matter.

Smart templates are naturally

extending existing SAPUI5 capabilities

without breaking any of the existing

qualities: flexibility, LCM…

If the capabilities and design patterns of

the smart templates are not sufficient,

the SAPUI5 Freestyle templates

can be used. These enable users to

build applications following best

practices for building applications with

SAPUI5

Page 139: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 149 Internal

What Should I Use?

Customers & Partners

Should use new approach already with SAPUI5 1.28.x, x > 6 (scaffolding framework not

released for customers)

Released SAP Applications

Do not touch. Changes would be incompatible (Extensibility etc.)

New SAP Applications Based on SAPUI5 1.28

Build with old approach using scaffolding (some new reuse assets are only in SAPUI5 1.30)

New SAP Applications Based on SAPUI5 1.30 (release in Q3/2015)

Started with old approach using scaffolding. The migration should be a case by case decision.

Contact the SAPUI5 team to discuss details.

New SAP Applications Based on SAPUI5 1.30 (release in Q4/2015)

Use new approach (SAPUI5 freestyle) or Smart Template: The upcoming Smart Templates will

provide greater efficiency for building applications. If you need greater flexibility, choose the

SAPUI5 freestyle templates without the scaffolding framework.

Page 140: BuildSAPFioriUIsWithSAPUI5_v2

Smart Templates

Page 141: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 151 Internal

Scale Fiori application development by applying a

metadata-driven approach

Significantly reduce the amount of front-end

code required for building Fiori applications and

provide a high code quality centrally through

predefined templates and controllers

Foster design consistency and help to keep

Fiori apps up-to-date with evolving Fiori design

guidelines

Embed the approach in overarching Fiori concepts

for UI flexibility, lifecycle management and

application notion

Smart Templates Address the main challenges in Fiori development

Page 142: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 152 Internal

Smart Templates (Scope: June 2015)

152

Object List

Display objects in a list with smart filter bar and

smart table

Object List with analytical table

Usage of an analytical table when the annotations

& metadata are available

Object Page

Object page for displaying a single instance of a

business object

Object Page with navigation to detail page

Navigation to detail page for items of a business

object

Edit/Create Page

Switch to edit mode or create mode with handling

of drafts/messages/roundtrip choreography

Documentation and Tooling

Annotation creation in CDS Editor, Checks, Rollout

material

Page 143: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 156 Internal

XML Templating https://jam4.sapjam.com/blogs/show/2BWKXZgOnq843V2nGozOBT

or see SAPUI5 Developer Guide

Smart Templates on Fiori Tech Wiki https://wiki.wdf.sap.corp/wiki/display/fioritech/Smart+Templates

Development Guideline Portal https://wiki.wdf.sap.corp/wiki/display/fioritech/Development+Guideline+Portal

Further Information

Page 144: BuildSAPFioriUIsWithSAPUI5_v2

SAPUI5 Freestyle Application

Page 145: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 158 Internal

New Application Architecture as of SAPUI5 1.30

UI5

Co

ntr

ols

Ap

p

Te

mp

late

- T

es

ts

UI5

Co

re

FL

P

Tem

pla

te -

Ap

p

Busy Indication Master List Logic

Mock Server Handling

Technical Error

Handling

Routing Implementation

Message Page Semantic Pages Overflow Toolbar

Busy Indication

Remember Selection

Unit Tests (QUnit)

Integration Tests (OPA)

Client Filtering Routing Targets Mobile

Router App Descriptor

Application Code

App Page Toolbar View Settings Dialog

MVC Data Binding Routing Mock Server Component

Save App as Tile Share in JAM Add Entry to User Menu

FLP Implementation

App Descriptor

Implementation

List

Page 146: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 159 Internal

Building Apps Using Freestyle Templates (SAP Web IDE)

Master-Detail Application

Worklist Application

Best Practice features and

concepts

Project structure

Error handling

Routing and Navigation

Sharing options

Compact / Cozy design mode

New sap.ui.define() syntax

Coding Conventions

JSDOC comments

Standard ESLint rules

Hungarian notation

Closures instead of events and asynchronous constructs

Private API is prefixed with a "_" character

Quality and Testing

Integration tests

Unit tests

FLP integration and Test Pages

Page 147: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 160 Internal

Exercise

Page 148: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 161 Internal

SAPUI5 Apps as Component

SAPUI5/Fiori apps are component-based and have

a component controller

App Descriptor contains application-specific

configuration settings

SAPUI5 apps can have more than one model and

can use different model types

SAPUI5 views are built with controls and can have

a view controller to handle events

Reusable view content can be grouped in fragments

and can be reused in views

Different view types can be used

in one application

View

View

Controllers

Models

Component

Controller

Models Models

View View

View

Controllers

Fragments Controls Controls

Component

Container

Fiori Launchpad

Fiori App

app descriptor

Page 149: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 162 Internal

Project Structure (1/2)

controller for controller files and controller-specific functionality

i18n collection of *.properties files for localization

model for all data-related files like formatters, groupers, and model

instantiation (no mock data)

view for the UI description artifacts like views and fragments

Component.js - component that encapsulates all the UI assets

manifest.json - App Descriptor contains application settings

neo-app.json - configuration file for Hana Cloud Proxy

Additional folders can be added, e.g.:

img for images

css for custom style sheets

Page 150: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 163 Internal

Project Structure (2/2)

webapp/test.html – Testing Overview lists the following access points:

webapp/test/testFLP.html - Start the app in the SAP Fiori launchpad sandbox*

webapp/test/testFLPService.html - Start the app in the SAP Fiori launchpad sandbox

with MockServer*

webapp/test/integration for OPA-based integration tests of the app (cover all basic

functionality and provide several “journeys”/series of OPA5 tests)

opaTests.qunit.html - main test suite file to execute all journeys

webapp/test/unit for the QUnit tests of the app (using Sinon.js stubs and other helper

tools to remove dependencies before executing the test case)

unittests.qunit.html - test suite file to execute all unit tests

webapp/localService for the mock server script and the mock data used for testing the

application

mockserver.js - instantiates the mock server from within the app

metadata.xml – metadata describing OData service entities

mockdata should be located under webapp/localService/mockdata

*sap.ushell library must be available

Page 151: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 164 Internal

Exercise

Page 152: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 165 Internal

Building Apps Using Templates in SAPUI5 Developer Guide http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/#docs/guide/3a9398ed714c420b9608ec8c4bc9d162.html

SAPUI5 Freestyle Templates Rollout https://jam4.sapjam.com/groups/about_page/km1yusxqKb6vPGu0AhItPD

App Descriptor http://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/AdvancedTopics/Manifest

https://wiki.wdf.sap.corp/wiki/display/fioritech/AppDescriptor+News

App Descriptor Step by Step Migration Guide

http://vesapui5.dhcp.wdf.sap.corp:1080/trac/sapui5/wiki/Documentation/AdvancedTopics/ManifestMigration

Further Information

Page 153: BuildSAPFioriUIsWithSAPUI5_v2

History: Scaffolding

Page 154: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 167 Internal

SAP Scaffolding

Architecture Overview Views and Controllers

Navigation OData Service Consumption

Not released to customers

In maintenance mode

In Fiori wave 2, scaffolding

closed SAPUI5 gaps with

workarounds

In Fiori wave 3-9, SAPUI5

closed these gaps

As of Fiori wave 9, new

project to be built without

scaffolding

Apps started before wave 9

may still include scaffolding

Page 155: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 168 Internal

Application Architecture Using Scaffolding T

es

t

Ap

p

UI5

Co

ntr

ols

App Page List Toolbar

Sc

aff

old

ing

Fra

me

wo

rk

Busy Indication

Technical Error

Handling Not Found Page

List Client Filtering Toolbar Overflow

Management

Master List Logic

Model Handling Mock Server

Handling

Routing

Implementation

Design Guidelines for

Header & Footer

Routing

Implementation

FL

P

Save App as Tile

Application Code Unit Tests (QUnit) Integration Tests

(OPA)

UI5

Co

re

MVC Data Binding Routing Mock Server Component

Share in JAM Add Entry to User

Menu

Scaffolding API

View Settings Dialog

Page 156: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 169 Internal

Maven Project Structure

pom.xml – used by Maven Build Infrastructure

neo-app.json – configuration file for Hana Cloud Proxy

Folder /test – unit tests (QUnit/OPA5)

Folder /src/main/webapp/i18n – collection of *.properties

files for localization

Folder /src/main/webapp/model – service metadata and

mock data

Folder /src/main/webapp/view – views, controllers,

fragments (UI Source)

Component.js – component that encapsulates all the UI

assets

Configuration.js – Service(s) definition

localIndex.html – can be used to launch or preview the

application without using SAP Fiori launchpad

Main.view.xml/Main.controller.js – sap.m.App definition

(app concept in mobile applications)

Page 157: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 170 Internal

Scaffolding Wiki https://wiki.wdf.sap.corp/wiki/display/UI/Scaffolding

Scaffolding API https://wiki.wdf.sap.corp/wiki/display/UI/Development+Guidelines

Further Information

Page 158: BuildSAPFioriUIsWithSAPUI5_v2

OData Model

Page 159: BuildSAPFioriUIsWithSAPUI5_v2

UI5 Models Introduction

Page 160: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 174 Internal

UI5 Libraries UI5 Component

UI5 Architecture Overview

Application

CLIENT

Application

SERVER

View

Controllers

Models

Odata, XML, JSON

Controls

Themes

ABAP JAVA HANA Static

HCP HEC

data

local data i18n Mimes

Page 161: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 175 Internal

UI5 Models

Introduction

• UI5 Applications use the Model-View-Controller concept for the screens and logic of the application

• A model holds the data and provides methods to retrieve the data from the data source and to set

and update data.

• A UI5 application supports various data sources, like XML, JSON and OData.

• UI5 supports data binding between Views and Models, which is used to bind two data sources or information

sources together and to keep them in synch.

• Within UI5, the way in which data binding is defined and implemented within the UI controls is uniform and

independent of the respective data source.

• Within a UI5 application it is possible to

use of multiple models to bind UI5 controls

• It is also possible to create a custom model

implementation for data sources that are

not yet covered by the framework or are

domain-specific. You can implement them by extending the sap.ui.model.Model

Page 162: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 176 Internal

Data Binding Model Types

Model

Client

Model

XML JSON Resource Message OData

OData

MetaData

Control

Server-side Client-side Helper

Device

Page 163: BuildSAPFioriUIsWithSAPUI5_v2

OData Models Introduction

Page 164: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 178 Internal

SAP New Platform Technology

HANA DB

XS2 ABAP JAVA

Application logic

Views Procedures

UI5

as uniform and open UI technology

datastore

NetWeaver Gateway Apache Olingo

ODATA

for Uniform Data Access

FIORI

for (re)new business applications

XS NodeJS J2EE … .NET

ASP.NET Web API 2

JAVA ABAP

ODBC

Page 165: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 181 Internal

Server-Side Models

• In SAPUI5, facilitate communication between the UI

app and the back-end system

• Controls in the view can be bound to the data in a

model and will be updated automatically

• The model sends a request to the server to request

data

• On the server side, an OData engine interprets and

processes the request and collects the requested

data

• This data is then sent back to the model

• This round trip takes place for every data request

UI5 Component

View

Controllers

Server-side

Model

data

OData Engine

Page 166: BuildSAPFioriUIsWithSAPUI5_v2

Introduction to OData

Page 167: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 183 Internal

Introduction to OData OData - Open Data Protocol

• Industry-standard protocol for creating and consuming data APIs

• Based on core protocols like HTTP and open standards like XML and JSON

• Enables provision of data services based on REST principles

• Initiated by Microsoft, adopted by SAP, IBM and others

• Data handling using URLs constructed with specific rules

• Defines data formats representing resources like collections, entries, properties

• Optimized for consuming data, also known as “ODBC of the web”

OData URL structure:

http://services.odata.org/Northwind/Northwind.svc/Customers?$top=3

Service Root URI Resource Path Query Options

Page 168: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 184 Internal

Introduction to OData URI to access data

OData URI Results

Service

Document

<service_root_url> http://services.odata.org/Northwind/Northwind.svc/ http://services.odata.org/Northwind/Northwind.svc/?$format=json

Collection of entity sets, e.g. a list of available

tables in a service

EDMX /$metadata http://services.odata.org/Northwind/Northwind.svc/$metadata

Definitions of the schema, like entity type,

property type, associations, navigations

Entity Set /<entityset> http://services.odata.org/Northwind/Northwind.svc/Suppliers

http://services.odata.org/Northwind/Northwind.svc/Suppliers?$format=json

All entities of an entity set, e.g. all rows of a table

Entity /<entityset>(<key>=<value>,<key>=<value>) http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)

http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)?$format=json

Entity of an entity set, based on key fields

Property /<entityset>(<key>=<value>,<key>=<value>)/<property> http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)/CompanyName

http://services.odata.org/Northwind/Northwind.svc/Suppliers(2)/CompanyName?$for

mat=json

Property of the entity, e.g. a field of a row

Page 169: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 186 Internal

Introduction to OData JSON or XML-Atom format

• OData supports XML and JSON as

payload for the data exchange

• Query parameter $format can be

used to specify the format json or xml.

• The json format has less protocol

overhead

$format=json

$format=xml

Page 170: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 187 Internal

Introduction to OData Using browsers for testing OData

• XML and JSON are technical formats, but most browsers and editors are able to display them.

Additional plugins can be installed to solve this problem

• When using NetWeaver Gateway as an OData engine, you can add a query parameter sap-ds-debug=true to the request to show and analyze the OData call

Page 171: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 188 Internal

OData Model in SAPUI5

• The OData model enables binding of control

properties and aggregations to data from a remote

server

• The complete dataset is stored on the server and

only the requested fields are transferred to the client

• SAPUI5 supports multiple OData models

• Fiori requires OData model version 2

sap.ui.model.odata.v2.ODataModel

• All SAPUI5 OData models are currently based on

OData specification version 2.0

UI5 Component

View

Controllers

Server-Side

Model

DB Data

Data Engine

OData specification version 2.0.

See http://www.odata.org/documentation/odata-version-2-0/

Page 172: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 189 Internal

OData Model in SAPUI5 Comparison between version 1 and 2

• New features will only be implemented in the sap.ui.model.odata.v2.ODataModel

• The sap.ui.model.odata.ODataModel is deprecated.

Feature sap.ui.model.odata.v2.ODataModel sap.ui.model.odata.ODataModel

OData version support 2.0 2.0

JSON format Yes (default) Yes

XML format Yes Yes (default)

Support of two-way binding mode Yes; for property changes only, not yet

implemented for aggregations

Experimental; only properties of one entity

can be changed at the same time

Default binding mode One-way binding One-way binding

Client-side sorting and filtering Yes; see sap.ui.model.odata.OperationMode No

$batch Yes; all requests can be batched Only manual batch requests are possible

Data cache in model All data is cached in the model Manually requested data is not cached

Automatic refresh Yes (default) Yes

Message handling Yes, see Message Model No

Page 173: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 190 Internal

Creating the Model Instance

• The service root URI returns the service document which gives URLs of all entity sets

• This service root is used to initiate the OData model.

• One OData model instance can only cover one OData service. This means you have to create

multiple OData model instances if you need to access multiple services.

• The only mandatory parameter when creating an ODataModel instance is the service URL. It can

be passed as first parameter or the serviceUrl parameter within the constructor.

• Additional parameters can be set to configure the model

https://<server>:<port>/sap/opu/odata/iwfnd/USERSERVICE/

Service Root URI

var oModel = new sap.ui.model.odata.v2.ODataModel("http://services.odata.org/Northwind/Northwind.svc/"); var oModel = new sap.ui.model.odata.v2.ODataModel({serviceUrl: "http://services.odata.org/Northwind/Northwind.svc"});

SAP Gateway Service SAP OData Engine

Page 174: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 191 Internal

Entity Data Model – Overview

An Entity Data Model (EDM) describes the organization and relationship of the data resources that are

modelled as entity types within a particular business scenario.

Entity sets are collections of Entities which are instances of Entity Types

Association

Relationship between

two entity types

An entity type is built from

one or more properties Navigation

Implements an association

Entity Type

EDM basic building block.

Represents a specific

business object

At least one property must

be defined as a key field

Entity Set

EDM basic building block.

Instances of entity types

Page 175: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 192 Internal

Service Metadata

• The $metadata entry for an OData service returns an EDMX file (Entity Data Model XML) that

contains a complete description of the feeds, types, properties and relationships exposed by the

OData service

<SAP OData Engine>/iwfnd/USERSERVICE/$metadata

<EntityContainer Name="USERSERVICE_Entities" m:IsDefaultEntityContainer="true"> <EntitySet Name="AddressCollection" EntityType="USERSERVICE.Address" sap:content-version="1"/> <EntitySet Name="UserCollection" EntityType="USERSERVICE.User" sap:content-version="1"/> <EntitySet Name="RoleCollection" EntityType="USERSERVICE.Role" sap:content-version="1"/> <AssociationSet Name="AssocSet_address" Association="USERSERVICE.address" sap:creatable="false" sap:updatable="false" sap:deletable="false" sap:content-version="1"> <End EntitySet="UserCollection" Role="FromRole_address"/> <End EntitySet="AddressCollection" Role="ToRole_address"/> </AssociationSet> </EntityContainer> Association

Entity Type

Entity Set

Annotation

used by SAP to

provide additional info

Service Root URI Resource Path

Page 176: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 193 Internal

Service Metadata

• When an ODataModel instance is created, a request is sent to retrieve the service metadata

• The service metadata is cached per service URL

• Multiple OData models that are using the same service can share this metadata. Only the first

model instance triggers a $metadata request.

• A JSON representation of the service metadata can be accessed by calling the

getServiceMetadata() method on an OData model instance.

• Alternatively, you can use the OData meta model using the getMetaModel() method

var oMetadata = oModel.getServiceMetadata();

var oModel = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/iwfnd/USERSERVICE/"); oMetaModel = oModel.getMetaModel(); oMetaModel.loaded().then(function () { ... });

Page 177: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 194 Internal

Entity Types and OData Types

<EntityType Name="User" sap:content-version="1"> <Key> <PropertyRef Name="username"/> </Key> <Property Name="fullname" Type="Edm.String" Nullable="false" MaxLength="80" sap:label="Full name" sap:creatable="false" sap:filterable="false"/> <Property Name="username" Type="Edm.String" Nullable="false" MaxLength="12" sap:label="User name" sap:creatable="false" sap:filterable="false"/> <Property Name="lastname" Type="Edm.String" Nullable="false" MaxLength="40" sap:label="Last name" sap:creatable="false" sap:filterable="false"/> <Property Name="firstname" Type="Edm.String" Nullable="false" MaxLength="40" sap:label="First name" sap:creatable="false" sap:filterable="false"/> <NavigationProperty Name="address" Relationship="USERSERVICE.address" FromRole="FromRole_address" ToRole="ToRole_address"/> <NavigationProperty Name="roles" Relationship="USERSERVICE.roles" FromRole="FromRole_roles" ToRole="ToRole_roles"/> </EntityType>

Entity Type

Key

Property

Navigation

Property

Annotations

OData Type

Page 178: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 195 Internal

Exercise

Page 179: BuildSAPFioriUIsWithSAPUI5_v2

Data Binding Introduction

Page 180: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 197 Internal

Binding Controls to the Model Primitive binding types

• To retrieve data from the model for visualization in the UI, the controls have to be bound to the

model by means of a binding path.

• For binding controls to the model, several primitive binding types exist:

• Property binding allows properties of the control to get automatically initialized and updated from model

data.

• Element binding allows you to bind elements to a specific object in the model data, which will create a

binding context and allow relative binding within the control and all of its children.

• Aggregation binding can be used to automatically create child controls according to model data. This can

be done either by cloning a template control, or by using a factory function.

Page 181: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 198 Internal

Binding Path

• Binding paths address the different properties and lists in a model and define how a node in the

hierarchical data tree can be found.

• A binding path consists of a number of name tokens, which are separated by a separator char. In all

models provided by the framework, the separator char is the slash "/".

• A binding path can either be absolute or relative: Absolute binding paths start with a slash, relative

binding paths start with a name token and are resolved relative to the context of the control that is

bound.

Example for an absolute binding path:

/Employees('ID004711')/FirstName

Example for a relative binding path:

FirstName

Page 182: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 199 Internal

OData Binding Path

• The binding path syntax for OData models matches the URL path relative to the service URL used

in OData to access specific entities or entity sets.

• OData Query parameters, such as filters, cannot be added to a binding path in SAPUI5.

• A property binding path can be absolute or relative

Data Binding SAPUI5 Methods Binding Path OData

Aggregation oControl.bindAggregation(sPath,oTempl) /<entityset> Entityset

Element oControl.bindElement(sPath) /<entityset>(<key>=<value>,<key>=<value>) Entity

Property oControl.bindProperty(sPath) /<entityset>(<key>=<value>,<key>=<value>)/<property> Property

Property (relative) oControl.bindProperty(sPath) <property> Property

Page 183: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 201 Internal

Property Binding

• Most of the properties of a control can be bound to model properties using curly braces {} in the

XML View.

• You can only bind control properties to model properties of a matching type, or use a formatter

function or built in UI5 data type to convert the data as needed.

• If you want to update a property binding at runtime, you can use the bindProperty(sName, sPath) method of the UI control.

A A

<Text id="idPropertyBindingFirstName" text="{/EmployeeSet('0000000001')/FirstName}" />

var sNum = "0000000002"; var sPath = "/EmployeeSet('" + sNum + "')/FirstName"; var oControl = this.getView().byId("idFirstNameText"); oControl.bindProperty("text", sPath);

JS

XM

L V

iew

Page 184: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 202 Internal

• Relative property bindings are relative to their parent and do not start with a slash .

• For example, if the absolute binding paths /EmployeeAddressSet(1)/Building, we split this

into an absolute path /EmployeeAddressSet(1), which we will bind to a parent UI control,

and a relative path Building, which we will bind to a child UI control:

<f:SimpleForm id="SimpleFormDisplay471" minWidth="1024" maxContainerCols="2" editable="false" layout="ResponsiveGridLayout" title="Address" labelSpanL="4" labelSpanM="4" emptySpanL="1" emptySpanM="1" columnsL="1" columnsM="1" binding="{/EmployeeAddressSet(1)}"> <f:content> <Label text="Name" /> <Text text="{Building}" /> <Label text="Street" /> <Text text="{Street}" /> <Label text="ZIP Code/City" /> <Text text="{PostalCode} {City}" /> <Label text="Country" /> <Text text="{Country}" /> </f:content> </f:SimpleForm>

Relative Property Binding X

ML

Vie

w

Page 185: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 203 Internal

Element Binding & Relative Property Binding

• An element binding is mostly used in list-based scenarios where you react to user selection.

• In the controller, you can “rebind” the parent control by using the bindElement(path) method to

change the information that is displayed.

this.updateElement("0");

updateElement: function(index) { var oPanelEB = this.getView().byId("SimpleFormDisplay471"); var sPath = "/EmployeeAddressSet(" + index + ")"; oPanelEB.bindElement(sPath);

}

this.updateElement("1"); J

S

Page 186: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 204 Internal

Navigation Properties

Navigation properties are mostly used for header-items scenarios. By changing the header binding of

the page, the related navigation properties are bound automatically.

The navigation properties

of an entity provide a way

to navigate to an associate

entity (1:1) or entity set (1:n)

Service Root URI Resource Path

<SAP OData Engine>/iwfnd/RMTSAMPLEFLIGHT/EmployeeSet('0000000001')/EmployeeAddress

Navigation Property

<Page id="DetailsPage" title="{i18n>detailTitle}" navButtonPress="onNavBack"> <content> <f:SimpleForm id="SimpleFormDisplay471" minWidth="1024" maxContainerCols="2" editable="false" layout="ResponsiveGridLayout" title="Address" labelSpanL="4" labelSpanM="4" emptySpanL="1" emptySpanM="1" columnsL="1" columnsM="1" binding="{EmployeeAddress}"> <f:content> <Label text="Name" /> <Text text="{Building}" /> <Label text="Street" /> <Text text="{Street}" /> <Label text="ZIP Code/City" /> <Text text="{PostalCode} {City}" /> <Label text="Country" /> <Text text="{Country}" /> </f:content> </f:SimpleForm> </content> </Page>

XM

L V

iew

Page 187: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 205 Internal

Exercise

Page 188: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 206 Internal

Aggregation Binding

• Aggregation binding is used to bind datasets, like binding multiple rows to an aggregation-

supported UI control, for example tables, lists or pulldown controls.

• For this, you bind the collection using the bindAggregation(sPath, oTemplate) method of the

control. The UI template consists of at least one other UI control, which is used as a repeated list

item.

• Aggregations can only be bound to datasets defined in the model, that is, to multiple tags with the

same name in XML, to arrays in a JSON model, or a collection

in the OData model.

Dataset UI Template

+

{ company: { contact: [ { name: "Barbara", phone: "873“ }, { name: "Gerry", phone: "734" }, { name: "Susan", phone: "275"} ] }}

=

UI Table

Page 189: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 207 Internal

OData Binding Path

<mvc:View xmlns:l="sap.ui.layout" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="sap.m.sample.Table.Table" > <Table id="idProductsTable" inset="false" items="{path: '/ProductCollection'}"> <columns> <Column width="12em"> <Text text="Product" /></Column> <Column hAlign="Right"> <Text text="Price" /></Column> </columns> <items> <ColumnListItem> <cells> <ObjectIdentifier title="{Name}" text="{ProductId}"/> <ObjectNumber number="{WeightMeasure}" unit="{WeightUnit}" state="{ path: 'WeightMeasure', formatter: 'sap.m.sample.Table.Formatter.weightState'}" /> </cells> </ColumnListItem> </items> </Table> </mvc:View>

Aggregation binding

Properties

binding Template of

aggregation

XM

L V

iew

Page 190: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 208 Internal

Aggregation Binding Binding methods

When an aggregation is bound to a control, you can use the following methods at runtime to get

information about the aggregation:

Method Remarks oAggrControl.getBindingPath("<property>"); Returns the path of the control property

oAggrControl.getBindingInfo("<property>");

Returns an object with information about the binding, including the template

oAggrControl.getBinding("<property>");

Returns the binding object, including the bound data

oAggrControl.getAggregation("<property>");

Returns an array of the bound data

Page 191: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 209 Internal

Aggregation / Element Binding Binding context

A context exists either for each entry of the aggregation in the case of aggregation binding, or it can be set explicitly for a control by using the setBindingContext method to an element. Relative bindings

without a defined context are resolved relative to the model root.

You can get the binding context using the following methods:

Method Remarks oAggrControl.getAggregation("<property>")[<i>] .getBindingContext();

Returns the context of a bound aggregation item

oAggrControl.getBinding("<property>") .getContexts()[<i>];

Returns the context of a bound aggregation item

oElemControl.getElementBinding() .getBoundContext();

Returns the context of a bound element

oElemControl .getBindingContext();

Returns the context of a bound element

Page 192: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 210 Internal

Other Binding Methods

• A lot of controls also support additional binding methods based on the control metadata. These

binding methods are always a variant of the primitive binding types. For example:

Binding Method Primitive Binding Method

sap.m.Text.bindText({path:sPath}) Property “text”

sap.m.Text.bindProperty("text", {path:sPath})

sap.m.Table.bindItems({path:sPath,template:oTemplate}) Aggregation „items“

sap.m.Table.bindAggregation("Items",{path:sPath,template:oTemplate})

Page 193: BuildSAPFioriUIsWithSAPUI5_v2

Setting Models

Page 194: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 212 Internal

Creating a Model Instance Model instantiation

To use data binding in a SAPUI5 applications you will need to instantiate an appropriate model first.

This is done automatically by the framework when specify you specify models in the “sap.ui5” part of

the app descriptor.

var oJSONModel = new sap.ui.model.json.JSONModel(sData); var oXMLModel = new sap.ui.model.xml.XMLModel(sData); var oODataModel = new sap.ui.model.odata.v2.ODataModel(sData, {});

{ "sap.app": { ... "dataSources": { "invoiceRemote": { "uri": "/services.odata.org/V2/Northwind/Northwind.svc/", "type": "OData", "settings": { "odataVersion": "2.0" } } } }, ... "sap.ui5": { ... "models": { "invoice" : { "dataSource": "invoiceRemote" } } } } App Descriptor: manifest.json

Note: As a fallback, you can manually instantiate

the model in the app code if necessary. The

constructor takes the URL of the model data or the

data itself as the first parameter.

JS

Page 195: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 213 Internal

Setting Models

• A model can be set to the core (not

recommended as it is visible globally), the

component, a view, or a control using the

setModel(oModel) method

• All children will automatically inherit the

model of the parent

• if you set a model on the component or app

descriptor, all views and controls can make

use of that model

View

Controls (aggregation)

Controls (element level)

Controls (property level)

SAPUI5 Core

Component

Controller

C V A E P U Set model to

Model can

be used by

var oModel = new sap.ui.model.json.JSONModel(); var oView = this.getView(); oView.setModel(oModel);

JS

Page 196: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 214 Internal

Setting Models Named models

• It is possible to set multiple models by specifying individual names for the models, which are used

to identify them. Such a model is called a “named model”.

• App descriptor models are named by the key in the “models” section

• You can set models with the same name on multiple UI controls, but these names must be unique

within a UI control. If you set a model with the same name, the original model will be replaced by

the new model.

• Named models influence the path of the binding. The name of the named model + > sign will be a

prefix of the binding path:

var oModel = new sap.ui.model.json.JSONModel(); var oView = this.getView(); oView.setModel(oModel, "myModel");

var oModel = new sap.ui.model.json.JSONModel(); oView.setModel(oModel, "myModel"); oControl.bindProperty("value", "myModel>name")

JS

J

S

Page 197: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 215 Internal

Setting Models Unset models & get models

• Use the getModel(sModelName) method to get a reference to the current named model of a view

or ui control

• You can unset a model by setting an undefined model with the same name

• Note that if an ancestor (parent, UIArea or Core) has a model with the same name, these UI

controls will inherit that model from its ancestor again.

var oView = this.getView(); if (oView.getModel("myModel")){ oView.setModel(undefined, "myModel"); }

JS

Page 198: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 216 Internal

Setting Models Domain model

• If you set a model without a name on the component controller, this model is named as the domain

model

• A domain model can be used in all child controls of the component controller without a name prefix

var oModel = new sap.ui.model.json.JSONModel(); var sComponentId = sap.ui.core.Component.getOwnerIdFor(this.getView()); var oComponentController = sap.ui.component(sComponentId); oComponentController.setModel(oModel);

Domain Model

JS

{ "sap.app": { ... "dataSources": { "invoiceRemote": { "uri": "/services.odata.org/V2/Northwind/Northwind.svc/", "type": "OData", "settings": { "odataVersion": "2.0" } } } }, ... "sap.ui5": { ... "models": {

"" : { "dataSource": "invoiceRemote" } } } } App Descriptor: manifest.json

Page 199: BuildSAPFioriUIsWithSAPUI5_v2

Binding Modes

Page 200: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 218 Internal

Binding Mode

In UI5, DATA BINDING is used to bind UI5 controls to a data models that holds the application data, so that the

controls are updated automatically whenever the model data is changed

one-way binding When one-way binding is used, only changes

of data in the model will change the data in all

bounded UI controls. If the data is changed in the control, the data in the model will be unchanged. To change the data in the

model, you need to update this data by coding.

one-time binding

When one-time binding is used, only first setting

of data in the model will change the data in all

bounded UI controls. If the data is changed in a control, the data in the model and other controls will be unchanged. To

change the data in the model, you need to update this data by coding, but the bounded controls will not change.

two-way binding

With two-way-binding the model data is updated

whenever the value of a bound control changes,

e.g. through user input.

Page 201: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 219 Internal

Setting the Binding Mode

var oView = this.getView(); var myModel = oView.getModel("myModel"); myModel.setDefaultBindingMode(sap.ui.model.BindingMode.TwoWay);

JS

<Text id="idElementBindingPhone" text: "{ path:'/company/contact/0/phone' mode:sap.ui.model.BindingMode.OneWay }" /> X

ML

Vie

w

Ap

p D

escri

pto

r

... "sap.ui5": { ... "models": { "invoice" : { "dataSource": "invoiceRemote",

"settings" : { "defaultBindingMode" : "OneWay" } } } ...

Page 202: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 220 Internal

Exercise

Page 203: BuildSAPFioriUIsWithSAPUI5_v2

OData Simple Query Language

Page 204: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 222 Internal

OData Simple Query Language

OData specifies a simple yet powerful

query language that allows a client to

request arbitrary operations to server-

side datasets

The names of all query string

parameters defined by OData are

prefixed with a $ character

Operation Query Option SQL Equivalent

Filtering $filter Where clause

Projecting $select Field selection

Sorting $orderby Sort

Paging $top Up to .. rows

$skip -

Inlining $expand Innerjoin

Count $count Count(..)

$inlinecount -

Service Root URI Resource path Query options

<SAP OData Engine>/iwfnd/USERSERVICE/UserCollection?<query parameters>

List of (most important) Query options: http://www.odata.org/developers/protocols/uri-conventions#QueryStringOptions

Page 205: BuildSAPFioriUIsWithSAPUI5_v2

OData Paging

Page 206: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 224 Internal

Client-Side Paging

• The query options $top and $skip can be used for client-side paging

• When solely using the query option $top, the service only returns the first <n> results specified by

the number passed via $top. When it is used in combination with $skip, it ignores the first number

of rows and you can walk through the dataset with delta rows.

Row 1 - 7 Row 8 - 14

/$top=7 /$top=14&$skip=7

http://services.odata.org/OData/OData.svc/Products?$top=14&$skip=7

Service Root URI Resource Path Query Options

Page 207: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 225 Internal

Client-Side Paging

• In SAPUI5, $top and $skip aren’t implemented as parameters, instead their behavior is

implemented out-of-the-box in the UI controls themselves. For example, List, Table and ComboBox

all support paging.

• UI control parameters are used to activate paging (growing) and set the threshold that is used to

determine the $top and $skip for the OData call.

• Note that even if it is activated in the UI control, paging will not work if the bounded OData service

doesn’t handle the paging parameters in the back-end system.

<Table id="catalogTable" class="navTableControlLayout" items="{ path:'/Products' }" growing="true" growingScrollToLoad="true" growingThreshold="45"> ... </Table>

Page 208: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 226 Internal

Number of Records

• Adding $inlinecount=allpages to the query option returns the number of entries in an entity set

as part of the response based on these query options.

• Paging does not influence counting and will be ignored when determining the number of entries.

<SAP OData Engine>/IWFND/CATALOGSERVICE;v=2/ServiceCollection/$count

Service Root URI Resource Path

<SAP OData Engine>/IWFND/CATALOGSERVICE;v=2/ServiceCollection?$top=8&$inlinecount=allpages

Service Root URI Resource Path Query Options

• Adding $count to the resource path returns the total number of entries in an entity set in plain text

format.

Page 209: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 227 Internal

Number of Records

In SAPUI5, $count and $inlinecount=allpages aren’t implemented as parameters of the path,

instead they can be set in the model. For this, you set the property defaultCountMode of the model:

The following count modes are supported by SAPUI5: • Request Count is retrieved by sending a separate $count request, before requesting data

• Inline Count is retrieved by adding $inlinecount=allpages and is included in the data request

• InlineRepeat Count is retrieved by adding $inlinecount=allpages and is included in every data request

• Both Count is retrieved by a separate request up-front and inline with each data request

• None Count is not requested from the server

var oModel = new sap.ui.model.odata.v2.ODataModel({ defaultCountMode:sap.ui.model.odata.CountMode.Inline });

Page 210: BuildSAPFioriUIsWithSAPUI5_v2

Data Typing

Page 211: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 229 Internal

Data Typing Data type process

01.05.2015 01-05-2015

Parse

Format

Validate

20150501

BACK-END FORMAT SAPUI5 MODEL FORMAT DISPLAY FORMAT

n/a

• Data typing is important because the internal SAPUI5 model data format doesn’t have to be the

same format in the back-end system as the data format you want to present on the UI.

• Data binding supports the definition of types which can be handed over when binding properties.

Bound properties with a defined type will automatically be formatted when displayed on the UI, input

values in UI controls are parsed and converted back to the defined type in the model.

Page 212: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 230 Internal

Data Typing Primitive types

SAP delivers the following primitive types out-of-the box:

• sap.ui.model.type.Boolean

• sap.ui.model.type.Currency

• sap.ui.model.type.Date

• sap.ui.model.type.DateTime

• sap.ui.model.type.FileSize

Primitive types are based on the core model types:

• sap.ui.model.SimpleType

• sap.ui.model.CompositeType

You can create your own data types by extending the core model type of one of the existing primitive

data types.

• sap.ui.model.type.Float

• sap.ui.model.type.Integer

• sap.ui.model.type.String

• sap.ui.model.type.Time

Page 213: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 231 Internal

Data Typing Constructor parameters

For each type, you can define the following parameters in the constructor:

sap.ui.model.type.DataType(oFormatOptions,oConstraints);

Format options:

Format options define how a value is formatted and displayed on the UI.

Constraints (optional):

Constraints define how an input value entered in

the UI should look. When parsed, the value

is then validated against these constraints.

var oText = this.getView().byId("idPropertyBindingText"); var oFormatOptions = {}; oFormatOptions.minIntegerDigits = 2; oFormatOptions.maxIntegerDigits = 3; var oConstraints = {}; oConstraints.minimum = 10; oConstraints.maximum = 745; var oIntegerType = new sap.ui.model.type.Integer(oFormatOptions,oConstraints); oText.bindProperty("value", { path: "/company/contact/1/phone", type: oIntegerType} });

Page 214: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 232 Internal

Data Typing Binding types

You can use data typing directly within your binding, even for calculation fields and expression binding

in XML

oControl.bindProperty("controlProperty",{ parts: [ { path: "/firstname", type: sap.ui.model.type.String },{ path: "/lastname" , type: sap.ui.model.type.String } ], formatter: function(firstname,lastname){ if (firstname && lastname){ return "Dear" + firstname + " " + lastname + ", " } else ( return null } } });

<TextView text="Hello {parts:[ { path: "/firstname", type: sap.ui.model.type.String },{ path: "/lastname", type: sap.ui.model.type.String }], formatter: ".myFormatter"}, "/>

javaScript XML-based

Page 215: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 233 Internal

Data Typing Events & event handlers

• Data types will follow a sequence flow when data is bound to the model and the bound UI control

property is changed. Based on this flow, the framework calls methods and fires events.

• You can use event handlers to react to these events. Even when setting event handlers to an

ancestor UI control, this will still react to this event, because the event will bubble up through its

parents until it reaches sap.ui.core

Data Type Method Fire Data Type Event Control Event Handler

parseValue sap.ui.model.parseException attachParseError

formatValue sap.ui.model.formatException attachFormatError

validateValue sap.ui.model.validateException attachValidationError

validateValue When no exception raised attachValidationSuccess

Page 216: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 234 Internal

Data Typing Example data type events

... var oText = this.getView().byId("idPropertyBindingText"); sap.ui.getCore().attachValidationError(function(e){ var oElement = e.getParameter("element"); if (oElement.setValueState){ oElement.setValueState(sap.ui.core.ValueState.Error); }}); oText.attachValidationSuccess(function(e){ var oSource = e.getSource(); if (oSource.setValueState){ oSource.setValueState(sap.ui.core.ValueState.Success); }}); oText.attachParseError(function(e){}); oText.attachFormatError(function(e){}); ...

React to all typed UI controls

React to the specific

UI control only

Page 217: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 235 Internal

Data Typing Example custom data type

sap.ui.define(['jquery.sap.global', 'sap/ui/model/SimpleType'], function(jQuery, SimpleType) { "use strict"; var myOwnType = SimpleType.extend("myproject.type.MyOwnType", { constructor : function () { SimpleType.apply(this, arguments); this.sName = " MyOwnType"; } }); myOwnType.prototype.formatValue = function (vValue, sInternalType) { return vValue; }, myOwnType.prototype.parseValue = function (vValue, sInternalType) { return vValue; }, myOwnType.prototype.validateValue = function (oValue) { if (!/^([a-zA-Z]*)$/.test(oValue)) { throw new sap.ui.model.ValidateException("Name can only exist letters"); } } return myOwnType; });

Validate the value

Invalid, throw an exeption

Page 218: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 236 Internal

Data Typing Formatter classes

• Beside using data types in the model, you can also use standard formatter classes, which can be

used for formats such as dates.

• List of predefined formatter classes: • sap.ui.core.format.DateFormat

• sap.ui.core.format.NumberFormat

• sap.ui.core.format.Filesize

• The formatter classes can only be used for parsing and formatting data and do not provide any

validation.

jQuery.sap.require("sap.ui.core.format.DateFormat"); var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({pattern: "dd/MM/yyyy HH:mm"}); var oText = this.getView().byId("idPropertyBindingText"); oText.setValue(oDateFormat.format(oDate)); oText.attachChange(function () { oDate = oDateFormat.parse(oField.getValue()); });

Page 219: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 237 Internal

OData Primitive Types

• SAPUI5 supports simple types that are used

together with OData models.

• These types support OData Version 2.0

including relevant property facets as

constraints.

• All types have the nullable constraint

which specifies whether empty input is

allowed. All other constraints are type-

specific.

OData Type SAPUI5 Type Implementation

Edm.Boolean sap.ui.model.odata.type.Boolean

Edm.Byte sap.ui.model.odata.type.Byte

Edm.DateTime sap.ui.model.odata.type.DateTime

Edm.DateTimeOffset sap.ui.model.odata.type.DateTimeOffset

Edm.Decimal sap.ui.model.odata.type.Decimal

Edm.Double sap.ui.model.odata.type.Double

Edm.Guid sap.ui.model.odata.type.Guid

Edm.Int16 sap.ui.model.odata.type.Int16

Edm.Int32 sap.ui.model.odata.type.Int32

Edm.Int64 sap.ui.model.odata.type.Int64

Edm.SByte sap.ui.model.odata.type.SByte

Edm.Single sap.ui.model.odata.type.Single

Edm.String sap.ui.model.odata.type.String

Edm.Time sap.ui.model.odata.type.Time

Page 220: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 238 Internal

OData Entity Types

• You can use OData entity types in data bindings just like other model data types

• OData entity types are very useful when used in XML templating.

When you bind properties using the sap.ui.model.odata.AnnotationHelper formatter, these

properties are automatically typed including the constraints based on the definition in the OData

metadata.

<Label text="{path: 'Label', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/> <Input value="{path: 'Value', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>

<Label text="Birthday"/> <Input value="{ path: 'Birthday', type: 'sap.ui.model.odata.type.DateTime', constraints: { displayFormat: 'Date', nullable: false } }"/>

Page 221: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 239 Internal

Exercise

Page 222: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 240 Internal

Metadata Property Binding

• The extended syntax makes it possible to access the metadata for certain properties of an entity in

OData services, such as heading, label, and precision using property binding.

• The annotations can be addressed either absolute or relative to a data path, and the path to the

metadata must therefore be marked with /#.

• An absolute binding path starts with the entity type name followed by the property name. Property

attributes can be accessed with @ + propertyName, nodes can be accessed with the node name

only.

<Label text="{/#Product/Price/@sap:label}"/>

Entity Type Annotation

Property Annotation Marker

Page 223: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 241 Internal

• In addition, a relative binding path can also be resolved relative to metadata properties.

• In the controller, it looks like this:

<Label id="mylabel" text="{UserCollection('FIORIUSER')/fullname/#@sap:label}"}"/>

Metadata Property Binding

var myLabel = this.getView().byId("myLabel"); myLabel.bindProperty("text","City/#@sap:label"}); myLabel.bindElement("UserCollection('FIORIUSER')");

Relative Property Path Annotation

Annotation Marker

Page 224: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 242 Internal

Exercise

Page 225: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 243 Internal

Filtering

• Binding results of an aggregation can be restricted using filters

like where clauses in a SQL statement.

• An array of sap.ui.model.Filter objects can be used to build

the where clause. The filter supports and and or operators.

• sap.ui.model.FilterOperator can be used to assign a

property and the filter value. SAPUI5 supports the following operators:

EQ, NE, LT, LE, GT, GE, BT, Contains, StartsWith and EndsWith.

• Filters must be assigned to the aggregation using the filter method or in the constructor of the

binding path:

Filter

var oFilter = new sap.ui.model.Filter("LastName", sap.ui.model.FilterOperator.EQ , 'JOHNSON', true); aFilters.push(oFilter); var sLangu = sap.ui.getCore().getConfiguration().getLocale().getSAPLogonLanguage(); oFilter = new sap.ui.model.Filter("Language", sap.ui.model.FilterOperator.EQ , sLangu); aFilters.push(oFilter);

Result of filter in an SQL-like syntax: where lastname eq 'JOHNSON' and Language eq 'EN'

Page 226: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 244 Internal

Filtering

• The parameter $filter is used to query a dataset. The OData specification supports a lot of

different filter options, but SAP back ends do not support them all. Just like sorting, your SAP OData

service will provide annotations if filtering is not supported

• Applying filters is just like what we did before with other models. You need to build a filter array and

call the filter method on the binding.

http://services.odata.org/OData/OData.svc/ProductCollection?$filter=startswith(Name,'S')

Service Root URI Resource Path Query Options

onSearchPressed: function(evt) { var sValue = evt.getSource().getValue(); var oFilter = new sap.ui.model.Filter("firstname", sap.ui.model.FilterOperator.Contains, sValue); var oBinding = this.byId("catalogTable").getBinding("items"); oBinding.filter([oFilter]); },

Filter

Page 227: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 245 Internal

Exercise

Page 228: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 246 Internal

Operation Modes

• OData model v2 supports both client-side and server-side sorting and

filtering setting for an operation mode.

• When initiating the model, you can specify sDefaultOperationMode

using the sap.ui.model.OperationMode.Server or

sap.ui.model.OperationMode.Client.

• If you use the client-side operation mode, all data will be requested

and cached on the client side. When calling the operation, no round

trip to the server occurs, instead the operation is performed for the

existing data.

• The sap.ui.model.OperationMode.Server is the default mode for

OData models and recommended for Fiori applications.

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl: "/sap/opu/odata/iwfnd/USERSERVICE/", defaultOperationMode: sap.ui.model.OperationMode.Client });

Server OperationMode

Client OperationMode

Page 229: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 247 Internal

Custom Query Options

Global query options used in all OData calls

• For all OData services, you can use addition URL configuration parameters. SAPUI5 sets most URL

parameters automatically, according to the respective binding.

• For example for authentication tokens or general configuration options you can add additional

arguments to the request URL. These parameters will be included in every request sent to the

OData server.

<SAP OData Engine>/IWFND/CATALOGSERVICE;v=2/ServiceCollection?sap-language=EN

Service Root URI Resource Path Query Options

var oModel = new sap.ui.model.odata.v2.ODataModel("http://myserver/MyService.svc/?myParam=value&myParam2=value");

Page 230: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 248 Internal

Custom Query Options Global query options for OData services and metadata requests

• You can pass URL parameters that are used for $metadata requests only (metadataUrlParams) as

well as URL parameters that are only included in data requests (serviceUrlParams). The

parameters are passed as maps when creating the OData model:

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl: "http://services.odata.org/Northwind/Northwind.svc", serviceUrlParams: { myParam1: "value1", myParam2: "value2" }, metadataUrlParams: { myParam3: "value3", myParam4: "value4" } });

http://services.odata.org/Northwind/Northwind.svc/Products?myParam1=Value1&myParam2=Value2

http://services.odata.org/Northwind/Northwind.svc/$metadata?myParam3=Value3&myParam4=Value4

Page 231: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 249 Internal

Custom Query Options

• Some query options parameters must not be included in every request, but should only be added to

specific aggregation or element bindings. Here you can use the custom parameters of the binding

path.

• You can set these in the binding directly in the view or at runtime in the controller:

<Table id="catalogTable" items="{ path:'/ServiceCollection', parameters: { custom:{ 'sap-language' : 'EN' } } }"> </Table>

oTable.bindRows({ path: "/ServiceCollection", parameters: { custom: { "sap-language" : "DE" } }, template: rowTemplate });

XML view JS View Controller

Page 232: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 250 Internal

Exercise

Page 233: BuildSAPFioriUIsWithSAPUI5_v2

Sorting

Page 234: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 252 Internal

• Binding results of an aggregation can be ordered using sorting

like order by in a SQL statement.

• An array of sap.ui.model.Sorter(sPath, bDescending?, vGroup) is used to build the sorting logic.

• When building a sorter, you need to specify the bDescending

parameter if the sort is descending (true) or ascending (false).

• Sorters must be assigned to the aggregation using the sort method or in the constructor of the

binding path.

Sorting

a

b

d

a

b

t

s

3

2

1

1

1

2

1

s

b

b

t

a

a

d

1

1

2

2

1

3

1

sort

Page 235: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 253 Internal

Sorting Example for sorting a list table before showing

oController.prototype._Sort = function () { var oView = this.getView(); var oTable = oView.byId("idTable"); var aSorters = []; var oSorter = new sap.ui.model.Sorter("LastName", true ,"Group"); aSorters.push(oSorter); oSorter = new sap.ui.model.Sorter("FirstName", false ,"Group"); aSorters.push(oSorter); var oBindingItems = oTable.getBinding("items"); oBindingItems.sort(aSorters); }

Page 236: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 254 Internal

Sorting

• The query parameter $orderby is used to sort the OData dataset. You need to specify the field

names separated by a comma. The default sorting is ascending, but descending is also supported

by adding desc separated by a space or %20.

• Keep in mind that SAP OData services built on top of the Business Suite do not access data

directly, instead they use a Gateway layer in between. The implementation of this Gateway OData

Service must support sorting. If sorting is supported, a well-defined SAP EDMX file contains details

about any fields you cannot use. These are marked as sap:sortable="false".

http://services.odata.org/OData/OData.svc/ProductCollection?$orderby=Name%20desc

Service Root URI Resource Path Query Options

Page 237: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 255 Internal

Sorting

• Don’t use query parameters directly, instead let the OData model handle operations.

• You only need to define a sorter directly in the view or at runtime in the controller.

• The model will interpret the bindings and will construct the

according OData URI to the server automatically

sortCatalogTableByNameDescending: function(){ var sPath = "Name" var bDescending = true; var oSorter = new sap.ui.model.Sorter(sPath, bDescending); var oBinding = this.byId("catalogTable").getBinding("items"); oBinding.sort([oSorter]); };

a b

d

a b

t

s

3 2

1

1 1

2

1

s b

b

t a

a

d

1 1

2

2 1

3

1

sort

<Table id="catalogTable" inset="false" items="{ path: '/ProductCollection' sorter: [{ path: 'field1', descending: false }, { path: 'field2', descending: true }] }"> ... </Table>

Page 238: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 256 Internal

Exercise

Page 239: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 257 Internal

Field Selection

• You use parameter $select to select only those fields of an OData service that you will use in your

application. This reduces the amount of data transported between the SAPUI5 application and the

server.

• You specify this parameter selection when you specify the binding path of your aggregation or

element:

http://services.odata.org/OData/OData.svc/Products?$select=Name,Price

Service Root URI Resource Path Query Options

<Table id="catalogTable" class="navTableControlLayout" items="{ path:'/Products', parameters:{ select: 'Name,Price' } }" growing="true" growingScrollToLoad="true"> ... </Table>

select

Page 240: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 258 Internal

Inner Joins

• You use parameter $expand to combine related tables by creating inner joins. This is not restricted

to direct association, you can also use it for deeper layers.

• OData expands reduce the number of calls between the SAPUI5 application and the server.

• You specify these parameter expands when you specify the binding path of your aggregation or

element:

<SAP OData Engine>/IWFND/CATALOGSERVICE;v=2/ServiceCollection?$expand=EntitySets

Service Root URI Resource Path Query Options

expand

<Table id="catalogTable" class="navTableControlLayout" items="{ path:'/ServiceCollection', parameters:{ expand: 'EntitySets' } }"> ... </Table>

Page 241: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 259 Internal

Exercise

Page 242: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 260 Internal

Entity Type

Navigation

PropertyProperty Type

Simple TypeComplex

Type

Entity Set

Entity

*

*

1..*

1..*

1*

Entity Key

1..*

1

Association

2

*

Entity

Container

Service

Document

Function

Import *

1Describes

structure of

1

*

*

*

CRUD Operations

• OData uses standard HTTP methods as CRUD operators for manipulating the dataset

Combine multiple requests in one call: POST $batch

Read a row: GET

Modify the whole row PUT

Modify some fields

of a row PATCH

Delete a row DELETE

Read a list: GET

Insert a row: POST

Batch of

multiple calls

Call Function: GET() || POST()

Page 243: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 261 Internal

CRUD Operations

• Beside automatic data handling, the OData model also allows manual CRUD (create, read, update,

delete) operations on the OData service.

Operation HTTP Verb SAPUI5 sap.ui.model.odata.v2.ODataModel

Create POST create(sPath, oData, oContext?, fnSuccess?, fnError?)

Read GET read(sPath, oContext?, oUrlParams?, bAsync?, fnSuccess?, fnError?)

Update PUT/PATCH update(sPath, oData, oParameters?)

Delete DELETE remove(sPath, oParameters?)

Batch POST submitBatch(fnSuccess?, fnError?, bAsync?)

Function Import POST/GET callFunction(sFunctionName, sMethod, oParameters, oContext, fnSuccess, fnError)

CSRF Token GET refreshSecurityToken(fnSuccess?, fnError?, bAsync?)

Page 244: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 262 Internal

CRUD Operations

There are some rules you must keep in mind when using OData CRUD operations:

• All operations require a mandatory sPath parameter as well as an optional mParameters map.

• If a manual operation returns data, the data is imported into the data cache of the OData model.

• The create and update methods also require a mandatory oData parameter for passing the created

or changed data object.

• Each operation returns an object containing a function abort, which can be used to abort the

request. If the request is aborted, the error handler is called. This ensures that the success or the

error handler is executed for every request.

• It is also possible to pass additional header data, URL parameters, or an eTag when you use

manual CRUD operators.

Page 245: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 263 Internal

Reading Entities

• The read function triggers a GET request to the oData service, calling an entity or entityset

depending on the path specified.

• Depending on the processing or the service, you will retrieve data in the success callback handler

function or an error callback handler will be called.

var sPath = "/Products(999)"; oModel.read(sPath, { success: function(oData,response){ ... //process data }, error: function(oError){ ... //handle error } });

Page 246: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 264 Internal

Creating Entities

• The create function triggers a POST request to an OData service. The application has to specify the entity set in which the new data is to be created.

var oData = { ProductId: 999, ProductName: "myProduct" } oModel.create("/Products", oData, { success: function(oData,response){ ... //process data }, error: function(oError){ ... //handle error } });

Page 247: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 265 Internal

Updating Entities

• The update function triggers a PUT/MERGE request to an OData service entity.

• After a successful request, the bindings in the model are updated. This refresh is triggered

automatically.

• You can use a merge parameter if you only want to update some or all of the fields.

var oData = { ProductId: 999, ProductName: "myProductUpdated" } oModel.update("/Products(999)", oData, { success: function(oData,response){ ... //process data }, error: function(oError){ ... //handle error }, merge: true });

Page 248: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 266 Internal

Deleting Entities

• The remove function triggers a DELETE request to an OData service to specify the entity path

which should be deleted.

oModel.remove("/Products(999)", { success: function(oData,response){ ... //process data }, error: function(oError){ ... //handle error } );

Page 249: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 267 Internal

Refresh After Change

• The model provides a mechanism to automatically refresh bindings that depend on changed

entities.

• If you carry out a create, update or delete function, the model identifies the bindings and triggers a

refresh for these bindings.

• If the model runs in batch mode, the refresh requests are bundled together with the changes in the

same batch request.

• You can disable the auto refresh by calling setRefreshAfterChange(false). If the auto refresh is

disabled, the application has to take care of refreshing the respective bindings.

oModel.setRefreshAfterChange(false);

Page 250: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 268 Internal

Refresh

• The refresh function refreshes all data within an OData model.

• Each binding reloads its data from the server. For list or element bindings, a new request to the

backend is triggered. If the XSRF token is no longer valid, it has to be fetched again with

a read request to the service document.

• Data that has been imported via manual CRUD requests is not reloaded automatically.

oModel.refresh();

Page 251: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 269 Internal

XSFR Token

• To address cross-site request forgery, an OData service may require XSRF tokens for change

requests by the client application. In this case, the client has to fetch a token from the server and

send it with each change request to the server.

• The OData model fetches the XSRF token when reading the metadata and then automatically

sends it with each write request header.

• If the token is no longer valid, a new token can be fetched by calling

the refreshSecurityToken() function on the OData model.

• The token is fetched with a request to the service document. To ensure that you get a valid token,

make sure that the service document is not cached.

oModel.refreshSecurityToken({ success: function(oData,response){ ... //process data }, error: function(oError){ ... //handle error } );

Page 252: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 270 Internal

Custom HTTP Headers

• You can add custom headers which are sent with each request. To do this, provide a map of

headers to the OData model constructor or use the setHeaders() function:

• When you add custom headers, all previous custom headers are removed if not specified again in

the headers map.

• Some headers are private, that is, they are set by the OData model internally and cannot be set:

• "accept"

• "accept-language"

• "maxdataserviceversion"

• "dataserviceversion"

• "x-csrf-token"

var oModel = new sap.ui.model.odata.v2.ODataModel({ headers: { "myHeader1" : "value1", "myHeader2" : "value2" } });

oModel.setHeaders({ "myHeader1" : "value1", "myHeader2" : "value2“ });

Page 253: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 271 Internal

Batch Operator

• The batch operator is used to bundle a collection of single OData requests and send them together

as one batch request call.

• All single requests are handled by the OData server and all results are combined in one batch

response.

• The collection of single OData requests are sent in the payload of the HTTP call. This makes it

possible to protect data such as query strings and header information, which is usually visible in

normal OData call.

<SAP OData Engine>/IWFND/CATALOGSERVICE;v=2/$batch

Service Root URI Resource Path

Page 254: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 272 Internal

Batch Operator

HTTP Request

POST $batch HTTP/1.1

Content-Type: multipart/mixed;boundary=batch HTTP Header

HTTP Payload

HTTP Operation

- HTTP method POST

- HTTP url /$batch

- HTTP version 1.1

Content-type of payload

- content-type multipart/mixed

- separator of parts batch --batch

Content-Type: application/http

GET BusinessPartners HTTP/1.1

--batch

Content-Type: application/http

GET Products HTTP/1.1

--batch--

Part 1 – http request

- HTTP method GET

- HTTP url /BusinessPartners

Part 2 – http request

- HTTP method GET

- HTTP url /Products

Page 255: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 273 Internal

Batch Operator HTTP Response

--batch

Content-Type: application/http

GET BusinessPartners HTTP/1.1

--batch

Content-Type: application/http

GET Products?$top=200 HTTP/1.1

--batch--

HTTP $batch Request

Content-Type: multipart/mixed;boundary=batch

POST $Batch HTTP/1.1

--eejjeeffe0

Content-Type: application/http

...

HTTP/1.1 200 OK

Content-Type: application/atom+xml;type=feed

...

<feed>

...

</feed>

--eejjeeffe0

...

--eejjeeffe0--

HTTP $batch Response

Content-Type: multipart/mixed;boundary=eejjeeffe0

HTTP/1.1 202 Accepted

Part 1

HTTP Request

- HTTP method GET

- HTTP url /BusinessPartners

HTTP Response

Part 2

HTTP Request

- HTTP method GET

- HTTP url /Products?$top=200

HTTP Response

Page 256: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 274 Internal

Batch Operator $batch changeset

• In a OData batch call, you can combine

single requests together in what is

known as a changeset.

• This changeset can be used to create

a logical unit of work. If one call in the

changeset fails, all will fail.

• changeset is a reserved word in

OData

POST $batch HTTP/1.1

Content-Type: multipart/mixed;boundary=batch

--batch

Content-Type: multipart/mixed; boundary=changeset

--changeset

Content-Type: application/http

Content-Transfer-Encoding: binary

PUT BusinessPartners('0100000044') HTTP/1.1

Content-Type: application/atom+xml

Content-Length: 10210

<entry> …</entry>

--changeset

Content-Type: application/http

Content-Transfer-Encoding: binary

PUT SalesOrders('0500000009') HTTP/1.1

Content-Type: application/atom+xml

Content-Length: 10210

<entry>…</entry>

--changeset--

--batch--

batc

h p

art

Ch

an

geset p

art 1

C

han

geset p

art 2

Page 257: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 276 Internal

All manual CRUD requests, as well as requests triggered by a binding, are collected and bundled in a

default batch group and are automatically submitted in a single batch request. The framework does

this by default for every thread, meaning that batch request is sent in a timeout immediately after the

current call stack is finished.

Using batch calls is the default behavior for the OData model v2.

OD

AT

A

SE

RV

ER

Default Batch Group

Auto Submit

Batch Operator Initiate batch mode

ON var oModel = new sap.ui.model.odata.v2.ODataModel(myServiceUrl);

Page 258: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 277 Internal

If you want to turn of the batch mode, you can do so in the constructor of the model. In this case, all

requests for this model are single calls to the OData server. The recommended approach is to use

batch mode, but if the OData server doesn’t support batch mode, you can fallback to this mode.

OD

AT

A

SE

RV

ER

Batch Operator Turn batch mode off

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl : myServiceUrl, useBatch : false});

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl : myServiceUrl, useBatch : true});

OFF ON

Page 259: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 278 Internal

Batch Operator Batch groups

The model itself cannot decide how to bundle the requests. For this, SAPUI5 provides

the batchGroupId. For each binding and each manual request, a batchGroupId can be specified. All

requests belonging to the same group are bundled into one batch request. Requests that do not have

a batchGroupId are bundled in the default batch group.

Batch Group ID:

myGroupId_2

Auto Submit

Auto Submit

Batch Group ID:

myGroupId_1

OD

AT

A

SE

RV

ER

var oPanelEB = this.getView().byId("idPanelEB"); oPanelEB.bindElement({ path:"/myEntities", parameters: { batchGroupId: "myGroupId_2" } });

<Table id="catalogTable" inset="false" items="{ path: '/ProductCollection' parameters: { batchGroupId: 'myGroupId_1' } }"> ... </Table>

Page 260: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 279 Internal

Batch Operator Batch groups

By default, all changes have their own changeset. When you want to create an LUW of changes, you

need to set a changeSetId for changes. Each change belonging to the same changeSetId is bundled

into one changeset in the batch request.

Auto Submit

Same BatchGroupId

OD

AT

A

SE

RV

ER

var oPanelEB = this.getView().byId("idPanelEB"); oPanelEB.bindElement({ path:"/myEntities", parameters: { batchGroupId: "myGroupId_2", changeSetId: "mySetId_1" } });

<Table id="catalogTable" inset="false" items="{ path: '/ProductCollection' parameters: { batchGroupId: 'myGroupId_1', changeSetId: 'mySetId_1' } }"> ... </Table>

Same ChangeSetId

no ChangeSetId

Page 261: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 280 Internal

Batch Operator Batch calls submitted manually

You can use the the setDeferredBatchGroups() method to set each batch group to deferred: All

requests belonging to the batch group are then stored in a request queue. The deferred batch group

must then be submitted manually by means of the submitChanges(batchGroupId) method. If you

do not specify a batch group ID when calling submitChanges(), all deferred batch groups are

submitted.

var oModel = new sap.ui.model.odata.v2.ODataModel(myServiceUrl); oModel.setDeferredBatchGroups(["myGroupId_1", "myGroupId2_2"]);

Deferred Batch Groups

Submit One Deferred Group Batch Group ID:

myGroupId_1

Batch Group ID:

myGroupId_2

Submit All Deferred Groups

OD

AT

A

SE

RV

ER

oModel.submitChanges({ batchGroupId: "myGroupId", success: mySuccessHandler, error: myErrorHandler });

Page 262: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 281 Internal

Two-Way Binding Initiate two-way binding OData models

By default, the OData model is configured with the one-way binding mode. To enable two-way binding

in an OData model version 2, you need to set the defaultBindingMode to TwoWay:

By default, all changes are collected in a batch group called "changes" which is set to deferred.

To submit the changes, use submitChanges().

To avoid inconsistent data, the paging feature should not be used with two-way binding!

You may also use filtering and sorting in two-way bindings. But you have to make sure that there are

no pending changes to avoid inconsistent data on the UI. Therefore, before you carry out sorting or

filtering, you must submit or reset changes. You can check for changes with the method hasPendingChanges().

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl : myServiceUrl, defaultBindingMode : sap.ui.model.BindingMode.TwoWay });

Page 263: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 282 Internal

Two-Way Binding Reset changes

In the OData model v2 two-way bindings, the data changes are made on a data copy. This enables

you to reset the changes without sending a new request to the back end to fetch the old data again.

With resetChanges() you can reset all changes. You can also reset only specific entities or entity sets

by calling resetChanges with the paths of the aggregation or element.

The resetChanges method is mostly used in the error handler of the submitChanges().

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl : myServiceUrl, defaultBindingMode : sap.ui.model.BindingMode.TwoWay }); //do a change oModel.setProperty("/myEntity(0)", oValue); //reset the change oModel.resetChanges(["/myEntity(0)"]);

Page 264: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 283 Internal

Two-Way Binding Specify own batch groups and changesets

You can collect the changes for different entities or

types in different batch groups. To configure this,

use the setChangeBatchGroups() method of the

model.

To collect the changes for all entity types in the

same batch group, use '*' as EntityTypeName.

If the change is not set to deferred, the changes are sent to the back end immediately.

By setting the single parameter for changeSet to true or false, you define if a change is assigned its

own change set (true) or if all changes are collected in one change set (false).

If the single parameter ID is set to true, the model will ignore the changeSetId .

The first change of an entity defines the order in the change set.

var oModel = new sap.ui.model.odata.v2.ODataModel({ serviceUrl : myServiceUrl, defaultBindingMode : sap.ui.model.BindingMode.TwoWay }); oModel.setDeferredBatchGroups(["myGroupId", "myGroupId2"]); oModel.setChangeBatchGroups({ "EntityTypeName": { batchGroupId: "myGroupId", [changeSetId: "ID",] [single: true/false,] } );

Page 265: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 284 Internal

Two-Way Binding Create new entities

In the OData model, you need an object to create new entities for a specified entity set. For this,

SAPUI5 supports the createEntry() method which returns a context object that points to the newly

created entity. The application can bind against these objects and change the data by means of two-

way binding.

To store the entities in the OData back end, the application calls submitChanges(). To reset the

changes, the application can call the deleteCreatedEntry() method.

The application can choose the properties that shall be included in the created object and can pass its

own default values for these properties. By default, all property values are empty, that is, undefined.

Page 266: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 285 Internal

Exercise

Page 267: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 286 Internal

Accessing Cached Data from an OData Model

• The data requested from an OData service is automatically cached in the OData model, except for

manual requested data in OData model version 1.

• This cached data can be accessed by the getData() and the getProperty() methods, which

return the entity object or value.

• As these methods trigger a round trip to the back end, you can only access entities that have

already been requested and cached.

• The getData() method returns single entities (elements) and the getProperty() method returns

properties. All returned values are copies of the data in the model.

• Entity sets (aggregations) cannot be returned directly by the model, but when you bind these to a UI

control, you can use the oControl.getList() method to get the binding contexts of all entities in

the list.

• Note that cached data in the OData model isn’t the same as browser-cached OData services.

Cached data in the OData model is handled by the SAPUI5 framework. Browser-cached OData

services are handled by the browser.

Page 268: BuildSAPFioriUIsWithSAPUI5_v2

Function Imports

Page 269: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 288 Internal

Function Imports

OData supports further service operations (function imports) that can be invoked by the HTTP methods

GET or POST for anything that cannot be mapped to the standard CRUD operations. This means that

you should only create function imports for custom operations that cannot be invoked using a standard

operation.

Function imports get their importing parameters through query options. Possible returning parameters

are no return, any entity or any entityset. This depends on the implementation of the function import.

<SAP OData Engine>/IWFND/MY_PRICE_CATALOG/ChangeAllPrices?ammount=10&change=increase

Service Root URI Resource Path Query Options

Page 270: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 289 Internal

Function Imports

In the UI, you can use the statement callFunction(sFunctionName, mParameters?) to trigger a

request to the function import OData service. You need to specify the HTTP method GET/POST and

provide the importing parameters through the urlParameters.

var oModel = new sap.ui.model.odata.v2.ODataModel(myServiceUrl); oModel.callFunction('ChangeAllPrices',{ method:'GET', urlParameters:{ ... //importing parameters } success: function(oData,response){ ... //process return }, error: function(oError){ ... //handle error } })

Page 271: BuildSAPFioriUIsWithSAPUI5_v2

MIME handling ($value)

Page 272: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 291 Internal

MIME

In OData every entity can have a related MIME. By adding the $value to the path of the entity, you will

receive the MIME in the payload. This makes it possible to create, read, update and delete a MIME,

just like you handle entities.

A MIME in OData is simply specified as raw data with a content type. This makes it possible to bind

any type of data (e.g. office documents, pdf, videos, images) to the entity.

If you need to bind more than one MIME to an entity, you need to create a MIME entity set and use

navigation properties to access them. The reason for this is that there is only a 0..1 relation between

the entity and the MIME.

Service Root URI Resource Path

<SAP OData Engine>/iwfnd/USERSERVICE/UserCollection('FIORIUSER')/$value

Page 273: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 292 Internal

MIME

MIME is not yet supported by the OData model. In the current implementations of the OData model,

$value and raw payloads are not yet implemented, meaning you have to specify the source statically.

However, you can use the OData model to get the binding path and set the MIME source in the

controller at runtime.

<Image id="myImage" width="10rem" src="/sap/opu/odata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection('AA')/$value"> </Image>

Page 274: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 293 Internal

MIME

As an alternative for CRUD MIME operations in SAPUI5, you can build your own jQuery.ajax call.

Keep in mind that you create an entity against an entity set. Here, you need to provide the key fields of

the entity in what is known as the “slug” HTTP header field. The syntax of this slug depends on the

OData implementation.

performSaveMime: function(sPath,sSlug,sContentType,rData){ var mHeaders = {}; mHeaders["slug"] = slug; var jqxhr = $.ajax({ type : 'POST', url : sPath, headers : mHeaders, cache : false, contentType : contentType, processData : false, data : data, }) .done(function(oData, sStatus, oXHR) { alert( "success" ); }) .fail(function(oXHR, sStatus, oError) { alert( "error" ); }) .always(function() { alert( "complete" ); }); },

Page 275: BuildSAPFioriUIsWithSAPUI5_v2

Using Data Binding for Data

Export

Page 276: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 295 Internal

Using Data Binding for Data Export

• Data binding supports the export of data in a specific format so that the data can be used in other

programs.

• You need the export utility sap.ui.core.util.Export and an export type. SAP delivers a Comma

Separated Values export type sap.ui.core.util.ExportTypeCSV out-of-the-box, but you can

build your own export type by extending the sap.ui.core.util.ExportType.

• The export class provides a generate() method that triggers the generation process and returns

an ECMAScript 6 object. The then() handler is called when the generation process has finished. If

you use the OData model, this happens asynchronously. The catch() handler is called if the

generation has failed. When the generation has finished and the export object is no longer needed,

the destroy() method of the export object must called.

• You can use the saveFile() method to export the data to a local file. Be aware that some

browsers have some restrictions.

• Data export is integrated in some UI controls, such as sap.ui.table.Table.

Page 277: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 296 Internal

Using Data Binding for Data Export Process flow example

... jQuery.sap.require("sap.ui.core.util.Export"); jQuery.sap.require("sap.ui.core.util.ExportTypeCSV"); var oSource = e.getSource(); var oModel = oSource.getModel(); var oExport = new sap.ui.core.util.Export({ exportType: new sap.ui.core.util.ExportTypeCSV({ separatorChar: ";“ }), models: oModel, rows: { path: "/company/contact" }, columns: [ { name: "Name", template: { content: { path: "name" } } }, { name: "Phone", template: { content: { path: "phone" } } } ] }); oExport.generate().then(function() { oExport.saveFile("filename"); }).then(function(){ oExport.destroy(); }).catch(function(err) { oExport.destroy(); }); ...

{ company: { contact: [ { name: "Barbara", phone: "873“ }, { name: "Gerry", phone: "734" }, { name: "Susan", phone: "275"} ] }}

Model

Save File Dialog

Name;Phone Barbara;873 Gerry;734 Susan;275

Page 278: BuildSAPFioriUIsWithSAPUI5_v2

Internationalization Introduction

Page 279: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 299 Internal

Internationalization Terms

Internationalization, shortly i18n, in UI5 is one of the important prerequisites of UI5 applications.

Internationalization is the process of designing an application so that it can be adapted to various

languages and regions without the need for changes to the source code - that is, so that it can

be localized. The term also refers to the process of altering an existing application for localization.

Localization is the process of adapting software for a specific region or language by adding locale-

specific components and translating text.

In the following, the terms translation and localization will be used slightly differently: translation relates

to actual translation of texts, while localization comprises all other aspects not directly involving

translation, most notably Locale-specific number and date formatting.

Page 280: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 300 Internal

Internationalization

Some language needs special characters and others use a right-to-left sentences.

i18n is not an issue for application text only but also for voice in sound, text in images and both in

video.

I18n influences also the presentation of dates, amounts and numbers

街头 Straße شارع Street

2015/03/01 01-03-2015

2015, 1 March 1 März 2015

1.002,87 -87.65

1,002.87 87.65-

Page 281: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 301 Internal

Internationalization

• Transactional data

• Text Element

• Error Messages

• Mimes Repository

• Application text with dates

• Application related

• Labels

• Headers

• Mimes

Static

Frontend

Dynamic

Frontend

Dynamic

Backend

Static

Backend

Resource Model

OData Model

Server-side

Client-side

Page 282: BuildSAPFioriUIsWithSAPUI5_v2

Languages

Page 283: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 303 Internal

Languages Identifying the Language Code / Locale

• For the identification of languages, the UI5 framework uses a language code of type string

• The UI5 language codes according to the de facto standard BCP-47, which are used by most

browsers for language identification. It exists of combines a lower case ISO 639 alpha-2 or alpha-3

language code with an ISO 3166 alpha-2 country code. Both codes are combined with an

underscore. An arbitrary sequence of variant identifiers (also separated by underscores) can be

appended as a third component. Example: de, en_US, zh_TW_Traditional

• UI5 applications are often used to connect to ABAP-based SAP application servers. For these

servers, UI5 uses proprietary language codes for compatibility reasons. These language codes

often match an ISO 639 alpha-2 language code and can be used directly. The only exceptions are

ZH, which will be replaced by zh-Hans in UI5, ZF by zh-Hant, 1Q by en-US-x-saptrc and 2Q by en-

US-x-sappsd

ISO 639 alpha-2: zh + ISO 3166 alpha-2: zh_TW + variant: zh_TW_Traditional

sap-language: E => sap-ui-language: en sap-language: D => sap-ui-language: de

Page 284: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 304 Internal

Languages Current Language Code / Locale

• UI5 tries to detect the user’s language or locale with the following steps. The sources are ordered

increasingly by priority and the last available user language/locale wins:

1. If no language can be determined, UI5 uses the default locale ('en')

2. Potentially configured browser language (window.navigator.browserLanguage);

• for Internet Explorer this is the language of the Operating System

3. Potentially configured user language (window.navigator.userLanguage);

• for Internet Explorer this is the language in the Region settings

4. General language information from the browser (window.navigator.language)

5. Only for Android, the language contained in the user agent string (window.navigator.userAgent)

6. Locale configured in the application coding (sap.ui.core.Configuration)

7. Locale configured via URL parameters

• sap-ui-language=en

• You can retrieve the detected language by querying the configuration API of UI5.

var sCurrentLocale = sap.ui.getCore().getConfiguration().getLanguage();

Page 285: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 305 Internal

Languages Right-to-Left Support in Controls

• The Unicode of the HTML pages defines the direction, left-to-right (LTR) or right-to-left (RTL) in

which a browser arranges characters to form words.

• The default base direction of HTML for UTF-8 is left-to-right. Some characters like parentheses and

dots are direction-neutral characters .

• The direction can be overruled by setting the dir attribute of a tag or using CSS. This direction will

also be inherent by its children. The lang attribute will NOT influence the text direction

• UI5 is also supporting directions and the default direction within UI5 is LTR. You can set the RTL

property in the bootstrap and configuration for the whole application

• Most UI5 Controls have a direction attribute you can get and set. The attribute name depends on

the control

var bAppRunsRTL = sap.ui.getCore().getConfiguration().getRTL();

var sDirection = myTextView.getTextDirection(); myText.setTextDirection(sap.ui.core.TextDirection.RTL);

Page 286: BuildSAPFioriUIsWithSAPUI5_v2

Plain Text

Page 287: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 307 Internal

Plain Text Resources

In your UI5 application you will have a lot of texts which are of language dependent. Those texts

mostly will be available through databinding in UI Controls. You must not set hardcoded text in your UI

Controls. And we have more possibilities do so.

Text in

UI5

Hard Coded Resource Files OData

Content

OData Error

Messages

OData

Annotations

OData will be covered in the chapter about server-side models

Page 288: BuildSAPFioriUIsWithSAPUI5_v2

I18n Resource Files

Page 289: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 309 Internal

i18n Resource Files

• Resource files are used to store locally language-depending text and properties values

• The file contains key/value pairs where the values are the language-dependent texts and the keys

are language independent and used by the application to identify and access the corresponding

values.

• A value can have a placeholders, between curly brackets, which will be replaced at runtime

• Special characters must be html-encoded

SHELL_TITLE=Approve Requests MASTER_TITLE=Approve Requests ({0}) XBUT_SUBMIT=Submit XBUT_OK=OK XTIT_SUBMIT_DECISION=Submit Decision XMSG_DECISION_QUESTION=You have selected "{0}".

SHELL_TITLE=Antr\u00E4ge genehmigen MASTER_TITLE=Antr\u00E4ge genehmigen ({0}) XBUT_SUBMIT=Best\u00E4tigen XBUT_OK=Best\u00E4tigen XTIT_SUBMIT_DECISION=Entscheidung best\u00E4tigen XMSG_DECISION_QUESTION=Sie haben "{0}" ausgew\u00E4hlt.

i18n_local_de.properties i18n_local_en.properties

Page 290: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 310 Internal

I18n Resource Files naming convention

• Resource files are a collection of *.properties files. All files are named

with the same base name), an optional suffix that identifies the language

contained in each file, and the fixed .properties extension and placed in

the i18n folder. The language suffixes are formed using UI5 language codes

• By convention, a file without a language suffix should exist and contain

the raw untranslated texts in the developer's language. This file is used

if no more suitable language can be found.

• When a localized text is needed, the application uses the SAPUI5 APIs to load the properties file

that matches the current language best. If no text can be found for this key, the next best matching

file is loaded and checked for the text. Finally, if no file matches, the raw file is loaded and checked.

i18n_en_US.properties

i18n.properties

Page 291: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 311 Internal

I18n Resource Files Use of resource files

Resource

Files

Resource

Bundle Resource

Model

Resource Bundle Resource Model

Databinding Indirect via JSON Model Direct, one-way

Parameter support Yes No

Automatically initiation No Yes in App Descriptor in models

Page 292: BuildSAPFioriUIsWithSAPUI5_v2

i18n Resource Bundle

Page 293: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 313 Internal

i18n Resource Bundle

• You can use the jQuery.sap.resources API to access localized texts.

• The API loads a resource bundle file from a given URL and for a given locale.

• Initiation of the resource bundle will return an jQuery.sap.util.ResourceBundle, which provides

access to the localized texts. Use the getText(skey,aParameters) method to access the texts

by means of their key.

• If a text has one or more placeholders, you can specify an array of strings in the aParameters.

These strings will be replacing the placeholders in the text;

var sBundleLocale = sap.ui.getCore().getConfiguration().getLanguage(); var sBundleUrl = "i18n/i18n.properties"; var oBundle = jQuery.sap.resources({url : sBundleUrl, locale: sBundleLocale });

var sText = oBundle.getText("XBUT_SUBMIT");

var sText = oBundle.getText("MASTER_TITLE", ["12"]);

en_US: Submit de: Bestätigen

en_US: Approve Requests (12) de: Anträge genehmigen (12)

Page 294: BuildSAPFioriUIsWithSAPUI5_v2

i18n Resource Model

Page 295: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 315 Internal

i18n Resource Model Generic use

• The Resource Model is a wrapper for i18n resource files that exposes the localized texts as a model for data

binding.

• You can instantiate the Resource Model with bundleName.

This name is the UI5 notation of a file location without

the suffix '.properties'. E.g. the file i18n.properties in

directory /i18n of my project sap.ui5.training

becomes sap.ui5.training.i18n.i18n

• You can instantiate the resource model using a

bundleUrl, which points directly to a resource bundle.

• When you have the Resource Model, you can bind

properties of UI controls to language dependent values

of the resource i18n file.

• You can, however, access the resource bundle directly

from the model instead of loading

var sBundleLocale = sap.ui.getCore().getConfiguration().getLanguage(); var sBundleUrl = "i18n/i18n.properties"; var oResourceModel = new sap.ui.model.resource.ResourceModel({ bundleUrl: sBundleUrl, bundleLocale: sBundleLocale}); oControl.setModel(oResourceModel,"i18n");

var sBundleLocale = sap.ui.getCore().getConfiguration().getLanguage(); var sBundleName = "sap.ui5.training.i18n.i18n"; var oResourceModel = new sap.ui.model.resource.ResourceModel({ bundleName: sBundleName , bundleLocale: sBundleLocale}); oControl.setModel(oResourceModel,"i18n");

<Page title="{i18n>SHELL_TITLE}"> <content> <Text id="myText" text="{i18n>MY_TEXT}" width="200px"/> <Button id="myXMLButton" text="{i18n>MY_LABEL}" press=".onPress"/> </content> </Page>

var myBundle = oModel.getResourceBundle();

Page 296: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 316 Internal

i18n Resource Model Use i18n Resource Model in Fiori apps

• Mostly you will declare the i18n resource model in the metadata of the configuration and the models

of the app descriptor (UI5 SDK 1.30+).

• If declared as a model in the App Descriptor, the resource model will instantiated automatically.

... "sap.ui5": { "_version": "1.1.0", "rootView": "sap.ui.demo.wt.view.App", "dependencies": { "minUI5Version": "1.30", "libs": { "sap.m": {} } }, "models": { "i18n": { "type": "sap.ui.model.resource.ResourceModel", "settings": { "bundleName": "sap.ui5.training.i18n.i18n" } } } } }

App Descriptor: Manifest.json

Page 297: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 317 Internal

i18n Resource Model Enhance i18n Resource Models

• The sap.ui.model.resource.ResourceModel can be enhanced to add custom i18n resource

texts.

• The enhanced Resource Model tries to resolve the i18n texts from the customized bundle first. If a

text does not exist there, it tries to look up the i18n text in the standard bundle.

• The additional resource bundles are not part of the customizing configuration, but can be added as

part of a controller extension

var oModel = new sap.ui.model.resource.ResourceModel({bundleUrl:"i18n/i18n.properties"}); oModel.enhance({bundleUrl:"i18n/i18n_custom.properties"});

Page 298: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 318 Internal

i18n Resource Model Best practice using resource bundle parameters in data binding

• To pass parameters to your texts in the resource model, you need to use multipart binding and the UI5 helper

function jQuery.sap.formatMessage.

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="sap.ui5.training.controller.myViewController" xmlns:html="http://www.w3.org/1999/xhtml"> <Page title="{i18n>SHELL_TITLE}"> <content> <TextView text="({parts:[{path: 'i18n>MY_TEXT'}, {path: '/my_data'}, {path: '/my_second_data'} ], formatter: 'jQuery.sap.formatMessage'})"/> <Button id="myXMLButton" text="{i18n>MY_LABEL}" press=".onPress"/> </content> </Page> </core:View>

Page 299: BuildSAPFioriUIsWithSAPUI5_v2

Mimes

Page 300: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 320 Internal

Mimes UI5 Mime flavors

In UI5 mimes have 3 different flavors:

• Read-only mimes part of your UI5 project

These mimes are located locally in the mimes or images (if you have only pictures) folder of your

UI5 project. You can access those mimes with a relative source URL.

• Read-only mimes in Mime Repository

These mimes are mostly located in a read-only mime repository (e.g. in ERP), content management

system or somewhere else on the web. You can access those mimes with a absolute source URL,

but must be aware that they don’t belong to your UI5 project directly.

• Dynamic server-side mimes

Just like read-only servers-side mimes, these mimes are located in a mime repository or content

management system. But now you can not only read those mimes, but also create, modify and

delete those files. In UI5 projects, this is mostly done mime features of Odata using $value.

Page 301: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 321 Internal

Mimes Reading mimes

• For read-only mimes, we use i18n resources to specify the URL of the mime and use data binding

to set the source of our image UI control.

• For dynamic mimes, we use the Odata URL and can specify the language as a key field or use the

logon language of the backend system

# Handling Multilanguage Images LOCAL_PROJECT_MIME=images/myimage_de.png MIME_REPOSITORY_MIME=http://cms.sap.local/image/myimage_de.png

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="sap.ui5.training.controller.myViewController" xmlns:html="http://www.w3.org/1999/xhtml"> <Page title="Title"> <content> <Image id="myImage" src="{i18n>LOCAL_PROJECT_MIME}"> </Image> </content> </Page> </core:View>

# Handling Multilanguage Images LOCAL_PROJECT_MIME=images/myimage_en.png MIME_REPOSITORY_MIME=http://cms.sap.local/image/myimage_en.png

i18n.properties

i18n_de.properties

myImageView.view.xml

var sSAPLangu = sap.ui.getCore().getConfiguration().getLocale().getSAPLogonLanguage(); var sServiceRoot = this.getView().getModel(). sServiceUrl; var oImageSrc = sServiceRoot + "/employeeSet(employeeId='1000',langu=" + sSAPLangu + ")/$value"; var oImage = this.getView().byId("myImage"); var oImageSrc2 = sServiceRoot + "/employeeSet(employeeId='1000')/$value?sap-language='" + sSAPLangu + "'"; oImage.setSrc(oImageSrc);

myViewController.controller.js

Page 302: BuildSAPFioriUIsWithSAPUI5_v2

Dates & Numbers

Page 303: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 323 Internal

Formatting Dates and Numbers

The right presentation of dates, amounts and numbers is very important in enterprise applications. If

you type your fields to Date, DateTime, Time, Float, Integer and Currency fields in your models,

formatting is done automatically.

The date is formatted based on the following settings in order: • Create custom type by extending primitive type and set formatting option.

• Formatting based on the user’s locale (sap.ui.core.Configuration.formatLocale)

• Formatting based on the user’s language (sap.ui.core.Configuration.language)

To retrieve the current formatting options, you can query the configuration API.

<TextView text="My birthday: { path: "/birthDay", type: sap.ui.model.type.Date }"/>

var sCurrentFormattingOptions = sap.ui.getCore().getConfiguration().getFormatSettings();

Page 304: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 324 Internal

Formatting Dates and Numbers

If fields are not bound or bound to other types (mostly strings) its your responsibility to do the

formatting.

There are three options to manually format the date:

• Use a custom formatter to format the field. These formatters should be put into “model/formatter.js”

file and only loaded in the controller

• Format the field before you set the value of a UI control

• Or let the backend do the conversion, which mostly is the case when you have text which contains

dates and numbers which must be converted

oController.prototype.myFormatter = function(oDate){ var oDateFormat = sap.ui.core.format.DateFormat .getDateTimeInstance({pattern: "dd/MM/yyyy HH:mm"}); return oDateFormat.format(oDate); };

var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({pattern: "dd/MM/yyyy HH:mm"}); var oText = this.getView().byId("idPropertyBindingText"); oText.setValue(oDateFormat.format(oDate));

<TextView text="My Birthday {path: "/firstname"}, formatter: ".myFormatter"}"/>

Page 305: BuildSAPFioriUIsWithSAPUI5_v2

Smart Controls

Page 306: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 327 Internal

During the Early Days of SAPUI5…

There was a lot of code

For views

For controllers

For making CSS adaptations

that was written by hand using…

Page 307: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 328 Internal

Smart Controls

Smart Controls

Consume OData annotations like data type, max. length, F4 help, groups, etc. and customize the control

accordingly

Smart FilterBar and Table were introduced with wave 7

Field, Input, Form are available in with wave 8 and ObjectPage will follow with wave 9

Page 308: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 329 Internal

Smart Controls

Smart FilterBar

Smart Table

Page 309: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 330 Internal

SAP Annotations for OData

sap:label

sap:creatable

sap:updatable

sap:deletable

sap:display-format

sap:semantics

sap:field-control

http://scn.sap.com/docs/DOC-44986

Page 310: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 331 Internal

OData Annotations: Value Lists

<Collection>

<Record Type="com.sap.vocabularies.Common.v1.ValueListParameterInOut">

<PropertyValue Property="LocalDataProperty" PropertyPath="CompanyCode"/>

<PropertyValue Property="ValueListProperty" String="BUKRS"/>

</Record>

<Record Type="com.sap.vocabularies.Common.v1.ValueListParameterDisplayOnly">

<PropertyValue Property="ValueListProperty" String="BUTXT"/>

</Record>

<Record Type="com.sap.vocabularies.Common.v1.ValueListParameterDisplayOnly">

<PropertyValue Property="ValueListProperty" String="ORT01"/>

</Record>

<Record Type="com.sap.vocabularies.Common.v1.ValueListParameterDisplayOnly">

<PropertyValue Property="ValueListProperty" String="WAERS"/>

</Record>

</Collection>

Page 311: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 332 Internal

Smart Controls: Achievements

Using Smart Controls…

Reduced the code in (XML-)View-description files up to 90%

(e.g. more than 2500 lines less for Customer Line Items, Vendor Line Items application)

Gives the developers a rich set of standard functionality like Variants, Personalization Dialogs and

Export to Excel

Reduced the JavaScript controller code (~500 lines per app)

Unified the user experience as they provide built-in features instead of having them inside the

individual apps

Using Smart Controls indirectly has…

Improved the readiness for central changes

Improved the code quality

Page 312: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 333 Internal

Exercise

Page 313: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 334 Internal

Smart Controls: The BUT

Using Smart Controls…

Leads to screen areas that are closed boxes for application developers

Developers lose the ability to achieve pixel perfectness inside these areas

„Complex“ Smart Controls start to get a nasty change API when the central control has to enable all adaptation requests that

are urgently required from at least one application

The Solution

Using XML Templating together with Smart Controls…

Use the templating approach in combination with standard SAPUI5 layout controls and basic smart controls like “Smart Field”

Enable to execute the templates at design and at runtime

Applications that urgently have to change the default are able to unlock the template (i.e. execution at design time) and start to

adapt the resulting “view” doing standard SAPUI5 programming

Page 314: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 335 Internal

XML Templating http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/#docs/guide/5ee619fc1370463ea674ee04b65ed83b.html

<template:if test="{meta>com.sap.vocabularies.UI.v1.Identification}">

<sfo:Group label="Identification">

<template:repeat list="{meta>com.sap.vocabularies.UI.v1.Identification}">

<sfo:GroupElement label="{path: 'meta>Label'}">

<sfi:SmartField value="{path: 'meta>Value'}"/>

</sfo:GroupElement>

</template:repeat>

</sfo:Group>

</template:if>

Preprocessing instructions such as <template:if>, which can be used inside XML views.

An OData meta model which offers a unified access to both, OData v2 metadata and OData v4 annotations.

A set of OData type implementations which add knowledge of OData types to SAPUI5.

Expression binding which facilitates the use of expressions instead of custom formatter functions

The helper class sap.ui.model.odata.AnnotationHelper that offers formatter and helper functions to be used

inside XML template views. It knows about the OData meta model and helps with standard tasks like

accessing a label or providing a runtime binding path. It brings in the OData types, along with their facets. Its

output uses expression binding, if needed.

Page 315: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 336 Internal

SAP Web IDE Smart Template

(incl. Routing, Master Detail/ Full

Screen app structures, XML

templating etc.)

Smart Templates

Template

Configuration

App

Custom views (e.g. using XML

templating)

Annotations

SAPUI5 Smart FilterBar

Re-Use Controllers

Smart Table …

Page 317: BuildSAPFioriUIsWithSAPUI5_v2

Navigation Concepts

Page 318: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 340 Intenal

General Concept

Typical Mobile application structure:

App with multiple screens

Master / Detail screens with split apps

Drilldown navigation

Edit and Display

Back and Forward navigation

Entries in Browser History

Deep Links

Lazy loading

Not found pages

sap.m.App (sap.m.NavContainer) root control

sap.m.Page sap.m.Page

Animation between pages can be chosen

(show, slide, fade, flip)

Page 319: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 341 Intenal

Inner-App Navigation

Component.js

Browser

Fiori App

App Descriptor "routing" : {

// The default values for every route

"config" : {

...

},

// Define routes and pattern

"routes" : {

...

},

// Define which view to load

"targets" : {

...

},

}

}

WorkList.view.xml

sap.m.Page

ObjectNotFound.view.xml

sap.m.Page

NotFound.view.xml

sap.m.Page

Object.view.xml

sap.m.Page

App.view.xml

sap.m.App

sap.m.routing.

Router

init

add created page

create create create

SAPUI5 navigation features

sap.m.routing.Router - SAPUI5 router class to load the pages and update the URL (change/replace hash)

Routing configuration in the App descriptor

Navigation events

Animation between pages

(show, slide, fade, flip)

hash

index.html

Component

Container

Fiori LaunchPad create

change/replace

Page 320: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 342 Internal

Launchpad Navigation – Main principles

Launchpad uses a resource-based navigation paradigm > every application within the

Launchpad has a resource locator (URL) by which it can be loaded

All information about the applications to load is encoded in the URL fragment, i.e. the part

after the hash character

Navigation can be performed by either setting the browser URL hash explicitly via a

JavaScript call or implicitly by rendering a link

The Unified Shell services provide a listener which is registered for the hash change

event and loads the application according to the information encoded in the URL hash

The navigation concept is used to “save” states (by reflecting it in the URL), allowing to

bookmark (or share, e.g. send in an e-mail) the current application state

It is important that one builds the application in a way that it can reconstruct the application

state from any application URL to support

- browser back

- refresh

- bookmarking

Page 321: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 343 Internal

Key Navigation Concepts

1. Load App 1 (View 1 is default) http://<host>:<port>/<path>/shell.html#app1

2. Inner-App Navigation to View 2 http://<host>:<port>/<path>/shell.html#app1&/view2

3. App-to-app Navigation to App 2 http://<host>:<port>/<path>/shell.html#app2

4. Back Navigation (Browser) http://<host>:<port>/<path>/shell.html#app1&/view2

SAP Fiori Launchpad with a single HTML document hosting all apps

http://<server>:<port>/<path>/FioriLaunchpad.html

Navigation based on URL fragments http://<server>:<port>/<path>/FioriLaunchpad.html#<fragment>

Intent-based navigation http://<server>:<port>/<path>/FioriLaunchpad.html#<SemanticObject>-<Action>

Cross-App Navigation #<SemanticObject>-<Action>[~<InternalTargetID>]?<parameter-1>=<value-1>&…&<parametern>=<value-n>

Inner-App Navigation #<SemanticObject>-<Action>[~<InternalTargetID>]?<parameter-1>=<value-1>&…&<parametern>=<value-n>[&/<innerappspecificfragment>

Schematic illustration of navigation steps and URLs:

Page 322: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 344 Internal

Launchpad URL schemas

The actual URLs are constructed and parsed via API calls of shell services,

Fiori Apps must not attempt to construct them themselves!

1. One Launchpad URL (fixed)

2. Application encoded in Hash : Managed by Shell

3. Inner Application State encoded in Hash (Application specific)

Current scheme: http://<server>:<port>/<path>/FioriLaunchpad.html#<fragment>

Complete syntax for the URL fragment:

#<SemanticObject>-<Action>[~<InternalTargetID>]?<parameter-1>=<value-1>&…&<parametern>=<value-n> [&/<innerappspecificfragment>]

https://wdciw19.wdf.sap.corp:1033/sap/bc/ui5_ui5/ui2/ushell/shells/abap/FioriLaunchpad.html#Supplier-manage?Supplier=12345&/supplier/12345/edit

Shell path App-specific path

Shell path App-specific path Launchpad URL

Page 323: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 345 Internal

Intent based navigation concept http://<server>:<port>/<path>/FioriLaunchpad.html#<SemanticObject>-<Action>

The Launchpad enables you to specify that the

same application is launched in different views or

modes depending on the end user's role. Each

application within the Launchpad has a resource

locator (URL) by which it can be loaded. Instead of

directly encoding the (technical) name of the target

application into the URL hash, the Launchpad

performs an indirection by so-called intents.

An intent is a mechanism that allows users to

perform actions on semantic objects (such as

navigating to a sales order or displaying a fact

sheet), without worrying about the UI technology or

technical implementation of the navigation target.

http://<server>:<port>/<path>/FioriLaunchpad.html#Employee-display

Page 324: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 346 Internal

Exercise

Page 325: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 347 Internal

Cross-App Navigation

Use the CrossApplicationNavigation service to construct shell fragments and links from local fragments. Do not construct

them yourself.

Use startup parameters to pass information to the next app.

Use single-value parameters only. Multi-valued parameters are not recommended.

Do not use deep links to the app-specific fragment for passing information to the next app.

Check whether the given navigation intent(s) are supported by isNavigationSupported(aIntents) and disable links if not

Passing Startup Parameters Dynamically with JavaScript Receiving Startup Parameters Dynamically with JavaScript

sap.ui.core.UIComponent.extend("AppNavSample.Component", {

...

createContent : function() { // contains e.g. { startupParameters : { AAA : ["BBB"], DEF: ["HIJ","KLM"] } }

// note that parameter values are passed as an array!

var oComponentData = this.getComponentData();

jQuery.sap.log("app was started with parameters " +

JSON.stringify(oComponentData.startupParameters || {} ));

...

}});

var href_For_Product_display = ( sap.ushell &&

sap.ushell.Container &&

sap.ushell.Container.getService("CrossApplicationNavigation").

hrefForExternal({

target : { semanticObject : "Product", action : "display" },

params : { "ProductId" : "102343333", SupplierId : "90210" }

}))

|| "";

<a href="#Product-display?ProductId=102343333&amp;SupplierId=90210" target="_self">Details</a>

Page 326: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 348 Internal

Exercise

Page 327: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 349 Internal

Further Information

SAP Fiori Launchpad for Developers – Architecture Overview

https://scn.sap.com/docs/DOC-57363

Setting up Navigation

http://help.sap.com/saphelp_uiaddon10/helpdata/en/03/dbca33e25b44398e13be2f77082e79/content.htm

Unified Shell – Navigation

https://wiki.wdf.sap.corp/wiki/display/unifiedshell/Inner+and+Cross+App+Navigation+for+the+Fiori+Launchpad+(

Example+Code)

https://wiki.wdf.sap.corp/wiki/display/unifiedshell/Fiori+Launchpad+Navigation+Concept

SAPUI5 Developer Guide – Navigation Tutorial

Page 328: BuildSAPFioriUIsWithSAPUI5_v2

SAP Fiori Launchpad Application Developer Guide

Page 329: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 351 Internal

Fiori Launchpad Overview

The FIORI Launchpad provides end-users an

entry point to Fiori applications in a role-based,

consistent and user-friendly manner using tiles.

Tiles show dynamic/live/real-time application

information (like status, KPIs)

on the home page.

Predefined content and high degree of

personalization

Tiles can be selected from catalogs and

arranged in groups.

Search is integrated.

Tile

Group

Search

Page 330: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 352 Internal © 2014 SAP AG. All rights reserved. 352

Benefits for: End user, Admin, Developer

ONE, single point of access

Intuitive user interface

Zero footprint

Responsive design (across devices)

Harmonized UI

Personalized

Role-base, context-based navigation

End User (LoB)

Stack-agnostic runtime / design-time

tools

Flexible deployment options with best

practices for different options

Central design-time tools for roles,

catalog, themes

Process Expert / Admin (IT)

Open, standards-based framework

(HTML/LESS) for extensions and

customization

Consistent APIs

Leverage application-context and

personalization services

Developer (Dev)

Page 331: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 353 Internal

Integration with Development/Test environment

Standalone (isolated)

•Basic App behaviour and UI

•Local navigation

•OData services (with cross domain relaxation or a proxy)

•Unified shell services in "sandbox" mode

Fiori Sandbox

•App packaging (Component initialization, correct relative paths)

•Shell-services available in Sandbox, e.g. Personalization, CrossAppNavigation

•Startup parameter passing

FLP with proxy

•Correct UI embedding in presence of Launchpad ui frames.

•All ABAP shell services

•Launchpad provided functionality(header, footer buttons and functionality)

•With backend

local App with central FLP

•Correct backend navigation

•Cross app navigation

App with central FLP

•Correct deployment of all resources

Parts of Fiori UI Development can be done in different scenarios and

technical environments.

Final deployment is deployed at customer sites

Test and development with faster round-trip-times

or in the absence of back-end configuration.

Page 332: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 354 Internal

Well defined Fiori App patterns (Fiori App Do`s and Don`ts)

Integration with SAP Web IDE (Develop, Extend, Deploy)

Rich set of APIs (unified shell) for rapid application development (navigation, personalization, container,

bookmark etc.)

Leveraging platform services for rapid development process (connectivity, IdP)

Typical Use Cases (How To...)

Sample Applications

Application Developer Guide

Page 333: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 355 Internal

Further Information

SAP Fiori Launchpad for Developers – Architecture Overview

https://scn.sap.com/docs/DOC-57363

Application Developer Guide (FLP)

https://wiki.wdf.sap.corp/wiki/display/unifiedshell/Application+Developer+Guide

Page 334: BuildSAPFioriUIsWithSAPUI5_v2

SAP Fiori and

SAPs collaboration platform

(SAP Jam)

Page 335: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 357 Internal

Integrated Experience SAP Fiori and SAP Jam

Project Issue Handling Demo Link

Page 336: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 359 Internal

SAP Jam Fiori UI5 Re-usables (I) Share on SAP Jam

Break-out to SAP Jam

Start a collaboration with SAP Jam

toolset (e.g. pro/con tables, forums)

Share the object, note and deep link

into an existing Jam group

Upload attachments

Get quickview and fact sheet of the

object live in Jam

Page 337: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 360 Internal

SAP Jam Fiori UI5 Re-usables (II) Share on SAP Jam – Factsheets

Generic Jam enablement for all Fiori

factsheets (share)

Visualization within the Business

Record Viewer of SAP Jam

No coding required

Based on OData and Annotations

Own OData services can be enabled

with the share re-usable

Page 338: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 361 Internal

SAP Jam Fiori UI5 Re-usables (III) Social Timeline Component

In place discussion

Comment and reply in the context of

a business object

See user’s SAP Jam profile

Secure, access is bound to the

object’s access rights

Driven by OData and annotations

Based on the UI5 Timeline Control

Page 339: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 362 Internal

SAP Jam Fiori UI5 Re-usables (IV) SAP Jam Tiles

Group tiles

Put shortcuts to your favorite groups on

the Launchpad

Notification tile

Don’t miss important information

addressed to you

Page 340: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 364 Internal

Further Information

help.sap.com – Social Media Integration customer documentation

scn.sap.com – SAP Jam Developer Community

Demokit Share / Social Timeline Controls Components Collaboration

Page 341: BuildSAPFioriUIsWithSAPUI5_v2

Agile Software Engineering

Page 342: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 367 Internal

Motivation

With great power comes great responsibility.

Spider-Man

JavaScript is a highly dynamic language

Marginal tool support to detect errors statically

The only way to verify something works is to actually run the code

It is very easy to “make a mess”, i.e. write non-maintainable code

Refactoring is hindered by lack of static code analysis

Good engineering practices are essential

to address these issues!

Page 343: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 368 Internal

Agile Software Engineering

Agile Engineering Practices

Test-Driven Development

Clean Code

Refactoring

Pair Programming

Continuous Integration

Simple Design

Collective Code Ownership

Acceptance Tests

Exploratory Testing

Page 344: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 369 Internal

Test-Driven Development

Page 345: BuildSAPFioriUIsWithSAPUI5_v2

Fiori Test Concept

Page 346: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 371 Internal

Test Automation Tool Positioning

System Tests

Integration Tests

Component Tests

Unit Tests

manual & automated automated

Scenario test for complete stack

Test of multiple components

Test of a high level APIs built on multiple units

Single unit test

Purpose Test Type

* Optional for specific use cases

Order to Cash

Fiori App backend communication

oData service, transaction, Fiori App (isolated)

get entity

formatter

Examples

START, Selenium*

UI: START, Selenium*

non UI: eCATT oData Assistant, eCATT

QUnit/OPA5 (frontend), ABAP Unit & eCATT (ABAP

backend)

QUnit (frontend), ABAP Unit (backend), Jasmin

(HANA content)

Tools

Page 347: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 372 Internal

Fiori Test Device Matrix

Focus on most used devices in the market

Cover all available browsers with the device-OS-combination(s)

Consider the Fiori Device Test Matrix to get an overview which combinations of operation

system & device & browser have to be tested

Test 2 combinations of each device category (phone, tab or desktop) for a detailed test (spread over the

different manufacturers)

1-3 (depends on the device category) combinations for a smoke test

Responsible for the tests with the Fiori test device matrix is the development team with support

of Suite Test Engineering (STE)

Development team tests 1 combination for which the team has a device available

STC tester tests the rest of the selected combinations

If no STC tester is assigned to the development team: The team has to test the selected combinations

Page 348: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 373 Internal

SAPUI5 Application Testing

What Should You Test?

Availability of certain controls

Controller logic, e.g. trigger actions

and check if the controls appear (based on the databinding)

and check if the model/backend received the request

and check if data are correct

What Should You NOT Test?

DOM of UI5 controls (not API)

All properties of a control, only the most relevant

UI5 framework functionality

Page 349: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 374 Internal

Agile Software Engineering – SAPUI5/Fiori

https://wiki.wdf.sap.corp/wiki/pages/viewpage.action?pageId=1605557289

Fiori&BusinessSuite Quality Engineering

https://wiki.wdf.sap.corp/wiki/display/fiorisuite/Test+Automation

Fiori Test Device Matrix

https://wiki.wdf.sap.corp/wiki//pages/viewpage.action?pageId=1559338096

SAP Test Automation Network

https://wiki.wdf.sap.corp/wiki/display/ECFQE/SAP+Test+Automation+Network

Further Information

Page 350: BuildSAPFioriUIsWithSAPUI5_v2

START

Page 351: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 376 Internal

Integrated with SAP Test Workbench

START Simple Test Automation for Regression Tests

Automate Simple Run Simple Maintain Simple

FIORI / UI5 Apps

(HCP/S4HANA/ON-PREM/IoT)

Dynamic input/output and check

points

NO CODING/SCRIPTING

Data Variants

Iterations, Scheduling, Mass

Execution with Jenkins

Multiple Landscape and Browsers

NO CODING/SCRIPTING

Add/Delete Steps

Chain START or non START Test

cases for scenario tests

Create Test Catalog/Plans

NO CODING/SCRIPTING

Coming Soon

Enhance coverage for UI5 controls, Performance Measurements (SUPA)

Page 352: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 377 Internal

START Features / Pre-requisites

■ Automation of test case with START START tool is used to create and run test automates without any coding / scripting.

Simple UI for online test case creation using SUT (System Under Test)

User can create input/output parameters, define checks online (static and dynamic).

Add / Delete of test steps, optional steps

Mass execution (un-attended) using Jenkins

Execution of automated test case on multiple landscapes (SUT)

FIORI Application developed for S4HANA, HCP, On-Prem. can be automated using START.

START can be used during development (application on user specific SAP Web IDE instance can also be automated)

■ Cross platform/browser compatibility Currently execution supports IE, Chrome and FireFox

Device Mode of Chrome (only for Tablet options)

■ Integration with SAP Test Workbench Automated tests can be collected in the Test Catalog repository

Test cases can be organized into test plans for batch execution and reporting

■ Reuse of eCATT framework START test case generates an eCATT wrapper, automated test cases (START and non START) can be chained together for scenario tests

Test Data Containers can be used to execute automated test with different test data variants. System Data Container allows management of test landscape

■ START available in ECA. Transactions: Create Test Case (START_F01)

Maintain Test Case (START_F02)

■ START tool must be installed on developer’s windows PC/Laptop (Only Windows OS is supported).

Page 353: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 378 Internal

Best Practice for test case design

Prerequisite

Ensure proper and relevant customizing, master & test data is available before execution of test scripts

For creating sales order, material, pricing conditions, customers should be available in system

For create outbound delivery, ensure similar sales order as initially recorded is available

Parameterization

Parameterize dynamic and input/output fields

For Stock overview script, consider parameterizing stock quantity which dynamically changes

according to stock situation

For Sales order create script, sales order number will be an output field. For create delivery sale

order number will be an input field

Modularization

Start with larger business picture in mind, create different scripts for reusable actions and business

specific actions

Reusable Script: For sales order application, create single script to check filtering and fuzzy search

Business Specific: Create SO with ref to quotation, direct SO creation

Try including related test cases in one automated script

Checks

Check only necessary fields. For create sales order with ref to quotation, checking material in line item

would be sufficient, check on all the fields not required

Further Information: START wiki, eCATT wiki

Create Sales Order App

• Prerequisite: Material, customer

• Output Field: Sales Order Number

Create Delivery App

• Input Field: Sales Order Number (prerequisite)

• Output Field: Delivery Number

Create Invoice App

• Input Field: Delivery Number

• Output Field: Invoice Number

Page 354: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 379 Internal

Wiki links

START, recommend tool for test automation of FIORI Apps: https://wiki.wdf.sap.corp/wiki/display/fiorisuite/Test+Automation

Guidelines for Application Developer: https://wiki.wdf.sap.corp/wiki/display/fiorisuite/START+Tool+Guidelines+for+Application+Developer%2C+Test+

Automation+Developer+or+Testers

Demo – Create / Execute Automated Test. Also how to use START when using SAP Web IDE

for FIORI app. development: https://wiki.wdf.sap.corp/wiki/display/STARTtool/START+User+Guide

Installation of START https://wiki.wdf.sap.corp/wiki/display/STARTtool/START+Installation

START Team https://wiki.wdf.sap.corp/wiki/display/STARTtool/START+Team+and+Roles

Page 355: BuildSAPFioriUIsWithSAPUI5_v2

QUnit http://qunitjs.com/

Page 356: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 381 Internal

QUnit

QUnit is a framework for unit testing JavaScript code

Originating from jQuery open source project

Used by jQuery, SAP UI5, . . .

Supports asynchronous tests

Provides stand-alone test runner or integrates with SAPUI5 CI environment

Included in SAP UI5 distribution

http://qunitjs.com/

Page 357: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 382 Internal

QUnit Example

QUnit.module("Calculator", {

setup : function() { // in the future beforeEach

this.calculator = new Calculator(); // Executed before each test case

},

teardown : function() {} // in the future afterEach

});

QUnit.test("show zero initially", function(assert) {

assert.equal(this.calculator.display(), 0);

});

QUnit.test("display entered digit", function(assert) {

this.calculator.press("1");

assert.equal(this.calculator.display(), 1);

});

Test Suite

Test Case

Arrange

Act

Assert

Page 358: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 383 Internal

Basic Assertion Toolkit

assert.ok(1, "1 should have been truthy");

assert.ok(!false, "!false should have been truthy");

assert.equal(1 + 1, 2, "1+1 should have equaled 2");

assert.equal(1, true, "1 should have been converted to true");

assert.strictEqual("there", "there");

assert.notEqual(Math.PI, 3.1415);

assert.notEqual({}, {});

assert.notStrictEqual(1, "1");

assert.deepEqual({}, {});

assert.deepEqual([1, 2], [1, 2]);

assert.notDeepEqual({ f : "this" }, { f : "that" });

assert.throws(function() {

"anna".reverse();

}, TypeError, "function should have thrown TypeError");

Page 359: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 384 Internal

QUnit Test Runner

Page 360: BuildSAPFioriUIsWithSAPUI5_v2

Sinon.JS http://sinonjs.org/

Page 361: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 386 Internal

Motivation: Test without Isolation

Page 362: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 387 Internal

Motivation: Test with Isolation

Page 363: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 388 Internal

Test Double

Stubs only provide return values for method calls (“indirect input”)

Mocks

additionally verify that expected methods are called with the right parameters (“indirect

output”)

Mocks allow to test and discover side effects

Caution! Tests can get fragile when mocks are too “strict”

Solution: dynamically created mocks using a mocking framework http://sinonjs.org/

Page 364: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 389 Internal

Sinon.JS Integration – Example: Stub

sap.ui.define([], function() {

"use strict";

return {

throwHeadOrTail: function() {

return Math.random() < 0.5 ?

"Head" : "Tail";

}

}

};

});

sap.ui.require(["myProject/model/utility", // module to test

"sap/ui/thirdparty/sinon", // Load Sinon into your test

"sap/ui/thirdparty/sinon-qunit"],

function(utility) { "use strict";

QUnit.module("Utility functions", {

setup: function() { },

teardown: function() { }

});

QUnit.test("should yield head", function(assert) {

// Arrange

// System under test

// Sinon.JS Stub - Provide indirect input

// Sinon.js functions part of the this object

var stub = this.stub(Math, "random");

stub.returns(0.3);

// Assert

assert.equal(utility.throwHeadOrTail(), "Head");

//Stubs are restored automatically after the test (Sandbox)

//stub.restore();

});

});

Module to test myProject/model/utility.js

Sinon.JS API

Spies: sinon.spy()

Stubs: sinon.stub()

Faking time: sinon.useFakeTimers() ……

Page 365: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 390 Internal

Mock Server http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/#docs/guide/69d3cbd4150c4ffb884e788f7f60fd93.html

sap.ui.define([ "sap/ui/core/util/MockServer" ],

function (MockServer) { "use strict";

var oMockServer;

return {

_sServiceUrl : "/sap/opu/odata/sap/EPM_REF_APPS_PROD_MAN_SRV/", // service url to mock

_sModulePath : "myproject.service", // module path containing metadata.xml

init : function () {

oMockServer = new MockServer({ rootUri: this._sServiceUrl });

// configure mock server with a delay

MockServer.config({

autoRespond : true,

autoRespondAfter : 1000

});

// simulate

var sPath = jQuery.sap.getModulePath(this._sModulePath);

oMockServer.simulate(sPath + "/metadata.xml", {

sMockdataBaseUrl : sPath,

bGenerateMissingMockData : true

});

// Start

oMockServer.start();

jQuery.sap.log.info("Running the app with mock data");

}

};

});

Isolates your app from the

backend

Simulates OData backend

calls with Sinon.JS

Transparent to data binding

Supports randomly

generated data (based on

the service metadata)

Supports mock data

provided in .JSON files (use

same module path as for

metadata.xml)

Each OData service needs

its own mock server

Can be extended with

additional calls to mock

function import calls

Page 366: BuildSAPFioriUIsWithSAPUI5_v2

One Page Acceptance Tests

(OPA5) http://veui5infra.dhcp.wdf.sap.corp:8080/demokit/docs/guide/2696ab50faad458f9b4027ec2f9b884d.html

Page 367: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 392 Internal

One Page Acceptance Tests (OPA5)

Write JavaScript-based acceptance tests with OPA5:

Helpful for testing:

user interactions

integration with SAPUI5

Navigation

data binding

It hides asynchronity by polling

Eases access to SAPUI5 elements

Foster clean/readable tests

Integration tests implemented in same programing

language as application

No need to learn an additional programing language

(Java – for the Selenium tests)

Test execution is faster than with Selenium

Tests are executed in the same way as unit QUnit tests

Work well with mock data from the SAP UI5 Mock Server

Page 368: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 393 Internal

sap.ui.require(["sap/ui/test/opaQunit"],

function () {"use strict";

module("My first Journey");

opaTest("Should press a Button", function (Given, When, Then) {

// Arrangements

Given.iStartMyApp();

//Actions

When.onTheAppPage.iPressOnTheButtonWithId(“myButton");

// Assertions

Then.onTheAppPage.theButtonWithIdShouldHaveTheText(“myButton“,“I got pressed“).

and.iTeardownMyAppFrame();

});

});

OPA5 Arrangements, Action, Assertions

OPA gives you the

following three objects:

Given = arrangements

When = actions

Then = assertions

Page 369: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 394 Internal

OPA5 Page Objects - Structuring OPA Tests

sap.ui.require(["sap/ui/test/Opa5"],

function(Opa5) {"use strict";

Opa5.createPageObjects({

onThe<Page Object> : { //give a meaningfull name for the test code

actions: {

//place all arrangements and actions here

<iDoSomething> : function() {

//always return this or a waitFor to allow chaining

return this.waitFor({

//see documentation for possibilities

});

}

},

assertions: {

//place all assertions here

<iCheckSomething> : function() {

//always return this or a waitFor to allow chaining

return this.waitFor({

//see documentation for possibilities

});

}

}

}});});

A page object

represents a significant

part of the app (e.g. a

view)

knows about locators

groups actions and

assertions of this part at

one place

Page 370: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 395 Internal

OPA5 Arrangements

iStartMyApp : function () {

return this.iStartMyAppInAFrame("../index.html");

}

Do the setup work

Provide some special URL parameter...

Other setup like functionality

Page 371: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 396 Internal

OPA5 Action

iPressOnTheButtonWithId : function (sId) {

return this.waitFor({

viewName : "Main",

id : sId,

success : function (oButton) {

oButton.$().trigger("tap");

},

errorMessage : "did not find the Button with id " + sId

});

}

Wait for UI5 controls to come available and trigger actions on them:

Page 372: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 397 Internal

OPA5 Assertions

theButtonWithIdShouldHaveTheText : function (sId, sText) {

return this.waitFor({

viewName : "Main",

id : sId,

matchers : new sap.ui.test.matchers.Properties({

text : sText

}),

success : function (oButton) {

//Opa5 would fail the test if the button didn’t get it’s property change

ok(true, "The button’s text changed to: " + oButton.getText());

},

errorMessage : "did not change the Button’s text for button with id " + sId

});

}

Wait for UI5 controls to get certain properties:

Page 373: BuildSAPFioriUIsWithSAPUI5_v2

Lean Development

Infrastructure

Page 374: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 400 Internal

Fiori Development Projects

Support of the end-to-end lifecycle for SAPUI5 based applications

Setup Develop Release

Page 375: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 401 Internal

Development Process

Team

LeanDI Gerrit

LeanDI Git

LeanDI Tomcat

Jenkins Build Server

Nexus

ABAP Backend System

Web IDE Translation System

ABAP UI Dev System

Local

Tomcat Mock

Data

Mock

Data

Clone Git

Download / Upload

Upload

ABAP UI Test/Cons

System OData calls

Code Review by Developer

Merge

Static Checks

Upload build

Transport

Page 376: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 404 Internal

Lean DI Overview Tools

Binary Artifact Repository

Team Build Server Source Repository / gerrit

Release Build Server

https://projectportal.neo.ondemand.com https://git.wdf.sap.corp:8080 http://ldipublic.mo.sap.corp:8080/jenkins

(public instance)

https://ldirelease.wdf.sap.corp:8443/hudson

https://nexus.wdf.sap.corp:8443/nexus/index.html

https://wiki.wdf.sap.corp/wiki/display/LeanDI/Nexus+Landscape

https://wiki.wdf.sap.corp/wiki/display/fiorisuit

e/Jenkins+Builds

(Fiori@BSuite)

Page 377: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 405 Internal

Setup Portal Project Setup Develop Release

Team

LeanDI Gerrit

LeanDI Git

LeanDI Tomcat

Jenkins Build Server

Nexus

ABAP UI Dev System

Page 378: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 406 Internal

Setup Portal Project https://projectportal.neo.ondemand.com

Central

Nexus

Jenkins

Build server

Developer

workspace Translation

system

Gerrit

triggers voter job

triggers CI job

push code upload/download

gets/stores

artifacts

creates Git repository

creates build jobs

set up initial access rights

creates JIRA

project

Setup Develop Release

Page 379: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 407 Internal

Exercise

Page 380: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 408 Internal

What is SAP Web IDE?

Browser-based (Web) toolkit available on SAP HANA Cloud Platform

An Integrated Development Environment to

create new SAPUI5/HTML5 or custom Fiori apps

extend SAP Fiori apps resp. SAPUI5 apps

Provides standard Web development tools like code editors, wizards,

and WYSIWYG tooling that are optimized for building responsive

apps with SAPUI5 (e.g., code completion)

Application templates act as the foundation for highly efficient app

development

Supports the E2E application lifecycle: UI design, development,

testing, deployment, and customer extensions for responsive SAPUI5

apps

Everything is source code-based – the tool never gets in the way of

the developer

Setup Develop Release

Page 381: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 409 Internal

Developer’s Workplace

SAP Web IDE on SAP HANA Cloud Platform Setup Develop Release

Page 382: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 410 Internal

Eclipse IDE for SAPUI5

Wizards for project and view/controller creation

Wizards for control development

Code Completion for UI5 controls

TeamProvider for SAPUI5 ABAP repositories

Application preview with an embedded Jetty server

Integration with any server instance (e.g. Tomcat)

Proxy-servlet to prevent same-origin-policy errors

Setup Develop Release

Page 383: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 411 Internal

Automated Tool for local DI Setup https://wiki.wdf.sap.corp/wiki/display/fiorisuite/A+Development+Environment+for+Fiori+-+Development+Infrastructure+Setup+with+an+automated+Tool

A tool hat automates the setup of a Fiori development environment on a Windows computer

Installation: JDK, Firefox Browser, Chrome Browser,

Safari Browser, Maven, SAPUI Eclipse IDE, GIT

Workplace, Fiori Plugins, ESLint, START, SUPA, Tomcat

Post Installation:

setup Git Workplace

install and Configure the Proxy Servlet

configure ESLint Plugin

configure line delimiter: Unix

Note: the initial creation of the Fiori App does no longer

work with Eclipse

Page 384: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 412 Internal

Developer’s Workplace

Eclipse IDE Setup Develop Release

Page 385: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 413 Internal

git/Gerrit

Local

git repository

Staging Area

central / origin

git repository

add

commit

push

fetch/pull

checkout

rebase

submit

Developer PC/

Cloud repository LeanDI Server

Landscape

Working

Directory Jenkins

Gerrit

Setup Develop Release

Page 386: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 415 Internal

Exercise

Page 387: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 416 Internal

Maven background

Local

Repository

pom.xml(POM)

Maven core Remote

Repository

Nexus Server

HTTP

1. require

2. Search

3. Search

5. install

4. Notify

Setup Develop Release

Page 388: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 417 Internal

GAV - basic 3 terms of a build artifact identity

<project …>

<groupId>com.sap.fiori</groupId>

<artifactId>cus.sd.customerinvoices.manage</artifactId>

<version>10.2.0-SNAPSHOT</version>

</project>

G:groupId [package name]

e.g. com.sap.fiori

A:artifactId [module name]

e.g. cus.sd.customerinvoices.manage

V:version [module version]

e.g. 10.2.0-SNAPSHOT

Setup Develop Release

<project …>

<groupId>com.sap.fiori</groupId>

<artifactId>cus.sd.customerinvoices.manage</artifactId>

<version>10.1.3</version>

</project>

Page 389: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 418 Internal

Maven Project Relationship

=Dependency =Transitive Dependency

=Inherits from

Setup Develop Release

<groupId>com.sap.fiori</groupId>

<artifactId>nw.epm.refapps.products.manage</artifactId>

<version>1.9.1-SNAPSHOT</version>

<groupId>com.sap.fiori</groupId>

<artifactId>fnf-parent-pom</artifactId>

<version>1.7.0-SNAPSHOT</version>

<groupId>com.sap.fiori</groupId>

<artifactId>nw.epm.refapps.lib.reuse</artifactId>

<version>1.9.1-SNAPSHOT</version>

<groupId>com.sap.fiori</groupId>

<artifactId>fiori-reuselib-pom</artifactId>

<version>1.7.0-SNAPSHOT</version>

<groupId>com.sap.fiori</groupId>

<artifactId>maven-webapp-pom</artifactId>

<version>1.29.1-SNAPSHOT</version>

<groupId>com.sap.ca</groupId>

<artifactId>scfld.md</artifactId>

<version>1.29.1-SNAPSHOT</version>

<groupId>com.sap.ui5</groupId>

<artifactId>core</artifactId>

<version>1.29.1-SNAPSHOT</version>

<groupId>com.sap.ui5.dist</groupId>

<artifactId>library-parent</artifactId>

<version>1.29.1-SNAPSHOT</version>

…. ….

….

….

Page 390: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 420 Internal

Release build Setup Develop Release

SNAPSHOT MILESTONE RELEASE End of Release e.g. End of Takt

SNAPSHOT versions can be

directly deployed to Nexus from

a CI build server or even a local

build.

Maven project artifacts internally

available for other development

teams by publishing them into the

Milestone Repository

Maven project artifacts available for

shipping to external customers by

publishing them into the Release

Repository

Steps to complete milestone release

1. Change dependencies of your project (no reference to SNAPSHOT allowed)

2. (Optional) Change the project version (GAV) to release version (usually automatic

version update)

3. Trigger the release build by "Run Milestone Release" or "Run Customer Release“

4. (Optional) Change project version for development

• Project's artifacts are available in Nexus and can be consumed

• The sources corresponding to the released artifacts are tagged in the version control

system

• A release branch is created to provide a patched version of the released artifact.

• The development branch is updated so that development of the next version can begin.

Page 391: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 421 Internal

A Practical Course on GIT/Gerrit Classroom Training

Git/Gerrit Training http://git.wdf.sap.corp:50002/

Recording of Git Training by Mathias Sohn General Overview

Free online book on GIT http://git-scm.com/book

Lean DI https://wiki.wdf.sap.corp/wiki/display/LeanDI/Home

Fiori@BusinessSuite Infrastructure https://wiki.wdf.sap.corp/wiki/display/fiorisuite/Infrastructure

Fiori (sFIN) Release Process FAQ https://wiki.wdf.sap.corp/wiki//x/cwDPZQ

Nexus Repository https://wiki.wdf.sap.corp/wiki/display/LeanDI/Nexus+Landscape

Further Information

Page 392: BuildSAPFioriUIsWithSAPUI5_v2

SAP Web IDE - Introduction

Page 393: BuildSAPFioriUIsWithSAPUI5_v2

Introduction to SAP Web IDE

Page 394: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 425 Internal

Eclipse

SAP Fiori

Toolkit

Introduction to SAP Web IDE From Today to Vision

AppBuilder AppDesigner

UI Development

Toolkit for

HTML5

Gateway

Productivity

Accelerators

This is the current state of planning and may be changed by SAP at any time.

SAP Web IDE

Page 395: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 426 Internal

Introduction to SAP Web IDE Speeding Development by Reducing Effort

Support end-to-end application lifecycle with one tool

Prototype* Develop Test Package/

Deploy

Extend

This is the current state of planning and may be changed by SAP at any time. * Future innovation

Page 396: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 427 Internal

Introduction to SAP Web IDE Key Use Cases

Develop new Fiori applications

Extend SAP Fiori applications Not covered in this training

Page 397: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 428 Internal

Introduction to SAP Web IDE Product Benefits

Develop once, deploy everywhere, & run on any

device - mobile, tablet, desktop

Reduces cost, complexity and effort through cloud-

based offering (zero installation)

Increases developer productivity by simplifying

development to create apps faster

Profit from code templates and SAP best practices

to rapidly build applications

Improves team productivity with the ability to code

and collaborate anywhere

Page 398: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 429 Internal

Introduction to SAP Web IDE Key Features I - Development environment

Development environment

Source code editor with SAPUI5-

specific code completion (configurable

for any UI5 version)

Simple Project persistency (Git)

Mock data support for

Decoupling frontend development

from backend

testing purposes

Instant preview in browser

Comprehensive search capabilities

*Experimental features

Page 399: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 430 Internal

Introduction to SAP Web IDE Key Features II - Templates

Templates for creating new project

SAP Fiori freestyle application templates

SAP Fiori smart application templates

Templates for Fiori Libraries

Create new library

Extend an existing library

Fiori Reference Applications integration

Enable developers to easily ramp up Fiori

development by audited ready-to-run end to end

samples

Enable designers to demonstrate design and

interaction patterns in real life

Full coding with comprehensive comments

Page 400: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 431 Internal

SAP offers out-of the-box plug-ins and templates that leverage SAP Web IDE’s modular and extensible framework.

SAP Web IDE Plugins

Hybrid Application Toolkit

Create and deploy Apache Cordova hybrid apps

Templates, code completion, testing, build and deploy

OData Model Editor

Define OData models

Create OData models from scratch or import from file

Edit OData models quickly using code assist, auto complete and beautify

Validation of the code on the fly

UI Annotations modeller (work in progress)

Create new UI annotations

Edit existing annotations

Page 401: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 432 Internal

Introduction to SAP Web IDE SAP HANA Cloud Connectivity Service

SAP HANA

Cloud Connector

Internet

SAP Web IDE

Destinations

NW Gateway ERP Others

Establishes secure SSL tunnel between the SAP HANA Cloud and on-premise

systems

Connectivity created by on-premise agent through reverse-invoke process

Supports pre-configured “Destination API” and certificate inspection to safeguard

against forgeries

Complementary to SAP Gateway, SAP HANA Cloud Integration and 3rd party

integration suites both on-premise and in the cloud

Cloud (on-demand)

Customer (on-premise)

Secure Integration with the SAP Web IDE, Business Suite, and Other

On-Premise Systems

Page 402: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 433 Internal

Introduction to SAP Web IDE Same-Origin Policy for Browsers

Two pages have the same origin if the

protocol, domain, and port are the same for

both pages.

The policy prevents scripts to access

objects loaded from another origin.

To circumvent the same-origin policy:

Access both pages via a central dispatcher.

HTML5 App

REST Service

HTML5 App

REST Service Dis

pa

tch

er

Page 403: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 434 Internal

Introduction to SAP Web IDE Accessing SAPUI5 Resources in the Application Descriptor neo-app.json

To access SAPUI5 resources in your

HTML5 application, configure the SAPUI5

service routing in the SAP Web IDE

application descriptor called neo-app.json.

The application descriptor must be located

in the root folder of the repository.

Use snapshot version to use the latest

nightly build version of the SAPUI5

resources

"routes": [ { "path": "/resources", "target": { "type": "service", "name": "sapui5", "version": "1.26.6", "entryPath": "/resources" }, "description": "SAPUI5 Resources" } ]

neo-app.json

"version": "snapshot",

Page 404: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 435 Internal

Introduction to SAP Web IDE parentneoapp in the Application Descriptor neo-app.json

As with the Maven-based pom.xml, in the SAP

Web IDE a parent neo-app.json file

available.

It includes all destinations needed to SAPUI5

resources.

parent neo-ap.json exists in different versions.

Calling without a version tag, by default the

version referring to the latest "x.-SNAPSHOT"

version of the SAPUI5 resources will be used.

To refer to a specific version (e.g. required for

maintenance) add a version tag

"routes": [ { "path": "/", "target": { "type": "application", "name": "parentneoapp", "preferLocal": true }, "description": "Parent neo-app.json" } ]

neo-app.json

"version": "1.5",

Page 405: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 436 Internal

Introduction to SAP Web IDE Back-End Routing in the Application Descriptor neo-app.json

HTML5 applications can connect to one or

multiple REST services.

The URL to the REST service is configured

in a destination.

The mapping between an application URL

and a destination is defined in the

application descriptor called

neo-app.json.

The application descriptor must be located

in the root folder of the repository.

Destinations are configured using the SAP

HANA Cloud Cockpit.

"routes": [ { "path": "/sap/opu/odata", "target": { "type": "destination", "name": "CC2CLNT715", "entryPath": "/sap/opu/odata" }, "description": "S4HANA Public Cloud Test System" } ]

neo-app.json

Page 406: BuildSAPFioriUIsWithSAPUI5_v2

SAP Web IDE App Development

Basics

Page 407: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 438 Internal

SAP Web IDE App Development Basics Development Process Overview

Coding

Templates

Source code editor with code

completion, dynamic API

reference, and so on.

Wizards guiding the user through

a step-by-step process,

automatically generating needed

files and code

New project

Create Develop

GIT integration

* Experimental feature

Preview Deploy

Commit to Git

Page 408: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 439 Internal

Opening the Web IDE -Welcome screen

Introducing the

home perspective

Quick and easy

access to the most

common creation

actions

Link to external

resources and

tools

Notification every

time an update is

pushed.

Users can read

about new features Developer

perspective

Page 409: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 440 Internal

SAP Web IDE App Development Basics Development Environment Overview

Menu bar

Search

Find in files

(file name or content)

Git

Manage your

development objects

in your Git repository

API reference

Context-sensitive

Dynamic support

Toolbar

Save

Create file

Create

folder

Delete

Undo

Redo

Run

User name

Development

view

User

preferences

History

Tag, cherry-pick,

revert

Editor

SAPUI5 code editor

Code completion

Collaboration

Integration with SAP Jam

Collaborate with project

members

Page 410: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 441 Internal

SAP Web IDE App Development Basics

IDE Environment configurations

With the Environment

configurations you can

configure web IDE

behavior and look to fit

your needs

Page 411: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 442 Internal

SAP Web IDE App Development Basics Project settings

With the project settings

screen you can adjust

project specific

configurations like:

1. Run configurations

2. Globalization

3. Mock data

Page 412: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 443 Internal

SAP Web IDE App Development Basics Creating a Project

Various options are available for the developer to create a new project:

Create a new project

from a template

Clone a project from an

existing Git repository

File New Project from Template

File Git Clone Repository

Additional options are available.

They are not covered in this training.

Page 413: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 444 Internal

SAP Web IDE App Development Basics Templates

The template wizard guides the user through

the definition of an application and then

generates the scaffolding and code

Standard templates are provided from

different categories

SAP Fiori freestyle applications (Master-Detail,

Worklist…)

SAP Fiori smart templates (Object List,Object Page,

OVP…)

SAP Fiori libraries

New component

Page 414: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 445 Internal

SAP Web IDE App Development Basics Template library

The Template Library displays all

the available templates

Tools > Template Library

Page 415: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 446 Internal

SAP Web IDE App Development Basics Coding (Assisted Development)

Code completion

For JavaScript and XML

Context-sensitive

Editor completes words, code fragments,

or entire SAPUI5 objects

JS snippets

Property files

Beautification

Validators and Linting (ESLint, XML…)

Insertion of XML code snippets

Metadata completion from schema files

API Reference pane

Integrated API reference

Context-sensitive, dynamic support

Auto-save

Page 416: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 447 Internal

SAP Web IDE App Development Basics Writing Tests (Assisted Development)

QUnit

Generate unit test stubs automatically

Out of the box unit tests with templates

OPA testing

Generate OPA test stubs automatically

Out of the box unit tests with templates

Page 417: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 448 Internal

SAP Web IDE App Development Basics Run the Application

There are various ways to run your application:

Run as

Web Application: Application Preview in browser (see

separate slide)

Unit Test: run the application as a unit test

SAP Fiori Component: run in the SAP Fiori launchpad

environment)

SAP Fiori Embedded mode (soon to come)

Run Configurations (see separate slide)

Run with Mock Data (see separate slide)

Automatically generated data

Mock data provided in JSON files

Additional options are available.

They are not covered in this training.

Page 418: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 449 Internal

SAP Web IDE App Development Basics Application Preview in browser

Choice of simulator

Desktop (large)

Mobile devices, e.g. iPad

(medium), iPhone (small),

Android, etc.

Define a custom size

The application is

responsive – will adapt its

appearance to the screen

size

Multiple screen sizes are

predefined

Orientation

The orientation of the screen

can be toggled between

landscape and portrait view

QR Code generation

A QR Code is generated for

the URL by

clicking the

rectangle

Refresh

The application can be

reloaded without needing to

rerun it from the development

environment

Language

If the application supports

multiple languages (i18n

properties), then the language

text can be changed on the fly

Frame

Page 419: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 450 Internal

SAP Web IDE App Development Basics Run configurations

You can configure how to run the applications in

the project settings:

Application file path to the file that is used to run the

application

Run the application preview with or without frame

Open the application with mock data

Application resource mapping, i.e. where to search for

application resources

Application URL Parameters: name = value

Application

File Path Frame Mock Data

Application

Resource

Mapping

Application

URL

Parameters

Web

application x x x x x

Unit Test x x

SAP Fiori

Component x x x

Page 420: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 451 Internal

SAP Web IDE App Development Basics Run the application with mock data

You can run the application with mock data, e.g. in case your

backend systems are not ready or not available

There are two options available:

Let the mock service generate data

Provide data in a JSON file

Edit Mock Data is available that allows to create a JSON file

Project Settings:

Page 421: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 452 Internal

SAP Web IDE App Development Basics What Is Git?

Version control system

Distributed versioning

Enables collaborative workflows

Git is a widely used revision control and source code management system.

Page 422: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 453 Internal

SAP HANA Cloud Platform

SAP Web IDE App Development Basics SAP Web IDE and Git Integration - Overview

Source code is stored in Git repositories

Every developer has a local clone of a central remote

repository

The clone is only executed initially to create the local

Git repository. (If the clone is executed again, then

the local Git repository will be overridden)

A specific state of the repository is checked out into

the developer’s workspace

Changes are collected in commits (≅ ABAP transport)

Commits can be pushed to and fetched from the

remote repository

Git allows you to branch or merge branches at any

time

Remote

Git

Repository

Local Git

Repository

Push Clone

Fetch

Workspace Checkout

Commit Files

1

2

3

4

Page 423: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 454 Internal

SAP Web IDE App Development Basics SAP Web IDE and Git Integration - GIT Pane

SAP Web IDE GIT client supports

full and easy integration with GIT.

You can achieve all of your GIT

activities with an easy and intuitive

interface Git client pane

Commit & Push

Page 424: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 455 Internal

SAP Web IDE App Development Basics SAP Web IDE and Git Integration - GIT History Pane

The GIT history pane enables you

to easily search, compare and

perform operations on your

previous GIT activities, cross

branches

Page 425: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 456 Internal

WEB IDE URL for SAP developers https://rde-fiori.dispatcher.neo.ondemand.com/index.html

WEB IDE Media channel videos https://mediashare.wdf.sap.corp/public/channel/SAP+WEB+IDE

Documentation within SAP Web IDE Choose Help > Documentation

Official documentation https://help.hana.ondemand.com/

under Platform Solutions choose SAP SAP Web IDE

SAPUI5 & SAP Web IDE http://scn.sap.com/community/developer-center/front-end

Fiori@BusinessSuite Guidelines https://wiki.wdf.sap.corp/wiki//x/G58MY

Further Information

Page 426: BuildSAPFioriUIsWithSAPUI5_v2

Fiori Reference Apps Global Design

Frontrunner Apps

Page 427: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 459 Internal

Fiori Reference Apps Overview

Enable developers to easily ramp up Fiori

development by audited ready-to-run end to

end samples

Enable designers to demonstrate design and

interaction patterns in real life

Full coding with comprehensive comments

Comprehensive documentation and cross

references

Test automation (Unit tests & One Page

Acceptance tests OPA)

Page 428: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 460 Internal

Fiori Reference Apps Technical Information

Based on standard Enterprise Procurement Model (EPM)

Simple business scenario model used e.g. for training, education, validation

Data generator to provide defined data sets

Running in NW Basis system

Also used for NW Outbound Qualification

Use within your preferred development environment

Works best with SAP Web IDE

Directly available as integrated samples

Mock-server support allows immediate look & try even without backend system

Tightly integrated by cross-references from surrounding documentation

Eclipse

Live backend (existing demo or own system)

Page 430: BuildSAPFioriUIsWithSAPUI5_v2

© 2015 SAP SE or an SAP affiliate company. All rights reserved. 464 Internal

Fiori Reference Apps Wiki

https://wiki.wdf.sap.corp/wiki/display/refapps/Fiori+Reference+Applications+Home

Portal: /go/referenceapps

SCN Documentation: http://scn.sap.com/docs/DOC-59963

Fiori Reference Apps Consultation Hours

WDF18 “Glass box” / 2nd floor.

Mondays: 4pm - 5pm

Thursdays :10am - 11am

Email: SAP Fiori Reference Apps

Further Information