Quantcast
Channel: SAPUI5 Developer Center
Viewing all articles
Browse latest Browse all 789

CRUD Operation on ODATA Model

$
0
0

When we play with data, then the most talked about operations are CRUD Operations. CRUD features are nothing but Create/Read/Update/Delete operations.

As we know we can bind a UI element in an SAPUI5 application to the data specified in an OData service. For example, you can populate the contents of table columns displayed in an SAPUI5 application with the data stored in a database table defined in an OData service. In this document, you learn how to build an SAPUI5 Mobile App that provides the options, which you can use to create a new record or update an existing record in a database table, for example, using the OData create, update, and delete (CRUD) features. Now lets take a look into it:

 

Create Request:

 

The create function triggers a POST request to an OData service which was specified during creation of the OData model. The application has to specify the collection where to create the entry and the entry data payload. To get the result of the request, the application can hand over callback handler functions. To recreate and update the bindings, a refresh is triggered automatically after the successful creation.

The following code triggers a new entry in the Products collection:

 

oModel.create()

var oEntry = {};

 

oEntry.ID = 9;

oEntry.Rating = 5;

oModel.create('/Products', oEntry, null,
function(){
          alert("Create successful");

               },function(){

        alert("Create failed");});

 

 

 

Delete Request:

 

The remove function triggers a DELETE request to an OData service which was specified during creation of the OData model. The application has to specify the path to the entry which should be
deleted. To update the bindings in the model, a refresh is triggered automatically after successful deletion. A single parameter oParameters can be passed into the function and can carry all optional attributes, such as attributes for success and error handling functions as well as ETag attributes.

 

The following code deletes the product entry with ID=1 from the Products collection of the data service:

oModel.delete()

oModel.remove('/Products(1)', null,
function(){
           alert("Delete successful"); },

function(){                alert("Deletefailed");});

 

 

Update Request:

 

The update function triggers a PUT request to an OData service which was specified during creation of the OData model. See the ODataModel API for information about attribute use. The application has to specify the path to the entry which should be updated with the specified updated entry. After a successful request to update the bindings in the model,a refresh is triggered automatically.

 

The following code updates the rating:

 

oModel.update()

var oEntry = {};

 

oEntry.Rating = 5;

oModel.update('/Products(1)', oEntry, null,
function(){
alert("Update successful");  },

function(){ alert("Updatefailed");});

 

 

Read Request:

 

The read function triggers a GET request to a specified path which should be retrieved from the OData service which was specified during creation of the OData model. The retrieved data is returned in the success callback handler function.

 

The following code reads the specific data:

oModel.read()

oModel.read('/Products(1)', null, null,
true, function(oData, oResponse){

alert("Read successful: " + JSON.stringify(oData));  },

function(){  alert("Readfailed");});

 

 

 

Now, Lets Create a small Demo app to demonstrate all these features.

 

Demo

Go to eclipse---New Project---SAPUI5 Mobile App—Create a js View View.

Now we would use the following oData service for our app:

http/services.odata.org/V2/(S(hgfvvt31yj5dms3ogd01si4d))/OData/OData.svc/

 

Now , Paste the following code in onInit function() of controller .js:

 

onInit() function of controller.js

var oModel = new sap.ui.model.odata.ODataModel "proxy/http/services.odata.org/V2/(S(hgfvvt31yj5dms3ogd01si4d))/OData/OData.svc/", false);

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

 

Now Paste the following code in the createContent function() of  view.js file:

 

 

createContent() of view.js

var oPage = new sap.m.Page({

 

                                title: "Product Details",

                                });

var oButton1 = new sap.m.Button("Submit", {

 

                                   text: "New Entry",

                                   tap: [ oController.NewEntry, oController ]

                              });

var oButton2 = new sap.m.Button("Save", {

 

                                   text: "Save",

                                 tap: [ oController.Save, oController ]

                              });

var oButton3 = new sap.m.Button("Cancel", {

       text: "Cancel",

    tap: [ oController.Cancel, oController ]

                              });

var oButton4 = new sap.m.Button("Update", {

    text: "Update",

  tap: [ oController.Update, oController ]

   });

  var oButton5 = new sap.m.Button("Delete", {

      text: "Delete",

  tap: [ oController.Delete, oController ]

    });

var oDialog = new sap.m.Dialog("Dialog1",{

  title:"Details of New Entry",

modal: true,

contentWidth:"1em",

buttons : [oButton2, oButton4, oButton5, oButton3 ],

  content:[

new sap.m.Label({text:"Enter Id(must be a number)"}),

new sap.m.Input({                                       

   maxLength: 20,

  id: "Id"   

  }), new sap.m.Label({text:"Enter Rating"}),

new sap.m.Input({                                       

   maxLength: 20,  id: "Rating"           

  }),

new sap.m.Label({text:"EnterPrice"}),

new sap.m.Input({                                       

  maxLength: 20,

   id: "Price"           }),

]

   });

