Load local JSON data in jQgrid without AddJsonRows - jqgrid

I'm using the method addJsonRows to add local data to a jQgrid. As this method disables the sorting I need another solution. One restriction: I can't set the url and fetch the data from the server because the data was passed through another component.
Underneath snippet enlightens the case. The commented line shows the restriction, I replaced it by defining a local variable to have a test case.
<script type="text/javascript" language="javascript">
function loadPackageGrid() {
// Get package grid data from hidden input.
// var data = eval("("+$("#qsmId").find(".qsm-data-packages").first().val()+")");
var data = {
"page": "1",
"records": "2",
"rows": [
{ "id": "83123a", "PackageCode": "83123a" },
{ "id": "83566a", "PackageCode": "83566a" }
]
};
$("#packages")[0].addJSONData(data);
};
$(document).ready(function() {
$("#packages").jqGrid({
colModel: [
{ name: 'PackageCode', index: 'PackageCode', width: "110" },
{ name: 'Name', index: 'Name', width: "300" }
],
pager: $('#packagePager'),
datatype: "local",
rowNum: 10000,
viewrecords: true,
caption: "Packages",
height: 150,
pgbuttons: false,
loadonce: true
});
});
</script>
I wonder how I could do this in an other (better) way to keep the sorting feature.
I tried something with the data option, without result.

I suppose that the same question is interesting for other persons. So +1 from me for the question.
You can solve the problem in at least two ways. The first one you can use datatype: "jsonstring" and datastr: data. In the case you need to add additional parameter jsonReader: { repeatitems: false }.
The second way is to use datatype: "local" and data: data.rows. In the case the localReader will be used to read the data from the data.rows array. The default localReader can read the data.
The corresponding demos are here and here.
I modified a little your data: filled "Name" column and included the third item in the input data.
Now you can use local paging, sorting and filtering/searching of the data. I included a little more code to demonstrate the features. Below you find the code of one from the demos:
$(document).ready(function () {
'use strict';
var data = {
"page": "1",
"records": "3",
"rows": [
{ "id": "83123a", Name: "Name 1", "PackageCode": "83123a" },
{ "id": "83432a", Name: "Name 3", "PackageCode": "83432a" },
{ "id": "83566a", Name: "Name 2", "PackageCode": "83566a" }
]
},
grid = $("#packages");
grid.jqGrid({
colModel: [
{ name: 'PackageCode', index: 'PackageCode', width: "110" },
{ name: 'Name', index: 'Name', width: "300" }
],
pager: '#packagePager',
datatype: "jsonstring",
datastr: data,
jsonReader: { repeatitems: false },
rowNum: 2,
viewrecords: true,
caption: "Packages",
height: "auto",
ignoreCase: true
});
grid.jqGrid('navGrid', '#packagePager',
{ add: false, edit: false, del: false }, {}, {}, {},
{ multipleSearch: true, multipleGroup: true });
grid.jqGrid('filterToolbar', { defaultSearch: 'cn', stringResult: true });
});
UPDATED: I decided to add more details about the differences between datatype: "jsonstring" and datatype: "local" scenarios because the old answer be read and voted by many readers.
I suggest to modify the above code a little to show better the differences. The fist code uses datatype: "jsonstring"
$(function () {
"use strict";
var data = [
{ id: "10", Name: "Name 1", PackageCode: "83123a", other: "x", subobject: { x: "a", y: "b", z: [1, 2, 3]} },
{ id: "20", Name: "Name 3", PackageCode: "83432a", other: "y", subobject: { x: "c", y: "d", z: [4, 5, 6]} },
{ id: "30", Name: "Name 2", PackageCode: "83566a", other: "z", subobject: { x: "e", y: "f", z: [7, 8, 9]} }
],
$grid = $("#packages");
$grid.jqGrid({
data: data,
datatype: "local",
colModel: [
{ name: "PackageCode", width: 110 },
{ name: "Name", width: 300 }
],
pager: "#packagePager",
rowNum: 2,
rowList: [1, 2, 10],
viewrecords: true,
rownumbers: true,
caption: "Packages",
height: "auto",
sortname: "Name",
autoencode: true,
gridview: true,
ignoreCase: true,
onSelectRow: function (rowid) {
var rowData = $(this).jqGrid("getLocalRow", rowid), str = "", p;
for (p in rowData) {
if (rowData.hasOwnProperty(p)) {
str += "propery \"" + p + "\" + have the value \"" + rowData[p] + "\n";
}
}
alert("all properties of selected row having id=\"" + rowid + "\":\n\n" + str);
}
});
$grid.jqGrid("navGrid", "#packagePager",
{ add: false, edit: false, del: false }, {}, {}, {},
{ multipleSearch: true, multipleGroup: true });
$grid.jqGrid("filterToolbar", { defaultSearch: "cn", stringResult: true });
});
It displays (see the demo)
One can see unsorted items in the same order like input data. The items of input data will be saved in internal parameters data and _index. getLocalRow method used in onSelectRow shows that items of internal data contains only properties of input items which names corresponds to name property of some jqGrid columns. Additionally unneeded _id_ property will be added.
On the other side the next demo which uses datatype: "local" displays sorted data and all properties inclusive complex objects will be still saved in the internal data:
The code used in the last demo is included below:
$(function () {
"use strict";
var data = [
{ id: "10", Name: "Name 1", PackageCode: "83123a", other: "x", subobject: { x: "a", y: "b", z: [1, 2, 3]} },
{ id: "20", Name: "Name 3", PackageCode: "83432a", other: "y", subobject: { x: "c", y: "d", z: [4, 5, 6]} },
{ id: "30", Name: "Name 2", PackageCode: "83566a", other: "z", subobject: { x: "e", y: "f", z: [7, 8, 9]} }
],
$grid = $("#packages");
$grid.jqGrid({
data: data,
datatype: "local",
colModel: [
{ name: "PackageCode", width: 110 },
{ name: "Name", width: 300 }
],
pager: "#packagePager",
rowNum: 2,
rowList: [1, 2, 10],
viewrecords: true,
rownumbers: true,
caption: "Packages",
height: "auto",
sortname: "Name",
autoencode: true,
gridview: true,
ignoreCase: true,
onSelectRow: function (rowid) {
var rowData = $(this).jqGrid("getLocalRow", rowid), str = "", p;
for (p in rowData) {
if (rowData.hasOwnProperty(p)) {
str += "propery \"" + p + "\" + have the value \"" + rowData[p] + "\"\n";
}
}
alert("all properties of selected row having id=\"" + rowid + "\":\n\n" + str);
}
});
$grid.jqGrid("navGrid", "#packagePager",
{ add: false, edit: false, del: false }, {}, {}, {},
{ multipleSearch: true, multipleGroup: true });
$grid.jqGrid("filterToolbar", { defaultSearch: "cn", stringResult: true });
});
So I would recommend to use datatype: "local" instead of datatype: "jsonstring". datatype: "jsonstring" could have some advantages only in some very specific scenarios.

