SAPUI5 for ABAPers: Accessing OData Services from SAPUI5 Applications – CRUD Operations

How to Consume OData Service

The ultimate fate of an OData service is to be consumed by front-end apps. SAPUI5 applications follow the Model View Controller (MVC) architecture. In MVC, View and Controller are the UI5 application’s Views (XML, HTML, JavaScript, and JSON Views) and Controllers (JavaScript Controllers). In the UI5 application, models can be OData, JSON, Resource, or XML.

This tutorial introduces the OData concept and guides you through creating a front-end application that uses it to execute CRUD operations.

You can use the OData Model to consume the OData Service. To accomplish this, establish an OData Service and implement its establish, READ, UPDATE, and DELETE functions. To use these techniques, build an OData Model Instance in the UI5 app and use the read(), create(), update(), and delete() operations from the OData model.

Let’s start…

The customer needs to display records from a custom table on a UI5 application and give end-users with read, create, update, and delete options.

Step 1: Prepare a Custom Table for us to play.

CRUD operation in SAPUI5

Creating a custom table called ‘zuserdata’ with id, name, email, and mobile fields.

Step 2: Creating an OData Service

Go to transaction SEGW and create a new OData Service named zcrud_demo.

If you’re new to OData Service, we recommend starting with the tutorial where we developed our first service.

  • Consider taking the free video course on OData Service and Netweaver Gateway.
  • Create the entity ‘userdata’ and the related entityset ‘userdataSet’.
  • Create four attributes for the ‘userdata’ entity: id, name, email, and mobile.
  • Ensure that the Properties datatype and length match those of the fields defined in the table in step 1.

Activate the OData service to generate its runtime.

How to REDEFINE the DPC Class methods

7 Write your logic (code) in each redefined method. (Redefinition code is given in the below section of the instruction)

8 Navigate to t-code /n/iwfnd/maint_service to add the service.

/n/iwfnd/maint_service
/n/iwfnd/maint_service

Configure ICF settings for the created OData service to enable Create operations using the OData model. Go to SICF transaction, open the OData service’s ICF node, and double-click on it. Click on the GUI Configuration button.

SICF in OData

Set the CHECK_CSRF_TOKEN value to zero. This will bypass the service’s CSRF protection. This is essential for the CREATE, UPDATE, and DELETE operations to function. To avoid security risks, use the READ operation to retrieve the X-CSRF-TOKEN before performing CREATE, UPDATE, or DELETE operations in the UI5 app. To keep things simple in this lesson, we’ve turned off the X-CSRF-TOKEN security feature.

OData ABAP code for the CREATE_ENTITY method.

method USERDATASET_CREATE_ENTITY.
    data : wa_userdata type zcl_zcrud_demo_mpc=>ts_userdata.
*    read data recieved from ui5
    io_data_provider->read_entry_data(
    IMPORTING
      es_data  = wa_userdata
    ).
    MODIFY zuserdata from wa_userdata.
    if sy-subrc eq 0.
      move 'success' to er_entity-name.
      else.
        move 'error' to er_entity-name.
        endif.
  endmethod.

Method name: USERDATASET_GET_ENTITY. Data: wa_userdata; type

Method: USERDATASET_GET_ENTITY. Data: wa_userdata, type ZCL_ZCRUD_DEMO_MPC=>TS_USERDATA.
SELECT A SINGLE * FROM zuserdata INTO THE CORRESPONDING FIELDS OF wa_userdata.
Move wa_userdata to er_entity. End procedure.

OData ABAP code for retrieving many records via the GET_ENTITYSET function.

Method name: USERDATASET_GET_ENTITYSET. Data: it_userdata TYPE ZCL_ZCRUD_DEMO_MPC->TT_USERDATA. Select * from zuserdata and add it to table et_entityset. Endmethod.

OData ABAP code for Update (update_entity method)

Method: USERDATASET_UPDATE_ENTITY.
data: wa_userdata type zcl_zcrud_demo_mpc->ts_userdata.

  • Read data received from UI5: io_data_provider->read_entry_data( IMPORTING es_data = wa_userdata).
  • Move’success’ to er_entity.
    UPDATE Zuserdata set email = wa_userdata-email, id = wa_userdata-id. endmethod.

OData ABAP code for the DELETE_ENTITY method.

