Why "allData" is an empty array? - jqgrid

I am trying to get the data from a jqGrid (free version and latest version) and it's suppose that I get:
all the data if none is selected
the selected data if any
This is how I am doing it:
$(function () {
var $order_logs = $('#order_logs');
$order_logs.jqGrid({
url: Routing.generate('api_order_logs'),
datatype: "json",
colModel: $colmodel.data('values'),
width: 980,
height: 300,
pager: true,
toppager: true,
hoverrows: true,
shrinkToFit: true,
autowidth: true,
rownumbers: true,
viewrecords: true,
rowList: [25, 50, 100],
rownumWidth: 60,
gridview: true,
sortable: {
options: {
items: ">th:not(:has(#jqgh_order_logs_cb,#jqgh_order_logs_rn,#jqgh_order_logs_actions),:hidden)"
}
},
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
cell: '',
repeatitems: false
},
cmTemplate: {autoResizable: true, editable: true},
autoResizing: {compact: true, resetWidthOrg: true},
autoresizeOnLoad: true
}).jqGrid('navGrid', {
edit: false,
add: false,
del: false,
search: false,
refresh: true,
refreshstate: "current",
cloneToTop: true
}).jqGrid('navButtonAdd', {
caption: 'Export',
title: 'Export',
onClickButton: function () {
var filteredData = $order_logs.jqGrid("getGridParam").lastSelectedData,
allData = $order_logs.jqGrid('getGridParam', 'data');
exportData(filteredData, allData);
}
});
});
function exportData(filteredData, allData) {
if (filteredData.length === 0 || allData.length === 0) {
alert('There is no data to export');
return;
}
// Export only the filtered data
if (filteredData.length > 0) {
return;
}
// Export all the grid data
}
For some reason the value of allData is always an empty array and I am not sure since I am using the same code as everyone is using out there and found in a lot of answer here in SO.
UPDATE:
Currently the grid is holding six columns and a set of 60 records as total paginated by 20 each time however you can change the pagination to be 50 or 100.
Can any tell me why is this?

I'd recommend to use loadonce: true, forceClientSorting: true options in case of small dataset: less at 1000 or 10000 rows. It simplifies the code server side and you can use full functionality of free jqGrid. The problem with access to lastSelectedData and data will be solved.
More then that, you can easy use many advanced features like createColumnIndex: true, generateValue: true of generateDatalist: true options and so on. See demos included in README of version 4.14.1. Good and comfortable filtering of the data is, in my option, the part of displaying the data. Having the data locally allows to find unique values and build <select> in the filter bar or to use <datalist> to have autocomplete functionality.

Related

How to perform toolbar searching based on certain condition in free jqgrid 4.15.4

Though I have spent a lot of time on looking for similar QA here but Can't able to find out. If You think that I missed checking something please let me know.
question metadata:
So I am using free jqGrid 4.15.4 for showing data in view. I am able to do all things with awesome documentation. but one certain condition where I am not getting about steps.
In my grid, I have 4 columns named as Id, Name, Group, and Status. Group(Section A/ Section B....) are coming from database. Status(New/Pass /Fail) column consist dropdown and by default value is "New" for all records.
question statement :
There are 5 records and I have Selected "Pass" status for 2 out of 5. Now I want to see all 5 records if I select "New" in filter toolbar for that particular group(section A). Since I don't how many names belongs to that particular group, so I want to check this by filtering all records with "New" status. Is this possible with jqgrid? StudentGrid.png
Here is the code snippet:
$("#grid").jqGrid({
url: '/StudentsView/GetAllData',
mtype: "GET",
datatype: "json",
colNames: ['Id','Name', 'Group','Status'],
colModel: [
{label: "Id",name: 'Id',hidden: true,search: false,key:true},
{label: "Name",name: 'Name', search: true, stype: 'text'},
{label: "GroupNo",name: 'GroupNo',searchoptions: {searchOperators: true,sopt: ['eq', 'cn', 'nc'] }, search: true, multipleSearch: true, multipleGroup:true},
{
label: "Status",
name: 'Status',
cellEdit: true,
edittype: 'select',
editable: true,
editoptions: {
value: getStatusOptions(),
dataEvents: [{
type: 'change',
fn: function (e) {
if (statusid != 0)
{
ChangeStatus(row.Id, row.Name, row.Group, statusid);
}
}
}],
}
}
pager: jQuery('#pager'),
loadonce: true,
viewrecords: true,
gridview: true,
iconSet: "fontAwesome",
emptyrecords: "No records to display",
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "Id"
}
});
$('#grid').jqGrid('filterToolbar', { stringResult: true,searchOnEnter:false, defaultSearch: "cn", multipleSearch: true, searchOperators: true,
search: true, loadFilterDefaults: true });
$('#grid').jqGrid('navGrid', "#pager", {
search: false, // show search button on the toolbar
add: false,
edit: false,
del: false,
refresh: true
});
I have added a diagram for better understanding. Thanks in Advance.

