Text input cell values clears in table when scrolling - sapui5

I have an input text value box in a table column in each table row. That data is fetched initially and populates in that particular table cell initially. This cell is editable by the user where it can be later saved in the DB upon clicking on a save button.
However the issue occurs when the user input the value in text field and scrolls up and down. The value gets cleared and defaults to the default fetched one. Is there anyway I can prevent that? When the table has small number of records this is not an issue rather the issue occurs when you have a large set of rows.
Does this has any configuration at table level or do I need to implement some soft of eventing mechanism for text inputs?
Here is the code.
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast",
"sap/ui/model/json/JSONModel",
"sap/ui/Device",
"sap/ui/table/Table",
"sap/ui/model/Filter",
"sap/ui/model/FilterOperator",
"sap/ui/ux3/FacetFilter",
"sap/m/TablePersoController",
"sap/m/UploadCollectionParameter",
"sap/m/MessageBox"
], function(Controller, MessageToast, JSONModel, Device, models, Filter, FilterOperator, TablePersoController) {
"use strict";
var dataPath;
var oModel;
var that;
var items;
var jModel = new sap.ui.model.json.JSONModel();
var result = {};
var ppernr;
var from_date;
var to_date;
var oTableEntry;
var t_ttwork = 0;
var t_ttout = 0;
var t_ttoin = 0;
var t_ttShift = 0;
var t_ttmhrs = 0;
var t_tthrapp = 0;
var t_AddHRs = 0;
var t_Syshr = 0;
var t_Penalty = 0;
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
return Controller.extend("OVERTIME.controller.OTMain", {
onInit: function() {
// dataPath = "/webidedispatcher/destinations/AV_GWD/sap/opu/odata/SAP/ZHRPT_OVERTIME_SRV/";
dataPath = "/sap/opu/odata/SAP/ZHRPT_OVERTIME_SRV/";
oModel = new sap.ui.model.odata.ODataModel(dataPath);
that = this;
that.setDates();
that.GET_DATA();
},
GET_DATA: function(oEvent) {
result.historySet = [];
// var URI = "/EMP_DETAILSSet?$filter=Pernr eq '" + pernr + "'";
oModel.read("/EMP_DETAILSSet/", null, null, false, function(oData, oResponse) {
result.EMP_DETAILSSet = oData.results;
items = result.EMP_DETAILSSet;
result.historySet = oData.results;
jModel.setData(result);
that.getView().setModel(jModel);
});
},
OnPressList: function(oEvent) {
t_ttwork = 0;
t_ttout = 0;
t_ttoin = 0;
t_ttShift = 0;
t_ttmhrs = 0;
t_tthrapp = 0;
t_AddHRs = 0;
t_Syshr = 0;
t_Penalty = 0;
if (items !== "") {
var BindingContext = oEvent.getSource().getBindingContext();
result.EMP_DATASet = BindingContext.getProperty();
jModel.setData(result);
that.getView().setModel(jModel);
ppernr = BindingContext.getProperty("Pernr");
that.getData();
}
},
getData: function() {
if (ppernr !== undefined) {
from_date = that.getView().byId("fdate").getValue();
to_date = that.getView().byId("tdate").getValue();
var oFilter = new Array();
oFilter[0] = new sap.ui.model.Filter("Pernr", sap.ui.model.FilterOperator.EQ, ppernr);
oFilter[1] = new sap.ui.model.Filter("FromDate", sap.ui.model.FilterOperator.EQ, from_date);
oFilter[2] = new sap.ui.model.Filter("ToDate", sap.ui.model.FilterOperator.EQ, to_date);
var oTable = this.getView().byId("oTable");
//this.getView().setModel(oModel);
oTable.setModel(oModel);
oTable.bindRows({
//method: "GET",
path: '/EE_OVETIMESet/',
filters: oFilter
});
// that.OnCalc();
} else {
// MessageToast.show("Please select employee first");
sap.m.MessageBox.show("Please select employee first", {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Error",
onClose: function(evt) {}
});
}
},
OnCalc: function() {
oTableEntry = this.getView().byId("oTable");
var count = oTableEntry._getRowCount();
var oTData;
var cells;
var hour_inoffice = 0;
var minute_inoffice = 0;
var hour_shift = 0;
var minute_shift = 0;
var hour_manual = 0;
var minute_manual = 0;
var hour_sys = 0;
var minute_sys = 0;
var hour_hr = 0;
var minute_hr = 0;
// var second = 0;
t_ttoin = 0;
t_ttShift = 0;
t_ttmhrs = 0;
t_tthrapp = 0;
t_Syshr = 0;
t_AddHRs = 0;
for (var i = 0; i < count; i++) {
oTData = oTableEntry.getContextByIndex(i).getObject();
//cells = oTableEntry.getRows()[i].getCells();
var hrAppValue = oTableEntry.getRows()[i].getCells()[9]._lastValue;
if (oTData.InOffice !== "") {
var splitTime1 = oTData.InOffice.split(':');
hour_inoffice = hour_inoffice + parseInt(splitTime1[0]);
minute_inoffice = minute_inoffice + parseInt(splitTime1[1]);
}
if (oTData.EligableHours !== "") {
var splitTime1 = oTData.EligableHours.split(':');
hour_shift = hour_shift + parseInt(splitTime1[0]);
minute_shift = minute_shift + parseInt(splitTime1[1]);
}
if (oTData.ManualOvt !== "") {
var splitTime1 = oTData.ManualOvt.split(':');
hour_manual = hour_manual + parseInt(splitTime1[0]);
//minute_manual = minute_manual + parseInt(splitTime1[1]);
}
if (oTData.TimeDiff !== "") {
var splitTime1 = oTData.TimeDiff.split(':');
if (splitTime1[0].charAt(0) === "+") {
splitTime1[0] = splitTime1[0].replace('+', '');
hour_sys = hour_sys + parseInt(splitTime1[0]);
minute_sys = minute_sys + parseInt(splitTime1[1]);
} else {
splitTime1[0] = splitTime1[0].replace('-', '');
hour_sys = hour_sys - parseInt(splitTime1[0]);
minute_sys = minute_sys - parseInt(splitTime1[1]);
}
}
if (hrAppValue !== "") {
var splitTime1 = hrAppValue.split(':');
if (splitTime1[0].charAt(0) === "+") {
splitTime1[0] = splitTime1[0].replace('+', '');
hour_hr = hour_hr + parseInt(splitTime1[0]);
minute_hr = minute_hr + parseInt(splitTime1[1]);
} else {
splitTime1[0] = splitTime1[0].replace('-', '');
hour_hr = hour_hr - parseInt(splitTime1[0]);
minute_hr = minute_hr - parseInt(splitTime1[1]);
}
}
/* minute_inoffice = minute_inoffice%60;
second_inoffice = parseInt(splitTime1[2]);
minute_inoffice = minute_inoffice + second_inoffice/60;
second_inoffice = second_inoffice%60;*/
/* if (parseFloat(cells[3].getText()) > 0) {
t_ttwork = parseFloat(t_ttwork) + parseFloat(cells[3].getText().replace(':', '.'));
}
t_ttout = parseFloat(t_ttout) + parseFloat(cells[4].getText().replace(':', '.'));
t_ttoin = parseFloat(t_ttoin) + parseFloat(cells[5].getText().replace(':', '.'));
t_ttShift = parseFloat(t_ttShift) + parseFloat(cells[6].getText()); //.replace(':', '.'));
t_ttmhrs = parseFloat(t_ttmhrs) + parseFloat(cells[7].getText().replace(':', '.'));
t_tthrapp = parseFloat(t_tthrapp) + parseFloat(cells[9].getValue().replace(':', '.'));
if (parseFloat(cells[9].getValue().replace(':', '.')) > 0) {
t_AddHRs = parseFloat(t_AddHRs) + parseFloat(cells[9].getValue());
} else if (parseFloat(cells[9].getValue().replace(':', '.')) < 0) {
t_Penalty = parseFloat(t_Penalty) + parseFloat(cells[9].getValue());
}*/
}
var temp;
t_ttoin = roundToTwo(hour_inoffice + minute_inoffice / 60);
t_ttShift = roundToTwo(hour_shift + minute_shift / 60);
t_ttmhrs = hour_manual;
t_Syshr = roundToTwo(hour_sys + minute_sys / 60);
t_AddHRs = roundToTwo(hour_hr + minute_hr / 60);
/* temp = t_ttoin ;
temp = '.' + temp.split('.') ;
temp[1] = temp[1] * 60 ;
t_ttoin = temp[0] + ':' + temp[1] ;*/
// this.getView().byId("t_ttwork").setValue(t_ttwork);
// this.getView().byId("t_ttoout").setValue(t_ttout);
this.getView().byId("t_ttoin").setValue(t_ttoin);
this.getView().byId("t_ttShift").setValue(t_ttShift);
this.getView().byId("t_ttmhrs").setValue(t_ttmhrs);
this.getView().byId("t_tsyshr").setValue(t_Syshr);
this.getView().byId("t_tthrapp").setValue(t_AddHRs);
// this.getView().byId("t_Penalty").setValue(t_Penalty);
},
setDates: function() {
var today = new Date();
var dd = today.getDate().toString();
var mm = (today.getMonth() + 1).toString(); //January is 0!
var yyyy = today.getFullYear();
var date = yyyy.toString().concat((mm[1] ? mm : "0" + mm[0]).toString(), '01');
this.getView().byId("fdate").setValue(date);
var lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 15);
lastDay = yyyy.toString().concat((mm[1] ? mm : "0" + mm[0]).toString(), lastDay.getDate());
this.getView().byId("tdate").setValue(lastDay);
},
OngetData: function(oEvent) {
that.getData();
},
OnSave: function(oEvent) {
var oTEntry = this.getView().byId("oTable");
var count = oTEntry._getRowCount();
var cells;
var bodyArray = [];
for (var i = 0; i < count; i++) {
var oTData = oTEntry.getContextByIndex(i).getObject();
//cells = oTableEntry.getRows()[i].getCells();
var hrAppValue = oTableEntry.getRows()[i].getCells()[9]._lastValue;
var requestBody = {};
requestBody.Pernr = "" + oTData.Pernr;
requestBody.FromDate = "" + oTData.FromDate;
requestBody.ToDate = "" + oTData.ToDate;
requestBody.OtDate = "" + oTData.OtDate;
requestBody.FcIn = "" + oTData.FcIn;
requestBody.LcOut = "" + oTData.LcOut;
requestBody.LogicHours = "" + oTData.LogicHours;
requestBody.OutOffice = "" + oTData.OutOffice;
requestBody.InOffice = "" + oTData.InOffice;
requestBody.EligableHours = "" + oTData.EligableHours;
requestBody.ManualOvt = "" + oTData.ManualOvt;
requestBody.HrApp = "" + hrAppValue; //oTData.HrApp;
bodyArray.push(requestBody);
}
var Sflag;
for (var i = 0; i < bodyArray.length; i++) {
oModel.create("/EE_OVETIMESet", bodyArray[i], {
success: function(oData, oResponse) {
Sflag = "S";
},
error: function() {
Sflag = "E";
break;
}
});
}
/**oModel.create("/EE_OVETIMESet", bodyArray, {
success: function(oData, oResponse) {
Sflag = "S";
},
error: function() {
Sflag = "E";
}
});*/
if (Sflag === "S") {
var msg = "Saved Successfully";
sap.m.MessageBox.show(msg, {
icon: sap.m.MessageBox.Icon.SUCCESS,
title: "Success",
onClose: function(evt) {}
});
} else {
sap.m.MessageBox.show("Data Not Saved", {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Error",
onClose: function(evt) {}
});
}
},
OnApprove: function(oEvent) {
var requestBody = {};
requestBody.Pernr = ppernr;
requestBody.FromDate = from_date;
requestBody.ToDate = to_date;
requestBody.Svalue = this.getView().byId("t_AddHRs").getValue();
requestBody.Pvalue = this.getView().byId("t_Penalty").getValue();
/* if (this.getView().byId("addover").getSelected() === true ) {
requestBody.Sflag = "A";
requestBody.Svalue = this.getView().byId("t_AddHRs").getValue();
} else if (this.getView().byId("subover").getSelected() === true ) {
requestBody.Sflag = "P";
requestBody.Pvalue = this.getView().byId("t_Penalty").getValue();
}*/
oModel.create("/EE_SOVTSet", requestBody, {
// method: "POST",
success: function(oData, oResponse) {
var status = oData.STATUS;
if (status === "S") {
sap.m.MessageBox.show("Data Saved", {
icon: sap.m.MessageBox.Icon.SUCCESS,
title: "Success",
onClose: function(evt) {}
});
} else if (status === "E") {
sap.m.MessageBox.show("Data Not Saved", {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Error",
onClose: function(evt) {}
});
}
},
error: function() {
MessageToast.show("Error. Try Again");
}
});
},
onNavBack: function() {
window.history.go(-1);
},
onSearch: function(oEvt) {
var sQuery = oEvt.getSource().getValue();
if (sQuery && sQuery.length > 0) {
var filter1 = new sap.ui.model.Filter("Pernr", sap.ui.model.FilterOperator.Contains, sQuery);
var filter2 = new sap.ui.model.Filter("Name", sap.ui.model.FilterOperator.Contains, sQuery);
var allfilter = new sap.ui.model.Filter([filter1, filter2], false);
}
var list = this.getView().byId("idList");
var binding = list.getBinding("items");
binding.filter(allfilter);
}
});
});
View
<mvc:View controllerName="OVERTIME.controller.OTMain" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
xmlns:f="sap.ui.layout.form" xmlns:t="sap.ui.table" xmlns:co="sap.ui.commons" xmlns:sc="sap.ui.core">
<SplitApp id="idSplitApp">
<masterPages>
<Page id="idMaster" title="{i18n>title}" icon="sap-icon://action" class="sapUiSizeCompact">
<headerContent class="sapUiSizeCompact"></headerContent>
<subHeader>
<Toolbar>
<SearchField width="100%" liveChange="onSearch" class="sapUiSizeCompact"/>
</Toolbar>
</subHeader>
<content>
<List id="idList" items="{/EMP_DETAILSSet}" class="sapUiSizeCompact">
<items class="Masterpage">
<ObjectListItem title="{Name}" type="Active" press="OnPressList" class="Masterpage">
<firstStatus>
<!--<ObjectStatus text="{Pernr}"/>-->
</firstStatus>
<attributes>
<ObjectAttribute text="{Pernr}"/>
</attributes>
</ObjectListItem>
</items>
</List>
</content>
<footer>
<Toolbar>
<ToolbarSpacer/>
</Toolbar>
</footer>
</Page>
</masterPages>
<detailPages>
<Page id="idDetails" showHeader="true" title="{i18n>appTitle}" class="sapUiSizeCompact" showNavButton="true" navButtonText="Back"
navButtonPress="onNavBack">
<ObjectHeader id="oh1" responsive="true" binding="{/EMP_DATASet}" intro="{i18n>pernr} - {Pernr}" title="{i18n>name} - {Name}"
showMarkers="false" markFlagged="false" markFavorite="false" backgroundDesign="Translucent">
<attributes>
<ObjectAttribute title="{i18n>org}" text="{Orgtx}"/>
<ObjectAttribute title="{i18n>posi}" text="{Postx}"/>
<ObjectAttribute title="{i18n>group}" text="{Ptext01}"/>
</attributes>
<statuses>
<ObjectStatus title="{i18n>subgroup}" text="{Ptext02}"/>
<ObjectStatus title="" text=""/>
</statuses>
</ObjectHeader>
<IconTabBar id="idIconTabBarMulti" class="sapUiResponsiveContentPadding">
<items>
<IconTabFilter icon="sap-icon://account">
<f:SimpleForm xmlns:sap.ui.layout.form="sap.ui.layout.form" xmlns:sap.ui.core="sap.ui.core" editable="fales" layout="ResponsiveGridLayout"
id="from_header" title="">
<f:content>
<Label text="{i18n>fromdate}" id="l_fdate" required="true"/>
<DatePicker width="30%" id="fdate" valueFormat="yyyyMMdd" displayFormat="dd/MM/yyyy"/>
<Label text="{i18n>todate}" id="l_tdate" required="true"/>
<DatePicker width="61%" id="tdate" valueFormat="yyyyMMdd" displayFormat="dd/MM/yyyy"/>
<Button id="iddate" press="OngetData" type="Unstyled" icon="sap-icon://display" width="30%"/>
</f:content>
</f:SimpleForm>
<f:SimpleForm xmlns:sap.ui.layout.form="sap.ui.layout.form" xmlns:sap.ui.core="sap.ui.core" editable="fales" layout="ResponsiveGridLayout"
id="from_overtime" title="">
<f:content id="cc">
<ScrollContainer horizontal="true" vertical="false" focusable="true" width="55rem">
<!--<sc:ScrollBarheight="20rem" vertical="false" size = "200px" contentSize = "500px" scrollPosition = "50"> -->
<t:Table selectionMode="None" id="oTable" navigationMode="Paginator" filter="onfilter" showNoData="true" width="70rem" visibleRowCount="16">
<t:columns>
<t:Column id="c_odate" width="10%" autoResizable="true">
<Label text="{i18n>odate}"/>
<t:template>
<Label id="t_odate" text="{OtDate}"/>
</t:template>
</t:Column>
<t:Column id="c_cin" autoResizable="true">
<Label text="{i18n>cin}"/>
<t:template>
<Label id="t_cin" text="{FcIn}"/>
</t:template>
</t:Column>
<t:Column id="c_cout" autoResizable="true">
<Label text="{i18n>cout}"/>
<t:template>
<Label id="t_cout" text="{LcOut}"/>
</t:template>
</t:Column>
<t:Column id="c_lhour" autoResizable="true">
<Label text="{i18n>lhour}"/>
<t:template>
<Label id="t_lhour" text="{LogicHours}"/>
</t:template>
</t:Column>
<t:Column id="c_toout" autoResizable="true">
<Label text="{i18n>toout}"/>
<t:template>
<Label id="t_toout" text="{OutOffice}"/>
</t:template>
</t:Column>
<t:Column id="c_toin" autoResizable="true">
<Label text="{i18n>toin}"/>
<t:template>
<Label id="t_toin" text="{InOffice}"/>
</t:template>
</t:Column>
<t:Column id="c_elhours" autoResizable="true">
<Label text="{i18n>elhours}"/>
<t:template>
<Label id="t_elhours" text="{EligableHours}"/>
</t:template>
</t:Column>
<!-- <t:Column id="c_stime" autoResizable="true">
<Label text="{i18n>stime}"/>
<t:template>
<Label id="t_stime" text="{TimeDiff}"/>
</t:template>
</t:Column>-->
<t:Column id="c_mover" autoResizable="true">
<Label text="{i18n>mover}"/>
<t:template>
<Label id="t_mover" text="{ManualOvt}"/>
</t:template>
</t:Column>
<t:Column id="c_diff" autoResizable="true">
<Label text="{i18n>tdiff}"/>
<t:template>
<Label id="t_diff" text="{TimeDiff}"/>
</t:template>
</t:Column>
<t:Column id="c_hrapp" autoResizable="true">
<Label text="{i18n>hrapp}"/>
<t:template>
<Input id="t_hrapp" value="{HrApp}"/>
</t:template>
</t:Column>
<!-- <t:Column id="c_ElgHrApp" autoResizable="true">
<Label text="{i18n>ElgHrApp}"/>
<t:template>
<Label id="t_ElgHrApp" text="{ElgHrApp}"/>
</t:template>
</t:Column>-->
</t:columns>
</t:Table>
</ScrollContainer>
<!-- </sc:ScrollBar>-->
</f:content>
</f:SimpleForm>
<f:SimpleForm xmlns:sap.ui.layout.form="sap.ui.layout.form" xmlns:sap.ui.core="sap.ui.core" editable="true" layout="ResponsiveGridLayout"
id="from_tovertime" title="Totals ">
<Button id="idCalc" text="{i18n>Calc}" press="OnCalc" type="Default" icon="sap-icon://simulate" width="10%"/>
<f:content id="cc1">
<!-- <Label id="t_twork" text="{i18n>TWOffice}"/>
<Input id="t_ttwork" editable="false" width="40%"/>
<Input id="t_ttout" value="{i18n>TOutOffice}" editable="false"/>
<Input id="t_ttoout" type="Number" editable="false"/>-->
<Label id="t_ttin" text="{i18n>TInOffice}"/>
<Input id="t_ttoin" type="Number" editable="false"/>
<Input id="t_tShift" value="{i18n>TShift}" editable="false"/>
<Input id="t_ttShift" type="Number" editable="false"/>
<Label id="t_tmhrs" text="{i18n>Tmhrs}"/>
<Input id="t_ttmhrs" type="Number" editable="false"/>
<Label id="t_syshr" text="{i18n>Tsyshr}"/>
<Input id="t_tsyshr" editable="false" width="40%"/>
<Input id="t_thrapp" value="{i18n>thrapp}" editable="false"/>
<Input id="t_tthrapp" type="Number" editable="false"/>
</f:content>
</f:SimpleForm>
<f:SimpleForm xmlns:sap.ui.layout.form="sap.ui.layout.form" xmlns:sap.ui.core="sap.ui.core" editable="false" layout="ResponsiveLayout"
id="from_tovertime2" title="Approved Hrs ">
<f:content >
<!--<RadioButton id="addover" groupName="G1" text="Add Over Hrs" selected="true" valueState="Warning"/>-->
<Label id="l_AddHRs" text="Add Over Hrs"/>
<Input id="t_AddHRs" type="Number" editable="true" width="30%" valueState="Success"/>
<!--<RadioButton id="subover" groupName="G1" text="Add Penalty" valueState="Error"></RadioButton>-->
<Label id="l_Penalty" text="Add Penalty"/>
<Input id="t_Penalty" type="Number" editable="true" width="30%"/>
</f:content>
</f:SimpleForm>
</IconTabFilter>
<!--<IconTabFilter icon="sap-icon://attachment">
<Panel>
<UploadCollection id="UploadCollection" maximumFilenameLength="55" multiple="true" showSeparators="None" items="{/AttachmentsSet}"
change="onChange" fileDeleted="onFileDeleted" uploadComplete="onUploadComplete">
<UploadCollectionItem fileName="{Filename}" mimeType="{MimeType}" url="{url}"/>
</UploadCollection>
</Panel>
</IconTabFilter>-->
</items>
</IconTabBar>
<footer>
<Toolbar>
<ToolbarSpacer/>
<Button id="idSubmit" text="{i18n>save}" press="OnSave" type="Emphasized" icon="sap-icon://add"/>
<Button id="idApprove" text="{i18n>approve}" press="OnApprove" type="Accept" icon="sap-icon://accept"/>
<Button id="idCancel" text="{i18n>close}" press="onNavBack" type="Reject" icon="sap-icon://sys-cancel"/>
</Toolbar>
</footer>
</Page>
</detailPages>
</SplitApp>
</mvc:View>