Method: USERDATASET_DELETE_ENTITY. Data: wa_keytab, LIKE LINE OF it_keytab.
READ TABLE it_key_tab INTO wa_keytab, KEY name = 'id'.
If sy-subrc equals 0.
DELETE from zuserdata when id = wa_keytab-value. ENDIF. Endmethod.

Step 3: Create the SAPUI5 application.

Create a SAPUI5 application that consumes the OData service developed in Step 2 and calls the OData model’s CREATE, READ, UPDATE, and REMOVE methods.

Also see: An ABAPer’s First SAPUI5 App in SAP WebIDE.

  1. Create a new SAPUI5 application with the name crud_demo.
  2. Create an XML view named ‘crud_demo.view’. Write the following code in it.
  3. <core:View xmlns:core=”sap.ui.core” xmlns:mvc=”sap.ui.core.mvc” xmlns=”sap.m” controllerName=”crud_demo.crud_demo” xmlns:html=”http://www.w3.org/1999/xhtml” xmlns:l=”sap.ui.commons.layout”> <Page title=”CRUD Operations”> <content> <l:AbsoluteLayout width=”10rem” height=”10rem”></l:AbsoluteLayout> <VBox xmlns=”sap.m” id=”vboxid”> <items> <HBox xmlns=”sap.m”> <items> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Button xmlns=”sap.m” id=”cbtn” press=”oDataCall” text=”Create”></Button> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Button xmlns=”sap.m” id=”rbtn” press=”oDataCall” text=”Read”></Button> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Button xmlns=”sap.m” id=”ubtn” press=”oDataCall” text=”Update”></Button> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Button xmlns=”sap.m” id=”dbtn” press=”oDataCall” text=”Delete”></Button> </items> </HBox> <HBox xmlns=”sap.m”> <items> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Input xmlns=”sap.m” id=”uniqueid” placeholder=”ID” value=”1″></Input> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Input xmlns=”sap.m” id=”nameid” placeholder=”Name” value=”test”></Input> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Input xmlns=”sap.m” id=”emailid” placeholder=”Email” value=”test@gmail.com”></Input> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Input xmlns=”sap.m” id=”mobid” placeholder=”Mobile” value=”8888888888″></Input> </items> </HBox> <HBox xmlns=”sap.m”> <items> <l:AbsoluteLayout width=”20px” height=”20px”></l:AbsoluteLayout> <Table xmlns=”sap.m” id=”userdatatable” headerText=”User Data”> <items> <ListItemBase xmlns=”sap.m” id=”id1″></ListItemBase> </items> <columns> <!– sap.m.Column –> <Column xmlns=”sap.m”> <header> <Text xmlns=”sap.m” text=”Id” ></Text></header></Column> <Column xmlns=”sap.m”> <header> <Text xmlns=”sap.m” text=”Name” ></Text></header></Column> <Column xmlns=”sap.m”> <header> <Text xmlns=”sap.m” text=”Email” ></Text></header></Column> <Column xmlns=”sap.m”> <header> <Text xmlns=”sap.m” text=”Mobile” ></Text></header></Column> </columns> </Table> </items> </HBox> </items> <!– sap.ui.core.Control –> </VBox> </content> </Page> </core:View>3. Create crud_demo.controller.js. Write below code in it.onInit: function() { that = this; // Create Model Instance of the oData service var oModel = new sap.ui.model.odata.v2.ODataModel(“/sap/opu/odata/sap/ZCRUD_DEMO_SRV”); sap.ui.getCore().setModel(oModel, “myModel”); },
