Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / SAPUI5 / Data, Binding & Navigation

Data, Binding & Navigation

SAPUI5 · SAP Fiori UI5 and Mobile ·

Open the interactive lesson →
  1. Models
  2. Setting models and binding paths
  3. Binding types
  4. Binding modes
  5. Composite and expression binding, formatters, types
  6. Texts and translation (i18n)
  7. OData basics for UI5 developers
  8. Connecting the app to a service
  9. CRUD with the OData V2 and V4 models
  10. OData V4 in depth: the Sales Order Approval dashboard
  11. Filters, sorters and paging
  12. Routing and navigation
  13. Fragments and dialogs
  14. Build, deployment and Git
  15. Interview questions

Everything about data in a freestyle SAPUI5 app: models, data binding, formatters and types, i18n, consuming OData V2 and V4 services (read, create, update, delete, $batch, filters), routing and navigation, fragments and dialogs, build, deployment and Git. The basic examples use the Products app (my.products) from SAPUI5 › 03 · SAPUI5 Fundamentals; OData V4 in depth uses the Sales Order Approval dashboard (Part 10). Custom controls are on SAPUI5 › 05 and testing on SAPUI5 › 06. The backend side of OData (SEGW, Gateway) is on CORE ABAP › 08 OData; RAP services in the RAP section.

Part 1 – Models

A model is a client-side object that holds the data (or fetches it on demand) and offers methods to read, set and update it. Controls are bound to model paths, so the UI updates when the data changes. A UI5 model is not the backend service: an ODataModel is a proxy in the browser that talks to an OData service built in ABAP (SEGW, RAP) or CAP.

Models in an app: internal sources (i18n texts, JS objects, device info) and external sources (OData V4/V2, REST/JSON) feed the OData, JSON and Resource models, which views bind to with their default binding mode

Model

Module

Side

Typical use

Default mode

JSONModel

sap/ui/model/json/JSONModel

Client

View state, small data sets, mock data, data loaded from a REST/JSON URL

TwoWay

XMLModel

sap/ui/model/xml/XMLModel

Client

XML data; rarely used (all values arrive as strings)

TwoWay

ResourceModel

sap/ui/model/resource/ResourceModel

Client

Translatable texts from i18n.properties (Part 6)

OneWay

ODataModel V2

sap/ui/model/odata/v2/ODataModel

Server

OData V2 services (SEGW, RAP V2 binding)

OneWay

ODataModel V4

sap/ui/model/odata/v4/ODataModel

Server

OData V4 services (RAP, CAP); recommended for new apps

TwoWay

Device model

JSONModel wrapping sap/ui/Device

Client

Named device; {device>/system/phone} to adapt the UI

set to OneWay

  • Client-side models load all their data into the browser; sorting and filtering then run in the browser without server calls (like an internal table in ABAP). Use them for small data sets.
  • Server-side models request data in pages as the UI needs it ($top/$skip, growing lists), cache it, and write changes back; sorting and filtering are sent to the server ($orderby, $filter).

Working with a JSONModel

sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"
], (Controller, JSONModel) => {
"use strict";
return Controller.extend("my.products.controller.List", {
onInit() {
const oModel = new JSONModel({
priceLimit: 500,
products: [
{ id: "P-100", name: "Laptop 15", price: 899, currency: "EUR", inStock: true },
{ id: "P-200", name: "Monitor 27", price: 249, currency: "EUR", inStock: false }
]
});
this.getView().setModel(oModel);                    // default (unnamed) model

oModel.getProperty("/products/0/name");             // "Laptop 15"
oModel.setProperty("/products/1/inStock", true);    // bound controls update at once
},

async loadFromFile() {
const oModel = new JSONModel();
await oModel.loadData("model/products.json");       // async; or new JSONModel(url)
this.getView().setModel(oModel, "shop");            // named model: {shop>/products}
}
});
});
  • Other methods: setData(obj) (replace all data), getData(), refresh(true) (force bound controls to update after you changed the data object directly).

Part 2 – Setting models and binding paths

Where

How

Visible to

manifest.json (recommended)

sap.ui5/models – the component creates and sets them

All views of the component

Component in code

this.getOwnerComponent().setModel(oModel, "name")

All views of the component

View

this.getView().setModel(oModel, "name")

That view and its controls

Control

this.byId("productTable").setModel(oModel)

That control and its children

  • Models are propagated down the control tree: a child sees the models of its parents. Dialogs and fragments are not in the view's tree, so add them as dependents (addDependent) to inherit the view's models (Part 13).
  • Named models: setModel(oModel, "shop"), then {shop>/products} in bindings and getModel("shop") in code. The unnamed default model uses {/products}.
  • Legacy: sap.ui.getCore().setModel(oModel) (global model for the whole page) is deprecated; use the manifest or the component instead.

Binding paths and contexts

Path

Example

Meaning

Absolute (starts with /)

/products/1/price

From the model root; / steps into objects, a number selects an array index

Relative (no /)

price

Resolved against the control's binding context (set by an aggregation template or by element binding)

Named model

shop>/products, shop>price

Same, in the model named shop

OData

/Products('P-100')/Name, /Products('P-100')/_Supplier/Name

Entity set + key, then properties or navigation properties

  • A binding context points at one record: oItem.getBindingContext() (add the model name for named models). Use .getPath() (e.g. /products/1), .getProperty("price") or .getObject() (the whole record).

Part 3 – Binding types

Property, aggregation, element and expression binding with a small JSON model

Property binding

A control property is bound to one value: <Input value="{/customer/name}"/>. The extended form allows options: value="{ path: '/customer/name', mode: 'OneWay' }".

Aggregation (list) binding

An aggregation is bound to an array or an OData entity set; the inner control is the template that UI5 clones once per entry, and its paths are relative to each entry.

