Thursday, April 13, 2017

SAP Models and oData Model Consumptions



Model


·      A model in the Model View Controller concept holds the data and provides methods to retrieve the data from the database and to set and update data.



Json Model:
                              Var Data = {
                                                            "Carrier": "",
                                                            "TUNum": "",
                                                            "Shipdate": "",
                                                            "CarrierTxt": "",
                                                            "TUNumExt": "",
                                                            "PackMaterial":"",
                                                            "meansoftransportaion": "",
                                                            "carrierstate": "Error",
                                                            "Shipdatestate": "Error",
                                                            "meansoftransportaionstate": "Error"
                                             };
Ø  Java Script Object Notation Model
Ø  Client Side Model
Ø  Creating new Json Model

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


Ø SetData

oModel.SetData(Data);

Ø Setting Model to The View
Var oView= this.getView();
oView.setModel(oModel,”CarrierModel”);

Ø Get Data

oView.getModel(“CarrierModel”).getData();

Ø Binding to any Control


     <Text text="{CarrierModel>/ TUNum}"/>

     <Button title="{CarrierModel>/ CarrierTxt}" press=”handleaddcontrol”/>

Ø Get Current Object

curobj=evt.getSource().getBindingContext("pickingmodel").getObject();




Ex: var data={

“Containers”:[{
           “fname”:””,
           “lname”:””
           },
           {
           “fname”:””,
           “lname”:””
           },
           {
           “fname”:””,
           “lname”:””
           }]
}




 
 
 
 
 
 
 
 
 
 
 
Var data={
    company: {
        name: "Treefish Inc",
        info: {
            employees: 3,
        },
        contacts: [
            {
                name: "Barbara",
                phone: "873"
            },
            {
                name: "Gerry",
                phone: "734"
            },
            {
                name: "Susan",
                phone: "275"
            }
        ]
    }
}


Ø Absolute binding paths within this model
Ex:
        /company/name
     /company/info/employees
     /company/contacts
 
Ø Relative binding paths within the "/company" context:

Ex:

          name
                      info/employees
                      contacts

     
Ø Relative binding paths within an aggregation binding of "/company/contacts":
    
     Ex:
          name
                      phone
 
 
 
Resource Model:
 
Ø mainly to provide texts in different languages.
Ø Create New Resource model
 
var oModel = new sap.ui.model.resource.ResourceModel({bundleName:"myBundle",locale:"en"});
 
 
Ø I18n_en.properties file
     CLOSE_BUTTON_TEXT=Close
     OPEN_BUTTON_TEXT=Open
     CANCEL_BUTTON_TEXT=Cancel
Ø Binding model to the View
Ex:
<Button text="{i18n>CLOSE_BUTTON_TEXT}"/>
OData Model:


  "serviceConfig": {
"name": "Z_MMWM_FIORI_SHIPPING_SRV",
"serviceUrl": "/sap/opu/odata/sap/Z_MMWM_FIORI_SHIPPING_SRV/"
           }


Ø Server side Model
Ø Creating new Model
Var oModel= new sap.ui.model.odata.ODataModel(sUrl, true);

Ø Setting Model to The View
Var oView= this.getView();
oView.setModel(oModel);

Ø Adding Busy Dialog when OData request calls

var busyDialog = busyDialog ? busyDialog : sap.ui.core.BusyIndicator;
      oModel.attachRequestSent(function() {
               busyDialog.show(1000);

           });
      oModel.attachRequestCompleted(function() {
               busyDialog.hide();

           });

Ø Get Model in View Controller
Var oDataModel= this.getView().getModel();

 Create Service Call:
Ø Syntax
Ex
create(sPath, oData, mParameters?)

Ø Trigger a POST request to the odata service


EX:

var spath="/TUSet";
oDataModel.create(spath, payload, {
     success: function(oData, oResponse) {
sap.m.MessageBox.show("TU Successfully Created.", {    icon: sap.m.MessageBox.Icon.SUCCESS,
           title: "Success",
           actions: [sap.m.MessageBox.Action.OK],
           onClose: function(oAction) {}
           });
                           me._oRouter.navTo("ShippingMaster", {
                from: "ShippingCreate"
                           }, false);
                      },
     error: function(error, resp1, resp2) {
     sap.m.MessageBox.show("TU creation failed", {
     icon: sap.m.MessageBox.Icon.ERROR,
     title: "Error",
details:JSON.parse(error.response.body).error.message.value,
     actions: [sap.m.MessageBox.Action.OK]
                           });

                      }
     });

Call Function:
Ø Syntax:
callFunction(sFunctionName, mParameters?)

Ø Trigger a request to the function import odata service


Ex :

<FunctionImport Name="LoadTU" ReturnType="Z_MMWM_FIORI_SHIPPING_SRV.TULoad" m:HttpMethod="POST">

<Parameter Name="TUNum" Type="Edm.String" Mode="In"/>
<Parameter Name="TUActNum" Type="Edm.String" Mode="In"/>

</FunctionImport>

Ø call Function Example



