How to delete rows from a wijmo grid in a loop and refresh? - wijmo

Is there a way we can delete rows from a wijmo grid running within a loop and refresh the grid with new data. I tried with the following approach, I can see the rows getting deleted while debugging but after the loop ends the grid is refreshed with old set of data.
self.delete = function (obj, event) {
var pagesize = $("#pageDisplay :selected").val();// 5
var pageSizeDiff = defaultPageSize - pagesize;//5
var $grid = $("#Grid");
var newData = $grid.wijgrid("data");// array of 10 objects
var i = 0;
while (i < pagesize) {
newData.splice(pageSizeDiff, 1);// delete from 5th row
$grid.wijgrid("data", newData);
//refresh grid
$grid.wijgrid("ensureControl", true);
i++;
};
};

I am not sure why you are setting the new data in the loop. Ideally, you should delete the rows in the loop and then, set the new data.

Related

How to create multi items/records or save item/record array at one time in client script file

I want to create multiple records at the same time using client script. This is what I'm doing:
var ceateDatasource = app.datasources.Reservation.modes.create;
var newItem = ceateDatasource.item;
newItem.User = user; //'eric'
newItem.Description = description; //'000'
newItem.Location_Lab_fk = lab.value.Id; //'T'
newItem.Area_fk = area.value.Id; //'L'
newItem.Equipment_fk = equipment.value.Id; //'S'
for(var i = 0 ; i < 3; i ++) {
newItem.Start_Date = startDate;
newItem.Start_Hours = '03';
newItem.Start_Minutes = '00';
newItem.End_Date = startDate;
newItem.End_Hours = '23';
newItem.End_Minutes = '30';
// Create the new item
ceateDatasource.createItem();
}
But the result I'm getting is this one:
The three records are created but the only the first one has data. The other two records have empty values on their fields. How can I achieve this?
Thanks.
Update(2019-3-27):
I was able to make it work by putting everything inside the for loop block. However, I have another question.
Is there any method like the below sample code?
var recordData = [Data1, Data2, Data3]
var ceateDatasource;
var newItem = new Array(recordData.length) ;
for(var i = 0 ; i < recordData.length; i ++) {
ceateDatasource = app.datasources.Reservation.modes.create;
newItem[i] = ceateDatasource.item;
newItem[i].User = recordData[i].user;
newItem[i].Description = recordData[i].Description;
newItem[i].Location_Lab_fk = recordData[i].Location_Lab_fk;
newItem[i].Area_fk = recordData[i].Area_fk;
newItem[i].Equipment_fk = recordData[i].Equipment_fk;
newItem[i].Start_Date = recordData[i].Start_Date;
newItem[i].Start_Hours = recordData[i].Start_Hours;
newItem[i].Start_Minutes = recordData[i].Start_Minutes;
newItem[i].End_Date = recordData[i].End_Date;
newItem[i].End_Hours = recordData[i].End_Hours;
newItem[i].End_Minutes = recordData[i].End_Minutes;
}
// Create the new item
ceateDatasource.createItem();
First, it prepares an array 'newItem' and only calls 'ceateDatasource.createItem()' one time to save all new records(or items).
I try to use this method, but it only saves the last record 'newItem[3]'.
I need to write a callback function in 'ceateDatasource.createItem()' but Google App Maker always show a warning "Don't make functions within a loop". So, are there any methods to call 'createItem()' one time to save several records? Or are there some functions like 'array.push' which can be used?
Thanks.
As per AppMaker's official documentation:
A create datasource is a datasource used to create items in a particular data source. Its item property is always populated by a draft item which can be bound to or set programmatically.
What you are trying to do is create three items off the same draft item. That why you see the result you get. If you want to create multiple items, you need to create a draft item for each one, hence all you need to do is put all your code inside the for loop.
for(var i = 0 ; i < 3; i ++) {
var ceateDatasource = app.datasources.Reservation.modes.create;
var newItem = ceateDatasource.item;
newItem.User = user; //'eric'
newItem.Description = description; //'000'
newItem.Location_Lab_fk = lab.value.Id; //'T'
newItem.Area_fk = area.value.Id; //'L'
newItem.Equipment_fk = equipment.value.Id; //'S'
newItem.Start_Date = startDate;
newItem.Start_Hours = '03';
newItem.Start_Minutes = '00';
newItem.End_Date = startDate;
newItem.End_Hours = '23';
newItem.End_Minutes = '30';
// Create the new item
ceateDatasource.createItem();
}
If you want to save several records at the same time using client script, then what you are looking for is the Manual Save Mode. So all you have to do is go to your model's datasource and click on the checkbox "Manual Save Mode".
Then use the same code as above. The only difference is that in order to persist the changes to the server, you need to explicitly save changes. So all you have to do is add the following after the for loop block:
app.datasources.Reservation.saveChanges(function(){
//TODO: Callback handler
});