Great advice, Oleg.
In my web app, I pre-loaded some JSON data which looked like this:
{
WorkflowRuns:
[
{
WorkflowRunID: 1000,
WorkflowRunName: "First record",
},
{
WorkflowRunID: 1001,
WorkflowRunName: "Second record",
}
],
UserInformation:
{
Forename: "Mike",
Surname: "Gledhill"
}
}
And here's the code I needed to create the jqGrid, just based on the WorkflowRuns part of this JSON:
var JSONstring = '{ WorkflowRuns: [ { WorkflowRunID: 1000, .. etc .. } ]';
$("#tblWorkflowRuns").jqGrid({
datatype: "local",
data: JSONstring.WorkflowRuns,
localReader: {
id: "WorkflowRunID",
repeatitems: false
},
...
});
This was a bit of trial and error though.
For example, jqGrid seemed to ignore datastr: JSONstring for me.
And notice how, with local data, I needed to use localReader, rather than jsonReader, otherwise it wouldn't set the row IDs properly.
Hope this helps.

Related

jqGrid subGrid how to hide "+" expand icon if we don't have data sub grid

When i don't have any data in subgrid i am getting empty grid in subgrid. Also need to hide the expand icon. Below is the code i used.
$(document).ready(function() {
'use strict';
var myData = [
{
id: "10",
c1: "My Value 1",
c2: "My Value 1.1",
subgridData: [
{ id: "10", c1: "aa", c2: "ab" },
{ id: "20", c1: "ba", c2: "bb" },
{ id: "30", c1: "ca", c2: "cb" }
]
},
{
id: "20",
c1: "My Value 2",
c2: "My Value 2.1",
subgridData: [
{ id: "10", c1: "da", c2: "db" },
{ id: "20", c1: "ea", c2: "eb" },
{ id: "30", c1: "fa", c2: "fb" }
]
},
{
id: "30",
c1: "My Value 3",
c2: "My Value 3.1"
}
],
$grid = $("#list"),
mainGridPrefix = "s_";
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["Column 1", "Column 2"],
colModel: [
{ name: "c1", width: 180 },
{ name: "c2", width: 180 }
],
rowNum: 10,
rowList: [5, 10, 20],
pager: "#pager",
gridview: true,
ignoreCase: true,
sortname: "c1",
viewrecords: true,
autoencode: true,
height: "100%",
idPrefix: mainGridPrefix,
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId);
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: $(this).jqGrid("getLocalRow", pureRowId).subgridData,
colModel: [
{ name: "c1", width: 178 },
{ name: "c2", width: 178 }
],
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
gridview: true,
idPrefix: rowId + "_"
});
$subgrid.closest("div.ui-jqgrid-view")
.children("div.ui-jqgrid-hdiv")
.hide();
}
});
$grid.jqGrid("navGrid", "#pager", {add: false, edit: false, del: false});
});
My output like below screenshot. How to remove the expand icon and subgrid if we don't have any data for subgrid.
Is there any way to achieve this behavior. My output like below.
The solution of the problem depends on the version and the fork of jqGrid, which you use. I develop free jqGrid fork and have implemented hasSubgrid callback, which I described in the answer (see the demo).
The items of your input data contains subgridData property as the array of subgrid data. Thus one should create the subgrid only if subgridData property is defined and subgridData.length > 0. Thus you need just to upgrade to the current version of jqGrid (4.13.4 or 4.13.5pre) and to add the option
subGridOptions: {
hasSubgrid: function (options) {
// the options contains the following properties
// rowid - the rowid
// iRow - the 0-based index of the row
// iCol - the 0-based index of the column
// data - the item of the data, with the data of the row
var subgridData = options.data.subgridData;
return subgridData != null && subgridData.length > 0;
}
}
to the main grid. The callback subGridOptions.hasSubgrid will be called during building the grid data, thus it works very effective like rowattr, cellattr and custom formatters.

