opensap evolved web apps with sapui5 · 2019-06-03 · with the validated data, an odata entry will...

25
openSAP Evolved Web Apps with SAPUI5 Week 4 Unit 1: Creating Items and Validating User Input Exercises PUBLIC

Upload: others

Post on 29-May-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

openSAP Evolved Web Apps with SAPUI5 Week 4 Unit 1: Creating Items and Validating User Input Exercises

PUBLIC

Page 2: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

2

TABLE OF CONTENTS

WEEK INTRODUCTION .............................................................................................................................. 3

CREATING ITEMS AND VALIDATING USER INPUT.................................................................................. 4 Adding a button to open the view for creation ......................................................................................... 4 Creating a new view ................................................................................................................................... 6 Adding some fields to the view ................................................................................................................11 Validation in the view................................................................................................................................14 Using message popovers for logging errors ...........................................................................................19 Creating an item in the OData ..................................................................................................................22

RELATED MATERIAL................................................................................................................................24

Page 3: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

3

WEEK INTRODUCTION

Summary In this week you will learn about

• Handling user input

• Tips and tricks for validation of user entry

• Creation of an OData entry Preview

Imagine that someone has provided wrong data in your app for a very important item in one of the orders. To avoid problems for your business because of issues like that, you’ll learn how to handle the situation: This includes the input validation concept and a way of creating a new OData entry. You will introduce a new view into the last column of the FlexibleColumnLayout, which can be loaded

via a button in the detail view. Then, you will add some fields to the detail view, which enable the users to enter values for a new order item. In addition, you will learn about some handy features of the framework with which you can validate user input. With the validated data, an OData entry will be created.

Figure 1 – The final look of the view for creating an item in the order

Page 4: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

4

CREATING ITEMS AND VALIDATING USER INPUT

Adding a button to open the view for creation

First of all, the app would have to provide the user with a way to start the item creation process. An appropriate place for that is the second column of the FlexibleColumnLayout, which shows all the

existing order items.

Let’s add a Button at the top of the Table shown in the Detail.view.xml. When the user presses it, it

will open a new view with input fields for the new item.

webapp/view/Detail.view.xml

<headerToolbar>

<Toolbar>

<Title id="lineItemsTitle"

text="{detailView>;/lineItemListTitle}"

titleStyle="H3"/>

<ToolbarSpacer />

<Button

icon="sap-icon://add"

tooltip="{i18n>createButtonTooltip}"

press=".onCreate"/>

</Toolbar>

</headerToolbar>

<columns>

<Column>

<Text text="{i18n>detailLineItemTableIDColumn}"/>

</Column>

Simply add a ToolbarSpacer and a Button icon with a tooltip. The handler function of the defined press

event will be implemented later in this unit.

webapp/i18n/i18n.properties

#XTIT: Title text for the delivery status

StatusDesc=Delivery status

#XTOL: Tooltip for the create button

createButtonTooltip=Create a new order item for this order

#~~~ Info View ~~~~~~~~~~~~~~~~~~~~~~~~~~

#XFLD: Text for item description of each item in the order

infoItemDescription=Item description

Also add the corresponding tooltip text for internationalization.

Page 5: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

5

Figure 2 – The button for opening the creation view is placed at the toolbar content in the table

Page 6: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

6

Creating a new view

Let’s create a new view in which the user will fill the fields for a new item. The new file Create.view.xml

should be located in the view sub folder of the webapp folder.

webapp/view/Create.view.xml (NEW)

<mvc:View

controllerName="opensap.orders.controller.Create"

xmlns="sap.m"

xmlns:mvc="sap.ui.core.mvc"

xmlns:uxap="sap.uxap">

<uxap:ObjectPageLayout

id="objectPageLayout"

alwaysShowContentHeader="true"

isChildPage="true"

showFooter="true">

<uxap:headerTitle>

<uxap:ObjectPageDynamicHeaderTitle>

<uxap:heading>

<Title text="{i18n>createItemTitle}"/>

</uxap:heading>