Hide navgrid buttons depending on the number of records in jqgrid

I need to hide the delete button if there are less than 2 records in the grid. This is the js code. For some reason, the flag showDelCurrencyButton is not working out here and is always false.
Any other way to do it?
showDelCurrencyButton = false;
grid.jqGrid({
datatype: 'local',
jsonReader: jqgrid.jsonReader('CurrCd'),
mtype: 'POST',
pager: '#currencyPager',
colNames: ['Abbrev.', 'Name', 'Symbol'],
colModel: [
{
name: 'CurrCd', index: 'CurrCd', width: 200, sortable: false,
editable: true,
edittype: 'select', stype: 'select',
editrules: { required: true },
editoptions: {
dataUrl: getServerPath() + 'Ajax/GetCurrencies',
buildSelect: function (data) {
var currSelector = $("<select id='selCurr' />");
$(currSelector).append($("<option/>").val('').text('---Select Currency---'));
var currs = JSON.parse(data);
$.each(currs, function () {
var text = this.CurName;
var value = this.CurCode;
$(currSelector).append($("<option />").val(value).text(text));
});
return currSelector;
}
}
},
{ name: 'CurrName', index: 'CurrName', width: 200, sortable: false },
{ name: 'CurrSymbol', index: 'CurrSymbol', width: 200, sortable: false },
],
loadtext: 'Loading...',
caption: "Available Currencies",
scroll: true,
hidegrid: false,
height: 116,
width: 650,
rowNum: 1000,
altRows: true,
altclass: 'gridAltRowClass',
onSelectRow: webview.legalentities.billing.onCurrencySelected,
loadComplete: function (data) {
if (data.length > 1) {
showDelCurrencyButton = true;
}
var rowIds = $('#currencyGrid').jqGrid('getDataIDs');
$("#currencyGrid").jqGrid('setSelection', rowIds[0]);
},
rowNum: 1000
});
grid.jqGrid('navGrid', '#currencyPager', {
edit: false,
del: (showDelCurrencyButton == true),
deltitle: 'Delete record',
search: false,
refresh: false
}
});
Your current code uses datatype: 'local' without specifying data parameter with input data. It seems strange. In any way you can hide the Delete button dynamically identifying it by id. It's "del_" + grid[0].id in your case. Thus you can use $("#del_" + grid[0].id).hide(); to hide it. By the way one can use this instead of grid[0] inside of loadComplete.
I'd recommend you to read the old answer for more details and to read the answer, which shows how to disable/enable navigator buttons (like Delete button) instead of hiding.

How to show subgrid in jqgrid in ASP.NET MVC 5?

