Skip to Content
Technical Articles
Author's profile photo Pooja D S

How to Add/Remove rows in the table by the button click in SAP Ui5

Hi Everyone,

In this blog I’m going to explain how to add a new input row to the table by the button click in the sap Ui5 which will help the beginners, for more information about table : https://sapui5.hana.ondemand.com/sdk/#/api/sap.m.Table%23controlProperties

Firstly we need to create a project, then in view we have to write a code for the simple table and I just added the property as delete to delete the row using this property.

1.Xml

<mvc:View controllerName="addrow.addrow.controller.View1" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
	<Shell id="shell">
		<App id="app">
			<pages>
				<Page id="page" title="AddingRow">
					<content>
						<Table id="tableId1" width="60%" mode="Delete" delete="deleteRow">
							<headerToolbar>
								<Toolbar>
									<ToolbarSpacer></ToolbarSpacer>
									<Button icon="sap-icon://add" type="Emphasized" press="onAdd"/>
								</Toolbar>
							</headerToolbar>
							<columns>
								<Column width="50%">
									<Text text="Delete Items"/>
								</Column>
								<Column width="50%">
									<Text text="First Name"/>
								</Column>
								<Column width="50%">
									<Text text="Last Name"/>
								</Column>
								<Column width="50%">
									<Text text="Salary"/>
								</Column>
							</columns>
						</Table>
					</content>
				</Page>
			</pages>
		</App>
	</Shell>
</mvc:View>

2.Controller.js

In the controller, I’ve written the function for both adding the row to the table and deleting the row from the table.

so by writing these functionality we can achieve this thing and JavaScript plays a major role here. please follow these 3 steps.

Step 1: To Add a row to the table

    onAdd: function (oEvent) {                               //to add a new row
			 var oItem = new sap.m.ColumnListItem({
				cells: [new sap.m.Button({
					icon: "sap-icon://delete",
					type: "Reject",
					press: [this.remove, this]
				}), new sap.m.Input(), new sap.m.Input(), new sap.m.Input({
					showValueHelp: true

				}), ]
			});

			var oTable = this.getView().byId("tableId1");
			oTable.addItem(oItem);
     },

In the above function I’ve written the code for adding the row to the table,

  • I’ve taken the addItem method to add or create the row to the table which we can see in the function
  • new sap.m.Input() creates a new input boxes to the row, if we want dropdown or value help we can also customize as shown in the output picture
  • table id must be match in view and in this function as well

Step 2: To Delete a row from the table (Delete Bin Icon)

	remove: function (oEvent) {
			var oTable = this.getView().byId("tableId");
			oTable.removeItem(oEvent.getSource().getParent());
		}

In this function

  • table id must be match in view and in this function as well
  • we need to add removeItem method to delete action
  • In the addRow function we can see i’ve written  press: [this.remove, this] which is calling here

Step 3: To Delete a row from the table using tables property (Delete X Icon)

	deleteRow: function (oEvent) {
			var oTable = this.getView().byId("tableId");
			oTable.removeItem(oEvent.getParameter("listItem"));
		},

In the above function

  • we need to add removeItem method to delete action
  • table id must be match in view and in this function as well

Output :

In the below picture we can see how the rows are added by clicking on the ‘+’ button at the right top corner and deleting the rows as well by clicking on the  delete ‘Bin’ button or ‘x’ button.

Conclusion:

From the above scenario, we will learn how to add row to the table and delete a row from table using table property also using button I’ve created in the controller using xml and js.

it is very useful for the beginners and hope it will help them too. please give me your feedback as well to improve my future blogs.

Happy learning folks!!!

Regards,

Pooja D S

