Column Chooser icon not visible in pager bar - jqgrid

Does anyone know why is the Column Chooser icon not visible in jqGrid's pager bar? I'm using free-jqGrid v4.9.2
[Html]
<script src="~/Member/Scripts/jquery-ui-v1.10.3.themes/redmond/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script> <!-- JQuery UI -->
<script src="~/Member/Scripts/jqgrid-v4.9.2/i18n/grid.locale-en.js" type="text/javascript"></script> <!-- jqGrid Plugin -->
<script src="~/Member/Scripts/jqgrid-v4.9.2/jquery.jqgrid.min.js" type="text/javascript"></script> <!-- jqGrid Plugin -->
<script src="~/Member/Scripts/jqgrid-v4.9.2/ui.multiselect.min.js" type="text/javascript"></script> <!-- jqGrid Plugin -->
<div id="BatchReportJqgrid" class="GridViewForceCenterInAllWebBrowsers" style="padding-top:2px;padding-bottom:20px;">
<div><table id="BatchReportJqgrid_Spreadsheet"></table></div>
<div id="BatchReportJqgrid_Pager"></div>
</div>
[Javascript]
var _httpHost = window.location.host; //This give you "localhost:<<port #>>" on local machine...
var _dealerAccountId = parmDealerAccountId;
var _dealerUserId = parmDealerUserId;
var _dealerBranchAccountId = parmDealerBranchAccountId;
var _jqgridSpreadsheetId = "BatchReportJqgrid_Spreadsheet";
var _jqgridPagerId = 'BatchReportJqgrid_Pager';
var _jqgridLayoutWidth = 1022;
var _jqgridDialogColumnChooserWidth = 800;
//===============================================================================
//jqGrid - Initialize...
//===============================================================================
$('#' + _jqgridSpreadsheetId).jqGrid({
url: "https://" + _httpHost + "/WebApi/Webpages/Member/BatchFooReport/JqgridSpreadsheetLookup/" + _dealerAccountId + "/" + _dealerUserId + "/" + _dealerBranchAccountId + "",
datatype: "local",
mtype: 'POST',
jsonReader: { repeatitems: false },
postData: {},
colName: ["StockNumber", "VIN", "Year", "Make", "Model", "Trim"],
colModel: [
{ jsonmap: function (o) { return o.cell[0]; }, name: 'Stock Number', index: 'StockNumber', sortable: true, sorttype: 'text', align: 'center' },
{ jsonmap: function (o) { return o.cell[1]; }, name: 'Vin', index: 'Vin', sortable: true, sorttype: 'text', width: 190, align: 'center' },
{ jsonmap: function (o) { return o.cell[2]; }, name: 'Year', index: 'Year', sortable: true, sorttype: 'int', align: 'center' },
{ jsonmap: function (o) { return o.cell[3]; }, name: 'Make', index: 'Make', sortable: true, sorttype: 'text', align: 'center'},
{ jsonmap: function (o) { return o.cell[4]; }, name: 'Model', index: 'Model', sortable: true, sorttype: 'text', align: 'center' },
{ jsonmap: function (o) { return o.cell[5]; }, name: 'Trim', index: 'Trim', sortable: true, sorttype: 'text', align: 'center' },
],
pager: '#' + _jqgridPagerId,
emptyrecords: "No vehicles found that match your search.",
loadtext: "Locating vehicles, please wait...",
recordtext: "Viewing {0} - {1} of {2} vehicles.",
rowNum: 25,
viewrecords: true,
caption: "Batch Foo Report",
rowList: [25, 50, 100],
loadonce: false,
width: _jqgridLayoutWidth,
height: 400,
loadError: function (xhr, status, error) {
alert("Error occured while retrieving data.");
}
});
//==========================================
//===============================================================================
//jqGrid --> Navigation Buttons...
//===============================================================================
//Column Chooser Icon [Columns]...
//#$('#' + _jqgridSpreadsheetId).navButtonAdd('#' + _jqgridPagerId, {
$('#' + _jqgridSpreadsheetId).jqGrid('navButtonAdd', '#' + _jqgridPagerId, {
position: "first",
caption: "Columns",
title: "Columns",
//cursor: "pointer", //This does not work...
onClickButton: function () {
//http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jquery_ui_methods&s[]=column&s[]=chooser...
//$('#' + _jqgridSpreadsheetId).columnChooser({
$(this).columnChooser({
title: "Columns",
caption: "Select Columns",
width: _jqgridDialogColumnChooserWidth,
modal: true,
done: function (perm) {
if (perm) { /* "OK" button are clicked... */
this.jqGrid("remapColumns", perm, true);
}
else { /* "Cancel" button or "x" button are clicked... */ }
}
});
}
});
//===============================================================================