</uxap:ObjectPageDynamicHeaderTitle>

</uxap:headerTitle>

</uxap:ObjectPageLayout>

</mvc:View>

Include an ObjectPageLayout that displays only a title at the top. Use its headerTitle aggregation with

a Title in it.

webapp/i18n/i18n.properties

#XTOL: Tooltip for the create button

createButtonTooltip=Create a new order item for this order

#~~~ Create new item view ~~~~~~~~~~~~~

#XTIT: Heading title of the create item page

createItemTitle=Create New Order Item

#~~~ Info View ~~~~~~~~~~~~~~~~~~~~~~~~~~

#XFLD: Text for item description of each item in the order

infoItemDescription=Item description

Fill the internationalization file with the needed title text.

Create a new controller called Create.controller.js in the controller sub folder of the webapp

folder.

Page 7: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

7

webapp/controller/Create.controller.js (NEW)

sap.ui.define([

"./BaseController"

], function (BaseController) {

"use strict";

return BaseController.extend("opensap.orders.controller.Create", {

onInit: function () {

this.getRouter().getRoute("create").attachPatternMatched(this._onCreateMatched,

this);

},

_onCreateMatched: function (oEvent) {

this.getModel("appView").setProperty("/layout", "ThreeColumnsMidExpanded");

}

});

});

Create a controller for the view. When the view is opened, and the route gets hit, call the _onCreateMatched function asynchronously. In it, adjust the layout property of the flexible column

layout.

webapp/manifest.json

{

"_version": "1.12.0",

"sap.app": {

},

"sap.ui5": {

"resourceRoots": {

"opensap.reuse.control": "./control"

},

"routing": {

"config": {

"routerClass": "sap.f.routing.Router",

"viewType": "XML",

"viewPath": "opensap.orders.view",

"controlId": "layout",

"controlAggregation": "beginColumnPages",

"bypassed": {

"target": "notFound"

},

"async": true

},

"routes": [

{

"pattern": "",

"name": "master",

Page 8: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

8

"target": "master"

},

{

"pattern": "SalesOrderSet/{objectId}",

"name": "object",

"target": [

"master",

"object"

]

},

{

"pattern": "SalesOrderSet/{objectId}/create",

"name": "create",

"target": [

"master",

"object",

"create"

]

},

{

"pattern": "SalesOrderSet/{objectId}/Item/{itemPosition}",

"name": "info",

"target": [

"master",

"object",

"info"

]

}

],

"targets": {

"master": {

"viewName": "Master",

"viewLevel": 1,

"viewId": "master"

},

"object": {

"viewName": "Detail",

"viewId": "detail",

"viewLevel": 1,

"controlAggregation": "midColumnPages"

},

"detailObjectNotFound": {

"viewName": "DetailObjectNotFound",

"viewId": "detailObjectNotFound",

"controlAggregation": "midColumnPages"

},

"notFound": {

"viewName": "NotFound",

"viewId": "notFound"

},

"create": {

"viewType": "XML",

"viewName": "Create",

"controlAggregation": "endColumnPages",

"viewId": "create"

},

"info": {

"viewType": "XML",

"viewName": "Info",

"controlAggregation": "endColumnPages",

"viewId": "info"

}

}

}

Page 9: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

9

}

}

Create a new route and target in the manifest.json file. This tells the app that there is a new view that

can be shown.

webapp/controller/Detail.controller.js

onInit : function () {

// Model used to manipulate control states. The chosen values make sure that

// the detail page shows a busy indication immediately so there is no break

// between the busy indication for loading the view's metadata.

var oViewModel = new JSONModel({

busy : false,

delay : 0,

lineItemListTitle :

this.getResourceBundle().getText("detailLineItemTableHeading")

});

this.getRouter().getRoute("object").attachPatternMatched(this._onObjectMatched,

this);

this.getRouter().getRoute("info").attachPatternMatched(this._onObjectMatched, this);

this.getRouter().getRoute("create").attachPatternMatched(this._onObjectMatched,

this);

this.setModel(oViewModel, "detailView");

this.getOwnerComponent().getModel().metadataLoaded().then(this._onMetadataLoaded.bin

d(this));

},