From the SDK documentation
In order to keep the document DOM as lean as possible, the Table control reuses its DOM elements of the rows. When the user scrolls, only the row contexts are changed but the rendered controls remain the same. This allows the Table control to handle huge amounts of data. Nevertheless, restrictions apply regarding the number of displayed columns. Keep the number as low as possible to improve performance. Due to the nature of tables, the used control for column templates also has a big influence on the performance.
Emphasis mine. I think the behavior you're describing is as designed.
How much data are you displaying this way? If you don't need to display thousands of lines, you might be better of going with sap.m.Table which does not do this.

The issue is because of the ODataModel. Used the version 2 of ODataModel which solved the issue.
ODataModel v2 API Documentation

Related

How to drag and drop rows of a table

In my view.xml file:
<html:div class="container-fluid">
<html:div class="row">
<Table id="ConnectorModuleTable"
items="{
path: '/datalist'}">
<columns>
<Column ><Text text="Connector Module"/></Column>
<Column ><Text text="Setting A"/></Column>
<Column ><Text text="Setting B"/></Column>
<Column ><Text text="Custom Pin"/></Column>
<Column ><Text text="Actions"/></Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{Connectormodule}" wrapping="false" />
<Text text="{settingA}" wrapping="false" />
<Text text="{settingB}" wrapping="false" />
<Text text="{settingB}" wrapping="false" />
</cells>
</ColumnListItem>
</items>
</Table>
</html:div>
</html:div>
I am trying to drag and drop the rows of this table
I have referred the link from docs showing for list as:
Documentation example link here
The same I have applied with the table in controller as :
attachDragAndDrop: function () {
var oList = this.byId("MyTable");
oList.addDragDropConfig(new DragInfo({
sourceAggregation: "items"
}));
oList.addDragDropConfig(new DropInfo({
targetAggregation: "items",
dropPosition: "Between",
dropLayout: "Vertical",
drop: this.onDrop.bind(this)
}));
},
onDrop: function (oInfo) {
var oDragged = oInfo.getParameter("draggedControl"),
oDropped = oInfo.getParameter("droppedControl"),
sInsertPosition = oInfo.getParameter("dropPosition"),
oDraggedParent = oDragged.getParent(),
oDroppedParent = oDropped.getParent(),
oDragModel = oDraggedParent.getModel(),
oDropModel = oDroppedParent.getModel(),
oDragModelData = oDragModel.getData(),
oDropModelData = oDropModel.getData(),
iDragPosition = oDraggedParent.indexOfItem(oDragged),
iDropPosition = oDroppedParent.indexOfItem(oDropped);
// remove the item
var oItem = oDragModelData[iDragPosition];
oDragModelData.splice(iDragPosition, 1);
if (oDragModel === oDropModel && iDragPosition < iDropPosition) {
iDropPosition--;
}
// insert the control in target aggregation
if (sInsertPosition === "Before") {
oDropModelData.splice(iDropPosition, 0, oItem);
} else {
oDropModelData.splice(iDropPosition + 1, 0, oItem);
}
if (oDragModel !== oDropModel) {
oDragModel.setData(oDragModelData);
oDropModel.setData(oDropModelData);
} else {
oDropModel.setData(oDropModelData);
}
},
initData: function (datalist) {
this.byId("MyTable").setModel(new JSONModel([
datalist
]));
}
Here datalist has all rows data in JSON (for ref)
But this did n't work , any help or guiding links are appreciated
I used the following view with your onDrop() and it worked.
Can you describe, what is not working?
<Table id="MyTable" items="{/}">
<columns>
<Column ><Text text="Connector Module"/></Column>
<Column ><Text text="Setting A"/></Column>
<Column ><Text text="Setting B"/></Column>
</columns>
<dragDropConfig>
<dnd:DragDropInfo
sourceAggregation="items"
targetAggregation="items"
dropPosition="Between"
drop=".onDrop"/>
</dragDropConfig>
<items>
<ColumnListItem>
<cells>
<Text text="{Connectormodule}" wrapping="false" />
<Text text="{settingA}" wrapping="false" />
<Text text="{settingB}" wrapping="false" />
<Text text="{settingB}" wrapping="false" />
</cells>
</ColumnListItem>
</items>
</Table>
Can you see data in the original table?
Setting of the model is incorrect: the JSONModel constructor needs an object rather than an array as listed in your initData function. It seems like a binding problem to me...
I just tried to modify your code as follows and everithing works fine:
onDrop: function (oInfo) {
var oDragged = oInfo.getParameter("draggedControl"),
oDropped = oInfo.getParameter("droppedControl"),
sInsertPosition = oInfo.getParameter("dropPosition"),
oDraggedParent = oDragged.getParent(),
oDroppedParent = oDropped.getParent(),
oDragModel = oDraggedParent.getModel(),
oDropModel = oDroppedParent.getModel(),
oDragModelData = oDragModel.getData(),
oDropModelData = oDropModel.getData(),
iDragPosition = oDraggedParent.indexOfItem(oDragged),
iDropPosition = oDroppedParent.indexOfItem(oDropped);
// remove the item
var oItem = oDragModelData.datalist[iDragPosition];
oDragModelData.datalist.splice(iDragPosition, 1);
if (oDragModel === oDropModel && iDragPosition < iDropPosition) {
iDropPosition--;
}
// insert the control in target aggregation
if (sInsertPosition === "Before") {
oDropModelData.datalist.splice(iDropPosition, 0, oItem);
} else {
oDropModelData.datalist.splice(iDropPosition + 1, 0, oItem);
}
if (oDragModel !== oDropModel) {
oDragModel.setData(oDragModelData);
oDropModel.setData(oDropModelData);
} else {
oDropModel.setData(oDropModelData);
}
},
initData: function (datalist) {
//just an example
var oData = {
datalist: [{
Connectormodule: "one",
settingA: "one",
settingB: "one"
}, {
Connectormodule: "two",
settingA: "two",
settingB: "two"
}, {
Connectormodule: "three",
settingA: "three",
settingB: "three"
}]
};
var oModel = new sap.ui.model.json.JSONModel(oData);
this.byId("ConnectorModuleTable").setModel(oModel);
},