<Table id="productTable" growing="true" growingThreshold="20"
items="{ path: '/Products', sorter: { path: 'Name' } }">
<columns>
<Column><Text text="Product"/></Column>
<Column hAlign="End"><Text text="Price"/></Column>
</columns>
<items>
<ColumnListItem type="Navigation" press=".onItemPress">
<cells>
<ObjectIdentifier title="{Name}" text="{ProductID}"/>
<ObjectNumber number="{Price}" unit="{Currency}"/>
</cells>
</ColumnListItem>
</items>
</Table>
  • Grid table (sap.ui.table.Table): bind rows="{/Products}" and give each t:Column a t:template, e.g. <t:Column><t:label><Label text="Product"/></t:label><t:template><Text text="{Name}"/></t:template></t:Column>.
  • Without the template (<items>…) an aggregation binding has nothing to clone. For different row layouts use a factory function instead of a template.

Element (context) binding

Element binding sets a binding context on a container (view, form, panel), so all children can use relative paths. It is the standard way to show one record, typically on a detail page.

<form:SimpleForm id="productForm" binding="{/Products('P-100')}">
<Label text="Product ID"/>
<Text text="{ProductID}"/>
<Label text="Name"/>
<Text text="{Name}"/>
</form:SimpleForm>
// in code, usually in the route's patternMatched handler (Part 12)
this.getView().bindElement({
path: `/Products('${sId}')`,
parameters: { $expand: "_Supplier" }  // V4; with the V2 model: { expand: "Supplier" }
});

Expression binding

A short calculation directly in the view (Part 5): visible="{= ${/products}.length > 0 }".

Part 4 – Binding modes

Mode

Direction

Typical use

OneTime

Model → view once, when the binding is created; later changes are ignored

Static data, metadata, texts that never change

OneWay

Model → view; every model change updates the view

Display-only data

TwoWay

Model ↔ view; user input is written back to the model

Input fields, forms

Modes supported per model

Model

OneTime

OneWay

TwoWay

OData V4 model

Yes

Yes

Yes (default)

OData V2 model

Yes

Yes (default)

Yes

ODataMetaModel (V4)

Yes (default)

Yes

No

ODataMetaModel (V2)

Yes (default)

No

No

JSON model

Yes

Yes

Yes (default)

XML model

Yes

Yes

Yes (default)

Resource model

Yes

Yes (default)

No

  • Change the default of a model with oModel.setDefaultBindingMode("OneWay") or in the manifest ("settings": { "defaultBindingMode": "TwoWay" } – needed for editable forms with the V2 model).
  • Change it for one binding: value="{ path: 'Name', mode: 'OneTime' }".

Part 5 – Composite and expression binding, formatters, types

Syntax

Example

Simple

text="{/customer/name}", text="{Name}", text="{i18n>title}"

Extended (object)

value="{ path: 'Price', type: 'sap.ui.model.type.Float', mode: 'OneWay' }"

Composite (several parts)

text="{ parts: ['firstName', 'lastName'], formatter: '.formatter.fullName' }"

Expression

state="{= ${Price} > ${/priceLimit} ? 'Warning' : 'None' }"

OData V2 metadata

maxLength="{/#Product/Name/@maxLength}"

OData V4 metadata

text="{Name##@com.sap.vocabularies.Common.v1.Label}" (## switches from data to metadata)

  • Composite and expression binding use the complex binding syntax, which is the default in current releases (the old binding-syntax bootstrap option is deprecated); apps also set data-sap-ui-compat-version="edge".
Choosing between i18n text, type, expression binding and formatter, with sales order examples

Expression binding

  • Syntax: {= expression }. Inside, ${path} is the bound value (formatted by its type) and %{path} the raw model value. JavaScript operators work: comparison, &&, ||, !, ? :, +.
<ObjectStatus text="{Name}" state="{= ${Price} > ${/priceLimit} ? 'Warning' : 'Success' }"/>
<Input value="{Price}" editable="{= ${Status} !== 'LOCKED' }"/>
<Text text="{= %{Stock} > 10 ? 'In stock' : 'Only ' + %{Stock} + ' left' }"/>
<Button text="Delete" visible="{= ${/selectedCount} > 0 }"/>
  • OData decimal and Int64 values arrive as strings, and ${…} may give a formatted string ("1,234.00"); use %{…} for numeric comparisons, or a formatter.
  • Keep expressions short; anything with more logic belongs in a formatter (readable and testable).

Formatters

A formatter is a function called with the model value(s) just before the value is shown. It changes only what is displayed, not the model data (like a conversion exit in ABAP, but one-way). Typical uses: status texts, colours, dates, combined values.

// webapp/model/formatter.js
sap.ui.define([], () => {
"use strict";
return {
stockText(bInStock) {
return bInStock ? "In stock" : "Out of stock";
},
priceState(fPrice, fLimit) {
return fPrice > fLimit ? "Warning" : "None";
}
};
});
// controller: make the module available as this.formatter
sap.ui.define([
"sap/ui/core/mvc/Controller",
"../model/formatter"
], (Controller, formatter) => {
"use strict";
return Controller.extend("my.products.controller.List", {
formatter: formatter
});
});
<!-- view: the leading dot means "property of the controller" -->
<Text text="{ path: 'inStock', formatter: '.formatter.stockText' }"/>
<ObjectNumber number="{price}"
state="{ parts: ['price', '/priceLimit'], formatter: '.formatter.priceState' }"/>
  • Alternative without a controller property: core:require="{ formatter: 'my/products/model/formatter' }" on the view or a control, then formatter: 'formatter.stockText' (no dot).
  • Put formatters in model/formatter.js, never in global variables, so they are reusable and unit-testable.

Types: format, parse and validate

A data type formats the value for display and parses and validates user input on the way back, so it works with two-way binding (a formatter does not).

<Input value="{ path: '/quantity', type: 'sap.ui.model.type.Integer',
constraints: { minimum: 1, maximum: 99 } }"/>
<Input value="{ path: '/deliveryDate', type: 'sap.ui.model.type.Date',
formatOptions: { style: 'medium' } }"/>
<ObjectNumber number="{ parts: ['price', 'currency'], type: 'sap.ui.model.type.Currency',
formatOptions: { showMeasure: false } }" unit="{currency}"/>
  • Types: String, Integer, Float, Boolean, Date, Time, DateTime, Currency, Unit in sap.ui.model.type; OData types in sap.ui.model.odata.type (the V4 model derives them automatically from the metadata).
  • Invalid input raises a validation error; with message handling on ("handleValidation": true in sap.ui5) the field gets a red valueState and the message appears in the message model.
  • XML model pitfall: every value from an XML model is a string, so controls that expect a boolean or a number (CheckBox selected, RatingIndicator value) need a type, e.g. { path: 'inStock', type: 'sap.ui.model.type.Boolean' }, or use a JSON model.

