Dynamic Columns in jqGrid - jqgrid

I've tried with limited success to get dynamic columns to work with jqGrid. Limited in that I can control the column names and formatting from the controller. But when I do this I can't get the data in.
Do you have a small sample solution that shows the controller code for the two calls.

you can actually bind the column as normal but you can show/hide them at runtime using jquery. for example i have to show link column in jqgrid for admin user and for normal users that column needs to be hidden so implement this in following way.
$("#grid").showCol("Link");
$("#grid").hideCol("Link");
$("#grid").trigger("reloadGrid");

JQGrid1.Columns.FromDataField(ColumnName).Visible = false;
JQGrid1.Columns.FromDataField(ColumnName).HeaderText = "Sample";

JQGrid(action, caption, 920, 400, loadtext);
function columnsData(Data) {
var str = "[";
for (var i = 0; i < Data.length; i++) {
str = str + "{name:'" + Data[i] + "', index:'" + Data[i] + "', editable: true}";
if (i != Data.length - 1) {
str = str + ",";
}
}
str = str + "]";
return str;
}
function JQGrid(action, caption, width, height, loadtext) {
var grid = $("#tblGrid");
var lastsel;
var editurl = '/PayInvoice/GridSave';
$.ajax({
url: action,
dataType: "json",
mtype: 'POST',
beforeSend: function () {
$("#dvloading").show();
},
success: function (result) {
if (result) {
if (!result.Error) {
var colData = columnsData(result.column);
colData = eval('{' + colData + '}');
grid.jqGrid('GridUnload');
grid.jqGrid({
url: action,
datatype: 'json',
mtype: 'POST',
colModel: colData,
colNames: result.column,
// multiselect: true,
width: width,
height: height,
rowNum: 20,
rowList: [20, 40, 60],
loadtext: loadtext,
pager: '#tblGridpager',
sortorder: "asc",
viewrecords: true,
gridview: true,
altRows: true,
cellEdit: true,
cellsubmit: "remote",
cellurl: '/PayInvoice/GridSavecell',
beforeSubmitCell: function (id, cellname, value, iRow, iCol) {
objedit(id, cellname, value);
return { id: id, cellname: cellname, value: value, iRow: iRow, iCol: iCol };
},
afterSaveCell: function (id, cellname, value, iRow, iCol) {
objedit(id, cellname, value);
return { id: id, cellname: cellname, value: value, iRow: iRow, iCol: iCol };
},
caption: caption
});
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr && thrownError) {
alert('Status: ' + xhr.status + ' Error: ' + thrownError);
}
}, complete: function () {
$("#dvloading").hide();
}
});
}
function objedit(id, cellname, value) {
var flag = 0;
for (var i = 0; i < index; i++) {
if (obj[i][0] == id && obj[i][1] == cellname) {
obj[i] = [id, cellname, value]
flag++;
}
}
if (flag == 0) {
obj[index] = [id, cellname, value];
index++;
}
}

Here we go;
$("#datagrid").jqGrid({
//url: "user.json",
//datatype: "json",
datatype: "local",
data: dataArray,
colNames:getColNames(dataArray[0]),
colModel:getColModels(dataArray[0]),
rowNum:100,
loadonce: true,
pager: '#navGrid',
sortname: 'SongId',
sortorder: "asc",
height: "auto", //210,
width:"auto",
viewrecords: true,
caption:"JQ GRID"
});
function getColNames(data) {
var keys = [];
for(var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
function getColModels(data) {
var colNames= getColNames(data);
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: colNames[i],
index:colNames[i],
key:true,
editable:true
};
} else {
str = {
name: colNames[i],
index:colNames[i],
editable:true
};
}
colModelsArray.push(str);
}
return colModelsArray;
}

Related

Configuring jqgrid search to search one of many

