How to get the selected row ids sorted according to index in jqgrid? - jqgrid

I'm using
getGridParam('selarrrow');
to get the rows that are selected,where the method returns me the selected row ids according to their selection,but I want the ids according to their index.Do I have to write a method to sort the ids or is there a inbuilt method which returns me the selected row ids in order of their indexes.
thanks in advance

If you mean the index of the row in the grid then you have to resort the array or id returned by $("#gridId").jqGrid("getGridParam", "selarrrow"). You can use sort() method of Array with your custom sort function. You can just use the fact that ids are the ids of <tr> elements. So the DOM elements of <tr> has native implemented rowIndex property which you can get by $("#"+rowid)[0].rowIndex.
In the simplified form the code could be about the following
var selRowIds = $("#gridId").jqGrid("getGridParam", "selarrrow");
selRowIds.sort(function (id1, id2) {
// one can use document.getElementById alternatively
return $("#" + id1)[0].rowIndex - $("#" + id2)[0].rowIndex;
});
or you can use namedItem method instead
var $grid = $("#gridId"),
selRowIds = $grid.jqGrid("getGridParam", "selarrrow"),
rows = $grid[0].rows;
selRowIds.sort(function (id1, id2) {
return rows.namedItem(id1).rowIndex - rows.namedItem(id2).rowIndex;
});
Probably you should include more verification in the code to be sure that the item with id will be found and it has the rowIndex property.

Related

Sorting an observable array, which has queried data returned by breezeJS

The above image is of observableArray which is coming while queryinq database using breezeJS (using EntityManager).
My question is that
how do we sort this observable based on some criteria i.e.,
(object.attributeName) ?
So that this array is sorted based on some attribute name and we can simply use the observable within foreach bindings and use them in sorted way because I don't wanna query all the time (locally or from server) to get data in sorted order.
So make a computed
var orderDirection = ko.observable(1);
var orderField = ko.observable("id");
var orderedObsArr = ko.computed(function(){
var oDir = orderDirection();
var oField = orderField();
var newArr = originalObsArr().slice(0);
newArr.sort(function(a,b){
return oDir * (a[oField] > b[oField] ? 1 : -1);
});
return newArr;
});
so to change to a sort by name descending, you simply change:
orderDirection(-1);
orderField("name");
and your computed dependent orderedObsArr will be updated.
See this pen for a working example.

slickgrid - grid.getDataItem(0), dataView.getItem(0) and .dataView.getItemByIdx(0) returning reference

I'm trying to duplicate a row, but change like one column.
So I do something like this:
var item = myGrid.grid.getDataItem(rowIndex);
item.id=123;
myGrid.dataView.addItem(item);
My issue is that if I am duplicating the row at index 0, when I do:
item.id = 123;
It actually makes id of the row at index 0 as 123 as well as the new line.
Is there a way to get the data and not get the actual reference to the row?
Thanks!
In this case, I would use the jQuery $.extend method to create a new object:
var newItem = {};
$.extend(newItem, item);
newItem.id=123;
myGrid.dataView.addItem(newItem);

JQGrid Grouping GroupText formatting and modification

I have a grid that implements grouping but would like to expand on the details that display in the groupText: area. Ideally I would be able to take data about that grouping and display in that group row with the group name ({0} default value).
In other words what I am trying to achieve is a way to display not only the group name but also some other data items contained in the JSON feed to the grid.
My searching seems to be coming up short on anyone being able to achieve this but I'm hoping someone can shed some light on expanding this setting and providing access to formating this area.
I find your question interesting, but the implementation is not simple. In the answer I showed before how one could use custom formatter in summary rows of the grouping.
In the demo you can see how to implement custom formatting of the grouping text. The demo display the following:
The implementation consist just from the implementation of the custom formatter which can be used for both purpose: formatting of the content of the corresponding column and formatting of the grouping text in case of grouping by the column. The code is a little tricky, but I hope that all will be able follow it. The code use the differences of the input parameters to define whether the formatter will be called to format the column content or to format the grouping text.
One part of the code which get the texts like "(test4,test7)" is not so effective in case of the usage of large number of rows, but it works.
Below is the code of formatter of the "Date" column which would by typically used with the predefined formatter: 'date'. I called in the part of the code the original Date-formatter, but used for the the grouping text more sophisticated code:
formatter: function (cellval, opts, rowObject, action) {
var fullOpts = $.extend({}, $.jgrid.formatter.date, opts),
formattedDate = $.fmatter.util.DateFormat('Y-m-d', cellval, 'd-M-Y', fullOpts),
groupIdPrefix = opts.gid + "ghead_",
groupIdPrefixLength = groupIdPrefix.length,
month = Number(cellval.split('-')[1]), // input format 'Y-m-d'
names = [], data, i, l, item;
// test wether opts.rowId start with opts.gid + "ghead_" and integer
// and rowObject is the array and action is undefined.
if (opts.rowId.substr(0, groupIdPrefixLength) === groupIdPrefix && typeof action === "undefined") {
// custom formating of the group header
// we just simulate some login by testing of the month > 9
// the next code fragment is not effective, but it can be used
// in case of not so large number of groups and the local data
data = $(this).jqGrid("getGridParam", "data");
for (i = 0, l = data.length; i < l; i++) {
item = data[i];
if (item.invdate === cellval) {
names.push(item.name);
}
}
return (month > 9 ? ('<span class="ui-icon ui-icon-alert" style="float: left;"></span>' +
'<span style="color:tomato; margin-left: 5px;">') : "<span>") +
formattedDate + ' (' + names.join() + ')</span>'
}
return formattedDate;
}
UPDATED: The fixed version of the demo is here. It uses $.fn.fmatter instead of currently removed from jqGrid method $.fmatter.util.DateFormat.