How to make group of toggle buttons responsive

The xml for toggle buttons:
<HBox id="toggleButtons1" fitContainer="false" class="fullWidthButtons" alignItems="Center">
<items>
<ToggleButton text="BUTTON1" enabled="true" pressed="true" press=".onPress1" class="firsttogglebutton" >
<layoutData>
<FlexItemData growFactor="1" />
</layoutData>
</ToggleButton>
<ToggleButton text="BUTTON2" enabled="true" pressed="false" press=".onPress2">
<layoutData>
<FlexItemData growFactor="1" />
</layoutData>
</ToggleButton>
<ToggleButton text="BUTTON3" enabled="true" pressed="false" press=".onPress3">
<layoutData>
<FlexItemData growFactor="1" />
</layoutData>
</ToggleButton>
</items>
</HBox>
Applied some CSS guess not required
I am checking for responsive,when viewed in small/medium devices it is perfect with all size of devices:
for ref:
But When I changed(Enlarged) text inside buttons, It is not responsive. What might be the reason? how to overcome this?
I tried my luck replacing HBox with FlexBox but it is same(May be I should include some more properties).
Controller.js:
sap.ui.define("myController", [
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
var toggleButtons1;
return Controller.extend("myController", {
onInit: function() {
toggleButtons1 = this.byId("toggleButtons1").getItems();
},
onPressNext: function(e) {
for (var i = 0; i < toggleButtons1.length - 1; ++i) {
if (toggleButtons1[i].getPressed()) {
toggleButtons1[i].setPressed(false);
toggleButtons1[i + 1].setPressed(true);
break;
}
}
},
onPressPrevious: function() {
for (var i = toggleButtons1.length - 1; i > 0; --i) {
if (toggleButtons1[i].getPressed()) {
toggleButtons1[i - 1].setPressed(true);
}
}
},
onPress: function(e) {
var btn = e.getSource();
if(!btn.getPressed()) {
btn.setPressed(true);
return;
}
for (var i = 0; i < toggleButtons1.length; ++i) {
if (toggleButtons1[i] != btn) {
toggleButtons1[i].setPressed(false);
}
}
},
onPress1: function(e) {
this.onPress(e);
alert("Do something here!");
}
});
});
view.xml
<l:Grid id="gridToggleButtons" containerQuery="true" defaultSpan="XL2 L4 M4 S6">
<ToggleButton text="BUTTON1EEE" enabled="true" pressed="true" press=".onPress1" class="firsttogglebutton" />
<ToggleButton text="BUTTON2EEE" enabled="true" pressed="false" press=".onPress2" />
<ToggleButton text="BUTTON3EEE" enabled="true" pressed="false" press=".onPress3" />
</l:Grid>
controller.js
var oGrid = this.byId("gridToggleButtons");
var oBtns = oGrid.getContent();
var oBUTTON1EEE = oBtns[0];
var oBUTTON2EEE = oBtns[1];
var oBUTTON3EEE = oBtns[2];
Note: containerQuery is used to get the size based on the Grid size not based on the device sizes(Large, Medium and Small).
defaultSpan is set based on your requirement. For more information regarding the Grid go through the Grid API