on jquery ajax call , unable to bind jqgrid data

I have 2 queries on binding jgGrid in MVC application..
1. I am unable to bind jsonData which is coming from controller on Success callback method
2. On button click i am loading jqgrid from server data, but when i click 2nd time it is not firing my server code(which is in controller), only first time it is executing the server code.
below is my javascript code
function buildGrid() {
// setup custom parameter names to pass to server prmNames: { search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" }, // add by default to avoid webmethod parameter conflicts postData: { searchString: '', searchField: '', searchOper: '' }, // setup ajax call to webmethod datatype: function(postdata) { mtype: "GET", $.ajax({ url: 'PageName.aspx/getGridData', type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(postdata), dataType: "json", success: function(data, st) { if (st == "success") { var grid = jQuery("#list")[0]; grid.addJSONData(JSON.parse(data.d)); } }, error: function() { alert("Error with AJAX callback"); } }); }, // this is what jqGrid is looking for in json callback jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it userdata: "userdata", repeatitems: true }, colNames: ['Id', 'First Name', 'Last Name'], colModel: [ { name: 'id', index: 'id', width: 55, search: false }, { name: 'fname', index: 'fname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} }, { name: 'lname', index: 'lname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} } ], rowNum: 10, rowList: [10, 20, 30], pager: jQuery("#pager"), sortname: "fname", sortorder: "asc", viewrecords: true, caption: "Grid Title Here" }).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false }, {}, // default settings for edit {}, // add {}, // delete { closeOnEscape: true, closeAfterSearch: true}, //search {} ) });
var grid = $("#jQGrid"); $("#jQGrid").jqGrid({
//setup custom parameter names to pass to server
prmNames: { search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" },
// add by default to avoid webmethod parameter conflicts
postData: {
'ddlDSVIN': function () {
return $('#ddlDevice :selected').val();
},
'search': function () { return $("#searchId").val(); },
'OEMType': function () { return $('#ddlOEM :selected').text(); },
'frmDate': function () { return fromDate.toDateString(); },
'toDate': function () { return toDate.toDateString(); }
},
datatype: function(postdata) { mtype: "POST",
$.ajax({ url: '/DataIn/DataInSearchResult/', type: "POST", contentType: "application/json; charset=utf-8",
//data: postData,
datatype: "json",
success: function(data, st) {
if (st == "success") {
var grid = jQuery("#jQGrid")[0]; grid.addJSONData(JSON.parse(data.d));
var container = grid.parents('.ui-jqgrid-view');
$('#showgrid').show();
$('#jQGrid').show();
$('#divpager').show();
//container.find('.ui-jqgrid-hdiv, .ui-jqgrid-bdiv').show();
$("#hideandshow").show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
$("#hideandshow2").hide();
}
},
error: function(error) { alert("Error with AJAX callback" + error); } }); }, // this is what jqGrid is looking for in json callback
jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it
userdata: "userdata", repeatitems: true
},
// url: '/DataIn/DataInSearchResult/',
colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', index: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2, key: true },
// { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
{ name: 'Device', jsonmap: 'Device', width: '65px' },
{ name: 'Type', jsonmap: 'Type', width: '65px' },
{ name: 'DateReported', jsonmap: 'DateReported', width: '100px' },
{ name: 'ErrorType', jsonmap: 'ErrorType', width: '85px' },
{ name: 'Error', jsonmap: 'Error', width: '160px' },
{ name: 'Latitude', jsonmap: 'Latitude', width: '78px' }, { name: 'Longitude', jsonmap: 'Longitude', width: '78px' },
{ name: 'Payloadurl', jsonmap: 'Payloadurl', width: '180px', formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
rowNum: 10, rowList: [10, 20, 30],
pager: jQuery("#divpager"), sortorder: "asc",
viewrecords: true, caption: "Grid Title Here"
}).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false }, {}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true}, //search
{ });
}
above method is called in document.ready function
$(documen).ready(function() {
("#buttonclick").click(function() {
buildGrid();
});
});
Can you please what was wrong with my code.. because i need to search on button click by passing the paramerter's to service method using postData {},but how to send this postData to url and bind the result to JqGrid.
thanks
Raj.
Usage of datatype as is not recommend way. Instead of that one can use datatype: "json". It informs that jqGrid should make for you the Ajax request using $.ajax method. One can use additional options of jqGrid to specify the options of the underlying $.ajax request.
The next problem you have in the code
$(documen).ready(function() {
$("#buttonclick").click(function() {
buildGrid();
});
});
The function buildGrid will be called every time if the user click on #buttonclick button. The problem is that you have initially the empty table
<table id="jQGrid"></table>
on your page, but after creating the grid (after the call $("#jQGrid").jqGrid({...});), the empty table will be converted in relatively complex structure of dives and tables (see the picture). The second call on non-empty table will be just ignored by jqGrid. It's the reason why the 2nd click on the button #buttonclick do nothing.
You can solve the problem in two ways. The first would be including $("#buttonclick").jqGrid("GridUnload"); before creating the grid. It would be destroy the grid and recreate the initial empty table. The second way os a little better. You can not destroy the grid at the second time, but to call $("#buttonclick").trigger("reloadGrid"); instead. It will force making new Ajax request to the server.
Minimal changing of your original code will follow us to about the following:
$(documen).ready(function() {
var $grid = $("#jQGrid");
$grid.jqGrid({
//setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
ddlDSVIN: function () {
return $('#ddlDevice').val();
},
search: function () {
return $("#searchId").val();
},
OEMType: function () {
return $('#ddlOEM')
.find("option")
.filter(":selected")
.text();
},
frmDate: function () {
return fromDate.toDateString();
},
toDate: function () {
return toDate.toDateString();
}
},
mtype: "POST",
url: '/DataIn/DataInSearchResult/',
datatype: "json",
ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
loadComplete: function () {
$('#showgrid').show();
$('#jQGrid').show();
$('#divpager').show();
$("#hideandshow").show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
$("#hideandshow2").hide();
},
jsonReader: {
root: root: function (obj) {
return typeof obj.d === "string" ?
$.parseJSON(obj.d) :
obj.d;
},
total: "totalpages",
records: "totalrecords"
},
colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', hidden: true, width: 2, key: true },
// { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
{ name: 'Device', width: 65 },
{ name: 'Type', width: 65 },
{ name: 'DateReported', width: 100 },
{ name: 'ErrorType', width: 85 },
{ name: 'Error', width: 160 },
{ name: 'Latitude', width: 78 },
{ name: 'Longitude', width: 78 },
{ name: 'Payloadurl', width: 180, formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
rowNum: 10,
rowList: [10, 20, 30],
pager: "#divpager",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here"
}).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true} //search
);
$("#buttonclick").click(function() {
$grid.trigger("reloadGrid");
});
});

