Search code examples
javascriptodatasapui5abap

SAPUI5 - oModel.create is not a function


I'm trying to build a simple SAPUI5 application that basically lists a table filled with employee data (ID, name, address). enter image description here

However, I cannot add new employee because I always get the same error:

Uncaught TypeError: oModel.create is not a function at constructor.Save (EmpDetails.controller.js?eval:87)

Could you please help me solve this? I don't understand why the create function does not work given that it is connected to the model and should work fine (just like the GET-method that fills the table on initialization). Here is my code for the controller:

sap.ui.controller("zemployee_crud.EmpDetails", {

	onInit: function() {
		var sServiceUrl = "proxy/http/<server>:<port>/sap/opu/odata/sap/ZEMPLOYEE_SRV";
		var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true);

		var oJsonModel = new sap.ui.model.json.JSONModel();

		oModel.read("/EmployeeSet",null,null,true,function(oData,response){
			oJsonModel.setData(oData);
		});

		sap.ui.getCore().setModel(oJsonModel);
	},

	Save: function() {
		var oId = sap.ui.getCore().byId("Id").getValue();
		var oName = sap.ui.getCore().byId("Name").getValue();
		var oAddress = sap.ui.getCore().byId("Address").getValue(); 
		
		var oEntry = {};

		oEntry.Empid = oId;
		oEntry.Empname = oName;
		oEntry.Empadd = oAddress;
		
		var oModel = sap.ui.getCore().getModel();
		
		oModel.create("/EmployeeSet", oEntry, null, function (response) {
			// success message
			// table reload
		}, function (Error) {
			//show error 
		});
	}
});


Solution

  • Your JSONModel does not support create. You have to use an ODataModel.

    First you have to store your model somewhere

    var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true);
    this.getView().setModel(oModel);
    

    Then later you can access the model and call create.

    var oModel = this.getView().getModel();
    oModel.create(...);
    

    This is the most simple approach. I strongly suggest getting to know the framework:

    • sap.ui.model.odata.ODataModel is deprecated. Use sap.ui.model.odata.v2.ODataModel.
    • Declare your model in your manifest.json. Then all controllers can access it.
    • In most cases you don't need an extra JSONModel. You can directly use the ODataModel and show it in your list
    • Setting any model (JSON or OData) to the core (sap.ui.getCore().setModel()) is not necessary. The core is on a very high/global level. Mostly it's enough to set it on an app/component level (either in your manifest.json or in the Component.js) or on a controller level.

    I also strongly suggest doing the official walkthrough. It takes 1-2 days to complete but after that you are almost a pro since it answers 95% of all beginner questions.