How to remove dynamically added texbox

I found a good workin example where one can dynamically add textbox and calculate average from those inputs but i can´t figure out how to delete those added textboxes... I know i should do it with first with document.getElementById but what is the id i should look for? And then continue with removechild command?...I´m really newbie, can you please help me?
See here on JSFiddle http://jsfiddle.net/davidThomas/vzftsz3a/1/
JS
function currentlyExisting(selector) {
return document.querySelectorAll(selector).length;
}
function addNew() {
var parent = document.getElementById(this.dataset.divname),
label = document.createElement('label'),
input = document.createElement('input'),
current = currentlyExisting('input[name="myInputs[]"'),
limit = 10;
if (current < limit) {
input.type = 'text';
input.name = 'myInputs[]';
label.appendChild(document.createTextNode('Subject number ' + (current + 1) + ':'));
label.appendChild(input);
parent.appendChild(label);
this.disabled = currentlyExisting('input[name="myInputs[]"') >= limit;
}
}
function average() {
var parent = document.getElementById('dynamicInput'),
inputs = parent.querySelectorAll('input[name="myInputs[]"]'),
sum = Array.prototype.map.call(inputs, function (input) {
return parseFloat(input.value) || 0;
}).reduce(function (a, b) {
return a + b;
}, 0),
average = sum / inputs.length;
document.getElementById('average').textContent = average;
document.getElementById('sum').textContent = sum;
document.getElementById('total').textContent = inputs.length;
}
document.getElementById('addNew').addEventListener('click', addNew);
document.getElementById('btnCompute').addEventListener('click', average);
Try below code
function currentlyExisting(selector) {
return document.querySelectorAll(selector).length;
}
function addNew() {
var parent = document.getElementById(this.dataset.divname),
label = document.createElement('label'),
input = document.createElement('input'),
current = currentlyExisting('input[name="myInputs[]"'),
limit = 10;
if (current < limit) {
input.type = 'text';
input.name = 'myInputs[]';
label.appendChild(document.createTextNode('Subject number ' + (current + 1) +
':'));
label.appendChild(input);
parent.appendChild(label);
this.disabled = currentlyExisting('input[name="myInputs[]"') >= limit;
}
}
function average() {
var parent = document.getElementById('dynamicInput'),
inputs = parent.querySelectorAll('input[name="myInputs[]"]'),
sum = Array.prototype.map.call(inputs, function (input) {
return parseFloat(input.value) || 0;
}).reduce(function (a, b) {
return a + b;
}, 0),
average = sum / inputs.length;
document.getElementById('average').textContent = average;
document.getElementById('sum').textContent = sum;
document.getElementById('total').textContent = inputs.length;
}
function removeRow() {
var parent = document.getElementById(this.dataset.divname);
parent.removeChild(parent.lastChild);
}
document.getElementById('addNew').addEventListener('click', addNew);
document.getElementById('btnCompute').addEventListener('click', average);
document.getElementById('remove').addEventListener('click', removeRow);
Below is the updated HTML
<div id="results"> <span id="average"></span>
<span id="sum"></span>
<span id="total"></span>
</div>
<form method="POST" action="#">
<div id="dynamicInput">
<label>Subject number 1:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 2:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 3:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 4:
<input type="text" name="myInputs[]" />
</label>
<label>Subject number 5:
<input type="text" name="myInputs[]" />
</label>
</div>
<input id="addNew" data-divname="dynamicInput" type="button" value="Add a subject" />
<input id="btnCompute" data-divname="dynamicInput" type="button" name="BtnCompute" value="Compute Average" />
<input id="remove" data-divname="dynamicInput" type="button" value="Remove subject" />
</form>