I'm having trouble either understanding or implementing search/filter functionality in jqgrid.
The data set is returned to the client with each item having a list of designers:
"IAConsultWorkflowRequestsList": [
{
"AppID": "ISP",
"SubmittedDate": "12/13/2018",
"IAAssigned": "<a style='color:blue !important;' href='mailto:Joseph#somewhere.com'><u>Joseph Kraft</u></a>",
"IAAssignedName": null,
"Status": "In Discovery",
"SLA": 0,
"DaysPassed": 157,
"IsUserFM": false,
"IsUserSecureEnv": false,
"DesignParticipants": [
{
"Name": "John Kraft",
"EmailAddress": "",
"ID": "A2049"
},
{
"Name": "Zack Adamas",
"EmailAddress": "Zachary.Adamas#somewhere.com",
"ID": "U6696"
},
{
"Name": "David Kosov",
"EmailAddress": "David.Kosov#somewhere.com",
"ID": "U6644"
}
]
}
So in the 'Designers' column, I am concatenating the results to be comma separated, e.g.
John Kraft,
Zack Adamas,
David Kosov
And, if the item has an email address, the individual name is formatted as an email link:
<td role="gridcell" style="text-align:center;" title="John Kraft,Zack Burns,David Cosand" aria-describedby="workFlowIAGrid_DesignParticipants">
John Kraft,<br>
<a style="color:blue !important;" ref="mailto:Zachary#somewhere.com"><u>Zack </u></a>,<br>
<a style="color:blue !important;" href="mailto:David#somewhere.com"><u>David </u></a></td>
I have a select element with entries John, Zack, and David, but when I select one of the options, I do not get expected results. If I select David, I would like to be shown any rows that contain David as one of potentially several names in the Designer column.
However, I am getting erratic behavior. Some of the sopt options will cause something to happen, but not what is expected. None of the contains/not contained or in/not in options seem to do what I need. What am I doing wrong?
Per Tony's comment, here is the grid init code:
$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: [
{ label: 'Design Participants', name: 'DesignParticipants', align: "center", formatter:commaSeparatedList },
//same for other columns...
],
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 () {
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
var rowIDs = $gridEl.getDataIDs();
var inCompleteFlag = false;
//Filter code to apply filter in headers in MyWork grid
var datatoFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
var $grid = $gridEl, postfilt = "";
var getUniqueNames = function (columnName) {
var uniqueTexts = [],
mydata = datatoFilter,
texts = $.map(mydata, function(item) {
return item[columnName];
}),
textsLength = texts.length,
text = "",
textsMap = {},
i;
if (texts[0] && texts[0].Name)
texts = $.map(texts,
function(item) {
return item.Name;
});
for (i = 0; i < textsLength; i++) {
text = texts[i];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
if (columnName == 'ConsultID') {
return (uniqueTexts.sort(function (a, b) { return a - b; }));
} else return uniqueTexts.sort();
}, buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
}, setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{
type: "change",
fn: function (e) {
setTimeout(function () {
//get values of dropdowns
var DesignParticipant = $('#gs_workFlowIAGrid_DesignParticipants').val();
//same for other columns...
var columnNamesArr = columns.split(',');
changedColumns.push(columnName);
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
var val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
$('#gs_workFlowIAGrid_DesignParticipants').val(DesignParticipant);
//same for other columns...
},
500);
//setting the values :
}
}
]
}
});
};
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
setSearchSelect.call($grid, "DesignParticipants");
//same for other columns...
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
var localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
$gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
})
.trigger("reloadGrid");
//Ending Filter code
var columnNamesArr = columns.split(',');
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
Here is the formatter I am using on the column:
function commaSeparatedList(cellValue, options, rowdata, action) {
let dps = [];
_.forEach(cellValue, function (item) {
let formatted = '';
if (item.EmailAddress)
formatted += '<a style="color:blue !important;" href="mailto:' +
item.EmailAddress +
'"><u>' +
item.Name +
'</u></a>';
else formatted = item.Name;
dps.push(formatted + ',<br/>');
});
let toString = dps.join('');
return toString.substring(0,toString.length-6);
}
And then the only other pertinent thing is that I used a function to return 'in' (or some other key - these are the options I said weren't apparently working in the initial post) if the column is named 'Design Participants', else equal for any other column:
setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{...
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
The issue was that the underlying data (the DesignParticipants in the returned JSON above) did not match the selected string, since the data itself was an array. I believed the filtering was based on the displayed text in the grid table, but, it was based on the underlying data. So, I created a new property of the returned JSON that was a string, and the filtering worked as expected.

JsGrid Sorting not working

Following is part of my JsGrid code, which I think something is missing in order for me to sort my data like any other examples on Fiddle.
autoload: true,
inserting: false,
editing: false,
paging: true,
pageIndex: 1,
pageSize: 5,
pageLoading: true,
autoload: true,
filter: true,
sorting: true,
controller: {
loadData: function(filter) {
return $.ajax({
type: "GET",
url: BASE_URL,
data: filter,
dataType: "json",
cache: false
});
},
},
I have tried with sorting:"number".
Below logic of sorting on the basis of number
$("#Grid2").jsGrid({
height: "auto",
width: "100%",
filtering: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
inserting: false,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
var d = $.Deferred();
$.ajax({
cache: false,
type: 'GET',
url: "http://" + servername + ":" + portnumber + "/api,
data: filter,
dataType: "json",
success: function(data) {
filteredData = $.grep(data, function(item) {
//filtering logic
;
});
d.resolve(filteredData);
testdata = JSON.stringify(data);
$("#Grid2").jsGrid("sort", 1);
HistoricData = data;
},
error: function(e) {
console.log(e);
console.log(e.responseText);
var errorMsg = e.responseText;
var msg = errorMsg + " for this particular combination";
showError(msg);
$("#displayingHistoryValues").hide();
$("#ExportGrid2").hide();
$("#Grid2").hide();
d.resolve();
}
});
return d.promise();
}
},
fields: [{
title: "Value",
name: "MeasureValue",
type: "number",
width: "5%",
css: "custom-field",
sorting: true,
itemTemplate: function(value, item) {
if (item.MeasureValue != null && item.MeasureValue != '' && item.MeasureValue.trim().length > 0) {
var mesval = FormatValeur(item.MeasureUnit, item.MeasureValue);
return "<div>" + mesval + "</div>";
}
}
}, {
type: "control",
editButton: false,
deleteButton: false,
width: "5%"
}]
})
Another way to sort, get the filteredData or loaded data
and call onRefresing of JSGrid .
Way to sort JS grid on column after grid load :
onRefreshing: function (args) {
fundCodeList = [];
jsonNumLst = [];
jsonNANLst = [];
if(this._visibleFieldIndex(this._sortField) == -1
|| this._visibleFieldIndex(this._sortField)==1){
$.each(filteredData, function(inx, obj) {
if($.isNumeric(obj.fundCode)){
jsonNumLst.push(obj);
}else{
jsonNANLst.push(obj);
}
});
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
jsonNumLst.sort(sortByNumFCAsc);
jsonNANLst.sort(sortByNANFCAsc);
}else if(this._sortOrder == 'desc'){
jsonNANLst.sort(sortByNANFCDesc);
jsonNumLst.sort(sortByNumFCDesc);
}
if(jsonNumLst.length>0 || jsonNANLst.length>0){
filteredData = [];
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNumLst.length){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
}
}else if(this._sortOrder == 'desc'){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNANLst.length){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
}
}
}
if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
$("#measureImportGrid3").data("JSGrid").data = filteredData;
//isSortGrid = false;
//saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
}
}
//Ascending order numeric
function sortByNumFCAsc(x,y) {
return x.fundCode - y.fundCode;
}
//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}
//Descending order numeric
function sortByNANFCDesc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}
//Descending order non-numeric
function sortByNumFCDesc(x,y) {
return y.fundCode - x.fundCode;
}
}

