SAPUI5 Getting Started (SAP HANA)

Aus MattWiki

This page contains basic knowledge on how to start with SAPUI5 development on SAP HANA development stack and also how the SAPUI5 application looks like.

The repository for the examples can be found here:

SAPUI5 App Structure

Dynamic odataView App

We create an app odataView. All of its files will be located inside



Relative Path File Function
./ index.html
  • Load SAPUI5 bootstrap sap-ui-core.js
  • Load error handler
  • Load startup.js for session info, unified shell
  • Specifies async loading of UI
./ Component.js
  • Represents the real start of the application
  • Initialize SAPUI5 component
  • Define metadata and load it from manifest JSON
  • Initialize Router
  • Initialize additional models, that are not defined in the manifest, i.e. the device model
  • Load first view
./ manifest.json

Also called: Application descriptor


  • component configuration
  • libraries and versions
  • device types and supported themes
  • data sources
  • root view
  • dependencies
  • odata models (Binding data source to model)
  • text bundles
  • routes
  • asnyc loading of root view
  • text bundles for language EN
./view/ App.view.xml


  • Shell control and overall flow of the page
  • Fragment for embedded areas
./view/ MRead.fragment.xml


  • Input fields
  • Fragment for header area
  • Fragment for item area
./view/ MTableHead.fragment.xml
  • SmartTable control for display of Purchase Order Header returned by XSODATA service
./view/ MTableItem.fragment.xml
  • SmartTable control for display of Purchase Order Items
./controller/ App.controller.js

Contains methods:

  • onInit: Model binding to table
  • callMultiService: Handles call of odata service to dynamically create columns in table controls
  • callExcel: Calls download of PO data in Excel format

sap.ui.define is used for asynchronous loading

./controller/ Base.controller.js

Base controllers can contain functions and share them to multiple app controllers.

./model/ formatter.js, grouper.js, GroupSortState.js, models.js

Model subdirectory contains reusable functions like formatters

Basic OData App Skeleton from SAP


The file contains all necessary subfolders and should be imported in your project into this module:


This will create a subfolder for the skeleton app named:


Tasks to be done in order to bind an OData service to the SmartTable defined wihtin the App.view in the skeleton app:

File Section Task
manifest.json ""
  • Specify data source
  • Define model
manifest.json "models"
  • Create model
  • Bind model to data source defined above
controller/App.controller.js onInit
  • Set model created above to oTable table control
  • Specify visible fields for SmartTable

Text Bundles

Text bundles are best located in a subfolder of:



Relative Path File Function
./i18n/ Default language message bundle
./i18n/ Language DE message bundle

A language can be selected by changing browser language or adding the URL parameter sap-ui-langauge=DE_de to tue URL of your app.

Add code:

/* Language Resource Loader */"");
var sLocale = sap.ui.getCore().getConfiguration().getLanguage();
var oBundle ={url: "./i18n/", locale: sLocale});

// create the button instance
var myButton = new sap.m.Button("btn");

// set properties, e.g. the text (there is also a shorter way of setting several properties)
// myButton.setText("Hello World!");


Local SAPUI5 Micro Service

SAPUI5 libraries can be used from the public SAPUI5 libraries.

Since SAP HANA 2.0 SPS 03 XS Advanced is capable of providing a micro service itself for local consumption.

A local micro service can be created either in XS Advanced Cockpit at

  • HANAExpress -> development space -> Services -> Service Marketplace -> sapui5_sb

or via command line with:

xs create-service sapui5_sb sapui5-1.52 openSAPHANA_00-ui5

The service has to be added in:

Path File Function
/ mta.yaml Create new resource and add it to modules
/web/ xs-app.json Use replace capability of app router to insert UI5 service URL dynamically
/web/ index.html Fetch bootstrap from resource by utilizing variable

UI Controls and Libraries

Control Library Function Properties
Image sap.m Show image src, width, tooltip
Page sap.m Create a page with footer title
Link sap.m Show link emphasized, text, target, href
SearchField sap.m Input field for search placeholder
Select sap.m List of items for selection
Button sap.m Button for triggering actions text
Label sap.m Text label for other controls labelFor
SimpleForm sap.ui.layout.form Create nicely arranged simple forms layout, columnsM, columnsL, columnsXL
MessageToast sap.m Display a message text
PlanningCalendar sap.ui.unified Display rows with appointments startDate, rows, Aggregation PlanningCalendarRow