Table Not Getting Refreshed After Deleting a Row

I am facing two issues when deleting a record in sap.m.Table as mentioned below.
After deleting a row using delete button, other rows are also getting vanished. Only after refreshing the page, I can see those records.
I have used success and error message after deleting the rows but it is not appearing.
Table.view.xml
<mvc:View
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
controllerName="sem.stock_app.controller.table"
>
<Page
title="Material Status"
showNavButton="true"
navButtonPress="onNavBack"
>
<Table id="table"
growing="true"
mode="MultiSelect"
items="{odata>np_on_matid}"
>
<columns>
<Column>
<CheckBox text="Select Entry"/>
</Column>
<Column>
<Text text="Material ID"/>
</Column>
<Column>
<Text text="Category"/>
</Column>
<Column>
<Text text="Material Desc"/>
</Column>
<Column>
<Text text="Plant"/>
</Column>
</columns>
<items>
<ColumnListItem type="Active" press="onPress">
<CheckBox selected="{false}"/>
<Text text="{odata>Matid}"/>
<Text text="{odata>Category}"/>
<Text text="{odata>Matdesc}"/>
<Text text="{odata>Plant}"/>
</ColumnListItem>
</items>
</Table>
<Button
text="Delete"
enabled="true"
press="onDelete"
/>
</Page>
</mvc:View>
Table.Controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"sap/ui/model/Filter",
"sap/ui/core/routing/History",
"sap/m/MessageToast",
"sap/m/MessageBox"
], function(Controller, JSONModel, Filter, History, MessageToast, MessageBox) {
"use strict";
return Controller.extend("sem.stock_app.controller.table", {
onInit: function() {
this.getOwnerComponent().getRouter().getRoute("r2").attachPatternMatched(this.mynav, this);
},
mynav: function(oeve) {
var key = this.getOwnerComponent().getModel("odata").createKey("matlistSet", {
"Matid": oeve.getParameters().arguments.noti
});
this.getView().bindElement({
path: "odata>/" + key,
parameters: {
expand: "np_on_matid"
}
});
},
onNavBack: function() {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("r1", {}, true);
}
},
onPress: function(oitem) {
var x = oitem.getSource().getBindingContext("odata").getProperty("Matid");
this.getOwnerComponent().getRouter().navTo("r3", {
matnr: x
});
},
onDelete: function() {
var i, tbl, aSelectedProducts, sPath, oProduct, oProductId;
tbl = this.byId("table").getSelectedItems();
aSelectedProducts = this.byId("table").getSelectedItems();
if (aSelectedProducts.length) {
for (i = 0; i < aSelectedProducts.length; i++) {
oProduct = aSelectedProducts[i];
oProductId = oProduct.getBindingContext("odata").getProperty("Matid");
sPath = oProduct.getBindingContextPath();
this.getOwnerComponent().getModel("odata").remove(sPath, {
success: this._handleUnlistActionResult.bind(this, oProductId, true, i + 1, aSelectedProducts.length),
error: this._handleUnlistActionResult.bind(this, oProductId, false, i + 1, aSelectedProducts.length)
});
}
} else {
this._showErrorMessage(this.getModel("i18n").getResourceBundle().getText("TableSelectProduct"));
}
},
_handleUnlistActionResult: function(sProductId, bSuccess, iRequestNumber, iTotalRequests, oData, oResponse) {
if (iRequestNumber === iTotalRequests) {
MessageToast.show(this.getModel("i18n").getResourceBundle().getText("StockRemovedSuccessMsg", [iTotalRequests]));
}
},
});
});
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/Device",
"sem/stock_app/model/models"
], function(UIComponent, Device, models) {
"use strict";
return UIComponent.extend("sem.stock_app.Component", {
metadata: {
manifest: "json"
},
init: function() {
var url = "/sap/opu/odata/sap/ZMATLIST_SRV_03";
var odata = new sap.ui.model.odata.ODataModel(url, {
json: true
});
this.setModel(odata,"odata");
UIComponent.prototype.init.apply(this, arguments);
this.getRouter().initialize();
this.setModel(models.createDeviceModel(), "device");
}
});
});
As discussed in the comments, the issues were:
Use of sap.ui.model.odata.ODataModel which has been out of maintenance since long time ago
There was no $batch operation implemented in the back-end system.