Performance server scripting

I have table with multiple customerKey values assigned to a numeric value; I wrote a script where foreach row of data I scan whole table to find all values assigned to the current customerKey and return a highest one;
I have a problem with performance - script processes around 10 records per second - any ideas how to improve this or maybe propose an alternative solution plesae?
function getLastest() {
var date = app.models.magicMain.newQuery();
var date_all = date.run();
date_all.forEach(function(e) { // for every row of date_all
var temp = date_all.filter(function(x) {
return x.SubscriberKey === e.SubscriberKey; // find matching records for the current x.SubscriberKey
});
var dates = [];
temp.forEach(function(z) { // get all matching "dates"
dates.push(z.Date);
});
var finalValue = dates.reduce(function(a, b) { // get highest dates value (integer)
return Math.max(a, b);
});
var record = app.models.TempOperatoins.newRecord(); // save results to DB
record.email = e.SubscriberKey.toString() + " " + finalValue.toString();
app.saveRecords([record]);
});
}
The only suggestion I have would be to add:
var recordstosave = [];
At the top of your function.
Then replace app.saveRecords([record]) with recordstosave.push(record).
Finally outside of your foreach function do app.saveRecords(recordstosave).
I saw major processing time improvements doing this rather than saving each record individually inside a loop.

update edited cells within treetable after expand/collapse items

I have a treeTable with editable cells within the expanded rows. The editable cells get a dirty flag after editing (in the example the background color is set to red).
The problem i'm running into is that i found no certain way to update the dirty flag on expand/collapse (edited cells get the css class 'edited-cell').
At the moment the code looks like that:
// each editable textfield gets a Listener
textField.attachLiveChange(
var source = oEvent.oSource;
...
jQuery('#' + source.getId()).addClass(EDITED_CELL_CLASS, false)
// list with cell ids, e.g. "__field1-col1-row1"
DIRTY_MODELS.push(model.getId()) //*** add also binding context of row
)
// the table rows are updated on toggleOpenState
new sap.ui.table.TreeTable({
toggleOpenState: function(oEvent) {
...
this.updateRows() // see function below
}
})
// update Rows function is also delegated
oTable.addDelegate({ onAfterRendering : jQuery.proxy(this.updateRows, oTable)});
//http://stackoverflow.com/questions/23683627/access-row-for-styling-in-sap-ui5-template-handler-using-jquery
// this method is called on each expand/collapse: here i can make sure that the whole row has it's correct styling...
// but how to make sure that special cells are dirty?
function updateRows(oEvent) {
if (oEvent.type !== 'AfterRendering'){
this.onvscroll(oEvent);
}
var rows = this.getVisibleRowCount();
var rowStart = this.getFirstVisibleRow();
var actualRow;
for (var i = 0; i < rows; i++){
actualRow = this.getContextByIndex(rowStart + i); //content
var row = this.getRows()[i]
var obj = actualRow.getObject()
var rowId = row.getId()
updateStyleOfRows(obj, rowId, actualRow)
updateDirtyCells(rowId) //*** how to get the binding context in this function???
}
};
// update Dirty Cells in function updateRows():
function updateDirtyCells(rowId){
for (var i = 0; i < DIRTY_MODELS.length; i++){
var dirtyCellId = DIRTY_MODELS[i]
//*** make sure that only the correct expanded/collapsed rows will be updated -> depends on the bindingContext of the row
jQuery('#' + rowId).find('#' + dirtyCellId + '.editable-cell').addClass(EDITED_CELL_CLASS, false)
}
}
This doesn't work correctly, because the ids of the cells change on each layout render (e.g. collapse/expand rows). Please see attached image.
Let me know if i should provide more information.

How to compute a column value while editing in jqgrid

