How to highlight the last selected row after client-side sorting on jqGrid? - jqgrid

I've a jqGrid-based application, and I use loadonce: true in the grid option and sortable: true, sorttype: 'text in the colModel to allow client-side sorting on the data grid. However, I found that, once the data grid is re-sorted, the last selected row will no longer be highlighted. My question is, how to keep the selected row being highlighted across data resorting?

I prepared for you the small demo which keeps the row selection. In the demo I rewrote the code of selectionPreserver used in case of reloadGrid usage having additional parameters: $("#list").trigger("reloadGrid", [{current:true}]);. See the answer for details.
The demo saves the current selection inside of the onSortCol event handler and restore it inside of the loadComplete:
onSortCol: function () {
saveSelection.call(this);
},
loadComplete: function () {
restoreSelection.call(this);
}
How you see the usage is very simple and you can integrate it in your code. The implementation of the saveSelection and restoreSelection is the following:
var lastSelArrRow = [],
lastScrollLeft = 0,
lastSelRow = null,
saveSelection = function () {
var $grid = $(this);
lastSelRow = $grid.jqGrid('getGridParam', 'selrow');
lastSelArrRow = $grid.jqGrid('getGridParam', 'selrow');
lastSelArrRow = lastSelArrRow ? $.makeArray(lastSelArrRow) : null;
lastScrollLeft = this.grid.bDiv.scrollLeft;
},
restoreSelection = function () {
var p = this.p,
$grid = $(this);
p.selrow = null;
p.selarrrow = [];
if (p.multiselect && lastSelArrRow && lastSelArrRow.length > 0) {
for (i = 0; i < lastSelArrRow.length; i++) {
if (lastSelArrRow[i] !== lastSelRow) {
$grid.jqGrid("setSelection", lastSelArrRow[i], false);
}
}
lastSelArrRow = [];
}
if (lastSelRow) {
$grid.jqGrid("setSelection", lastSelRow, false);
lastSelRow = null;
}
this.grid.bDiv.scrollLeft = lastScrollLeft;
};

Related

Execute validation with button

I'm looking to execute the Handsontable validation on the click of a button instead of on cell change. Something like this: validateCells() (return bool isValid). This function doesn't seem to be working for me.
var
data = [],
container = document.getElementById('hot-Handsontable'),
save = document.getElementById('save'),
hidden = document.getElementById('hot-Handsontable-value'),
hot,
hotIsValid = true,
emailValidator;
emptyValidator = function(value, callback) {
callback(false);
};
hot = Handsontable(container, {
data: data,
minRows: 1,
minCols: 21,
maxCols: 21,
minSpareRows: 1,
stretchH: 'all',
colHeaders: ['Test'],
columns: [{data:'Test',allowInvalid:true, validator: emptyValidator}]
});
// exclude empty rows from validation
$('.title-block .united-alert a[href^=#Handsontable]').click(function() {
var href = $(this).attr('href');
var row = href.getIdIndex();
var prop = /([^__]*)$/.exec(href)[0];
hot.selectCellByProp(parseInt(row), prop);
return false;
});
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
var test = hot.validateCells(); // test is undefined
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
});
What you should be doing, instead of var test = hot.validateCells() is the following:
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
hot.validateCells(function(hotIsValid) {
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
})
});
Notice that validateCells takes a callback and returns undefined. This is why you see test as undefined. One other thing to note is that the callback is executed for every cell in your table so be careful with it.

How do I retain filters in JqGrid whilst still getting remote data?

