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 XI/PI – Invoice Attachment Transfer from ARIBA to VIM

The documents that are connected to the invoice in the Ariba Network system should be transferred to the VIM system via PI Integration as part of the Ariba Supplier Invoice…

Attachments for SAP XI/PI – ARIBA Invoices sent via PI to S/4HANA

Integration with SAP systems has never been more intriguing, especially with Ariba, Workday, Concur, Successfactors, Fieldglass, Hybris, and other satellite cloud solution vendors banging on doors every day. 🙂 I…

Leave a Reply

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

You Missed

Important T codes for FI GL AR AP

  • By Varad
  • December 21, 2024
  • 19 views
Important T codes for FI GL AR AP

Dynamically Download Data From Any SAP Table in ABAP-740 – Part 1

  • By Varad
  • December 20, 2024
  • 13 views
Dynamically Download Data From Any SAP Table in ABAP-740 – Part 1

Error While Setting Up Trusted System RFC

  • By Varad
  • December 19, 2024
  • 11 views
Error While Setting Up Trusted System RFC

 Credit Management T codes in SAP

  • By Varad
  • December 18, 2024
  • 24 views
 Credit Management T codes in SAP

Troubleshooting SAP BD22: Delete Change Pointer Not Picking Correct Processed Messages

  • By Varad
  • December 17, 2024
  • 56 views
Troubleshooting SAP BD22: Delete Change Pointer Not Picking Correct Processed Messages

Working with Shell Scripts in SAP ABAP Environment

  • By Varad
  • December 16, 2024
  • 34 views
Working with Shell Scripts in SAP ABAP Environment