Skip to Content

The model is the most import component in SAP UI5 application. The purpose of this post is to show you how to use it in different manner.

Playing with Path

All example are based on this data source structure

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

How to retrieve data from the model?

First, you have to find the model instance, then call the following method:

getProperty(sPath, oContext?)

sPath is important here, because it will indicate the wanted value.

Example 1: Get the value of value attribute

// Accès direct
Var oData = oModel.getProperty(« /menu/value ») ;
// Accès déroutée
Var oData = oModel.getProperty(“/menu”);
oData.value;

Example 2: Get the onClick value from the second line

// Accès direct
Var oData = oModel.getProperty(« /menu/popup/menuitem/1/onclick ») ;
// Accès dérouté
Var oData = oModel.getProperty(“/menu”);
oData.popup.menuitem[1].onclick;

How to write data into the model?

Example 3: Change the id value attribute

oModel.setProperty(« /menu/value », newValue);

How to loop inside a node?

Example 4: Loop inside menuitem node

var oData = oModel.getProperty(“/menu/popup/menuitem”);
If (oData instanceof Array){
  oData.foreach( function(oValue, i){
    //…
  });
}

Conclusion

Hope you will find those tips interesting.

Enjoy 😉

To report this post you need to login first.

26 Comments

You must be Logged on to comment or reply to a post.

    1. Former Member

      Check your path. Is it correct? Try to debug in Google Chrome console: get all content of your oData like this:

      oData.getData();

      or

      oData.oData;

      Maybe your oData is empty?

      (0) 
      1. Former Member

        Seems it’s not intended to be used in index.html …

        here is the example, json taken from the original post:

                        var jsonModel = new sap.ui.model.json.JSONModel (“data.json”, “”, false);    
                        sap.ui.getCore().setModel(jsonModel);
                       
                        alert( ‘test ‘);

                        var title = jsonModel.getProperty(“/menu/id”);   
                       
                        alert(title);

        If I remove “alert(‘test’)” – title is “undefined”, if it’s there, everything is ok.

        I’ve tried to hook up on events of jsonmodel, but it doesn’t help either.

        (0) 
        1. Former Member

          Your example is not correct. I understand you are trying to get json data from file “data.json”. But there are no method to load data to json model.

          For example, data loaded to jsonModel from string by method setJSON:

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

          jsonModel.setJSON(‘{“menu”: {“id”: “id1″,”ad”: “ad1″,”bd”: “bd1”}}’);

          var title = jsonModel.getProperty(“/menu/id”);

          alert(title);

          You can load data from file by method loadData.

          Usefull information about json model and json methods is here.

          (0) 
          1. Former Member

            Solved:

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

            jsonModel.loadData(“data.json”, “”, false);

            I’m using api 1.17, and seems it’s not yet stable enougth. In embedded doc there are params similar to loaddata in constructor, but seems they aren’t working as expected. Still thanks for giving an idea.

            (0) 
    1. Joseph BERTHE Post author

      Hello,

      Are you sure about your property name (case sensitive and so on) ? Are you starting with the right path (sometime we should start by ‘/’ when the property is in the root) ? When you do a : console.log(oModel);

      what it shows you in oData variable ?

      Regards,

      Joseph

      (0) 
  1. Former Member

    Hi,

    Can we read oData Model in the similar way as done here for JSON Model ?

    I tried reading it but it returns undefined. Following is my code:

    var oModelChart = new sap.ui.model.odata.ODataModel(“http://xyz.com:8002/sap/opu/odata/SAP/MYSERVICE/“,true,”uid”,”pwd“);

     

    oChartX.setModel(oModelChart);

     

    oModelChart.getProperty(“/MyCollection/0/Dept_ID”);

    Can any one help ?

    (0) 
    1. Joseph BERTHE Post author

      Hi,

      Try using read() function from model:

              var oModel = sap.ui.getCore().getModel();

              var oProp = oModel.read(“/MyCollection/0/Dept_ID“, null, null, true, function(oData, oResponse){

                  console.log(oResponse);

              });

      Regards,

      (0) 
      1. Ravi kiran R

        Hi Joseph,

        I tried the above method, i am able to see the data, thing is how do i set the data to the model as i see setData property of odata model is deprecated. Below is the code for your reference. Thanks in advance.

        //////////////////////

        var oModel = new sap.ui.model.odata.ODataModel(“proxy/http/services.odata.org/V4/TripPinServiceRW”, true);

          sap.ui.getCore().setModel(oModel,”Model”);

          oModel.read(“/People”, null, null, true,

          function(value, response){

          //oModel.setProperty(“People” ,JSON.parse(response.body)); 

              console.log(JSON.parse(response.body));

            },

              function(err){

           alert(“Error”);

          }

          );

        //////////////////////

        Regards,

        Ravikiran

        (0) 
    1. Joseph BERTHE Post author

      Hello,

      To delete an array from model  do the following :

      1/ Read the property wich contains the array

         e.g. var oProp = oModel.getProperty(“/”);

      2/ Then delete the array

        e.g. oProp[“myArray”] = [];

      3/ Set the property

        e.g. oModel.setProperty(“/”, oProp);

      It should work.

      Regards

      (1) 
    1. Joseph BERTHE Post author

      Hello,

      I guess you are talking about a Menu control (sap.ui.commons.Menu) in wich is binded to a Model.

      If it is true, then, you have to do the following :

      1/ Read the property wich contains the menuitems array

         e.g. var oProp = oModel.getProperty(“/”);

      2/ Push new item to the array

        e.g. oProp[“myItemsArray”].push({“text” : “blabla”, “icon”: “”images/new.gif”});

      3/ Set the property

        e.g. oModel.setProperty(“/”, oProp);

      regards,

      (1) 
          1. Former Member

            Joseph,

            I am trying out code like this

            var data=”{‘menu’: {“;

              data += “‘id’: ‘file’,”;

              data += “‘value’: ‘File’,”;

              data += “‘popup’: {“;

              data +=     “‘menuitem’: [“;

              data += “{‘value’: ‘New’, ‘onclick’: ‘CreateNewDoc()’},”;

              data += “{‘value’: ‘Open’, ‘onclick’: ‘OpenDoc()’},”;

              data += “{‘value’: ‘Close’, ‘onclick’: ‘CloseDoc()’}”;

              data += ”    ] “;

              data += ”     }”;

              data +=    ”  }}  “;

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

            console.log(oModel.getProperty(“/menu”));

            But I am getting undefined is there anything wrong with what I do?

            (0) 
            1. Krishnakant Joshi

              Hi sagar,

              It seems your JSON is malformerd.

              It should look like

              {“RESULTS”:[

                             

                             {“RESULT”:{“TGROUP”:”0002″,”TGROUP_TXT”:”Stagiairs”}},

                             {“RESULT”:{“TGROUP”:”0003″,”TGROUP_TXT”:”Starters/pas afgestudeerden”}},

                             {“RESULT”:{“TGROUP”:”0004″,”TGROUP_TXT”:”Leidinggevenden/directie”}},

                             {“RESULT”:{“TGROUP”:”0005″,”TGROUP_TXT”:”Specialisten”}},

                             {“RESULT”:{“TGROUP”:”0006″,”TGROUP_TXT”:”ICT”}},

                             {“RESULT”:{“TGROUP”:”0007″,”TGROUP_TXT”:”Technici”}},

                             {“RESULT”:{“TGROUP”:”0008″,”TGROUP_TXT”:”Arbeiders”}},

                             {“RESULT”:{“TGROUP”:”0009″,”TGROUP_TXT”:”Zorg”}},

                             {“RESULT”:{“TGROUP”:”0010″,”TGROUP_TXT”:”Maatschappelijk werk”}},

                             {“RESULT”:{“TGROUP”:”0011″,”TGROUP_TXT”:”Hoger onderwijs”}},

                             {“RESULT”:{“TGROUP”:”0012″,”TGROUP_TXT”:”Kleuter/lager onderwijs”}},

                             {“RESULT”:{“TGROUP”:”0013″,”TGROUP_TXT”:”Shared Service”}}]}

                             ;

              while concatenating strings you should use (Double Quotes) instead of (Single Quote )

              Please check the links below.

              jQuery.parseJSON() | jQuery API Documentation

              http://www.w3schools.com/json/json_eval.asp

              SAPUI5 with JSON or XML Data.

              Hope it will help. 🙂

              (0) 
            2. Krishnakant Joshi

              Hi sagar,

              Try this.

              var data =   ‘{‘;

                data +=  ‘”menu”: {‘;

                data += ‘”id”: “CC167”,’;

                data += ‘”value”: “CC167”,’;

                data += ‘”popup”: {‘;

                data +=   ‘”menuitem”: [{‘;

                data +=     ‘”value”: “new”,’;

                data +=     ‘”onclick”: “Beginning XNA”‘;

                data +=    ‘},’;

                data +=    ‘{‘;

                data +=    ‘”value”: “new”,’;

                data +=    ‘”onclick”: “Beginning XNA 20l”‘;

                data +=    ‘}]}}}’;

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

              var data1 = jQuery.parseJSON(data);

              oModel.setData(data1);

              alert(oModel.getProperty(“/menu/popup/menuitem/0/value”));

              Happy Learning 🙂

              (0) 
            3. Joseph BERTHE Post author

              Hello,

              In fact, Krishnakant Joshi is right.

              If you want to construct a JSon with Javascript the easiest way is :

              var myJSon = { “Attr1” : “Value”, “myArra” : [ { “Attr1” : “value” }, { “Attr2” : “value” }]};

              Here value can be the content of any variable.

              Regards,

              (0) 
  2. Former Member

    hi, I need to populate data in a table, later, complete and modify that data, and later save all data.

    here’s the code:

    —controller.js—

      populateData: function(oSHTable){

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

      aData = [

              {material: “Material 1”, cantUme: “10”, ok: false, fechaProd: “”, destino: “”},

              {material: “Material 2”, cantUme: “20”, ok: true, fechaProd: “”, destino: “”},

              {material: “Material 3”, cantUme: “50”, ok: false, fechaProd: “”, destino: “”},

              {material: “Material 4”, cantUme: “65”, ok: true, fechaProd: “”, destino: “”}

      ];

      oModel.setData({modelData: aData});

      sap.ui.getCore().setModel(oModel);

      oSHTable.setModel(oModel);

      },

      save: function (){

      console.info(sap.ui.getCore().getModel().getProperty(“/modelData”));

      //I need to iterate “modelData” and obtain each values for “material”, “cantUme”, “fechaProd” an so on

      for(var i=0; i<sap.ui.getCore().getModel().getProperty(“/modelData”).length; i++){

      //clearly, it doesn’t work

      console.info(“material ” + [i] + ” ” + sap.ui.getCore().getModel(“/modelData/material”));

      // how can I get materials values???

      };

      },

      onInit: function(){

      },

    —log—

    material 0 undefined

    material 1 undefined

    material 2 undefined

    material 3 undefined

    regards

    (0) 

Leave a Reply