This blog explains how to create a CRUD application using SAPUI5 Using Odata Model.

Blog Content :

Creating the User Interface

  • Creating the project
  • Setting up the SAPUI5 bootstrap and required libraries
  • Creating the view components
  • Implementing the Controller’s methods

Read

Create

Update

Delete

Prerequisites

  • You have to installed the SAPUI5 Application Development Tool into your Eclipse
  • UI Development Toolkit for HTML5 Version SAPUI5 1.16

Steps to be followed :-

  1. 1. Create the Project :

create a SAPUI5 MVC project in eclips

It shows like below mentioned in the picture :

Picture1.gif

Setting up the SAPUI5 bootstrap and required libraries in index.html file

Add the required libraries in the  “data-sap-ui-libs” tag

Picture2.jpg

  1. 2. Creating the view components and fetching the Bank data :

Add following code in to the bank.view.js

  1. sap.ui.jsview(“bankcrud.bank”, {

/** Specifies the Controller belonging to this View.

* In the case that it is not implemented, or that “null” is returned, this View does not have a Controller.

* @memberOf bankcrud.bank

*/

getControllerName : function() {

return “bankcrud.bank”;

},

/** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.

* Since the Controller is given to this method, its event handlers can be attached right away.

* @memberOf bankcrud.bank

*/

createContent : function(oController) {

var layout = new sap.ui.commons.layout.MatrixLayout({

id : ‘matrix4’,

layoutFixed : false,

});

var appHeader = new sap.ui.commons.ApplicationHeader(‘appHeader’,   {

logoText : “Bank Application”,

displayLogoff : false,

displayWelcome : true,

userName : “Welcome”

});

layout.createRow(appHeader);

var rPannel = new sap.ui.commons.Panel(‘rPannel’, {

text : “BankCollection List”,

});

var oTable = new sap.ui.table.DataTable({

id : “bankTableID”,

title: “Bank CRUD Application”,

width : “100%”,

visibleRowCount: 10,

selectionMode : sap.ui.table.SelectionMode.Single,

//setEditable : false,

rowSelectionChange : function(oEvent) {},

toolbar: new sap.ui.commons.Toolbar({

                 items: [

                      new sap.ui.commons.Button({

                                text: “Create”,

                                press: function() {

                                     oController.Create();

                                }

                      }),

                      new sap.ui.commons.Button({

                             text: “Update”,

                                press: function() {

                                     oController.Update();

                                }

                      }),

           new sap.ui.commons.Button({

                   text: “Delete”,

                    press: function() {

                   oController.Delete();

                                }

                      }),

                     ]

}

});

oTable.addColumn(new sap.ui.table.Column({

label : new sap.ui.commons.Label({

text : “Bank ID”

}),

template : new sap.ui.commons.TextField().bindProperty(“value”,

“bankID”),

sortProperty : “bankID”

}));

oTable.addColumn(new sap.ui.table.Column({

label : new sap.ui.commons.Label({

text : “Bank Country”

}),

template : new sap.ui.commons.TextField().bindProperty(“value”,

“bankCountry”),

sortProperty : “bankCountry”

}));

oTable.addColumn(new sap.ui.table.Column({

label : new sap.ui.commons.Label({

text : “Bank Name”

}),

template : new sap.ui.commons.TextField().bindProperty(“value”,

“bankName”),

sortProperty : “bankName”

}));

oTable.addColumn(new sap.ui.table.Column({

label : new sap.ui.commons.Label({

text : “Region”

}),

template : new sap.ui.commons.TextField().bindProperty(“value”,

“region”),

sortProperty : “region”

}));

oTable.addColumn(new sap.ui.table.Column({

label : new sap.ui.commons.Label({

text : “Street”

}),

template : new sap.ui.commons.TextField().bindProperty(“value”,

“street”),

sortProperty : “street”

}));

oTable.addColumn(new sap.ui.table.Column({

label : new sap.ui.commons.Label({

text : “City”

}),

template : new sap.ui.commons.TextField().bindProperty(“value”,

“city”),

sortProperty : “city”

}));

// Add table to the Panel

rPannel.addContent(oTable);

// Add panel to the Layout

layout.createRow(rPannel);

// Display Layout

this.addContent(layout);

}

});

Then bind the bank table in controller file. Add the  following code in to theonInit function

onInit: function() {

//Initialize the Model

var oModel = new sap.ui.model.odata.ODataModel( http://domain_name/sap/opu/odata/sap/Z_TM_BANK_SRV,false, “Username”, “Password”);

//Set the Model to the Table

var oTable = sap.ui.getCore().byId(“bankTableID”);

oTable.setModel(oModel);

// Filter the DATA

var FilterOperator = sap.ui.model.FilterOperator;

var filter = new sap.ui.model.Filter(“bankCountry”,FilterOperator.EQ, “AR”);

//Bind the Data to the Table

oTable.bindRows(“/BankCollection”, null, null,[ filter ]);

},

Output :

After binding the table :

Create Operation :

  1. 1. Add the button in view file (already created-in view file)
  2. 2. Create the function for create operation in controller file

Add the following code mentioned below :

Create: function() {

// Create a dialog to get the information of the bank to be created

var oDialog = new sap.ui.commons.Dialog(“Dialog”, {

    modal: true,

closed: function(oControlEvent){

  sap.ui.getCore().getElementById(‘Dialog’).destroy();

     }

  });

  oDialog.setTitle(“New Bank Collection”);

  // Create a layout to place the controls in the dialog

  var oLayout = new sap.ui.commons.layout.MatrixLayout({

columns: 2,

width: “100%”

  });

  // Create text field for the bankCountry

  var oTF = new sap.ui.commons.TextField(“tbankCountry”, {

          tooltip: ‘Bank Country’,

          editable: true,

          width: ‘200px’,

        required: true

  });

var oLabel = new sap.ui.commons.Label(“lbankCountry”, {

    text: ‘Bank Country’,

   labelFor: oTF

  });

// Create the first row

  oLayout.createRow(oLabel, oTF);

  // Create text field for the bankID

  oTF = new sap.ui.commons.TextField(“tbankID”, {

tooltip: ‘Bank ID’,

   editable: true,

required: true,

width: ‘200px’

  });

oLabel = new sap.ui.commons.Label(“lbankID”, {

    text: ‘Bank ID’,

labelFor: oTF

});

  oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tbankName”, { 

          tooltip: ‘Bank Name’,

             editable: true,

          required: true,

          width: ‘200px’

  });

  oLabel = new sap.ui.commons.Label(“lbankName”, {

   text: ‘Bank Name’,

  labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tregion”, {

      tooltip: ‘Region Name’,

          maxLength:3,

          editable: true,

               width: ‘200px

  });

  // Label for the last name field

  oLabel = new sap.ui.commons.Label(“lregion”, {

          text: ‘Region Name’,

          labelFor: oTF

  });

  // Create the 4th row

  oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tstreet”, {

tooltip: ‘Street Name’,

editable: true,

width: ‘200px’

});

  oLabel = new sap.ui.commons.Label(“lstreet”, {

       text: ‘Street Name’,

     labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tcity”, {

     tooltip: ‘City Name’,

     editable: true,

       width: ‘200px’

});

  oLabel = new sap.ui.commons.Label(“lcity”, {

        text: ‘City Name’,

        labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

// Add the layout to the dialog

  oDialog.addContent(oLayout);

// Add a button to post the bank‘s data to the odata interface

  oDialog.addButton(new sap.ui.commons.Button({text: “Save”, press:function(){

  // Add a button to post the bank‘s data to the odata interface

    var bankCountry_var    = sap.ui.getCore().getControl(“tbankCountry”).getValue(); 

         var bankID_var      = sap.ui.getCore().getControl(“tbankID”).getValue(); 

         var bankName_var  = sap.ui.getCore().getControl(“tbankName”).getValue(); 

         var region_var   = sap.ui.getCore().getControl(“tregion”).getValue(); 

         var street_var   = sap.ui.getCore().getControl(“tstreet”).getValue(); 

         var city_var    = sap.ui.getCore().getControl(“tcity”).getValue(); 

         OData.request 

         ({  

              requestUri:      http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection/?$filter=bankCountry eq’AR'”,  

                    method: “GET”,  

                    headers:  

                        {       

    “X-Requested-With”: “XMLHttpRequest”

   “Content-Type”: “application/atom+xml”

“DataServiceVersion”: “2.0”,          

“X-CSRF-Token”:“Fetch”                                 }                    

                 },  

                 function (data, response) 

                 { 

     header_xcsrf_token = response.headers[‘x-csrf-token’]; 

                  OData.request 

                  ({  

                       requestUri: 

                        http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection,  

                             method: “POST”,  

    headers: {   “X-Requested-With”: “XMLHttpRequest”,                        

“Content-Type”: “application/atom+xml”

     “DataServiceVersion”: “2.0”,  

“Accept”: “application/atom+xml,application/atomsvc+xml,application/xml”

“X-CSRF-Token”: header_xcsrf_token    },  

                             data:  

                                 {  

                              bankCountry: bankCountry_var,  

                              bankID:bankID_var, 

                              bankName:bankName_var, 

                              region: region_var, 

                              street: street_var, 

                              city: city_var, 

                      }  

                          },

                          function (data, response) 

                            {  

                           document.location.reload(true);

                                             $(“<div>Returned data “ + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”)); 

                            },  

                                   function (err)  

                                   { 

                                        $(“<div>Returned error “ + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”)); 

                                   } 

                  ); 

        },  

        function (err)  

                       { 

                            var request = err.request; // the request that was sent. 

                            var response = err.response; // the response that was received. 

                            alert(“Error in Get — Request “+request+” Response “+response); 

                       } 

        );                      

  oDialog.close();

}}));

  oDialog.open();

},

Output :

Before creation :

After Creation :


Update Operation :

  1. 1. Add the button in view file (already created-in view file)
  2. 2. Create the function for update operation in controller file

Add the following code mentioned below :

Update : function() {

var oTable = sap.ui.getCore().getElementById(‘bankTableID’);

       var i = oTable.getSelectedIndex();

       var ServiceURL = http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV;

       if (i == -1) {

               alert(“Please Select a row to Update”);

               return;

             }else if(i>=0){


   var selectedRow = oTable.getRows()[i];

var selectedId = selectedRow.getCells()[0].getValue();

        var selectedCount = selectedRow.getCells()[1].getValue();

        OData.read(ServiceURL + “/BankCollection(bankCountry='”

+ selectedCount + “‘,bankID='”

+ selectedId + “‘)”,

        function(response) {

      var oDialogu = new sap.ui.commons.Dialog(“Dialogu”, {

                  modal: true,

           closed: function(oControlEvent){

          sap.ui.getCore().getElementById(‘Dialogu’).destroy();

             }

  });

      oDialogu.setTitle(“Update Bank Collection”);

var oLayout = new sap.ui.commons.layout.MatrixLayout({

            columns: 2,

        width: “100%”

  });

  var oTF = new sap.ui.commons.TextField(“tbankCountry”, {

               tooltip: ‘Bank Country’,

    editable: false,

             value:response.bankCountry,

          width: ‘200px’,

        required: true

  });

var oLabel = new sap.ui.commons.Label(“lbankCountry”, {

        text: ‘Bank Country’,

      labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

   oTF = new sap.ui.commons.TextField(“tbankID”, {

          tooltip: ‘Bank ID’,

         editable: false,

          required: true,

          width: ‘200px’,

      value:response.bankID

  });

  oLabel = new sap.ui.commons.Label(“lbankID”, {

          text: ‘Bank ID’,

          labelFor: oTF

  });

         oLayout.createRow(oLabel, oTF);

      oTF = new sap.ui.commons.TextField(“tbankName”, {

          tooltip: ‘Bank Name’,

          editable: true,

          required: true,

          width: ‘200px’,

       value:response.bankName

  });

oLabel = new sap.ui.commons.Label(“lbankName”, {

          text: ‘Bank Name’,

          labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tregion”, {

          tooltip: ‘Region Name’,

          maxLength:3,

          editable: true,

          value:response.region ,

          width: ‘200px’

  });

  oLabel = new sap.ui.commons.Label(“lregion”, {

        text: ‘Region Name’,

         labelFor: oTF

  });

oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tstreet”, {

tooltip: ‘Street Name’,

editable: true,

width: ‘200px’,

  value:response.street

  });

  oLabel = new sap.ui.commons.Label(“lstreet”, {

text: ‘Street Name’,

    labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

  oTF = new sap.ui.commons.TextField(“tcity”, {

          tooltip: ‘City Name’,

          editable: true,

          value:response.city,

          width: ‘200px’

  });

  oLabel = new sap.ui.commons.Label(“lcity”, {

text: ‘City Name’,

labelFor: oTF

  });

  oLayout.createRow(oLabel, oTF);

  oDialogu.addContent(oLayout);

  oDialogu.addButton(new sap.ui.commons.Button({text: “Update”, press:function(){

  var bankCountry_var    = sap.ui.getCore().getControl(“tbankCountry”).getValue(); 

         var bankID_var      = sap.ui.getCore().getControl(“tbankID”).getValue(); 

         var bankName_var  = sap.ui.getCore().getControl(“tbankName”).getValue(); 

         var region_var   = sap.ui.getCore().getControl(“tregion”).getValue(); 

         var street_var   = sap.ui.getCore().getControl(“tstreet”).getValue(); 

         var city_var    = sap.ui.getCore().getControl(“tcity”).getValue(); 

  OData.request 

         ({  

  requestUri: 

               http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection/?$filter=bankCountry eq’AR'”,  

                    method: “GET”,  

                    headers:  

                        {       

“X-Requested-With”: “XMLHttpRequest”

“Content-Type”: “application/atom+xml”

“DataServiceVersion”: “2.0”,          

“X-CSRF-Token”:“Fetch”  

                          }                    

                 },  

                 function (data, response) 

                 { 

           header_xcsrf_token = response.headers[‘x-csrf-token’]; 

                  OData.request 

                  ({  

                       requestUri: http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection(bankCountry=‘”+ selectedCount + “‘,bankID='”+ selectedId+ “‘)”,  

                             method: “PUT”,  

                             headers: {  

     “X-Requested-With”: “XMLHttpRequest”,                        

“Content-Type”: “application/atom+xml”

“DataServiceVersion”: “2.0”,  

  “Accept”: “application/atom+xml,application/atomsvc+xml,application/xml”

  “X-CSRF-Token”: header_xcsrf_token  

  },   data:  

    {    bankCountry: bankCountry_var,  

      bankID:bankID_var, 

       bankName:bankName_var, 

       region: region_var, 

        street: street_var, 

       city: city_var, 

}  

                          },

   function (data, response) 

                            {

var oSubDialog = new sap.ui.commons.Dialog( {title: “Updated”,

                           content : [new sap.ui.commons.Label({

                           text : “Data Updated Successfully”

                           })]});

                           oSubDialog.open();

                           oSubDialog.addButton(new sap.ui.commons.Button({text: “OK”, press:function(){oSubDialog.close();}}));                       

                     

                                             $(“<div>Returned data “ + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”)); 

                                       //      document.location.reload(true);

                            },  

                                   function (err)  

                                   { 

                                        $(“<div>Returned error “ + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”)); 

                                   } 

                  ); 

        },  

   function (err)  

   var request = err.request; // the request that was sent. 

var response = err.response; // the response that was received. 

alert(“Error in Get — Request “+request+” Response “+response); 

                       } 

        );

  oDialogu.close();

     }}));

  oDialogu.open();    

        });

       }

    },

Output :

Before Update :

After Update :

Delete Operation

  1. 1. Add the button in view file (already created-in view file)
  2. 2. Create the function for create operation in controller file

Add the following code mentioned below :

Delete : function(oEvent) {

         var oTable = sap.ui.getCore().getElementById(‘bankTableID’);

  // Retrieve the selected index, i.e., the index of the selected row

      var i = oTable.getSelectedIndex();

var ServiceURL = http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV;

        if (i == -1) {

               alert(“Please Select a row to Delete”);

               return;

             }

             else if(i>=0){

        var selectedRow = oTable.getRows()[i];

        var selectedId = selectedRow.getCells()[0].getValue();

        var selectedCount = selectedRow.getCells()[1].getValue();

       }

     OData.request 

        ({  requestUri: http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection/?$filter=bankCountry eq’AR'”,  

                   method: “GET”,  

                   headers:  

                       {       

  “X-Requested-With”: “XMLHttpRequest”

   “Content-Type”: “application/atom+xml”

  “DataServiceVersion”: “2.0”,          

  “X-CSRF-Token”:“Fetch”  

                         }                    

                },

                function (data, response) 

                {  

                       header_xcsrf_token = response.headers[‘x-csrf-token’]; 

           OData.request 

           ({ 

            requestUri: http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection(bankCountry='”+ selectedCount + “‘,bankID='”+ selectedId+ “‘)”,

  method: “DELETE”,  

  headers: {  

                    “X-Requested-With”: “XMLHttpRequest”,                        

                    “Content-Type”: “application/atom+xml”

                    “DataServiceVersion”: “2.0”,  

                    “X-CSRF-Token”: header_xcsrf_token  

                         } 

                   },  

                     function (data, request) 

                     { 

                    document.location.reload(true);

                                 $(“<div>Returned data in Delete “ + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”)); 

                      },  

                    function (err)  

                    { 

                                 $(“<div>Returned error in Delete “ + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”));                              

                     } 

           ); 

       }, 

         function (err)  

             { 

                      var request     = err.request;  

                      var response = err.response;  

                      alert(“Error in Get — Request “+request+” Response “+response); 

             } 

       );       

    }

});

