jqGrid local filtering causing rowid to be set to null - jqgrid

Based on jqGrid Filtering Records solution, i implemented the filtering on local.
However i am unable to set the first row as selected.Looks the row ids have been set to null. I am not sure why this would happening.
Code is as below
$("#showMatchingRecords").click(function(e) {
e.preventDefault();
var grid = $("#WorkList"), filter,searchfiler;
searchfiler = "700677";
grid[0].p.search = true;
filter = { groupOp:'OR', rules: [] };
filter.rules.push({field:"Id",op:"eq",data:searchfiler});
$.extend(grid[0].p.postData, {filters:JSON.stringify(filter)});
grid.trigger("reloadGrid", [{page:1}]);
});
$("#showAllRecords").click(function(e) {
e.preventDefault();
var grid = $("#WorkList");
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
grid.trigger("reloadGrid", [{page:1}]);
});
Here is my gridComplete method, I have tried the same with loadComplete as well
gridComplete : function() {
$("tr.jqgrow:odd").css("background", "#DDDDDC");
var grid = $("#WorkList");
var ids = grid.getDataIDs();
console.log('before ids....', ids);
for (var i = 0; i < ids.length; i++) {
grid.setRowData(ids[i], false, { height: 35 });
}
Here are my grid options:
caption: 'Records List',
width: 1000,
height: 200,
pager: $("#WorkListPager"),
rowNum: 50,
sortname: 'Name',
loadonce: true,
sortorder: "asc",
cellEdit: false,
viewrecords: true,
imgpath: '/Content/Themes/Redmond/Images',
autowidth: false,
onSelectRow: function (rowid, status, e) {
/* function */
}

To select the first row on every reload of the grid you need do the following
loadComplete: function () {
var $self = $(this);
if (this.rows.length > 1) { // test that grid is not empty
$self.jqGrid("setSelection", this.rows[1].id);
}
}
I strictly recommend you additionally to include gridview: true option (see the answer for details) in the grid and to replace gridComplete to the usage of rowattr (see the answer).

Related

What causes jqgrid events to fire multiple times?

Our jqgrid is configured in an initgrid function that is called as the last statement of a ready handler. For some reason, the gridcomplete function is getting called multiple times. With the code below, it gets called twice, but it had been getting called 3 times. Twice is bad enough. After stepping through it multiple times, I don't see what is triggering the second execution of the gridComplete function.
When I hit the debugger at the start of gridComplete, the call stack is virtually identical each time, the only difference being a call to 'L' in the jqgrid:
Anyone have an idea why this is occurring? We are using the free version 4.13, in an ASP.net MVC application.
$(function(){
....
initGrid();
}
function initGrid(){
$gridEl.jqGrid({
xhrFields: {
cors: false
},
url: "/IAConsult/GetWorkFlowIARequests",
postData: {
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
datatype: "json",
crossDomain: true,
loadonce: true,
mtype: 'GET',
sortable: true,
viewrecords: true,
pager: '#workFlowIAGridPager',
multiselect: true,
rowNum: 50,
autowidth: true,
colModel: [...],
beforeSelectRow: function (rowid, e) {
var $myGrid = $(this),
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = $myGrid.jqGrid('getGridParam', 'colModel');
return (cm[i].name === 'cb');
},
jsonReader: {
repeatitems: true,
root: "IAConsultWorkflowRequestsList"
},
beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
return {
gridData: gridData
};
},
serializeCellData: function (postdata) {
return JSON.stringify(postdata);
},
gridComplete: function () {
console.log('grid complete');
let rowIDs = $gridEl.getDataIDs();
let inCompleteFlag = false;
let dataToFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
let $grid = $gridEl, postfilt = "";
let localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
let columnNames = columns.split(',');
$('.moreItems').on('click', function () {
$.modalAlert({
body: $(this).data('allitems'),
buttons: {
dismiss: {
caption: 'Close'
}
},
title: 'Design Participants'
});
});
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
let getUniqueNames = function (columnName) {
... };
let buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
};
let setSearchSelect = function (columnName) {
...
};
function getSortOptionsByColName(colName) {
...
}
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
let grid = $gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
});
//grid.trigger("reloadGrid");
//Ending Filter code
for (i = 0; i < columnNames.length; i++) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNames[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNames[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
debugger;
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
I personally almost never use gridComplete callback. It exists in free jqGrid mostly for backwards compatibility. I'd recommend you to read the old answer, which describes differences between gridComplete and loadComplete.
Some additional advices: it's dangerous to register events inside of callbacks (see $('.moreItems').on('click', ...). If you need to make some actions on click inside of grid then I'd recommend you to use beforeSelectRow. Many events, inclusive click event supports event bubbling and non-handled click inside of grid will be bubbled to the parent <table> element. You use already beforeSelectRow callback and e.target gives you full information about clicked element.
I recommend you additionally don't use setGridParam method, which can decrease performance. setGridParam method make by default deep copy of all internals parameters, inclusive arrays like data, which can be large. In the way, changing one small parameter with respect of setGridParam can be expensive. If you need to modify a parameter of jqGrid then you can use getGridParam without additional parameters to get reference to internal object, which contains all jqGrid parameters. After that you can access to read or modify parameters of jqGrid using the parameter object. See the answer for example for small code example.
Also adding the property
loadonce: true
might help.

jqGrid getGridParam('colModel') missing information

I would like capture the colModel for my jqGrid when the page unloads and store it in session so the next time the user comes to the page it can be loaded automatically. But, the information returned by ('#contract_grid').getGridParam('colModel') is missing part or all of the information in searchoptions for the grid columns.
Any idea why this is or how to capture the full colModel? The grid works great on the initial load but without the other searchoptions params, the filter bar features/menus don't work when I refresh the page from the colModel stored in session.
Create the default colModel for the grid
var defaultColModel =
[
{name:'REQUESTID'
,index:'requestID'
,label:'Request ID'
,search:true
,stype:'text'
,width:75
,key:true
,hidden:false
},
{name:'REQUESTEDDATE'
,index:'requestedDate'
,label:'Request Date'
,sorttype:"date"
,search:true
,width:50
,searchoptions:{
dataInit:function(el){jQuery(el).daterangepicker(
{
arrows:false
, dateFormat:'yy-mm-dd'
, onClose: function(dateText, inst){ jQuery("#contract_grid")[0].triggerToolbar();}
, onOpen: function() {
jQuery('div.ui-daterangepickercontain').css({"top": jQuery('#mouseY').val() + 'px', "left": jQuery('#mouseX').val() + 'px' });
}
});
}
}
,hidden:false
},
{name:'BUSINESSOWNERPERSONID'
,index:'businessOwnerPersonID'
,label:'Business Owner'
,search:true
,stype:'select'
,width:100
,hidden:false
,searchoptions: {
dataUrl: 'cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID',
buildSelect: function(resp) {
var sel= '<select><option value=""></option><option value="7583,1636">My Reports</option>';
var obj = $.parseJSON(resp);
$.each(obj, function() {
sel += '<option value="'+this['lk_value']+ '">'+this['lk_option'] + "</option>"; // label and value are returned from Java layer
});
sel += '</select>';
return sel;
},
dataEvents: [{
type: 'change',
fn: function(e) {
alert(this.value)
}
}]
}
}
];
When user navigates away from page, save the grid to session so it loads when they come back
$(window).on('beforeunload', function(){
takeSnapshot();
});
function takeSnapshot(){
var gridInfo = new Object();
gridInfo.colModel = jQuery('#contract_grid').getGridParam('colModel');
gridInfo.postData = jQuery('#contract_grid').jqGrid('getGridParam', 'postData');
var snapshotData = JSON.stringify(gridInfo);
$.ajax({
url: "actions/act_filter.cfc?method=takeSnapshot",
type: "POST",
async: false,
data: {gridName:'contract_grid'
,gridParamName:'contractGridParams'
,filterData:snapshotData
}
});
}
Create grid variable
var myGrid = jQuery("#contract_grid").jqGrid({
url: 'cfc/com_ajxRequestNew.cfc?method=getReqJSON&returnformat=json',
datatype: 'json',
postData: {filters: myFilters},
mtype: 'POST',
search: true,
colModel: defaultColModel,
altRows: true,
emptyrecords: 'NO CONTRACTS FOUND',
height: 400,
width: 1200,
sortname: lastSortName,
sortorder: lastSortOrder,
page: lastPage,
pager: jQuery('#report_pager'),
rowNum: lastRowNum,
rowList: [10,20,50,100],
viewrecords: true,
clearSearch: false,
caption: "Contracts Dashboard",
sortable: true,
shrinkToFit: false,
ajaxSelectOptions: {type: "GET"},
gridComplete: function() {
//set the selected toolbar filter values
var myFields = JSON.parse(myFilters);
//set fields in form at top. filter contains index value so get corresponding name value because its used in the column label #gs
if ( myFields['rules'].length > 0 ) {
for (var i=0; i < myFields['rules'].length; i++ ) {
$.each(defaultColModel, function(j) {
if(this.index == myFields['rules'][i]['field'] ) {
thisFieldName = this.name;
jQuery('#gs_' + thisFieldName).val( myFields['rules'][i]['data'] );
}
})
}
}
}
});
jQuery("#contract_grid").navGrid('#report_pager',{
edit:false,
add:false,
del:false,
search:false,
refresh:false
}).navButtonAdd("#report_pager",{ caption:"Clear",title:"Clear Filters", buttonicon :'ui-icon-trash',
onClickButton: function() {
jQuery.ajax({
url: "/assets/js/ajx_clearFilter.cfm?showHeader=0",
async: false,
type: "POST",
data: ({variableName:'session.contractGridParams'})
});
myGrid[0].clearToolbar();
}
}).navButtonAdd("#report_pager",{ caption:"Restore",title:"Restore Default Grid Columns and Filters", buttonicon :'ui-icon-refresh',
onClickButton: function() {
window.location = '?page=dsp_requestListingNew&clearSession=1';
}
}).navButtonAdd("#report_pager",{
caption: "Export",
title: "Export to Excel",
buttonicon :'ui-icon-document',
onClickButton: function(e){
jQuery("#contract_grid").jqGrid('excelExport',{url:'includes/act_requestListingExport.cfm'});
}
}).navButtonAdd("#report_pager",{
caption: "Columns",
buttonicon: "ui-icon-calculator",
title: "Select and Reorder Columns",
jqModal: true,
onClickButton: function(e){
$('#contract_grid').jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
}
}).navButtonAdd("#report_pager",{
caption: "Save",
title: "Save Snapshot",
buttonicon :'ui-icon-disk',
onClickButton: function(e){
takeSnapshot(0);
$('#fltrFrmLink').click();
}
});
jQuery("#contract_grid").jqGrid('filterToolbar', {
stringResult : true
, searchOnEnter : true
, autoSearch : true
, beforeClear : function() {
//set sortnames
var sn = jQuery("#contract_grid").jqGrid('getGridParam','sortname');
//set sort orders
var so = jQuery("#contract_grid").jqGrid('getGridParam','sortorder');
so = "desc";
//set grid params
jQuery("#contract_grid").jqGrid('setGridParam',{ sortorder:so, sortname:sn });
}
});
colModel returned by ('#contract_grid').getGridParam('colModel') on unload. searchoptions is missing everything for REQUESTEDDATE. Part of dataEvents and all of buildSelect are missing for BUSINESSOWNERPERSONID.
[{"name":"REQUESTID",
"index":"requestID",
"label":"Request ID",
"search":true,
"stype":"text",
"width":75,
"key":true,
"hidden":false,
"title":true,"lso":"",
"widthOrg":75,"resizable":true,"sortable":true},
{"name":"REQUESTEDDATE",
"index":"requestedDate",
"label":"Request Date",
"sorttype":"date",
"search":true,
"width":50,
"searchoptions:{},
"hidden":false,
"title":true,
"lso":"",
"widthOrg":50,
"resizable":true,
"sortable":true,"stype":"text"},
{"name":"BUSINESSOWNERPERSONID",
"index":"businessOwnerPersonID",
"label":"Business Owner",
"search":true,
"stype":"select",
"width":100,"hidden":false,
"searchoptions":{"dataUrl":"cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID",
"dataEvents":[{"type":"change"}]},
"title":true,
"lso":"",
"widthOrg":100,
"resizable":true,
"sortable":true}]
JSON don't support serialization of functions. So the functions from searchoptions.dataInit, searchoptions.buildSelect and all other which you use in colModel will be discarded after you use JSON.stringify.
It's important to know which version of jqGrid/free jqGrid or Guriddo jqGrid JS you use. Starting with jqGrid 4.7 one can define template in colModel with string value (see the pull request). In the way you will have the main information in colModel which can be serialized using JSON.stringify.

jqGrid: Form edits saved to row but all changes lost when paging back or forth

I am using form editing for local data. I am able to edit the values in the form and set the values back to the row (using setRowData). But when I page back or forth, the changes are lost.
How do I save the changes to the row and the underlying source in the grid? Later I have to iterate the rows, validate all the errors are corrected (using the edit form), and post it to server.
Code:
var gridId = 'mygrid';
var pagerId = 'mygridpager';
var grid = $('#mygrid');
var pager = $('#mygridpager');
grid.jqGrid({
caption: caption,
colModel: getColModel(),
recreateForm: true,
hidegrid: true,
sortorder: 'desc',
viewrecords: true,
multiselect: true,
rownumbers: true,
autowidth: true,
height: '100%',
scrollOffset: 0,
datatype: 'local',
data: dataAsArray,
localReader: {
repeatitems: true,
cell: '',
id: 2
},
pager: '#' + pagerId,
pgbuttons: true,
rowNum: 5,
rowList: [2, 5, 7, 10, 250, 500]
});
grid.jqGrid('navGrid',
'#' + pagerId,
{
add: false,
del: false,
search: false,
edit: true,
edittext: 'Fix Error',
editicon: 'ui-icon-tag',
editurl: 'clientArray',
refreshtext: 'Refresh',
recreateForm: true
},
{
// edit options
editCaption: 'Fix Error',
editurl: 'clientArray',
recreateForm: true,
beforeShowForm: function(form) {
/* Custom style for elements. make it disabled etc */
},
onclickSubmit: function(options, postdata) {
var idName= $(this).jqGrid('getGridParam').prmNames.id;
// [UPDATED]
if (postdata[idName] === undefined) {
var idInPostdata = this.id + "_id";
postdata[idName] = postdata[idInPostdata];
postdata['row'] = postdata[idInPostdata];
}
$('#mygrid').jqGrid('setRowData', postdata.row, postdata);
if (options.closeAfterEdit) {
$.jgrid.hideModal('#editmod' + gridId, {
gb: '#gbox_' + gridId,
jqm: options.jqModal,
onClose: options.onClose
});
}
options.processing = true;
return {};
}
},
{}, // add options
{}, // del options
{} //search options
).trigger('reloadGrid');
Your help is appreciated.
Thanks
I suppose that the reason of your problem is usage of array format (repeatitems: true in localReader) of input data. I suppose that you need build array from postdata and use it as the parameter of setRowData instead of postdata.
If the advice will don't help you that you should post more full code of the grid with the test data. The code like colModel: getColModel(), don't really help. In other words you should post enough information to reproduce the problem. The best would be a working demo in http://jsfiddle.net/. If you prepare such demo please use jquery.jqGrid.src.js instead of jquery.jqGrid.min.js.
UPDATED: The problem in your code is the usage arrays is items if input data (you use repeatitems: true in localReader). The current implementation of setRowData don't support (works incorrect) in the case. For example if you have such data initially
and start editing of the third row you will have something like the following
after usage the like $('#mygrid').jqGrid('setRowData', postdata.row, postdata); inside of onclickSubmit. So the internal data will be incorrectly modified.
To fix the problem I suggest overwrite the current implementation of setRowData by including the following code
$.jgrid.extend({
setRowData : function(rowid, data, cssp) {
var nm, success=true, title;
this.each(function(){
if(!this.grid) {return false;}
var t = this, vl, ind, cp = typeof cssp, lcdata=t.p.datatype === "local" && t.p.localReader.repeatitems === true? [] : {}, iLocal=0;
ind = $(this).jqGrid('getGridRowById', rowid);
if(!ind) { return false; }
if( data ) {
try {
$(this.p.colModel).each(function(i){
nm = this.name;
var dval =$.jgrid.getAccessor(data,nm);
if( dval !== undefined) {
vl = this.formatter && typeof this.formatter === 'string' && this.formatter === 'date' ? $.unformat.date.call(t,dval,this) : dval;
if (t.p.datatype === "local" && t.p.localReader.repeatitems === true) {
lcdata[iLocal] = vl;
} else {
lcdata[nm] = vl;
}
vl = t.formatter( rowid, dval, i, data, 'edit');
title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {};
if(t.p.treeGrid===true && nm === t.p.ExpandColumn) {
$("td[role='gridcell']:eq("+i+") > span:first",ind).html(vl).attr(title);
} else {
$("td[role='gridcell']:eq("+i+")",ind).html(vl).attr(title);
}
}
if (nm !== "cb" && nm !== "subgrid" && nm !== "rn") {
iLocal++;
}
});
if(t.p.datatype === 'local') {
var id = $.jgrid.stripPref(t.p.idPrefix, rowid),
pos = t.p._index[id], key;
if(t.p.treeGrid) {
for(key in t.p.treeReader){
if(t.p.treeReader.hasOwnProperty(key)) {
delete lcdata[t.p.treeReader[key]];
}
}
}
if(pos !== undefined) {
t.p.data[pos] = $.extend(true, t.p.data[pos], lcdata);
}
lcdata = null;
}
} catch (e) {
success = false;
}
}
if(success) {
if(cp === 'string') {$(ind).addClass(cssp);} else if(cssp !== null && cp === 'object') {$(ind).css(cssp);}
$(t).triggerHandler("jqGridAfterGridComplete");
}
});
return success;
}
});
I will post my suggestion later to trirand. So one can hopes that the problem will be fixed in the next version of jqGrid.

Reloading of data in JQgrid on button click is not working

I have successfully loaded data in my grid. I have enabled cell edit and on clicking a cell it will be in edit mode and multiple cells can be edited. The edited data will be stored later on clicking a custom update button. On clicking another custom button a new row will be added to the grid and that also will be saved on clicking the update button previously mentioned.
Now the problem is when I am trying to reset the edited values(ie. the edited cell values and the new row added before saving) using "reload" functionality nothing happens in the grid.It remains as same with the edited values and the empty new row...
My code is here
$scope.init = function() {
var grid = $("#list");
var lastSel, dataSel, dataLen;
var colD, colM, colN, userdata;
jQuery.ajax({
async: false,
type: "GET",
url:"getData.htm",
data: "",
dataType: "json",
success: function(result){
colD = result.colData,
colM = result.colModel,
colN = result.colNames,
userdata = colD.userdata;
jQuery("#list").jqGrid({
datatype: 'local',
data: colD.rootVar,
colModel:colM,
sortorder: 'asc',
viewrecords: true,
resizable: true,
gridview: true,
altRows: true,
cellEdit:true,
footerrow: true,
scrollbar: true,
overflow: scroll,
scrollrows: true,
loadonce:true,
autowidth: true,
shrinkToFit: false,
editurl: 'clientArray',
cellsubmit: 'clientArray',
afterEditCell: function (id,name,val,iRow,iCol){
},
afterSaveCell : function(rowid,name,val,iRow,iCol) {
var updtd = jQuery("#list").jqGrid('getCol', name, false, 'sum');
var objs = [];
objs[name] = updtd;
jQuery("#list").jqGrid('footerData','set',objs);
},
loadComplete: function(data){
jQuery("#list").jqGrid('footerData','set',{'Employer':'Max Guest Count:'});
var colnames = jQuery("#list").jqGrid ('getGridParam', 'colModel');
dataLen = colnames.length;
dataSel = colnames[3]['name'];
for (var i = 3; i < colnames.length; i++){
var tot = jQuery("#list").jqGrid('getCol', colnames[i]['name'], false, 'sum');
var ob = [];
ob[colnames[i]['name']] = tot;
jQuery("#list").jqGrid('footerData','set',ob);
}
var ids = grid.getDataIDs();
for (var i = 0; i < ids.length; i++) {
grid.setRowData ( ids[i], false, {height: 25} );
}
jQuery ("table.ui-jqgrid-htable", jQuery("#list")).css ("height", 30);
},
gridComplete: function () {
jQuery("#list").jqGrid('setColProp','id',{width:20});
jQuery("#list").jqGrid('setColProp','Employer',{width:80});
jQuery("#list").jqGrid('setColProp','Sponsor',{width:80});
var tabs = $("#tabs");
var width = tabs.width();
jQuery("#list").jqGrid('setGridWidth', width - 80, true);
jQuery("#list").jqGrid('setGridHeight', 270);
},
});
},
});
jQuery("#list").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'id', numberOfColumns: 1, titleText: ''},
{startColumnName: 'Employer', numberOfColumns: 2, titleText: ''},
{startColumnName: dataSel, numberOfColumns: dataLen, titleText: '<Strong><font color="white">Here Comes</font></Strong>'}
]
});
$("#addtn").click(function(){
var newRowData = {"Id":"","Employer":"","Sponsor":"",col1:"",col2:"",col3:"",col4:"",col5:"",col6:"",col7:"",col8:"",col9:"",col10:"",col11:"",col12:"",col13:"",col14:"",col15:"",col16:"",col17:"",col18:"",col19:"",col20:""};
jQuery("#list").addRowData(0,newRowData,"first",1);
jQuery("#list").editRow(0,true);
});
$("#rstbtn").click(function(){
$("#list").jqGrid('setGridParam',{datatype:'json', page:1, current:true}).trigger('reloadGrid')
});
};
I will really appreciate if someone can advice on this..
Probably because of this line: loadonce:true, in jqgrid definition. Set it as false and try again.
And for reloading, try this code:
$( '#list' ).trigger( 'reloadGrid', [{ page: 1}] );
Below code worked for me, to load updated data from the array.
$('#grid').jqGrid('clearGridData');
$("#grid").jqGrid('setGridParam',{data: DataArr, datatype:'local'}).trigger('reloadGrid');

JQGrid InlineNav delete option

I am using "inlineNav" for my jqgrid. It has all the required features for Addition, edit, Cancel add. but cant find anything for deletion. I tried using "navGrid" delete but then that gives error "error Status: 'Not Found'. Error code: 404".
So can something be done about it?
#Oleg I am counting for your help!!
Following your suggestion I created this code but it is not working!! Can you tell me what went wrong:
var jsonData;
var jsonData1;
var dropdownVal;
function createDataStructure()
{
var mData;
if (document.forms[0].gridData.value == "" )
"";
else
mData = document.forms[0].gridData.value
jsonData = {
"rows": [ mData ]
};
dropdownVal = "12345:Party;12346:Miscellaneous;12347:Conveyance;12348:Staff Welfare";
}
function callGrid()
{
createDataStructure();
"use strict";
var webForm = document.forms[0],
mydata = "",
grid = $("#View1"),
lastSel,
getColumnIndex = function (columnName) {
var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if ((cm[i].index || cm[i].name) === columnName) {
return i; // return the colModel index
}
}
return -1;
},
onclickSubmitLocal = function (options, postdata) {
var $this = $(this),
grid_p = this.p,
idname = grid_p.prmNames.id,
grid_id = this.id,
id_in_postdata = grid_id + "_id",
rowid = postdata[id_in_postdata],
addMode = rowid === "_empty",
oldValueOfSortColumn,
new_id,
tr_par_id,
colModel = grid_p.colModel,
cmName,
iCol,
cm;
// postdata has row id property with another name. we fix it:
if (addMode) {
// generate new id
new_id = $.jgrid.randId();
while ($("#" + new_id).length !== 0) {
new_id = $.jgrid.randId();
}
postdata[idname] = String(new_id);
} else if (typeof postdata[idname] === "undefined") {
// set id property only if the property not exist
postdata[idname] = rowid;
}
delete postdata[id_in_postdata];
// prepare postdata for tree grid
if (grid_p.treeGrid === true) {
if (addMode) {
tr_par_id = grid_p.treeGridModel === 'adjacency' ? grid_p.treeReader.parent_id_field : 'parent_id';
postdata[tr_par_id] = grid_p.selrow;
}
$.each(grid_p.treeReader, function (i) {
if (postdata.hasOwnProperty(this)) {
delete postdata[this];
}
});
}
// decode data if there encoded with autoencode
if (grid_p.autoencode) {
$.each(postdata, function (n, v) {
postdata[n] = $.jgrid.htmlDecode(v); // TODO: some columns could be skipped
});
}
// save old value from the sorted column
oldValueOfSortColumn = grid_p.sortname === "" ? undefined : grid.jqGrid('getCell', rowid, grid_p.sortname);
// save the data in the grid
if (grid_p.treeGrid === true) {
if (addMode) {
$this.jqGrid("addChildNode", new_id, grid_p.selrow, postdata);
} else {
$this.jqGrid("setTreeRow", rowid, postdata);
}
} else {
if (addMode) {
// we need unformat all date fields before calling of addRowData
for (cmName in postdata) {
if (postdata.hasOwnProperty(cmName)) {
iCol = getColumnIndex.call(this, cmName);
if (iCol >= 0) {
cm = colModel[iCol];
if (cm && cm.formatter === "date") {
postdata[cmName] = $.unformat.date.call(this, postdata[cmName], cm);
}
}
}
}
$this.jqGrid("addRowData", new_id, postdata, options.addedrow);
} else {
$this.jqGrid("setRowData", rowid, postdata);
}
}
if ((addMode && options.closeAfterAdd) || (!addMode && options.closeAfterEdit)) {
// close the edit/add dialog
$.jgrid.hideModal("#editmod" + grid_id, {
gb: "#gbox_" + grid_id,
jqm: options.jqModal,
onClose: options.onClose
});
}
if (postdata[grid_p.sortname] !== oldValueOfSortColumn) {
// if the data are changed in the column by which are currently sorted
// we need resort the grid
setTimeout(function () {
$this.trigger("reloadGrid", [{current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
options.processing = true;
return {};
},
editSettings = {
//recreateForm: true,
jqModal: false,
reloadAfterSubmit: false,
closeOnEscape: true,
savekey: [true, 13],
closeAfterEdit: true,
onclickSubmit: onclickSubmitLocal
},
addSettings = {
//recreateForm: true,
jqModal: false,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true,
onclickSubmit: onclickSubmitLocal
},
delSettings = {
// because I use "local" data I don't want to send the changes to the server
// so I use "processing:true" setting and delete the row manually in onclickSubmit
onclickSubmit: function (options, rowid) {
var $this = $(this), grid_id = $.jgrid.jqID(this.id), grid_p = this.p,
newPage = grid_p.page;
// reset the value of processing option to true to
// skip the ajax request to 'clientArray'.
options.processing = true;
// delete the row
if (grid_p.treeGrid) {
$this.jqGrid("delTreeNode", rowid);
} else {
$this.jqGrid("delRowData", rowid);
}
$.jgrid.hideModal("#delmod" + grid_id, {
gb: "#gbox_" + grid_id,
jqm: options.jqModal,
onClose: options.onClose
});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
$this.trigger("reloadGrid", [{page: newPage}]);
}
return true;
},
processing: true
},
initDateEdit = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
//autoSize: true,
showOn: 'button',
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 100);
},
initDateSearch = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
//autoSize: true,
//showOn: 'button', // it dosn't work in searching dialog
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 100);
};
grid.jqGrid({
datatype: "local",
data: jsonData.rows,
localReader: {
repeatitems: false,
id: "1"
},
colNames: ['Date','Expense Head','Amount', 'Reason','Remarks'],
colModel: [
{name:'sdate', index:'sdate', width:200, sorttype: 'date',
formatter: 'date', formatoptions: {newformat: 'd-M-Y'},
editable: true, datefmt: 'd-M-Y',
editoptions: {dataInit: initDateEdit, size: 14},
searchoptions: {dataInit: initDateSearch},
editrules: {required: true} },
{name:'expHead', index:'expHead', width:150, editable:true, sortable:true, edittype:"select", editoptions:{value:dropdownVal}, editrules: {required: true} },
{name:'expAmt', index:'expAmt', width:100, editable:true, summaryType:'sum', editrules: {required: true} },
{name:'expReason', index:'expReason', width:200, editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}, editrules: {required: true} },
{name:'expRemark', index:'expRemark', width:200,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"} }
],
loadtext: "Loading...",
sortname: 'sdate',
sortorder: 'desc',
pager: '#pView1',
caption: "Expense Table",
gridview: true,
rownumbers: true,
autoencode: true,
ignoreCase: true,
viewrecords: true,
footerrow: true,
height: "250",
editurl: 'clientArray',
beforeSelectRow: function (rowid) {
if (rowid !== lastSel) {
$(this).jqGrid('restoreRow', lastSel);
lastSel = rowid;
}
return true;
},
ondblClickRow: function (rowid, ri, ci) {
var $this = $(this), p = this.p;
if (p.selrow !== rowid) {
// prevent the row from be unselected on double-click
// the implementation is for "multiselect:false" which we use,
// but one can easy modify the code for "multiselect:true"
$this.jqGrid('setSelection', rowid);
}
$this.jqGrid('editGridRow', rowid, editSettings);
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
// cancel editing of the previous selected row if it was in editing state.
// jqGrid hold intern savedRow array inside of jqGrid object,
// so it is safe to call restoreRow method with any id parameter
// if jqGrid not in editing state
if (typeof lastSel !== "undefined") {
$(this).jqGrid('restoreRow', lastSel);
}
lastSel = id;
}
},
loadComplete: function () {
var sum = grid.jqGrid('getCol', 'expAmt', false, 'sum');
grid.jqGrid('footerData','set', {ID: 'Total:', expAmt: sum});
jsonData1 = grid.jqGrid('getGridParam', 'data');
document.forms[0].gridData.value = JSON.stringify(jsonData1);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
grid.jqGrid('navGrid', '#pView1', {}, editSettings, addSettings, delSettings, {reloadAfterSubmit:true, beforeSubmit:validate_edit}, {reloadAfterSubmit:true, beforeSubmit:validate_add}, {}, {});
}
I am not providing any data but the same will come after it has been saved in the field and will be reloaded. But when I click on Add the form opens up and when I click on Submit after entering data it just stops. So can you tell me what must be wrong with my code!
Thanks for your help you are such a savior!!!
Siddhartha
inlineNav don't support Delete button, but you can use the corresponding button from navGrid. The problem is only that navGrid add button which implemented by form editing and form editing don't support editing local grid (editurl: 'clientArray') out-of-the-box.
In the old answer I suggested one way how one can do implement delete operation in form editing. In the answer I posted even the way how form editing can be used with local data. Another answer contains updated code which work with the current version (4.4.1 and 4.4.4) of jqGrid. I recommend you to use delSettings from the answer.

Resources