onCreate: function (oEvent) {

var bReplace = !Device.system.phone;

this.getRouter().navTo("create", {

objectId : oEvent.getSource().getBindingContext().getProperty("SalesOrderID")

}, bReplace);

},

/* =========================================================== */

/* event handlers */

/* =========================================================== */

/**

* Event handler when the share by E-Mail button has been clicked

* @public

*/

onSendEmailPress: function (oEvent) {

},

Ensure that the new view is bound to the model by executing the_onObjectMatched method in the

controller of the detail view, when the route gets hit. In the handler function of the button, navigate with the router to the creation view.

Page 10: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

10

Figure 3 – Now the new view shows only a heading

Page 11: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

11

Adding some fields to the view

It’s time to add some content to the new view. For each editable field from the backend, there should be an input in the frontend that enables the user to enter a value for it.

webapp/view/Create.view.xml

<mvc:View

controllerName="opensap.orders.controller.Create"

xmlns="sap.m"

xmlns:mvc="sap.ui.core.mvc"

xmlns:uxap="sap.uxap"

xmlns:form="sap.ui.layout.form">

<uxap:ObjectPageLayout

id="objectPageLayout"

alwaysShowContentHeader="true"

isChildPage="true"

showFooter="true">

<uxap:headerTitle>

</uxap:headerTitle>

<uxap:sections>

<uxap:ObjectPageSection id="details"

title="{i18n>createItemDetailsTitle}">

<uxap:subSections>

<uxap:ObjectPageSubSection>

<uxap:blocks>

<form:SimpleForm editable="true">

<Label

text="{i18n>createItemProductID}"/>

<Input

id="productName"

required="true"/>

<Label

text="{i18n>createItemDescription}"/>

<TextArea/>

<Label

text="{i18n>createItemQuantityDescription}"/>

<Input

id="productQuantity"

required="true">

</Input>

</form:SimpleForm>

</uxap:blocks>

</uxap:ObjectPageSubSection>

</uxap:subSections>

</uxap:ObjectPageSection>

<uxap:ObjectPageSection title="{i18n>createItemDeliveryTitle}">

<uxap:subSections>

<uxap:ObjectPageSubSection>

<uxap:blocks>

<form:SimpleForm editable="true">

<Label

text="{i18n>createItemDeliveryDate}"/>

<DatePicker

id="deliveryDate"

Page 12: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

12

required="true"

displayFormat="long"/>

</form:SimpleForm>

</uxap:blocks>

</uxap:ObjectPageSubSection>

</uxap:subSections>

</uxap:ObjectPageSection>

</uxap:sections>

</uxap:ObjectPageLayout>

</mvc:View>

Add two sections – one for the product details, and one for the shipping date. Both should contain a

SimpleForm that wraps a Label as well as an appropriate Input field:

• sap.m.Input for the product name

• sap.m.TextArea for the description

• sap.m.Input for entering a quantity

• sap.m.DatePicker for selecting a delivery date

Mark the mandatory fields by setting the required property of each to true.

webapp/i18n/i18n.properties

#~~~ Create new item view ~~~~~~~~~~~~~

#XTIT: Heading title of the create item page

createItemTitle=Create New Order Item

#XFLD: Text for the product name in the create item page

createItemProductID=Product ID

#XFLD: Text for item description in the create item page

createItemDescription=Description

#XFLD: Text for the quantity of each item in the create item page

createItemQuantityDescription=Quantity

#XGRP: Title of the delivery group of information in the create item dialog

createItemDeliveryTitle=Delivery

#XFLD: Text for the delivery date in the create item page

createItemDeliveryDate=Delivery date

#XGRP: Title of the details group of information in the create item page

createItemDetailsTitle=Details

#~~~ Info View ~~~~~~~~~~~~~~~~~~~~~~~~~~

#XFLD: Text for item description of each item in the order

infoItemDescription=Item description

Add the properties to the internationalization file.