jqGrid filterToolbar with local data

I have a jQgrid that loads data initially via an ajax call from backend(java struts). Again, this is one time load and once loaded, the jqGrid should operate on the data available locally.
Initially, datatype:json and once loadcomplete, set datatype:local.
Now is there a way to use filterToolbar for local datatype with the following options in free jqgrid;
autocomplete enabled in the toolbar
excel like filtering options
Jqgrid Options:
jQuery("#listTable").jqGrid({
url:'/WebTest/MainAction.do',
datatype: "json",
colNames: ['Label','Value'],
colModel: [
{name:'label',index:'label',width: 40,search:true, stype:'text',sorttype:'int'},
{name:'value',index:'value',width: 56,search:true, stype:'text',sorttype:'text'}
],
autowidth: true,
autoResizing: { compact: true, widthOfVisiblePartOfSortIcon: 13 },
rowNum: 10,
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: true,
toppager: true,
rownumbers: true,
sortname: "label",
sortorder: "desc",
caption: "Test 235",
height: "200",
search: true,
loadonce: true,
loadComplete: function (data) {
},
gridComplete: function(){
jQuery("#listTable").jqGrid('setGridParam', { datatype: 'local' });
}
}) .jqGrid("navGrid", { view: true, cloneToTop: true})
.jqGrid("filterToolbar")
.jqGrid("gridResize");
All the features are enabled by default if I understand you correctly. The server just have to return all data instead of one page of data to make loadonce: true property work correctly. You need just call filterToolbar after creating the grid. All will work like with local data. You should consider to set sorttype property for correct local sorting and stype and searchoptions for correct filtering of data.
To have "autocomplete" and "excel like filtering options" you need additionally to follow the answer which set autocomplete or stype: "select", searchoptions: { value: ...} properties based on different values of input data. You can do this inside of beforeProcessing callback. The code from the answer use this.jqGrid("getCol", columnName) which get the data from the grid. Instead of that one have access to data returned from the server inside of beforeProcessing callback. So one can scan the data to get the lists with unique values in every column and to set either autocomplete or stype: "select", searchoptions: { value: ...} properties.
UPDATED: I created JSFiddle demo which demonstrates what one can do: http://jsfiddle.net/OlegKi/vgznxru6/1/. It uses the following code (I changed just echo URL to your URL):
$("#grid").jqGrid({
url: "/WebTest/MainAction.do",
datatype: "json",
colNames: ["Label", "Value"],
colModel: [
{name: "label", width: 70, template: "integer" },
{name: "value", width: 200 }
],
loadonce: true,
pager: true,
rowNum: 10,
rowList: [5, 10, "10000:All"],
iconSet: "fontAwesome",
cmTemplate: { autoResizable: true },
shrinkToFit: false,
autoResizing: { compact: true },
beforeProcessing: function (data) {
var labelMap = {}, valueMap = {}, i, item, labels = ":All", values = [],
$self = $(this);
for (i = 0; i < data.length; i++) {
item = data[i];
if (!labelMap[item.label]) {
labelMap[item.label] = true;
labels += ";" + item.label + ":" + item.label;
}
if (!valueMap[item.value]) {
valueMap[item.value] = true;
values.push(item.value);
}
}
$self.jqGrid("setColProp", "label", {
stype: "select",
searchoptions: {
value: labels,
sopt: ["eq"]
}
});
$self.jqGrid("setColProp", "value", {
searchoptions: {
sopt: ["cn"],
dataInit: function (elem) {
$(elem).autocomplete({
source: values,
delay: 0,
minLength: 0,
select: function (event, ui) {
var grid;
$(elem).val(ui.item.value);
if (typeof elem.id === "string" && elem.id.substr(0, 3) === "gs_") {
grid = $self[0];
if ($.isFunction(grid.triggerToolbar)) {
grid.triggerToolbar();
}
} else {
// to refresh the filter
$(elem).trigger("change");
}
}
});
}
}
});
// one should use stringResult:true option additionally because
// datatype: "json" at the moment, but one need use local filtreing later
$self.jqGrid("filterToolbar", {stringResult: true });
}
});