I'm using this demo to display text and dropdown list filters in the columns of a JqGrid. The grid has a remote data source and with each sort, filter, or page view etc, it grabs the data from the remote source.
The problem I am having is that when the new data arrives, the grid is refreshed, and the filters revert to default. I've looked at a few examples by Dr Oleg but I can't get it to work with remote data and persistence. Any setting of datatype to "local" or loadonce to true breaks the remote datasource.
Does anyone have any ideas of how to get this to work?
I've tried the following, but as I said, this stops the JqGrid from making API requests:
loadComplete: function () {
var $this = $(this);
var postfilt = $this.jqGrid('getGridParam', 'postData').filters;
var postsord = $this.jqGrid('getGridParam', 'postData').sord;
var postsort = $this.jqGrid('getGridParam', 'postData').sidx;
var postpage = $this.jqGrid('getGridParam', 'postData').page;
console.log(postfilt);
console.log(postsord);
console.log(postsort);
console.log(postsort);*/
if ($this.jqGrid("getGridParam", "datatype") === "json") {
setTimeout(function () {
$this.jqGrid("setGridParam", {
datatype: "local",
postData: { filters: postfilt, sord: postsord, sidx: postsort },
search: true
});
$this.trigger("reloadGrid", [{ page: postpage}]);
}, 25);
}
}
I think the issue has something to do with the select2 dropdown menus. Here you can see it destroys the filter menu and recreates it.
var options = colModelOptions, p, needRecreateSearchingToolbar = false;
if (options != null) {
for (p in options) {
if (options.hasOwnProperty(p)) {
if (options[p].edittype === "select") {
options[p].editoptions.dataInit = initSelect2;
}
if (options[p].stype === "select") {
options[p].searchoptions.dataInit = initSelect2;
}
$grid.jqGrid("setColProp", p, options[p]);
if (this.ftoolbar) { // filter toolbar exist
needRecreateSearchingToolbar = true;
}
}
}
if (needRecreateSearchingToolbar) {
$grid.jqGrid("destroyFilterToolbar");
$grid.jqGrid("filterToolbar", filterToolbarOptions);
}
}
If there was a way this could be done just once per JqGrid load rather than per every request, then that may be a step in the right direction.
The answer to this was quite simple, it just didn't present itself to me until the next morning. I simply wrapped the code that built the search bar in a boolean check, so that it only loaded once.
// somewhere in the class
var gridLoaded = false;
// and in the JqGrid initialization
loadComplete: function (response) {
if (!gridLoaded) {
var options = colModelOptions, p, needRecreateSearchingToolbar = false;
if (options != null) {
for (p in options) {
console.log(p);
if (options.hasOwnProperty(p)) {
if (options[p].edittype === "select") {
options[p].editoptions.dataInit = initSelect2;
}
if (options[p].stype === "select") {
options[p].searchoptions.dataInit = initSelect2;
}
$(this).jqGrid("setColProp", p, options[p]);
if (this.ftoolbar) { // filter toolbar exist
needRecreateSearchingToolbar = true;
}
}
}
if (needRecreateSearchingToolbar) {
$(this).jqGrid("destroyFilterToolbar");
$(this).jqGrid("filterToolbar", filterToolbarOptions);
}
}
gridLoaded = true;
}
}
Thanks again to Dr Oleg for the help.

SlickGrid filter not working