You need to include the call of navGrid which creates navigator bar before you can add any custom button in the navigator bar with respect of navButtonAdd. Even if you don't need any standard buttons you should add the call of navGrid with the corresponding parameters: .jqGrid("navGrid", {add: false, edit: false, del: false, refresh: false, search: false});

Related

jqgrid textbox value not getting update

Problem: unable to get updatable value of textbox in jqgrid.
It just retrieve old value.
example - default value of textbox field inside jqgrid is - "0"
now, if i update its value to "1" and inspect the field then its value does not get updated into HTML and not able to retrieve with jqgrid object through below syntax.
var rowData = $('#gerList').jqGrid('getRowData', rowId);
Below is my jqgrid stuff:
$('#gerList').jqGrid({
ajaxGridOptions: {
error: function () {
$('#gerList')[0].grid.hDiv.loading = false;
alert('An error has occurred.');
}
},
url: '#Url.Action("GetEnrolls", "Attendance")/' + 0,
gridview: true,
autoencode: true,
postData: { adID: rowID },
datatype: 'json',
jsonReader: { root: 'List', page: 'Page', total: 'TotalPages', records: 'TotalCount', repeatitems: false, id: 'syStudentID' },
mtype: 'GET',
colNames: ['GrdID', 'name', 'Minutes', 'comment'],
colModel: [
{ name: 'syID', index: 'syID', hidden: true },
{ name: 'FullName', index: 'FullName', width: 150 },
{
name: 'Min', index: 'Min', width: 75, align: 'left', formatter: function (cellValue, option) {
return '<input type="text" style="width: 40px" name="txtMin" id="txt_' + option.rowId + '" value="' + cellValue + '" />';
}
},
{ name: 'MSG', index: 'MSG', width: 150 }
],
pager: $('#gerListPager'),
sortname: 'syStudentID',
rowNum: 40,
rowList: [40, 80, 120],
width: '525',
height: '100%',
viewrecords: true,
beforeSelectRow: function (rowid, e) {
console.log("final");
var $txt = $(e.target).closest('tr').find('input[type="text"]');
alert($txt);
$txt.attr('value', rowid);
return true; // allow row selection*/
return true;
},
sortorder: 'desc'
}).navGrid('#gerListPager', { edit: false, add: false, del: false, search: false, refresh: false });
Please suggest me what is wrong to use this textbox in jqgrid.
In grid UI, all fields are non editable except textbox field appear to allow edit always.
Thanks
Try to use this:
jQuery("#gerList").saveRow("rowid", false, 'clientArray');

Calling "groupingGroupBy" function cause jqGrid to go into infinite loop. Better suggestion?

