cancel
Showing results for 
Search instead for 
Did you mean: 

I am trying to add an new item but I get an empty item in my table

mahmood_hammood
Participant
0 Kudos
585

Hello,

When I add an new item by using add icon onmy page everything happens in true way. But when I try to add an new item by useng (insert) from kyeboard , then write the new item info and click on add button on dialog view, I get new item but without info, empty cells. can somene help me please?

////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/m/Dialog",
	"sap/m/Button",
	"sap/m/Text"
	////are the arguments of the callback function, representing the loaded modules.
], function(Controller, JSONModel, Label, Filter, FilterOperator, PersonalizableInfo, MessageToast, Core, Dialog, Button, Text) {
	"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);

			// Attach a keydown event listener to the table
			//An event delegate is an object that handles events for a specific control.
			/*onkeydownx is defined as an anonymous function within the event delegate*/
			/*The onkeydown function is defined as an anonymous function within the event delegate.
			     It takes an oEvent parameter, which represents the event object for the keydown event.*/
			// Check if the Delete key is pressed
			/*console.log(oEvent.keyCode);*/

			var table = this.byId("table");
			table.addEventDelegate({
				onkeydown: function(oEvent) {
					if (oEvent.keyCode === 46) {
						this.onRemoveRowsUi();
					}
					/*	if (oEvent.keyCode === 45) {
							this.onCreate();
						}*/
				}.bind(this)
			});
			var view = this.getView();
			view.addEventDelegate({
				onkeydown: function(oEvent) {
					if (oEvent.keyCode === 45) { // Check if Insert key is pressed
						this.onOpenDialog(); // Call the onOpenDialog function to open the dialog
					}
				}.bind(this)
			});

		},
		onOpenDialog: function() {
			var dialog = this.getView().byId("oDialogCreate");
			dialog.setVisible(true);
			dialog.open();
		},

		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
			});
		},

		onPress: function(oEvent) {
			var oItem = oEvent.getParameters("items").listItem.getBindingContextPath().split('/')[2];
			/*var oRouter = this.getOwnerComponent().getRouter();*/
			this.oRouter.navTo("detail", {
				ProductId: oItem
			});
		},

		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);
		},

		onCreate: function() {

			this.getView().byId("oDialogCreate").setVisible(true).open(); //Refers to the current view object. is used to retrieve the current view instance.This makes the control visible on the screen.
		},

		onAdd: function() {
			// Get the input field values
			var name = this.byId("nameInput").getValue();
			var category = this.byId("categoryInput").getValue();
			var supplier = this.byId("supplierInput").getValue();
			var status = this.byId("statusInput").getValue();
			var dateOfProduction = this.byId("dateOfProductionInput").getValue();
			var price = this.byId("priceInput").getValue();

			// Create a new item object with the entered values
			var newItem = {
				Name: name,
				Category: category,
				SupplierName: supplier,
				Status: status,
				DateOfProduction: dateOfProduction,
				Price: price
			};

			// Get the table model and add the new item to it
			var oTable = this.byId("table");
			var oModel = oTable.getModel();
			var aItems = oModel.getProperty("/ProductCollection");
			aItems.push(newItem);
			oModel.setProperty("/ProductCollection", aItems);

			// Close the dialog
			this.byId("oDialogCreate").close();
		},

		onCancel: function() {
			this.getView().byId("oDialogCreate").setVisible(true).close();
		},
		checkDone: function(oEvent) {
			var bSelected = oEvent.getParameter('selected');
			var oItem = oEvent.getSource().getBindingContext().getObject();

			if (bSelected) {
				this.selectedItems.push(oItem);
			} else {
				var index = this.selectedItems.indexOf(oItem);
				if (index !== -1) {
					this.selectedItems.splice(index, 1);
				}
			}
		},

		/* //mode="Delete" in Table control in Overview.view.xml .These lines retrieve the table object from the event source (oEvent.getSource()) 
		 and the selected item object from the event parameters (oEvent.getParameter("listItem")).
		 The oEvent parameter is an event object representing the delete event*/
		handleDelete: function(oEvent) {
			var oTable = oEvent.getSource(),
				oSelectedItem = oEvent.getParameter("listItem");

			/*	 after deletion, put the focus back to the table. This line attaches an event listener to the "updateFinished" event of the table (oTable).
				Once the update of the table is finished (e.g., after the item is removed), the event handler (oTable.focus) is invoked, which sets the focus back 
				to the table. The use of attachEventOnce ensures that the event listener is executed only once*/
			/*	oTable.attachEventOnce("updateFinished", oTable.focus, oTable);*/

			// remove the selected item from the table aggregation
			oTable.removeItem(oSelectedItem);
		},
		onRemoveRowsUi: function() {
			var table = this.byId("table"); //Get a reference to the table element 
			var items = table.getItems(); //Get an array of all the items in the table.
			var selectedItems = []; //Create an empty array to store the selected items.

			/* Collect selected items .Iterate over each item in the table and check if the checkbox in 
			the first column of each item is selected. If an item is selected, add it to the selectedItems array.*/
			for (var i = 0; i < items.length; i++) {
				var item = items[i];
				var checkbox = item.getCells()[0]; // Assuming the checkbox is in the first column
				if (checkbox.getSelected()) {
					selectedItems.push(item);
				}
			}

			// Check if any items are selected
			if (selectedItems.length === 0) {
				sap.m.MessageBox.warning("No items selected.", {
					title: "Information"
				});
				return;
			}

			// Confirm removal with the user. sap.m.MessageBox.confirm is a function 
			sap.m.MessageBox.confirm("Are you sure you want to remove the selected items?", {
				title: "Confirmation",
				onClose: function(oAction) { //The onClose callback function will be triggered when the user responds to the confirmation dialog.
					if (oAction === sap.m.MessageBox.Action.OK) { //check if the user clicked the "OK" button 
						// Remove selected items
						for (var j = 0; j < selectedItems.length; j++) { //If the user clicked OK, make loop over the selectedItems array, remove each selected item from the table using the removeItem 
							var selectedItem = selectedItems[j];
							table.removeItem(selectedItem);
						}

						// Clear selection
						table.removeSelections(); //clear the selection after the peocess finished

						// Display success message
						sap.m.MessageBox.success("Selected items removed successfully.", {
							title: "Success"
						});
					}
				}
			});
		}

	});
});