Page 13: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

13

Figure 4 – The view for creating an item now has empty input fields

Page 14: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

14

Validation in the view To ensure that the scenario flows nicely and smoothly, it’s a good practice to provide hints to the users during the workflow. This is done by validating the users’ input.

webapp/view/Create.view.xml

<mvc:View

controllerName="opensap.orders.controller.Create"

xmlns="sap.m"

xmlns:mvc="sap.ui.core.mvc"

xmlns:uxap="sap.uxap"

xmlns:form="sap.ui.layout.form">

<uxap:ObjectPageLayout

id="objectPageLayout"

alwaysShowContentHeader="true"

isChildPage="true"

showFooter="true">

<uxap:headerTitle>

</uxap:headerTitle>

<uxap:sections>

<uxap:ObjectPageSection id="details"

title="{i18n>createItemDetailsTitle}">

<uxap:subSections>

<uxap:ObjectPageSubSection>

<uxap:blocks>

<form:SimpleForm editable="true">

<Label

text="{i18n>createItemProductID}"/>

<Input

id="productName"

required="true"

value="{

path: 'ProductID',

type: 'sap.ui.model.type.String',

constraints: {

search: '^HT-[0-9]{4}$'

}

}"

change=".onNameChange"/>

<Label

text="{i18n>createItemDescription}"/>

<TextArea

value="{

path: 'Note',

type: 'sap.ui.model.type.String'

}"/>

<Label

text="{i18n>createItemQuantityDescription}"/>

<Input

id="productQuantity"

required="true"

value="{

path: 'Quantity',

type: 'sap.ui.model.odata.type.Decimal',

constraints: {

minimum: '1',

Page 15: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

15

nullable: false

},

formatOptions: {

source: {}

}

}">

</Input>

</form:SimpleForm>

</uxap:blocks>

</uxap:ObjectPageSubSection>

</uxap:subSections>

</uxap:ObjectPageSection>

<uxap:ObjectPageSection title="{i18n>createItemDeliveryTitle}">

<uxap:subSections>

<uxap:ObjectPageSubSection>

<uxap:blocks>

<form:SimpleForm editable="true">

<Label

text="{i18n>createItemDeliveryDate}"/>

<DatePicker

id="deliveryDate"

required="true"

displayFormat="long"

value="{

path: 'DeliveryDate',

type: 'sap.ui.model.type.DateTime'

}"/>

</form:SimpleForm>

</uxap:blocks>

</uxap:ObjectPageSubSection>

</uxap:subSections>

</uxap:ObjectPageSection>

</uxap:sections>

<uxap:footer>

<OverflowToolbar>

<ToolbarSpacer/>

<Button

id="createButton"

type="Emphasized"

text="{i18n>createItemSaveButtonText}"

enabled="{= !${message>/}.length }"

press=".onCreate"/>

<Button

id="cancelButton"

text="{i18n>createItemCancelButtonText}"

press=".onCancel"/>

</OverflowToolbar>

</uxap:footer>

</uxap:ObjectPageLayout>

</mvc:View>

For the value property of each field set the binding path to be the corresponding property from the oData

model. Also specify the value type – again it is the corresponding oData property type. This way the app uses backend validation and ensures that the oData properties will receive correct entries regarding their type. In a similar way, use some constrains to ensure that the correct values are entered. The product name should start with HT- and end with 4 digits. So, use a regular expression in the input constraint to check that.

Page 16: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

16

Also, set the minimum quantity of an ordered product to 1, as it does not make sense to order zero or a negative number of products. You can do that in the backend via setting a constraint (minimum: 1)

At the bottom of the page, add a footer and two buttons – one to create the item, and one to cancel this action. webapp/i18n/i18n.properties

#XGRP: Title of the details group of information in the create item page

createItemDetailsTitle=Details

#XBUT: Text for create new item button

createItemSaveButtonText=Save

#XBUT: Text for cancelling the creation of a new item button

createItemCancelButtonText=Cancel

#~~~ Info View ~~~~~~~~~~~~~~~~~~~~~~~~~~

