Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
rajesh_salapu
Participant
Hi Readers !!

Hope Everyone are doing Good and safe.

Target Audience: Sapui5 Beginners.

In this blog post I am going to explain Crud operations (DELETE, ADD, EDIT and READ) with Raw JSON Data. It includes adding multiple records with Validations, delete multiple records and also edited multiple records.

Steps includes:

1.create a Responsive Table(sap.m)

2.Set Json data globally(manifest.json)

3.Call Global Json data in controller and create a model and call the model in our View Table (Aggregation Binding).

4.Edit Functionality

  • Throw a message if no record selected after click on edit.

  • If records are selected then the selected records will able to editable and also set key field to non-editable.

    • For this we use Expression Binding to set Visible true or False.

    • Show Save and Cancel Button at the Footer.



  • If we click on Save that records are saved and set that fields to non-editable.

    • Hide Save and Cancel Button at the Footer.



  • If we click on Cancel the edited record retrieve its old data.

    • Hide Save and Cancel Button at the Footer.




5.Add Functionality

  • If we click on Add a record added at the end of the Table.

    • Hide Edit and Delete Buttons

    • Show Save and Cancel at the Footer

    • The added record able to Editable to enter data

    • If we click on Save check validations

      • Empty record cannot be added

      • Duplicate record not allowed and able to show Error Status

      • If all Validations are clear then added records able to added successfully.

      • Show Edit and Delete Buttons

      • Hide Save and Cancel at the Footer



    • If we click on cancel the Added records are able to delete without selecting record.

      • Show Edit and Delete Buttons

      • Hide Save and Cancel at the Footer






6.Delete functionality

  • If we click on Delete user can able Delete selected records Successfully.


 

1.create a Responsive Table(sap.m): View1.view


In the above pic Column Contains:


Each HBox contains text Box and Input By using expression Binding we Visible the content.


 

2.Set Json data globally(manifest.json)


Here we declare our model globally.so we use this data in any view.

 

3.Call Global Json data in controller and create a model and call the model in our View Table (Aggregation Binding).


 

4.Edit Functionality

  • Throw a message if no record selected after click on edit.


If we click on Edit with out selecting record it shows message Like this:




  • If records are selected then the selected records will able to editable and also set key field to non-editable.

  • For this we use Expression Binding to set Visible true or False.

  • We Set Properties of newmodel Editable when click on edit.

    newmodel:



  • sOrder1 contains edit field .Edit functionality in View1.controller.js





  • Show Save and Cancel Button at the Footer.

  • If we click on Save that records are saved and set that fields to non-editable.


                       Hide Save and Cancel Button at the Footer.



Save Functionality in View1.controller:




  • If we click on Cancel the edited record retrieve its old data.


  • When click on cancel it retrieves old data.




  • Cancel Functionality on Edit:



  • 5.Add Functionality

    • If we click on Add a record added at the end of the Table.

      • Hide Edit and Delete Buttons

      • Show Save and Cancel at the Footer

      • The added record able to Editable to enter data




    I click Add Button





  • If we click on Save check validations

    • Empty record cannot be added

    • Duplicate record not allowed and able to show Error Status

    • If all Validations are clear then added records able to added successfully.

    • Show Edit and Delete Buttons

    • Hide Save and Cancel at the Footer








If all Validations Pass it saves the record when click on Save:


Add Functionality when click on Add:





  • Save Functionality in Add:

  • Validations:If we click on cancel the Added records are able to delete without selecting record.

    • Show Edit and Delete Buttons

    • Hide Save and Cancel at the Footer






When user click on cancel it deletes the added record without selection

  • Cancel Functionality in Add:6.Delete functionality

    • Select the records to delete

    • If we click on Delete user can able Delete selected records Successfully.

      Delete Functionality:






View1.view.code:
<mvc:View controllerName="comcurdTask.controller.View1" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core">
<App>
<Page title="{i18n>title}" enableScrolling="true" class="sapUiContentPadding" showFooter="false" showSubHeader = "false">
<content>
<Table id="idSalesTable" growing="true" items="{ path: 'sOrder1>/Sales' }" mode="MultiSelect" selectionChange="onselectionChange">
<headerToolbar>
<OverflowToolbar id="otbSubheader">
<Title text="Products" level="H2"/>
<ToolbarSpacer/>
<Button id="editButton" text="Edit" type="Transparent" press="onEdit" visible = "{newModel>/edit}" />
<Button id="addButton" text="Add" type="Transparent" press="onAdd" visible="{newModel>/add}"/>
<Button id="deleteButton" text="Delete" type="Transparent" press="onDelete" visible= "{newModel>/delete}"/>
<Button id="_IDGenButton1" icon="sap-icon://action-settings" press="onPersoButtonPressed" />
</OverflowToolbar>
</headerToolbar>
<columns>
<Column minScreenWidth="Tablet">
<Text text="SalesOrder"/>
</Column>
<Column minScreenWidth="Tablet" demandPopin="true">
<Text text="SoldToParty"/>
</Column>
<Column minScreenWidth="Tablet" demandPopin="true">
<Text text="CustomerReference"/>
</Column>
<Column>
<Text text="RequestedDeliveryDate"/>
</Column>
<Column minScreenWidth="Tablet" demandPopin="true">
<Text text="OveralllStatus"/>
</Column>
</columns>
<items >
<ColumnListItem vAlign="Middle" press="tableSelected">
<cells>
<HBox visible="true">
<Text text="{sOrder1>SalesOrder}" visible="{= ${newModel>/editable} === true ? ${sOrder1>neweditable} === true ? false:true :true}" />
<Input change="onChange" value="{sOrder1>SalesOrder}" visible="{= ${newModel>/editable} === true ? ${sOrder1>neweditable} === true ? true:false:false}" valueState="{newModel>/valueState}" liveChange="onLiveChange"></Input>
</HBox>
<HBox visible="true">
<Text text="{sOrder1>SoldToParty}" visible="{= ${sOrder1>editable} === true ? false:true}"/>
<Input value="{sOrder1>SoldToParty}" visible="{= ${sOrder1>editable} === true ? true:false}"></Input>
</HBox>
<HBox visible="true">
<Text text="{sOrder1>CustomerReference}" visible="{= ${sOrder1>editable} === true ? false:true}"/>
<ComboBox change="handleChange" items="{ path: 'statusModel>/reference' }" value="{sOrder1>CustomerReference}" visible="{= ${sOrder1>editable} === true ? true:false}">
<core:Item text="{statusModel>CustomerReference}"/>
</ComboBox>
</HBox>
<HBox visible="true">
<Text text="{sOrder1>RequestedDeliveryDate}" visible="{= ${sOrder1>editable} === true ? false:true}"/>
<DatePicker valueFormat="dd-MM-yyyy" displayFormat="dd-MM-yyyy" value="{sOrder1>RequestedDeliveryDate}" visible="{= ${sOrder1>editable} === true ? true:false}"></DatePicker>
</HBox>
<HBox visible="true">
<Text text="{newModel>/status}" visible="{= ${sOrder1>editable} === true ? false:true}"/>
<Text text="{newModel>/status1}" visible="{= ${sOrder1>editable} === true ? true:false}"/>
</HBox>
</cells>
</ColumnListItem>
</items>
</Table>
</content>
<footer>
<OverflowToolbar >
<ToolbarSpacer/>
<Button id="saveButton" text="Save" type="Accept" press="onSave" />
<Button id="cancelButton" text="Cancel" type="Reject" press="onCancel"/>
</OverflowToolbar>
</footer>
</Page>
</App>
</mvc:View>