Part 6 – Texts and translation (i18n)

Apps are used in many languages, so no visible text is hard-coded. Texts live in .properties files (key = text) and are bound through a ResourceModel; this is internationalisation (i18n).

# webapp/i18n/i18n.properties  (default / fallback texts)
appTitle=Products
title=Product list
productCount=Products ({0})
stockLow=Only {0} left in stock
deleteConfirm=Delete product {0}?
  • Translations: i18n_de.properties, i18n_fr.properties … The runtime picks the user's language and falls back along the chain i18n_de_CH → i18n_de → i18n_en (the fallback locale, default en) → i18n.properties, unless supportedLocales / fallbackLocale say otherwise.
  • Manifest: sap.app/i18n names the file (for {{appTitle}} in the descriptor) and sap.ui5/models/i18n creates the model with "bundleName": "my.products.i18n.i18n". Optional settings: supportedLocales, fallbackLocale.
  • In a view: text="{i18n>title}". Texts with placeholders ({0}) are usually filled in code:
const oBundle = this.getOwnerComponent().getModel("i18n").getResourceBundle();
const sText = oBundle.getText("stockLow", [3]);       // "Only 3 left in stock"
  • The language comes from the launchpad user settings or the browser; test with the URL parameter sap-language=DE.

Part 7 – OData basics for UI5 developers

OData (Open Data Protocol) is a REST-based protocol for reading and changing data over HTTP. It was created by Microsoft and is now an OASIS standard. A browser cannot call ABAP function modules, BAPIs, classes or CDS views directly, so an OData service sits in between and exposes them as resources. Like all REST services it is stateless: each request carries everything the server needs, so the server keeps no session memory and scales to many users.

Term

Meaning

Example

Entity type

Structure of a record: properties, key, data types, lengths

Product (key ProductID, Name, Price, Currency)

Entity set

Addressable collection of an entity type; the endpoint for CRUD

Products (SEGW naming: ProductSet)

Navigation property

Follows an association to related entities (a join)

Order → Order_Details

Service document

Lists the entity sets

…/Northwind.svc/

Metadata document

Full description of types, keys, associations, annotations

…/Northwind.svc/$metadata

  • Often one database table or CDS view becomes one entity type with one entity set, and a join becomes an association with a navigation property; real services can also combine or project data.
  • URL shape: https://<host>:<port>/<service path>/<EntitySet>?<query options>.

Query options (try them on the public Northwind sample service)

Service root for learning: https://services.odata.org/V2/Northwind/Northwind.svc/ (V4: replace V2 with V4). V2 returns XML in the browser unless you add $format=json; V4 returns JSON.

Task

URL part

SQL analogy

Read all products

/Products?$format=json

SELECT * FROM products

Paging: skip 10, take 3

/Products?$skip=10&$top=3

OFFSET 10 ROWS FETCH 3

Filter

/Products?$filter=CategoryID eq 2

WHERE categoryid = 2

Contains (V2)

$filter=substringof('cola',ProductName) eq true

WHERE productname LIKE '%cola%'

Contains (V4)

$filter=contains(ProductName,'cola')

WHERE productname LIKE '%cola%'

Some columns

$select=ProductID,ProductName,Discontinued

SELECT productid, productname, …

Sort

$orderby=UnitPrice desc

ORDER BY unitprice DESCENDING

Count

/Products/$count

SELECT COUNT(*)

One record by key

/Products(11), /Orders(10248)

SELECT SINGLE … WHERE key = …

Related data

/Orders(10248)?$expand=Order_Details,Employee

INNER JOIN

  • Inline count with the data: $inlinecount=allpages (V2) / $count=true (V4). Many requests can be sent in one HTTP call with $batch (Part 9).

EPM – SAP's demo data model on ABAP systems

  • EPM (Enterprise Procurement Model) is SAP's demo data model for a fictitious company: business partners, products, sales orders, purchase orders and invoices, stored in the SNWD_* tables.
  • Fill the tables with the data generator, transaction SEPM_DG.
  • SAP's demo OData services are built on it, e.g. /sap/opu/odata/IWBEP/GWSAMPLE_BASIC/, so it is the on-premise alternative to Northwind for practising.

OData V2 vs V4 in UI5

Aspect

OData V2 model

OData V4 model

Module

sap/ui/model/odata/v2/ODataModel

sap/ui/model/odata/v4/ODataModel

Typical backend

SEGW projects, RAP service binding (V2)

RAP service binding (V4), CAP

Default binding mode

OneWay

TwoWay

Create / update / delete

Model methods: create, update, remove, createEntry + submitChanges

Through bindings and contexts: ODataListBinding.create, Context.setProperty, Context.delete

Actions / functions

callFunction (function imports)

Operation binding: bindContext(...).invoke()

Update request

MERGE or PUT

PATCH

$batch

On by default (useBatch), deferred groups + submitChanges

Always for $auto and own groups; submitBatch(groupId)

$select / $expand

Explicit (urlParameters, binding parameters)

Can be automatic: autoExpandSelect: true

Fiori elements stack

Fiori elements for OData V2

Fiori elements for OData V4 (sap.fe), SAP Fiori › 03

Part 8 – Connecting the app to a service

Path of an OData request: control, binding, ODataModel, $batch over HTTP, OData service and database; proxy in local development, same origin in production

Steps: (1) declare a data source in the manifest, (2) create the default model for it, (3) during local development add a proxy (or a mock server), (4) bind controls to entity sets.