#XFLD: Text for item description of each item in the order

infoItemDescription=Item description

Add the texts for the buttons at the bottom to the internationalization file.

webapp/controller/Create.controller.js

onInit: function () {

// create a message manager and register the message model

this._oMessageManager = sap.ui.getCore().getMessageManager();

this._oMessageManager.registerObject(this.getView(), true);

this.setModel(this._oMessageManager.getMessageModel(), "message");

this.getRouter().getRoute("create").attachPatternMatched(this._onCreateMatched,

this);

},

_onCreateMatched: function (oEvent) {

// set a dynamic date constraint in controller, as "today" cannot be

// defined declaratively in XMLView

var oToday = new Date();

oToday.setHours(0, 0, 0, 0);

this.byId("deliveryDate").getBinding("value").getType().setConstraints({

minimum: oToday

});

this.getModel("appView").setProperty("/layout", "ThreeColumnsMidExpanded");

},

onCancel: function () {

var sObjectId = this.getView().getBindingContext().getProperty("SalesOrderID");

// discard the new context on cancel

this.getModel().deleteCreatedEntry(this.oContext);

Page 17: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

17

// close the third column

this.getRouter().navTo("object", {

objectId : sObjectId

}, true);

}

});

In the onInit method we fetch the global message manager and register this view. In a special message

model we can then retrieve and display error messages that occurred on the view’s controls. When the create route has been matched, include the logic to validate the delivery date. Find today’s date, get the date-related information from the date object by setting the time part to 0, and set it as a minimum.

In the callback function of the Cancel button, we need to discard the binding context that we created when navigating to the view. Then we simply perform a routing to the order in context to go back to the detail view.

webapp/manifest.json

{

"sap.ui5": {

"contentDensities": {

"compact": true,

"cozy": true

},

"models": {

"i18n": {

"type": "sap.ui.model.resource.ResourceModel",

"settings": {

"bundleName": "opensap.orders.i18n.i18n"

}

},

"": {

"dataSource": "mainService",

"preload": true,

"settings": {

"defaultBindingMode": "TwoWay"

}

}

},

"routing": {

}

}

}

As a last step, define that the app will use TwoWay binding, because it needs handling of the transport of data

both from the model to the controls, and back from the controls to the model. Until now, the app has used the default binding mode – OneWay

Page 18: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

18

Figure 5 – The fields are now validated

Page 19: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

19

Using message popovers for logging errors

In general, it makes for a good user experience if all the errors are stored in one place. This way, they are easy to find and track. The sap.m.MessagePopover control is a good choice for this.

webapp/view/Create.view.xml

<mvc:View

controllerName="opensap.orders.controller.Create"

xmlns="sap.m"

xmlns:mvc="sap.ui.core.mvc"

xmlns:uxap="sap.uxap"

xmlns:form="sap.ui.layout.form">

<uxap:ObjectPageLayout

id="objectPageLayout"

alwaysShowContentHeader="true"

isChildPage="true"

showFooter="true">

<uxap:footer>

<OverflowToolbar>

<Button

id="messagePopoverButton"

icon="sap-icon://message-popup"

type="Emphasized"

text="{= ${message>/}.length }"

visible="{= !!${message>/}.length }"

press=".onOpenMessages"/>

<ToolbarSpacer/>

<Button

id="createButton"

type="Emphasized"

text="{i18n>createItemSaveButtonText}"

enabled="{= !${message>/}.length }"

press=".onCreate"/>

<Button

id="cancelButton"

text="{i18n>createItemCancelButtonText}"

press=".onCancel"/>

</OverflowToolbar>

</uxap:footer>

<uxap:dependents>

<MessagePopover

id="messages"

items="{message>/}">

<MessageItem

type="{message>type}"

title="{message>message}"

subtitle="{message>additionalText}"

description="{message>description}"/>

</MessagePopover>

</uxap:dependents>

</uxap:ObjectPageLayout>

</mvc:View>

Add a Button to the footer which will appear on the screen only if errors are detected. It also shows the

