Modifying sort columns in jqGrid - jqgrid

I'm having some difficulty figuring out how to programatically modify the sort definition that is sent to the server when a user clicks on a column to sort it. I have added a onSortCol function to my grid configuration. In that function, I need to check whether the "Id" column is in any sort position other than the last position. If it is, it should be removed.
Here is what I have tried:
onSortCol: function (index, iCol, sortOrder) {
var grid = $(this);
var rawSorts = index.split(",");
if (rawSorts.length > 1) {
var idFieldIndex = -1;
var processedSorts = [];
for (i = 0; i < rawSorts.length; i++) {
var currentSort = rawSorts[i].match(/[^ ]+/g);
if (idFieldIndex === -1 && currentSort[0].toUpperCase() === "ID") {
idFieldIndex = i;
}
processedSorts.push({
field: currentSort[0],
direction: currentSort[1] || sortOrder
})
}
if (idFieldIndex !== -1) {
processedSorts.splice(idFieldIndex, 1);
for (i = 0; i < processedSorts.length; i++) {
if (i + 1 < processedSorts.length) {
grid.sortGrid(processedSorts[i].field + " " + processedSorts[i].direction);
}
else {
grid.setGridParam("sortorder", processedSorts[i].direction);
grid.sortGrid(processedSorts[i].field + " ", true);
}
}
return "stop";
}
}
}

The most simple implementation seems to me the following: you don't use any sortname in the grid initially and you sort by Id on the server side if sidx is empty. It seems the only what you need to do to implement your requirements.

Related

How to copy a formula from "Parent Tab" to "Child Tab" on Google Sheet

