Skip to Content

How to load a JSON Model from Manifest file and send JSON object as a parameter through Routing and Navigation

Hi

I have two views and in first view binding table data and I want to navigate selected row data to a second view. Here we are using the Global JSON Model Declared in the manifest.json file.

Step – 1:

First, we need to login to SAP Cloud Platform by entering the credentials. After login, I have created a  project in SAP Web IDE. Here I’m creating a project with a project name “navigationjson” which is shown below the workspace.

Step – 2: webapp/model/Object.json

Now we need to create JSON  file in order to bind our data to the view. the JSON file code like as below.

{
	"Objects": [{
			"Name": "Alice Mutton",
			"Supplier": "Exotic Liquids",
			"Price": "75.00 EUR",
			"Units": "20 PC"

		}, {
			"Name": "Aniseed Syrup",
			"Supplier": "Grandma Kelly's Homestead",
			"Price": "3.00 EUR",
			"Units": "6 PC "
		}, {
			"Name": "Chang",
			"Supplier": "New Orleans Cajun Delights",
			"Price": "56.00 EUR",
			"Units": "40 PC"
		}

	]
}

Step – 3:  webapp/view/View1.view.XML

Now in View1.view.XML  I have defined a table and going to bind the above JSON data to that table.

The code goes as follows:

<mvc:View controllerName="navigationjson.controller.View1" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m">
	<App id="app">
		<pages>
			<Page title="Tableview">
				<content>
					<Table class="sapUiSizeCompact" id="table1" includeItemInSelection="true" items="{path: 'DataModel>/Objects'}" mode="MultiSelect"
						selectionChange="onselectionChange">
						<columns>
							<Column>
								<Label text="Product Name"/>
							</Column>
							<Column>
								<Label text="Supplier"/>
							</Column>
							<Column>
								<Label text="Price"/>
							</Column>
							<Column>
								<Label text="Units Ordered"/>
							</Column>
						</columns>
						<ColumnListItem press="onPress" type="Navigation">
							<Text text="{DataModel>Name}"></Text>
							<Text text="{DataModel>Supplier}"></Text>
							<Text text="{DataModel>Price}"></Text>
							<Text text="{DataModel>Units}"></Text>
						</ColumnListItem>
					</Table>
				</content>
			</Page>
		</pages>
	</App>
</mvc:View>

Step – 4:  webapp/manifest.json

Then define the router class and routes under sap.ui5, declare the JSON model under the Model like as “TableData”. then declare its alias name under the datasources  like “tableData_alias”

{
	"_version": "1.1.0",
	"sap.app": {
		"_version": "1.1.0",
		"id": "navigationjson",
		"type": "application",
		"i18n": "i18n/i18n.properties",
		"applicationVersion": {
			"version": "1.0.0"
		},
		"title": "{{appTitle}}",
		"description": "{{appDescription}}",
		"sourceTemplate": {
			"id": "ui5template.basicSAPUI5ApplicationProject",
			"version": "1.32.0"
		},
		
		"dataSources": {
			"tableData_alias": {
				"uri": "model/Object.json",
				"type": "JSON"
			}
		}
	},
	"sap.ui": {
		"_version": "1.1.0",
		"technology": "UI5",
		"icons": {
			"icon": "",
			"favIcon": "",
			"phone": "",
			"phone@2": "",
			"tablet": "",
			"tablet@2": ""
		},
		"deviceTypes": {
			"desktop": true,
			"tablet": true,
			"phone": true
		},
		"supportedThemes": ["sap_hcb", "sap_bluecrystal"]
	},
	"sap.ui5": {
		"_version": "1.1.0",
		"rootView": {
			"viewName": "navigationjson.view.View1",
			"type": "XML"
		},
		"dependencies": {
			"minUI5Version": "1.30.0",
			"libs": {
				"sap.ui.core": {},
				"sap.m": {},
				"sap.ui.layout": {}
			}
		},
		"routing": {
			"config": {
				"routerClass": "sap.m.routing.Router",
				"viewType": "XML",
				"viewPath": "navigationjson.view",
				"controlId": "app",
				"controlAggregation": "pages"

			},
			"routes": [{
					"pattern": "",
					"name": "View1",
					"view": "View1",
					"controlAggregation": "pages"
				},

				{

					"pattern": "View2/{selectedobj}",
					"name": "View2",
					"target": "View2",
					"controlAggregation": "pages"
				}
			],
			"targets": {
				"View1": {
					"viewName": "View1"

				},
				"View2": {
					"viewName": "View2"

				}
			}

		},

		"contentDensities": {
			"compact": true,
			"cozy": true
		},
		"models": {
			"i18n": {
				"type": "sap.ui.model.resource.ResourceModel",
				"settings": {
					"bundleName": "navigationjson.i18n.i18n"
				}
			},
			"tableData": {
				"type": "sap.ui.model.json.JSONModel",
				"dataSource": "tableData_alias"
			}
		},
		"resources": {
			"css": [{
				"uri": "css/style.css"
			}]
		}
	}
}

This below code  snippet is for declaring the JSON model added in the manifest.json file shown in above.

	"tableData": {
				"type": "sap.ui.model.json.JSONModel",
				"dataSource": "tableData_alias"
			}