View1.controller.js:
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"sap/m/MessageToast",
"sap/ui/model/Filter",
"sap/ui/model/FilterOperator"
], function(Controller, JSONModel, MessageToast, Filter, FilterOperator) {
"use strict";

return Controller.extend("comcurdTask.controller.View1", {
onInit: function(oEvent) {
this.mode = undefined;

var dataModel = this.getOwnerComponent().getModel("tableData");
this.getView().setModel(dataModel, "sOrder1");

this.temp = JSON.stringify(this.getView().getModel("sOrder1").getData());



// create a new model for property binding .for visible property
var newModel1 = new JSONModel({
visibleHeader: true,
"editable": false,
"valueState": "None",
"add": true,
"edit": true,
"delete": true,
"status":"completed",
"status1":"Edited"

});
this.getView().setModel(newModel1, "newModel");

var statusModel1 = new JSONModel({
"reference": [{
"CustomerReference": "A"
}, {
"CustomerReference": "B"

}, {
"CustomerReference": "C"

}]
});
this.getView().setModel(statusModel1, "statusModel");
},

onDelete: function(oEvent) {
this.mode = "delete";
var that = this;
var sData = oEvent.getSource().getModel("sOrder1").getData();
var oTable = this.byId("idSalesTable");
var selectedRowData = oTable.getSelectedContexts();//get the selected contexts
if (selectedRowData.length === 0) {
MessageToast.show("please select atleast one row");
return;
} else {

for (var i = selectedRowData.length - 1; i >= 0; i--) {
var oThisObj = selectedRowData[i].getObject();
var index = $.map(sData.Sales, function(obj, index) {
if (obj === oThisObj) {
return index;
}
});
sData.Sales.splice(index, 1);//delete record by using Splice
}
that.getView().getModel("sOrder1").setData(sData);//after deleting set the data
// this._oTable.getModel().setData(sData);
oTable.removeSelections(true);
}
},
onEdit: function(oEvent) {
// this.mode is a global varible
this.mode = "Edit";
var that = this;
// declare a arry for holding old records.
this.oldDataArry = [];
// var sData = oEvent.getSource().getModel("sOrder1").getData();
var oTable = this.byId("idSalesTable");
// selected row data containts selected records to edit
var selectedRowData = oTable.getSelectedContexts();

if (selectedRowData.length === 0) {//this condiction check wheather the records got selected or not
MessageToast.show("please select atleast one row");

return;
} else {

oEvent.getSource().getParent().getParent().getParent().setShowFooter(true);//one of the way to show the footer
that.getView().getModel("newModel").setProperty("/add", false);//we set property add to false so that it disappear when click on edit button
that.getView().getModel("newModel").setProperty("/delete", false);//we set property delete to false so that it disappear when click on edit button
that.getView().getModel("newModel").setProperty("/editable", false);//we set property editable to false so that first property is non-editable
selectedRowData.forEach(function(item) {
var sContext = item;
var sPath = sContext.getPath();
var sObj = sContext.getObject();
var oldObj = {//here old Obj collects selected data
sPath: sPath,
sObj: JSON.stringify(sObj)//Json.Stringfy method used to convert in String format
};
that.oldDataArry.push(oldObj);//append the record to arry which we declare before
sObj.editable = true;//by using this property we enable inputfeilds visible

that.getView().getModel("sOrder1").setProperty(sPath, sObj, sContext, true);//finally we set record in model in that path

});

}

},
onLiveChange: function(oEvent) {
this.enteredValue = oEvent.getParameter("value");

},
onAdd: function(oEvent) {
this.mode = "Add";
var that = this;
oEvent.getSource().getParent().getParent().getParent().setShowFooter(true);
that.getView().getModel("newModel").setProperty("/edit", false);
that.getView().getModel("newModel").setProperty("/add", true);
that.getView().getModel("newModel").setProperty("/delete", false);
that.getView().getModel("newModel").setProperty("/editable", true);

var newRecord = {//create a dummy record to push when user click on Add
"SalesOrder": "",
"SoldToParty": "",
"CustomerReference": "",
"RequestedDeliveryDate": "",
"OveralllStatus": "",
"editable": true,
"neweditable": true
};
var oTableData = oEvent.getSource().getModel("sOrder1").getData();//get table data
oTableData.Sales.push(newRecord);//push this new record in model
that.getView().getModel("sOrder1").setData(oTableData);//set data to the view
},

onChange: function(oEvent) {
var that = this;
var enteredText = oEvent.getParameters("value").value;
this.recordexists = undefined;
// var index=undefined;
var sData = this.getView().getModel("sOrder1").getData().Sales;//get the moedl data
var spath = parseInt(oEvent.getSource().getBindingContext("sOrder1").getPath().split("/")[2]);//get the index of enter data row

var index = sData.findIndex(function(item, sindex) {//findIndex is a method used to validate if same value found it returns index position othervise it returns -1
return item.SalesOrder === enteredText && sindex !== spath;
});
if (index > -1) {
this.recordexists = index;
that.getView().getModel("newModel").setProperty("/valueState", "Error");//set value state to error
MessageToast.show("entered sales order is alreay exists");

return;
}
that.getView().getModel("newModel").setProperty("/valueState", "None");


},
onSave: function(oEvent) {
var that = this;
if (this.mode === "Edit") {//if user click on save in edit functionality
var oTable = this.byId("idSalesTable");
var selectedRowData = oTable.getSelectedContexts();
selectedRowData.forEach(function(item) {
var sContext = item;
var sPath = sContext.getPath();
var sObj = sContext.getObject();
sObj.editable = false;//we set editable false
that.getView().getModel("sOrder1").setProperty(sPath, sObj, sContext, true);

});
oEvent.getSource().getParent().getParent().setShowFooter(false);//we set property add to false so that footer disappear when click on save button
that.getView().getModel("newModel").setProperty("/edit", true);//we set property add to true so that it appers when click on save button
that.getView().getModel("newModel").setProperty("/add", true);//we set property add to true so that it appers when click on save button
that.getView().getModel("newModel").setProperty("/delete", true);//we set property delete to true so that it appers when click on save button
MessageToast.show("Record updated Successfully");//throws a message
return;

} else if (this.mode === "Add") {
var sData = oEvent.getSource().getModel("sOrder1").getData().Sales;//get the table data
var sIndex = sData.length - 1;//get the length of the sdata
if (this.recordexists !== undefined) {
MessageToast.show("SalesOrder Number is already exists");

return;

} else {
for (var i = 0; i <= sIndex; i++) {

if (sData[i].editable === true) {//check feilds which are Appended by click on Add
if (sData[i].SalesOrder === "") {//check if the entered data is black then it throws a error message
MessageToast.show("SalesOrder Number is cannot be empty");
return;
} else {
sData[i].editable = false;//if record is not blank set editable to false
sData[i].neweditable = false;//this is for first property
that.getView().getModel("sOrder1").setProperty("/Sales/" + i, sData[i]);//set property binding for that records
that.getView().getModel("newModel").setProperty("/edit", true);//edit button visible
that.getView().getModel("newModel").setProperty("/add", true);//add button visible
that.getView().getModel("newModel").setProperty("/delete", true);//delete button visible
that.getView().getModel("newModel").setProperty("/editable", false);//we set property editable to false so that first property is non-editable
oEvent.getSource().getParent().getParent().setShowFooter(false);//footer false
MessageToast.show("Record saved Successfully");
}
}
}
}
}

},
onCancel: function(oEvent) {
if (this.mode === "Edit") {

var that = this;
var oTable = this.byId("idSalesTable");
// var selectedRowData = oTable.getSelectedContexts();

this.oldDataArry.forEach(function(item) {
// var sContext = item;
var sPath = item.sPath;
var sObj = JSON.parse(item.sObj);
sObj.editable = false;
that.getView().getModel("sOrder1").setProperty(sPath, sObj, true);
});
oEvent.getSource().getParent().getParent().setShowFooter(false);
that.getView().getModel("newModel").setProperty("/edit", true);
that.getView().getModel("newModel").setProperty("/add", true);
that.getView().getModel("newModel").setProperty("/delete", true);
oTable.removeSelections(true);

} else if (this.mode === "Add") {
var oTable = this.byId("idSalesTable");
var sData = oEvent.getSource().getModel("sOrder1").getData().Sales;
var sIndex = sData.length - 1;
for (var i = sIndex; i >= 0; i--) {
var cellsInEdit = sData[i].editable;
if (cellsInEdit === true) {
sData.splice(i, 1);//delete a record by slice method

}
oTable.removeSelections(true);
}
this.getView().getModel("sOrder1").setProperty("/Sales/", sData);
oEvent.getSource().getParent().getParent().setShowFooter(false);
this.getView().getModel("newModel").setProperty("/edit", true);
this.getView().getModel("newModel").setProperty("/add", true);
this.getView().getModel("newModel").setProperty("/delete", true);
MessageToast.show("Record saved Successfully");
}

}

});
});

 

Conclusion: Hope this blog post will give better understanding for beginners to Work on Crud operations using local data.

Thanks for Reading.

Stay home Stay safe.

Thank You

Rajesh Salapu
8 Comments
Labels in this area