<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>
				<Table id="table" inset="false" items="{path: '/ProductCollection'}" itemPress="onPress" >
					<headerToolbar>
						<Toolbar>
							<ToolbarSpacer/>
							<Button icon="sap-icon://add" press="onCreate"/>
							<!--	<Button icon="sap-icon://edit" press="onEdit"/>-->
							<Button icon="sap-icon://delete" 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 >
								<CheckBox id="ch1" select="checkDone"/>
								<!--	<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>
		<!--resizable="true" resize Dialog
			draggable="true" is default, dragg Dilaog
			-->


	<Dialog id="oDialogCreate" title="Create New Item" contentWidth="400px" resizable="true" class="myDialogStyle" >
    <content>
        <VBox alignItems="Center">
            <Label text="Name" class="dialogLabel"/>
            <Input id="nameInput" width="100%" class="dialogInput" />
            <Label text="Category" class="dialogLabel"/>
            <Input id="categoryInput" width="100%" class="dialogInput"/>
            <Label text="Supplier" class="dialogLabel"/>
            <Input id="supplierInput" width="100%" class="dialogInput"/>
            <Label text="Status" class="dialogLabel"/>
            <Input id="statusInput" width="100%" class="dialogInput"/>
            <Label text="DateOfProductionInput" class="dialogLabel"/>
            <Input id="dateOfProductionInput" width="100%" class="dialogInput"/>
            <Label text="Price" class="dialogLabel"/>
            <Input id="priceInput" width="100%" class="dialogInput"/>
        </VBox>
    </content>
    <beginButton>
        <Button text="Add" type="Accept" press="onAdd" class="dialogButton"/>
    </beginButton>
    <endButton>
        <Button text="Cancel" type="Reject" press="onCancel" class="dialogButton"/>
    </endButton>
</Dialog>

	</App>
</mvc:View>


Accepted Solutions (1)

Accepted Solutions (1)

junwu
Active Contributor
0 Kudos

it is very likely those value are empty.

var name = this.byId("nameInput").getValue();
			var category = this.byId("categoryInput").getValue();
			var supplier = this.byId("supplierInput").getValue();
			var status = this.byId("statusInput").getValue();
			var dateOfProduction = this.byId("dateOfProductionInput").getValue();
			var price = this.byId("priceInput").getValue();

you should use data binding, going to ui control to get value is very bad practice in ui5.

Answers (0)