jqGrid master grid problem - jqgrid

I have a master grid and want to display the results on row click from master grid in detail grid..
I am not able to fetch the data on my detail grid ....
$(document).ready(function(){
{ $("#navmenu-v li").hover(
function() {
$(this).addClass("iehover"); },
function() {
$(this).removeClass("iehover");
} );
jQuery("#list10").jqGrid({
sortable:true,
url: '/cpsb/json/jsonpageheader.txt',
datatype:'json',
colNames:['Order','Load', 'Gate Time', 'Stop','Customer','Status'],
colModel:[
{
name:'orderNumber',
index:'orderNumber',
width:130,
align:"center",
sorttype:"int"
},
{
name:'loadNumber',
index:'loadNumber',
width:100, align:"center",
sorttype:"int"
},
{
name:'latestTime',
index:'latestTime',
width:160,
align:"center"
},
{
name:'stopSeq',
index:'stopSeq',
width:80,
align:"center",
sorttype:"int"
},
{
name:'customerNumber',
index:'customerNumber',
width:100,align:"center",
sorttype:"int"
},
{
name:'orderStatus',
index:'orderStatus',
width:80, align:"center"
} ],
rowNum:10,
rowList:[10,20,30],
jsonReader : {repeatitems: false,
root: function(obj) {
return obj;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
pager: '#pager10',
sortname: 'Gate Time',
sortorder: "desc",
viewrecords: true,
multiselect: true,
caption: "Order Header",
onSelectRow: function(ids) {
if(ids == null) {
ids=0;
if(jQuery("#list10_d").jqGrid('getGridParam','records') >0 )
{
jQuery("#list10_d").jqGrid('setGridParam',{url:"/cpsb/unprocessedOrders.do?method=getUnprocessedOrderDetails"+ids,page:1});
jQuery("#list10_d").jqGrid('setCaption',"Order Header: "+ids).trigger('reloadGrid'); }
}
else {
jQuery("#list10_d").jqGrid('setGridParam',{url:"/cpsb/unprocessedOrders.do?method=getUnprocessedOrderDetails"+ids,page:1});
jQuery("#list10_d").jqGrid('setCaption',"Order Details: "+ids).trigger('reloadGrid');
}
} ,
height:'100%'
});
jQuery("#list10").jqGrid('navGrid','#pager10',{excel:true, add:false,edit:false,del:false,searchtext:"Filter"},{},{},{},{multipleSearch:true});
$("#list10").jqGrid('hideCol', 'cb');
jQuery("#relCasePick").click( function(){
var id = jQuery("#list10").jqGrid('getGridParam','selarrrow');
alert(id);
});
jQuery("#list10_d").jqGrid({
height: 100,
url:'/cpsb/unprocessedOrders.do?method=getUnprocessedOrderDetails',
datatype: "json",
colNames:['Order','SKU', 'UPC', 'Item Description','Quantity Ordered','Teach in Hold?'],
colModel:[ {name:'Order',index:'', width:55},
{name:'SKU',index:'sku', width:55},
{name:'UPC',index:'qty', width:40, align:"right"},
{name:'Item Description',index:'unit', width:150, align:"right"},
{name:'Quantity Ordered',index:'quantity', width:150,align:"right", sortable:false, search:false},
{name:'Teach in Hold?',index:'teachInId', width:150, align:"right"}, ],
rowNum:5,
rowList:[5,10,20],
jsonReader : {repeatitems: false,
root: function(obj) {
return obj;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
pager: '#pager10_d',
sortname: 'SKU',
viewrecords: true,
sortorder: "asc",
multiselect: true,
caption:"Order Detail"
}).navGrid('#pager10_d',{add:false,edit:false,del:false}, {},{},{},{multipleSearch:true});
jQuery("#ms1").click( function() {
var s;
s = jQuery("#list10_d").jqGrid('getGridParam','selarrrow');
alert(s); });
}});
is there a way that i will not pull the other grid data and instead of that only on row click from 1st grid i will get the values for next grid
Yes next grid is detail grid... what is basically do is to fetch the corresponding values for order number from master grid and display it in detail ....
for second part
is there a way that i will not pull the other grid data and instead of that only on row click from 1st grid i will get the values for next grid?
Instead of getting all the data from server can I just pull the data only on selecting the row from first grid...
Moreover, I have a button call release to case pick and clicking on that button I have send the selected rows to database....I hav ea action class for that but how I have to send that selected rows.
jQuery("#relCasePick").click( function(){
var id = jQuery("#list10").jqGrid('getGridParam','selarrrow');
alert(id);
});
can i do something like jQuery(("#list10").jqGrid('getGridParam','action class URL')
can I do something like this for sending the rows to server
jQuery("#relCasePick").click( function(){
var rows= jQuery("#list10").jqGrid('getRowData');
var paras=new Array();
for(var i=0;i<rows.length;i++){
var row=rows[i];
paras.push($.param(row));
}
$.ajax({
type: "POST",
url: "/cpsb/unprocessedOrders.do?method=releaseToCasePick",
data: paras.join('and'),
success: function(msg){
alert(msg);
}
});

In your current code you set url for the detail grid like
"/cpsb/unprocessedOrders.do?method=getUnprocessedOrderDetails"+ids
do you want probably have
"/cpsb/unprocessedOrders.do?method=getUnprocessedOrderDetails&someParameter="+ids
Could you also reformulate your second question
is there a way that i will not pull
the other grid data and instead of
that only on row click from 1st grid i
will get the values for next grid?
What do you mean under "to get the values for next grid"? Is next grid is detail grid? From where you want to get the values? With respect of getRowData method (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods#grid_related_methods) you can get full data from the selected row of the master grid, but from which source you plan to get data for the detail grid?

Related

Retain filter text in filter toolbar on grid reload

I'm using jqgrid in which i'm trying to retain the filter text after the grid reload.
I have cell update functionality,
//Code:
$.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) {
myfilter = $('#TransactionsGrid').jqGrid("getGridParam", "postData").filters;
Loadgrid($('#TransactionsGrid').getGridParam('page'));
}
After the successful udpate of the cell i'm reloading the grid for the cell to reflect the udpated values. In the OnComplete i'm getting the filter assigned to a golbally declared variable(myfilter).
//Grid:
datatype: 'local',
hoverrows: false,
colNames: colHeader,
colModel: colname,
localReader: { id: 'TransactionId' },
rowNum: 10,
hidegrid: false,
rownumbers: true,
pager: '#TransactionsGridPager',
viewrecords: true,
caption: "Transaction Details",
height: 'auto',
scrollOffset: 0,
page: PageNumber,
gridview: true,
shrinkToFit: true,
autoencode: true,
ignoreCase: true,
mySelection: {},
onInitGrid: function () {
// get reference to parameters
var p = $(this).jqGrid("getGridParam");
// set data parameter
p.data = gridData.BuildTransactionsDataTable;
},
In grid reload(ajax function is called), once the grid is loaded i'm re assigning the filter. In this place i'm getting the filtered results in the grid exactly bu the text which i used to filter the results is not in the filter toolbar. Its empty.
GridReload(Retain filter):
jQuery("#TransactionsGrid").jqGrid({
});
if (myfilter) {
var searchFiler = JSON.parse(myfilter).rules[0].data, grid = $("#TransactionsGrid"), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: JSON.parse(myfilter).rules[0].field, 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 }]);
}
Now i need the filtered text to be retained in the filter toolbar. how can i achieve this?

Add check boxes in Jquery grid view

I have the following code in page which binds the data to j query grid.
Now i want to add one more column for check-boxes to the existing grid and when i select some check boxes and press some button .. i need to get the selected row values .
I have seen some tutorials for this they mentioned about some formatter .... but they are not clear
Please help me to achieve this.
Thanks in advance.
Code:
$(document).ready(function () {
$("#btn_GenerateEmpList").click(function () {
var firstClick = true;
if (!firstClick) {
$("#EmpTable").trigger("reloadGrid");
}
firstClick = false;
var empId= $("#txt_emp").val();
$.ajax({
type: "POST",
url: "PLBased.aspx/GetEmpNames",
data: JSON.stringify({ empId: empId}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
result = result.d;
jQuery("#EmpTable").jqGrid({
datatype: "local",
colNames: ['Emp Name'],
colModel: [
{ name: "EmpName", Index: "EmpName", width: 80 }
],
data: JSON.parse(result),
rowNum: 10,
rowList: [5, 10, 20],
pager: '#pager',
loadonce: false,
viewrecords: true,
sortorder: 'asc',
gridview: true,
autowidth: true,
sortname: 'EMPID',
height: 'auto',
altrows: true,
});
},
error: function (result) {
alert("There was some error ");
}
});
});
});
You can use customformatter to show checkbox in the column. For this, you can write the code as below in your jqGrid Code.
colNames: ['Id','Emp Name','Emp Checkbox'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'EmpName', Index: 'EmpName', width: 80 },
{ name: 'Empchk', Index: 'Empchk', width: 50, align: 'center', editable: true, edittype: "checkbox", editoptions: { value: "true:false" },
formatter: generateEmpCheckBox, formatoptions: { disabled: false } }
],
formatter function code as below,
function generateEmpCheckBox(cellvalue, options, rowObject) {
var checkedStr = "";
if (cellvalue == true) {
checkedStr = " checked=checked ";
}
return '<input type="checkbox" onchange="UpdateEmpcheckbox(' + rowObject.Id + ',this)" value="' + cellvalue + '" ' + checkedStr + '/>';
}
function UpdateEmpcheckbox(selectedId, chkBox) {
if ($(chkBox).prop("checked")) {
//you can write an ajax here, to update the server
//when the checkbox is checked
}
else if (!($(chkBox).prop("checked"))) {
//you can write an ajax here to update the server
//when the checkbox is unchecked
}
return false;
}
Set the option multiselect:true which will add column of checkboxes. Then add
$('#EmpTable').jqGrid('getGridParam', 'selarrrow')
will return an array of selected id's.

Passing extra parameters in JQGrid delete with multiselect

I want to have delete functionality in my JQGrid for deleting multiple rows. My code looks like this:
{height:180,mtype:"POST",closeAfterDel:true, url:'gridedit.jsp',reloadAfterSubmit:true,
onclickSubmit: function (options, rowid) {
var rowData = jQuery(this).jqGrid('getRowData', rowid);
var params ={amount:rowData.amount,account:rowData.account.replace(/-/g,"")};
return params;
},
afterSubmit: function () {
$(this).jqGrid('setGridParam', {datatype:'json'});
return [true,''];
}
}
I want to make deletions as per the values of the column rowData.account
The problem is that when I select multiple rows, I can see that the grid passes all the rowid's back to the edit URL, but only passes the rowData.account value of the first row !
Is there a way to make the grid pass back all the values? I cant delete based on the row id on the back end as my database does not have any row id's.
Please help.
Here is my grid code:
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
datatype: 'json',
url:'gridfeeder.jsp?ctlSelectedDate=<%= request.getParameter("ctlSelectedDate")%>',
colNames: ['Date', 'Account ', 'Amount', 'Code'],
colModel: [
//First Column, DATE
{name: 'adate', index: 'adate', width: 300, sorttype: 'date', align: 'center',datefmt: 'Y-m-d',
editable:true, formatter: myLinkFormatter, editoptions:{
dataInit:function(elem)
{
jQuery(elem).datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true
});
}}, search:true, stype:'text',searchoptions:{
dataInit:function(elem)
{
jQuery(elem).datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true
});
}
}
},
//Second Column, ACCOUNT
{ name: 'account', index: 'account', width: 300, align: 'center', sorttype: 'string', editable:true,
search:true, stype:'text',editrules:{custom:true, custom_func:
//Validation for this column for editing
function(value, colname) {
if (value.length<9 || value.length>11)
return [false,"Invalid Input"];
else
return [true,""];
}
},
searchrules:{custom:true, custom_func:
//Validation for this column for searching
function(val, colname) {
if (val.length<9 || val.length>11)
return [false,"Invalid Input"];
else
return [true,""];
}
}
},
//Third Column, AMOUNT
{ name: 'amount', index: 'amount', width: 300, align: 'center', sorttype: 'float', editable:true,
editrules:{number:true}, search:true, stype:'text'
},
//Fourth Column, CODE
{ name: 'code', index: 'code', width: 300, align: 'center', sorttype: 'float', editable:true,
search:true, stype:'text'
}
],
pager: "#pager", //Identifying the navigation bar
rowNum: 500, // how many rows to display on page 1
rowList: [500,1000, 2000, 3000,4000], //values for the dropdown which specifies how many rows to show
sortorder: "desc", //the order of sorting by default
viewrecords: true, // displays total number of rows
gridview: true,
autoencode: true,
height:400, //height of the grid
ignoreCase:true,// case insensitive search
multiselect:true, // checkboxes before each row
multiboxonly: true,
loadonce:true, //for client side sorting, searching and pagination
caption:"This is me" // caption for the grid header
here is the navgrid section :
}).navGrid('#pager',{edit:true,add:true,del:true,search:true,refresh:true},
// Options for EDIT
{height:280,mtype: "POST",closeAfterEdit: true,reloadAfterSubmit:true, url:'gridedit.jsp',
recreateForm: true,
//set some properties beofre the dialog box is seen by the user
beforeShowForm: function(form) {
/*$('#adate',form).attr('readonly','readonly');
$('#account',form).attr('readonly','readonly');*/
$('#adate',form).hide();
$('#account',form).hide();
},
// what happens when the user clicks submit. passing extra parameters
onclickSubmit: function (options, postdata) {
var rowid = postdata[this.id + "_id"]; // postdata.list_id
var dataF = jQuery('#list').jqGrid ('getCell', rowid, 'account');
return {account:dataF.replace(/-/g,"")};
},
// changing the datatype
afterSubmit: function () {
$(this).jqGrid("setGridParam", {datatype: 'json'});
return [true,''];
}
},
//ADD options
{height:280,mtype:"POST", closeAfterAdd:true, reloadAfterSubmit:true, url:'gridedit.jsp',
beforeShowForm: function(form) {
/*var cm = jQuery("#list").jqGrid('getColProp','adate');
alert(cm);
cm.editable = false;
$('#adate',form).attr('readonly','readonly');
$('#account',form).attr('readonly','readonly');*/
$('#adate',form).show();
$('#account',form).show();
},
//Change the datatype
afterSubmit: function () {
$(this).jqGrid("setGridParam", {datatype: 'json'});
return [true, ""];
}
},
{height:180,mtype:"POST",closeAfterDel:true, url:'gridedit.jsp',reloadAfterSubmit:true,
/* onclickSubmit: function (options, rowid) {
var rowData = jQuery(this).jqGrid('getRowData', rowid);
var params ={account:rowData.account.replace(/-/g,"")};
return params;
},*/
delData: {
account: function() {
var sel_id = $("#list").jqGrid('getGridParam', 'selrow');
var value = $("#list").jqGrid('getCell', sel_id, 'account');
return value.replace(/-/g,"");
}
},
afterSubmit: function () {
$(this).jqGrid('setGridParam', {datatype:'json'});
return [true,''];
}
}
);
function myLinkFormatter(cellvalue, options, rowObject) {
return "<a href='account094act.jsp?GETDATE=" + cellvalue + "&GETACC=" + rowObject[1] + "'>" + cellvalue + "</a>";
}
jQuery("#refresh_list").click(function(){
jQuery("#list").setGridParam({datatype: 'json'});
jQuery("#list").trigger("reloadGrid");
});
});
One uses mostly unique values which are the best for your situation as rowids. Probably you should consider to use the value from account column as rowid? You don't posted the full code of jqGrid which you you and don't posted JSON/XML data used for filling the grid. So it's difficult to give an exact advice to you.
You can consider to place key: true property in colModel in the definition of the column account. If all values from the column are unique (the values are different in all rows of the grid) then you can use the settings. In the case the rowid (the value of id attribute of <tr> elements of the grid) will be assigned the same as the values from account column.
All editing operation sends id of the editing row. So you will get account sent to the server. In case of multiselect: true jqGrid send comma separated list of rowids. In your case you will get on the server comma separated list of deleted accounts. Probably you can get all other information (like amount), if it's required, based on the account value. If account value are really unique and you have all data on the server that you can get any information which corresponds to account chosen.

