jqGrid inline deleting the row using clienArray - jqgrid

$('#jqGrid').navGrid('#jqGridPager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate: true,
checkOnSubmit: true,
closeAfterEdit: true,
// afterShowForm: PayTypeValidation,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
// afterShowForm: PayTypeValidation,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
//delete
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
}
});
Above is the code for add and edit but the delete section doesnot work,please suggest the code for inline delete of row in grid with clientarray

Related

jqgrid - filter not working on some columns

In the below grid, filtertooblar works for few columns and does not for few other.
I have verified that index and name for colModel is same for the columns for which filtering is not working.
The filters are coming through correctly when I check it in beforesearch event.
Here is one of the colModels that does not filter:
7:
formoptions: {label: 'If Yes to previous question, would your familiari… affect how you view this case or those involved?'}
frozen: false
index: "ifyestopreviousquestionwouldyourfamiliaritywiththeparticipantsaffecthowyouviewthiscaseorthoseinvolved"
name: "ifyestopreviousquestionwouldyourfamiliaritywiththeparticipantsaffecthowyouviewthiscaseorthoseinvolved"
search: true
sortable: true
And the filter is coming as below
{"groupOp":"AND","rules":[{"field":"ifyestopreviousquestionwouldyourfamiliaritywiththeparticipantsaffecthowyouviewthiscaseorthoseinvolved","op":"cn","data":"Yes"}]}
Can you please help? Thank you very much
var grid = $("#list-grid").jqGrid({
datatype: "local",
height: 'auto',
colNames: colNames,
colModel: colModels,
data: rows,
gridview: true,
sortable: true,
autowidth: true,
shrinkToFit: false,
editable: true,
scrollOffset: true,
ExpandColClick: true,
viewsortcols: [true, 'vertical', true],
loadonce: true,
onSelectRow: function() {
return false;
},
search:
{
caption: "Search...",
Find: "Find",
Reset: "Reset",
odata: ['equal', 'not equal', 'less', 'less or equal', 'greater', 'greater or equal', 'begins with', 'does not begin with', 'is in', 'is not in', 'ends with', 'does not end with', 'contains', 'does not contain'],
groupOps: [{ op: "AND", text: "all" }, { op: "OR", text: "any" }],
matchText: " match",
rulesText: " rules"
},
caption: '<h4>Report</h4>',
regional: 'en',
ondblClickRow: function(rowid) {
jQuery(this).jqGrid('viewGridRow', rowid);
},
loadComplete: function() {
var $this = $(this), ids = $this.jqGrid('getDataIDs'), i, l = ids.length;
for (i = 0; i < l; i++)
{
$this.jqGrid('editRow', ids[i], true);
}
},
sortable:
{
update: function(permutation) {
}
},
pager: "#pager"
}).navGrid('#pager', { view: true, del: false, edit: false, add: false, search: false, refresh: false,width: 800 },
{view:false}, // Edit Options
{ view: false}, // Add Options
{}, // Del Options
{ width: 800 }, // Search Options
{
closeOnEscape: true,
width: 1000,
beforeShowForm: function($form)
{
console.log('form', $form);
$form.find("td.DataTD").each(function() {
var html = $(this).html(); // <span> </span>
if (html.substr(0, 6) === " ")
{
$(this).html(html.substr(6));
}
});
}
} // View Options
).filterToolbar({
groupOp: 'AND',
defaultSearch: 'cn',
searchOnEnter: true,
searchOperators: false,
stringResult: true,
ignoreCase: true,
beforeSearch: function () {
var postData = $("#list-grid").jqGrid('getGridParam', 'postData');
console.log(postData);
}
});
//grid.data = row; // replace the data array to another data
//$("#list-grid").trigger("reloadGrid", { current: true });
//$("#list-grid").jqGrid('setFrozenColumns');
},
});
$("#list-grid").on("jqGridToolbarBeforeSearch", function (e) {
var filters = $(this).jqGrid("getGridParam", "postData").filters;
console.log(filters);
if (typeof filters === "string") {
filters = $.parseJSON(filters);
}
return e.result; // forward the result of the last event handler
});
</text>
}
});

jqgrid call a custom function when clicked on save button in place of edit url