var oTable = new sap.m.Table({

  id: "Products",

  itemPress : [ oController.ItemPress,oController ],

columns: [

  new sap.m.Column({

   width: "1em",

   header: new sap.m.Label({

      text: "ID"  })   }),
new sap.m.Column({

    width: "1em",    header: new sap.m.Label({

    text: "Release Date"    })

  }),
new sap.m.Column({

   width: "1em",  header: new sap.m.Label({

    text: "Discontinued Date"

     })

      }),
new sap.m.Column({
   width: "1em",

  header: new sap.m.Label({

      text: "Rating"

})

  }),
new sap.m.Column({

  width: "1em",

  header: new sap.m.Label({

    text: "Price"

  })   })

     ]  });

   var template = new sap.m.ColumnListItem({

 

                                             id: "first_template",

                                             type: "Navigation",

                                            visible: true,

                                             cells: [

 

                                             new sap.m.Label("ID", {

  text: "{ID}"

  }),
new sap.m.Label({

    text: "{ReleaseDate}"

  }),
new sap.m.Label({

                        text: "{DiscontinuedDate}"

     }),
new sap.m.Label({

                        text: "{Rating}"

     }),
new sap.m.Label({

                 text: "{Price}"

        })

                ]

       });

  var  oFilters = null;

  oTable.bindItems("/Products",template, null, oFilters);

  oPage.addContent(oButton1);

oPage.addContent(oTable);

  return oPage;

 

 

Now finally Paste the following code at the end of controller.js file:

controller,js

 

ItemPress: function(evt) {

   sap.ui.getCore().byId("Dialog1").open();

sap.ui.getCore().byId("Save").setVisible(false);

   sap.ui.getCore().byId("Update").setVisible(true);

sap.ui.getCore().byId("Delete").setVisible(true);

var oSelectedItem = evt.getParameter("listItem");

     varsID = oSelectedItem.getBindingContext().getProperty("ID");

  varsRating = oSelectedItem.getBindingContext().getProperty("Rating");

   var sPrice = oSelectedItem.getBindingContext().getProperty("Price");

sap.ui.getCore().byId("Id").setValue(sID);

   sap.ui.getCore().byId("Rating").setValue(sRating);

   sap.ui.getCore().byId("Price").setValue(sPrice);

sap.ui.getCore().byId("Id").setEnabled(false);

},

NewEntry: function() {

sap.ui.getCore().byId("Dialog1").open();

   sap.ui.getCore().byId("Save").setVisible(true);

sap.ui.getCore().byId("Update").setVisible(false);

   sap.ui.getCore().byId("Delete").setVisible(false);

   sap.ui.getCore().byId("Id").setValue("");

    sap.ui.getCore().byId("Rating").setValue("");

   sap.ui.getCore().byId("Price").setValue("");

sap.ui.getCore().byId("Id").setEnabled(true);

 

               },

   Save: function() {

     var oEntry = {};

  oEntry.ID = sap.ui.getCore().byId("Id").getValue();

oEntry.Rating= sap.ui.getCore().byId("Rating").getValue();

   oEntry.Price= sap.ui.getCore().byId("Price").getValue();

  sap.ui.getCore().getModel().create('/Products',
oEntry, null, function(){

    alert("Create successful");

   location.reload(true);

    },function(){

       alert("Create failed");});

               },

Update: function() {

var oEntry = {};

var ID = sap.ui.getCore().byId("Id").getValue();

oEntry.Rating= sap.ui.getCore().byId("Rating").getValue();

oEntry.Price= sap.ui.getCore().byId("Price").getValue();

sap.ui.getCore().getModel().update('/Products('+ID+')',
oEntry, null, function(){

    alert("Update successful");

  location.reload(true);

},function(){  alert("Update failed");});

 

               },

Delete: function() {

var oEntry = {};

var ID = sap.ui.getCore().byId("Id").getValue();

 

sap.ui.getCore().getModel().remove('/Products('+ID+')',
null, function(){
  alert("Delete successful");

  location.reload(true);

   },function(){   alert("Delete failed");});

 

               },

  Cancel:function() {

    sap.ui.getCore().byId("Dialog1").close();

               }

 

 

Complete, now save run your application:-

Select the Item you update and then a popup appears

 

 

chrome.jpg

Done!!!

 


Viewing all articles
Browse latest Browse all 789

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>