When the script used ajax to retrieve saved setting from the database and use it to populate the jqGrid layout setting. That's when it go into infinite loop. Upon some research, it turned out the "groupingGroupBy" function (in jqGrid source code) use "reloadGrid" trigger which doesn't mix well with jqGrid's "beforeRequest" event. I welcome better suggestion. Thanks...
Here's the code...
$('#' + jqgridSpreadsheetId).jqGrid({
url: jqgridWebUrl,
datatype: 'json',
mtype: 'POST',
postData: { WhichJqgridTemplate: jqgridWhichTemplate },
jsonReader: { repeatitems: false },
colNames: ['', 'Id', 'Stock Number', 'VIN', 'Year', 'Make', 'Model', 'Trim', 'Mileage', 'Purchase Price', 'Stock Date', 'Repair Cost', 'Total Cost', 'Days In Inventory', 'Hidden-Inventory-Tracker-Location-Id', 'Inventory Tracker Location', 'Category', 'Links'], //Display Text in Column Header...
colModel: [
//jsonmap --> http://stackoverflow.com/questions/16396229/use-jqgrid-action-formatter...
// --> http://stackoverflow.com/questions/6989608/jqgrid-inline-edit-rows-and-data-not-lining-up...
// --> http://stackoverflow.com/questions/6364473/using-the-jsonmap-property-of-jqgrid-colmodel-with-untyped-json
//action-delete --> http://stackoverflow.com/questions/14732234/how-to-delete-row-in-jqgrid...
//In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
//formatter doc --> "http://www.trirand.com/jqgridwiki/doku.php?id=wiki:predefined_formatter&s[]=cell&s[]=formatter"...
//formatter hyperlink --> Stackoverflow posting was said to use formatter's function declaration instead of formatter's "showlink" followed by "formatoptions"...
// --> (Old Link) - http://stackoverflow.com/questions/5010761/linking-from-a-column-value-in-jqgrid-to-a-new-page-using-get...
// --> (New Link) - http://stackoverflow.com/questions/14529358/jqgrid-need-hyperlink-need-to-capture-value-through-jquery/14537512#14537512...
// --> (New Link) - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter...
// --> Reasons are --> 1) far simpiler to use formatter for reading/writing and 2) much quicker and better performance...
{
jsonmap: function (o) { return ''; }, name: 'actDelete', index: 'actDelete', width: 40, align: 'center', sortable: false, hidedlg: true, formatter: 'actions', //"hidedlg" is use to hide the hidden column in "Column Chooser"...
formatoptions: {
keys: false, editbutton: false,
//http://stackoverflow.com/questions/11897649/cant-refresh-jqgrid-with-loadonce-true... (This show us how to reload jqGrid on edit/delete/add, the easy way, when using loadonce:true)...
delOptions: {
url: jqgridWebUrl,
mtype: 'POST',
onclickSubmit: function (objects, rowid) { return { WhichJqgridTemplate: jqgridWhichTemplate, WebpageVehicleVin: $(this).getCell(rowid, jqgridColumnIdVin), WebpageReason: $('textarea[id=#' + jqgridDialogDeleteTextareaId + ']').val() } },
width: 600,
errorTextFormat: function (response) { return "<div style='text-align:center;padding:3px 0px 3px 0px;'>Unable to delete vehicle from Inventory due to an internal error</div>"; },
beforeShowForm: function ($form) {
//http://stackoverflow.com/questions/10035911/jqgrid-inline-delete-selected-row-selrow-is-incorrect... (showed how to use "rowIdOfDeletedRow" in inline-delete dialog)...
//http://stackoverflow.com/questions/6913618/jqgrid-custom-delete-dialog-message... (showed how to customize the inline-delete's message)...
var rowIdOfDeletedRow = $('#DelData>td:nth-child(1)').text();
//Override delete wording message w/ custom message...
$('td.delmsg', $form[0]).html("<div style='padding-top:5px;text-align:center;'>Delete "" + $(this).getCell(rowIdOfDeletedRow, jqgridColumnIdYear) + " " + $(this).getCell(rowIdOfDeletedRow, jqgridColumnIdMake) + " " + $(this).getCell(rowIdOfDeletedRow, jqgridColumnIdModel) + " " + $(this).getCell(rowIdOfDeletedRow, jqgridColumnIdTrim) + "" vehicle record?</div>");
//Check to see if textarea exists, if not then create one...
if ($('table.DelTable tr:last td textarea[id=#' + jqgridDialogDeleteTextareaId + ']').length == 0) {
$('table.DelTable tr:last').after('<tr><td style="padding-bottom:10px;vertical-align:top;">Reasons: <textarea id="#' + jqgridDialogDeleteTextareaId + '" rows="2" cols="20" style="width:400px;height:60px;" /></td></tr>'); //display:table-cell;vertical-align:top;...
} else { $('textarea[id=#' + jqgridDialogDeleteTextareaId+']').val(''); }
},
resize: false,
}
},
search: false
}, //"hidedlg" is use to hide the hidden column in "Column Chooser"... //"search" is use to hide the field in search dialog...
{ jsonmap: function (o) { return o.cell[0]; }, name: 'Id', index: 'Id', sortable: false, width: 0, align: 'left', hidden: true, hidedlg: true, search: false }, //"search" is use to hide the field in search dialog, "hidedlg" is use to hide the hidden column in "Column Chooser"...
{ jsonmap: function (o) { return o.cell[1]; }, name: 'StockNumber', index: 'StockNumber', sorttype: 'text', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[2]; }, name: 'Vin', index: 'Vin', sorttype: 'text', width: 190, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[3]; }, name: 'Year', index: 'Year', sorttype: 'int', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[4]; }, name: 'Make', index: 'Make', sorttype: 'text', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[5]; }, name: 'Model', index: 'Model', sorttype: 'text', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[6]; }, name: 'Trim', index: 'Trim', sorttype: 'text', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[7]; }, name: 'Mileage', index: 'Mileage', sorttype: 'int', align: 'center', formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '0' } },
{ jsonmap: function (o) { return o.cell[8]; }, name: 'PurchasePrice', index: 'PurchasePrice', sorttype: 'currency', align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
{ jsonmap: function (o) { return o.cell[9]; }, name: 'StockDate', index: 'StockDate', sorttype: 'date', align: 'center', formatter: 'date', formatoptions: { newformat: 'm/d/Y' } }, //"formatter" and "formatoptions" is required for date sorting to works properly...
{ jsonmap: function (o) { return o.cell[10]; }, name: 'RepairCost', index: 'RepairCost', sorttype: 'currency', align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
{ jsonmap: function (o) { return o.cell[11]; }, name: 'TotalCost', index: 'TotalCost', sorttype: 'currency', align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } }, /*summaryType:'sum' is needed for column grouping to work...*/
{ jsonmap: function (o) { return o.cell[12]; }, name: 'DaysInInventory', index: 'DaysInInventory', sorttype: 'int', align: 'center', formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '1' } },
{ jsonmap: function (o) { return o.cell[13]; }, name: 'InventoryTrackerLocationId', sortable: false, width: 0, align: 'left', hidden: true, hidedlg: true, search: false }, //"search" is use to hide the field in search dialog, "hidedlg" is use to hide the hidden column in "Column Chooser"...
{ jsonmap: function (o) { return o.cell[14]; }, name: 'InventoryTrackerLocation', index: 'InventoryTrackerLocation', sorttype: 'text', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ jsonmap: function (o) { return o.cell[15]; }, name: 'Category', index: 'Category', sorttype: 'text', align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
//Links is not present in json data from the website, so we customize it here...
{ jsonmap: function (o) { return ''; }, name: 'Links', index: 'Links', sortable: false, width: 80, align: 'center', hidedlg: true, formatter: function (cellValue, options, rowObject) { return "<span style='text-decoration:underline;cursor:pointer;'>Links</span>" }, search: false } //"search" is use to hide the field in search dialog, "hidedlg" is use to hide the hidden column in "Column Chooser"...
],
pager: '#'+jqgridPagerId,
rowNum: 1000000000, //-1, //10, //06/13/2013 - It is reported that the use of "-1" broke jqGrid when loadonce:true is used. Alternatively, use the max # of rows...
//#rowList: //[5, 10, 20, 50], //Page size dropdown in footer - To show how many rows per page...
rowList: [], //Disable page size dropdown...
pgbuttons: false, //Disable page control like next, back button...
pgtext: null, //Disable pager text line like "Page 0 of 10"...
viewrecords: false, //Disable current view record text like 'View 1-10 of 100'...
caption: 'My Inventory',
width: jqgridLayoutWidth,
shrinkToFit: false, /* This is not reliable */
forceFit: false, /* This is not reliable, plus it it wouldn't work if shrinkToFit is set to false... */
autoWidth: false,
cellLayout: 0, /* This defaulted to 5, so we need to set it to 0 for custom css to works better */
height: 400,
sortable: false, /* Do not allow header-column to shift sideway.. Makes it harder for draggable Group-Header-Column features to work... */ /* Discontinued - This allows both 1) Moving columns sideway to other location fields and 2) for jqGrid Column Chooser Plugin / JQuery Multiselect Plugin to work... */
grouping: true, /* This allows row data to be group into row grouping... */
loadonce: false, /* 06/10/2013 - Set it to false from now on... It is learned that having loadonce:true is not worth the trouble when using search feature, delete feature, etc. so we're better off having client-side do both 1) jqGrid ajaxGridOption and 2) server-side querying to do the heavy work for us... */
//emptyrecords: "No records to display",
ajaxGridOptions: {
beforeSend: function (xhr) { ftnThrobblerAnimationBegin2(); },
complete: function (xhr) { ftnThrobblerAnimationEnd2(); },
error: function (xhr) { alert("An error had occurred, please try again or notify webmaster of this error"); ftnThrobblerAnimationEnd2(); }
},
loadComplete: function () {
JqgridSummarySpreadsheetDisplay();
JqgridGroupedColumnsFormatter();
},
//#loadBeforeSend: function (xhr, settings) { /*Notice: A pre-callback to modify the ajax request object (XMLHttpRequest - xhr) before it is sent. Use this to set custom headers etc. Returning false will cancel the request...*/ },
beforeRequest: function () {
//JqgridColumnChooserSavedBuildsRecordsSetup("INIT", "4444");
$('#' + jqgridSpreadsheetId).jqGrid('groupingGroupBy',
"Make,Model",
{
groupCollapse: true,
groupField: ['name']//,
//08/16/2013 - Appearantly, this "groupText" object is broken and doesn't allow adding "groupText"'s value to recursive grouped column's "groupText" starting with 2nd grouped Columns and after...
// - Use the "jqgridGroupedColumnsFormatter()" function instead under the jqGrid's "loadComplete" attribute...
//groupText: ["<span style='float:left;font-weight:bold;'>{0} - ({1})</span><span style='float:right;font-weight:bold;'> </span>"]
}
);
}
});
Example 1
$('#test').jqGrid({
//.....,
loadComplete: function() {
/* ... */
},
beforeRequest: function() {
/* ... */
},
grouping: true,
groupingView: {
groupField: ["Make","Model"],
groupCollapse: true
}
});
Example 2
$('#test').jqGrid({
//.....,
loadComplete: function() {
/* ... */
},
beforeRequest: function() {
$(this).jqGrid('setGridParam', {
grouping: true,
groupingView: {
groupField: ["Make","Model"],
groupCollapse: true
}
}); //.trigger('reloadGrid');
},
});
Example 3
$('#test').jqGrid({
//.....,
loadComplete: function() {
$(this).jqGrid('setGridParam', {
grouping: true,
groupingView: {
groupField: ["Make","Model"],
groupCollapse: true
}
}); //.trigger('reloadGrid');
},
beforeRequest: function() {
/* ... */
},
});
Example 4
$('#test').jqGrid({
//.....,
loadComplete: function() {
/* ... */
},
beforeRequest: function() {
/* ... */
},
beforeProcessing: function() {
$(this).jqGrid('setGridParam', {
grouping: true,
groupingView: {
groupField: ["Make","Model"],
groupCollapse: true
}
}); //.trigger('reloadGrid');
}
});
Example 5
var blockInfiniteLoopCounter = 0;
$('#test').jqGrid({
//.....,
loadComplete: function() {
/* ... */
},
beforeRequest: function() {
/* ... */
},
beforeProcessing: function() {
if (blockInfiniteLoopCounter == 0) {
blockInfiniteLoopCounter++;
$(this).jqGrid('setGridParam', {
grouping: true,
groupingView: {
groupField: ["Make","Model"],
groupCollapse: true
}
}).trigger('reloadGrid');
}
}
});
Example 6
var $grid = $("#list");
$grid.jqGrid({
datatype: 'json',
url: 'MyInventory-Testcase2.json',
jsonReader: {
repeatitems: false,
id: "Id",
root: function (obj) { return obj; },
page: function () { return 1; },
total: function () { return 1; },
records: function (obj) { return obj.length; }
},
loadonce: true,
colNames: ['Client', 'Date', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'],
colModel: [
{name: 'name', width: 65},
{name: 'invdate', width: 80, align: 'center', sorttype: 'date',
formatter: 'date', formatoptions: {newformat: 'd-M-Y'}, datefmt: 'd-M-Y',
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'] }},
{name: 'amount', width: 75, },
{name: 'tax', width: 52, },
{name: 'total', width: 65, },
{name: 'closed', width: 80, align: 'center', formatter: 'checkbox',
edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'},
stype: 'select',
searchoptions: {
sopt: ['eq', 'ne'],
value: 'true:Yes;false:No'
}},
{name: 'ship_via', width: 100, align: 'center', formatter: 'select',
edittype: 'select',
editoptions: {
value: 'FE:FedEx;TN:TNT;IN:Intim',
defaultValue: 'Intime'
},
stype: 'select',
searchoptions: {
sopt: ['eq', 'ne'],
value: 'FE:FedEx;TN:TNT;IN:Intim'
}},
{name: 'note', width: 100, sortable: false}
],
cmTemplate: {editable: true},
rowNum: 10,
rowList: [5, 10, 20],
pager: '#pager',
gridview: true,
ignoreCase: true,
rownumbers: false, //true,
sortname: 'invdate',
viewrecords: true,
sortorder: 'desc',
height: '100%',
caption: 'Set grouping dynamically',
beforeProcessing: function() {
//beforeRequest: function() {
//loadComplete: function() {
$(this).jqGrid('setGridParam', {
//grouping: true,
groupingView: { groupCollapse: true, groupField: ["name", "amount"] }
//}); //#.trigger('reloadGrid');
});
}
});
$("#dynamicGrouping").change(function () {
var groupingName = $(this).val();
if (groupingName) {
//$grid.jqGrid('groupingGroupBy', groupingName);
$grid.jqGrid('groupingGroupBy', groupingName, {
// groupField : [groupingName],
groupOrder : ['desc'],
groupColumnShow: [false],
//groupDataSorted : true,
groupCollapse: true
});
} else {
$grid.jqGrid('groupingRemove');
}
});
Example 2 have the following error: you use unneeded {...}. The code beforeRequest: function() {$('#test').jqGrid({'setGridParam', {...}});} should be replace with beforeRequest: function() {$(this).jqGrid('setGridParam', {...});}.
I still see no sense in usage of static groupField values. If you hold the data about groping on the server I would see more sense that the server return information about grouping preferences of the user as the part of server response. In the case you can use beforeProcessing callback to analyse the corresponding part of the server response and to set grouping and groupingView option of jqGrid.
UPDATED: One can fix the example 6 by additional calling of groupingSetup method after setting new groupingView options:
beforeProcessing: function () {
var $this = $(this);
$(this).jqGrid("setGridParam", {
grouping: true,
groupingView: {
groupCollapse: true,
groupField: ["name", "amount"]
}
});
$this.jqGrid("groupingSetup");
}
I prepared the corresponding demo. I use in the demo the JSON data in the following format
{
"groupField": ["name", "amount"],
"rows": [
{ "id": "1", "name": "test", ... },
{ "id": "2", "name": "test2", ... },
...
{ "id": "12", "name": "test12", ... }
]
}
and the following beforeProcessing:
beforeProcessing: function (data) {
var $this = $(this);
$(this).jqGrid("setGridParam", {
grouping: ($.isArray(data.groupField) && data.groupField.length > 0) ?
true :
false,
groupingView: {
groupCollapse: true,
groupField: data.groupField //["name", "amount"]
}
});
$this.jqGrid("groupingSetup");
}
So I get the grouping fields (["name", "amount"]) from the server response.

jqSubGrid not loading with data

I do realize many have asked this same question. I have tried all other suggestions and have had no success. I know for sure its something I am overlooking and wanted a second set of eyes to help me. Thanks in advance!!
My problem is that the primary grid loads find. Its the sub grid thats the problem.
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#PositionsGrid").jqGrid({
url: '/Position/GetPositions?projectid=#Model.ID',
datatype: 'json',
mtype: 'POST',
colNames: ['PositionID', 'ID', 'Job', 'Band', 'Start Date', 'End Date','Current Assignee','Terminated Worker','Status'],
colModel: [
{ name: 'PositionID', index: 'PositionID', width: 20, align: 'left', hidden: true, sortable: false, search: false,key:true },
{ name: 'DisplayID', index: 'DisplayID', width: 50, align: 'left' },
{ name: 'JobTitle', index: 'JobTitle', width: 100, align: 'left' },
{ name: 'Band', index: 'Band', width: 50, align: 'left' },
{ name: 'StartDate', index: 'StartDate', width: 50, align: 'left', searchoptions: { sopt: ['cn'], dataInit: datePick} },
{ name: 'EndDate', index: 'EndDate', width: 50, align: 'left', searchoptions: { sopt: ['cn'], dataInit: datePick} },
{ name: 'CurrentWorker', index: 'CurrentWorker', width: 100, align: 'left' },
{ name: 'TerminatedWorker', index: 'TerminatedWorker', width: 100, align: 'left' },
{ name: 'Status', index: 'Action', width: 50, align: 'left', search: false}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'PositionID',
sortorder: "asc",
viewrecords: true,
autowidth: true,
subGrid: true,
subGridRowExpanded: showDetails
});
$('#PositionsGrid').jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
$("#PositionGrid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false, refresh: true });
});
datePick = function (elem) {
$(elem).datepicker({ dateFormat: "mm/dd/yy", onSelect: function (dateText, inst) { $("#grid")[0].triggerToolbar(); } });
};
function showDetails(subgrid_id, row_id) {
showSubGrid_AssignmentsGrid(subgrid_id, row_id, "<br><b>Worker History</b><br><br>", "AssignmentsGrid");
}
function showSubGrid_AssignmentsGrid(subgrid_id, row_id, message, suffix) {
var subgrid_table_id;
subgrid_table_id = subgrid_id + "_t";
if (message) jQuery('#' + subgrid_id).append(message);
if (message) jQuery('#' + subgrid_id).append(message);
jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
jQuery("#" + subgrid_table_id).jqGrid({
url: "Position/GetAssignmentsByPosition?positionid=" + row_id,
datatype: "json",
colNames: ['AssignID', 'JobReqNum', 'WorkerName', 'StartDate', 'EndDate','Status'],
colModel: [
{ name: "AssignID", index: "AssignID", width: 80},
{ name: "JobReqNum", index: "JobReqNum", width: 130 },
{ name: "WorkerName", index: "WorkerName", width: 80, align: "right" },
{ name: "StartDate", index: "StartDate", width: 80, align: "right" },
{ name: "EndDate", index: "EndDate", width: 100, align: "right" },
{ name: "Status", index: "Status", width: 100, align: "right" }
],
height: '100%',
rowNum: 20,
sortname: 'AssignID',
sortorder: "asc"
});
}
</script>
the controller action that loads the subgrid is below
public JsonResult GetAssignmentsByPosition(int positionid)
{
ProjPosition position = uow.PositionRepository.GetPosition(positionid);
var jsonRows = position.ProjPositionAssignments.AsEnumerable()
.Select(a => new
{
cell = new string[] { a.ID.ToString(),
a.JobReqNum == null ? "" :a.JobReqNum,
a.Worker == null ? "" : a.Worker.FullName,
(a.StartDate == null) ? "" : ((DateTime)a.StartDate).ToString("MM/dd/yyyy"),
(a.EndDate == null) ? "" : ((DateTime)a.EndDate).ToString("MM/dd/yyyy"),
(a.Status == null ? "Active" : StatusDictionary.AssignmentStatusDictionary[a.Status])
}
})
.ToArray();
var jsonData = new
{
rows = jsonRows
};
return Json(jsonData);
}
You also need to pass to jqgrid:
page = numberOfPages
records = totalRecords,
I personally use something like:
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from item in pagedQuery
select new
{
cell = new string[] {
item.value1,
item.value2, ....
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);

set radiobutton in loadComplete of grid

$("#addressList").jqGrid({
url: '/Storage/Shipping/GetCustomerAddresses?q=2&Customerid=' + $("#saveCustomerID").val(),
datatype: "Json",
jsonReader: {
root: "Data.rows",
page: "Data.page",
total: "Data.total",
records: "Data.records",
repeatitems: true,
userdata: "userdata",
cell: "cell"
},
colNames: ['', 'Line 1', 'Line 2', 'City', 'State'],
colModel: [
{ name: 'myradio', width: 30, fixed: true, align: 'center', resizable: false, sortable: false,
formatter: function (cellValue, option) {
return '<input type="radio" name="radio_' + option.gid + '" />';
}
},
{ name: 'Line1', index: 'Line1', width: 250 },
{ name: 'Line2', index: 'Line2', width: 250 },
{ name: 'City', index: 'City', width: 210 },
{ name: 'State', index: 'State', width: 75 }
],
page: 1,
rowNum: 50,
rowList: [20, 50, 100],
pager: '#pager',
viewrecords: true,
grouping: false,
caption: "Addresses",
mtype: "POST",
width: "100%",
height: "100%",
loadonce: true,
sortable: false,
beforeSelectRow: function (rowid, e) {
var radio = $(e.target).closest('tr').find('input[type="radio"]');
radio.attr('checked', 'checked');
$("#saveCustomerAddressID").val(rowid.toString());
return true; // allow row selection
},
loadComplete: function () {
var grid_ids = $("#addressList").jqGrid('getDataIDs');
for (var i = 0; i < grid_ids.length; i++) {
if ($("#saveCustomerAddressID").val() == grid_ids[i]) {
{
$("#addressList").jqGrid('setSelection', grid_ids[i], true);
}
}
}
}
//, postdata: { CustomerID: $("#saveCustomerID").val() }
});
The above code sets the selection correctly in loadcomplete. The $("#saveCustomerAddressID").val() is the rowid fro the JSON Data.
The radiobutton is set in the beforeSelectRow. I know the row number and grid column of of the radiobutton to be set, but how do you set the radiobutton?
if you have row number and grid column, then it shouldn't be difficult. get the id(css) of that column where you have your radio button(check developer tools for this). now lets say that radio button is in a column name "Demo"
so the id would look like something like this i suppose
var demo= $("'#'+rowid+'Demo'")//check developer tools for confirmation
demo.attr('checked', 'checked');
$("#saveCustomerAddressID").val(rowid.toString());//continue with you loadComplete code
and for set selection use setSelection method of jqgrid after this continue with your code of loadcomplete

jqgrid apply filter after reload?

Am using jqgrid, loading data once, sorting and filtering locally and doing a refresh after each update/insert/delete. It works fine, besides that if I am using a filter (on top of grid), the filter remains the same after refresh, but the filter is not re-applied on the newly loaded data.
I have tried to call mygrid[0].triggerToolbar() after reloading grid with trigger('reloadGrid'), but there is no effect.
Thanks for any help or pointers :-)
Code below:
var lastsel;
var mygrid;
var currentLang;
//setup grid with columns, properties, events
function initGrid(lang, productData, resellerData, resellerSearchData) {
mygrid = jQuery("#list2").jqGrid({
//data loading settings
url: '/public/Gadgets/LinkGadget/ProductLinks/' + lang,
editurl: "/public/Gadgets/LinkGadget/Edit/" + lang,
datatype: "json",
mtype: 'POST',
jsonReader: {
root: "rows",
cell: "",
page: "currpage",
//total: "totalrecords",
repeatitems: false
},
loadError: function (xhr, status, error) { alert(status + " " + error); },
//column definitions
colNames: ['Id', 'ProductId', 'Reseller Name', 'Link', 'Link Status'],
colModel: [
{ name: 'Id', index: 'Id', width: 40, sortable: false, resizable: true, editable: false, search: false, key: true, editrules: { edithidden: true }, hidden: true },
{ name: 'ProductId', index: 'ProductId', width: 190, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: productData }, editrules: { required: true} },
{ name: 'ResellerName', indexme: 'ResellerName', width: 190, sortable: false, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: resellerData }, editrules: { required: true }, searchoptions: { sopt: ['eq'], value: resellerSearchData} },
{ name: 'Link', index: 'Link', width: 320, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, edittype: "textarea", editoptions: { rows: "3", cols: "50" }, editrules: { required: true }, searchoptions: { sopt: ['cn']} },
{ name: 'LinkStatus', index: 'LinkStatus', width: 100, sortable: false, resizable: true, editable: false, search: false, formatter: linkStatusFormatter}],
//grid settings
//rowList: [10, 25, 50],
rowNum: 20,
pager: '#pager2',
sortname: 'ProductId',
sortorder: 'asc',
height: '100%',
viewrecords: true,
gridview: true,
loadonce: true,
viewsortcols: [false, 'vertical', true],
caption: " Product links ",
//grid events
onSelectRow: function (id) {
if (id && id !== lastsel) {
if (lastsel == "newid") {
jQuery('#list2').jqGrid('delRowData', lastsel, true);
}
else {
jQuery('#list2').jqGrid('restoreRow', lastsel);
}
jQuery('#list2').jqGrid('editRow', id, true, null, afterSave); //reload on success
lastsel = id;
}
},
gridComplete: function () {
//$("#list2").setGridParam({ datatype: 'local', page: 1 });
$("#pager2 .ui-pg-selbox").val(25); //changing the selected values triggers paging to work for some reason
}
});
//page settings
jQuery("#list2").jqGrid('navGrid', '#pager2',
{ del: false, refresh: false, search: false, add: false, edit: false }
);
//refresh grid button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Refresh", title: "Refresh grid", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
reload();
}
});
//clear search button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Clear search", title: "Clear Search", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
mygrid[0].clearToolbar();
}
});
//add row button
jQuery("#list2").jqGrid('navButtonAdd', '#pager2', { caption: "New", buttonicon: 'ui-icon-circle-plus',
onClickButton: function (id) {
var datarow = { Id: "newid", ProductId: "", ResellerName: "", Link: "" };
jQuery('#list2').jqGrid('restoreRow', lastsel); //if editing other row, cancel this
lastsel = "newid"; // id;
var su = jQuery("#list2").addRowData(lastsel, datarow, "first");
if (su) {
jQuery('#list2').jqGrid('editRow', lastsel, true, null, afterSave); //reload on success
jQuery("#list2").setSelection(lastsel, true);
}
},
title: "New row"
});
//delete row button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Delete", title: "Delete row", buttonicon: 'ui-icon-circle-minus',
onClickButton: function () {
if (lastsel) {
if (confirm('Are you sure you want to delete this row?')) {
var url = '/public/Gadgets/LinkGadget/Edit/' + currentLang;
var data = { oper: 'del', id: lastsel };
$.post(url, data, function (data, textStatus, XMLHttpRequest) {
reload();
});
lastsel = null;
}
else {
jQuery("#list2").resetSelection();
}
}
else {
alert("No row selected to delete.");
}
}
});
jQuery("#list2").jqGrid('filterToolbar');
}
//Used by initGrid - formats link status column by adding button
function linkStatusFormatter(cellvalue, options, rowObject) {
if (rowObject.Id != "newrow")
return "<input style='height:22px;width:90px;' type='button' " + "value='Check link' " + "onclick=\"CheckLink(this, '" + rowObject.Id + "'); \" />";
else
return "";
}
//Used by initGrid - reloads grid
function reload() {
//jqgrid setting "loadonce: true" will reset datatype from json to local after grid has loaded. "datatype: local"
// does not allow server reloads, therefore datatype is reset before trying to reload grid
$("#list2").setGridParam({ datatype: 'json' }).trigger('reloadGrid');
//mygrid[0].clearToolbar();
lastsel = null;
//Comments: after reload, toolbar filter is not applied to refreshed data. Tried row below without luck
//mygrid[0].triggerToolbar();
}
//after successful save, reload grid and deselect row
function afterSave() {
reload();
}
Your data is not getting re binded to the grid after save/update delete

Resources