I'm doing RolePlay Character Sheets on a "Parent tab" I've called "MODEL", where I masterize my formulas.
I've created a second tab "Character1" and a third one "Character2". But when I try to use =QUERY or =TEXTFORMULA or whatever. It doesn't make the formulas to calculate on the actual spreadsheet, it just get the data from the "MODEL" tab.
My only way is actually to copy/past all my formulas, but if I do a mistake, I'll have to correct it in every spreadsheet every time.
Is that possible to have a formula which take the cell at:
MODELE!AE58
And automatically generate the same formulas in every tabs:
CHARACTER1!AE58
CHARACTER2!AE58
etc...
Sorry if its blur, I'm doing my best to explain.
simple
Try
function onEdit(e) {
var sh = e.source.getActiveSheet()
var rng = e.source.getActiveRange()
if (rng.getFormula() != '' && sh.getName() == 'MODEL') {
var excl = ['MODEL', 'OTHER'];//excluded sheets
SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(sh => {
if (!~excl.indexOf(sh.getSheetName())) {
sh.getRange(rng.getA1Notation()).setFormula(rng.getFormula())
}
})
}
}
when you change a formula in MODEL, this will also change in other tabs excepts excluded ones
multiple
If you edit the formulas by dragging them into the MODEL sheet, use this one which allows you to edit all the formulas at once
function onEdit(e) {
var sh = e.source.getActiveSheet()
if (sh.getName() != 'MODEL') return;
for (var i = e.range.rowStart; i <= e.range.rowEnd; i++) {
for (var j = e.range.columnStart; j <= e.range.columnEnd; j++) {
if (sh.getRange(i, j).getFormula() != '') {
var excl = ['MODEL', 'OTHER'];//excluded sheets
SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(child => {
if (!~excl.indexOf(child.getSheetName())) {
child.getRange(sh.getRange(i, j).getA1Notation()).setFormula(sh.getRange(i, j).getFormula())
}
})
}
}
}
}
global
Il you need to reset all formulas, enable google sheets api and try
function onOpen() {
SpreadsheetApp.getUi().createMenu('⇩ M E N U ⇩')
.addItem('👉 Apply all formulas from MODEL to all tabs', 'spreadFormulas')
.addToUi();
}
function spreadFormulas() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('MODEL')
if (sh.getName() != 'MODEL') return;
var data = [];
var formulas = sh.getRange(1, 1, sh.getLastRow(), sh.getLastColumn()).getFormulas()
for (var i = 0; i < formulas.length; i++) {
for (var j = 0; j < formulas[0].length; j++) {
if (formulas[i][j] != '') {
var excl = ['MODEL', 'OTHER'];//excluded sheets
SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(child => {
if (!~excl.indexOf(child.getSheetName())) {
data.push({
range: `${child.getName()}!${columnToLetter(+j + 1) + (+i + 1)}`,
values: [[`${formulas[i][j]}`]],
})
}
})
}
}
}
if (data.length) {
var resource = {
valueInputOption: 'USER_ENTERED',
data: data,
};
try { Sheets.Spreadsheets.Values.batchUpdate(resource, ss.getId()); } catch (e) { console.log(JSON.stringify(e)) }
}
}
function columnToLetter(column) {
var temp, letter = '';
while (column > 0) {
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
if your sheet is called MODELE try on some other sheet just:
=MODELE!AE58
for array it would be:
={MODELE!AE58:AE100}
also take a look into "Named Ranges" - maybe you will find it more handy

Changing number of columns while using tablesorter pager with ajax

I am trying to add/remove columns depending on what is returned from the server in the ajaxProcessing function. I can see in the pager source that this isn't possible directly.
// only add new header text if the length matches
if ( th && th.length === hl ) {
Is there any workaround to this or should I start tinkering with the code? If I need to make changes, any advice on what to start with? Thanks.
Added this in the ajaxProcessing event and it did the trick.
var headerCount = $('#id thead tr:eq(0) th').length;
var hl = data.headers.length;
if (headerCount < hl) {
for (var i = headerCount; i < hl; i++) {
$('#id thead tr:eq(0)').append('<th>' + data.headers[i] + '</th>');
}
}else if (headerCount > hl) {
for (var i = headerCount - 1; i >= hl; i--) {
$('#id thead tr:eq(0) th:eq(' + i + ')').remove();
}
}
if(headerCount !== hl) $('#id').trigger('updateAll', [false, null]);

Setting Sort Direction on Column Click for ASP.NET Telerik MVC Grid Column

Currently using the Telerik MVC 3.0 in Asp.net. I Have grid with few Columns.
When the pageloads the rows are binded. When i click on the column it should sort in Descending sorder in the first Click instead of Ascending order.
You can do it by overwritting grid's toggleOrder method.
First, define a new ReverseToggleOrder function:
function ReverseToggleOrder(l) {
l = typeof l == "number" ? this.columns[l] : l;
var n = "desc";
if (l.order == "desc") {
n = "asc";
} else {
if (l.order == "asc") {
n = null;
}
}
l.order = n;
var m = $.inArray(l, this.sorted);
if (this.sortMode == "single" && m < 0) {
$.each(this.sorted, function () {
this.order = null;
});
this.sorted = [];
}
if (m < 0 && n) {
this.sorted.push(l);
}
if (!n) {
this.sorted.splice(m, 1);
}
}
function grid_onLoad(e) {
var grid = $(this).data('tGrid');
grid.toggleOrder = ReverseToggleOrder;
}
Then in grid's OnLoad event handler you need to overwrite its default behaviour:
.ClientEvents(events => events.OnLoad("grid_onLoad"))
The Grid does not support such sorting configuration. It always sorts ASC then DESC.

Calling sort on slickgrid

In the slickgrid I'm able to set the sort column and it's sort direction using the grid.SetSortColumn(colName,true/false). This only sets the sorting glyph but does no sorting. Is there a way to call the sort event handler. I've defined the sort handler like grid.onSort.subscribe(function(){});
The behavior you are observing is correct.
grid.setSortColumn(columnId, isAsc);
only updates the glyph on the sort column.
In your case, you will initially need to sort the data, and then use setSortColumn to update the glyph on sortColumn. You can reuse sorter used in onSort event like this:
var gridSorter = function(columnField, isAsc, grid, gridData) {
var sign = isAsc ? 1 : -1;
var field = columnField
gridData.sort(function (dataRow1, dataRow2) {
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2) ? 0 :
((value1 > value2 ? 1 : -1)) * sign;
return result;
});
grid.invalidate();
grid.render();
}
var grid = new Slick.Grid($gridContainer, gridData, gridColumns, gridOptions);
//These 2 lines will sort you data & update glyph while loading grid
//columnField is field of column you want to sort initially, isAsc - true/false
gridSorter(columnField, isAsc, grid, gridData);
//I had the columnField, columnId same else used columnId below
grid.setSortColumn(columnField, isAsc);
grid.onSort.subscribe(function(e, args) {
gridSorter(args.sortCol.field, args.sortAsc, grid, gridData);
});
How I arrived on this solution?
Read comments here. https://github.com/mleibman/SlickGrid/issues/325
dataView.fastSort does the job. You can then use setSortColumn to set the sorting glyph.
I have multiple column sort enabled, I had to change the function to pass the correct sort column.
grid.onSort.subscribe(function(e, args) {
gridSorter(**args.sortCols[0].sortCol.field**, **args.sortCols[0].sortAsc**, grid, gridData);
});
You can trigger click event on the column header...which does sorting
I fixed the issue like this...
$('.slick-header-columns').children().eq(0).trigger('click'); // for first column
I was inspired by Mr.Hunts answer but I took a slightly different approach to extend the current grid.setSortColumn(columnId, isAsc) to grid.setInitialSortColumn(columnId, isAsc). This will apply the sort and do everything grid.setSortColumn does.
var thisGrid = { //Your grid obj
columns: , // Your columns object
grid: , // new Slick.Grid....
}
thisGrid.grid.onSort.subscribe(function (e, args) { // ar var cols = args.sortCols;]
thisGrid.grid.customSort(args);
});
thisGrid.grid.customSort = function (args) {
var cols = args.sortCols;
thisGrid.dataView.sort(function (dataRow1, dataRow2) {
if (cols) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field],
value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
}
return 0;
});
}
thisGrid.grid.setInitialSortColumn = function (columnId, ascending) {
thisGrid.grid.setInitialSortColumns([{
columnId: columnId,
sortAsc: ascending
}
]);
};
thisGrid.grid.setInitialSortColumns = function (cols) {
sortColumns = cols;
$.each(sortColumns, function (i, col) {
var columnIndex = thisGrid.grid.getColumnIndex(col.columnId);
var column = thisGrid.columns[columnIndex];
if (col.sortAsc == null) {
col.sortAsc = true;
}
var args = {
grid: thisGrid.grid,
multiColumnSort: true,
sortCols: [{
sortCol: column,
sortAsc: col.sortAsc
}
]
}
thisGrid.grid.setSortColumn(col.columnId, col.sortAsc);
thisGrid.grid.customSort(args);
});
};
// Trigger
thisGrid.grid.setInitialSortColumn("dateDue", true);
I can't leave comments due to reputation, which is where this would be most appropriate, however, my answer is in regard to #Premshankar Tiwari and #Siddharth answers.
I preferred the dataView.fastSort option in Siddharth's answer, which works for me in all browsers except IE7 and 8. I didn't test it in IE9 or above. Unfortunately, most on my network run IE7 or 8 due to compatibility issues for legacy applications. BUT, Premshankar's answer works in IE7 and 8.
So, I ended up doing something like this:
if (msie > 0) {
$(".slick-header-columns").children().eq(5).trigger("click");
$(".slick-header-columns").children().eq(4).trigger("click");
} else {
dataView.fastSort('process','unit');
}
where column index (5) = 'unit' and column index (4) = 'process'. Notice that is the reverse order in dataView.fastSort method. I am also using a function that detects IE browser version and assigns it to msie.
My only complaint about utilizing the .trigger method is that if you set up your grid to dynamically hide/show columns, the indexed feature would potentially sort on unintended columns unless you are only calling it on initialization when hide/show capabilities are present.
Maybe it will help you. Looks like SlickGrid is triggering sort to self - so You can trigger it manually if You want.
I'm using multicolumn sorting, and loading saved sort data when initialising the grid.
As expected, setSortColumns set the sorting, but didnt actually apply it, and dataView.reSort() or .fastSort() didnt seem to help, regardless of what point in loading I called them
(I must have missed something, but just couldnt get it to work).
In the end, this worked for me. I call it immediately after populating my dataView from an ajax call.
Its probably not the slickest, so happy to take feedback on board!
function forceResort() {
var sortColumns = grid.getSortColumns();
var cols = [];
$.each(sortColumns, function(index, value) {
var columnId = value.columnId;
var sortAsc = value.sortAsc;
var sortCol = { field: columnId };
var col = { sortCol: sortCol, sortAsc : sortAsc};
cols.push(col);
});
dataView.sort(function (dataRow1, dataRow2) {
var sortResult = 0;
for (var i = 0, l = cols.length; i < l; i++) {
if (sortResult !== 0) {
break;
}
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field] || ''; //handle nulls - otherwise erratic sorting
var value2 = dataRow2[field] || ''; //handle nulls - otherwise erratic sorting
if ($.inArray(field, dateTypeColumns) > -1) {
sortResult = compareDates(value1, value2) * sign;
} else {
if ($.inArray(field, numericColumns) > -1) {
sortResult = compareSimple(value1, value2) * sign;
} else {
sortResult = compareAlphaNumeric(value1, value2) * sign;
}
}
}
return sortResult;
});
grid.invalidate();
grid.render();
}
A more clean solution is not to rely on the arguments to onSort but call getSortColumns instead:
function gridSorter() {
var scol=grid.getSortColumns();
if (scol.length===0) return;
var scolId=scol[0].columnId, asc=scol[0].sortAsc;
data.sort(function(a, b) {
var result = a[scolId] > b[scolId] ? 1 : a[scolId] < b[scolId] ? -1 : 0;
return asc ? result : -result;
});
grid.invalidate();
}
Then do:
grid.onSort.subscribe(gridSorter);
This will allow to reestablish sorting anytime you want (from example after reloading the data with ajax) simply by calling gridSorter()
If you want multiple column sorting:
function grid_sorter(args, grid, dataView) {
let cols = args.sortCols;
console.log(cols)
dataView.sort(function (dataRow1, dataRow2) {
for (let i = 0, l = cols.length; i < l; i++) {
let field = cols[i].sortCol.field;
let sign = cols[i].sortAsc ? 1 : -1;
let value1 = dataRow1[field], value2 = dataRow2[field];
let result = (value1 === value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result !== 0) {
return result;
}
}
return 0;
});
grid.invalidate();
grid.render();
}
grid_sorter(default_sorting, grid_2, dataView_2);
cols is an object like this:
- sortCols {
- length: 2
- 0 : {
"sortAsc: true,
"sortCol": {
"field: column_id
}
}
- 1: {..}
}