My jqgrid is working perfectly but now i am implementing the subgrid. It shows the + sign and when i click on it the blank row displayed with loading.... this is the client side code
$(document).ready(function () {
$("#Grid").jqGrid({
url: '/Home/GetDetails',
datatype: 'json',
myType: 'GET',
colNames: ['id','Name', 'Designation', 'Address', 'Salary'],
colModel: [
{ key: false, name: 'Id', index: 'Id', },
{ key: false, name: 'Name', index: 'Name', editable: true },
{ key: false, name: 'Designation', index: 'Designation', editable: true },
{ key: false, name: 'Address', index: 'Address', editable: true },
{ key: false, name: 'Salary', index: 'Salary', editable: true }
],
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
id: '0',
repeatitems: true
},
pager: $('#pager'),
rowNum: 10,
rowList: [10, 20, 30],
width: 600,
viewrecords: true,
multiselect: true,
sortname: 'Id',
sortorder: "desc",
caption: 'Employee Records',
loadonce: true,
gridview: true,
autoencode: true,
subGrid: true,
subGridUrl: '/Home/Subgrid',
subGridModel: [{
name: ['No', 'Item','Quantity'],
width: [55, 55,55]
}
],
}).navGrid('#pager', { edit: true, add: true, del: true },
{
zIndex: 100,
url: '/Home/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText)
{
alert(response.responseText);
}
}
},
{
zIndex: 10,
url: '/Home/Add',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
zIndex: 100,
url: '/Home/Delete',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}
);
});
Subgrid url action method is as below:
public JsonResult Subgrid(String id)
{
Database1Entities db = new Database1Entities();
Product p= new Product {No=1,Item="Juice",Quantity=23};
var jsondata = new { rows=2,
cell = new string[] { p.No.ToString(),
p.Item,p.Quantity.ToString()}.ToArray()
};
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
I am doing this first time. What is the mistake?Thanks in advance
I don't recommend you to use subGridModel. Instead of that it's much more flexible to use Subgrid as Grid. If the user clicks "+" icon (expand subgrid) then jqGrid just inserts empty row under selected with simple structure described in the answer for example. The id of the <div> where some custom "subgrid" information need be displayed will be the first parameter of subGridRowExpanded callback which you need to implement. The second parameter is the rowid of the expending row. By implementing the corresponding callback you can create any custom "subgrid". See the old answer for very simple demo.
So what you need to do is just write the code which creates grid which will be placed in subgrid row. It's only strictly recommended to use idPrefix parameter which used any values which depends from subgriddivid or parent rowid. Additionally you can consider to use autowidth: true option for subgrid, which will make the width of subgrid be exact correspond to the width of the main grid. Of cause to have rowid of the parent row send as id parameter to '/Home/Subgrid' you need use postData: { id: rowid }. See the code from the answer for example which I referenced previously.

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 get number of rows (loadonce:true)

I have a jqgrid with inline client-side search. When the database returns 0 records I am trying to hide the grid and show a custom message. The problem is that now when I use the filters the same thing happens. I need to get the number of rows from the back-end response and none of the below lines work. When the page loads I get 5 and 5, and when I filter I get 0 and 0. How can this be achieved?
.jqGrid('getGridParam', 'records')
.jqGrid('getGridParam', 'reccount')
var contratsAC=$("#ContratsAC");
contratsAC.jqGrid({
url:'<?php echo base_url().'rest/AC_Rest/get_contrats/'?>',
mtype : "post",
datatype: "json",
colNames:['Nr dossier','Type','Nom','Statut','Date creation','Date derniere maj','Commentaires','Auteur'],
colModel:[
{name:'nr_dossier',index:'nr_dossier',search:false, align:"center"},
{name:'type',index:'type',search:false, align:"center"},
{name:'nomClient',index:'nomClient',search:false, align:"center"},
{name:'statut',index:'statut',search: true, sortable: false, width:180, stype:'select',
searchoptions:{ value:statuts}, editable: false},
{name:'date_cre',index:'date_cre',search:false, align:"center"},
{name:'dern_date_maj',index:'dern_date_maj',search:false, align:"center"},
{name:'commentaires',index:'commentaires',search:false, align:"center"},
{name:'auteur',index:'auteur',search:false, align:"center"}
],
rowNum:10,
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "nr_dossier",
userdata: "userdata"
},
width: 960,
height: "100%",
rowList:[10,20,30],
pager: '#pager1',
sortname: 'nr_dossier',
viewrecords: true,
rownumbers: true,
gridview: true,
loadonce: true,
loadComplete: function(data){
alert(contratsAC.jqGrid('getGridParam', 'records'));
alert(contratsAC.jqGrid('getGridParam', 'reccount'));
if (0==contratsAC.jqGrid('getGridParam', 'records'))
{
contratsAC.jqGrid('GridUnload');
$("#contratsACNoDataMessage").html('<span>Aucun enregistrement a afficher.</span>');
}
else $("#ContratsACContainer").show();
},
pagination:true,
}).navGrid('#pager1',
{add: false,
edit:false,
del:false});
contratsAC.jqGrid('filterToolbar',{searchOnEnter:true,stringResult: true});
You may try getting the length of the data array holded by the grid:
$("#ContratsAC").jqGrid('getGridParam', 'data').length;
The below will give you all the rows - initial data source based
contratsAC.jqGrid('getGridParam', 'records');
To get the number of rows on the current page, lets say after filtering, use
contratsAC.jqGrid('getGridParam', 'reccount');
To get all the records across all pages after filtering, use below
loadComplete: function (gridData) {
var isSearchPerformed = $grid.getGridParam("postData")._search;
if (isSearchPerformed) {
$("#spanFilterTotal").text(gridData.records);
}

Resources