I am writing a simple application which aims to display the local data of a json file.
How can I sum the values from a column?
Expected effect:
enter image description here
Below are the files to recreate the case
V_Root.view.xml
<mvc:View controllerName="Nawigacja.ZNavigation.controller.V_Root" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
<App id="V_Main">
<pages>
<Page title="Root View">
<content></content>
</Page>
</pages>
</App>
</mvc:View>
V_Source.view.xml
<mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="Nawigacja.ZNavigation.controller.V_Source"
xmlns:html="http://www.w3.org/1999/xhtml">
<App>
<pages>
<Page title="Soruce View">
<content>
<VBox width="100%" direction="Column" id="__vbox0">
<items>
<Button text="Button 1" width="100px" id="__button2" press="GoToTarget_1"/>
<Button text="Button 2" width="100px" id="__button3" press="GoToTarget_2"/>
</items>
</VBox>
</content>
</Page>
</pages>
</App>
</mvc:View>
V_Target_1.view.xml
<mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="Nawigacja.ZNavigation.controller.V_Target_1"
xmlns:html="http://www.w3.org/1999/xhtml">
<App>
<pages>
<Page title="Target One" showNavButton="true" navButtonPress="GoOneScreenBack">
<content>
<ScrollContainer vertical="true" focusable="true" height="95%">
<Table id="namiot" items="{path: '/namiot'}">
<columns>
<Column width="12rem">
<Label text="Najem"/>
</Column>
<Column minScreenWidth="tablet" demandPopin="true">
<Label text="Price"/>
</Column>
<Column width="12rem">
<Label text="Total Cost"/>
<footer>
<Text text="Sum:"/>
</footer>
</Column>
</columns>
<ColumnListItem>
<Text text="{ProductType}"></Text>
<Text text="{ProductPrice}"></Text>
<Text text="{ProductTotal}"></Text>
</ColumnListItem>
</Table>
</ScrollContainer>
</content>
</Page>
</pages>
</App>
</mvc:View>
V_Root.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("Nawigacja.ZNavigation.controller.V_Root", {
onInit: function () {
}
});
});
V_Source.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("Nawigacja.ZNavigation.controller.V_Source", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* #memberOf Nawigacja.ZNavigation.view.V_Source
*/
onInit: function () {
},
GoToTarget_1: function () {
// Now Get the Router Info
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
// Tell the Router to Navigate To Route_Tar_1
oRouter.navTo("Route_Tar_1", {});
},
GoToTarget_2: function () {
// Now Get the Router Info
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
// Tell the Router to Navigate To Route_Tar_2
oRouter.navTo("Route_Tar_2", {});
}
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* #memberOf Nawigacja.ZNavigation.view.V_Source
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* #memberOf Nawigacja.ZNavigation.view.V_Source
*/
// onAfterRendering: function() {
//
// },
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* #memberOf Nawigacja.ZNavigation.view.V_Source
*/
// onExit: function() {
//
// }
});
});
V_Target_1.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/core/routing/History",
"Nawigacja/ZNavigation/formatter/Formatter"
], function (Controller, History,formatter) {
"use strict";
return Controller.extend("Nawigacja.ZNavigation.controller.V_Target_1", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* #memberOf Nawigacja.ZNavigation.view.V_Target_1
*/
onInit: function () {
var oTable = this.getView().byId("namiot");
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData("model/namiot.json");
oTable.setModel(oModel);
},
GoOneScreenBack: function (Evt) {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
// Go one screen back if you find a Hash
if (sPreviousHash !== undefined) {
window.history.go(-1);
}
// If you do not find a correct Hash, go to the Source screen using default router;
else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("", true);
}
},
formatter: formatter
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* #memberOf Nawigacja.ZNavigation.view.V_Target_1
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* #memberOf Nawigacja.ZNavigation.view.V_Target_1
*/
// onAfterRendering: function() {
//
// },
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* #memberOf Nawigacja.ZNavigation.view.V_Target_1
*/
// onExit: function() {
//
// }
});
});
models.js
sap.ui.define([
"sap/ui/model/json/JSONModel",
"sap/ui/Device"
], function (JSONModel, Device) {
"use strict";
return {
createDeviceModel: function () {
var oModel = new JSONModel(Device);
oModel.setDefaultBindingMode("OneWay");
return oModel;
}
};
});
manifest.json
{
"_version": "1.12.0",
"sap.app": {
"id": "Nawigacja.ZNavigation",
"type": "application",
"i18n": "i18n/i18n.properties",
"applicationVersion": {
"version": "1.0.0"
},
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"sourceTemplate": {
"id": "ui5template.basicSAPUI5ApplicationProject",
"version": "1.40.12"
}
},
"sap.ui": {
"technology": "UI5",
"icons": {
"icon": "",
"favIcon": "",
"phone": "",
"phone#2": "",
"tablet": "",
"tablet#2": ""
},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
}
},
"sap.ui5": {
"flexEnabled": false,
"rootView": {
"viewName": "Nawigacja.ZNavigation.view.V_Root",
"type": "XML",
"async": true,
"id": "V_Root"
},
"dependencies": {
"minUI5Version": "1.65.6",
"libs": {
"sap.ui.layout": {},
"sap.ui.core": {},
"sap.m": {}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "Nawigacja.ZNavigation.i18n.i18n"
}
}
},
"resources": {
"css": [{
"uri": "css/style.css"
}]
},
"routing": {
"config": {
"routerClass": "sap.m.routing.Router",
"viewType": "XML",
"async": true,
"viewPath": "Nawigacja.ZNavigation.view",
"controlAggregation": "pages",
"controlId": "V_Main",
"clearControlAggregation": false,
"viewLevel": 1
},
"routes": [{
"name": "Route_Source",
"pattern": "",
"target": ["Target_Source"],
"titleTarget": ""
}, {
"name": "Route_Tar_1",
"pattern": "V_Target_1",
"titleTarget": "",
"greedy": false,
"target": ["Target_1"]
}, {
"name": "Route_Tar_2",
"pattern": "V_Target_2",
"titleTarget": "",
"greedy": false,
"target": ["Target_2"]
}],
"targets": {
"Target_1": {
"viewType": "XML",
"transition": "slide",
"clearAggregation": true,
"viewName": "V_Target_1",
"viewLevel": 2
},
"Target_2": {
"viewType": "XML",
"transition": "slide",
"clearAggregation":"true",
"viewName": "V_Target_2",
"viewLevel": 2
},
"Target_Source": {
"viewType": "XML",
"clearAggregation":"true",
"viewName": "V_Source",
"viewLevel": 1
}
}
}
}
}
namiot.json
{
"namiot":[
{
"ProductName": "Product1",
"ProductType": "Type1",
"ProductPrice": "25",
"ProductTotal": "5000",
"Productadd": "",
"ProductaddPr":""
},
{
"ProductName": "Product2",
"ProductType": "Type2",
"ProductPrice": "25",
"ProductTotal": "5000",
"Productadd": "",
"ProductaddPr":""
}
]
}
there are probably x options to realize this.
You could use the method attachUpdateFinished which will be called when the Tablebinding get's updated (the table receives the Items). Then you can summarize the values and store it in an JSONModel and bind it to the footertext. When the binding (the items) change the sum would be updated.
oTable.attachUpdateFinished(function (oEvt) {
var iSum = 0;
var aItems = oEvt.getSource().getItems();
for (var i = 0; i < aItems.length; i++) {
var oItem = aItems[i].getBindingContext().getObject();
iSum = iSum + parseFloat(oItem.ProductTotal);
}
//Do whatever you want with the iSum
});
Here's an example how it could be realized.
Code Sample
Related
<mvc:View xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:core="sap.ui.core"
controllerName="z.controller.Main">
<Page id="page" title="ComboBox" >
<content>
<ComboBox name="Drop-down List" id="box0" items="{/country}">
<items >
<core:Item key="{Key}" text="{Name}" id="item0"/>
</items>
</ComboBox>
</content>
<Button text="Change" press="onChange"/>
</Page>
</mvc:View>
model1.json
{
"country": [{
"Key": "IN",
"Name": "India"
},
{
"Key": "US",
"Name": "USA"
},{
"Key": "UK",
"Name": "United Kingdom"
}]
}
model2.json
{
"country2": [{
"Key": "BD",
"Name": "Bangladesh"
},
{
"Key": "CA",
"Name": "Canada"
},{
"Key": "FR",
"Name": "France"
}]
}
Main.controller.js
sap.ui.define([
'sap/ui/core/mvc/Controller',
"sap/ui/model/json/JSONModel",
"z/models/model"
], function(Controller,JSONModel, localModel) {
'use strict';
return Controller.extend("z.controller.Main",{
onInit: function(){
var oModel = localModel.createJSONModel("models/data/model1.json");
sap.ui.getCore().setModel(oModel);
var oModel2 = localModel.createJSONModel("models/data/model2.json");
sap.ui.getCore().setModel(oModel2, "model2");
},
onChange: function(){
}
})
});
controller.js
sap.ui.define([
'sap/ui/core/mvc/Controller',
"sap/ui/model/json/JSONModel"
], function(Controller,JSONModel) {
'use strict';
return {
createJSONModel: function(filePath){
var oModel = new JSONModel();
oModel.loadData(filePath);
return oModel;
}
}
});
I have two JSON models and building a combo list using aggregation binding(items="{/country}") by reading data from model1. I am trying to fill the same Combolist by reading the data from the model2 on a button press event.
You can switch the model by using it as a prefix model2> (as you have defined in the Main.controller.js in the onInit method) in the binding path:
onChange: function() {
var oComboBox = this.getView().byId("box0");
oComboBox.bindItems("model2>/country2", {
template: this.getView().byId("item0")
});
}
And change the aggregation from items to dependents.
<ComboBox name="Drop-down List" id="box0" items="{/country}">
<dependents>
<core:Item key="{Key}" text="{Name}" id="item0"/>
</dependents>
</ComboBox>
I'm trying to run a SAPUI5 application. I created a view with a view piecharts and add them in index.html to the body by referring to its ID content
<script>
var app = new sap.m.App();
var page = sap.ui.view({
viewName: "...",
type: sap.ui.core.mvc.ViewType.XML
});
app.addPage(page);
app.placeAt("content");
</script>
My problem now is that the Component.js isn't called. So I have no chance of using Routing since the Router isn't initialized.
I tried some different ways, like this:
<script>
sap.ui.getCore().attachInit(function() {
new sap.m.Shell({
app: new sap.ui.core.ComponentContainer({
height: "100%",
name: "vizFrame.gettingStarted.demoVizFrame"
})
}).placeAt("content");
});
</script>
After this approach, the Component.js got triggered, but the page is empty. The content of my root view isn't displayed.
manifest.json
{
"_version": "1.12.0",
"sap.app": {
"id": "vizFrame.gettingStarted.demoVizFrame",
"type": "application",
"i18n": "i18n/i18n.properties",
"applicationVersion": {
"version": "1.0.0"
},
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"sourceTemplate": {
"id": "ui5template.basicSAPUI5ApplicationProject",
"version": "1.40.12"
}
},
"sap.ui": {
"technology": "UI5",
"icons": {
"icon": "",
"favIcon": "",
"phone": "",
"phone#2": "",
"tablet": "",
"tablet#2": ""
},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
}
},
"sap.ui5": {
"flexEnabled": false,
"rootView": {
"viewName": "vizFrame.gettingStarted.demoVizFrame.view.VizChart",
"type": "XML"
},
"dependencies": {
"minUI5Version": "1.60.1",
"libs": {
"sap.ui.layout": {},
"sap.ui.core": {},
"sap.m": {}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "vizFrame.gettingStarted.demoVizFrame.i18n.i18n"
}
}
},
"resources": {
"css": [
{
"uri": "css/style.css"
}
]
},
"routing": {
"config": {
"routerClass": "sap.m.routing.Router",
"viewType": "XML",
"async": true,
"viewPath": "vizFrame.gettingStarted.demoVizFrame.view",
"controlAggregation": "pages",
"controlId": "app",
"clearControlAggregation": false
},
"routes": [
{
"name": "RouteVizChart",
"pattern": "RouteVizChart",
"target": ["TargetVizChart"]
},
{
"pattern": "detail",
"name": "detail",
"target": "detail"
}
],
"targets": {
"TargetVizChart": {
"viewType": "XML",
"transition": "slide",
"clearControlAggregation": false,
"viewId": "VizChart",
"viewName": "VizChart"
},
"testView": {
"viewType": "XML",
"viewName": "testView",
"viewId": "testView",
"viewLevel": 2
},
"detail": {
"viewType": "XML",
"viewName": "detailView"
}
}
}
}
}
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/Device",
"vizFrame/gettingStarted/demoVizFrame/model/models"
], function (UIComponent, Device, models) {
"use strict";
return UIComponent.extend("vizFrame.gettingStarted.demoVizFrame.Component", {
metadata: {
manifest: "json"
},
init: function () {
UIComponent.prototype.init.apply(this, arguments);
this.getRouter().initialize();
this.setModel(models.createDeviceModel(), "device");
}
});
});
VizChart.view.xml
This is the root view where only the page title gets displayed:
<mvc:View controllerName="vizFrame.gettingStarted.demoVizFrame.controller.VizChart"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:viz="sap.viz.ui5.controls"
xmlns:chart="sap.suite.ui.commons"
xmlns:l="sap.ui.layout"
>
<Page title="Übersicht">
<l:VerticalLayout
width="100%"
class="gridWrapper">
<l:Grid containerQuery="true">
<viz:VizFrame xmlns="sap.viz" id="l100" width="100%" selectData="onDataClick" />
<viz:VizFrame xmlns="sap.viz" id="l300" width="100%" selectData="onDataClick" />
<viz:VizFrame xmlns="sap.viz" id="l400" width="100%" selectData="onDataClick" />
<viz:VizFrame xmlns="sap.viz" id="l430" width="100%" selectData="onDataClick" />
<viz:VizFrame xmlns="sap.viz" id="l499" width="100%" selectData="onDataClick" />
</l:Grid>
</l:VerticalLayout>
</Page>
</mvc:View>
The topic App Initialization: What Happens When an App Is Started? explains which files are loaded in which order generally. In most cases, a Component is loaded with its descriptor (manifest.json) once the ComponentContainer is instantiated.
About the issue with the page being empty, see my other answer in stackoverflow.com/a/50951902.
In your case, the root view is missing a root control (e.g. sap.m.App). So it should be:
<!-- Root view -->
<mvc:View xmlns:mvc="sap.ui.core.mvc">
<App id="app" xmlns="sap.m">
<!-- Leave this block empty if Router should be used. Otherwise, continue.. -->
<Page title="Übersicht">
<!-- content -->
</Page>
</App>
</mvc:View>
In your 1st snippet, you could see the page content because there was already sap.m.App.
ComponentContainer loads component.js file from index.html
component.js loads component descriptor(manifest.json - application descriptor file to declare dependencies) which is referenced in the file.
component.js create root view, default and resource(i18n) model.
index.html
sap.ui.getCore().attachInit(function () {
new sap.ui.core.ComponentContainer({
name: "ABC.AppName"
}).placeAt("content");
});
component.js
sap.ui.core.UIComponent.extend("ABC.AppName.Component", {
metadata : {
includes: [jQuery.device.is.phone ? "assets/css/mStyle.css" : "assets/css/dStyle.css"]
},
createContent: function () {
// create root view
var oView = sap.ui.view({
id: "app",
viewName: "ABC.AppName.ViewFolder.App",
type: "JS",
viewData: { component: this },
});
i18nGlobal = new sap.ui.model.resource.ResourceModel({
bundleUrl: "i18n/i18n.properties",
bundleLocale: "de"
});
oView.setModel(i18nGlobal, "i18n");
sap.ui.getCore().setModel(i18nGlobal, "i18n");
return oView;
}
});
I am new to SAPUI5. I am trying to load a JSON Model from Manifest file and send JSON object as a parameter through Routing and Navigation.
I have only one view and in that i am trying to bind data in a simple form. I am getting one error :
View1.controller.js?eval:8 Uncaught (in promise) TypeError: Cannot
read property ‘getModel’ of undefined
Kindly help me in resolving the error.
Manifest.json
{
"_version": "1.8.0",
"sap.app": {
"_version": "1.3.0",
"id": "com.newproject.firstsapui5project",
"type": "application",
"i18n": "i18n/i18n.properties",
"applicationVersion": {
"version": "1.0.0"
},
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"sourceTemplate": {
"id": "ui5template.basicSAPUI5ApplicationProject",
"version": "1.40.12"
},
"dataSources": {
"data": {
"type" : "JSON",
"uri": "model/data.json"
}
}
},
"sap.ui": {
"_version": "1.3.0",
"technology": "UI5",
"icons": {
"icon": "",
"favIcon": "",
"phone": "",
"phone#2": "",
"tablet": "",
"tablet#2": ""
},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
},
"supportedThemes": [
"sap_hcb",
"sap_belize"
]
},
"sap.ui5": {
"_version": "1.2.0",
"rootView": {
"viewName": "com.newproject.firstsapui5project.view.View1",
"type": "XML"
},
"dependencies": {
"minUI5Version": "1.60.1",
"libs": {
"sap.ui.layout": {},
"sap.ui.core": {},
"sap.m": {}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "com.newproject.firstsapui5project.i18n.i18n"
}
},
"simpleForm": {
"type": "sap.ui.model.json.JSONModel",
"dataSource" : "data"
}
},
"resources": {
"css": [{
"uri": "css/style.css"
}]
},
"routing": {
"config": {
"routerClass": "sap.m.routing.Router",
"viewType": "XML",
"async": true,
"viewPath": "com.newproject.firstsapui5project.view",
"controlAggregation": "pages",
"controlId": "idAppControl",
"clearControlAggregation": false
},
"routes": [{
"name": "RouteView1",
"pattern": "RouteView1",
"target": ["TargetView1"]
}],
"targets": {
"TargetView1": {
"viewType": "XML",
"transition": "slide",
"clearControlAggregation": false,
"viewName": "View1"
}
}
}
}
}
View1.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
var oController= Controller.extend("com.newproject.firstsapui5project.controller.View1", {
onInit: function () {
var dataModel = this.getOwnerComponent().getModel("simpleForm");
this.getView().setModel(dataModel, "DataModel");
}
});
return oController;
});
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/Device",
"com/newproject/firstsapui5project/model/models"
], function (UIComponent, Device, models) {
"use strict";
var Component = UIComponent.extend("com.newproject.firstsapui5project.Component", {
metadata: {
manifest: "json"
},
/**
* The component is initialized by UI5 automatically during the startup of the app and calls the init method once.
* #public
* #override
*/
init: function () {
// call the base component's init function
UIComponent.prototype.init.apply(this, arguments);
this.setModel(models.createDeviceModel(), "device");
this.getRouter().initialize();
}
});
return Component;
});
data.json
{"Form" : [{
"first":"tom",
"lastname":"butler",
"height": "6foot",
"gender":"Male"
}]
}
View1.view.xml
<mvc:View controllerName="com.newproject.firstsapui5project.controller.View1" xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:mvc="sap.ui.core.mvc" xmlns:f="sap.ui.layout.form" displayBlock="true" xmlns="sap.m">
<App id="idAppControl">
<pages>
<Page title="My First sapui5 Project">
<content>
<f:SimpleForm id="idSimpleForm" editable="true" layout="ResponsiveGridLayout" title='TEST Form'>
<f:content>
<Label text="First Name"/>
<Input value="simpleForm>/Form/0/first" />
<Label text="Last Name"/>
<Input value="{simpleForm>/Form/0/lastname}">
</Input>
</f:content>
</f:SimpleForm>
</content>
</Page>
</pages>
</App>
</mvc:View>
model.js
sap.ui.define([
"sap/ui/model/json/JSONModel",
"sap/ui/Device"
], function (JSONModel, Device) {
"use strict";
return {
createDeviceModel: function () {
var oModel = new JSONModel(Device);
oModel.setDefaultBindingMode("OneWay");
return oModel;
}
};
});
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<title>firstsapui5project</title>
<script id="sap-ui-bootstrap"
src="../../resources/sap-ui-core.js"
data-sap-ui-async="true"
data-sap-ui-libs="sap.m"
data-sap-ui-theme="sap_belize"
data-sap-ui-compatVersion="edge"
data-sap-ui-language="en"
data-sap-ui-xx-componentPreload="off"
data-sap-ui-resourceroots='{"com.newproject.firstsapui5project": ""}'>
</script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
sap.ui.getCore().attachInit(function() {
/* new sap.m.Shell({
app: new sap.ui.core.ComponentContainer({
height : "100%",
name : "com.newproject.firstsapui5project"
})
}).placeAt("content");*/
var app = new sap.m.App({initialPage:"idView1"});
var page1 = sap.ui.view({id:"idView1", viewName:"com.newproject.firstsapui5project.view.View1", type:sap.ui.core.mvc.ViewType.XML});
app.addPage(page1);
// app.addDetailPage(page2);
app.placeAt("content");
});
</script>
</head>
<body class="sapUiBody" id="content">
</body>
</html>
View1 is not being initialized by a Component, thus an owner can't be determined. Instead of explicitly creating a view and putting it into DOM (index.html), create a sap.m.Shell as it's done in commented code. Shell would create a component which would create a root view that's specified in manifest.json.
I have a problem, that sometimes the controller does not get loaded:
and you can see the error message. It should load the following controller(marked with red border):
Why it is not getting loaded sometimes?
When the controller gets loaded, it looks like:
UPDATE:
I am using flexible column layout.
The App.view.xml looks like:
<mvc:View controllerName="ch.mindustrie.ZMM_CLASSIFICATION.controller.App" xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:f="sap.f">
<App id="root">
<f:FlexibleColumnLayout id="idClassLayout"/>
</App>
</mvc:View>
the manifest.json file:
{
"_version": "1.9.0",
"sap.app": {
"id": "ch.mindustrie.ZMM_CLASSIFICATION",
"type": "application",
"i18n": "i18n/i18n.properties",
"applicationVersion": {
"version": "0.1.0"
},
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"sourceTemplate": {
"id": "servicecatalog.connectivityComponentForManifest",
"version": "0.0.0"
},
"dataSources": {
"ZMM_CLASSIFICATION_SRV": {
"uri": "/sap/opu/odata/sap/ZMM_CLASSIFICATION_SRV/",
"type": "OData",
"settings": {
"odataVersion": "2.0",
"localUri": "localService/ZMM_CLASSIFICATION_SRV/metadata.xml"
}
}
}
},
"sap.ui": {
"technology": "UI5",
"icons": {
"icon": "",
"favIcon": "",
"phone": "",
"phone#2": "",
"tablet": "",
"tablet#2": ""
},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
},
"supportedThemes": [
"sap_hcb",
"sap_belize"
]
},
"sap.ui5": {
"handleValidation": true,
"rootView": {
"viewName": "ch.mindustrie.ZMM_CLASSIFICATION.view.App",
"type": "XML",
"async": true,
"id": "app"
},
"dependencies": {
"minUI5Version": "1.50.0",
"libs": {
"sap.ui.layout": {},
"sap.ui.core": {},
"sap.m": {},
"sap.f": {},
"sap.collaboration": {
"lazy": true
}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "ch.mindustrie.ZMM_CLASSIFICATION.i18n.i18n"
}
},
"Classification": {
"uri": "/sap/opu/odata/sap/ZMM_CLASSIFICATION_SRV/",
"type": "sap.ui.model.odata.v2.ODataModel",
"settings": {
"defaultOperationMode": "Server",
"defaultBindingMode": "OneWay",
"defaultCountMode": "Request"
},
"dataSource": "ZMM_CLASSIFICATION_SRV",
"preload": true
}
},
"resources": {
"css": [
{
"uri": "css/style.css"
}
]
},
"routing": {
"config": {
"routerClass": "sap.f.routing.Router",
"viewType": "XML",
"viewPath": "ch.mindustrie.ZMM_CLASSIFICATION.view",
"controlId": "idClassLayout",
"bypassed": {
"target": [
"search",
"characteristic"
]
},
"async": true
},
"routes": [
{
"pattern": "",
"name": "search",
"target": [
"characteristic",
"search"
],
"layout": "TwoColumnsBeginExpanded"
},
{
"pattern": "search/{internalclassnum}",
"name": "characteristic",
"target": [
"search",
"characteristic"
],
"layout": "TwoColumnsMidExpanded"
}
],
"targets": {
"search": {
"viewName": "Search",
"viewLevel": 1,
"viewId": "search",
"controlAggregation": "beginColumnPages"
},
"characteristic": {
"viewName": "Characteristic",
"viewLevel": 2,
"viewId": "characteristic",
"controlAggregation": "endColumnPages"
}
}
}
},
"sap.platform.abap": {
"uri": "/sap/bc/ui5_ui5/sap/zmm_classifi/webapp",
"_version": "1.1.0"
}
}
the Search.view.xml:
<mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:uxap="sap.uxap"
xmlns:f="sap.ui.layout.form" xmlns:smartFilterBar="sap.ui.comp.smartfilterbar"
controllerName="ch.mindustrie.ZMM_CLASSIFICATION.controller.Search" xmlns:html="http://www.w3.org/1999/xhtml">
<smartFilterBar:SmartFilterBar id="SelectionFilterBar" entitySet="ZMM_C_CLASSIFICATION" search="onSearchClass">
<smartFilterBar:controlConfiguration>
<smartFilterBar:ControlConfiguration key="ClassType" visibleInAdvancedArea="true" preventInitialDataFetchInValueHelpDialog="false"></smartFilterBar:ControlConfiguration>
<smartFilterBar:ControlConfiguration key="ClassNum" visibleInAdvancedArea="true" preventInitialDataFetchInValueHelpDialog="false"></smartFilterBar:ControlConfiguration>
</smartFilterBar:controlConfiguration>
</smartFilterBar:SmartFilterBar>
<Tree id="ClassTree" items="{path: 'Tree>/'}" toggleOpenState="onOpenAnItemOnTree">
<CustomTreeItem>
<FlexBox width="100%" alignItems="Center" justifyContent="SpaceBetween">
<items>
<Label text="{Tree>text}" wrapping="true"/>
<Button icon="sap-icon://display" type="Transparent" press="onClassPressed"/>
</items>
</FlexBox>
</CustomTreeItem>
</Tree>
</mvc:View>
And the Search.Controller
sap.ui.define([
"ch/mindustrie/ZMM_CLASSIFICATION/controller/BaseController"
], function (BaseController) {
"use strict";
return BaseController.extend("ch.mindustrie.ZMM_CLASSIFICATION.controller.Search", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* #memberOf ch.mindustrie.ZMM_CLASSIFICATION.view.Search
*/
onInit: function () {
//Set model for smart filter bar
const oModel = this.getModel("Classification");
this.setModel(oModel);
//Model for classification tree
this.setModel(new sap.ui.model.json.JSONModel(), "Tree");
},
onSearchClass: function () {
const aFilter = this.byId("SelectionFilterBar").getFilters();
const self = this;
//Build the first node
this._readClassification(aFilter)
.then(aData => self.getModel("Tree").setProperty("/", aData));
},
/*
* Read classification from server.
*/
_readClassification: function (aFilter) {
const self = this;
//Build entry node
const oModel = this.getModel("Classification");
const oDateFrom = new sap.ui.model.Filter({
path: "ValidFrom",
operator: sap.ui.model.FilterOperator.LE,
value1: new Date()
});
const oDateUntil = new sap.ui.model.Filter({
path: "ValidFrom",
operator: sap.ui.model.FilterOperator.GE,
value1: new Date()
});
return new Promise((resolve, reject) => {
oModel
.read("/ZMM_C_CLASSIFICATION", {
filters: aFilter.concat([oDateFrom, oDateUntil]),
success: function (oData) {
let aTreeWithNodes = [];
const aTree = oData.results.map(self._buildEntryTree);
aTree.forEach((oNode, index) => {
self._readSubClasses(oNode.internalClass)
.then(aData => {
const oWithNodes = aTree[index];
if (aData.length > 0) {
oWithNodes.nodes = aData;
}
aTreeWithNodes.push(oWithNodes);
if (aTreeWithNodes.length === aTree.length) {
resolve(aTreeWithNodes);
}
});
});
},
error: function (oError) {
reject(oError);
}
});
});
},
_readSubClasses: function (sSubInternalClass) {
const oModel = this.getModel("Classification");
const self = this;
const oUpInteralClass = new sap.ui.model.Filter({
path: "UpInternalClass",
operator: sap.ui.model.FilterOperator.EQ,
value1: sSubInternalClass
});
return new Promise((resolve) => {
oModel
.read("/ZMM_C_CLASSSUB_REL", {
filters: [oUpInteralClass],
success: function (oData) {
const aNewNodes = (oData.results.length > 0 ? oData.results.map(self._prepareDescEntryNodes) : []);
resolve(aNewNodes);
},
error: function () {
resolve([]);
}
});
});
},
/*
* Build the entry node.
*/
_buildEntryTree: function (oData) {
return {
text: oData.ClassType + " " + oData.ClassNum + " " + oData.ClassNumDescr,
classType: oData.ClassType,
classNum: oData.ClassNum,
internalClass: oData.InternalClass,
nodes: []
};
},
onOpenAnItemOnTree: function (oEvent) {
const bExpanded = oEvent.getParameter("expanded");
if (!bExpanded) {
return;
}
const iItemIndex = oEvent.getParameter("itemIndex");
const oItemContext = oEvent.getParameter("itemContext");
const oTree = this.byId("ClassTree");
const oModel = this.getView().getModel("Tree");
const sPath = oItemContext.getPath();
const oCurrentNode = oModel.getProperty(sPath);
this._loadOnDemand(oModel, oCurrentNode, sPath, oTree.getItems()[iItemIndex].getLevel());
},
/*
* Load descendants asynchronously.
*/
_loadOnDemand: function (oModel, oCurrentNode, sPath) {
const aChildNodes = oCurrentNode.nodes.map(oClass => {
return new sap.ui.model.Filter({
path: "InternalClass",
operator: sap.ui.model.FilterOperator.EQ,
value1: oClass.internalClass
});
});
this._readClassification(aChildNodes)
.then(aNewNodes => oModel.setProperty(sPath + "/nodes", aNewNodes));
},
/*
* When the item in the tree is getting pressed.
*/
onClassPressed: function (oEvent) {
const oRow = oEvent.getSource().getBindingContext("Tree").getObject();
this.getRouter().navTo("characteristic", {
internalclassnum: oRow.internalClass
});
}
});
});
I believe the flexibility services only work in the Fiori launchpad, not in the webide sandbox launchpad. Do you get the same issue if you deploy?
Can you help me solve this mystery? I got the walkthrough example in step 10 and adapted it so I can create a simple binding to an OData service.
Let me share the main files:
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/model/json/JSONModel"
], function(UIComponent, JSONModel) {
"use strict";
return UIComponent.extend("BasicMessages.Component", {
metadata: {
manifest: "json"
},
init: function() {
// call the init function of the parent
UIComponent.prototype.init.apply(this, arguments);
// set data model
var oData = {
recipient: {
name: "World"
}
};
var oModel = new JSONModel(oData);
this.setModel(oModel, "json");
},
});
});
Manifest.json (hid the service URI, but it's properly configured)
{
"_version": "1.8.0",
"sap.app": {
"id": "BasicMessages",
"type": "application",
"i18n": "i18n/i18n.properties",
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"applicationVersion": {
"version": "1.0.0"
},
"dataSources": {
"mainService": {
"uri": "hidden_service_uri",
"type": "OData",
"settings": {
"odataVersion": "2.0",
"localUri": "localService/metadata.xml"
}
}
}
},
"sap.ui": {
"technology": "UI5",
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
}
},
"sap.ui5": {
"rootView": {
"viewName": "BasicMessages.view.App",
"type": "XML",
"async": true,
"id": "app"
},
"dependencies": {
"minUI5Version": "1.30",
"libs": {
"sap.m": {}
}
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "BasicMessages.i18n.i18n"
}
},
"": {
"dataSource": "mainService",
"settings": {
"defaultUpdateMethod": "PUT",
"useBatch": false,
"metadataUrlParams": {
"sap-documentation": "heading"
},
"defaultBindingMode": "TwoWay"
}
}
}
}
}
App.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast"
], function(Controller, MessageToast) {
"use strict";
return Controller.extend("BasicMessages.controller.App", {
onInit: function() {
this.getView().setModel(this.getOwnerComponent().getModel());
},
onShowHello: function() {
// read msg from i18n model
var oBundle = this.getView().getModel("i18n").getResourceBundle();
var sRecipient = this.getView().getModel("json").getProperty("/recipient/name");
var sMsg = oBundle.getText("helloMsg", [sRecipient]);
// show message
MessageToast.show(sMsg);
},
});
});
App.view.xml (this is the tricky file)
<mvc:View controllerName="BasicMessages.controller.App"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">
<Button text="{i18n>showHelloButtonText}" press="onShowHello" />
<Input value="{json>/recipient/name}"
description="Hello {json>/recipient/name}"
valueLiveUpdate="true" width="60%"
/>
<Text text="{/Caixas(Id='0001',InicioValidade='20180712193002')/Descricao}" />
<List items="{/Caixas}">
<StandardListItem title="{Descricao}" />
</List>
</mvc:View>
If I use the view file exactly like that, it calls the OData service on the backend and retrieve the list and the text element contents.
link to screenshot:
If I comment the list lines, the OData service won't be called and the text element won't be filled with the text.
link to screenshot:
Why does this happen???
Got the answer on SAP Docs
Note: Requests to the back end are triggered by list bindings (ODataListBinding), element bindings (ODataContextBinding), and CRUD functions provided by the ODataModel. Property bindings (ODataPropertyBindings) do not trigger requests.
I think, Rafael explained why this happens (your question), now to answer the unasked question "howto make this work":
You would need to bind the Text control to the entitiy and the text property to the Descricio attribute, basically something like that:
<Text binding="{/Caixas(Id='0001',InicioValidade='20180712193002')" text="{Descricao}" />
(sorry, no ui5 runtime environment at hand, so I didnt actually run this)