JqGrid: sorting of local data

I have some problem with local data sorting in this example. Sorting doesn't work and I don't know reason of it. Could you explain problem in my code?
<table id="list" ></table>
<div id="pager"></div>
<script type="text/javascript">
var myData = [
{ id: "1", cell: ["1", "test"] },
{ id: "2", cell: ["2", "test2"] },
{ id: "3", cell: ["3", "test3"] },
{ id: "4", cell: ["4", "test4"] }
];
jQuery("#list").jqGrid({
data: myData,
datatype: "local",
colNames: ['MyId','Client'],
colModel: [{ name: 'MyId', index: 'MyId', width: 100, align: 'left' , sortable: true},
{ name: 'Client', index: 'Client', width: 100, align: 'left', sortable: true }],
rowNum:10,
rowList:[10,20,30,100],
pager: '#pager',
sortname: 'Id',
localReader: {repeatitems: true},
viewrecords: true,
sortable: true,
sortorder: "asc",
caption: "Tests",
loadonce: true
});
jQuery("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
</script>
P.S. Sorting also doesn't work in this demo with local data. http://www.ok-soft-gmbh.com/jqGrid/LocalReader.htm
You are right: jqGrid have bug in usage datatype: "local" with data parameter in localReader: {repeatitems: true} format.
There are many ways to fix the bug. One from the most easy one seems me to replace the lines
if(locdata || ts.p.treeGrid===true) {
rd[locid] = $.jgrid.stripPref(ts.p.idPrefix, idr);
ts.p.data.push(rd);
ts.p._index[rd[locid]] = ts.p.data.length-1;
}
with the following
if(locdata || ts.p.treeGrid===true) {
rd[locid] = $.jgrid.stripPref(ts.p.idPrefix, idr);
ts.p.data.push(rd);
ts.p._index[rd[locid]] = ts.p.data.length-1;
} else if (ts.p.datatype === "local" && dReader.repeatitems) {
var idStripted = $.jgrid.stripPref(ts.p.idPrefix, idr),
iData = ts.p._index[idStripted];
if (iData !== undefined && ts.p.data != null && ts.p.data[iData] != null) {
$.extend(true, ts.p.data[iData], rd);
}
}
The demo uses the fixed code and it works correctly now. I will post later the corresponding pull request with suggested fix to trirand.
UPDATED: I posted better implementation of the fix in the pull request.
UPDATED 2: My pull request is already merged to the main code of jqGrid on the github. You can do the same changes on jquery.jqGrid.srs.js, download the modified file from here. In any way the next version of jqGrid (version higher as 4.6.0) will contains the fix of described problem.

sortable rows not working while jquery-ui.js is implemented

I am trying to implement sortable rows in jqgrid, I have searched a lot but still sortable rows is not working. Here is my js files I have included
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.6.custom.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jqgrid/js/jquery.layout.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jqgrid/js/i18n/grid.locale-en.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jqgrid/js/jquery.jqGrid.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jqgrid/jquery.jqGrid.src.js")"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
here is my code
function BindGridView(columnNames, colModel) {
myData = [
{ ID: "1", Name: "Aswin", Value: "2" },
{ ID: "3", Name: "bshley", Value: "2" },
{ ID: "2", Name: "sgnel", Value: "4" },
{ ID: "4", Name: "dnoop", Value: "6" }
];
var gridimgpath = '/Scripts/jqgrid/themes/redmond/images';
$("#dataList").jqGrid('GridUnload');
jQuery("#dataList").jqGrid({
datatype: "local",
data: myData,
loadonce: true,
colNames: ["ID", "Name", "Value"],
colModel: [
{ name: "ID", width: 80 },
{ name: "Name", width: 90 },
{ name: "Value", width: 80, align: "right" }
],
autowidth: true,
width: 'auto',
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
scrolling: true,
shrinktofit: true,
pager: '#pager',
sortable: true,
sortname: 'Name',
rownumbers: false,
rownumWidth: 30,
viewrecords: true,
sortorder: "desc",
multiselect: false,
imgpath: gridimgpath,
}).navGrid("#pager",
{ refresh: false, add: false, edit: false, search: false, del: false },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{} // Search options. Some options can be set on column level
);
}
jQuery("#dataList").jqGrid(
'sortableRows',
{
update: function (e, ui) {
console.log("sortable");
alert("item with id=" + ui.item[0].id + " is droped");
}
});
jQuery("#dataList").setGridParam({ data: myData }).trigger("reloadGrid");
Grid is loaded with data but drag drop functionality of sortable row is not working.

Resources