Jqgrid - Multiselectected rows no longer persist after triggering a JqGrid reload

I have a multi-selected Jqgrid. Initially on loading the grid with the Json reponse from the server, the multiselected rows persist correctly as I navigate from one page to another.
The ids of the rows selected are stored in an Array and this Array is updated on paging. I use this array to check the already selected rows on returning back to the page. Sorting works fine and I faced no problem so far.
On applying a filter on a particular field, a request is sent to the server which returns the new filtered result in Json and then reloads the grid with it.
The first page is rendered correctly with the selected rows checked but on changing the page and returning back the rows are no longer selected. However the array still contains the ids and is also containing the new added ids.
How is that the Multiselected feature stops working after a reload??? Or is it not even because of the reload??
Here is the code:
<script type='text/javascript'>
var selectedFieldsMap={};
var selectedFieldsObjs = [];
var selectedFieldIds = [];
$(function() {
//function called when applying a filter
$('#ApplyFilterBtn').click(function() {
saveGridState();
$('#Grid').setGridParam({ url: getUrl() });
$('#Grid').trigger('reloadGrid');
});
});
function saveGridState() {
var selectedIds = $('#Grid').getGridParam('selarrrow');
$('#Grid').data(current_page, selectedIds);
_.each(selectedIds, function(id) {
selectedFieldIds.push(id);
});
var idsToBeAdded = _.difference(selectedIds, getExistingRowIdsForGrid('#list'));
selectedFieldsMap[current_page] = idsToBeAdded;
_.each(idsToBeAdded, function(id) {
selectedFieldsObjs.push($('#Grid').getRowData(id));
});
}
function getExistingRowIdsForGrid(gridSelector) {
var existingFields = $(gridSelector).getRowData();
return _.map(existingFields, function(obj) { return obj.Id; });
function resetFilterValuesAndReloadGrid() {
//reset filters and set grid param
$('#Grid').setGridParam({
sortname: 'Id',
sortorder: 'asc',
page: 1,
url: getUrl()
});
$('#Grid').jqGrid('sortGrid', 'Id', true);
$("#Grid").trigger('reloadGrid');
}
$("#Grid").jqGrid({
url: getUrl(),
datatype: "json",
edit: false,
add: false,
del: false,
height: 330,
mtype: 'GET',
colNames: ['Id', 'Type', 'Category'],
jsonReader: {
root: "DataRoot",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
cell: "",
id: "0"
},
colModel: [
{ name: 'Id', index: 'Id', width: 95, align: 'center', sorttype: "int" },
{ name: 'Type', index: 'ValueTypeName', width: 110, align: 'left',sortable: true },
{ name: 'Category', index: 'Category', width: 72, align: 'left', sortable: true },
],
pager: '#pager',
rowNum: pageCount[0],
rowList: pageCount,
sortname: 'Id',
sortorder: 'asc',
viewrecords: true,
gridview: true,
multiselect: true,
loadComplete: function () {
if(selectedFieldIds) {
$.each(_.uniq(selectedFieldIds), function(index, value) {
$('#Grid').setSelection(value, true);
});
}
} ,
onPaging : function () {
saveGridState();
},
loadBeforeSend: function() {
current_page = $(this).getGridParam('page').toString();
} ,
onSortCol: function () {
saveGridState();
}
});
}
function getUrl() {
//return url with the parameters and filtering
}
</script>
The problem is solved, what happens is on reload of the grid the function which checks the row is called as it is in the document.ready()and the on grid loadComplete the same function is called. Toggle happens and the selection is removed. I've added an if condition to see if the grid is selected or not.
loadComplete: function () {
var selRowIds = jQuery('#Grid').jqGrid('getGridParam', 'selarrrow');
if (selRowIds.length > 0) {
return false;
} else {
var $this = $(this), i, count;
for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {
$this.jqGrid('setSelection', idsOfSelectedRows[i], false);
}
}
}