oDataCall:function(oEvent)
 	{
		// call oData service's function based on which button is clicked.
		debugger;
		var myModel = sap.ui.getCore().getModel("myModel");
		myModel.setHeaders({
			"X-Requested-With" : "X"
		});
		// CREATE******************
		if ('Create' == oEvent.oSource.mProperties.text) {
			var obj = {};
			obj.id = that.getView().byId("uniqueid").getValue();
			obj.name = that.getView().byId("nameid").getValue();
			obj.email = that.getView().byId("emailid").getValue();
			obj.mobile = that.getView().byId("mobid").getValue();
			myModel.create('/userdataSet', obj, {
				success : function(oData, oResponse) {
					debugger;
					alert('Record Created Successfully...');
				},
				error : function(err, oResponse) {
					debugger;
					alert('Error while creating record - '
							.concat(err.response.statusText));
				}
			});
		}
		// READ******************
		else if ('Read' == oEvent.oSource.mProperties.text) {
			var readurl = "/userdataSet?$filter=(id eq '')";
			myModel.read(readurl, {
				success : function(oData, oResponse) {
					debugger;
					var userdata = new sap.ui.model.json.JSONModel({
						"Result" : oData.results
					});
					var tab = that.getView().byId("userdatatable");
					tab.setModel(userdata);
					var i = 0;
					tab.bindAggregation("items", {
						path : "/Result",
						template : new sap.m.ColumnListItem({
							cells : [ new sap.ui.commons.TextView({
								text : "{id}",
								design : "H5",
								semanticColor : "Default"
							}), new sap.ui.commons.TextView({
								text : "{name}",
								design : "H5",
								semanticColor : "Positive"
							}), new sap.ui.commons.TextView({
								text : "{email}",
								design : "H5",
								semanticColor : "Positive"
							}), new sap.ui.commons.TextView({
								text : "{mobile}",
								design : "H5",
								semanticColor : "Positive"
							}), ]
						})
					});
				},
				error : function(err) {
					debugger;
				}
			});
		}		
		// UPDATE******************
		if ('Update' == oEvent.oSource.mProperties.text) {
			var obj = {};
			obj.id = that.getView().byId("uniqueid").getValue();
			obj.email = that.getView().byId("emailid").getValue();
			var updateurl = "/userdataSet(id='"
					+ that.getView().byId("uniqueid").getValue() + "')";

			myModel.update(updateurl, obj, {
				success : function(oData, oResponse) {
					debugger;
					alert('Record Updated Successfully...');
				},
				error : function(err, oResponse) {
					debugger;
					alert('Error while updating record - '
							.concat(err.response.statusText));
				}
			});
		}		
		// DELETE******************
		if ('Delete' == oEvent.oSource.mProperties.text) {
			var delurl = "/userdataSet(id='"
					+ that.getView().byId("uniqueid").getValue() + "')";
			myModel.remove(delurl, {
				success : function(oData, oResponse) {
					debugger;
					alert('Record Removed Successfully...');
				},
				error : function(err, oResponse) {
					debugger;
					alert('Error while removing record - '
							.concat(err.response.statusText));
				}
			});
		}
	}

Conserve, set up, and start the app. You should be able to execute the application using the following URL.

http://hostname:8000/sap/bc/ui5_ui5/sap/zcrud_demo/index.html

Output

CRUD Operation of ABAPers

You must be able to build the aforementioned simple application. All of the buttons should operate correctly. If you have any problems, please leave your queries in the comments area below. You may also email us at: career@technicalgyanguru.com.

you may be interested in this blog here :-

How to find BAdIs ?

Oracle database structure diagram

Boosting Customer Service with Salesforce and SharePoint Integration

Related Posts

SAP Netweaver Gateway and SAP OData. Section IV. OData Service Association and Navigation

As of our third tutorial in the series on SAP Netweaver Gateway and OData, our data models are built to independently retrieve item data from EKPO and header data from…

SAP Netweaver Gateway and OData. Section VI. Commonly Asked Questions

The SAP Netweaver Gateway and OData Tutorials’ five earlier sections included practical exercises along with some technical insights.Those lessons would be helpful and sufficient for ABAPers, but in order to…

Leave a Reply

Your email address will not be published. Required fields are marked *

You Missed

ABAP Programming Model for SAP Fiori – 11 – Enabling Draft Functionality for Transactional Apps

  • By Varad
  • September 17, 2024
  • 2 views
ABAP Programming Model for SAP Fiori – 11 – Enabling Draft Functionality for Transactional Apps

Just 4 Versions of the same program to understand OOPs ABAP

  • By Varad
  • September 16, 2024
  • 5 views

SAP Netweaver Gateway and OData SAP. Section I: A Brief History

  • By Varad
  • September 16, 2024
  • 3 views
SAP Netweaver Gateway and OData SAP. Section I: A Brief History

SAP Netweaver Gateway and OData. Section Two. Make your initial ODataService.

  • By Varad
  • September 14, 2024
  • 3 views

SAP Netweaver Gateway and SAP OData. Section 3. Options for Queries in OData Service URL

  • By Varad
  • September 13, 2024
  • 4 views

SAP Netweaver Gateway and SAP OData. Section IV. OData Service Association and Navigation

  • By Varad
  • September 12, 2024
  • 6 views