I am fairly new to SlickGrid. I am trying to make SlickGrid filter work but no luck. I am following the example (http://mleibman.github.io/SlickGrid/examples/example4-model.html).
Below is my source code.
$(document).ready(function() {
var tName;
$('#submit').click(function(e) {
tName = $('#source option:selected').text();// name1
tName = tName.trim();
$.ajax({
url : 'someUrl',
type : 'GET',
cache : false,
success : function(d) {
var grid;
var searchString = "";
var data = [];
var columns = new Array();
var cols = d[0].columns;
var pkColNames = d[0].pkColNames;
for (var j=0; j< cols.length; j++) {
var key = {id: cols[j].colName, name: cols[j].colName, field: cols[j].colName, width: 200, sortable:true, editor: Slick.Editors.LongText};
columns[j] = key;
}
var options = {
editable: true,
enableAddRow: false,
enableCellNavigation: true,
asyncEditorLoading: false,
enableColumnReorder:true,
multiColumnSort: false,
autoEdit: false,
autoHeight: false
};
function myFilter(item, args) {
return true;// Let us return true all time ?
}
for (var i = 0; i < d.length; i++) {
var tempData = (data[i] = {});
var title = null;
var val = null;
for (var q = 0; q < d[i].columns.length; q++) {
title = d[i].columns[q].colName;
val = d[i].columns[q].colValue;
tempData[title] = val;
}
}
var dataView = new Slick.Data.DataView({ inlineFilters: true });
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.setPagingOptions({
pageSize: 25
});
var pager = new Slick.Controls.Pager(dataView, grid, $("#myPager"));
var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onAddNewRow.subscribe(function(e, args) {
// Adding a new record is not yet decided.
});
grid.onCellChange.subscribe(function (e) {
var editedCellNo = arguments[1].cell;
var editedColName = grid.getColumns()[editedCellNo].field;
var newUpdatedValue= arguments[1].item[grid.getColumns()[editedCellNo].field];
var editedColType = "";
for (var cnt = 0; cnt < cols.length; cnt++) {
if (editedColName == cols[cnt].colName) {
editedColType = cols[cnt].colType;
break;
}
}
var pkKeyValue="";
for (var v=0; v <pkColNames.length;v++) {
for (var p=0; p<grid.getColumns().length; p++) {
if (pkColNames[v] == grid.getColumns()[p].field) {
var value = arguments[1].item[grid.getColumns()[p].field];
pkKeyValue += "{"+pkColNames[v] + '~' +getColDbType(grid.getColumns()[p].field) + ":"+value+"},";
break;
}
}
}
function getColDbType(colName) {
for (var c = 0; c < cols.length; c++) {
if (colName == cols[c].colName) {
return cols[c].colType;
}
}
}
pkKeyValue = pkKeyValue.substring(0, pkKeyValue.length-1);
$.ajax({
url: 'anotherUrl',
type:'GET',
dataType:'text',
success: function(f) {
bootbox.alert("Data updated successfully");
},
error: function() {
bootbox.alert("Error - updating data. Please ensure you are adding the data in right format.");
grid.invalidateAllRows();
grid.render();
}
});
});
grid.onClick.subscribe(function (e) {
//do-nothing
});
dataView.onRowsChanged.subscribe(function(e, args) {
grid.updateRowCount();
grid.invalidateRows(args.rows);
grid.render();
});
grid.onSort.subscribe(function(e, args) {
// args.multiColumnSort indicates whether or not this is a multi-column sort.
// If it is, args.sortCols will have an array of {sortCol:..., sortAsc:...} objects.
// If not, the sort column and direction will be in args.sortCol & args.sortAsc.
// We'll use a simple comparer function here.
var comparer = function(a, b) {
return a[args.sortCol.field] > b[args.sortCol.field];
}
// Delegate the sorting to DataView.
// This will fire the change events and update the grid.
dataView.sort(comparer, args.sortAsc);
});
// wire up the search textbox to apply the filter to the model
$("#txtSearch").keyup(function (e) {
console.log('Called...txtSearch');
Slick.GlobalEditorLock.cancelCurrentEdit();
// clear on Esc
if (e.which == 27) {
this.value = "";
}
searchString = this.value;
updateFilter();
});
function updateFilter() {
console.log("updateFilter");
dataView.setFilterArgs({
searchString: searchString
});
dataView.refresh();
}
dataView.beginUpdate();
dataView.setItems(data, pkColNames);
dataView.setFilterArgs({
searchString: searchString
});
dataView.setFilter(myFilter);
dataView.endUpdate();
},
error : function() {
bootbox.alert("Invalid user");
}
});
});
});
Your function myFilter() is always returning true so of course it will never work. The example that you looked at, was to filter something specific. I would recommend that you look at the following example to have a generic filter. From the example, simply type the text you are looking on a chosen column and look at the result... see example below (from SlickGrid examples).Using fixed header row for quick filters
In case you want a more in depth conditional filters ( > 10, <> 10, etc...), please take a look at my previous answer on how to make this kind of filtering possible, see my previous answer below:SlickGrid column type
Hope that helps you out

Kendo Ui Grid - dataItem.set() method not working properly

I have a grid with 4 columns name, age, collection, profit. But when I try to set a number column it's not reflecting on grid.
schema:
{
model:{
fields:{
name:{type:"string"},
age:{type:"number"},
collection: { type:"number", defaultValue:0.00},
profit: { type:"number", defaultValue:0.00}
}
}
}
This code works perfectly:
var grid = $("#grid").data("kendoGrid");
var data = grid.dataSource.at(0);
data.set("name", "John Doe");
But I want to update numeric column:
var grid = $("#grid").data("kendoGrid");
var data = grid.dataSource.at(0);
var collectionVal = 50000;
data.set("collection", collectionVal);
And it's not updating because the column is of type "number".
UPDATE:
pageable:
{
refresh : true,
pageSizes: true
},
edit: function(e)
{
$('input[name="age"]').blur(function()
{
mygrid = $("#grid").data("kendoGrid");
selectedRow = mygrid.select();
dataItem = mygrid.dataItem(selectedRow);
dataItem.collection = dataItem.age * dataItem.profit;
dataItem.set("collection", dataItem.collection);
});
}
Instead of updating collection in a blur handler defined in the edit, define a save event handler in your grid as follow:
pageable : {
refresh : true,
pageSizes: true
},
save : function (e) {
var profit = e.values.profit || e.model.profit;
var age = e.values.age || e.model.age;
this.dataSource.getByUid(e.model.uid).set("collection", age * profit);
}

How to specify row id using data option in jqgrid

I am using jqgrid and tableToGrid plugin but found that it's relatively slow with a large table. So I would like to rewrite it using the jqgrid's data option instead of using the original addRowData method. However, I cannot find any reference about specifying the row id using the data option. The grid just generate the id starting from 1 but I would like to specific the id in my row of data.
Do I need to use localReader together to make it work? A sample piece of code will be appreciated.
Here's my grid declaration. (edited from the original tabletogrid)
jQuery(this).jqGrid(jQuery.extend({
datatype: "local",
data:data,
width: w,
colNames: colNames,
colModel: colModel,
multiselect: selectMultiple
//inputName: inputName,
//inputValueCol: imputName != null ? "__selection__" : null
}, options || {}));
OK I figured it out using localReader. Here's the modified tableToGrid with better performance.
function tableToGrid(selector, options) {
jQuery(selector).each(function() {
if(this.grid) {return;} //Adedd from Tony Tomov
// This is a small "hack" to make the width of the jqGrid 100%
jQuery(this).width("99%");
var w = jQuery(this).width();
// Text whether we have single or multi select
var inputCheckbox = jQuery('input[type=checkbox]:first', jQuery(this));
var inputRadio = jQuery('input[type=radio]:first', jQuery(this));
var selectMultiple = inputCheckbox.length > 0;
var selectSingle = !selectMultiple && inputRadio.length > 0;
var selectable = selectMultiple || selectSingle;
//var inputName = inputCheckbox.attr("name") || inputRadio.attr("name");
// Build up the columnModel and the data
var colModel = [];
var colNames = [];
jQuery('th', jQuery(this)).each(function() {
if (colModel.length === 0 && selectable) {
colModel.push({
name: '__selection__',
index: '__selection__',
width: 0,
hidden: true
});
colNames.push('__selection__');
} else {
colModel.push({
name: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),
index: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),
width: jQuery(this).width() || 150
});
colNames.push(jQuery(this).html());
}
});
var data = [];
var rowIds = [];
var rowChecked = [];
jQuery('tbody > tr', jQuery(this)).each(function() {
var row = [];
var rowobj = {};
var rowPos = 0;
jQuery('td', jQuery(this)).each(function() {
if (rowPos === 0 && selectable) {
var input = jQuery('input', jQuery(this));
var rowId = input.attr("value");
rowIds.push(rowId || data.length);
rowobj["id"] = rowId || data.length;
if (input.attr("checked")) {
rowChecked.push(rowId);
}
//row[colModel[rowPos].name] = input.attr("value");
row.push( input.attr("value"));
} else {
//row[colModel[rowPos].name] = jQuery(this).html();
row.push(jQuery(this).html());
}
rowPos++;
});
if(rowPos >0) { rowobj["cell"] = row; data.push(rowobj); }
});
// Clear the original HTML table
jQuery(this).empty();
// Mark it as jqGrid
jQuery(this).addClass("scroll");
jQuery(this).jqGrid(jQuery.extend({
datatype: "local",
data:data,
localReader: {
repeatitems: true,
cell: "cell",
id: "id"
},
gridview: true,
width: w,
colNames: colNames,
colModel: colModel,
multiselect: selectMultiple
//inputName: inputName,
//inputValueCol: imputName != null ? "__selection__" : null
}, options || {}));
// Set the selection
for (a = 0; a < rowChecked.length; a++) {
jQuery(this).jqGrid("setSelection",rowChecked[a]);
}
});
};

Resources