Aggregations of controls are used to nest other controls to be displayed inside them.

Association to the Select control is the currently selected item.



Event Belongs to Description
press Button, Image Fires when pressing on a button
onInit Controller After the controller is initialized
onBeforeRendering Controller Before rendering, i.e. for checking device parameters
onAfterRendering Controller After rendering, i.e. for checking contents of DOM
onExit Controller Before destroying the App

Example Listing:

URL Parameters

Parameters are specified by adding parameter-value-pairs to the URL. Example:

Parameter Description Example Values
sap-ui-language Set language in as <Language>_<Region>

German in Germany: de_DE
Chinese in China: zh_CN
Arabic in Saudi Arabia: ar_SA

sap-ui-theme Set theme

High Contrast White: sap_belize_hcw
High Contrast Black: sap_belize_hcb

How to Implement

Dynamic Table Field List Based on OData Service Metadata

This example is based on the odataView App from above.

Visible table columns can eiter be hard coded in controller/App.controller.js in OnInit with oTable.setInitiallyVisibleFields:

onInit: function() {
  this.getView().addStyleClass("sapUiSizeCompact"); // make everything inside this View appear in Compact mode
  var oConfig = this.getOwnerComponent().getModel("config");
  var userName = oConfig.getProperty("/UserName");
  var bpModel = this.getOwnerComponent().getModel("bpModel");
  var oTable = this.getView().byId("bpTable");

Or they can be made visible dynamically by looking them up in the meta data of the service at dataServices.schema[0].entityType[0].property:

function fnLoadMetadata() {
  try {
    var oMeta = bpModel.getServiceMetadata();
    var headerFields = "";
    for (var i = 0; i < oMeta.dataServices.schema[0].entityType[0].property.length; i++) {
      var property = oMeta.dataServices.schema[0].entityType[0].property[i];
      headerFields += + ",";
  } catch (e) {
bpModel.attachMetadataLoaded(bpModel, function() {

Hint: If your service metadata has multiple tables then you probably have to loop through the different entityType or even schema.

OData CRUD with Input List and SmartTable

Based on the odataView app from above the following has to be changed:

(The results are implemented in the odataCRUD app.

Model in manifest.json has to be changed:

    "userModel": {
      "dataSource": "userService",
      "type": "sap.ui.model.odata.v2.ODataModel",
      "preload": true,
      "settings": { 
        "useBatch": false,
        "json": true,
        "defaultBindingMode": "TwoWay",
        "defaultUpdateMethod": "PUT"

Notably is the defaultBindingMode TwoWay. This means that changes, which happen in the odata Service, are automatically reflected in bound UI controls and vice versa. When changes happen in the UI controls, they are automatically reflected in the model and sent to the server.

New event handlers in app controller for the buttons:

  • callUserService -> for create operation -> calls the oModel.create function
  • callUserUpdate -> for update operation -> calls the oModel.submitChanges function

Batch Insert with XMLfragment based Dynamically Created Dialog

Batching enables serverside parallelization if the queries are sent to the server as a batch operation.

Example Application: odataCRUD --> See event handler for onBatchDialogPress and the respective buttons and fragments.

Event handler getItem creates dynamically dialog elements in the UI for add and delete icon as well as input fields for first name, last name and email.

Event handler onSubmitBatch handles the batch processing. For that first a JSON object with all users will be created.

Class sap.ui.model.odata.v2.ODataModel parameter oParams.usetBatch = true overwrites the settings from the manifest.json. Also a new model will be created to use the batch option.

This enables SAPUI5 to communicate with a odata service with different settings.

When batch is used a mParams.groupId will be available. It should be set.

batchModel.create sends the records actually one by one to the server. But as the model was created with the useBatch option all the records will be sent to the server as a batch after all commands are done on the client side.



OData V2 Deep Insert with Content-ID and Links

Example Application:


Deep inserts allow to insert data into tables with parent-child relationship and ensure that all the inserted records of both tables are correctly related to each other.

In the example below this actually happens by inserting records into both tables seperately using content ID and then updating the second table to have the same primary keys as the first table.

Definition of OData Service businessPartnersAddresses.xsodata:

service  { 
      as "BusinessPartners"
      navigates ("ToAddresses" as "AddRef")
      create events(before 
      as "Addresses"
      without ("POINT")
      create events(before 
  association "ToAddresses" principal "BusinessPartners"("ADDRESSES.ADDRESSID")
      multiplicity "1" 
      dependent "Addresses"("ADDRESSID") multiplicity "1"
        over "MD.Addresses"
        principal("ADDRESSID") dependent ("ADDRESSID")
        update using 

The service has three user exits:

  • bp_create_before_exit: Generates partnerID from sequence and fills some fields before create
  • address_create_before_exit: Generates addressID from sequence and fills some fields before create
  • association_create_exit: Fetches both previously created records and updates the business partner record with the addressID from the address record.

Listing of businessPartnersAddresses.xsjslib containing the three exits:

In order to use batch with content-ids the SAPUI5 odata object cannot be used. Instead the request will be build by the controller during run time. Calling of the services utilizes jQuery.ajax and must also handle CSRF tokens.


<script type="text/javascript" src="/common/csrf.js" ></script> 

Listing of app controller which builds the complete OData batch request (unlike earlier SAPUI5 exercises where the framework did all the work):

Notice the Content-ID option. It works as a place holder ($1 and $2) to represent the keys which will not be generated until the server side has processed the work. The $1 and $2 placeholders can be used in the association URL and work as placeholders for actual values. XSODATA framework on the server side will replace this values during processing.

Fiori Annotations with OData V4 and CDS

Example Application:


OData V4 and CDS enable a large range of metadata definitions for Fiori applications to allow nearly everything about the UI like:

  • Value helps
  • Sort Options
  • Output columns

The metadata can be placed at different levels of the CDS like:

  1. Lowest level: At the entity definitions
  2. At the service level or UI page
Types of annotations
Type Description
title Text description used as field label and column headers. Can be used at reusable type level or within entity or view definition
FieldControl Set state of input field to i.e. Read Only or Mandatory
Measures i.e. amount of fields gets measure from currency column
ValueList i.e. currency column which points to foreign entity CURRENCY. This allows to pupulate drop down list boxes or fill value helps within the UI from this definition.

Code excerpts for entity level annotations from /db/PurchaseOrder.cds:

type HistoryT { 
	CREATEDBY : BusinessKey @(title: '{i18n>CreatedBy}', Common.FieldControl: #ReadOnly);
	CREATEDAT : SDate  @(title: '{i18n>CreatedAt}',  Common.FieldControl: #ReadOnly);
	CHANGEDBY : BusinessKey  @(title: '{i18n>ChangedBy}',  Common.FieldControl: #ReadOnly);
	CHANGEDAT : SDate  @(title: '{i18n>ChangedAt}',  Common.FieldControl: #ReadOnly);

entity Headers {
	key PURCHASEORDERID : Integer @(
			title: '{i18n>po_id}', 
			Common.FieldControl: #Mandatory, 
			Common.Label: '{i18n>po_id}'
		ITEMS           : association to many Items on ITEMS.POHeader = $self @(
			title: '{i18n>po_items}', 
			Common: { Text: {$value: ITEMS.PRODUCT, "@UI.TextArrangement": #TextOnly }}
		HISTORY         : HistoryT;
		NOTEID          : BusinessKey null @title: '{i18n>notes}';
		PARTNER         : BusinessKey @title: '{i18n>partner_id}';
		CURRENCY        : CurrencyT @(
			Common: {
				Text: {$value: CURRENCY.CURRENCY, "@UI.TextArrangement": #TextOnly},
				ValueList: {entity: 'CURRENCY', type: #fixed},
		GROSSAMOUNT     : AmountT @( title: '{i18n>grossAmount}', Measures.ISOCurrency: currency);
		NETAMOUNT       : AmountT @( title: '{i18n>netAmount}', Measures.ISOCurrency: currency);
		TAXAMOUNT       : AmountT @( title: '{i18n>taxAmount}', Measures.ISOCurrency: currency);
		LIFECYCLESTATUS : StatusT @(title: '{i18n>lifecycle}', Common.FieldControl: #ReadOnly);
		APPROVALSTATUS  : StatusT @(title: '{i18n>approval}', Common.FieldControl: #ReadOnly);
		CONFIRMSTATUS   : StatusT @(title: '{i18n>confirmation}', Common.FieldControl: #ReadOnly);
		ORDERINGSTATUS  : StatusT @(title: '{i18n>ordering}', Common.FieldControl: #ReadOnly);
		INVOICINGSTATUS : StatusT @(title: '{i18n>invoicing}', Common.FieldControl: #ReadOnly);

Full listing:

Code excerpt from /srv/fiori-annotations-my-service.cds for service level UI annotations:

using CatalogService as cats from './my-service'; 

annotate cats.POItemsView with @( // header-level annotations
// ---------------------------------------------------------------------------
// List Report
// ---------------------------------------------------------------------------
  // Product List
  UI: {
    LineItem: [ 
      {$Type: 'UI.DataField', Value: PO_ITEM_ID, "@UI.Importance":#High},
      {$Type: 'UI.DataField', Value: PRODUCT_ID, "@UI.Importance": #High},
      {$Type: 'UI.DataField', Value: PARTNER_ID, "@UI.Importance": #High},
      {$Type: 'UI.DataField', Value: PARTNERS.COMPANYNAME, "@UI.Importance": #Medium},			
      {$Type: 'UI.DataField', Value: AMOUNT, "@UI.Importance": #High},
      {$Type: 'UI.DataField', Value: CURRENCY_CODE, "@UI.Importance": #Medium},			
    PresentationVariant: {
      SortOrder: [ {$Type: 'Common.SortOrderType', Property: PO_ITEM_ID, Descending: false}, 
                   {$Type:  'Common.SortOrderType', Property: PRODUCT_ID, Descending: false} ]

Full listing:

Fiori allows XML templating. It will be implemented in the Main.view.xml by making use of template:with and template:repeat elements. This allow iterating over OData Annotations in order to control the UI output dynamically.

Example code excerpts from /web/resource/poListV4/view/Main.view.xml:

<template:with path="entityType>" var="lineItem">
  <!-- Note: this limits the data shown to 5 rows! -->
  <Table headerText="Purchase Orders" items="{path:'', parameters : {$expand : 'PARTNERS'}}" 
      growingThreshold="10"  growing="true">
      <template:repeat list="{lineItem>}" var="field">
        <template:if test="{= ${field>$EnumMember} !== 
                             '' }">
                design="{:= ${field>$EnumMember} === 
                         '' ? 'Bold' : 'Standard'}"
      <template:repeat list="{lineItem>}" var="field">
        <Text text="{field>Value/@@value}"/>

Full listing:

Consume OData V4 Service with Create Option

Example Application:


In order to use OData V4 appropriate settings for data source and model are necessary in manifest.json, i.e.:

"": {
	"dataSources": {
		"userService": {
			"uri": "/odata/v4/opensap.hana.CatalogService/",
			"type": "OData",
			"settings": {
				"odataVersion": "4.0"

"sap.ui5": {
	"models": {
		"": {
			"type": "sap.ui.model.json.JSONModel",
			"settings": {
				"defaultBindingMode": "TwoWay"
		"userModel": {
			"dataSource": "userService",
			"type": "sap.ui.model.odata.v4.ODataModel",
			"preload": false,
			"settings": {
				"synchronizationMode": "None",
				"operationMode": "Server",
				"autoExpandSelect": true

Entire listing:

As the SmartTable control does not yet allow OData V4 model (in early 2019) the m.table control will be used in App.view.xml:

<Table tableId="userTable" id="userTable" growingThreshold="10" growing="true"
		path: 'userModel&gt;/User', 
		sorter: [{ path: 'USERID', descending: false}], 
		events : {dataReceived : '.onDataEvents' } }">
			<header><Label text="User ID"/></header>
			<header><Label text="First Name"/></header>
			<header><Label text="Last Name"/></header>
			<header><Label text="Email"/></header>
				<Input value="{path: 'userModel&gt;USERID'}" name="PERS_NO" editable="false"/>
				<Input value="{path: 'userModel&gt;FIRSTNAME'}" name="FIRSTNAME"/>
				<Input value="{path: 'userModel&gt;LASTNAME'}" name="LASTNAME"/>
				<Input value="{path: 'userModel&gt;EMAIL'}" name="E_MAIL"/>

Entire listing:

In order to use OData V4 the App.controller.js has to account for that. This happens by creating a binding the new data to the OData V4 model. Besides that no special model functions have to be called:

callUserService: function () { 

	try { 
		var oModel = this.getOwnerComponent().getModel("userModel");
		var result = this.getView().getModel().getData();
		var oList = this.byId("userTable"),
			oBinding = oList.getBinding("items"),
			// Create a new entry through the table's list binding
			oContext = oBinding.create({
				"USERID": 0,
				"FIRSTNAME": result.FirstName,
				"LASTNAME": result.LastName,
				"EMAIL": result.Email

		// Note: this promise fails only if the transient entity is deleted
		oContext.created().then(function () {
			sap.m.MessageBox.alert("User created: " + oContext.getProperty("USERID"));
		}, function (oError) {
	} catch (err) {

callUserUpdate: function () {
	var oModel = this.getOwnerComponent().getModel("userModel");

	var mParams = {};
	mParams.error = function () {"Update failed");
	mParams.success = function () {"Update successful");

} ,

Entire listing:

Asynchronous Loading of Controls in Code

Loading of controls asynchronously is done by the sap.ui.require function.

This improves initial loading time of the application and reduces its size.


onPress: function (oEvent) {
	sap.ui.require(["sap/m/MessageToast"], function (oMessage) {"Searching...");
	} );

Logging Events to Console

Add data-sap-ui-logLevel to bootstrap:

		<script id="sap-ui-bootstrap"
			data-sap-ui-resourceroots='{"opensap.movies": "./"}'

Add logging at controller level by adding sap/base/Log module:

], function (Controller, Log) {
	"use strict";

	return Controller.extend("opensap.movies.controller.App", {
		onInit: function () {"Controller has been initialized.");
		onExit: function () {"Controller will shortly be destroyed.");
		onBeforeRendering: function () {"The view will shortly be rendered.");
		onAfterRendering: function () {"The view has been rendered.");
		onPress: function (sValue) {
			sap.ui.require(["sap/m/MessageToast"], function (oMessage) {"Searching..." + sValue);
			} );

Route to View on Event

Specify routes in manifest.json, here for the Detail view:

		"routing": {
			"config": {
				"routerClass": "sap.m.routing.Router",
				"viewType": "XML",
				"async": true,
				"viewPath": "opensap.movies.view",
				"controlAggregation": "pages",
				"controlId": "app",
				"clearControlAggregation": false
			"routes": [{
				"name": "Home",
				"pattern": "",
				"target": ["Home"]
			}, {
				"name": "Detail",
				"pattern": "movies/{movieId}/appointments/{appointmentId}",
				"titleTarget": "",
				"greedy": false,
				"target": ["Detail"]

Specify event and eventhandler in view definition, here event appointmentSelect:

<PlanningCalendar id="calendar" startDate="{path: 'movies>/initDate', formatter: '.formatter.formatDate'}" rows="{movies>/movies}"
    appointmentsVisualization="Filled" appointmentSelect=".onAppointmentSelect(${$parameters>/appointment})">
        <PlanningCalendarRow title="{movies>name}" text="{movies>genre}" appointments="{path: 'movies>appointments', templateShareable: 'true'}">

Full listing:

Add UIComponent to controller to access the app router:

], function (Controller, Log, formatter, Filter, FilterOperator, UIComponent) {
	"use strict";

	return Controller.extend("opensap.movies.controller.App", {

		onAppointmentSelect: function (oAppointment) {
			var oContext = oAppointment.getBindingContext("movies"),
				sPath = oContext.getPath();

			var aParameters = sPath.split("/");
			UIComponent.getRouterFor(this).navTo("Detail", {
				movieId: aParameters[2],
				appointmentId: aParameters[4]

Full listing:

Now the Detail.controller.js of the Detail view has to be enabled to respond to the new route pattern:

onInit: function () {
    UIComponent.getRouterFor(this).getRoute("Detail").attachPatternMatched(this._onDetailMatched, this);

_onDetailMatched: function (oEvent) {
    var oView = this.getView(),
        sMovieIndex = oEvent.getParameter("arguments")["movieId"],
        sAppointmentIndex = oEvent.getParameter("arguments")["appointmentId"];

        path: "/movies/" + sMovieIndex + "/appointments/" + sAppointmentIndex,
        model: "movies",
        events: {
            change: this._onBindingChange.bind(this)

_onBindingChange: function () {
    var oView = this.getView(),
        oElementBinding = oView.getElementBinding("movies"),
        sPath = oElementBinding.getPath();

    // if the path to the data does not exist we navigate to the not found page
    if (!oView.getModel("movies").getObject(sPath)) {
        //See Challenge at the end: 	UIComponent.getRouterFor(this).getTargets().display("NotFound");

onDetailsChanged binds the view to the model using the path of the appointment the user clicked on. This will display automatically the chosen appointment details on the Detail view.

onBindingChange transfers the binding contect to the Detail view.

Implement NotFound Page



Implement Feature-Rich Controls

Feature-Rich controls implemented in exercise:

Control Library Documentation
Sticky table header
Floating footer
Object Page Layout sap.uxap.ObjectPageLayout
Info Label sap.tnt.InfoLabel
Object Number sap.m.ObjectNumber
Status Indicator sap.suite.ui.commons.statusindicator.StatusIndicator

Exercise from openSAP course UI52: Week 3 Unit 4: Spicing up Your Scenario with Feature-Rich Controls


Reusing Patterns

Reuse Patterns:

  • Control
  • Fragment
  • View
  • Component
  • Library

Control Pattern:

  • Encapsulates Rendering and Behavior
  • Standardized Control Interface
  • Smallest Reusable UI Asset
  • Custom or Composite Control
  • Bundled in Control Libraries

XML Composite Control

  • Declarative UI definition in XML
  • Special $this model for binding properties
  • Control metadata description

Create XML composite control:

  • Create new folder "control" inside "webapp"
  • Create .js file for controller and metadata
  • Create .xml file for layout

Exercise from openSAP course UI52: Week 3 Unit 5: Scaling Up with UI Reuse patterns


Add CRUD Form to Flexible Column Layout

Exercise from openSAP course UI52: Week 4 Unit 1: Creating Items and Validating User Input

Form will be called by add-Button ("+") in Detail View. Implementation:

	<Title id="lineItemsTitle" text="{detailView&gt;/lineItemListTitle}" titleStyle="H3" level="H3"/>
	<ToolbarSpacer />
	<Button	icon="sap-icon://add" tooltip="{i18n>createButtonTooltip}" press=".onCreate"/>							

Create a new XML View and controller. Implementations:

Add create target and create route to the manifest.json:

"routes": [
		"pattern": "SalesOrderSet/{objectId}/create",
		"name": "create",
		"target": [
"targets": {
	"create": {
		"viewType": "XML",
		"viewName": "Create",
		"controlAggregation": "endColumnPages",
		"viewId": "create"

Full implementation:

Information about Routing and Navigation:

Extend existing Detail.controller.js:

Add Input Validation Client and Server Side

Add value property to the input fields:

  • ProductID
  • Note
  • Quantity

Set path and type of each value property to the corresponding property from the oData model. This way the app uses backend validation and ensures that the oData properties will receive correct entries regarding their type.

Use contraints to ensure input of correct values at the client side. In the following implementation this happens with regular expressions. Also set minimum value for quantity.


Define defaultBindingMode to TwoWay in order to be able to handle the transport of data both from the model to the controls and back from the controls to the model.

See also exercise from openSAP course UI52: Week 4 Unit 1: Creating Items and Validating User Input

Add MessageManager for Displaying Messages

In onInit a global message manager will be registered and a special message model will be established to redtieve and display error messages.


See also exercise from openSAP course UI52: Week 4 Unit 1: Creating Items and Validating User Input


Message Popover for Logging Errors

In general it is a good idea in terms of user experience to store all errors in one place. This helps the user to find and track errors. sap.m.MessagePopover is a good choice for this.

Add a button to the overflow toolbar for showing the message popover.

Initialize the MessageManager in onInit. Register the root element ObjectPageLayout of the view as an object for which errors will be tracked and displayed in the popover.

Ensure to remove all server-side erroors by removing all messages from the MessageManager _onCreateMatched.

Als remove old messages when the product name is changed and is about to be validated. This is implemented at the change event of the correspodings input field in the view - here implemented in the onNameChange function.

In the handler of the popover button onOpenMessages open the MessagePopover.


See also exercise from openSAP course UI52: Week 4 Unit 1: Creating Items and Validating User Input

Creating Entries with OData

First, when the route is matched and the view is created an entry is created locally in _onCreateMatched by utilizing the createEntry Method, specifying a collection, in our case SalesOrderLineItemSet. Also initial values to the mandatory fields from the model are added. As a result of the createEntry function you receife a contect that points to the new object. It must be set to the view.

_onCreateMatched: function (oEvent) {
	var sObjectId = oEvent.getParameter("arguments").objectId;

	// create a binding context for a new order item
	this.oContext = this.getModel().createEntry("/SalesOrderLineItemSet", {
		properties: {
			SalesOrderID: sObjectId,
			ProductID: "",
			Note: "",
			Quantity: "1",
			DeliveryDate: new Date()
		success: this._onCreateSuccess.bind(this)

_onCreateSuccess: function (oContext) {
	// show success message
	var sMessage = this.getResourceBundle().getText("newItemCreated", [oContext.ProductID]);, {
		closeOnBrowserNavigation : false

	// navigate to the new item in display mode
	this.getRouter().navTo("Info", {
		objectId : oContext.SalesOrderID,
		itemPosition : oContext.ItemPosition
	}, true);
onCreate: function () {
	// send new item to server for processing

In the onCreate handler the submit function of the OData model will be called. It creates a HTTP request against the server. The server completes the creatte action and sends a HTTP response back.

Register to the success event afterwards via the _onCreateSuccess callback function.

Afther the _onCreateSuccess function is triggered, the view will be unbound from the created object. A MessageToast shows a success message to the user. Lastly the As a last step, navigate to the created item.



See also exercise from openSAP course UI52: Week 4 Unit 1: Creating Items and Validating User Input

Enable Drag and Drop in Lists

The drag and drop feature will be enabled with the dragDropConfig aggregation and the DragInfo or DropInfo element inside of it, depending of if you want it to be a source or a target for drag and drop.

Add dragDropConfig aggregation and define the drag source by adding DragInfo inside of it with the property sourceAggregation:

	<dnd:DragInfo sourceAggregation="items"/>


Create a new custom button and extend its metadata:


Add XML code to enable drop feature to the custom button:

		<dnd:DropInfo drop=".onDelete" />

Implementation of the drop/press handler in Detail.controller.js:

onDelete : function (oEvent) {
	// delete the dragged item
	var oItemToDelete = oEvent.getParameter("draggedControl");

	// delete the selected item from the list - if nothing selected, remove the first item
	if (!oItemToDelete) {
		var oList = this.byId("lineItemsList");
		oItemToDelete = oList.getSelectedItem() || oList.getItems()[0];

	// delete the item after user confirmation
	var sPath = oItemToDelete.getBindingContextPath(),
		 sTitle = oItemToDelete.getBindingContext().getProperty("ProductID");
	this._confirmDelete(sPath, sTitle);

In order to provide a better user experience the user should be asked for confirmation before an item is deleted. this will be done with the _confirmDelete function.


See also exercise from openSAP course UI52: Week 4 Unit 2 - Exercise: Improving User Experience with Drag and Drop


Debugging Tools

Open diagnostics tool: Ctrl + Shift + Alt + S

Use debug sources: Ctrl + Shift + Alt + P

After that activate the "Use Debug Sources" checkbox. When reloading in the Chrome DevTools files will be loaded with the "-dbg" suffix. These are source code files that include comments and uncompressed code of the OpenUI5 artifacts.

This can be also achieved by adding the parameter to the url: sap-ui-debug=true