Here we are declaring path of JSON Model added in the manifest.json file shown in above.

	"dataSources": {
			"tableData_alias": {
				"uri": "model/Object.json",
				"type": "JSON"
			}
		}

Step – 5: 

First, we need to initialize router in component.js 

sap.ui.define([
	"sap/ui/core/UIComponent",
	"sap/ui/Device",
	"navigationjson/model/models",
	"sap/ui/model/json/JSONModel"

], function(UIComponent, Device, models,JSONModel) {
	"use strict";

	return UIComponent.extend("navigationjson.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);
	   /***Create the model and load data from the local JSON file ***/
		       //      var oModel = new JSONModel("./model/Object.json");
		       //      oModel.setDefaultBindingMode("OneWay");
		
			// set the device model
			this.setModel(models.createDeviceModel(), "device");
			this.getRouter().initialize();
		}
	});

});

 

Create Device Model for the app:  webapp/model/model.js

Here, we need to create device model for the application

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;
		}

	};
});

 

Step – 6:  webapp/controller/View1.controller.js

Here, we need to get the Global JSON Model from the manifest.json file. The code like as below.

sap.ui.define([
	"sap/ui/core/mvc/Controller"

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

	return Controller.extend("navigationjson.controller.View1", {
		onInit: function() {
			/*this below code for get the JSON Model form Manifest.json file*/
			var dataModel = this.getOwnerComponent().getModel("tableData");
			this.getView().setModel(dataModel, "DataModel");

		},
		/*this below code for cilck on row the the page will navgate to next View*/
		onPress: function(oEvent) {
			var spath = oEvent.getSource().getBindingContext("DataModel").getPath();
			var selectedPath = JSON.stringify(oEvent.getSource().getBindingContext("DataModel").getProperty(spath));
			var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
			oRouter.navTo("View2", {
				"selectedobj": selectedPath
			});
		},
		/*this below code for selected the row data and then navigate to next View */
		onselectionChange: function() {
			var contexts = this.getView().byId("table1").getSelectedContexts();
			var items = contexts.map(function(c) {
				return c.getObject();
			});
			var selectedItems = JSON.stringify(items);
			var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
			oRouter.navTo("View2", {
				"selectedobj": selectedItems
			});

		}
	});

});

Step – 7:

the View1 output like as below.

 

Step – 8: webapp/view/View2.view.XML

Now we are going to perform Navigate selected row data for the above output. So, I have created another view View2.view.xml as shown below.

<mvc:View controllerName="navigationjson.controller.View2" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m">
	<App id="app">
		<pages>
			<Page navButtonPress="onNavBack" showNavButton="true" title="Tableview2">
				<content>
					<Table class="sapUiSizeCompact" id="abc" items="{path: 'navigationModel>/Objects'}">
						<columns>
							<Column width="11rem">
								<Label text="Product Name"/>
							</Column>
							<Column width="11rem">
								<Label text="Supplier"/>
							</Column>
							<Column hAlign="End" width="6rem">
								<Label text="Price"/>
							</Column>
							<Column hAlign="End" width="15rem">
								<Label text="Units Ordered"/>
							</Column>
						</columns>
						<ColumnListItem press="onPress" type="Navigation">
							<Text text="{navigationModel>Name}"></Text>
							<Text text="{navigationModel>Supplier}"></Text>
							<Text text="{navigationModel>Price}"></Text>
							<Text text="{navigationModel>Units}"></Text>
						</ColumnListItem>
					</Table>
				</content>
			</Page>
		</pages>
	</App>
</mvc:View>

 

Step – 9:  webapp/controller/View2.controller.js

Now we are writing code for second view controller View2.controller.js as shown below.

sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel"
], function(Controller, JSONModel) {
	"use strict";

	return Controller.extend("navigationjson.controller.View2", {
		onInit: function() {
			var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
			oRouter.getRoute("View2").attachMatched(this._onObjectMatched, this);
		},
		_onObjectMatched: function(oEvent) {
			var selectedArguments = oEvent.getParameter("arguments");
			var selectedRecord = JSON.parse(selectedArguments.selectedobj);
		
			var obj = {
				"Objects": selectedRecord
			};
			var navigationobjModel = new JSONModel();
			navigationobjModel.setData(obj);
			this.getView().setModel(navigationobjModel, "navigationModel");
		},
		onNavBack: function() {
			window.history.go(-1);
		}

	});

});

Step – 10:Final output looks like below:

 

Have a nice Day!

 

 

Thanks & Regards,

Upender reddy DAREDDY,

MOURI Tech Pvt.Ltd

www.mouritech.com

5 Comments
You must be Logged on to comment or reply to a post.
    • Hi Seyed Ismail,

      Thanks for notifying me. here is the piece of code, you can replace with existing 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;
      		}
      
      	};
      });

      As well as I have updated the blog information.

       

  • Hi Upender,

    I am new to sapui5. I am also 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 have followed  steps mentioned above but 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>

     

    Regards,

    Parag

    •  

      Hi Parag

      In the View1.xml:

       

      you are using the wrong model, change the binding path of model to DataModel.

      like <Input value=”DataModel>/Form/0/first” />

       

      Thanks,

      Upender