validate jqgrid data on the server, callback function

I am using autocomplete in a textbox on my jqgrid. But i should not allow the user to select the same item twice. Because of pagination he wont see all data all times. Is there a way that on sending new row to server check for duplicate data in the server and send a status back to jqgrid maybe poping up an alert sayign "row already exist on table". What would be the bst approach to do this validation and notify the user? thanks.
$("#assessmentproduct").jqGrid({
url: 'orthofixServices.asmx/GetProductList',
colNames: ['id', 'Product Description', 'Commission Rate'],
colModel: [
{ name: 'id', hidden: true },
{ name: 'description', index: 'desc', width: 320, editable: true },
{ name: 'commissionrate', index: 'com', width: 120, editable: true, unformat: percentUnFormatter, formatter: percentFormatter, editrules: { number: true} }
],
serializeRowData: function(data) {
var params = new Object();
params.id = 0;
params.prdid = $("#prdid").val();
params.description = data.description;
params.commissionrate = data.commissionrate;
var result = JSON.stringify({ 'passformvalue': params, 'oper': data.oper, 'id': data.id });
return result;
},
mtype: "POST",
rowNum: 4,
height: 93,
width: 400,
pager: '#assessmentpager',
editurl: "orthofixServices.asmx/ModifyProductList"
});
$("#assessmentproduct").jqGrid('navGrid', '#assessmentpager', { add: false, edit: false, del: true, refresh: false, search: false }, {}, {}, { serializeDelData: function(postData) {
return JSON.stringify({ 'passformvalue': null, 'oper': postData.oper, 'id': postData.id });
}
});
$("#assessmentproduct").jqGrid('inlineNav', '#assessmentpager', { addParams: { position: "last", addRowParams: {
"errorfunc": duplicateRow, "aftersavefunc": function() { var grid = $("#assessmentproduct"); reloadgrid(grid); }
}
}, editParams: { "aftersavefunc": function() { var grid = $("#assessmentproduct"); reloadgrid(grid); } }
});
You should just hold the simple rule: if an error occur on the server (for example because of validation error) the server response should contains some error HTTP status code. In the case error message will be displayed to the user.
The exact error processing and the displayed error message format depends from the editing mode which you use. In case of inline editing I would recommend you to use errorfunc and restoreAfterError parameters of the editRow method. In case of form editing the errorTextFormat callback can be very helpful.

Resources