Column sort reset of ascending/descending on 3rd click

Suppose we've a grid with sortable columns.
If a user clicks on a column, it gets sorted by 'asc', then if a user clicks the column header again, it gets sorted by 'desc', now I want similar functionality when a user clicks the column third time, the sorting is removed, i.e. returned to previous style, the css is changed back to normal/non-italic etc?
Today I was trying to achieve same thing. I've skimmed through SlickGrid code but didn't find any 'Reset' function. So, I've tweaked the slick.grid.js v2.2 a little bit.
Basically you just need to add a new array - 'latestSortColumns' which will store sort columns state (deep copy of internal SlickGrid sortColumns array).
var latestSortColumns = [];
Optionally add new setting to opt-in for sort reset.
var defaults = {
(...),
autoResetColumnSort: false
};
Change setupColumnSort to reset sort after third click on column's header.
function setupColumnSort() {
$headers.click(function (e) {
// temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
e.metaKey = e.metaKey || e.ctrlKey;
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length) {
return;
}
var column = $col.data("column");
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
var sortOpts = null;
var i = 0;
for (; i < sortColumns.length; i++) {
if (sortColumns[i].columnId == column.id) {
sortOpts = sortColumns[i];
sortOpts.sortAsc = !sortOpts.sortAsc;
break;
}
}
**if ((e.metaKey || (options.autoResetColumnSort && latestSortColumns[i] != null && latestSortColumns[i].sortAsc === !column.defaultSortAsc)) && options.multiColumnSort) {**
if (sortOpts) {
sortColumns.splice(i, 1);
**latestSortColumns.splice(i, 1);**
}
}
else {
if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
sortColumns = [];
}
if (!sortOpts) {
sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc };
sortColumns.push(sortOpts);
} else if (sortColumns.length == 0) {
sortColumns.push(sortOpts);
}
}
setSortColumns(sortColumns);
if (!options.multiColumnSort) {
trigger(self.onSort, {
multiColumnSort: false,
sortCol: column,
sortAsc: sortOpts.sortAsc}, e);
} else {
trigger(self.onSort, {
multiColumnSort: true,
sortCols: $.map(sortColumns, function(col) {
return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
})}, e);
}
}
});
}
Store new state after every sort change in latestSortColumns:
function setSortColumns(cols) {
sortColumns = cols;
var headerColumnEls = $headers.children();
headerColumnEls
.removeClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
$.each(sortColumns, function(i, col) {
if (col.sortAsc == null) {
col.sortAsc = true;
}
var columnIndex = getColumnIndex(col.columnId);
if (columnIndex != null) {
headerColumnEls.eq(columnIndex)
.addClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
}
});
**for (var i = 0; i < sortColumns.length; i++)
latestSortColumns[i] = { columnId: sortColumns[i].columnId, sortAsc: sortColumns[i].sortAsc };**
}
That's all, should work now.
This is a function I call to reset all columns back to their original order.
It requires one of columns to be set up as not sortable.
In the example below I use the first column of the table, columns[0], which has the field id "locus".
function removeSorting() {
columns[0].sortable = true;
$('.slick-header-columns').children().eq(0).trigger('click');
columns[0].sortable = false;
// clear other sort columns
grid.setSortColumns( new Array() );
}
Then in the typical dataView.sort() function you make an exception for this column:
grid.onSort.subscribe(function(e,args) {
var cols = args.sortCols;
dataView.sort(function (dataRow1, dataRow2) {
for( var i = 0; i < cols.length; i++ ) {
var field = cols[i].sortCol.field;
// reset sorting to original indexing
if( field === 'locus' ) {
return (dataRow1.id > dataRow2.id) ? 1 : -1;
}
var value1 = dataRow1[field];
var value2 = dataRow2[field];
if( value1 == value2 ) continue;
var sign = cols[i].sortAsc ? 1 : -1;
return (value1 > value2) ? sign : -sign;
}
return 0;
});
});
Will the table always be sorted in some order on some column?
If not then you'll have to store a lot of state the first time a column is clicked just in case you want to restore it after a third click.

Resources