Below is my code
onSelectRow : function(id) {
$("#order_list").setGridParam({
'editurl' : 'clientArray'
});
}
});
jQuery("#order_list").jqGrid('navGrid',"#pjmap",{edit:false,add:false,del:false,search: false, refresh:false,cloneToTop:true});
jQuery("#order_list").jqGrid('inlineNav', '#order_list_toppager',{add:false,del:false,edit:true,search: false, refresh:false,cloneToTop:true, viewtext:"View", edittext:"Edit", savetext:"Save", canceltext:"Cancel"});
Hei
You can create your own functions for saving by adding a function in parameters for aftersavefunc. My code is like this:
$('#jqGridOutput').navGrid("#jqGridPagerOutput", { edit: false, add: false, del: true, refresh: false, view: false }, {}, {}, delSettings);
$('#jqGridOutput').inlineNav('#jqGridPagerOutput',
{
edit: true,
del: true,
add: true,
cancel: false,
editParams: {
aftersavefunc: function (id) { //what should happen on save edit row },
keys: true,
},
addParams: {
keys: true,
position: "last",
aftersavefunc: function (id) { //what should happen on save new row }
},
});
I think, this is what you are looking for if i understand you correctly?

Cancel edit event in jqGrid inline edit

I'm using jqgrid inline edit in which i have a scenario to invoke the "cancel edit" button event and throw a message "Are you sure to cancel?".
//Code:
//Unload the grid.
$('#CommentsData').jqGrid('GridUnload');
//Comments grid start.
$("#CommentsData").jqGrid({
datastr: tableSrc,
hoverrows: false,
datatype: "jsonstring",
jsonReader: {
id: 'CommentId',
repeatitems: false
},
height: 'auto',
width: 'auto',
hidegrid: false,
gridview: true,
sortorder: 'desc',
sortname: 'DateTime',
pager: '#CommentsPager',
rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: false, // disable current view record text like 'View 1-10 of 100'
caption: "Comments",
colNames: ['DateTime', 'UserName', 'Comments'],
colModel: [
{
name: 'DateTime', index: 'DateTime', width: 120, formatter: "date", sorttype: "date",
formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i A" }
},
{ name: 'UserName', index: 'UserName' },
{ name: 'CommentText', index: 'CommentText', editable: true }],
//Events to add and edit comments.
serializeRowData: function (postdata) {
var filterResult;
var jsonResult;
if (tableSrc == "")
jsonResult = $.parseJSON(commentDetails);
else
//Parse values bind to the comments.
jsonResult = $.parseJSON(tableSrc);
var newResult = new Object();
//Check if operation is edit.
if (postdata.oper == "edit") {
//Filter the edited comments from main source.
newResult = Enumerable.From(jsonResult).Where(function (s) { return s.CommentId = postdata.id }).First();
newResult.CommentText = postdata.CommentText;
}
else {
filterResult = Enumerable.From(jsonResult).First();
newResult.CommentText = postdata.CommentText;
newResult.TransactionId = filterResult.TransactionId;
newResult.TaskId = filterResult.TaskId;
}
filterResult = JSON.stringify(newResult);
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
selectTaskComment = false;
$('#dialog').dialog("close");
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
rowList = $('.ui-pg-selbox').val();
Loadgrid($("#TransactionsGrid").getGridParam('page'));
}
},
onSelectRow: function (id) {
selectTaskComment = true;
var thisId = $.jgrid.jqID(this.id);
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
var selectValues = jQuery('#CommentsData').jqGrid('getRowData', id);
thisId = $.jgrid.jqID(this.id);
if (selectValues.UserName == '#ViewBag.UserName' || '#ViewBag.IsAdmin' == 'True') {
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
}
else {
$("#" + thisId + "_iledit").addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
});
jQuery("#CommentsData").jqGrid('navGrid', '#CommentsPager', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {},
{
//Delete event for comments
url: '#Url.Action("UpdateComments", "Home")',
serializeDelData: function (postData) {
return {
resultData: JSON.stringify(postData.id),
action: JSON.stringify(postData.oper),
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
beforeSubmit: function () {
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
return [true, '', ''];
},
afterSubmit: function (response, postdata) {
selectTaskComment = false;
Loadgrid($("#TransactionsGrid").getGridParam('page'));
return [true, '', ''];
}
});
$('#CommentsData').jqGrid('inlineNav', '#CommentsPager', { edit: true, add: true, save: true, del: false, cancel: true });
$("#CommentsData_iledit").addClass('ui-state-disabled');
$("#del_CommentsData").addClass('ui-state-disabled');
In which event i have to write the code and throw the alert message?
Also if possible, need to know if the above code could be optimized. Because the delete event is written in a separate place comparing edit and add. I'm bit confused if this is right method.
The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.

JQGrid MultiSelect Filter option populate based on column's distinct value

I am using JQGrid with Multiselect filter to filter individual columns.
Currently I am populating filters(e.g. SkillCategory column) using database master values
{
name: 'SkillCategory', index: 'SkillCategory', width: '5%', sortable: true, resizable: true, stype: 'select',
searchoptions: {
clearSearch: false,
sopt: ['eq', 'ne'],
dataUrl: 'HttpHandler/DemandPropertyHandler.ashx?demprop=skillcat',
buildSelect: createSelectList,
attr: { multiple: 'multiple', size: 4 },
position: {
my: 'left top',
at: 'left bottom'
},
dataInit: dataInitMultiselect
}
},
This approach is populating all available master list(for SkillCategory) in to filter.
I would like to show only available filter value based on those are present in available rows for particular column(for SkillCategory).
This should show "Programming" and "Data" as option for SkillCategory filter as rows contains only "Programming" and "Data" value for that column.
I found below code(sorry forgot the link)
getUniqueNames = function (columnName) {
var texts = $("#listTableSupply").jqGrid('getCol', columnName), uniqueTexts = [],
textsLength = texts.length, text, textsMap = {}, i;
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);
}
}
return uniqueTexts;
}
buildSearchSelect = function (uniqueNames) {
var values = ":All";
$.each(uniqueNames, function () {
values += ";" + this + ":" + this;
});
return values;
}
setSearchSelect = function (columnName) {
$("#listTableSupply").jqGrid('setColProp', columnName,
{
searchoptions: {
sopt: ['eq', 'ne'],
value: buildSearchSelect(getUniqueNames(columnName)),
attr: { multiple: 'multiple', size: 3 },
dataInit: dataInitMultiselect
}
}
);
}
Calling setSearchSelect("SkillCategory")
.... 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: "Refresh", edit: false, add: false, del: false, search: false
}, {}, {}, {}, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true
}); .....
But seems its not working. Only "All" value is populated.
Any idea how can I achieve this.
Update1:
As per Oleg's suggestion below is the working code which worked for me.
initializeGridFilterValue = function () {
//jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("SkillCategory");
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);
}
And setting it from loadComplete event like below:
function loadCompleteHandler1() {
initializeGridFilterValue();
}
I see that you use the code from my old answer. About your problem: I suppose that you first call filterToolbar which creates the filter toolbar and only later you call setSearchSelect which set new searchoptions.value property. Another possible problem is that you call setSearchSelect before the data will be loaded in the grid. If you use datatype: "local" with data parameter then the data are filled in the grid during creating of the grid. If you use datatype: "json" then you should first load the data from the server and then call setSearchSelect and filterToolbar inside of loadComplete. For example if you use loadonce: true then you can test the value of datatype parameter inside of loadComplete. If the value is "json" then you made initial loading of the data. So you should call setSearchSelect, then if required call destroyFilterToolbar and finally call filterToolbar to create filter toolbar which selects will have all required values.