Google Directions with autocomplete

I'm trying to fill 2 inputs with google autocomplete and then get google map directions asd route.
I manage to use autocomplete, but when I click in the submit button nothing happens.
I'm using this code:
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(39.57182223734374, -7.811279296875), 15);
gdir = new GDirections(map, document.getElementById("directions"));
var input = document.getElementById('tb_fromPoint');
var autocomplete = new google.maps.places.Autocomplete(input);
var input2 = document.getElementById('tb_endPoint');
var autocomplete2 = new google.maps.places.Autocomplete(input2);
setDirections();
}
function setDirections() {
var fromAddress = document.getElementById('tb_fromPoint');
var toAddress = document.getElementById('tb_endPoint');
gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "pt_PT" });
}
google.maps.event.addDomListener(window, 'load', initialize);
From :
To:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service</title>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places" type="text/javascript"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(13.0524139, 80.25082459999999);
var mapOptions = {
zoom:7,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('city1').value;
var end = document.getElementById('city2').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 650px; height: 350px;"></div>
<script type="text/javascript">
function initialize1() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
};
var input1 = document.getElementById('searchTextField1');
var autocomplete = new google.maps.places.Autocomplete(input1,options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place1 = autocomplete.getPlace();
document.getElementById('city1').value = place1.name;
document.getElementById('cityLat1').value = place1.geometry.location.lat();
document.getElementById('cityLng1').value = place1.geometry.location.lng();
document.getElementById('cityy').value = place1.city_name;
initialize();
calcRoute()
});
}
google.maps.event.addDomListener(window, 'load', initialize1);
function initialize2() {
var options = {
//types: ['(cities)'],
componentRestrictions: {country: "in"}
};
var input2 = document.getElementById('searchTextField2');
var autocomplete = new google.maps.places.Autocomplete(input2, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place2 = autocomplete.getPlace();
document.getElementById('city2').value = place2.name;
document.getElementById('cityLat2').value = place2.geometry.location.lat();
document.getElementById('cityLng2').value = place2.geometry.location.lng();
initialize();
calcRoute()
});
}
google.maps.event.addDomListener(window, 'load', initialize2);
</script>
<input id="searchTextField1" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <br />
<input type="text" id="city1" name="city1" /> <br />
<input type="text" id="cityLat1" name="cityLat1" /> <br />
<input type="text" id="cityLng1" name="cityLng1" /> <br />
<input id="searchTextField2" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <br />
<input type="text" id="city2" name="city2" /> <br />
<input type="text" id="cityLat2" name="cityLat2" /> <br />
<input type="text" id="cityLng2" name="cityLng2" /> <br />
</body>
</html>