number of messages. It opens the MessagePopover, which displays the occurred errors.

Page 20: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

20

Include the sap.m.MessagePopover as a dependent, using the dependents aggregation of the

ObjectPageLayout, which allows the data binding context and lifecycle to be bound to the aggregated

element.

Also define how the error messages will be populated in the items aggregation of the MessagePopover

using sap.m.MessageItem for each.

webapp/controller/Create.controller.js

onInit: function () {

// create a message manager and register the message model

this._oMessageManager = sap.ui.getCore().getMessageManager();

this._oMessageManager.registerObject(this.getView(), true);

this.setModel(this._oMessageManager.getMessageModel(), "message");

this.getRouter().getRoute("create").attachPatternMatched(this._onCreateMatched,

this);

},

_onCreateMatched: function (oEvent) {

// reset potential server-side messages

this._oMessageManager.removeAllMessages();

// set a dynamic date constraint in controller, as "today" cannot be defined

// declaratively in XMLView

var oToday = new Date();

oToday.setHours(0, 0, 0, 0);

this.byId("deliveryDate").getBinding("value").getType().setConstraints({

minimum: oToday

});

this.getModel("appView").setProperty("/layout", "ThreeColumnsMidExpanded");

},

onCancel: function () {

},

onNameChange: function () {

// clear potential server-side messages to allow saving the item again

this._oMessageManager.getMessageModel().getData().forEach(function(oMessage){

if (oMessage.code) {

this._oMessageManager.removeMessages(oMessage);

}

}.bind(this));

},

onOpenMessages: function (oEvent) {

this.byId("messages").openBy(oEvent.getSource());

}

In the onInit function of the controller, initialize a MessageManager. Register the root element of the view

– ObjectPageLayout – as an object for which errors will be tracked and displayed in the popover.

Page 21: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

21

Ensure that all server-side errors are cleared by removing all messages from the MessageManager when

the route is matched.

Also make sure that there are no old messages when the product name is changed and is about to be validated. This is done in the handler function of the change event of the corresponding input from the view.

In the handler of the button that opens the popover – onOpenMessages – open the MessagePopover.

Figure 6 – When there are errors in the view, they are logged in the MessagePopover

Page 22: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

22

Creating an item in the OData

Now, when most of the validation is in place, you can create a call to the backend to add the new item to the model.

webapp/controller/Create.controller.js

sap.ui.define([

"./BaseController" , "sap/m/MessageToast"

], function (BaseController, MessageToast) {

"use strict";

return BaseController.extend("opensap.orders.controller.Create", {

onInit: function () {

},

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

});

this.getView().setBindingContext(this.oContext);

// reset potential server-side messages

this._oMessageManager.removeAllMessages();

// set a dynamic date constraint in controller, as "today" cannot be

// defined declaratively in XMLView

var oToday = new Date();

oToday.setHours(0, 0, 0, 0);

this.byId("deliveryDate").getBinding("value").getType().setConstraints({

minimum: oToday

});

this.getModel("appView").setProperty("/layout", "ThreeColumnsMidExpanded");

},

_onCreateSuccess: function (oContext) {

// show success message

var sMessage = this.getResourceBundle().getText("newItemCreated",

[oContext.ProductID]);

MessageToast.show(sMessage, {

closeOnBrowserNavigation : false

});

// navigate to the new item in display mode

this.getRouter().navTo("Info", {

objectId : oContext.SalesOrderID,

itemPosition : oContext.ItemPosition

Page 23: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

23

}, true);

},

onCreate: function () {

// send new item to server for processing

this.getModel().submitChanges();

},

onCancel: function () {

},

});

});

At the beginning, when the view is created and the routes are matched, create an entry locally. Specify the collection in which the new entry will be saved – SalesOrderLineItemSet. Then, add initial values to the

mandatory fields from the model by setting the created context to the view.

As a result of the createEntry function, you receive a context that points to the new object. Set it to the

view. In the onCreate handler, call the submit function of the OData model. It creates a HTTP request to be