var me = this;
var overviewmodel = me.getView().getModel("Overviewmodel").getData();
var odatamodel = this.getView().getModel();
    var tunum = overviewmodel.TUNum;
    var tuactnum = overviewmodel.TUActNum;
   
    odatamodel.callFunction("/LoadTU", {
               method: "POST",
               urlParameters: {
                   "TUNum": tunum,
                   "TUActNum": tuactnum
               },
success: function(oData, oResponse) {
                  me.getView().getModel().refresh(true);
            
               },
    error: function(error) {
                
               }
    });


GET SERVICE CALL:

Ø Trigger a GET request to the odata service that was specified in the model constructor.
Ø Syntax:
      read(sPath, mParameters?)

Example:
          Var odata= this.getView().getModel();
    var path="/PackagingMaterialSet";
    odata.read(path,{
    success:function(oData,oRes){
   
me.getView().getModel("PackingMaterialsetmodel").setData(oData);
               me.getView().getModel("PackingMaterialsetmodel").updateBindings(true);
               },
error: function(error) {

               }
           });

Batch Call:

Ø Syntax:
createBatchOperation(sPath, sMethod, oData?, oParameters?)
Ø Creates a single batch operation (read or change operation) which can be used in a batch request.

         var batchChanges = [];
          var oDataModel = this.getView().getModel();
jQuery.each(items, function createBatch(idx, item) {
batchChanges.push(oDataModel.createBatchOperation("DeliveryAssignmentSet", "POST", item));
                              });
jQuery.each(delitems, function DeleteBatch(idx, delitem) {

var delitempath="DeliveryAssignmentSet(TUNum='" + delitem.TUNum + "',TUActNum='" + delitem.TUActNum + "',SeqNum='" + delitem.SeqNum + "')";
batchChanges.push(oDataModel. createBatchOperation (delitempath, "DELETE"));
                             

});
                              //Calling Batch Service
oDataModel.addBatchChangeOperations(batchChanges);
oDataModel.submitBatch(function(success) {
                                        var bresponse = success.__batchResponses[0];
                                        if (bresponse.__changeResponses) {
                                                  var scres = bresponse.__changeResponses[0].data;
                                                  sap.m.MessageBox.show(scres, {
                                                            title: "Success",
                                                            icon: sap.m.MessageBox.Icon.SUCCESS,
                                                            actions: [sap.m.MessageBox.Action.OK],
                                                            details: scres,
                                                            onClose: function(oAction) {
                                                                      if (oAction === "OK") {
                                                                                          me.getView().byId("idIconTabBar").setSelectedKey("OBD");
                                                                                          me.getView().byId("idIconTabBar").setExpanded(true);
                                                                                          me.getView().byId("idIconTabBar").fireSelect({
                                                                                                    selectedKey: "OBD"
                                                                                          });
                                                                      }
                                                            }

                                                  });
                                                 
                                        } else if (bresponse.response) {
                                                  var responseBody = success.__batchResponses[0].response.body;
                                                  var successObj = JSON.parse(responseBody);
                                                  var message = successObj.error.message.value;
                                                  sap.m.MessageBox.show(message, {
                                                            title: "ERROR",
                                                            icon: sap.m.MessageBox.Icon.ERROR,
                                                            actions: [sap.m.MessageBox.Action.OK]
                                                  });
                                        }
                              }, function(error) {
                                        var resBody = error.response.body;
                                        var errObj = JSON.parse(resBody);
                                        var message = errObj.error.message.value;
                                        sap.m.MessageBox.show(message, {
                                                  title: "ERROR",
                                                  icon: sap.m.MessageBox.Icon.ERROR,
                                                  actions: [sap.m.MessageBox.Action.OK],
                                                  details: message
                                        });

                              }, false);






Update Service Call:


Ø  Syntax:
    update(sPath, oData, mParameters?)

Ø Trigger a PUT/MERGE request to the odata service that was specified in the model constructor.

Example:

          var updatedata= {
                              "TUNum":tunum,
                              "TUActNum":tuactnum,
                              "ShipDate":shipdate
                              };
var spath = "/TUSet(TUNum='" + tunum + "',TUActNum='" + tuactnum + "')";
odata.update(spath,updatedata, {
                               async: true,
          success: function(oData, oRes) {
                                         me._oRouter.navTo("ShippingMaster", false);
                                        },
          error: function(data) {
                                                  // oViewModel.setProperty("/busy", false);
                                        }
                              });
Delete Service Call:

Syntax: remove(sPath, mParameters?)


Ø Trigger a DELETE request to the odata service that was specified in the model constructor.
Example

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


var delpath = "/StoreBayArticleSet(StoreID='" + saveData.StoreID + "',BayLocation='" + saveData.BayLocation + "',Article='" +
saveData.Article + "')";
oModel.remove(delpath, {
success: function(oData, oResponse) {

}
                              error: function(data) {
                                                   
                                        }
                              });

   


           

Notes


var aFilters = [];
var filter1 = new Filter("StoreID", FilterOperator.EQ, Store);
var filter2 = new Filter("Dept", FilterOperator.EQ, departmentId);
aFilters.push(filter1, filter2);
var baylistModel = this.getOwnerComponent().getModel("baylistModel");
oModel.read(sPath, {
filters: aFilters,
async: true,
success: function(oData, oResponse) {


    

No comments:

Post a Comment