Assigned Tags

      10 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Boghyon Hoffmann
      Boghyon Hoffmann

      When using the generated removeXYZ methods (e.g. removeItem), please keep in mind that the removed control is not destroyed even if it's no longer displayed in the UI. Cf. https://stackoverflow.com/a/71131717/5846045

      I.e. in our case here, removeItem(...).destroy(); would help destroying the removed item additionally.

      Author's profile photo Pooja D S
      Pooja D S
      Blog Post Author

      yes, thanks for the info Boghyon Hoffmann .

      Author's profile photo Ramin Shafai
      Ramin Shafai

      I'm sorry Pooja, but can you please explain how this would have any practical purpose?

      In SAPUI5 applications, tables are (should be) used to show data, which means they are bound to a model, eg. an oData or a JSON model.

      If you want to add a row to the table, you just add an entry to the model that the table is bound to. If you want to remove a row, you remove the corresponding path from the bound context.

      That's part of the idea behind MVC, the Model drives the View.

      The table you show here is not bound to anything, and you hard-code the template in your controller to add a row to the table. The new row will not be bound to anything, what would you do with the data if the user enters something in those input fields? Perhaps in a Javascript forum this may be useful, but for a SAPUI5 program I just don't think this is good practice. 

      Thanks.

       

      Author's profile photo Pooja D S
      Pooja D S
      Blog Post Author

      Hi Ramin,

      this will help to the beginners, and yes I didn't binded the table with json or data here in this example because in this blog my purpose is to tell "How to Add/Remove rows in the table by the button click in SAP Ui5" not to focus on binding, maybe i'll cover it in future, thanks for the feedback.

      thanks.

      Author's profile photo Arpan Dashore
      Arpan Dashore

      Thank you it's very helpful for beginners, upload more like that so we can become good at that.

      Author's profile photo Pooja D S
      Pooja D S
      Blog Post Author

      Thanks Arpan, sure will upload more in coming days.

      Author's profile photo Sandeep Suggu
      Sandeep Suggu

      Thank You Pooja D S ,
      very helpful for beginners.
      Looking forward many more blogs like this

      The Problem i faced & got rectified,

      Those who are looking at this blog & executing the code in the same way Observe the things,

      Delete & Remove Option will not work.

      In View :

      <Table id="tableId1" width="60%" mode="Delete" delete="deleteRow">

      In Controls :

      remove: function (oEvent) {
      			var oTable = this.getView().byId("tableId1");
      			oTable.removeItem(oEvent.getSource().getParent());
      		},
      
      		deleteRow: function (oEvent) {
      			var oTable = this.getView().byId("tableId1");
      			oTable.removeItem(oEvent.getParameter("listItem"));
      		},

      Make Sure Id of Table need to change.

      Thank You,
      Suggu Sandeep.

      Author's profile photo Mahmood Shakir Hammood
      Mahmood Shakir Hammood

      Hello Pooja D S,

       

      I have this table and I want to add additional delete mode. I want to delete row directly from kyeboard. how I make this?

       

      thank you

      Author's profile photo Mahmood Shakir Hammood
      Mahmood Shakir Hammood
      <mvc:View controllerName="com.volkswagen.ifdb.cc.sopraempApplication.controller.Overview" height="100%" xmlns:mvc="sap.ui.core.mvc"
      	xmlns:core="sap.ui.core" xmlns="sap.m" xmlns:f="sap.f" xmlns:fb="sap.ui.comp.filterbar" xmlns:svm="sap.ui.comp.smartvariants"
      	xmlns:html="http://www.w3.org/1999/xhtml" xmlns:smartTable="sap.ui.comp.smarttable" xmlns:smartFilterBar="sap.ui.comp.smartfilterbar">
      	<App id="app">
      		<f:DynamicPage id="page" headerExpanded="{/headerExpanded}">
      			<f:title>
      				<f:DynamicPageTitle>
      					<f:heading>
      						<svm:SmartVariantManagement id="svm" showExecuteOnSelection="true"/>
      					</f:heading>
      					<f:expandedContent>
      						<Label id="expandedLabel" text="No filters active"/>
      					</f:expandedContent>
      					<f:snappedContent>
      						<Label id="snappedLabel" text="No filters active"/>
      					</f:snappedContent>
      				</f:DynamicPageTitle>
      			</f:title>
      			<f:header>
      				<f:DynamicPageHeader>
      					<f:content>
      						<fb:FilterBar id="filterbar" persistencyKey="myPersKey" useToolbar="false" search=".onSearch" filterChange=".onFilterChange"
      							afterVariantLoad=".onAfterVariantLoad">
      							<fb:filterGroupItems>
      								<fb:FilterGroupItem name="Name" label="Name" groupName="Group1" visibleInFilterBar="true">
      									<fb:control>
      										<MultiComboBox name="Name" selectionChange=".onSelectionChange" items="{ path: '/ProductNames', templateShareable: true }">
      											<core:Item key="{key}" text="{name}"/>
      										</MultiComboBox>
      									</fb:control>
      								</fb:FilterGroupItem>
      								<fb:FilterGroupItem name="Category" label="Category" groupName="Group1" visibleInFilterBar="true">
      									<fb:control>
      										<MultiComboBox name="Category" selectionChange=".onSelectionChange" items="{ path: '/ProductCategories', templateShareable: true }">
      											<core:Item key="{key}" text="{name}"/>
      										</MultiComboBox>
      									</fb:control>
      								</fb:FilterGroupItem>
      								<fb:FilterGroupItem name="SupplierName" label="SupplierName" groupName="Group1" visibleInFilterBar="true">
      									<fb:control>
      										<MultiComboBox name="SupplierName" selectionChange=".onSelectionChange" items="{ path: '/ProductSuppliers', templateShareable: true }">
      											<core:Item key="{key}" text="{name}"/>
      										</MultiComboBox>
      									</fb:control>
      								</fb:FilterGroupItem>
      							</fb:filterGroupItems>
      						</fb:FilterBar>
      					</f:content>
      				</f:DynamicPageHeader>
      			</f:header>
      			<f:content>
      				<!--<smartTable:SmartTable>
      		    			<Table id="table" inset="false" items="{path: '/ProductCollection'}" itemPress="onPress" >
      		    			    <columns>
      					<Column>
      						<Text text="Name"/>
      					</Column>
      					<Column>
      						<Text text="Category"/>
      					</Column>
      					<Column>
      						<Text text="SupplierName"/>
      					</Column>
      					<Column>
      						<Text text="Status"/>
      					</Column>
      					<Column>
      						<Text text="DateOfProduction"/>
      					</Column>
      					<Column>
      						<Text text="Price"/>
      					</Column>
      				</columns>
      				<items  >
      					<ColumnListItem vAlign="Middle" type="Navigation" >
      						<cells>
      							<ObjectIdentifier title="{Name}" text="{ProductId}"/>
      							<Text text="{Category}"/>
      							<Text text="{SupplierName}"/>
      							<ObjectIdentifier title="{Status}" text="{Quantity}"/>
      							<Text text="{DateOfProduction}"/>
      							<ObjectNumber number="{Price}" unit="{CurrencyCode}"/>
      						</cells>
      					</ColumnListItem>
      				</items>
      		    			</Table>
      				
      		    		    	</smartTable:SmartTable>-->
      				<Table id="table" inset="false" items="{path: '/ProductCollection'}" itemPress="onPress" mode="MultiSelect">
      				   
      					<headerToolbar>
      						<Toolbar>
      							<ToolbarSpacer/>
      							<Button icon="sap-icon://delete" text="" press="onRemoveRowsUi"/>
      						</Toolbar>
      					</headerToolbar>
      				
      					<columns>
      						<!--	<Column width="5em">
      						    
      							<CheckBox select="selectAll" />
      						</Column>-->
      						<Column>
      							<Text text="Name"/>
      						</Column>
      						<Column>
      							<Text text="Category"/>
      						</Column>
      						<Column>
      							<Text text="SupplierName"/>
      						</Column>
      						<Column>
      							<Text text="Status"/>
      						</Column>
      						<Column>
      							<Text text="DateOfProduction"/>
      						</Column>
      						<Column>
      							<Text text="Price"/>
      						</Column>
      					</columns>
      					<items >
      						<ColumnListItem vAlign="Middle" type="Navigation" >
      						
      							<cells >
      							  
      								<!--	<RadioButton id="selected" text="" selected="true"/>-->
      								<ObjectIdentifier title="{Name}" text="{ProductId}"/>
      								<Text text="{Category}"/>
      								<Text text="{SupplierName}"/>
      								<ObjectIdentifier title="{Status}" text="{Quantity}"/>
      								<Text text="{DateOfProduction}"/>
      								<ObjectNumber number="{Price}" unit="{CurrencyCode}"/>
      							</cells>
      						</ColumnListItem>
      					</items>
      
      				</Table>
      			</f:content>
      		</f:DynamicPage>
      	</App>
      </mvc:View>
      <!--<mvc:View controllerName="com.volkswagen.ifdb.cc.sopraempApplication.controller.Overview" xmlns:html="http://www.w3.org/1999/xhtml"
      	xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
      	<App>
      		<pages>
      			<Page title="{i18n>title}">
      				<content></content>
      			</Page>
      		</pages>
      	</App>
      </mvc:View>-->
      Author's profile photo Mahmood Shakir Hammood
      Mahmood Shakir Hammood
      ////sap.ui.define is a function used for module definition. It allows to define dependencies and 
      //specify the callback function that will be executed when all dependencies are loaded.
      sap.ui.define([
      	"sap/ui/core/mvc/Controller",
      	"sap/ui/model/json/JSONModel",
      	"sap/m/Label",
      	"sap/ui/model/Filter",
      	"sap/ui/model/FilterOperator",
      	"sap/ui/comp/smartvariants/PersonalizableInfo",
      	"sap/m/MessageToast",
      	"sap/ui/core/Core",
      	"sap/ui/events/KeyCodes"
      	////are the arguments of the callback function, representing the loaded modules.
      ], function(Controller, JSONModel, Label, Filter, FilterOperator, PersonalizableInfo, MessageToast, Core, KeyCodes) {
      	"use strict";
      
      	return Controller.extend("com.volkswagen.ifdb.cc.sopraempApplication.controller.Overview", {
      		onInit: function() {
      			//the controller's onInit method initializes the oRouter property with the router object obtained
      			//from the owner component using getOwnerComponent().getRouter()
      			this.oRouter = this.getOwnerComponent().getRouter();
      
      			this.oModel = new sap.ui.model.json.JSONModel();
      			this.oModel.loadData("model.json");
      			this.getView().setModel(this.oModel);
      
      			this.oSmartVariantManagement = this.getView().byId("svm");
      			this.oExpandedLabel = this.getView().byId("expandedLabel");
      			this.oSnappedLabel = this.getView().byId("snappedLabel");
      			this.oFilterBar = this.getView().byId("filterbar");
      			this.oTable = this.getView().byId("table");
      
      			var oPersInfo = new PersonalizableInfo({
      				type: "filterBar",
      				keyName: "persistencyKey",
      				dataSource: "",
      				control: this.oFilterBar
      			});
      			this.oSmartVariantManagement.addPersonalizableControl(oPersInfo);
      			this.oSmartVariantManagement.initialise(function() {}, this.oFilterBar);
      
      		},
      		selectAll: function(oEvent) {
      			var otab = this.byId("table"); // Fetch the table
      
      			var bSelected = oEvent.getParameter('selected'); // fetch whether user selected/de-selected all
      
      			otab.getItems().forEach(function(item) { // loop over all the items in the table
      				var oCheckBoxCell = item.getCells()[0]; //fetch the cell which holds the checkbox for that row.
      
      				oCheckBoxCell.setSelected(bSelected); // Select/de-select each checkbox
      			});
      		},
      	
      
      		onRemoveRowsUi: function() {
      			var oTable = this.getView().byId("table");
      			var aSelectedItems = oTable.getSelectedItems();
      
      			if (aSelectedItems.length === 0) {
      				sap.m.MessageToast.show("No items selected.");
      				return;
      			}
      
      			var that = this;
      
      			sap.m.MessageBox.confirm("Are you sure you want to remove the selected items?", {
      				title: "Confirmation",
      				onClose: function(oAction) {
      					if (oAction === sap.m.MessageBox.Action.OK) {
      						aSelectedItems.forEach(function(oSelectedItem) {
      							oTable.removeItem(oSelectedItem);
      						});
      
      						that.getView().getModel().refresh();
      						sap.m.MessageToast.show("Selected items removed successfully.");
      					}
      				}
      			});
      
      			console.log("The removed items are still stored in the model");
      			console.log(this.getView().getModel().getData());
      
      		},
      		
      
      		onPress: function(oEvent) {
      			var oItem = oEvent.getParameters("items").listItem.getBindingContextPath().split('/')[2];
      			/*var oRouter = this.getOwnerComponent().getRouter();*/
      			this.oRouter.navTo("detail", {
      				ProductId: oItem
      			});
      		},
      
      		/*    var sProductId = oItem.getBindingContext().getProperty("ProductId");*/
      
      		/*    var oRouter = sap.ui.core.UIComponent.getRouterFor(this);*/
      		/*oRouter.navTo("detail", {
      		    ProductId: sProductId
      		}*/
      
      		onSelectionChange: function(oEvent) {
      			this.oSmartVariantManagement.currentVariantSetModified(true);
      			this.oFilterBar.fireFilterChange(oEvent);
      		},
      
      		onSearch: function() {
      			var aTableFilters = this.oFilterBar.getFilterGroupItems().reduce(function(aResult, oFilterGroupItem) {
      				var oControl = oFilterGroupItem.getControl(),
      					aSelectedKeys = oControl.getSelectedKeys(),
      					aFilters = aSelectedKeys.map(function(sSelectedKey) {
      						return new Filter({
      							path: oFilterGroupItem.getName(),
      							operator: FilterOperator.Contains,
      							value1: sSelectedKey
      						});
      					});
      
      				if (aSelectedKeys.length > 0) {
      					aResult.push(new Filter({
      						filters: aFilters,
      						and: false
      					}));
      				}
      
      				return aResult;
      			}, []);
      
      			this.oTable.getBinding("items").filter(aTableFilters);
      			this.oTable.setShowOverlay(false);
      		},
      
      		onFilterChange: function() {
      			this._updateLabelsAndTable();
      		},
      
      		onAfterVariantLoad: function() {
      			this._updateLabelsAndTable();
      		},
      
      		getFormattedSummaryText: function() {
      			var aFiltersWithValues = this.oFilterBar.retrieveFiltersWithValues();
      
      			if (aFiltersWithValues.length === 0) {
      				return "No filters active";
      			}
      
      			if (aFiltersWithValues.length === 1) {
      				return aFiltersWithValues.length + " filter active: " + aFiltersWithValues.join(", ");
      			}
      
      			return aFiltersWithValues.length + " filters active: " + aFiltersWithValues.join(", ");
      		},
      
      		getFormattedSummaryTextExpanded: function() {
      			var aFiltersWithValues = this.oFilterBar.retrieveFiltersWithValues();
      
      			if (aFiltersWithValues.length === 0) {
      				return "No filters active";
      			}
      
      			var sText = aFiltersWithValues.length + " filters active",
      				aNonVisibleFiltersWithValues = this.oFilterBar.retrieveNonVisibleFiltersWithValues();
      
      			if (aFiltersWithValues.length === 1) {
      				sText = aFiltersWithValues.length + " filter active";
      			}
      
      			if (aNonVisibleFiltersWithValues && aNonVisibleFiltersWithValues.length > 0) {
      				sText += " (" + aNonVisibleFiltersWithValues.length + " hidden)";
      			}
      
      			return sText;
      		},
      
      		_updateLabelsAndTable: function() {
      			this.oExpandedLabel.setText(this.getFormattedSummaryTextExpanded());
      			this.oSnappedLabel.setText(this.getFormattedSummaryText());
      			this.oTable.setShowOverlay(true);
      		}
      	});
      });