sent to the server. Once the server completes the create action, a HTTP response is sent back. Register to the success event afterwards via the _onCreateSuccess callback function.

When the _onCreateSuccess function is triggered, unbind the view from the created object, and show a

MessageToast with a success message to the user. As a last step, navigate to the created item.

webapp/i18n/i18n.properties

#XBUT: Text for cancelling the creation of a new item button

createItemCancelButtonText=Cancel

#XMSG: Success message when a new item was created

newItemCreated=Order Item {0} was successfully created

#~~~ Info View ~~~~~~~~~~~~~~~~~~~~~~~~~~

#XFLD: Text for item description of each item in the order

infoItemDescription=Item description

Create a text in the internationalization file for the message to be shown after the creation is completed.

Page 24: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

24

Figure 7 – The newly created item and a MessageToast are shown when the user creates a new entry

RELATED MATERIAL

• Demo Kit: Object Page Layout

• Tutorial: Routing and Navigation

• Sample: MessageManager

• Demo Kit: Creating Entities with OData

Page 25: openSAP Evolved Web Apps with SAPUI5 · 2019-06-03 · With the validated data, an OData entry will be created. Figure 1 – The final look of the view for creating an item in the

www.sap.com/contactsap

No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company. The information contained herein may be changed without prior notice. Some software products marketed by SAP SE and its distributors contain proprietary software components of other software vendors. National product specifications may vary. These materials are provided by SAP SE or an SAP affiliate company for informational purposes only, without representation or warranty of any kind, and SAP or its affiliated companies shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP or SAP affiliate company products and serv ices are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty. In particular, SAP SE or its affiliated companies have no obligation to pursue any course of business outlined in this document or any related presentation, or to develop or release any functionality mentioned therein. This document, or any related presentation, and SAP SE’s or its affiliated companies’ strategy and possible future developments, products, and/or platform directions and functionality are all subject to change and may be changed by SAP SE or its affiliated companies at any time for any reason without notice. The information in this document is not a commitment, promise, or legal obligation to deliver any material, code, or functionality. All forward-looking statements are subject to various risks and uncertainties that could cause actual results to differ materially from expectations. Readers are cautioned not to place undue reliance on these forward-looking statements, and they should not be relied upon in making purchasing decisions. SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. All other product and service names mentioned are the trademarks of their respective companies. See http://www.sap.com/corporate-en/legal/copyright/index.epx for additional trademark information and notices.

© 2018 SAP SE or an SAP affiliate company. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company. The information contained herein may be changed without prior notice. Some software products marketed by SAP SE and its distributors contain proprietary software components of other software vendors. National product specifications may vary. These materials are provided by SAP SE or an SAP affiliate company for informational purposes only, without representation or warranty of any kind, and SAP or its a ffiliated companies shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP or SAP affiliate company products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty. In particular, SAP SE or its affiliated companies have no obligation to pursue any course of business outlined in this document or any related presentation, or to develop or release any functionality mentioned therein. This document, or any related presentation, and SAP SE’s or its affiliated companies’ strategy and possible future developments, products, and/or platform directions and functionality are all subject to change and may be changed by SAP SE or its affiliated companies at any time for any reason without notice. The information in this document is not a commitment, promise, or legal obligation to deliver any material, code, or functionality. All forward-looking statements are subject to various risks and uncertainties that could cause actual results to differ materially from expectations. Readers are cautioned not to place undue reliance on these forward-looking statements, and they should not be relied upon in making purchasing decisions. SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. All other product and service names mentioned are the trademarks of their respective companies. See http://www.sap.com/corporate-en/legal/copyright/index.epx for additional trademark information and notices.

Coding Samples Any software coding or code lines/strings (“Code”) provided in this documentation are only examples and are not intended for use in a production system environment. The Code is only intended to better explain and visualize the syntax and phrasing rules for certain SAP coding. SAP does not warrant the correctness or completeness of the Code provided herein and SAP shall not be liable for errors or damages cause by use of the Code, except where such damages were caused by SAP with intent or with gross negligence.