Get all rows not filtered from jqGrid

I have local data in a grid. How can I get all of the rows or IDs that are not removed after a user uses the filter toolbar? I need to get all filtered rows, regardless of pagination.
For example, say I begin with 50 rows in the grid. The user uses the filter toolbar and the set of rows decreases to 10 rows. How can I get those ten rows?
There are no direct way to get the information which you need. Internally jqGrid uses $.jgrid.from to filter local data. The main code which uses $.jgrid.from in inside of addLocalData. To get results which you need without studying all the code I suggest to use the fact that all filtered data will be returned by select method of $.jgrid.from (see the line of code). My suggestion is to catch the data before the data will be cut to the page size.
To do this I suggest to use sub-classing: overwriting of the method select method of $.jgrid.from. I demonstrate the technique in the examples created for the answer and this one.
In your case the code will be
var oldFrom = $.jgrid.from,
lastSelected;
$.jgrid.from = function (source, initalQuery) {
var result = oldFrom.call(this, source, initalQuery),
old_select = result.select;
result.select = function (f) {
lastSelected = old_select.call(this, f);
return lastSelected;
};
return result;
};
Now the variable lastSelected will save the array of elements which are results of the last sorting or filtering operation. Because $.jgrid.from is global the data are not connected to the grid. If you have more as one grid on the page it will be uncomfortable. One can fix the small disadvantage with the following line in the code of loadComplate of every grid:
loadComplete: function () {
this.p.lastSelected = lastSelected; // set this.p.lastSelected
}
In the way we introduce new jqGrid parameter lastSelected which will have close structure as data parameter, but will hold only last filtered data.
The following code will display the ids of filtered data in alert message
$("#getIds").click(function () {
var filteredData = $grid.jqGrid('getGridParam', 'lastSelected'), i, n, ids = [],
idName = $grid.jqGrid('getGridParam', 'localReader').id;
if (filteredData) {
for (i = 0, n = filteredData.length; i < n; i++) {
ids.push(filteredData[i][idName]);
}
alert("tolal number of filtered data: " + n + "\n" +
"ids of filtered data:\n" + ids.join(', '));
}
});
I used localReader.id parameter because property name used for local data are typically id or _id_. The _id_ will be used in case of data loaded from the server if one uses loadonce: true option.
The demo demonstrate the approach. If one filter for example only the data from FedEx and then clicks on "Show Ids" button one will see information about all filtered and not only about the data displayed on the current page:
UPDATED: free jqGrid provides new lastSelectedData option. See the demo in the list of demos.
You colud use afterSearch option of the search toolbar:
var filteredIDs = new Array(); //Global variable
$("#"+gridId).jqGrid("filterToolbar", { stringResult:true, searchOnEnter:false,
afterSearch:function(){
filteredIDs = $("#"+gridId).getDataIDs();
}
});
If you want to get the filtered rows instead the filtered IDs, use getRowData() instead of getDataIDs().
All, I found another answer which is far easier to include
loadComplete: function (gridData) {
var isSearchPerformed = $grid.getGridParam("postData")._search;
if (isSearchPerformed) {
$("#spanFilterTotal").text(gridData.records);
}
All you want is below:
$.each($grid.getRowData(), function( index, value ) {
a.push(value["COLUMN_NAME"]); //Get the selected data you want
});

Is there a way to get the column number by column name in jqgrid

I tried to access the rowObject in custom formatter function by column name but it didn't give any values. I have tried this with both JSON and XML data type .
Is there any way to get the column number by column name in jqgrid.
function Draw_Link ( cellvalue , options , rowObject )
{
return "<a href='someurl.php?col_name="+rowobject.col_name+"'>"+cellvalue+"</a>";
}
The column index for the column is the same as the index of the column in the colModel array before the jqGrid initialization (it is the same as in the input parameter colModel). If you use rownumbers:true, multiselect:true or subGrid:true additional columns will be addid to the grid as the first rows, so the column index which one has in the colModel array as the jqGrid parameter can be other as one have after the grid initialization. You can use for example this simple function to get the index
var getColumnSrcIndexByName = function(grid,columnName) {
var cm = grid.jqGrid('getGridParam','colModel'),
i=0, index=0, l=cm.length, cmName;
while (i<l) {
cmName = cm[i].name;
i++;
if (cmName===columnName) {
return index;
} else if (cmName!=='rn' && cmName!=='cb' && cmName!=='subgrid') {
index++;
}
}
return -1;
};
var index = getColumnSrcIndexByName($("#list"),'MyColumn');
UPDATED: Free jqGrid fork simplifies getting column index from column name because it holds internally the parameter iColByName, which is the map by the column name. One can just get iColByName via
var iColByName = $("#list").jqGrid("getGridParam", "iColByName");
and iColByName["MyColumn"] will be the required column index (iCol). I remind that one can use getGridParam without any parameter to get the reference to all parameters of jqGrid:
var p = $("#list").jqGrid("getGridParam");
The value
var iCol = p.iColByName["MyColumn"];
will be the column index and p.colModel[iCol].name will be "MyColumn".

Resources