"sap.app": {
"dataSources": {
"mainService": {
"uri": "/V2/Northwind/Northwind.svc/",
"type": "OData",
"settings": { "odataVersion": "2.0" }
}
}
},
"sap.ui5": {
"models": {
"": {
"dataSource": "mainService",
"preload": true,
"settings": { "defaultBindingMode": "TwoWay" }
}
}
}
  • The model type is derived from odataVersion (2.0 → V2 model, 4.0 → V4 model). The URI is relative; never hard-code a server in the manifest.
  • Then bind: <List items="{/Products}"><StandardListItem title="{ProductName}"/></List> – the model sends the request and fills the list.

CORS and the development proxy

CORS (cross-origin resource sharing) is the browser rule that a page from one origin ( http://localhost:8080) may call another origin (the SAP host) only if that server allows it. SAP systems normally don't, so a direct call fails with a CORS error. The fix in development is a proxy: the local server forwards /sap/... (or /V2/...) to the real backend, so the browser only talks to localhost.

# ui5.yaml – generated by the Fiori tools, run with "fiori run" (npm start)
server:
customMiddleware:
- name: fiori-tools-proxy
afterMiddleware: compression
configuration:
backend:
- path: /V2                              # an SAP system: path /sap
url:  https://services.odata.org        # an SAP system: https://<host>:<port>
ui5:
path:
- /resources
- /test-resources
url:  https://ui5.sap.com
  • The proxy exists only for BAS / VS Code development. In production the app and the service share an origin (launchpad on the ABAP server) or the BTP approuter forwards calls through a destination.
  • Mock server (no backend needed): the Fiori tools add @sap-ux/ui5-middleware-fe-mockserver with webapp/localService/metadata.xml and JSON mock files (npm run start-mock). Legacy: sap/ui/core/util/MockServer (V2 only).
  • Reaching on-premise systems from SAP BTP (destinations, Cloud Connector) → see BTP Foundations › BTP Services, Identity & Connectivity.

Part 9 – CRUD with the OData V2 and V4 models

Operation

V2 model / binding

V4 model

HTTP

SEGW method (DPC_EXT)

Read list

items="{/ProductSet}" or read("/ProductSet")

items="{/Products}" (list binding)

GET

<SET>_GET_ENTITYSET

Read one

bindElement("/ProductSet('P1')") or read(…)

bindElement / bindContext(…).requestObject()

GET

<SET>_GET_ENTITY

Create

create("/ProductSet", oData) or createEntry + submitChanges

oListBinding.create(oData)

POST

<SET>_CREATE_ENTITY

Update

update(sPath, oData) or two-way binding + submitChanges

Two-way binding or oContext.setProperty

MERGE/PUT (V2), PATCH (V4)

<SET>_UPDATE_ENTITY

Delete

remove(sPath)

oContext.delete()

DELETE

<SET>_DELETE_ENTITY

Function / action

callFunction("/Release", …)

bindContext("…release(...)", oCtx).invoke()

POST/GET

EXECUTE_ACTION

Deep insert

create with nested data

oListBinding.create() with nested data (newer releases)

POST

CREATE_DEEP_ENTITY

File download

GET …/ProductSet('P1')/$value (link or window.open)

same

GET

GET_STREAM

File upload

sap.m.upload.UploadSet or sap.ui.unified.FileUploader posting to the media entity

same

POST/PUT

CREATE_STREAM

  • bindElement, bindItems and bindRows are binding methods on controls, not model methods; they make the model send GET requests. There is no upload() method: uploads go through an upload control and a media entity.
  • The SEGW method names are generated per entity set in the DPC_EXT class (backend details: CORE ABAP › 08 OData). RAP services need no such methods (RAP section).

OData V2 model

const oModel = this.getOwnerComponent().getModel();       // v2.ODataModel from the manifest

oModel.read("/ProductSet", {                              // READ with filter and expand
filters: [new Filter("Category", FilterOperator.EQ, "Laptops")],
urlParameters: { "$expand": "ToSupplier", "$top": "20" },
success: (oData) => MessageToast.show(`${oData.results.length} products`),
error: (oError) => MessageBox.error(oError.message)
});

oModel.create("/ProductSet", {                            // CREATE
ProductId: "P-300", Name: "Keyboard", Price: "49.00", Currency: "EUR"
}, {
success: () => MessageToast.show("Created"),
error: (oError) => MessageBox.error(oError.message)
});

// success / error below: callback functions like the ones above
oModel.update("/ProductSet('P-300')", { Price: "45.00" }, { success, error });   // UPDATE
oModel.remove("/ProductSet('P-300')", { success, error });                       // DELETE

oModel.callFunction("/ReleaseProduct", {                  // function import
method: "POST",
urlParameters: { ProductId: "P-300" },
success, error
});
// form-based create: an entry that only exists in the browser until it is submitted
const oContext = oModel.createEntry("/ProductSet", {
properties: { Name: "", Price: "0.00" }
});
this.getView().setBindingContext(oContext);  // the form edits it (two-way binding)

oModel.submitChanges({ success, error });  // POST in one $batch
// oModel.resetChanges();                     // or discard all pending changes
  • Other useful V2 methods: metadataLoaded() (promise), refresh(), hasPendingChanges(), setDeferredGroups([...]), setUseBatch(false) (single requests, easier to debug).

OData V4 model

const oBinding = this.byId("productTable").getBinding("items");   // ODataListBinding

// CREATE – the row appears at once; POST goes with the next batch of its group
const oContext = oBinding.create({ ProductID: "P-300", Name: "Keyboard", Price: "49.00" });
oContext.created().then(() => MessageToast.show("Created"),
(oError) => { /* create failed or was cancelled */ });

// UPDATE – a two-way bound Input does this automatically; in code:
oContext.setProperty("Price", "45.00");                   // PATCH

// DELETE
await oContext.delete();                                  // DELETE

// bound ACTION – namespace-qualified action name from $metadata
const oAction = this.getView().getModel()
.bindContext("com.sap.gateway.srvd.zui_product.v0001.release(...)", oContext);
await oAction.invoke();                                   // older releases: execute()
  • Read one record without a control: oModel.bindContext("/Products('P-100')").requestObject().
  • Manifest settings commonly used: operationMode: "Server" (filter and sort on the server), autoExpandSelect: true (the model builds $select/$expand from the bindings), earlyRequests: true.
  • Draft-enabled RAP or CAP services handle Edit/Save/Discard through draft actions; Fiori elements does this automatically (→ see SAP Fiori › 03 · SAP Fiori Elements).

$batch, change groups and concurrency

$batch packs many OData requests into one HTTP POST to <service>/$batch. Modifying requests are grouped in change sets, which the server processes as one unit (all succeed or all fail); reads are outside change sets. Fewer round trips = faster apps.

  • V2: useBatch is on by default. Put changes in a deferred group (setDeferredGroups(["changes"]), groupId: "changes") to collect them and send them with submitChanges({ groupId: "changes" }).
  • V4: every binding has an update group. $auto (default) sends changes automatically in a batch, $direct sends single requests, and an own group name ($$updateGroupId: "productGroup" in the binding parameters) collects changes until oModel.submitBatch("productGroup"); undo with oModel.resetChanges("productGroup").
  • CSRF token: the models fetch an X-CSRF-Token automatically before modifying requests. ETag: if the service delivers ETags the model sends If-Match, so a change to data that someone else modified fails (optimistic locking).
  • Messages: backend error and success messages are collected in the message model (sap/ui/core/Messaging; Legacy: sap.ui.getCore().getMessageManager()) and shown with a MessagePopover or MessageBox.

Part 10 – OData V4 in depth: the Sales Order Approval dashboard

The V4 model works differently from the V2 model: there is no read(), create() or callFunction() on the model. Everything goes through bindings (list, context, property, operation) and the contexts they create. Once you see this tree, reading, editing, actions and refreshing become simple. The example is the manager dashboard on the service ZUI_SalesOrder_O4 (→ see SAPUI5 › 03 · SAPUI5 Fundamentals, Part 11).

OData V4 model: list binding with header context and row contexts, context binding for the detail page with child bindings, operation binding for the approve action, side effects, groups, batch and messages

Binding

Created by

Gives you

ODataListBinding

items="{/SalesOrder}", oModel.bindList(path)

Row contexts, create, filter, sort, getHeaderContext() (for $count), requestContexts()

ODataContextBinding

binding="{…}", bindElement, oModel.bindContext(path)

One bound context (getBoundContext()), requestObject()

Operation binding (context binding whose path ends with (...))

oModel.bindContext("…approve(...)", oContext)

setParameter, invoke(), the result context

ODataPropertyBinding

text="{NetAmount}"

One value with its OData type

  • A context (sap/ui/model/odata/v4/Context) is one entity: getProperty, requestObject, requestProperty, setProperty (PATCH), delete(), created() (promise of a new row), requestSideEffects, refresh.
  • Detail page: if you pass the row context of the list (setBindingContext(oRowContext)), list and detail share the same data. With bindElement(path) the detail page gets its own context binding and its own copy, so a change on one side must be refreshed on the other.

Binding parameters that matter

Parameter

Effect

$select, $expand, $filter, $orderby, $count: true

OData query options for this binding; with autoExpandSelect you rarely write $select / $expand yourself

$$updateGroupId: "orderEdit"

Changes of this binding wait in group orderEdit until submitBatch("orderEdit")

$$groupId

Group for read requests, e.g. $direct for one slow request outside the batch

$$ownRequest: true

The binding sends its own request instead of reusing the parent's data

$$patchWithoutSideEffects: true

The PATCH response does not overwrite other values; load them with requestSideEffects

$$operationMode: "Server"

Filter and sort on the server (or set operationMode once in the manifest)

Approve an order: bound action + side effects

// controller/OrderDetail.controller.js (excerpt) – the view is bound to one /SalesOrder('…')
async onApprove() {
const oContext = this.getView().getBindingContext();         // v4.Context of the order
const oAction = oContext.getModel().bindContext(
"com.sap.gateway.srvd.zui_salesorder.v0001.approve(...)", oContext);   // name from $metadata
try {
await oAction.invoke();                                      // POST …/approve
MessageToast.show(this.getResourceBundle().getText("approved"));
await oContext.requestSideEffects([                          // reload only what changed
{ $PropertyPath: "Status" },
{ $PropertyPath: "ApprovedBy" }
]);
} catch (oError) {
MessageBox.error(oError.message);                            // also in the message model
}
}
  • The action name is namespace-qualified, exactly as in $metadata: RAP com.sap.gateway.srvd.<service definition>.v0001.approve(...), CAP e.g. ManagerService.approve(...). Action parameters: oAction.setParameter("Reason", sText) before invoke() (the Reject dialog).
  • invoke() replaced execute() (UI5 1.123); both return a promise.
  • Side effects = values the server changed as a consequence (status, totals, items). Fiori elements reads the @Common.SideEffects annotations and refreshes automatically; a freestyle app calls requestSideEffects itself. { $NavigationPropertyPath: "" } reloads the whole entity, { $NavigationPropertyPath: "_Item" } the items.
  • Back on the dashboard the approved order must leave the "waiting" list: refresh the list binding (this.byId("orderTable").getBinding("items").refresh()), or share the row context with the detail page as described above.

Edit with Save and Cancel (own update group)

// OrderDetail: bind the order with an own update group, child bindings inherit it
this.getView().bindElement({
path: `/SalesOrder('${sId}')`,
parameters: { $$updateGroupId: "orderEdit" }
});

onSave() {
this.getView().getModel().submitBatch("orderEdit");     // send all PATCH/POST/DELETE of the group
},
onCancel() {
this.getView().getModel().resetChanges("orderEdit");    // discard them in the browser
},
onNavBack() {
if (this.getView().getModel().hasPendingChanges("orderEdit")) {
// ask before leaving (MessageBox.confirm), then resetChanges or submitBatch
}
}
  • Read without a control: await oModel.bindContext("/SalesOrder('SO-0000041')").requestObject(); one value: await oContext.requestProperty("NetAmount"); a list: await oModel.bindList("/SalesOrder").requestContexts(0, 10).
  • Draft-enabled services (RAP with draft, CAP @odata.draft.enabled) keep the edit state on the server with Edit / Activate / Discard actions; Fiori elements does this for you, a freestyle app calls these actions itself (→ see SAP Fiori › 03 · SAP Fiori Elements).
  • Messages: error and success messages of the service land in the message model (Messaging); bind a MessagePopover to it. In a $batch each request reports its own result, so one failed change does not hide the others.
  • Typing: OData Edm.Decimal and Edm.Int64 values are strings in JavaScript; compare with %{…} or convert in a formatter (Part 5).

Part 11 – Filters, sorters and paging

sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/Filter",
"sap/ui/model/FilterOperator",
"sap/ui/model/Sorter"
], (Controller, Filter, FilterOperator, Sorter) => {
"use strict";
return Controller.extend("my.products.controller.List", {
onSearch(oEvent) {                                     // SearchField search event
const sQuery = oEvent.getParameter("query");
const aFilters = sQuery ? [new Filter("Name", FilterOperator.Contains, sQuery)] : [];
this.byId("productTable").getBinding("items").filter(aFilters);
},

onFilterCheap() {                                      // combined filter: OR
const oFilter = new Filter({
filters: [
new Filter("Price", FilterOperator.LT, 100),
new Filter("Category", FilterOperator.EQ, "Accessories")
],
and: false
});
this.byId("productTable").getBinding("items").filter(oFilter);
},

onSortByPrice() {
const oBinding = this.byId("productTable").getBinding("items");
oBinding.sort(new Sorter("Price", true));            // true = descending
}
});
});
  • Operators: EQ, NE, GT, GE, LT, LE, BT (between, value1 + value2), Contains, StartsWith, EndsWith. Several filters on the same field are OR-combined, on different fields AND.
  • Grouping: new Sorter("Category", false, true) – the third argument groups the list with headers.
  • Declarative in XML: items="{ path: '/Products', sorter: { path: 'Name' }, filters: [{ path: 'Price', operator: 'GT', value1: 100 }] }". V4 binding parameters: parameters: { $select: 'ProductID,Name', $expand: '_Supplier', $count: true }.
  • With an OData model, filters and sorters become $filter / $orderby on the server; with a JSONModel they run in the browser. SearchField liveChange (parameter newValue) filters while typing.
  • Paging: growing="true" + growingThreshold="20" on a List or sap.m.Table loads 20 rows at a time ($skip/$top); the grid table loads rows while scrolling.