I have a supposedly common problem to solve (done easily with other grid controls I'm familiar with).
In jqgrid, i'm quite stumped.
I have a jqgrid with inline editing enabled. I would like to add some scripting so that when editing a row (or adding a new row), the value of ColumnC is automatically computed as ColumnA * ColumnB as default. The user can change the values in any column at any time. I want this value to be computed as soon as the user enters it and not wait till the data is saved.
My approach so far has been to attach a dataEvent of type "change" to ColumnA and ColumnB -
dataEvents: [
{ type: 'change', fn: function(e) {
var rowid = $("#myGrid").jqGrid('getGridParam','selrow');
var rowData = $("#myGrid").getRowData(rowid);
var cell1 = rowData['ColumnA'];
var cell2 = rowData['ColumnB'];
var newValue = cell1 * cell2;
$("#myGrid").jqGrid('setCell', rowid, 'ColumnC', newValue);
}
},
]
Obviously, cell1 & cell2 don't actually return the value but the whole cell content as already discovered by other users here How to get a jqGrid cell value. The only way to get a cell value seems to be to use a custom regex user function that strips out that value.
Apart from that, is there a better/alternate way to achieve what I need? Something as simple as jqGrid - How to calculated column to jqgrid? though obviously that won't cut it for me since it will only displaying data and user cannot update it.
Any help would be appreciated.
UPDATE: After guidance from Oleg, I was able to extend getTextFromCell to support what I need.
function getTextFromCell(cellNode) {
var cellValue;
//check for all INPUT types
if (cellNode.childNodes[0].nodeName == "INPUT") {
//special case for handling checkbox
if (cellNode.childNodes[0].type == "checkbox") {
cellValue = cellNode.childNodes[0].checked.toString();
}
else {
//catch-all for all other inputs - text/integer/amount etc
cellValue = cellNode.childNodes[0].value;
}
}
//check for dropdown list
else if (cellNode.childNodes[0].nodeName == "SELECT") {
var newCell = $("select option:selected", cellNode);
cellValue = newCell[0].value;
}
return cellValue;
}
function getCellNodeFromRow(grid,rowId,cellName) {
var i = getColumnIndexByName(grid, cellName);
var cellValue;
//find the row first
$("tbody > tr.jqgrow", grid[0]).each(function() {
//The "Id" column in my grid is at index 2...
var idcell = $("td:nth-child(2)", this);
var currRowId = getTextFromCell(idcell[0])
if (currRowId == rowId) {
cellValue = getTextFromCell($("td:nth-child(" + (i + 1) + ")", this)[0]);
return false;
}
});
return cellValue;
}
The code in getCellNodeFromRow is not the most efficient. There is a .each() loop for find the matching row node. I can see this being slow when the grid has thousands of rows. Is there a better/more efficient way to find the row node? I have the row Id already.
Look at the demo from the answer. It uses cell editing, but the same technique work for inline editing too. Just click on any cell in the "Amount" column and modify the numerical value. You will see that the value in the "Total" row (footer) will be changed dynamically during the cell is still in the editing mode. I think it is what you need.
you can achieve this using onCellSelect event of jqgrid as below
//global section
var columnA;
var ColumnB;
var ColumnC;
var currentRow;
//
onCellSelect: function (rowid, iCol, aData) {
currentRow = rowid;
var ColumnA = $('#grid').getCell(rowid, 'MyCol');
var ColumnB = $('#grid').getCell(rowid, 'MyCol');
$("#grid").jqGrid('editRow', rowid, true );
$("#myMenu").hide();
if (rowid && rowid !== lastsel) {
if (lastsel) jQuery('#grid').jqGrid('restoreRow', lastsel);
$("#grid").jqGrid('editRow', rowid, true );
lastsel = rowid;
}
else if (rowid && rowid === lastsel)
{ $("#grid").jqGrid('editRow', rowid, true ); }
//if it is in editable mode
// when you view the html using firebug it will be like the cell id change to
//format like "rowid_ColumnName"
$('#' + currentRow + '_ColumnC').val(ColumnA*ColumnB);
// or you can use achieve this using following jqgrid method at
//appropriate place
$("#myGrid").jqGrid('setCell', rowid, 'ColumnC', ColumnA*ColumnB);
}

Calculate the sum of a datagrid's rows

I have this datagrid which has columns with a NumericStepper as an itemEditor where the user can change the number of items he wants to buy. How can I calculate the sum of all cells when the user updates datagrid's values?
EDIT 1
My datagrid is about colors and sizes of a product. The columns are generated dynamically from this function
private function getColumn(dataField:String, headerText:String,editable:Boolean) : DataGridColumn
{
var column:DataGridColumn = new DataGridColumn(dataField);
column.headerText = headerText;
column.width = 20;
editable ? column.editable = true : column.editable = false;
column.editorDataField = "value";
column.itemEditor = new ClassFactory(ColorSizesFormRenderer);
return column;
}
and then I loop my xml http result
for each (var thisSize:XML in result.product.(#id == pId)..size) {
_columns.push(getColumn("size"+thisSize,thisSize,true));
}
So how can I find the sum of all cells?
EDIT 2
I use this code to loop all my cells
protected function color_sizes_itemFocusOutHandler(event:DataGridEvent):void
{
total = 0;
for each(var row:Object in color_sizes.dataProvider) {
total += row.size28;
}
}
the row.size28 is generated dynamically. So it could be row.size29,row.size30 etc.
How can I loop through all my cells without knowing their data.property?
Thanks in advance
Your numeric stepper should show a bindable property value from the [data] row you display.
Then you just parse the dataProvider of the datagrid and make the sum of that data.property.
for ex:
class MyObject
{
[Bindable]
var itemsNo:int = 0;
var productName:String = "";
}
The datagrid will have a NumericStepper custom column that will take the value of {data.itemsNo}
At the end just count all itemsNo from the datagrid.dataProvider items

Resources