I'm trying to load the subgrid data from the main grid. The main grid loads fine but When I click on a row the subgrid data does not load.
Don't know what I'm missing. Please help.
Below is the code I'm using.
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
var mydata = [],
grid = $("#list");
var mainGridPrefix = "s_";
grid.jqGrid({
url: '${recordsUrl}',
datatype: 'json',
ignoreCase: true,
mtype: 'GET',
colNames: ['Global Search', 'serverId', 'DeviceName', 'Description', 'Console', 'OS', 'Business Unit', 'Model', 'Manufacturer', 'Serial Number', 'LifeCycle', 'Tier'],
colModel: [{
name: 'globalSearch',
index: 'globalSearch',
width: 50,
hidden: true,
searchoptions: {
searchhidden: true
}
}, {
name: 'serverId',
index: 'serverId',
width: 10,
hidden: true
}, {
name: 'deviceName',
index: 'deviceName',
width: 50
}, {
name: 'serverDesc',
index: 'serverDesc',
width: 70
}, {
name: 'console',
index: 'console',
width: 50
}, {
name: 'groupName',
index: 'groupName',
width: 40
}, {
name: 'businessUnit',
index: 'businessUnit',
width: 30
}, {
name: 'model',
index: 'model',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'manufacturer',
index: 'manufacturer',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'serialNumber',
index: 'serialNumber',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'lifeCycle',
index: 'lifeCycle',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'tier',
index: 'tier',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}],
postData: {},
rowNum: 10,
rowList: [10, 20, 40, 60],
height: 'auto',
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'deviceName',
viewrecords: true,
sortorder: "asc",
caption: "Records",
emptyrecords: "Empty records",
idPrefix: mainGridPrefix,
loadonce: true,
loadComplete: function () {},
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "serverId"
},
subGrid: true,
beforeProcessing: function (data) {
var rows = data.rows,
l = rows.length,
i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.apps) {
subgrids[item.id] = item.apps;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: subgrids[pureRowId],
colNames: ["App Id", "Desc"],
colModel: [{
name: "appId"
}, {
name: "applicationDesc"
}],
sortname: "applicationDesc",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: {
repeatitems: false,
id: "appId"
},
gridview: true,
idPrefix: rowId + "_"
});
}
});
$("#search").click(function () {
var searchFiler = $("#filter").val(),
f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, {
filters: ""
});
}
f = {
groupOp: "OR",
rules: []
};
f.rules.push({
field: "globalSearch",
op: "cn",
data: searchFiler
});
f.rules.push({
field: "deviceName",
op: "cn",
data: searchFiler
});
grid[0].p.search = true;
$.extend(grid[0].p.postData, {
filters: JSON.stringify(f)
});
grid.trigger("reloadGrid", [{
page: 1,
current: true
}]);
});
grid.jqGrid('navGrid', '#pager', {
edit: false,
add: false,
del: false,
search: true,
view: true
}, {}, {}, {}, { // search
sopt: ['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}, { // vew options
beforeShowForm: function (form) {
$("tr#trv_id", form[0]).show();
},
afterclickPgButtons: function (whichbutton, form, rowid) {
$("tr#trv_id", form[0]).show();
}
});
grid.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-plus",
onClickButton: addRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Edit",
buttonicon: "ui-icon-pencil",
onClickButton: editRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title: "",
cursor: "pointer"
});
});
//]]>
you forgot to add the index: information for the colModel in the subgrid, you also need to pay attention to capitalization if the name is capitalized then so should be the index, that way jqgrid knows that where it needs to put the data. Here is the fixed code and also a link to a working example
//<![CDATA[
$(document).ready(function () {
var mydata = [{
globalsearch: "1",
serverId: "Test Name1",
deviceName: "Test Address1",
Console: "Test Date1"
}, {
globalsearch: "2",
serverId: "Test Name2",
deviceName: "Test Address2",
Console: "Test Date2"
}, {
globalsearch: "3",
serverId: "blah",
deviceName: "hello",
Console: "basketball"
}];
grid = $("#list");
var mydata2 = [{
AppId: "1",
Desc: "Test Name1"
}, {
AppId: "2",
Desc: "Test Name2"
}, {
AppId: "3",
Desc: "blah"
}];
var mainGridPrefix = "s_";
grid.jqGrid({
datatype: 'local',
data: mydata,
colNames: ['globalsearch', 'serverId', 'deviceName', 'Description', 'Console', 'OS', 'Business Unit', 'Model', 'Manufacturer', 'Serial Number', 'LifeCycle', 'Tier'],
colModel: [{
name: 'globalsearch',
index: 'globalsearch',
width: 50,
}, {
name: 'serverId',
index: 'serverId',
width: 10,
hidden: false
}, {
name: 'deviceName',
index: 'deviceName',
width: 50
}, {
name: 'serverDesc',
index: 'serverDesc',
width: 70
}, {
name: 'Console',
index: 'Console',
width: 50
}, {
name: 'groupName',
index: 'groupName',
width: 40
}, {
name: 'businessUnit',
index: 'businessUnit',
width: 30
}, {
name: 'model',
index: 'model',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'manufacturer',
index: 'manufacturer',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'serialNumber',
index: 'serialNumber',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'lifeCycle',
index: 'lifeCycle',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'tier',
index: 'tier',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}],
rowNum: 10,
rowList: [10, 20, 40, 60],
rownumbers: true,
pager: '#pager',
sortname: 'deviceName',
viewrecords: true,
sortorder: "asc",
caption: "Records",
height: 'auto',
autowidth: true,
loadComplete: function () {},
subGrid: true,
beforeProcessing: function (data) {
var rows = data.rows,
l = rows.length,
i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.apps) {
subgrids[item.id] = item.apps;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: mydata2,
colNames: ["AppId", "Desc"],
colModel: [{
name: "AppId",
index: "AppId"
}, {
name: "Desc",
index: "Desc"
}],
sortname: "applicationDesc",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: {
repeatitems: false,
id: "appId"
},
gridview: true,
idPrefix: rowId + "_"
});
}
});
$("#search").click(function () {
var searchFiler = $("#filter").val(),
f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, {
filters: ""
});
}
f = {
groupOp: "OR",
rules: []
};
f.rules.push({
field: "globalSearch",
op: "cn",
data: searchFiler
});
f.rules.push({
field: "deviceName",
op: "cn",
data: searchFiler
});
grid[0].p.search = true;
$.extend(grid[0].p.postData, {
filters: JSON.stringify(f)
});
grid.trigger("reloadGrid", [{
page: 1,
current: true
}]);
});
grid.jqGrid('navGrid', '#pager', {
edit: false,
add: false,
del: false,
search: true,
view: true
}, {}, {}, {}, { // search
sopt: ['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}, { // vew options
beforeShowForm: function (form) {
$("tr#trv_id", form[0]).show();
},
afterclickPgButtons: function (whichbutton, form, rowid) {
$("tr#trv_id", form[0]).show();
}
});
grid.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-plus",
onClickButton: addRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Edit",
buttonicon: "ui-icon-pencil",
onClickButton: editRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title: "",
cursor: "pointer"
});
});
//]]>
<table id="list"></table>
<div id="pager"></div>
Related
I want to add multiselect dropdown with chechbox in my application , i had added it , it works perfecty . Multiple selection is enabled but it's height is not getting set , here is my view ... please help
View
jQuery(grid_selector).jqGrid({
subGridRowExpanded: function (subgridDivId, rowId) {
},
autowidth: true,
shrinkToFit: true,
url: '#Url.Action("GetAllTasks","AdminIndex")',
datatype: 'json',
mtype: 'GET',
height: 'auto',
colNames:['Task Id ','Project Name', 'Assign To','Task Name','Task Description','Budget','Task Status','Start Date','End Date'],
colModel:[
{name:'Task_Id', key: true,searchoptions: { sopt: ['eq','ne','gt','ge','lt','le']}, index:'id', width:20, sorttype:"int", editable: true, editable: true, sortable: true, search: true, searchrules: { required: true}},
{name:'Project_Name',index:'pid', width:40,search:false,editrules: { required: true},editable: true,formoptions: { rowpos: 2, colpos: 1},editoptions:{size:"1",value: projects}, style: "width: 180px",edittype: "select", stype: "select",dataheight:'auto'},
{name:'User_Email',stype: 'select',index:'email',searchoptions: { sopt: ['eq','ne']},searchoptions:{ value: users }, width:60,editrules: { required: true},edittype: 'select',editable: true,editoptions:{size:5,value: users,dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({
header:"Choose an option!",
minWidth: 100, //'auto',
height: 600,
selectedList: 7,
checkAllText: "all",
uncheckAllText: "no",
noneSelectedText: "Any",
open: function () {
var $menu = $(".ui-multiselect-menu:visible");
$menu.width("auto");
return;
}
});
}, 50);
},multiple: true,defaultValue: 'IN'},editrules: { required: true},edittype: "select", stype: "select"},
{name:'Task_Name',index:'tname', width:40,searchoptions: { sopt: ['eq','ne']},editrules: { required: true},editable: true,editoptions:{size:"20",maxlength:"30"},editrules: { required: true}},
{name:'Task_Description',index:'Task_Description',width:90, edittype: "textarea",editoptions:{rows:"3",cols:"21"},search: false,editable: true,editrules: { required: true}, classes: "textInDiv"},
{name:'Task_hrs',index:'taskhrs', width:20,search:false,editrules: { required: true,number:true},editable: true,editoptions:{size:"20",maxlength:"30"},editrules: { required: true}},
{name:'Task_Status',index:'tstatus',searchoptions: { sopt: ['eq','ne']},searchoptions:{ value: getAllSelectOptions() }, width:25, editable: true,search:true,editrules: { required: true}, editoptions:{value: getAllSelectOptions()},edittype: "select", stype: "select"},
{name:'Task_Start_Time',sortable:false,search:false,width:30, editable:true,editrules: { required: true},formatter: "date", formatoptions: { newformat: "d/M/Y "} },
{name:'Task_End_Time',sortable:false,width:30,search:false, editable:true,editrules: { required: true},formatter: "date", formatoptions: { newformat: "d/M/Y "} },
// {name:'CreatedTimeStamp',sortable:false,width:30, editable:false,search:true,editrules: { required: true},formatter: "date", formatoptions: { newformat: "d/m/Y H:m:s"} },
// {name:'ModifyTimeStamp',sortable:false,width:30, editable:false,search:true,editrules: { required: true},formatter: "date", formatoptions: { newformat: "d/m/Y H:m:s"}},
],
});
I have a single page ASP.Net web forms application. And lots of grids. In my application, there is some links to hide or show grids. The problem is, when i start the application, the pagination of the displayed grid is working properly. (I tried this for each grid). But when I Click the link for hide a grid and show another grid, paging does not working. The grid initialization is;
$('#tblApplicationSettings').jqGrid({
url: cms.util.getAjaxPage(),
cellLayout: cms.theme.list.cellLayout,
hoverrows: false,
forceFit: true,
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "",
id: "0"
},
width: 900,
height: 400,
datatype: 'local',
colNames: ['SettingId',
'Description',
'Name',
'Value',
'ServerId',
'IsReadOnly',
''
],
colModel: [
{
name: 'SettingId',
index: 'SettingId',
hidden: true
},
{
name: 'Description',
index: 'Description',
search: false,
editable: true,
sortable: false,
width: 150,
inlineEditable: true
},
{
name: 'Name',
index: 'Name',
search: false,
editable: false,
sortable: false,
width: 150,
inlineEditable: false
},
{
name: 'Value',
index: 'Value',
search: false,
editable: true,
sortable: false,
width: 250,
inlineEditable: true,
},
{
name: 'ServerId',
index: 'ServerId',
search: false,
editable: true,
sortable: false,
width: 150,
formatter: 'select',
edittype: 'select',
editoptions: {
value: options,
},
inlineEditable: true
},
{
name: 'IsReadOnly',
index: 'IsReadOnly',
hidden: true
},
{
name: 'JsUsage',
index: 'JsUsage',
search: false,
editable: true,
sortable: false,
width: 150,
inlineEditable: true
},
],
onSelectRow: function (id) {
if (id && id !== lastSelection) {
jQuery('#grid').jqGrid('restoreRow', lastSelection);
lastSelection = id;
}
var columnModel = $('#grid').getGridParam('colModel');
var colNames = new Array();
$.each(columnModel, function (index, column) {
colNames.push(column.name);
if (isReadOnly || !column.inlineEditable) {
column.editable = false;
}
else {
column.editable = true;
}
if (column.edittype == "select") {
column.editoptions.dataEvents = [{
type: 'change',
fn: function (e) {
var newServerId = $(this).val();
that.isServerIdChanged = true;
if (newServerId == "null") {
}
}
}]
}
});
var row = $('#grid').getRowData(id);
var isReadOnly = row.IsReadOnly == "true" ? true : false;
if (isReadOnly) {
alert("row is not editable");
return null;
}
jQuery("#grid").jqGrid('editRow', id, {
keys: true,
extraparam: {
dataType: 'updateSetting',
colNames: JSON.stringify(colNames),
settingName: row.Name,
settingId: row.SettingId
},
successfunc: function (result) {
$("#grid").trigger('reloadGrid');
}
});
},
editurl: '/Ajax.ashx',
rowNum: 25,
direction: "ltr",
scroll: 1,
gridview: true,
pager: '#divPager',
viewrecords: true,
});
$('#grid').setGridParam({ datatype: "json", postData: { dataType: 'getSettings' } });
$('#grid').jqGrid('navGrid', '#divPager', { edit: false, add: false, del: false, search: false, refresh: false });
$('#grid').trigger('reloadGrid');
like this for all grids. I need tips or helps. Thanks.
I am using this to fill multiselect filter value based on those are present in available rows for particular column.
I am facing below issue when going to delete selected row i.e. say I have deleted the first row, after deletion multiselect filter should recalculate the value based on those are present in available rows for particular column(for SkillCategory). We can see after deletion first row still "Data" value is available for SkillCategory multiselect filter.
How can I recalculate multiselect filter value after deleting row/add/update?
<script type="text/javascript">
function loadCompleteHandler1() {
initializeGridFilterValueSupply();
}
jQuery(function () {
$.extend(true, $.jgrid.search, {
beforeShowForm: function ($form) {
$form.closest(".ui-jqdialog").position({
of: window,
at: "center center",
my: "center center"
});
}
});
$.extend($.jgrid.edit, { viewPagerButtons: false });
$grid = $("#listTableSupply"),
myDefaultSearch = "cn",
getColumnIndexByName = function (columnName) {
var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i += 1) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
modifySearchingFilter = function (separator) {
var i, l, rules, rule, parts, j, group, str, iCol, cmi, cm = this.p.colModel,
filters = $.parseJSON(this.p.postData.filters);
if (filters && filters.rules !== undefined && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
iCol = getColumnIndexByName.call(this, rule.field);
cmi = cm[iCol];
if (iCol >= 0 &&
((cmi.searchoptions === undefined || cmi.searchoptions.sopt === undefined)
&& (rule.op === myDefaultSearch)) ||
(typeof (cmi.searchoptions) === "object" &&
$.isArray(cmi.searchoptions.sopt) &&
cmi.searchoptions.sopt[0] === rule.op)) {
// make modifications only for the 'contains' operation
parts = rule.data.split(separator);
if (parts.length > 1) {
if (filters.groups === undefined) {
filters.groups = [];
}
group = {
groupOp: 'OR',
groups: [],
rules: []
};
filters.groups.push(group);
for (j = 0, l = parts.length; j < l; j++) {
str = parts[j];
if (str) {
// skip empty '', which exist in case of two separaters of once
group.rules.push({
data: parts[j],
op: rule.op,
field: rule.field
});
}
}
rules.splice(i, 1);
i--; // to skip i++
}
}
}
this.p.postData.filters = JSON.stringify(filters);
}
},
dataInitMultiselect = function (elem) {
setTimeout(function () {
var $elem = $(elem), id = elem.id,
inToolbar = typeof id === "string" && id.substr(0, 3) === "gs_",
options = {
selectedList: 2,
height: "auto",
checkAllText: "all",
uncheckAllText: "no",
noneSelectedText: "Any",
open: function () {
var $menu = $(".ui-multiselect-menu:visible");
$menu.width("auto");
return;
}
},
$options = $elem.find("option");
if ($options.length > 0 && $options[0].selected) {
$options[0].selected = false; // unselect the first selected option
}
if (inToolbar) {
options.minWidth = 'auto';
}
//$elem.multiselect(options);
$elem.multiselect(options).multiselectfilter({ placeholder: '' });
$elem.siblings('button.ui-multiselect').css({
width: inToolbar ? "98%" : "100%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}, 50);
};
jQuery("#listTableSupply").jqGrid({
url: 'HttpHandler/SupplyHandler.ashx',
ajaxSelectOptions: { cache: false },
postData: { ActionPage: 'TransportType', Action: 'Fill' },
datatype: 'json',
mtype: 'GET',
colNames: ['SupplyId', 'Account', 'AccountPOC', 'COE', 'Type', 'Location', 'EmpId', 'EmpName', 'Designation', 'AvailabilityDate', 'AvailabilityMonth', 'Exp', 'SkillCategory', 'PrimarySkill', 'SecondarySkill', 'OtherSkill', 'Role', 'VisaStatus', 'Country', 'Comments'],
colModel: [
{ name: 'SupplyId', index: 'SupplyId', width: '5%', align: 'center', sortable: true, resizable: true, hidden: true },
{
name: 'Account', index: 'Account', width: '10%', sortable: true, resizable: true, stype: 'select'
},
{ name: 'AccountPOC', index: 'AccountPOC', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'COE', index: 'COE', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'Type', index: 'Type', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'Location', index: 'Location', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{ name: 'EmpId', index: 'EmpId', width: '5%', sortable: true, resizable: true, hidden: true },
{ name: 'EmpName', index: 'EmpName', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'Designation', index: 'Designation', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'AvailabilityDate', index: 'AvailabilityDate', width: '5%', sortable: true, search: true, resizable: true, stype: 'select'
},
{ name: 'AvailabilityMonth', index: 'AvailabilityMonth', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'Experience', index: 'Experience', width: '5%', sortable: true, resizable: true, search: true, stype: 'select'
},
{
name: 'SkillCategory', index: 'SkillCategory', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'PrimarySkill', index: 'PrimarySkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'SecondarySkill', index: 'SecondarySkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'OtherSkill', index: 'OtherSkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'CurrentRole', index: 'CurrentRole', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{
name: 'VisaStatus', index: 'VisaStatus', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{
name: 'Country', index: 'Country', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{ name: 'Comments', index: 'Comments', width: '5%', search: false, sortable: false, resizable: true },
],
width: '1192',
height: '300',
loadonce: true,
pager: '#pagerSupply',
gridview: true,
rowNum: 15,
rowList: [15, 30, 45],
rowTotal: 5000,
sortorder: 'asc',
ignoreCase: true,
sortname: 'Account',
viewrecords: true,
rownumbers: true,
toppager: true,
caption: 'Supply',
emptyrecords: "No records to view",
loadtext: "Loading...",
refreshtext: "Refresh",
refreshtitle: "Reload Grid",
loadComplete: loadCompleteHandler1,
ondblClickRow: function (rowid) {
jQuery(this).jqGrid('viewGridRow', rowid);
},
beforeRequest: function () //loads the jqgrids state from before save
{
modifySearchingFilter.call(this, ',');
}
}).jqGrid('bindKeys');
$('#listTableSupply').bind('keydown', function (e) {
if (e.keyCode == 38 || e.keyCode == 40) e.preventDefault();
});
//setSearchSelect("SkillCategory");
$('#listTableSupply').jqGrid('navGrid', '#pagerSupply', {
cloneToTop: true,
refresh: true, refreshtext: "Clear Filter", edit: false, add: false, del: true, search: false
}, {}, {}, {//Del
closeOnEscape: true, //Closes the popup on pressing escape key
drag: true,
recreateForm: true,
//closeAfterEdit: true,
url: 'HttpHandler/SupplyHandler.ashx',
delData: {
ActionPage: 'TransportType', Action: 'Delete',
SupplyId: function () {
var sel_id = $('#listTable').jqGrid('getGridParam', 'selrow');
var value = $('#listTable').jqGrid('getCell', sel_id, 'SupplyId');
return value;
}
},
afterShowForm: function ($form) {
$form.closest(".ui-jqdialog").position({ of: window, my: "center center", at: "center center" });
//$form.closest(".ui-jqdialog").position({of: window,at: "center center",my: "left top"});
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
//$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after del
return [true, '']
}
else {
if (response.responseText == "Record Successfully Deleted!!!") {
//$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
var myInfo = '<div class="ui-state-highlight ui-corner-all">' +
'<span class="ui-icon ui-icon-info" ' +
'style="float: left; margin-right: .3em;"></span>' +
'<span>Record Successfully Deleted!!!</span></div>';
var infoTR = $("table#TblGrid_listTable>tbody>tr.tinfo");
infoTD = infoTR.children("td.topinfo");
infoTD.html(myInfo);
infoTR.show();
setTimeout(function () {
infoTD.children("div").fadeOut('slow',
function () {
infoTR.hide();
});
}, 8000);
initializeGridFilterValueSupply();
return [true, '']
}
else {
return [false, response.responseText]//Captures and displays the response text on th Del window
}
}
}
}, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true
});
jQuery("#listTableSupply").jqGrid('navButtonAdd', '#listTableSupply_toppager_left', { // "#list_toppager_left"
caption: "Refresh",
buttonicon: 'ui-icon-refresh',
onClickButton: function () {
$("#listTableSupply").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid", [{ page: 1 }]);
initializeGridFilterValueSupply();
}
});
jQuery("#listTableSupply").jqGrid('navButtonAdd', '#pagerSupply', { // "#list_toppager_left"
caption: "Refresh",
buttonicon: 'ui-icon-refresh',
onClickButton: function () {
$("#listTableSupply").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid", [{ page: 1 }]);
initializeGridFilterValueSupply();
}
});
});
//]]>
</script>
<script type="text/javascript">
initializeGridFilterValueSupply = function () {
jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("Account", jQuery("#listTableSupply"));
setSearchSelect("COE", jQuery("#listTableSupply"));
setSearchSelect("AccountPOC", jQuery("#listTableSupply"));
setSearchSelect("Type", jQuery("#listTableSupply"));
setSearchSelect("Location", jQuery("#listTableSupply"));
setSearchSelect("Designation", jQuery("#listTableSupply"));
setSearchSelect("EmpName", jQuery("#listTableSupply"));
setSearchSelect("AvailabilityDate", jQuery("#listTableSupply"));
setSearchSelect("Experience", jQuery("#listTableSupply"));
setSearchSelect("SkillCategory", jQuery("#listTableSupply"));
setSearchSelect("PrimarySkill", jQuery("#listTableSupply"));
setSearchSelect("SecondarySkill", jQuery("#listTableSupply"));
setSearchSelect("OtherSkill", jQuery("#listTableSupply"));
setSearchSelect("CurrentRole", jQuery("#listTableSupply"));
setSearchSelect("VisaStatus", jQuery("#listTableSupply"));
setSearchSelect("Country", jQuery("#listTableSupply"));
jQuery("#listTableSupply").jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: true,
defaultSearch: myDefaultSearch,
beforeClear: function () {
$(this.grid.hDiv).find(".ui-search-toolbar .ui-search-input>select[multiple] option").each(function () {
this.selected = false; // unselect all options
});
$(this.grid.hDiv).find(".ui-search-toolbar button.ui-multiselect").each(function () {
$(this).prev("select[multiple]").multiselect("refresh");
}).css({
width: "98%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}
});
jQuery("#listTableSupply").jqGrid('setGridHeight', 300);
}
</script>
I got my answer.
I need to use destroyFilterToolbar to destroy the filter toolbar and then create the toolbar one more time using filterToolbar.
initializeGridFilterValueDemand = function () {
//jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("AccountName", jQuery("#listTableDem"));
setSearchSelect("COE", jQuery("#listTableDem"));
setSearchSelect("DemandType", jQuery("#listTableDem"));
setSearchSelect("Location", jQuery("#listTableDem"));
setSearchSelect("Designation", jQuery("#listTableDem"));
setSearchSelect("Experience", jQuery("#listTableDem"));
setSearchSelect("ExpectedRole", jQuery("#listTableDem"));
setSearchSelect("SkillCategory", jQuery("#listTableDem"));
setSearchSelect("PrimarySkill", jQuery("#listTableDem"));
setSearchSelect("SecondarySkill", jQuery("#listTableDem"));
setSearchSelect("OtherSkill", jQuery("#listTableDem"));
setSearchSelect("RequiredDate", jQuery("#listTableDem"));
setSearchSelect("CriticalFlag", jQuery("#listTableDem"));
setSearchSelect("ConfidenceFactor", jQuery("#listTableDem"));
setSearchSelect("HiringSOId", jQuery("#listTableDem"));
**jQuery("#listTableDem").jqGrid("destroyFilterToolbar");**
jQuery("#listTableDem").jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: true,
defaultSearch: myDefaultSearch,
beforeClear: function () {
$(this.grid.hDiv).find(".ui-search-toolbar .ui-search-input>select[multiple] option").each(function () {
this.selected = false; // unselect all options
});
$(this.grid.hDiv).find(".ui-search-toolbar button.ui-multiselect").each(function () {
$(this).prev("select[multiple]").multiselect("refresh");
}).css({
width: "98%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}
});
jQuery("#listTableDem").jqGrid('setGridHeight', 300);
}
And I am calling it in loadComplete event.
Update:
This will not going to work if we use destroyGroupHeader
I have now a problem with validation of a record that is being edited.
The edit form (and the add form) has a field called "email". That field should be unique in database, so I use ajax to validate it, by mean of this function:
function check_email(value, colname) {
$.ajax({
url: '#Url.Action("CheckEmail")',
data: { email: value },
type: 'POST',
async: false,
datatype: 'text',
success: function (data) {
if (!data) result = [true, ""];
else result = [false, colname + ": ya existe en el sistema"];
}
})
return result;
}
This works, but the problem is when I am editing the record. Of course e-mail exists in this case, so it is not allowing me to save the record.
The algorithm might be: it should validate only if id is > 0 and the entered e-mail is different from the existing value. In other words, validation must occur if the user is changing e-mail.
I spent a lot of time trying to figure out how to know if the editform is for adding or for editing, and even more, I was trying to find the value of the primary key of the record being edited, without any success.
Any help will be appreciated,
EDIT:
This is the code of the grid:
$("#personal").jqGrid({
url: "#Url.Action("List")",
datatype: "json",
mtype: "GET",
colNames: ["Departamento",
"Nombres",
"Apellido Paterno",
"Apellido Materno",
"RUT",
"Contraseña",
"Fecha Nacimiento",
"Fotografía",
"Estado Civil",
"Género",
"Dirección",
"Cargo",
"E-mail",
"Fecha Ingreso",
"Creación",
"Modificación"],
colModel: [
{ name: "dep_id", index: "dep_nombre", editable: true, edittype: "select", formatter: 'select', editoptions: { width: 100, value: "#ViewData["Departamentos"]" }, width: 250, editrules: { required: true }, formoptions: { elmsuffix: '<span class="required">*</span>' }, stype: 'select', searchoptions: { sopt: ['eq'], value: "#ViewData["Departamentos"]" } },
{ name: "per_nombres", index: "per_nombres", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 }, editrules: { required: true }, formoptions: { elmsuffix: '<span class="required">*</span>' } },
{ name: "per_apellido_paterno", index: "per_apellido_paterno", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 }, editrules: { required: true }, formoptions: { elmsuffix: '<span class="required">*</span>' } },
{ name: "per_apellido_materno", index: "per_apellido_materno", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 } },
{ name: "per_dni", index: "per_dni", editable: true, width: 100, editoptions: { maxlength: 20, size: 17, dataInit: function (el) { $.mask.definitions['~'] = '[0-9kK]'; $(el).mask("?99.999.999-~"); } }, editrules: { required: true, custom: true, custom_func: is_rut }, formoptions: { elmsuffix: '<span class="required">*</span>' }, searchoptions: { dataInit: function (el) { $.mask.definitions['~'] = '[0-9kK]'; $(el).mask("?99.999.999-~"); } } },
{ name: "per_contrasena", editable: true, edittype: "password", hidden: true, width: 100, editoptions: { maxlength: 50, size: 17 }, editrules: { required: false, edithidden: true } },
{ name: "per_fecha_nacimiento", index: "per_fecha_nacimiento", editable: true, width: 100, editrules: { date: true, required: false }, formatter: 'date', formatoptions: { srcformat: 'SortableDateTime', newformat: 'd-m-Y' }, editoptions: { size: 17, dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } }, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } } },
{ name: "per_fotografia", index: "per_fotografia", editable: true, width: 250, edittype: "file", editoptions: { maxlength: 255, size: 32 } },
{ name: "per_estado_civil", index: "per_estado_civil", editable: true, edittype: "select", editoptions: { value: ":;S:Soltero;C:Casado;V:Viudo;D:Divorciado" }, width: 100, stype: 'select', searchoptions: { sopt: ['eq'], value: ":;S:Soltero;C:Casado;V:Viudo;D:Divorciado" } },
{ name: "per_sexo", index: "per_sexo", editable: true, edittype: "select", editoptions: { value: ":;M:Masculino;F:Femenino" }, width: 100, stype: 'select', searchoptions: { sopt: ['eq'], value: ":;M:Masculino;F:Femenino" } },
{ name: "per_direccion", index: "per_direccion", editable: true, width: 250, editoptions: { maxlength: 512, size: 32 } },
{ name: "per_cargo", index: "per_cargo", editable: true, width: 100, editoptions: { maxlength: 50, size: 32 } },
{ name: "per_email", index: "per_email", editable: true, width: 100, editoptions: { maxlength: 80, size: 32 }, editrules: { email: true, required: false, custom: true, custom_func: check_email } },
{ name: "per_fecha_ingreso", index: "per_fecha_ingreso", editable: true, width: 100, editrules: { date: true, required: false }, formatter: 'date', formatoptions: { srcformat: 'SortableDateTime', newformat: 'd-m-Y' }, editoptions: { size: 17, dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } }, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } } },
{ name: "per_creado_el", index: "per_creado_el", editable:false, search:false, width: 100, align: "center", formatter: "date" },
{ name: "per_modificado_el", index: "per_modificado_el", editable:false, search:false, width: 100, align: "center", formatter: "date" },
],
jsonReader: {
repeatitems: false,
id: "per_id"
},
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "per_apellido_paterno",
sortorder: "asc",
viewrecords: true,
gridview: true,
autoencode: true,
multiselect: true,
shrinkToFit: false,
caption: "Funcionarios",
editurl: "#Url.Action("AjaxEdit")",
height: '100%',
width: 935,
rownumbers: true,
rownumWidth: 40
});
$("#personal").jqGrid('hideCol', ["per_fotografia", "per_direccion"]);
$("#personal").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, search: false }, { width: 500 }, { width: 500 }, {}, { multipleSearch: false, multipleGroup: false });
$("#personal").jqGrid('filterToolbar', { searchOperators: false });
$.jgrid.edit.addCaption = "Agregar Funcionario";
$.jgrid.edit.editCaption = "Modificar Funcionario";
$.jgrid.edit.saveData = "¡El funcionario fue modificado! ¿Almacena los cambios?";
$.jgrid.formatter.date.newformat = 'd-m-Y H:i';
Thanks
Jaime
I think you should send the record ID for verification.
function check_email(value, colname) {
var rowid = jQuery('#personal').jqGrid('getGridParam', 'selrow');
$.ajax({
url: '#Url.Action("CheckEmail")',
data: { email: value, rowid: rowid },
type: 'POST',
async: false,
datatype: 'text',
success: function (data) {
if (!data) result = [true, ""];
else result = [false, colname + ": ya existe en el sistema"];
}
})
return result;
}
and so the server has any record can be checked with the ID does not match with the rowid.
Suppose the following grids
$(document).ready(function() {
$('#Clientes').jqGrid({colNames: ['Razón Social','Cuit','Dirección','Localidad','Teléfono','Tipo IVA','Mail','Saldo inicial','Facturar'],
colModel: [{ editable: true, editoptions: { "maxlength":70 }, editrules: { required: true }, name: 'RazonSocial' },
{ editable: true, editoptions: { dataInit: CuitMask, "maxlength":13 }, editrules: { custom: true, custom_func: ValidateCuit, required: true }, name: 'NidentFiscal' },
{ editable: true, editoptions: { "maxlength":70 }, editrules: { required: true }, name: 'Direccion' },
{ editable: true, edittype: 'select', editoptions: { dataUrl: '/Ciudad/CmbCiudad' }, editrules: { required: true }, name: 'Ciudad' },
{ editable: true, editoptions: { "maxlength":20 }, name: 'Telefono' }],
url: '/Clientes/List',
datatype: 'json',
mtype: 'POST',
pager: '#ClientesPager',
prmNames: { id: 'ClienteId' },
rowList: [10,15,20,25,30],
sortname: 'ClienteId',
subGrid: true,
subGridRowExpanded: function(subgridId, rowId) {
var subgridTableId = subgridId + '_t';
jQuery('#' + subgridId).append('<table id="' + subgridTableId + '"></table>');
var subgridPagerId = subgridId + '_p';
jQuery('#' + subgridId).append('<div id="' + subgridPagerId + '"></div>');
$('#' + subgridTableId).jqGrid({colNames: ['Fecha','Importe'],
colModel: [{ name: 'Fecha' },
{ editable: true, editrules: { number: true }, formatter: 'currency', formatoptions: { prefix: '$' }, name: 'Importe' }
],url: '/Honorarios/DetailSubgrid?id=' + rowId, datatype: 'json', mtype: 'POST', pager: '#' + subgridPagerId,
prmNames: { id: 'HonorarioId' },
rowList: [10,15,20,25,30],
sortname: 'HonorarioId',
viewrecords: true,
width: 600,
height: '100%'}).jqGrid('navGrid', '#' + subgridPagerId,{ search: false },{ url: '/Honorarios/Update', closeAfterEdit: true },{ url: '/Honorarios/Update', closeAfterEdit: true },{ url: '/Honorarios/Delete' });
},
viewrecords: true,
width: 1000,
height: '100%'
}).jqGrid('navGrid', '#ClientesPager',{ search: false },{ url: '/Clientes/Update', width: 500, closeAfterEdit: true }, { url: '/Clientes/Update', width: 500, closeAfterEdit: true }, { url: '/Clientes/Delete' });
});
I need to pass the ClienteId parameter when a record is added or edited in the sub grid
This should be done using postdata?
something like
postData: {ClienteId: row_id}
the solution is using
editData: { ClienteId: rowId }
Tanks #tpeczek