Output:

Before Delete :

Before delete four records are there in the table.


After Delete :

After delete three records are there in the table.

In this way we can create the desktop application in sapui5 with MVC structure and for the bacnkend data we  have to consume the Nerweaver Gateway Service.In this application Odta Model is used.

To report this post you need to login first.

74 Comments

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

      1. huang kaiwei

        hi:shruti

          

        Thank you for sharing, according to your article, the effect is a success.

        But there is a problem, updating the data, the table of contents can not be refreshed. I must go to  click browser refresh button to get the updated data

         

         

        Is there any way you can update the complete data, and can refresh the contents of the table in time?

         

            best regard!

        (0) 
        1. Seyed Ismail

          document.location.reload(true);

                                   $(“<div>Returned data ” + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”));

                                }, 

           

          Hi Huang, Its possible.

          Make sure you are using the above code inside function (data, request)

           

          Best Regards

          Seyed Ismail MAC

          (0) 
  1. Patrick Dean

    Great article, really good level of detail, and helped me with my second steps in Eclipse development. I’m using JSON rather than oData, but the design and layout bits in Eclipse are the same. Thanks for your contribution, and it’s a great example for others on SDN!

    (0) 
  2. Alexandre Felippes

    Hi Shruti, you don’t happen to have the whole project saved, do you?

     

    I’m still running into a few problems, if you do, would you mind sharing it?

     

    Thanks and Regards

     

    Alex

    (0) 
    1. shruti m Post author

      Hi Alexandre,

       

      In the blog I mentioned whole project.It’s working properly.Where you struck explain me in detail.

       

       

      Regards

      Shruti

      (0) 
      1. Alexandre Felippes

        Forget everything else, got pretty much everything to work, but the update part.

         

        I’m getting :

         

          Uncaught ReferenceError: selectedRow is not defined

        1. sap.ui.controller.Update
        2. sap.ui.table.DataTable.toolbar.sap.ui.commons.Toolbar.items.sap.ui.commons.Button.press
        3. sap.ui.base.EventProvider.fireEvent
        4. sap.ui.core.Element.fireEvent
        5. (anonymous function)
        6. sap.ui.commons.Button.onclick
        7. sap.ui.core.Element._callEventHandles
        8. sap.ui.core.Element._handleEvent
        9. sap.ui.core.UIArea._handleEvent
        10. f3
        11. Q.event.dispatch
        12. i.handle.j

        any tips on that?

         

        Thanks and Regards

         

        Alex

        (0) 
        1. shruti m Post author

          HI Alexandre,

           

           

          sorry for the late reply.

           

          define the “selectedRow” as variable like below mentioned.

           

             var selectedRow = oTable.getRows()[i];

           

           

          Regards

          Shruti

          (0) 
          1. Jim Giffin

            Shruti – great write up and information.   I have been trying the methods described, but if I scroll down on my table, select a row that was not on the original view and click the update button, I get an error that selectedRow does not exist. 

             

            It works great if I don’t scroll down in the table.  I am using Chrome (32) and I have also tested in Firefox (27).  Is this a known issue or am I doing something strange?

             

            Thank you.

            (0) 
            1. Jim Giffin

              I solved the update after scrolling problem.  I removed the oTable.getRows()[i] statement and used getContextByIndex(i) instead.

               

              //var selectedRow = oTable.getRows()[i];

                var selectedRow = oTable.getContextByIndex(i);

                var selectedID = selectedRow.getProperty(‘ID’);

              (0) 
  3. Andreas Appelt

    Hi Shruti,

    thanks for the example. I get an error message in line “rowSelectionChange : function(oEvent) {},” in the view file. Eclipse tells me that a semicolon is missing. Do you have an idea for that?

    Thanks.

    Regards, Andreas

     

    (0) 
    1. shruti m Post author

      Hi Andreas,

       

      What i mentioned it is correct only,there is no need of semicolon there. Could you please provide me the screenshot of that error ,to resolve the issue.

       

       

       

      Regards

      Shruti

      (0) 
      1. Andreas Appelt

        Hi Shruti,

        Thanks for your reply. Down below the coding of my view (I havent created the controller file so far). Also the image is attached that shows the first error message in the file followed by a couple of error messages.

        Regards, Andreas

         

         

        “bankcrud.bank”, {

        /** Specifies the Controller belonging to this View.



        * In the case that it is not implemented, or that “null” is returned, this View does not have a Controller.



        * @memberOf bankcrud.bank



        */



        function() {

        return “bankcrud.bank”;

        /** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.



        * Since the Controller is given to this method, its event handlers can be attached right away.



        * @memberOf bankcrud.bank



        */



        function(oController) {

        var layout = new sap.ui.commons.layout.MatrixLayout({

        ‘matrix4’,

        false,

        var appHeader = new sap.ui.commons.ApplicationHeader(‘appHeader’, {

        “Bank Application”,

        false,

        true,

        “Welcome”


        var rPannel = new sap.ui.commons.Panel(‘rPannel’, {

        “BankCollection List”,

        var oTable = new sap.ui.table.DataTable({

        “bankTableID”,

        “Bank CRUD Application”,

        “100%”,

        //setEditable : false,



        function(oEvent) {},

        new sap.ui.commons.Toolbar({

        new sap.ui.commons.Button({

        “Create”,

        function() {


        new sap.ui.commons.Button({

        “Update”,

        function() {


        new sap.ui.commons.Button({

        “Delete”,

        function() {








        new sap.ui.table.Column({

        new sap.ui.commons.Label({

        “Bank ID


        new sap.ui.commons.TextField().bindProperty(“value”,

        “bankID”),

        “bankID


        new sap.ui.table.Column({

        new sap.ui.commons.Label({

        “Bank Country


        new sap.ui.commons.TextField().bindProperty(“value”,

        “bankCountry”),

        “bankCountry


        new sap.ui.table.Column({

        new sap.ui.commons.Label({

        “Bank Name


        new sap.ui.commons.TextField().bindProperty(“value”,

        “bankName”),

        “bankName


        new sap.ui.table.Column({

        new sap.ui.commons.Label({

        “Region


        new sap.ui.commons.TextField().bindProperty(“value”,

        “region”),

        “region


        new sap.ui.table.Column({

        new sap.ui.commons.Label({

        “Street


        new sap.ui.commons.TextField().bindProperty(“value”,

        “street”),

        “street


        new sap.ui.table.Column({

        new sap.ui.commons.Label({

        “City


        new sap.ui.commons.TextField().bindProperty(“value”,

        “city”),

        “city


        // Add table to the Panel


        // Add panel to the Layout


        // Display Layout



        this.addContent(layout);


        /wp-content/uploads/2014/02/shruti_389491.jpg

        (0) 
        1. shruti m Post author

          Hi Andreas,

           

          Use the below mentioned code and then try to run it

           

           

          sap.ui.jsview(“bankcrud.bank”, {

           

              /** Specifies the Controller belonging to this View.

              * In the case that it is not implemented, or that “null” is returned, this View does not have a Controller.

              * @memberOf bankcrud.bank

              */

              getControllerName : function() {

                  return “bankcrud.bank”;

              },

           

              /** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.

              * Since the Controller is given to this method, its event handlers can be attached right away.

              * @memberOf bankcrud.bank

              */

              createContent : function(oController) {

                 

                 

                  var layout = new sap.ui.commons.layout.MatrixLayout({

                      id : ‘matrix4’,

                      layoutFixed : false,

                      //width : ‘1000px’,

                     

                  });

                 

                  var appHeader = new sap.ui.commons.ApplicationHeader(‘appHeader’, {

                      //logoSrc : “images/Atumit_45_40.png”,

                      logoText : “Bank Application”,

                      displayLogoff : false,

                      displayWelcome : true,

                      //userName : “Shruti Mukkawar(Kotturi)”

                  });

                  layout.createRow(appHeader);

                  var rPannel = new sap.ui.commons.Panel(‘rPannel’, {

                      text : “BankCollection List”,

                     

                  });

                 

                 

                 

                  var oTable = new sap.ui.table.DataTable({

                      id : “bankTableID”,

                       title: “Bank CRUD Application”,

                      width : “100%”,

                      visibleRowCount: 10,

                      selectionMode : sap.ui.table.SelectionMode.Single,

                      //setEditable : false,

                      rowSelectionChange : function(oEvent) {},

                     

                       toolbar: new sap.ui.commons.Toolbar({

           

                           items: [

           

                                new sap.ui.commons.Button({

           

                                          text: “Create”,

           

                                          press: function() {

           

                                               oController.Create();

           

                                          }

           

                                }),

           

           

           

                                new sap.ui.commons.Button({

           

                                          text: “Update”,

           

                                          press: function() {

           

                                               oController.Update();

           

                                          }

           

                                }),

           

                                   

           

                                new sap.ui.commons.Button({

           

                                          text: “Delete”,

           

                                          press: function() {

           

                                               oController.Delete();

           

                                          }

           

                                }),

           

                                   

           

                               ]

           

                 })

                     

                     

                     

                     

                     

                     

                  });

                 

                  oTable.addColumn(new sap.ui.table.Column({

                      label : new sap.ui.commons.Label({

                          text : “Bank ID”

                      }),

                      template : new sap.ui.commons.TextField().bindProperty(“value”,

                              “bankID”),

                      sortProperty : “bankID”

                  }));

                 

                  oTable.addColumn(new sap.ui.table.Column({

                      label : new sap.ui.commons.Label({

                          text : “Bank Country”

                      }),

                      template : new sap.ui.commons.TextField().bindProperty(“value”,

                              “bankCountry”),

                      sortProperty : “bankCountry”

                  }));

                 

                  oTable.addColumn(new sap.ui.table.Column({

                      label : new sap.ui.commons.Label({

                          text : “Bank Name”

                      }),

                      template : new sap.ui.commons.TextField().bindProperty(“value”,

                              “bankName”),

                      sortProperty : “bankName”

                  }));

                 

                  oTable.addColumn(new sap.ui.table.Column({

                      label : new sap.ui.commons.Label({

                          text : “Region”

                      }),

                      template : new sap.ui.commons.TextField().bindProperty(“value”,

                              “region”),

                      sortProperty : “region”

                  }));

                 

                 

                  oTable.addColumn(new sap.ui.table.Column({

                      label : new sap.ui.commons.Label({

                          text : “Street”

                      }),

                      template : new sap.ui.commons.TextField().bindProperty(“value”,

                              “street”),

                      sortProperty : “street”

                  }));

                 

                  oTable.addColumn(new sap.ui.table.Column({

                      label : new sap.ui.commons.Label({

                          text : “City”

                      }),

                      template : new sap.ui.commons.TextField().bindProperty(“value”,

                              “city”),

                      sortProperty : “city”

                  }));

                 

                 

                  // Add table to the Panel

                  rPannel.addContent(oTable);

                  // Add panel to the Layout

                  layout.createRow(rPannel);

                  // Display Layout

                  this.addContent(layout);

                 

           

              }

           

          });

          (0) 
          1. Andreas Appelt

            Hi Shruti,

            Thanks for your support. Now I don’t have any error message anymore.  I will use my own oData model and adjust the coding. But may I ask you one more question? What kind of file is Z_TM_BANK_SRV?

            Thanks.

            Regards, Andreas

            (0) 
  4. Seyed Ismail

    Hi Shruti,

     

     

    Really very great work and useful info for beginners.

     

    Thank you so much.

     

     

    It would be even better if you shared your OData service details, like Entity Types & the DDIC/RFC FM you used.

     

    Thanks again.

    (0) 
  5. Virag Upadhyay

    Hi Shruti,

     

    Your article is really very good & easy to understand.

    But i am getting error if i am running my app on firefox, error is “NetworkError: 403 Forbidden – ……”.

    Can you please tell what could be the reason..!!!

    (0) 
  6. Melanie Saldua

    Hi Shruti,

     

    Thanks for this article. Very informative. I would like to ask just one question. The application above uses Z_TM_BANK_SRV gateway service. Just wondering if we have to create our own BANK_SRV on our system or have you tried using SAP’s demo of this gateway service in SAP Gateway Demo System.

    (0) 
      1. Matthieu Pelatan

        Hi shruti,

         

        thank you for this great tutorial. Really well done.

        The create and update functionnalities works fine for me but delete doesn’t work.

        Here is the error:

         

        1. DELETE https://sapes1.sapdevcenter.com/sap/opu/odata/sap/Z_BANK/BankCollection(Bankcountry='DE‘,Bankkey=’11111111’) 500 (Internal Server Error)
        2. o.defaultHttpClient.request
        3. E2
        4. o.request
        5. OData.request.request
        6. (anonymous function)
        7. o9

         

        Do you have an idea why?

        I’m using the SAP Netweaver Gateway Demo System.

         

        Best,

        Matt

         

        PS: I’ve checked it with Postman and I have the following error message:

        Method ‘BANKCOLLECTION_DELETE_ENTITY’ not implemented in data provider class

        It seems we cann’t do any delete action

        (0) 
  7. le xian

    Hello Shruti:

         Could you please tell me the function module of demo bank ?


        I want to build the odata service,but I don’t find the function module.


        Thank you very much.


        lexian.

    (0) 
    1. Syam Babu

      Hi,

       

      Below of bank function modules

       

      BAPI_BANK_GETLIST

      BAPI_BANK_GETDETAIL

      BAPI_BANK_CREATE

      BAPI_BANK_CHANGE

      BAPI_BANK_DELETE

       

      Thanks,

      Syam

      (0) 
      1. le xian

        Hi Syam,

             Thank you for providing me with these modules.

         

             I want to know which modules this blog use?

         

             thank you .

        (0) 
  8. Meghna Udhwani

    Hi,

     

    I am using the delete functionality in my application as stated above.

    I want to display ‘sap-message’ in front end which is returned from SAP in HTTP Response header like this:

     

    Code for Deletion:

    OData.request({

             requestUri: ‘some url’,

                 method: “DELETE”,

                     headers: {    

                         “X-Requested-With”: “XMLHttpRequest”,                       

                        “Content-Type”: “application/atom+xml”,

                        “DataServiceVersion”: “2.0”,     

                        “X-CSRF-Token”:csrfToken  

                     }

                 },

                 function (data, response){

                     console.log(response);

                 }

    );

     

    The console.log returns:

    It doesnt returns ‘sap-message’ field at all.

     

    Can any one please tell what could be the reason?

     

    Regards,

    Meghna

    (0) 
    1. Seyed Ismail

      Hi Meghna,

       

      I am not sure whether you can catch the expected error via OData.request. I will look into it. Meanwhile, Please go through think link.

       

       

      Deleting Entries

      Entries are deleted by executing an HTTP DELETE request against a URI that points at the Entry. If the operation executed successfully servers should return 200 (OK) with no response body.

      If the Entry has dependent Entries such as Entries Linked to it, it is up to the server whether deletion should be cascaded, the operation should fail because of the presence of dependent Entries, or if Links are left dangling after the Entry is deleted. This largely depends on the server, storage model and the actual application the OData service is a part of.

      In the case of Media Link Entries, deleting the Media Link Entry also deletes the Media Resource.

       

      Best Regards,

      Seyed Ismail MAC

      (0) 
  9. le xian

    Hello everyone:

     

        I have created the view controller and run ok.

       

       But now I have a problem about Odata Service in SEGW,Syam told me these function:

    1  BAPI_BANK_GETLIST

    2  BAPI_BANK_GETDETAIL

    3  BAPI_BANK_CREATE

    4  BAPI_BANK_CHANGE

    5  BAPI_BANK_DELETE

     

     

     

    I know we have to create a Z_TM_BANK_SRV gateway service in SEGW,

     

    but I am confused is which function will be used or above all?

     

     

     

    It would be  better if someone shared your OData service details, like Entity Types & the DDIC/RFC FM you used.

     

     

     

    thank you very much,

    Best wishes for you.

     

     

    lexian.

     

     


    (0) 
  10. Tin de Zeeuw

    Most of the functionality you build with custom ajax requests (OData.request() functions) can be rewritten in a much easier way with the built-in functions such as read(), create(), update(), and remove() on the ODataModel (SAPUI5 SDK – Demo Kit)

    (0) 
  11. Mahesh Z

    Hi All,

     

    I am trying for POST operation however I am getting error : Uncaught ReferenceError: OData is not defined 

     

    My Code is :

     

    OData.request({

      requestUri : “MYURL”,

      headers : {

              Hedear Info

      },

      method : “POST”,

      data : connectiondata

      }, onSuccess, onError);

     

    Any suggestions on this ? Do I need to declare it somewhere first before use ? As per my understanding OData is default object. Correct me if I am wrong.

     

    Thanks ,

    Mahesh.

    (0) 
      1. DURAI VENKATESH

        Hi Mahesh,

                         I’m also getting the same error Uncaught ReferenceError: OData is not defined. how can I add the data.js file and what information that file should keep?. Please assist me.

         

        Thanks,

        Duraivenkatesh.R

        (0) 
        1. Mahesh Z

          Hello Venkatesh,

           

          You need to download datajs-1.0.1.min.js file and put it inside your project folder( I kept it at this location for my project :logindemo/resources/utils/) . Then add that path inside your index.html as follows.

           

          <script type=”text/javascript” src=”logindemo/resources/utils/datajs-1.0.1.min.js”></script>

           

          Thanks ,

          Mahesh.

          (0) 
  12. rajeesh o

    Hi shruti,

        when logging out i need to clear mysapsso2 cookie, Or i need to delete webviewchromiumcookes.db…iam using below code on logout how can i achive this.?

    Regards

     

     

    logOut : function(evt) {

      var app = this.getView().app;

     

        

      if(app) {

      // alert(‘hai’);

      userId=””;

      recId = “”;

      pass = “”;

      app.backToPage(“ProductDetail”);

      }

     

      }

    (0) 
  13. Madhav B

    Hi ,

     

    I am getting the following error, can you please help me out,

     

    When I am checking through the gateway client in the service is working fine in segw, its working fine for adding the entries.

     

    Regards,

    Madhav

    (0) 
    1. Srinivasan S

      Hi Madhav,

       

      I am getting the same error. Were you able to resolve it. If so please share your findings, it would be very helpful.

       

       

      Regards,

      Srinivasan

      (0) 
  14. Anusha C

    Hi shruthi,

     

    Thanks for your response..

    I tried with odata it is giving me the error while creating the CRUD application..and also I need to implement the CRUD application By using JSON model also..

    (0) 
  15. Les Williamson

    Hi

    I am using this oData.request method to update records in back-end SAP system, it is doing the update, but am getting this pop-up coming up every time. it looks like the entity set info but not sure how to stop it, can you help.

     

     

    Thanks Les./wp-content/uploads/2015/03/message_673339.jpg

    (0) 
  16. Ashok Dhayalaraj

    Hi Shruthi,

     

      I am trying to create OData service to update a PO. I am unable to use the PUT service , since it gives a Status 405 when I run it using Activate and Maintain Services on the Netweaver Gateway. Pls help.

     

    Thanks and Regards,

    Ashok

    (0) 
  17. deepika reddy

    Hi ,

     

           I am trying to create new record by using above coding but its not getting created and also it doesnt show any error also . Please guide me to resolve this issue .

     

    /wp-content/uploads/2015/10/create_819276.png

     

    This is my console picture .

     

    Thanks

    (0) 
      1. deepika reddy

        Here is my create code .

        Create:function()

            {

          var oDialog = new sap.ui.commons.Dialog(“Dialog”, {

             modal: true,

          closed: function(oControlEvent){

           sap.ui.getCore().getElementById(‘Dialog’).destroy();

              }

           });

           oDialog.setTitle(“New Bank Collection”);

           // Create a layout to place the controls in the dialog

           var oLayout = new sap.ui.commons.layout.MatrixLayout({

          columns: 2,

          width: “100%”

           });

           // Create text field for the bankCountry

           var oTF = new sap.ui.commons.TextField(“tbankCountry”, {

                   tooltip: ‘Bank Country’,

                   editable: true,

                   width: ‘200px’,

                 required: true

           });

          var oLabel = new sap.ui.commons.Label(“lbankCountry”, {

             text: ‘Bank Country’,

            labelFor: oTF

           });

          // Create the first row

           oLayout.createRow(oLabel, oTF);

           // Create text field for the bankID

           oTF = new sap.ui.commons.TextField(“tbankID”, {

          tooltip: ‘Bankid’,

            editable: true,

          required: true,

          width: ‘200px’

           });

          oLabel = new sap.ui.commons.Label(“lbankID”, {

             text: ‘Bank ID’,

          labelFor: oTF

          });

           oLayout.createRow(oLabel, oTF);

          

           oTF = new sap.ui.commons.TextField(“tbankName”, {

                   tooltip: ‘Bank Name’,

                      editable: true,

                   required: true,

                   width: ‘200px’

           });

           oLabel = new sap.ui.commons.Label(“lbankName”, {

            text: ‘Bankname’,

           labelFor: oTF

           });

           oLayout.createRow(oLabel, oTF);

           oTF = new sap.ui.commons.TextField(“tregion”, {

               tooltip: ‘Region Name’,

                   maxLength:3,

                   editable: true,

                        width: ‘200px’

           });

           // Label for the last name field

           oLabel = new sap.ui.commons.Label(“lregion”, {

                   text: ‘Region’,

                   labelFor: oTF

           });

           // Create the 4th row

           oLayout.createRow(oLabel, oTF);

           oTF = new sap.ui.commons.TextField(“tstreet”, {

          tooltip: ‘Street Name’,

          editable: true,

          width: ‘200px’

          });

           oLabel = new sap.ui.commons.Label(“lstreet”, {

                text: ‘Street’,

              labelFor: oTF

           });

           oLayout.createRow(oLabel, oTF);

           oTF = new sap.ui.commons.TextField(“tcity”, {

              tooltip: ‘City Name’,

              editable: true,

                width: ‘200px’

          });

           oLabel = new sap.ui.commons.Label(“lcity”, {

                 text: ‘City’,

                 labelFor: oTF

           });

           oLayout.createRow(oLabel, oTF);

          // Add the layout to the dialog

           oDialog.addContent(oLayout);

          // Add a button to post the bank’s data to the odata interface

           oDialog.addButton(new sap.ui.commons.Button({text: “Save”, press:function(){

           // Add a button to post the bank’s data to the odata interface

          

             var bankCountry_var    = sap.ui.getCore().getControl(“tbankCountry”).getValue();

                  var bankID_var      = sap.ui.getCore().getControl(“tbankID”).getValue();

                  var bankName_var  = sap.ui.getCore().getControl(“tbankName”).getValue();

                  var region_var   = sap.ui.getCore().getControl(“tregion”).getValue();

                  var street_var   = sap.ui.getCore().getControl(“tstreet”).getValue();

                  var city_var    = sap.ui.getCore().getControl(“tcity”).getValue();

                  OData.request

                  ({ 

                       requestUri:      “proxy/http/ranak.com/emplist-web/emplist.svc”, 

                             method: “GET”, 

                             headers: 

                                 {      

             “X-Requested-With”: “XMLHttpRequest”,

            “Content-Type”: “application/xml”,

          “DataServiceVersion”: “1.0”,         

          “X-CSRF-Token”:”Fetch”                                 }                   

                          }, 

                          function (data, response)

                          {

              header_xcsrf_token = response.headers[‘x-csrf-token’];

                           OData.request

                           ({ 

                                requestUri:

                                 “proxy/http/ranak.com/emplist-web/emplist.svc/Banks”, 

                                      method: “POST”, 

             headers: {   “X-Requested-With”: “XMLHttpRequest”,                       

          “Content-Type”: “application/xml”,

              “DataServiceVersion”: “1.0”, 

          “Accept”: “application/xml”,

          “X-CSRF-Token”: header_xcsrf_token    }, 

                                      data:JSON.stringify( 

                                          { 

                                       “Bankcountry”: bankCountry_var, 

                                       Bankid:bankID_var,

                                       Bankname:bankName_var,

                                       Region: region_var,

                                       Street: street_var,

                                       City: city_var,

                               })

                                   },

                                   function (data, response)

                                     { 

                                    document.location.reload(true);

                                                      $(“<div>Returned data ” + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”));

                                     }, 

                                            function (err) 

                                            {

                                                 $(“<div>Returned error ” + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”));

                                            }

                           );

                 }, 

                 function (err) 

                                {

                                     var request = err.request; // the request that was sent.

                                     var response = err.response; // the response that was received.

                                     alert(“Error in Get — Request “+request+” Response “+response);

                                }

                 );                     

           oDialog.close();

          }}));

           oDialog.open();

            },

         

         

        Thanks 

        P.Deepika

        (0) 
          1. deepika reddy

            Hi ,

             

                        This url is correct . I have displayed the records which is in this url . I cannot able to create new record in sap ui5 .

             

            Thanks  &  Regards

             

            Deepika

            (0) 
                1. Mahesh Z

                  Hello Deepika,

                   

                  This is because you are trying to access the remote host service from your localhost.

                   

                  In this case , you need to disable your web-security of browser.

                   

                  http://stackoverflow.com/questions/24290149/creating-google-chrome-shortcut-with-disable-web-security

                   

                  This is not needed when you deploy your application to gateway server.

                   

                  Once you disable the web security , you wont get this error.

                   

                  One more thing is , My name is not Sir , its Mahesh

                   

                  Thanks,

                  Mahesh.

                  (0) 
                2. Mahesh Z

                  One simple method to get URL :

                   

                  function getODataServiceURL() {

                   

                   

                    var sServiceURL = “Relative Path of your service”;

                    if (window.location.host === ‘localhost’) {

                    return “http://hostname:port” + sServiceURL;

                    } else {

                    return sServiceURL;

                    }

                  }

                   

                  Thanks ,

                  Mahesh.

                  (0) 
                    1. deepika reddy

                      Hi ,

                       

                               I have one doubt , i can able to display records in table format which is in the url .

                                After changing the path to disable web security . I am getting Failed to load resource and uncaught object error .  /wp-content/uploads/2015/11/table_832607.png 

                       

                      Thanks  &  Regards

                       

                      P.Deepika

                      (0) 
  18. Manjunath Babu Rayampalli

    HI Shruthi,

     

    basically im trying to upload an image  using post url in UI5, is there any way i can achieve it using UI5 APplication. i am executing below code after clicking button.

     

       OData.request({

                                                          requestUri : “ServiceURL”,

                                                          method : “GET”,

                                                          headers : {

                                                          “X-Requested-With” : “XMLHttpRequest”,

                                                          “Content-Type” : “application/atom+xml”,

                                                          “DataServiceVersion” : “2.0”,

                                                          “X-CSRF-Token” : “Fetch”

                                                          }

                                                          },

                                                          function(data, response) {

                                                          header_xcsrf_token = response.headers[‘x-csrf-token’];

                                                          oHeaders = {

                                                          “x-csrf-token” : header_xcsrf_token,

                                                          ‘Accept’ : ‘application/json’,

                                                          };

                                                         

                                                           OData.request({

                                                                        requestUri : “<post URL>”,

                                                                        method : “POST”,

                                                                        headers : oHeaders,

                                                                        data : oEntry

                                                                        },                

                                                                        function(data,request) {

    //                                                                    loadAttachment();

                                                                        },

                                                                        function(err){

                                                                        sap.m.MessageToast.show(“Couldn’t Deleted due to following exception : “+ err);

                                                                        });

                                                          },

                                                         

                                                          function(err) {

                                                          var request = err.request;

                                                          var response = err.response;

                                                          sap.m.MessageToast.show(“Error in Get — Request “ + request + ” Response “ + response);

                                                          });



    But i am getting error:TypeError: undefined is not an object (evaluating ‘sap.AuthProxy.OData.request’)


    Appreicated any help here


    Regards,MBR

    (0) 
  19. Vinay Kumar Dalapathirao

    Hi Shruthi,

     

     

    Thanks for your sharing knowledge on CRUD operations with sample application.

    It helps a lot like us to learn how to connect ecliplse to Odata.

    At first I missed headers in the request tag and trying.

    After seeing yours blog I got to know that I missed something.

    Now, I have successfully connected and retrieving the data.

     

    Regards,

    Vinay

    (0) 
  20. Angesh Kumar

    Hi Expert ,

     

    I am not able to do put  and delete operation . I get the dialog box without table data..

     

    here is my all controller code..

     

    Update : function() {

      var oTable = sap.ui.getCore().getElementById(‘bankTableID’);

            var i = oTable.getSelectedIndex();

            //var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet”;

             //var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘,Userid='”+ selectedId+ “‘)”;

            if (i == -1) {

                    alert(“Please Select a row to Update”);

                    return;

                  }else if(i>=0){

            var selectedRow = oTable.getRows()[i];

            //var selectedId = selectedRow.getCells()[0].getValue();

            var selectedCount = selectedRow.getCells()[1].getValue();

            var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq'”+ selectedCount + “‘ “;

            ///?$filter=Firstname eq’KIRAN'”

            //OData.read(ServiceURL + “/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘ , Userid='”+ selectedId + “‘)”,

            //proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘,Userid='”+ selectedId+ “‘)”

            //OData.read(ServiceURL + “(Firstname='”+ selectedCount + “‘, Userid='”+ selectedId + “‘)”,

          

            OData.read(ServiceURL , 

            function(response) {

            var oDialogu = new sap.ui.commons.Dialog(“Dialogu”, {

                    modal: true,

                   closed: function(oControlEvent){

                   sap.ui.getCore().getElementById(‘Dialogu’).destroy();

                  }

             });

            oDialogu.setTitle(“Update Employee Collection”);

                

            var oLayout = new sap.ui.commons.layout.MatrixLayout({

                        columns: 2,

                        width: “100%”

              });

      

      var oLayout = new sap.ui.commons.layout.MatrixLayout({ columns: 2, width: “100%” });

         // Create text field for the bankCountry

         var oTF = new sap.ui.commons.TextField(“tuserid”, { tooltip: ‘User ID’, editable: true, value: response.Userid, width: ‘200px’});

      var oLabel = new sap.ui.commons.Label(“luserid”, {  text: ‘User ID’, labelFor: oTF });

      // Create the first row

      oLayout.createRow(oLabel, oTF);

     

       // Create text field for the bankID

      oTF = new sap.ui.commons.TextField(“tfname”, { tooltip: ‘First Name’, editable: true,value:response.Firstname, required: true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lfname”, { text: ‘First Name’, labelFor: oTF });

      oLayout.createRow(oLabel, oTF);

     

     

      oTF = new sap.ui.commons.TextField(“tlname”, { tooltip: ‘Last Name’, editable: true,value:response.Lastname ,required: true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“llname”, { text: ‘Last Name’, labelFor: oTF });

      oLayout.createRow(oLabel, oTF);

     

     

      oTF = new sap.ui.commons.TextField(“temailid”, { tooltip: ‘Email ID’, editable: true,  value:response.Emailid ,required: true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lemailid”, { text: ‘Email ID’, labelFor: oTF });

      oLayout.createRow(oLabel, oTF);

      

      oTF = new sap.ui.commons.TextField(“tcountry”, { tooltip: ‘Country’, maxLength:23, editable: true,  value:response.Country, width: ‘200px’ });

       // Label for the last name field

      oLabel = new sap.ui.commons.Label(“lcountry”, { text: ‘Country’,labelFor: oTF });

       // Create the 4th row

      oLayout.createRow(oLabel, oTF);

      

      oTF = new sap.ui.commons.TextField(“tphone”, {tooltip: ‘Phone’,editable: true,  value:response.Phone, required : true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lphone”, {text: ‘Phone’,labelFor: oTF});

      oLayout.createRow(oLabel, oTF);

      

      oTF = new sap.ui.commons.TextField(“tsalary”, {tooltip: ‘Salary’,editable: true,   value:response.Salary, required : true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lsalary”, {text: ‘Salary’,labelFor: oTF});

      oLayout.createRow(oLabel, oTF);

     

     

      oDialogu.addContent(oLayout);

     

      oLayout.addStyleClass(“mystyle1”);

     

      // Add a button to post the bank’s data to the odata interface

      oDialogu.addButton(new sap.ui.commons.Button({text: “Update”,

        width : “100px”,

        style : sap.ui.commons.ButtonStyle.Emph,

        press:function(){

       // Add a button to post the bank’s data to the odata interface

        var bankCountry_var    = sap.ui.getCore().getControl(“tuserid”).getValue();

              var bankID_var      = sap.ui.getCore().getControl(“tfname”).getValue();

              var lnameID_var      = sap.ui.getCore().getControl(“tlname”).getValue();

              var bankName_var  = sap.ui.getCore().getControl(“temailid”).getValue();

              var countryName_var  = sap.ui.getCore().getControl(“tcountry”).getValue();

              var region_var   = sap.ui.getCore().getControl(“tphone”).getValue();

              var street_var   = sap.ui.getCore().getControl(“tsalary”).getValue();

      

              OData.request

              ({ 

                   requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq’KIRAN'”,

              //requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq'”+ selectedCount + “‘)”,

                   method: “GET”, 

                      headers: {      

                      “X-Requested-With”: “XMLHttpRequest”,

                      “Content-Type”: “application/atom+xml”,

                      “DataServiceVersion”: “2.0”,         

                      “X-CSRF-Token”:”Fetch”                           

                      }                   

                   }, 

                   function (data, response)

                   {

                        header_xcsrf_token = response.headers[‘x-csrf-token’];

                OData.request

                ({ 

                //”http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection(bankCountry=‘”+ selectedCount + “‘,bankID='”+ selectedId+ “‘)”,

                requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq'”+ selectedCount + “‘)”, 

                           method: “PUT”, 

                           headers: { “X-Requested-With”: “XMLHttpRequest”,                       

                          “Content-Type”: “application/atom+xml”,

                          “DataServiceVersion”: “2.0”, 

                          “Accept”: “application/atom+xml,application/atomsvc+xml,application/xml,text/html”,

                          “X-CSRF-Token”: header_xcsrf_token }, 

                           data:

                          {

                            Userid: bankCountry_var, 

                               Firstname:bankID_var,

                               Lastname: lnameID_var,

                               Emailid: bankName_var,

                               Country :countryName_var,

                               Phone: region_var,

                               Salary: street_var,

                              

                       } 

                           },

                           function (data, response)

                           { 

                          var oSubDialog = new sap.ui.commons.Dialog( {title: “Updated”,

                                   content : [new sap.ui.commons.Label({

                                   text : “Data Updated Successfully”

                                   })]});

                                   oSubDialog.open();

                                   oSubDialog.addButton(new sap.ui.commons.Button({text: “OK”, press:function(){

                                  oSubDialog.close();

                                   }}));

                                  

                                  $(“<div>Returned data ” + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”));

                           }, 

                                  function (err) 

                                  {

                                       $(“<div>Returned error ” + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”));

                                  }

                 );

       }, 

       function (err) 

                      {

                           var request = err.request; // the request that was sent.

                           var response = err.response; // the response that was received.

                           alert(“Error in Get — Request “+request+” Response “+response);

                      }

       );     

             

              oDialogu.close();

             

    }}));

      oDialogu.open();

     

     

     

     

    });

     

     

     

     

    }

      

    },

      

    Delete : function(oEvent) {

               var oTable = sap.ui.getCore().getElementById(‘bankTableID’);

            // Retrieve the selected index, i.e., the index of the selected row

                var i = oTable.getSelectedIndex();

                //var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV”;

                  if (i == -1) {

                         alert(“Please Select a row to Delete”);

                         return;

                       }

                       else if(i>=0){

                  var selectedRow = oTable.getRows()[i];

                 // var selectedId = selectedRow.getCells()[0].getValue();

                  var selectedCount = selectedRow.getCells()[1].getValue();

                 }

               OData.request

                  ({

                  requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq’KIRAN'”, 

                             method: “GET”, 

                             headers: 

                                 {      

                              “X-Requested-With”: “XMLHttpRequest”,

                              “Content-Type”: “application/atom+xml”,

                              “DataServiceVersion”: “2.0”,         

                              “X-CSRF-Token”:”Fetch” 

                                   }                   

                          },

                          function (data, response)

                          { 

                                 header_xcsrf_token = response.headers[‘x-csrf-token’];

                     OData.request

                     ({

                      requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘)”,

                      method: “DELETE”, 

                      headers: { 

                              “X-Requested-With”: “XMLHttpRequest”,                       

                              “Content-Type”: “application/atom+xml”,

                              “DataServiceVersion”: “2.0”, 

                              “X-CSRF-Token”: header_xcsrf_token 

                                   }

                             }, 

                               function (data, request)

                               {

                              document.location.reload(true);

                                           $(“<div>Returned data in Delete ” + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”));

                                }, 

                              function (err) 

                              {

                                           $(“<div>Returned error in Delete ” + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”));                             

                               }

                     );

                 },

                   function (err) 

                       {

                                var request     = err.request; 

                                var response = err.response; 

                                alert(“Error in Get — Request “+request+” Response “+response);

                       }

                 );      

              }

              

    });

     

     

    Please help me.

     

    Thanks

    (0) 
  21. Angesh Kumar

    Hi Expert ,

     

    I am not able to do put  and delete operation . I get the dialog box without table data..

     

    here is my all controller code..

     

    Update : function() {

      var oTable = sap.ui.getCore().getElementById(‘bankTableID’);

            var i = oTable.getSelectedIndex();

            //var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet”;

             //var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘,Userid='”+ selectedId+ “‘)”;

            if (i == -1) {

                    alert(“Please Select a row to Update”);

                    return;

                  }else if(i>=0){

            var selectedRow = oTable.getRows()[i];

            //var selectedId = selectedRow.getCells()[0].getValue();

            var selectedCount = selectedRow.getCells()[1].getValue();

            var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq'”+ selectedCount + “‘ “;

            ///?$filter=Firstname eq’KIRAN'”

            //OData.read(ServiceURL + “/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘ , Userid='”+ selectedId + “‘)”,

            //proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘,Userid='”+ selectedId+ “‘)”

            //OData.read(ServiceURL + “(Firstname='”+ selectedCount + “‘, Userid='”+ selectedId + “‘)”,

          

            OData.read(ServiceURL , 

            function(response) {

            var oDialogu = new sap.ui.commons.Dialog(“Dialogu”, {

                    modal: true,

                   closed: function(oControlEvent){

                   sap.ui.getCore().getElementById(‘Dialogu’).destroy();

                  }

             });

            oDialogu.setTitle(“Update Employee Collection”);

                

            var oLayout = new sap.ui.commons.layout.MatrixLayout({

                        columns: 2,

                        width: “100%”

              });

      

      var oLayout = new sap.ui.commons.layout.MatrixLayout({ columns: 2, width: “100%” });

         // Create text field for the bankCountry

         var oTF = new sap.ui.commons.TextField(“tuserid”, { tooltip: ‘User ID’, editable: true, value: response.Userid, width: ‘200px’});

      var oLabel = new sap.ui.commons.Label(“luserid”, {  text: ‘User ID’, labelFor: oTF });

      // Create the first row

      oLayout.createRow(oLabel, oTF);

     

       // Create text field for the bankID

      oTF = new sap.ui.commons.TextField(“tfname”, { tooltip: ‘First Name’, editable: true,value:response.Firstname, required: true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lfname”, { text: ‘First Name’, labelFor: oTF });

      oLayout.createRow(oLabel, oTF);

     

     

      oTF = new sap.ui.commons.TextField(“tlname”, { tooltip: ‘Last Name’, editable: true,value:response.Lastname ,required: true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“llname”, { text: ‘Last Name’, labelFor: oTF });

      oLayout.createRow(oLabel, oTF);

     

     

      oTF = new sap.ui.commons.TextField(“temailid”, { tooltip: ‘Email ID’, editable: true,  value:response.Emailid ,required: true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lemailid”, { text: ‘Email ID’, labelFor: oTF });

      oLayout.createRow(oLabel, oTF);

      

      oTF = new sap.ui.commons.TextField(“tcountry”, { tooltip: ‘Country’, maxLength:23, editable: true,  value:response.Country, width: ‘200px’ });

       // Label for the last name field

      oLabel = new sap.ui.commons.Label(“lcountry”, { text: ‘Country’,labelFor: oTF });

       // Create the 4th row

      oLayout.createRow(oLabel, oTF);

      

      oTF = new sap.ui.commons.TextField(“tphone”, {tooltip: ‘Phone’,editable: true,  value:response.Phone, required : true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lphone”, {text: ‘Phone’,labelFor: oTF});

      oLayout.createRow(oLabel, oTF);

      

      oTF = new sap.ui.commons.TextField(“tsalary”, {tooltip: ‘Salary’,editable: true,   value:response.Salary, required : true, width: ‘200px’});

      oLabel = new sap.ui.commons.Label(“lsalary”, {text: ‘Salary’,labelFor: oTF});

      oLayout.createRow(oLabel, oTF);

     

     

      oDialogu.addContent(oLayout);

     

      oLayout.addStyleClass(“mystyle1”);

     

      // Add a button to post the bank’s data to the odata interface

      oDialogu.addButton(new sap.ui.commons.Button({text: “Update”,

        width : “100px”,

        style : sap.ui.commons.ButtonStyle.Emph,

        press:function(){

       // Add a button to post the bank’s data to the odata interface

        var bankCountry_var    = sap.ui.getCore().getControl(“tuserid”).getValue();

              var bankID_var      = sap.ui.getCore().getControl(“tfname”).getValue();

              var lnameID_var      = sap.ui.getCore().getControl(“tlname”).getValue();

              var bankName_var  = sap.ui.getCore().getControl(“temailid”).getValue();

              var countryName_var  = sap.ui.getCore().getControl(“tcountry”).getValue();

              var region_var   = sap.ui.getCore().getControl(“tphone”).getValue();

              var street_var   = sap.ui.getCore().getControl(“tsalary”).getValue();

      

              OData.request

              ({ 

                   requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq’KIRAN'”,

              //requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq'”+ selectedCount + “‘)”,

                   method: “GET”, 

                      headers: {      

                      “X-Requested-With”: “XMLHttpRequest”,

                      “Content-Type”: “application/atom+xml”,

                      “DataServiceVersion”: “2.0”,         

                      “X-CSRF-Token”:”Fetch”                           

                      }                   

                   }, 

                   function (data, response)

                   {

                        header_xcsrf_token = response.headers[‘x-csrf-token’];

                OData.request

                ({ 

                //”http://server_name/sap/opu/odata/sap/Z_TM_BANK_SRV/BankCollection(bankCountry=‘”+ selectedCount + “‘,bankID='”+ selectedId+ “‘)”,

                requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq'”+ selectedCount + “‘)”, 

                           method: “PUT”, 

                           headers: { “X-Requested-With”: “XMLHttpRequest”,                       

                          “Content-Type”: “application/atom+xml”,

                          “DataServiceVersion”: “2.0”, 

                          “Accept”: “application/atom+xml,application/atomsvc+xml,application/xml,text/html”,

                          “X-CSRF-Token”: header_xcsrf_token }, 

                           data:

                          {

                            Userid: bankCountry_var, 

                               Firstname:bankID_var,

                               Lastname: lnameID_var,

                               Emailid: bankName_var,

                               Country :countryName_var,

                               Phone: region_var,

                               Salary: street_var,

                              

                       } 

                           },

                           function (data, response)

                           { 

                          var oSubDialog = new sap.ui.commons.Dialog( {title: “Updated”,

                                   content : [new sap.ui.commons.Label({

                                   text : “Data Updated Successfully”

                                   })]});

                                   oSubDialog.open();

                                   oSubDialog.addButton(new sap.ui.commons.Button({text: “OK”, press:function(){

                                  oSubDialog.close();

                                   }}));

                                  

                                  $(“<div>Returned data ” + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”));

                           }, 

                                  function (err) 

                                  {

                                       $(“<div>Returned error ” + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”));

                                  }

                 );

       }, 

       function (err) 

                      {

                           var request = err.request; // the request that was sent.

                           var response = err.response; // the response that was received.

                           alert(“Error in Get — Request “+request+” Response “+response);

                      }

       );     

             

              oDialogu.close();

             

    }}));

      oDialogu.open();

     

     

     

     

    });

     

     

     

     

    }

      

    },

      

    Delete : function(oEvent) {

               var oTable = sap.ui.getCore().getElementById(‘bankTableID’);

            // Retrieve the selected index, i.e., the index of the selected row

                var i = oTable.getSelectedIndex();

                //var ServiceURL = “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV”;

                  if (i == -1) {

                         alert(“Please Select a row to Delete”);

                         return;

                       }

                       else if(i>=0){

                  var selectedRow = oTable.getRows()[i];

                 // var selectedId = selectedRow.getCells()[0].getValue();

                  var selectedCount = selectedRow.getCells()[1].getValue();

                 }

               OData.request

                  ({

                  requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet/?$filter=Firstname eq’KIRAN'”, 

                             method: “GET”, 

                             headers: 

                                 {      

                              “X-Requested-With”: “XMLHttpRequest”,

                              “Content-Type”: “application/atom+xml”,

                              “DataServiceVersion”: “2.0”,         

                              “X-CSRF-Token”:”Fetch” 

                                   }                   

                          },

                          function (data, response)

                          { 

                                 header_xcsrf_token = response.headers[‘x-csrf-token’];

                     OData.request

                     ({

                      requestUri: “proxy/sap/opu/odata/SAP/ZODATA_CURD_FINAL_PROJECT_ANG_SRV/EMPLIST_INFOSet(Firstname='”+ selectedCount + “‘)”,

                      method: “DELETE”, 

                      headers: { 

                              “X-Requested-With”: “XMLHttpRequest”,                       

                              “Content-Type”: “application/atom+xml”,

                              “DataServiceVersion”: “2.0”, 

                              “X-CSRF-Token”: header_xcsrf_token 

                                   }

                             }, 

                               function (data, request)

                               {

                              document.location.reload(true);

                                           $(“<div>Returned data in Delete ” + window.JSON.stringify(data) + “</div>”).appendTo($(“#MessageDiv”));

                                }, 

                              function (err) 

                              {

                                           $(“<div>Returned error in Delete ” + window.JSON.stringify(err.response) + “</div>”).appendTo($(“#MessageDiv”));                             

                               }

                     );

                 },

                   function (err) 

                       {

                                var request     = err.request; 

                                var response = err.response; 

                                alert(“Error in Get — Request “+request+” Response “+response);

                       }

                 );      

              }

              

    });

     

     

    Please help me.

     

    Thanks

    (0) 
  22. Srinivasan S

    Hi Shruthi,

     

    Thank you for the blog. My requirement is to perform the create functionality. When I submit the data I get the below error.crud-error.PNG

    It is an immediate requirement. Hope you can provide some suggestions regarding it.

     

     

    Thanks,

    Srinivasan

    (0) 
  23. k p

    Hi All,

    I have just started learning. I don’t understand one thing. I have seen code for CRUD operations using Odata in this example follows different syntax and complex. I have seen  Other different way  which used by my colleague.

     

    var oResultModel = new sap.ui.model.odata.ODataModel(“XXXXXXXXX/sap/opu/odata/sap/ZXXXXXXUPDATE_SRV/”, false);
    oResultModel.create(“/HeaderSet”,requestData,{success: function(oData,oResponse){   }

     

    Could you please anybody tell the difference if any ?

    (0) 

Leave a Reply