Part 12 – Routing and navigation

The router turns the URL hash (index.html#/products/P-100) into views: each view state gets its own URL, so the browser back button, bookmarks and launchpad deep links work. The router belongs to the component (UIComponent provides it), reads its configuration from the manifest and is started with this.getRouter().initialize() in Component.init (SAPUI5 › 03).

Routing flow: navTo, hash change, route pattern match, target view placed in the App, patternMatched handler binds the record, back navigation with History

Routing configuration in manifest.json

"routing": {
"config": {
"routerClass": "sap.m.routing.Router",
"type": "View",
"viewType": "XML",
"path": "my.products.view",
"controlId": "app",
"controlAggregation": "pages",
"async": true,
"bypassed": { "target": "notFound" }
},
"routes": [
{ "name": "list",   "pattern": "",                     "target": "list" },
{ "name": "detail", "pattern": "products/{productId}", "target": "detail" }
],
"targets": {
"list":     { "id": "list",     "name": "List",     "level": 1 },
"detail":   { "id": "detail",   "name": "Detail",   "level": 2 },
"notFound": { "id": "notFound", "name": "NotFound", "transition": "show" }
}
}

Part

Meaning

config

Defaults for all targets: view type, package path, the container control (controlId = ID of the App in the root view) and its aggregation (pages)

routes

Name + URL pattern + target(s). The first matching route wins; "" is the start route

targets

Which view to show (name in path), its ID, and level (decides the slide direction)

bypassed

Target shown when no route matches (a "not found" page)

  • A route contains targets and a target contains a view. A route can show several targets at once ("target": ["master", "detail"] for a SplitApp with controlAggregation masterPages / detailPages), or a target can name a parent target that is shown first.
  • Root view App.view.xml: <mvc:View … displayBlock="true"><App id="app"/></mvc:View>.
  • Older property names viewPath, viewName, viewLevel are aliases of path, name, level. Legacy: the SAP Web IDE App Descriptor Editor; today edit the JSON or use the Fiori tools Application Modeler.

Pattern

Meaning

Matches

products/{productId}

Mandatory parameter

#/products/P-100

products/:productId:

Optional parameter

#/products and #/products/P-100

products{?query} / products:?query:

Mandatory / optional query parameters

#/products?tab=info

:all*:

Rest of the hash as one string

anything

Navigate, read parameters, go back

// List.controller.js
onItemPress(oEvent) {
const sId = oEvent.getSource().getBindingContext().getProperty("ProductID");
this.getOwnerComponent().getRouter().navTo("detail", {
productId: encodeURIComponent(sId)  // keys may contain special characters
});
}
// Detail.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/core/routing/History"
], (Controller, History) => {
"use strict";
return Controller.extend("my.products.controller.Detail", {
onInit() {
const oRouter = this.getOwnerComponent().getRouter();
oRouter.getRoute("detail").attachPatternMatched(this._onPatternMatched, this);
},

_onPatternMatched(oEvent) {  // runs every time the route matches
const sId = decodeURIComponent(oEvent.getParameter("arguments").productId);
this.getView().bindElement({ path: `/Products('${sId}')` });
},

onNavBack() {               // Page navButtonPress=".onNavBack"
if (History.getInstance().getPreviousHash() !== undefined) {
window.history.go(-1);  // back in the browser history
} else {
const oRouter = this.getOwnerComponent().getRouter();
oRouter.navTo("list", {}, undefined, true);  // true = replace history entry
}
}
});
});
  • navTo(routeName, parameters, componentTargetInfo, replace): replace = true replaces the current history entry instead of adding one. The older three-argument form navTo(name, {}, true) still works.
  • patternMatched vs routeMatched: getRoute("detail").attachPatternMatched fires only for that route; the router's attachRouteMatched fires for every matched route (including parent routes). The handler extracts the parameter, builds the path and binds the element.
  • Flexible column layout: sap.f.routing.Router with targets in beginColumnPages, midColumnPages, endColumnPages for list-detail-detail apps.
  • Cross-app navigation in the launchpad uses intents (#SemanticObject-action, e.g. #Product-display?ProductID=P-100) through the launchpad's Navigation service; inbound intents are declared in sap.app/crossNavigation/inbounds and configured as target mappings (→ see SAP Fiori › 02 · SAP Fiori Launchpad & Security). Inside the launchpad your own routes follow &/: #Product-manage&/products/P-100.

Part 13 – Fragments and dialogs

A fragment is a light-weight, reusable piece of UI (*.fragment.xml) without its own controller: it uses the controller of the view that loads it (or one you pass). Fragments split large views and hold dialogs, popovers and value helps – similar to subscreens in ABAP dialog programming.

Kind

How

Use

Static (embedded)

<core:Fragment fragmentName="my.products.view.ProductForm" type="XML"/> inside a view

Reuse the same form or toolbar in several views

Dynamic (loaded in code)

this.loadFragment({ name }) in the controller, or Fragment.load from sap/ui/core/Fragment

Dialogs and popovers created when first needed

<!-- webapp/view/ProductDialog.fragment.xml -->
<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core">
<Dialog id="productDialog" title="{i18n>newProduct}">
<content>
<Label text="Name" labelFor="dialogName"/>
<Input id="dialogName" value="{/newName}"/>
</content>
<beginButton>
<Button text="Save" type="Emphasized" press=".onSaveDialog"/>
</beginButton>
<endButton>
<Button text="Cancel" press=".onCloseDialog"/>
</endButton>
</Dialog>
</core:FragmentDefinition>
async onOpenDialog() {
this._pDialog ??= this.loadFragment({ name: "my.products.view.ProductDialog" });
const oDialog = await this._pDialog;                    // loaded only once, then reused
oDialog.open();
},

onCloseDialog() {
this.byId("productDialog").close();                     // IDs are prefixed with the view ID
}
  • loadFragment (controller method) loads asynchronously, prefixes IDs with the view ID (so this.byId works) and adds the fragment as a dependent of the view, so it gets the view's models and i18n and is destroyed with the view.
  • With Fragment.load({ id: this.getView().getId(), name, controller: this }) call this.getView().addDependent(oDialog) yourself.
  • Legacy: sap.ui.xmlfragment(...) (synchronous, deprecated).
  • Simple messages need no fragment: MessageToast.show("Saved"), MessageBox.error("…"), and
MessageBox.confirm("Delete this product?", {
onClose: (sAction) => {
if (sAction === MessageBox.Action.OK) {
this._deleteProduct();
}
}
});
  • No standard control, composition (VBox + controls) or fragment fits? Build a custom control → see SAPUI5 › 05 · UI5 Tooling, TypeScript & Custom Controls.

Part 14 – Build, deployment and Git

Develop, build with ui5 build, then deploy either to the ABAP repository and Fiori launchpad or to SAP BTP and SAP Build Work Zone

Build

  • ui5 build (or npm run build) writes the deployable app to dist/: Component-preload.js bundles all modules and views into one file (one request instead of many), files are minified, and -dbg copies keep the readable sources for debugging.
  • ui5 build --clean-dest empties dist/ first; ui5 build self-contained also bundles the needed framework parts for a fully standalone app.

Deploy to an ABAP system (S/4HANA, SAP Gateway)

npx fiori add deploy-config   # asks for system, BSP name, package, transport
npm run deploy                # builds and uploads (fiori deploy --config ui5-deploy.yaml)
# ui5-deploy.yaml (excerpt)
builder:
customTasks:
- name: deploy-to-abap
afterTask: generateCachebusterInfo
configuration:
target:
url: https://<abap-host>:<port>
app:
name: ZPRODUCTS                 # BSP application, customer namespace
description: Products app
package: ZUI_PRODUCTS
transport: <transport request>
  • The app becomes a BSP application in the ABAP repository (served under /sap/bc/ui5_ui5/sap/zproducts/) and is recorded in the transport request, which moves it Dev → QA → Prod.
  • Prerequisites on the server: the OData service /UI5/ABAP_REPOSITORY_SRV must be active and the user needs developer authorisation for the package.
  • Legacy / fallback: report /UI5/UI5_REPOSITORY_LOAD (SE38) uploads a zipped or local dist folder into a BSP application, and can also download or delete one. After manual uploads, run /UI5/APP_INDEX_CALCULATE to refresh the UI5 application index.
  • Then make it reachable for users: catalog, tile and target mapping, space and page, PFCG role (→ see SAP Fiori › 02).

Deploy to SAP BTP (Cloud Foundry)

  • fiori add deploy-config cf adds an mta.yaml (multi-target application) and xs-app.json (approuter routes). npm run build in the MTA folder (mbt build) creates an .mtar archive; npm run deploy (cf deploy <file>.mtar) deploys it.
  • The app is stored in the HTML5 Application Repository and served by the managed approuter; calls to the backend go through a destination (and the Cloud Connector for on-premise systems).
  • Users open it from a SAP Build Work Zone site (the BTP launchpad, successor of the SAP Launchpad service). Details: SAP Fiori › 02 and the SAP Build with Work Zone section.

Launchpad inbound in the manifest

"sap.app": {
"crossNavigation": {
"inbounds": {
"product-manage": {
"semanticObject": "Product",
"action": "manage",
"title": "{{appTitle}}",
"signature": { "parameters": {}, "additionalParameters": "allowed" }
}
}
}
}

Git basics

Git is a distributed version control system: every developer has the full history locally, and save points are called commits. Install it from git-scm.com; BAS and VS Code have Git built in (Source Control view). A remote repository (GitHub, GitLab, Azure DevOps, Bitbucket) is used to share code.

git --version                       # is Git installed?
git init                            # create a local repository in the project folder
# .gitignore: never commit generated or local files
#   node_modules/
#   dist/
git add .                           # stage all changes
git commit -m "Add product list"    # create a save point
git log --oneline                   # history
git reset --hard                    # discard all uncommitted changes (careful: they are lost)
git reset <commit-id>               # move back to an earlier commit, keep the files' changes

# share it: create an empty remote repository first (HTTPS needs a personal access token)
git remote add origin https://github.com/<your-org>/my-products.git
git branch -M main                  # older repositories use master
git push -u origin main

# a second developer
git clone https://github.com/<your-org>/my-products.git
git pull                            # get the latest commits
git add . && git commit -m "Add detail page" && git push
  • Work on a branch per feature (git switch -c feature/detail-page) and merge it through a pull request.

Part 15 – Interview questions

Q1. Which models does UI5 offer, and what is the difference between client-side and server-side models?

JSONModel, XMLModel and ResourceModel are client-side: all data is in the browser, sorting and filtering run locally. The ODataModel (V2, V4) is server-side: it requests data on demand, pages it, and sends filter, sort and changes to the OData service. A model is a client object; the OData service is the backend.

Q2. What are the binding modes, and what is the default per model?

OneTime (model to view once), OneWay (model to view on every change), TwoWay (both directions). Defaults: JSON, XML and OData V4 TwoWay; OData V2 and Resource model OneWay; metadata models OneTime.

Q3. Explain property, aggregation and element binding.

Property binding links one control property to one value. Aggregation binding links an aggregation to a collection and clones a template per entry. Element binding sets a binding context (one record) on a container, e.g. bindElement("/Products('P-100')"), so children bind with relative paths.

Q4. Absolute vs relative binding path?

An absolute path starts with / and is resolved from the model root (/products/0/name). A relative path has no leading slash and is resolved against the binding context set by an aggregation template or element binding (name).

Q5. Expression binding vs formatter vs type?

Expression binding ({= … }) is for short logic inside the view. A formatter is a controller or module function for more complex display logic; it is one-way. A type formats, parses and validates, so it supports two-way binding and input checks (Integer with constraints, Date, Currency).

Q6. How do you implement translation (i18n)?

Put texts in i18n/i18n.properties plus i18n_<lang>.properties, declare a ResourceModel named i18n in the manifest, bind {i18n>key} in views and use getResourceBundle().getText("key", [args]) in code. The runtime falls back from the specific language to the default file.

Q7. How do create, update and delete differ between the OData V2 and V4 models?

V2 has model methods: create, update, remove, callFunction, createEntry + submitChanges. V4 works through bindings: ODataListBinding.create, Context.setProperty or two-way binding (PATCH), Context.delete, operation bindings with invoke(), and submitBatch for own groups.

Q8. What is $batch, and how do you control when changes are sent?

One HTTP POST that carries several OData requests; changes inside a change set are atomic. V2: deferred groups collect changes until submitChanges. V4: $auto sends automatically, $direct without batch, an own update group waits for submitBatch(groupId).

Q9. How do you filter and sort a table?

Get the binding (getBinding("items")) and call filter([new Filter("Name", FilterOperator.Contains, sQuery)]) or sort(new Sorter("Price", true)). With OData this becomes $filter / $orderby on the server; with a JSONModel it runs in the browser.

Q10. How is routing configured, and how do you pass and read a parameter?

In manifest.json › sap.ui5 › routing: config (container control and aggregation), routes (name, pattern, target) and targets (views). Initialise the router in Component.init. Navigate with navTo("detail", { productId }) for the pattern products/{productId}, and read it in getRoute("detail").attachPatternMatched via oEvent.getParameter("arguments").productId.

Q11. What is a fragment, and how do you open a dialog from one?

A reusable UI part without its own controller. Load it with this.loadFragment({ name }) (or Fragment.load + addDependent), cache the promise, then open() the dialog; close it with close(). As a dependent it inherits the view's models and is destroyed with the view.

Q12. How do you deploy a UI5 app to an ABAP system and to SAP BTP?

ABAP: fiori add deploy-config creates ui5-deploy.yaml; npm run deploy builds and uploads the app as a BSP application with a transport (legacy: /UI5/UI5_REPOSITORY_LOAD); then configure the launchpad. BTP: an MTA project is built with mbt build, deployed with cf deploy to the HTML5 Application Repository, and added to SAP Build Work Zone.

Q13. What is a context in the OData V4 model, and how do you show the number of rows?

A context (sap/ui/model/odata/v4/Context) stands for one entity: a list binding creates one row context per entry, a context binding one bound context. Relative bindings resolve against it, and it offers requestObject, setProperty, delete, requestSideEffects. The row count comes from $count: true on the list binding: read it in the table's updateFinished event (total) or bind to $count on the list's header context (getHeaderContext()).

Q14. What are side effects, and how do you handle them in a freestyle app?

Values that the server changes as a consequence of an edit or action (status, totals, items). Fiori elements reads the @Common.SideEffects annotations automatically. In a freestyle app call oContext.requestSideEffects([{ $PropertyPath: "Status" }, { $NavigationPropertyPath: "_Item" }]) after the change, optionally with $$patchWithoutSideEffects on the binding.

Q15. Scenario: after Approve the detail page shows the new status, but the dashboard list still shows the order as waiting. Why, and how do you fix it?

The detail page was bound with bindElement, so it has its own context binding and its own copy of the order; the list binding still holds the old data. Fix: refresh the list binding after the action, or open the detail page with the list's row context (setBindingContext(oRowContext)) so both share one entity; for dependent values use requestSideEffects.

Q16. Scenario: a status column needs a text and a colour, and a quantity input must reject values below 1. Which binding features do you use?

Status text and colour: a formatter in model/formatter.js (or a short expression binding for the colour), with texts from i18n. Quantity: a type such as sap.ui.model.odata.type.Decimal with constraints: { minimum: '1' } in a TwoWay binding, so wrong input is rejected and shown as a value state; with the V4 model the type is derived from $metadata, you only add the extra constraint.

🏠 Start Here · ◀ 03 · UI5 Fundamentals · 05 · Tooling & TypeScript ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP