jqGrid getLocalRow return false - jqgrid

I'm creating a JQgrid with datatype local and I want to get row values from editing row using getLocalRow or getCell but I always get false.
This is my grid definition:
jQuery("#rowed5").jqGrid({
datatype: 'local',
data: mydata,
loadtext:"Cargando...",
height: altura*0.4,
width: anchoDefecto*0.9,
colNames:['Cuenta',
'Subcuenta',
'Importe',
'Signo',
'Clave',
'Documento',
'Doc. Referencia',
'Ampliación',
'Extensión'],
colModel:[
{name:'intIdfCuenta',index:'intIdfCuenta', width:200, sorttype:"int", editable:true,editrules:{required:true}, edittype:'custom',
editoptions:{custom_element: myelemcuentas, custom_value:myvaluecuentas} },
{name:'intIdfSubcuenta',index:'intIdfSubcuenta', width:200,editable: true,editrules:{required:true}, edittype:'custom',
editoptions:{custom_element: myelemsubcuentas, custom_value:myvaluesubcuentas}},
{name:'floatImporte',index:'floatImporte', width:200,editable: true,editrules:{required:true}, edittype:'text'},
{name:'strSigno',index:'strSigno', width:200,editable: true, edittype:'custom',editrules:{required:true},
editoptions:{custom_element: myelemsigno, custom_value:myvaluesigno} },
{name:'strIdfClave',index:'strIdfClave', width:200,editable: true,editrules:{required:true}, edittype:'custom',
editoptions:{custom_element: myelemclave, custom_value:myvalueclave} },
{name:'strDocumento',index:'strDocumento', width:200,editable: true,editrules:{required:true},edittype:'text'},
{name:'strDocumentoReferencia',index:'strDocumentoReferencia', width:200,editable: true,edittype:'text'},
{name:'strAmpliacion',index:'strAmpliacion', width:200,editable: true,edittype:'text',editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [
{
type: 'keydown',
fn: function (e) {
var key = e.charCode || e.keyCode;
if (key == 9)
{
procesarTabulacionAmpliacion();
}
}
}
]
}
},
{name:'strIdfTipoExtension',index:'strIdfTipoExtension', width:200,editable:true,edittype:'custom',
editoptions:{custom_element: myelemextension, custom_value:myvalueextension} }
],
cellsubmit: "clientArray",
pager:"#pager",
onSelectRow: function(id){
selectNextRow(id);
}
});
The onSelectRow function is:
function selectNextRow(id){
if (lastsel!=null && id!==lastsel && !myRowIsValid(lastsel) ) {
if(lastsel!=null && id!==lastsel){
jQuery('#rowed5').jqGrid('setSelection', lastsel);
}
return false;
}else if(id && id!==lastsel){
newline = '0';
jQuery("#rowed5").saveRow(lastsel, false, 'clientArray');
jQuery("#rowed5").editRow(id, false);
lastsel=id;
actsel = id;
// ponemos foco
$(getId("intIdfCuenta",actsel,true)).focus();
}
}
I try to get row info using:
var floatImporte = $("#rowed5").jqGrid('getCell', 'floatImporte');
var localRowData = $("#rowed5").jqGrid('getLocalRow');
But in both case I always get false.
Any solution?

The method getLocalRow has one parameter: rowid. So the correct usage of getLocalRow is
var localRowData = $("#rowed5").jqGrid('getLocalRow', id);
If you call getLocalRow without the parameter the getLocalRow sees rowid as undefined and can't return you the data for the corresponding row. In the case the getLocalRow returns false.

I've got the same issue and just created a fiddle. You can change some some values by clicking on a row. The problem is that "getLocalRow" always returns false because the rowid is not found. I look a little bit into the code and in jquery.jqGrid.src.js there is the row:
ind = this.p._index[stripPref(this.p.idPrefix, rowid)];
it is called with rowid="a_jqg2" for example where this.p.idPrefix is "a_".
Am I using it wrong?
Dennis

Related

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.

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.

jqGrid change dynamically edittype for specific row

Following to this post where I found some way to do that I would want to get, I meet some trouble with it.
Here is my code :
var myDlg = $("#dlgpers"),lastsel;
myDlg.jqGrid({
url:'pers.php?id='+dataRow.id,
mtype:'GET',
datatype: "json",
ajaxGridOptions: { cache: false },
height:250,
cmTemplate: {sortable:false},
gridview: true,
cellEdit:true,
scroll:false,
colNames:['Id','Label','Information','Type','Data'],
colModel:[
{name:'id',index:'id',hidden:true,key:true},
{name:'label',index:'label',align:'right',width:100,editable:false,
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"' ;
}
},
{name:'info',index:'info',width:200,editable:true,edittype:'text'},
{name:'type',index:'type',width:30,hidden:true},
{name:'data',index:'data',width:30,hidden:true}
],
loadComplete: function () {
var rowIds = myDlg.jqGrid('getDataIDs');
$.each(rowIds, function (i, row) {
var rowData = myDlg.jqGrid('getRowData',row);
if (rowData.type == 'select') {
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'select';
cm.editoptions = { value: rowData.data };
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}else{
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}
});
}
});
and the result as image :
and the JSON response :
{"page":1,"total":1,"records":1,"rows":[
{"cell":[0,"Nom ","LEBRUN","text",""]},
{"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},
{"cell":[2,"Initiales ","LJ","text",""]},
{"cell":[3,"Fonction ","","text",""]},
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
{"cell":[5,"T\u00e9l\u00e9phone ","","text",""]},
{"cell":[6,"Email ","","text",""]},
{"cell":[7,"Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int"]},
{"cell":[8,"Entr\u00e9 le ","2008-10-06","text",""]},
{"cell":[9,"Sorti le ","0000-00-00","text",""]}]}
Two questions I submit to your knowledge:
As you can see, the second line (Prénom) don't seem editable, but it is.
I don't understand why these inputs are visible, as I would want they appear only if I edit some cell.
Many thanks for all your kind help for resolve (and explain) my wrong way.
JiheL
UPDATED 2013-03-29
I have applied your answer code and that run fine ! Many thanks.
But I have created another form in such a way for another subject, and that cause me some troubles.
Here is the code of this new form :
var showAbs=function(){
$('#EditDialog').empty();
var $table=$('<table></table>')
.attr('id','dlgcong')
.appendTo($('#EditDialog'));
var myCong = $("#dlgcong");
myCong.jqGrid({
url:'xpabs.php?id='+id+'&y='+y,
datatype: "json",
height:"auto",
cmTemplate: {sortable:false},
gridview: true,
colNames:['Type absence','Début','Fin','id'],
colModel:[
{name:'abs',index:'abs',width:155,editable:true,edittype:'select',
editoptions:{
dataUrl:"selabs.php",
dataEvents: [
{
type: 'change',
fn: function(e) {
$(this).parent().css('background-color','#'+$(this).find('option:selected').attr('colr'));
if($(this).find('option:selected').attr('colr')=='ffffff'){
$(this).parent().parent().find('input').datepicker('disable');
}else{
$(this).parent().parent().find('input').datepicker('enable');
$(this).parent().parent().attr('changed',true);
}
}
}
]
},
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="background-color:#'+rawObject[4]+';color:white;"';
}
},
{name:'debut',index:'debut',align:'center',width:70,editable:true},
{name:'fin',index:'fin',align:'center',width:70,editable:true},
{name:'id',index:'id',hidden:true}
],
jsonReader: {
cell: "",
root: function (obj) {
return obj;
}
},
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "debut"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
}
var cm = $self.jqGrid("getColProp", "fin");
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
idPrefix: "cong",
rowNum: 10000
});
//********************
// Button ' Valider '
//********************
$('<input />')
.attr({
type:'button',
})
.css({
float:'right',
marginTop:'5px'
})
.click(function(){
var toBeSaved='';
myCong.find('tr[changed=true]').each(function(idx){
if(toBeSaved.length>0){
toBeSaved+='|';
}
toBeSaved+=$(this).find('td:eq(3)').text()+';';
toBeSaved+=$(this).find('select option:selected').val()+';';
toBeSaved+=$(this).find('input:eq(0)').val()+';';
toBeSaved+=$(this).find('input:eq(1)').val();
});
if(toBeSaved.length>0){
$.ajax({
url:'majpabs.php?id='+id+'&data='+toBeSaved,
async:false,
dataType:'json',
success:function(data){
myGrid.trigger('reloadGrid');
$('#newAbs').val(' Nouveau ').attr('disabled',false);
}
});
}
})
.val(' Valider les absences ')
.appendTo($('#EditDialog'));
//*******************
// Button ' Retour '
//*******************
$('<input />')
.attr({
type:'button',
id:'newAbs'
})
.css({
float:'left',
marginTop:'5px'
})
.click(function(){
showPers();
})
.val(' Retour ')
.appendTo($('#EditDialog'));
//********************
// Button ' Nouveau '
//********************
$('<input />')
.attr({
type:'button',
disabled:false
})
.css({
float:'left',
marginTop:'5px',
marginLeft:'7px'
})
.click(function(){
if($(this).val()==' Nouveau '){
var myRow = {abs:"0", debut:'00/00/'+y, fin:'00/00/'+y, id:'0'};
myCong.jqGrid('addRowData','',myRow, 'last');
$(this).val(' Sauver ').attr('disabled',true);
}else{
}
})
.val(' Nouveau ')
.appendTo($('#EditDialog'));
}
and the result as image :
As you can see, the first row does not receive select and datepicker as other rows. Strange !
When I add new row, it does not receive select and datepicker as the first row.
I think I'm wrong in understanding this method.
I'm worry to bother you with these questions, I had a look in wiki without success to find any way to make these points correct. I would like to find some more detailed tutorial which show some cases examples.
Thank you VERY MUCH if you can spend again some time for give me a way to be more efficient with jqGrid.JiheL
UPDATED 2013-04-01
I have applied Oleg's suggestions and that works now. But a trouble remains.
here is the image :
For the first row, select box is OK.
The first input field receive datepicker, but the second (the column called 'fin') not !
All others rows receive well datepickers, but not the last field of first row.
Here is the code :
loadComplete: function (data) {
var $self = $(this),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item,
cm;
for (i = 0; i < l; i++) {
item = data[i];
cm = $self.jqGrid("getColProp", "debut");
cm.editoptions = {
dataInit: function(element) {
//alert('deb'+i);
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
//
cm = $self.jqGrid("getColProp", "fin");
cm.editoptions = {
dataInit: function(element) {
//alert('fin'+i);
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
Another time, I hope you can help me to resolve this trouble and close this request.
Many thanks for all the time you spend to help newbies.
JiheL
I think that many from the problems in your code common. So I tried to answer on you question more detailed.
First of all you posted wrong JSON data. The line
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
contains two errors:
no ':' after "cell"
no " after "Service
After the changes the line will be so
{"cell":[4,"Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
and JSON data could be read. The next problem is the usage of numbers together with string in one array. Because the bug in the line of jqGrid code
idr = ccur !== undefined ? ccur[idn] || idr : idr;
ids could not be integer value 0. I posted the bug report about the error. To fix the problem using existing code of jqGrid you should use strings instead of numbers. For example the line
{"cell":[0,"Nom ","LEBRUN","text",""]},
should be changed to
{"cell":["0","Nom ","LEBRUN","text",""]},
Without the changes you will have id duplicates. Both first lines ({"cell":[0,"Nom ","LEBRUN","text",""]} and {"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},) will get the same id equal to 1 instead of 0 and 1. It was the main reason of the problem which you described.
Additionally I would recommend you the following:
remove cellEdit:true option. You use editRow later in the code. It means that you use inline editing instead of cell editing which means cellEdit:true. You can't combine both editing modes in one grid.
replace height:250 option to height:"auto"
remove all index properties from colModel. Remove all properties of colModel with default values (edittype:'text', editable:false)
remove options of jqGrid with default values (mtype:'GET', scroll:false)
all parameters of functions in JavaScript are optional. So if you don't use for example any parameters of cellattr callback you can replace cellattr: function (rowId, val, rawObject, cm, rdata) {...} to cellattr: function () {...}
the callback loadComplete has one parameter data which can provide you all data which returned from the server. So you don't need to use getDataIDs and getRowData. The array data.rows can by directly used.
if you use data parameter of loadComplete callback you can remove unneeded 'type' and 'data' columns from the grid.
if you place information about id after 'Label','Information' then you can use id property of jsonReader and remove hidden id column from the grid too. For example if you move id as the last in the cell array you can use jsonReader: {id: 4} and remove hidden id column from the grid. If you add additionally cell: "" property in jsonReader you can remove "cell": from the input data. If you would use root property of jsonReader defined as function (see the documentation) you can remove some unneeded data from the server response.
For example the server can produce the simplified data
[
["Nom ","LEBRUN","text","","0"],
["Pr\u00e9nom ","Jacques","text","","1"],
["Initiales ","LJ","text","","2"],
["Fonction ","","text","","3"],
["Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests","4"],
["T\u00e9l\u00e9phone ","","text","","5"],
["Email ","","text","","6"],
["Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int","7"],
["Entr\u00e9 le ","2008-10-06","text","","8"],
["Sorti le ","0000-00-00","text","","9"]
]
The corresponding jqGrid could be
$("#dlgpers").jqGrid({
url: "pers.php?id=" + dataRow.id,
datatype: "json",
height: "auto",
cmTemplate: {sortable: false},
gridview: true,
colNames: ["Label", "Information"],
colModel: [
{name: "label", align: "right", width: 100,
cellattr: function () {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"';
}},
{name: "info", width: 200, editable: true}
],
jsonReader: {id: 4, cell: "", root: function (obj) { return obj; } },
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "info"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.edittype = item[2] === "select" ? "select" : "text";
cm.editoptions = { value: item[3] };
$self.jqGrid("editRow", idPrefix + item[4]);
}
},
idPrefix: "dlg",
rowNum: 10000 // to have no paging
});
See the demo:

jqGrid Setting id of new added Row intoGrid

jQuery.extend(
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" }, //form editor
reloadAfterSubmit: true
// afterSubmit: function (response, postdata) {
// return [true, "", $.parseJSON(response.responseText).d];
//}
});
$.extend($.jgrid.defaults, {
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
ajaxRowOptions: { contentType: "application/json", type: "POST" },
//row inline editing
serializeGridData: function(postData) { return JSON.stringify(postData); },
jsonReader: {
repeatitems: false,
id: "0",
cell: "",
root: function(obj) { return obj.d.rows; },
page: function(obj) { return obj.d.page; },
total: function(obj) { return obj.d.total; },
records: function(obj) { return obj.d.records; }
}
});
$("#grantlist").jqGrid({
url: 'webservice.asmx/GetGrant',
colNames: ['ID', 'Name', 'Title'],
colModel: [
{ name: 'ID', width: 60, sortable: false },
{ name: 'name', width: 210, editable: true },
{ name: 'title', width: 210, editable: true }
],
serializeRowData: function(data) {
var params = new Object();
params.ID = 0;
params.name = data.name;
params.title = data.title;
return JSON.stringify({ 'passformvalue': params, 'oper': data.oper, 'id': data.id });
},
mtype: "POST",
sortname: 'ID',
rowNum: 4,
height: 80,
pager: '#pager',
editurl: "webservice.asmx/ModifyGrant"
});
$("#grantlist").jqGrid('navGrid', '#pager', { add: false, edit: false, del: false, refresh: false, search: false });
$("#grantlist").jqGrid('inlineNav', '#pager');
//this is my server code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JQGrid<GrantComittee> GetGrantComittee(int? page, int? rows, string sidx, string sord, bool _search)
{
JQGrid<GrantComittee> jqgrid = new JQGrid<GrantComittee>();
List<GrantComittee> data = GetGComittee();
jqgrid.records = data.Count; //total row count
jqgrid.total = (int)Math.Ceiling((double)data.Count / (double)rows); //number of pages
jqgrid.page = page.Value;
//paging
data = data.Skip(page.Value * rows.Value - rows.Value).Take(rows.Value).ToList();
foreach(GrantComittee i in data)
jqgrid.rows.Add(i);
return jqgrid;
}
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int ModifyGrantComittee(GrantComittee passformvalue, string oper, string id)
{
if (String.Compare(id, "_empty", StringComparison.Ordinal) == 0 ||
String.Compare(oper, "add", StringComparison.Ordinal) == 0)
{
GrantComittee data = new GrantComittee();
List<GrantComittee> set = new List<GrantComittee>();
set = (List<GrantComittee>)Session["grantcomittee"];
data = passformvalue;
data.ID = set.Max(p => p.ID) + 1;
set.Add(data);
Session["grantcomittee"] = set;
return data.ID;
}
else if (String.Compare(oper, "edit", StringComparison.Ordinal) == 0)
{
// TODO: modify the data identified by the id
return 0;
}
else if (String.Compare(oper, "del", StringComparison.Ordinal) == 0)
{
// TODO: delete the data identified by the id
return 0;
}
return 0;
}
I am using JqGrid to retrieve and add new records to database. So far i have been able to retrieve and add new items to the DB, I am using "json". I do get in the response {"d": "5"} for the id of the newly created row in the DB. However the new id does not display in the grid.
How can I update that value to new added row?
In the most cases you don't need to do anything because of default setting reloadAfterSubmit: true. It means that the full grid will be reloaded from the server after the user add new row or modify an existing one.
If you want use reloadAfterSubmit: false setting and the server returns the id of the new created row in the response you need implement afterSubmit callback function which will decode the server response and return it for the usage of by jqGrid. The corresponding code could be about the following:
afterSubmit: function (response, postdata) {
return [true, "", $.parseJSON(response.responseText).d];
}
You can define the callback by overwriting the default parameters $.jgrid.edit (see here and here).
I am using 'inlinNav' and after adding a new row i was not getting the grid to reload. The solution I found was to add parametes to the 'inlineNav' declaration. So I end up with the code i am providing as reference:
$("#grantlist").jqGrid('inlineNav', '#pager', { addParams: { position: "last", addRowParams: {
"keys": true, "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); }
}
}, editParams: { "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); } }
});
function reloadgrid(grid) {
grid.trigger("reloadGrid");
}
I was using more than one grid that is why i pass a grid parameter to the reload function.

Resources