Create Jqgrid pass value from datatable and change column names dynamically

I want to create jqgrid by passing value from Datatable as I have multiple tables ,based on that I need to change colomn names dynamically,in asp.net mvc.
Hi after working hard on it finally i have got a solution.
<table id="tableDetails1" cellpadding="0" cellspacing="0">
<tr><td></td></tr></table>
<div id="pager" style="text-align: center"></div>
Jqgrid and javascript function
<script type="text/javascript">
$(document).ready(function () {
// $("#tableDetails1").GridUnload();
CreateColumnDetails();
});
function getData() {
debugger;
$.ajax({
url: '#Url.Action("TableDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
var obj = $.parseJSON(result);
resultData = JSON.parse(result);
$(resultData).each(function (e) {
$("#tableDetails1").addRowData(e, this);
});
}
});
}
function CreateColumnDetails() {
debugger;
$.ajax({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
var colName = JSON.parse(result);
debugger;
var colModels = BuildColumnModel(colName);
$("#tableDetails1").jqGrid({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
datatype: 'json',
colNames: colName,
colModel: colModels
})
}
});
getData();
}
function CreateGrid(result) {
debugger;
$("#tableDetails1").jqGrid({
url: '#Url.Action("TableDetails", "TableInfo")',
datatype: 'json',
mtype: 'Get',
pager: $('#pager'),
rowNum: 5,
gridview: true,
rowList: [5, 10, 20, 30],
height: '100%',
viewrecords: true,
caption: 'Table Details ',
emptyrecords: 'No Records found',
jsonReader: {
root: function (rows) {
debugger;
return typeof rows === "string" ? $.parseJSON(rows) : rows;
},
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
id: "0"
},
autowidth: true,
multiselect: false,
loadError: function (jqXHR, textStatus, errorThrown) {
debugger;
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
}).navGrid('pager', { edit: false, add: false, del: false });
}
function BuildColumnModel(result) {
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if(uFields[i].length>-1){
columns.push({ name: uFields[i], index: uFields[i]})
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
</script>
Controllers
**Httppost method adding rows dynamically
[HttpPost]
public ActionResult TableDetails(int? id, DataTable dt)
{
dt = new DataTable();
dt = GetTableDetails(id);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
serializer.Serialize(col.ColumnName);
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Json(serializer.Serialize(rows), JsonRequestBehavior.AllowGet);
}
Column Details in string format
[HttpPost]
public ActionResult GetColumnDetails(int ? id, DataTable dt)
{
dt = GetTableDetails(1);
// id = (int)Session["id"] ;
// dt = GetTableDetails(id);
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(columnNames), JsonRequestBehavior.AllowGet);
}

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 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