JqGrid Width resizing Issue with Browser resize

Can I set JqGrid width in a way that it automatically resizes with browser width.
Have tried using this.
autowidth:true,
.....
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
Resizing isnt working as expected, When I resize the browser I expect grid to resize accordingly to that of browser width.
UPDATE:
$(function () {
$grid = $("#table");
$grid.jqGrid({
url: '../../Services/OrderService.asmx/getGlbOrders',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
//if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records",
id: "d.names"
},
colModel: [
{ name: 'select', label: 'select', width: 50,
formatter: function radio(cellValue, option) {
return '<input type="radio" name="radio_' + option.gid + '" value=' + cellValue + ' />';
}
},
{ name: 'code', label: 'Order ID' },
{ name: 'qty', label: 'Quantity' },
{ name: 'qtyr', label: 'Remaining Qty'},
{ name: 'uts', label: 'Units' },
{ name: 'status', label: 'Status' },
],
rowNum: 10,
rowList: [10, 20, 300],
sortname: 'name',
sortorder: "asc",
pager: "#pager",
viewrecords: true,
gridview: true,
rownumbers: true,
height: 250,
autowidth: true,
caption: 'Global Order List'
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
})
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
change your code from:
$(function () {
$grid = $("#table");
$grid.jqGrid({
// etc..
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
})
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
to:
$(function () {
$grid = $("#table");
$grid.jqGrid({
// etc..
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
});
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
You have forgotten a semicolon after the end of your jqGrid function. Then the code that comes after your function is ignored.

Resources