JQGrid with Bootstrap Multiselect and Custom Save - jqgrid

I have 2 requirements I need to solve for. I'm using a JQGrid on an aspx page with other form controls. Saving the main form generates a database id that is populated in a hidden field. If the hidden field is empty, I don't want to save the grid record because I need the db id first. If the hidden field has a value, I want to save the row with a editurl.
The second part is related to a Bootstrap multiselect in one of the grid columns (I need the filtering capability). When a user selects a value from the multiselect I'd like to populate the PERNR column with the value selected. I can't use the onchange event for the multiselect since if the user doesn't change from the first option obviously it won't trigger the event.
How can I solve these 2 issues?
var roleDdlItems = $.parseJSON($("input[id$='hdfRoleDdlItems']").val());
$("#grdParticipants").jqGrid({
jsonReader: {
repeatitems: false,
root: 'Table',
page: function (obj) { return 1; },
total: function (obj) { return 2; },
records: function (obj) { return obj.ItemCount; },
id: "0"
},
caption: getParticipantCaption(),//"Participants",
pgbuttons: false,
recordtext: "Total: {2}",
emptyrecords: "",
loadtext: "Loading...",
pgtext: "",
datatype: function () {
UpdateParticipant("getParticipants");
},
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
// serializeGridData: function (postData) { return JSON.stringify(postData); },
colNames: ['Id', 'PERNR', 'Name', 'Email', 'RoleId', 'Role', 'Active', 'Updated'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true, editable: true, hidedlg: true },
{ name: 'PERNR', index: 'PERNR', hidden: true, editable: true, hidedlg: true },
{ name: 'Name', index: 'Name', width: 200, align: "center", editable: true, edittype: "select",
editoptions: { value: function () {
var ITDdlItems = $.parseJSON($("input[id$='hdfITEmployeesDdlItems']").val());
var s = "";
if (ITDdlItems.Table4 && ITDdlItems.Table4.length) {
for (var i = 0, l = ITDdlItems.Table4.length; i < l; i++) {
var item = ITDdlItems.Table4[i];
s += item.PERNR + ":" + item.Name + ";";
}
}
s = s.substring(0, s.length - 1);
return s;
},
dataInit: function (e) {
$(e).multiselect({
maxHeight: 200,
enableFiltering: true,
filterPlaceholder: "Search Employees",
enableCaseInsensitiveFiltering: true,
templates: {
filter: '<li class="multiselect-item filter"><div class="input-group"><input class="form-control input-sm multiselect-search" id="txtITEmployeeFilter" type="text"></div></li>',
filterClearBtn: "<span class='input-group-btn'><button class='btn btn-default input-sm multiselect-clear-filter' type='button'><i class='glyphicon glyphicon-remove'></i></button><button class='btn btn-primary input-sm multiselect-clear-filter' type='button' onclick='javascript:searchEmployees("#" + e.id + "");'><i class='glyphicon glyphicon-search'></i></button></span>"
},
onDropdownHide: function (event) {
$(e).multiselect("updateButtonText");
$(e).multiselect("updateSelectAll");
}
// onChange: function(option, checked) {
// var selectedOption = $("#" + e.id + " option:selected").val();
// alert(selectedOption);
// }
});
}
}
},
{ name: 'Email', index: 'Email', width: 250, align: "center", editable: false },
{ name: 'RoleId', index: 'RoleId', hidden: true, editable: true, hidedlg: true },
{ name: 'Role', index: 'Role', width: 175, align: "center", editable: true, edittype: "select",
editoptions: { value: function () {
var roleDdlItems = $.parseJSON($("input[id$='hdfRoleDdlItems']").val());
var s = "";
if (roleDdlItems.Table3 && roleDdlItems.Table3.length) {
for (var i = 0, l = roleDdlItems.Table3.length; i < l; i++) {
var item = roleDdlItems.Table3[i];
s += item.Id + ":" + item.Role + ";";
}
}
s = s.substring(0, s.length - 1);
return s;
},
dataInit: function (e) {
$(e).multiselect({
maxHeight: 200,
onDropdownHide: function (event) {
$(e).multiselect("updateButtonText");
$(e).multiselect("updateSelectAll");
}
});
}
}
},
{
name: 'Active', index: 'Active', hidden: false, width: 75, align: "center", editable: true, hidedlg: true,
edittype: 'checkbox', editoptions: { value: "true:false", defaultValue: "Active" },
formatter: "checkbox", formatoptions: { disabled: true }
},
{ name: 'Updated', index: 'Updated', width: 100, align: "center", editable: false, sorttype: "date",
formatter: 'date', formatoptions: { newformat: 'n/j/y g:i A' }
}
],
rowNum: 5000,
autoWidth: true,
rowList: [],
pager: '#pgrParticipants',
toppager: true,
sortname: 'Name',
viewrecords: true,
sortorder: 'asc'
});
$('#grdParticipants').navGrid("#pgrParticipants", {edit: false, add: false, del: true, refresh: false, search: false, view: false});
$('#grdParticipants').inlineNav('#pgrParticipants',
// the buttons to appear on the toolbar of the grid
{
edit: true,
add: true,
del: true,
cancel: true,
editParams: {
keys: true
},
addParams: {
addRowParams: {
keys: true
}
}
});
$('#grdParticipants').navSeparatorAdd('#pgrParticipants', {
sepclass: 'ui-separator',
sepcontent: '',
position: 'last'
});
$('#grdParticipants').navButtonAdd('#pgrParticipants',
{
buttonicon: "ui-icon-help",
title: "Roles & Responsibilities Matrix",
caption: "Roles & Responsibilities Matrix",
position: "last",
onClickButton: showRoleMatrix
});
* EDIT *
The datatype function contains an ajax call that populates the grid. I’m using this based on an example someone else in my company provided. I’ll look around today for a better method, as it sounds this isn’t the best way. Maybe using url, which I stumbled across today.
This is a tab interface to track outages that will ultimately have a total of 5 separate JQGrids. When the page initially loads for a new outage this grid is on the first tab and is empty. It would only contain records if they’re editing an existing outage. In that instance, I would populate values in the main outage form controls and load data in the grid. The UpdateParticipant function seemed work well for this as it allows me to check for that hidden field before deciding whether a db call is even needed.
The PERNR is an employee id that the user doesn’t need to know, hence hidden. It’s not strictly confidential info, but we don’t advertise it either. They only need to see Name and Email (maybe) based on the value selected from the Name multiselect. Id will be a Participant Id generated by the database after the grid data is saved. Which can’t happen until the main outage form above is saved because I need that unique Outage Id as a foreign key for the participants. This attaches a participant to an outage and becomes the unique Id for the grid rows.
The selectedOption = $("#" + e.id + " option:selected").val() is commented out, but was only to trigger onchange for that specific Bootstrap Multiselect. The Role multiselect didn’t have an onchange function registered in code. So yes, it was for one element only. As mentioned previously, I was trying to use this to populate PERNR on a Name select. I need PERNR not Name to save to the db later. To solve for this I’m using the custom formatter on that column so I’ve since removed that onchange function for the Name multiselect. The ITDdlItems = $.parseJSON($("input[id$='hdfITEmployeesDdlItems']").val()) contains a json list of employee names and PERNRs to populate the Name multiselect. That works fine so this isn’t code relevant.
The only thing I need to figure out is how to perform a check for OutageId in the hidden field before the grid data is posted to the server. Thinking about it last night, if all else fails, I’ll let it post to the server and check there for the OutageId. I just don’t like posting if it isn’t going to make a db call. I’d share a demo somewhere if I knew how. This is an internal application so my options are limited.

Related

Hide navgrid buttons depending on the number of records in jqgrid

I need to hide the delete button if there are less than 2 records in the grid. This is the js code. For some reason, the flag showDelCurrencyButton is not working out here and is always false.
Any other way to do it?
showDelCurrencyButton = false;
grid.jqGrid({
datatype: 'local',
jsonReader: jqgrid.jsonReader('CurrCd'),
mtype: 'POST',
pager: '#currencyPager',
colNames: ['Abbrev.', 'Name', 'Symbol'],
colModel: [
{
name: 'CurrCd', index: 'CurrCd', width: 200, sortable: false,
editable: true,
edittype: 'select', stype: 'select',
editrules: { required: true },
editoptions: {
dataUrl: getServerPath() + 'Ajax/GetCurrencies',
buildSelect: function (data) {
var currSelector = $("<select id='selCurr' />");
$(currSelector).append($("<option/>").val('').text('---Select Currency---'));
var currs = JSON.parse(data);
$.each(currs, function () {
var text = this.CurName;
var value = this.CurCode;
$(currSelector).append($("<option />").val(value).text(text));
});
return currSelector;
}
}
},
{ name: 'CurrName', index: 'CurrName', width: 200, sortable: false },
{ name: 'CurrSymbol', index: 'CurrSymbol', width: 200, sortable: false },
],
loadtext: 'Loading...',
caption: "Available Currencies",
scroll: true,
hidegrid: false,
height: 116,
width: 650,
rowNum: 1000,
altRows: true,
altclass: 'gridAltRowClass',
onSelectRow: webview.legalentities.billing.onCurrencySelected,
loadComplete: function (data) {
if (data.length > 1) {
showDelCurrencyButton = true;
}
var rowIds = $('#currencyGrid').jqGrid('getDataIDs');
$("#currencyGrid").jqGrid('setSelection', rowIds[0]);
},
rowNum: 1000
});
grid.jqGrid('navGrid', '#currencyPager', {
edit: false,
del: (showDelCurrencyButton == true),
deltitle: 'Delete record',
search: false,
refresh: false
}
});
Your current code uses datatype: 'local' without specifying data parameter with input data. It seems strange. In any way you can hide the Delete button dynamically identifying it by id. It's "del_" + grid[0].id in your case. Thus you can use $("#del_" + grid[0].id).hide(); to hide it. By the way one can use this instead of grid[0] inside of loadComplete.
I'd recommend you to read the old answer for more details and to read the answer, which shows how to disable/enable navigator buttons (like Delete button) instead of hiding.

set radiobutton in loadComplete of grid

$("#addressList").jqGrid({
url: '/Storage/Shipping/GetCustomerAddresses?q=2&Customerid=' + $("#saveCustomerID").val(),
datatype: "Json",
jsonReader: {
root: "Data.rows",
page: "Data.page",
total: "Data.total",
records: "Data.records",
repeatitems: true,
userdata: "userdata",
cell: "cell"
},
colNames: ['', 'Line 1', 'Line 2', 'City', 'State'],
colModel: [
{ name: 'myradio', width: 30, fixed: true, align: 'center', resizable: false, sortable: false,
formatter: function (cellValue, option) {
return '<input type="radio" name="radio_' + option.gid + '" />';
}
},
{ name: 'Line1', index: 'Line1', width: 250 },
{ name: 'Line2', index: 'Line2', width: 250 },
{ name: 'City', index: 'City', width: 210 },
{ name: 'State', index: 'State', width: 75 }
],
page: 1,
rowNum: 50,
rowList: [20, 50, 100],
pager: '#pager',
viewrecords: true,
grouping: false,
caption: "Addresses",
mtype: "POST",
width: "100%",
height: "100%",
loadonce: true,
sortable: false,
beforeSelectRow: function (rowid, e) {
var radio = $(e.target).closest('tr').find('input[type="radio"]');
radio.attr('checked', 'checked');
$("#saveCustomerAddressID").val(rowid.toString());
return true; // allow row selection
},
loadComplete: function () {
var grid_ids = $("#addressList").jqGrid('getDataIDs');
for (var i = 0; i < grid_ids.length; i++) {
if ($("#saveCustomerAddressID").val() == grid_ids[i]) {
{
$("#addressList").jqGrid('setSelection', grid_ids[i], true);
}
}
}
}
//, postdata: { CustomerID: $("#saveCustomerID").val() }
});
The above code sets the selection correctly in loadcomplete. The $("#saveCustomerAddressID").val() is the rowid fro the JSON Data.
The radiobutton is set in the beforeSelectRow. I know the row number and grid column of of the radiobutton to be set, but how do you set the radiobutton?
if you have row number and grid column, then it shouldn't be difficult. get the id(css) of that column where you have your radio button(check developer tools for this). now lets say that radio button is in a column name "Demo"
so the id would look like something like this i suppose
var demo= $("'#'+rowid+'Demo'")//check developer tools for confirmation
demo.attr('checked', 'checked');
$("#saveCustomerAddressID").val(rowid.toString());//continue with you loadComplete code
and for set selection use setSelection method of jqgrid after this continue with your code of loadcomplete

jqGrid Switch a field to dropdown from text

Ive got a jqGrid where i have a some columns and 1 of the columns is a dropdownlist(select) populated from database.
What i want is : When im not in editmode column with dropdowns just have to show text which have to be taken from query, and when im in edit mode it should show dropdown list.
exactly like here: http://www.trirand.com/blog/jqgrid/jqgrid.html go into row editing/input tipyes
here is the code for my grid:
<script type="text/javascript">
var lastsel;
$(document).ready(function () {
$.getJSON('#Url.Action("ConstructSelect")', function (data) {
setupGrid(data);
});
});
function setupGrid(data) {
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Id', index: 'Id', width: 50 },
{ name: 'Butiks Kategori', index: 'StoreId', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Buttiks Navn', index: 'StoreName', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Country', index: 'Country', width: 80, sortable: true, editable: true, edittype: "select", editoptions: { value: data }}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "500px",
imgpath: '/scripts/themes/base/images'
});
jQuery("#list").jqGrid('navGrid', "#page", { edit: false, add: false, del: false });
});
}
</script>
P.S. Ill link code as soon as i am back home
UPDATED: Thanks for an answer, im new to jq, so im making alot of mistakes ofc., but now im back to where i was before, the dropdownlist is not populated with data. i cleaned up the code as u said, so it looks like this now:
btw. The ConstructSelect return a list of Strings
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
ajaxSelectOptions: { type: "POST", dataType: "json" },
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Kategori', index: 'Kategori', width: 50, key: false},
{ name: 'Navn', index: 'Navn', align: 'center', editable: false },
{ name: 'By', index: 'By', align: 'center', editable: false },
{ name: 'Sælger', index: 'Sælger', editable: true, edittype: "select",
editoptions: { dataUrl: '#Url.Action("ConstructSelect")',
buildSelect: function (data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + "</select>";
}
}
}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "900px"
});
jQuery("#list").jqGrid('navGrid', "#page", {edit:false, add:false, del:false});
});
Okay, slight modifications was needed to get it working :
var response = typeof(data) === "string" ? jQuery.parseJSON(data.responseText):data;
aparently u have to tell buildselect that the data u want to modify is String
But i still have the problem that it doesnt show from begining which sellers is already selected!
Okay after restart it mysticly worked... it is solved now
What you need to do is to use
editoptions: { dataUrl: '#Url.Action("ConstructSelect")' }
instead of
editoptions: { value: data }
Depend on the format of the output of the action ConstructSelect you can need to use an additional property buildSelect of the editoptions. jqGrid expected that the server response on the HTTP 'GET' request of dataUrl will be HTML fragment which represent <select>. For example:
<select>
<option value="de">Germany</option>
<option value="us">USA</option>
</select>
If the server return other formatted data, like JSON data
["Germany","USA"]
or
[{"code":"de","display":"Germany"},{"code":"us","display":"USA"}]
you can write JavaScript function which convert the server response to the HTML fragment of the <select> and set the value of the property buildSelect to the function.
In the answer you will find an example of the function.
If your action support only HTTP POST and no GET you will have to use ajaxSelectOptions: { type: "POST" } parameter additionally, to overwrite the type of the corresponding ajax requests. In the same way you can overwrite other ajax parameters. For example you can use
ajaxSelectOptions: { type: "POST", dataType: "json"}
(defaults are type : "GET" and dataType: "html")
Some other small remarks to the code:
you should not place $(document).ready(function () { inside of another $(document).ready(function () {.
You use 'Id' instead of 'id'. So jqGrid will not find the id property. You can a) rename
'Id' to 'id' b) include additional parameter jsonReader: {id: 'Id'} c) include additional property key: true in the definition of the column 'Id'. Any from the ways will solve the described problem.
You can remove default properties like edittype: 'text', sortable: true or editable: false. See jqGrid documentation which describes the default values of all colModel properties.
You should remove imgpath parameter of jqGrid. The parameter is not exist since many many versions of jqGrid (see here).

jqGrid with Virtual Scrolling not returning records in correct order

We're using a jqGrid 3.8.2 with virtual scrolling to scroll a list of records. It works well if the user is scrolling through the list slowly. As soon as the user grabs the scroll bar and quickly scrolls all the way to the bottom the records returned in the grid are completely out of order and sometimes duplicated. The AJAX call we are making to get the records calls a WCF service that returns the records from a database to the AJAX callback in the jqGrid in which the data then gets loaded to the grid. The database expects a page number which in turn indicates which page of records we want.
I am pretty sure the results are coming back in the wrong order due to timing of the AJAX calls. Meaning the calls aren't always first in first out. Newer calls are likely being returned back to the jqGrid before earlier calls.
Any thoughts on how to get this to work correctly? Any steps that I could take to help get us going in the right direction?
If it helps, here is the js configuration:
PersonalListContactGridControl.GetGridConfig = function() {
var jqGridConfig = {
url: Common.AjaxService.serviceUrl + "/GetPersonalListContacts",
datatype: "JSON",
ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
mtype: "POST",
autowidth: true,
height: PersonalListContactGridControl.Constants.Height,
altRows: true,
sortname: "LastName",
viewrecords: true,
emptyrecords: "",
loadtext: '',
multiselect: true,
//sortorder: "desc",
//- virtual scrolling:: 1 ON / 0 OFF
loadonce: false, // SUPPORT FOR REBIND
rowNum: PersonalListContactGridControl.Constants.GridPageSize,
scroll: 1,
gridview: true,
//- column header text
colNames: ['EndPointID',
PersonalListContactGridControl.Constants.FirstNameColumnDisplayText,
PersonalListContactGridControl.Constants.LastNameColumnDisplayText,
PersonalListContactGridControl.Constants.EmailFaxColumnDisplayText,
PersonalListContactGridControl.Constants.TypeColumnDisplayText],
//- column specific definitions
colModel: [
{ name: 'EndPointID', index: 'EndPointID', hidden: true },
{ name: 'FirstName', index: 'FirstName', width: 155, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatLink },
{ name: 'LastName', index: 'LastName', width: 155, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatLink },
{ name: 'EmailAddress', index: 'EmailAddress', width: 240, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatEmailFax },
{ name: 'EndPointType', index: 'EndPointType', width: 60, align: 'left', editable: false, title: true,
hidden: false, resizable: true, sortable: true, editoptions: { readonly: true },
formatter: PersonalListContactGridControl.formatType }
],
//- jqGrid's "reader" ... the structure of the JSON/XML returned (Fiddler) must match this
jsonReader: {
root: "d.Contacts",
total: function(obj) {
return Math.ceil(obj.d.TotalRecords / PersonalListContactGridControl.Constants.GridPageSize);
},
records: function(obj) {
return obj.d.TotalRecords;
},
id: 'EndPointID',
repeatitems: false
},
serializeGridData: function(jqGridParms) {
//alert(jqGridParms.page);
return PersonalListContactGridControl.GetRequest(jqGridParms);
},
loadComplete: function(data) {
if (data.d) {
if (data.d.ResponseProperties.Success === false) {
if (data.d.ResponseProperties.ErrorMessage.indexOf('The List has been deleted') > -1) {
ManagePersonalList.OnPersonalListErrorHandler();
return;
}
}
var grid = PersonalListContactGridControl.Grid();
if (data.d.Contacts == null || data.d.Contacts.length == 0) { // are there any records?
// check if row exists
if (!grid.getInd(-1)) {
if (PersonalListContactGridControl.SearchString == "") {
grid.addRowData(-1, { "FirstName": PersonalListContactGridControl.Constants.NoContactDisplayText });
}
else {
grid.addRowData(-1, { "FirstName": PersonalListContactGridControl.Constants.NoContactForSearchDisplayText });
}
grid.find('#-1 input').hide(); // takeout the selection checkbox
}
PersonalListGridControl.ToggleExportButton(false);
}
else {
if (PersonalListContactGridControl.Constants.dtoToSelectID != null) {
if (PersonalListContactGridControl.SelectContactById(PersonalListContactGridControl.Constants.dtoToSelectID, true))
PersonalListContactGridControl.Constants.dtoToSelectID = null;
}
PersonalListGridControl.ToggleExportButton(true);
}
// cache the return objects
PersonalListContactGridControl.DTOS = PersonalListContactGridControl.DTOS.concat(data.d.Contacts);
PersonalListContactGridControl.InitRows();
}
},
loadError: function(xhr, status, error) {
alert("Type: " + status + "; Response: " + xhr.status + " " + xhr.statusText);
},
onCellSelect: function(rowid, iCol, cellcontent, e) {
if (iCol == 0)
PersonalListContactGridControl.CheckItem();
else
PersonalListContactGridControl.SelectContactById(rowid);
},
onSelectRow: function(id, status) {
if (!status) return;
},
onSelectAll: function() {
var grid = PersonalListContactGridControl.Grid();
var selections = new Array();
selections = grid.getGridParam('selarrrow');
if (selections[0] == -1) {
//if -1, then no rows are available
PersonalListContactGridControl.UpdateHeaderCount(0);
}
else {
PersonalListContactGridControl.UpdateHeaderCount(selections.length);
ManagePersonalList.OnSelectAllChanged(this, { Ids: selections });
}
}
};
return jqGridConfig;
}
Try changing your JSONReader to..
jsonReader: {
root: "d.Contacts",
page: "d.currpage",
total: "d.totalpages",
records: "d.TotalRecords",
id: 'EndPointId',
repeatitems: false
},
the d.totalpages and d.currpage should come back from the AJAX call

Can jqGrid summary footer be populated without userdata server request?

I have poured through every question asked on this website related to populating the jqGrid summary footer WITHOUT the userdata being a server request. And the jqGrid wiki resource and just cannot find an answer. Is this possible to do?
I use the jqGrid in many typical ways as part of my admin portal but have one particular use where I want the look & feel of the jqGrid to start out as an empty UI container of sorts for some user interaction adding rows through a form which doesn't post on Submit (thanks to Oleg's great script below) but simply adds the row and updates the summary footer with the values from the newly added row. I have 'summarytype:"sum"' in the colModel, "grouping:true", footerrow: true, userDataOnFooter: true, altRows: true, in the grid options but apart from the initial values supplied by the userdata in the local data string, the summary footer values never change. It seems like no one wants to touch this subject. Is it because the primary nature of the jqGrid is it's database driven functionality? I use about 15 instances of the jqGrid in it's database driven stance (many of which are in a production service now) but need to use it for consistency sake (all my UI's are inside jqTabs) initially as a client side UI with no server request (everything will be saved later to db) but I am pulling my hair out trying to manipulate the summary footer programmatically on and by the client only. Can anyone suggest how to cause values to the summary footer to update when a new row is added the values of which would be summed up with any existing rows and which does not involve any posting to server, just updates inside the grid?
The code supplied is kind of long and based primarily on user Oleg's solution for adding a row from a modal form without posting to the server. I've changed the local array data to JSON string simply to better understand the notation as I'm used to xml. The jsonstring initializes the grid with one default row for the user to edit. I've left out the jsonReader because the grid would not render with it.
In a nutshell then what I want to do is to have the summary footer update when a new row is added to the grid (no posting to server occurring at this point) or edited or deleted. When a certain set of values is achieved the user is prompted by a displayed button to save row data to db.
var lastSel, mydata = { "total": 1, "page": 1, "records": 1, "rows": [{ "id": acmid, "cell": ["0.00", "0.00", "0.00", "0.00"]}], "userdata":{ "mf": 0.00, "af":0.00,"pf":0.00,"cf":0.00 }}
grid = $("#ta_form_d"),
onclickSubmitLocal = function (options, postdata) {
var grid_p = grid[0].p,
idname = grid_p.prmNames.id,
grid_id = grid[0].id,
id_in_postdata = grid_id + "_id",
rowid = postdata[id_in_postdata],
addMode = rowid === "_empty",
oldValueOfSortColumn;
// postdata has row id property with another name. we fix it:
if (addMode) {
// generate new id
var new_id = grid_p.records + 1;
while ($("#" + new_id).length !== 0) {
new_id++;
}
postdata[idname] = String(new_id);
//alert(postdata[idname]);
} 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) {
var 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);
//alert(oldValueOfSortColumn);
// save the data in the grid
if (grid_p.treeGrid === true) {
if (addMode) {
grid.jqGrid("addChildNode", rowid, grid_p.selrow, postdata);
} else {
grid.jqGrid("setTreeRow", rowid, postdata);
}
} else {
if (addMode) {
grid.jqGrid("addRowData", rowid, postdata, options.addedrow);
} else {
grid.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 () {
grid.trigger("reloadGrid", [{ current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
this.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 grid_id = grid[0].id,
grid_p = grid[0].p,
newPage = grid[0].p.page;
// delete the row
grid.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.
grid.trigger("reloadGrid", [{ page: newPage}]);
}
return true;
},
processing: true
}; //,
/*initDateEdit = 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
});
//$(elem).focus();
}, 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
});
//$(elem).focus();
}, 100);
};*/
//jQuery("#ta_form_d").jqGrid({
grid.jqGrid({
// url:'/admin/tg_cma/ta_allocations.asp?acmid=' + acmid + '&mid=' + merchantid + '&approval_code=' + approval_code,
//datatype: "local",
//data: mydata,
datatype: 'jsonstring',
datastr: mydata,
colNames: ['ID', 'Monthly Fees', 'ATM Fees', 'POS Fees', 'Card to Card Fees'],
colModel: [
{ name: 'id', index: 'id', width: 90, align: "center", editable: true, editoptions: { size: 25 }, formoptions: { rowpos: 1, colpos: 1, label: "EzyAccount ID", elmprefix: "(*) " }, editrules: { required: true} },
{ name: 'mf', index: 'mf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 2, colpos: 1, label: "Monthly Fee", elmprefix: "(*) " }, editrules: { required: true} },
{ name: 'af', index: 'af', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 3, colpos: 1, label: "ATM Fee", elmprefix: "(*) " }, editrules: { required: true} },
{ name: 'pf', index: 'pf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 4, colpos: 1, label: "POS Fee", elmprefix: "(*) " }, editrules: { required: true} },
{ name: 'cf', index: 'cf', width: 130, align: "right", formatter: 'number', editable: true, summaryType: 'sum', editoptions: { size: 25 }, formoptions: { rowpos: 5, colpos: 1, label: "Card to Card Fee", elmprefix: "(*) " }, editrules: { required: true} }
],
rowNum: 5,
rowList: [5, 10, 20],
pager: '#pta_form_d',
toolbar: [true, "top"],
width: 500,
height: 100,
editurl: 'clientArray',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
multiselect: false,
cellEdit: false,
caption: "Allocations",
grouping: true,
/*groupingView: {
groupField: ['id', 'mf', 'af', 'pf', 'cf'],
groupColumnShow: [true],
groupText: ['<b>{0}</b>'],
groupCollapse: false,
groupOrder: ['asc'],
groupSummary: [true],
groupDataSorted: true
},*/
footerrow: true,
userDataOnFooter: true,
altRows: true,
ondblClickRow: function (rowid, ri, ci) {
var p = grid[0].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"
grid.jqGrid('setSelection', rowid);
}
grid.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") {
grid.jqGrid('restoreRow', lastSel);
}
lastSel = id;
}
},
afterEditCell: function (rowid, cellname, value, iRow, iCol) {
alert(iCol);
},
gridComplete: function () {
},
loadComplete: function (data) {
}
})
.jqGrid('navGrid', '#pta_form_d', {}, editSettings, addSettings, delSettings,
{ multipleSearch: true, overlay: false,
onClose: function (form) {
// if we close the search dialog during the datapicker are opened
// the datepicker will stay opened. To fix this we have to hide
// the div used by datepicker
//$("div#ui-datepicker-div.ui-datepicker").hide();
}
});
$("#t_ta_form_d").append("<input type='button' class='add' value='Add New Allocation' style='height:20px; color:green; font-size:11px;' />");
$("input.add", "#t_ta_form_d").click(function () {
jQuery("#ta_form_d").jqGrid('editGridRow', "new", {
//recreateForm:true,
jqModal: false,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true,
onclickSubmit: onclickSubmitLocal
})
})
In case of "local" datatype one can use footerData method to set (or get) the data in the footer. Additionally the method getCol can be used co calculate the sum of elements in the column.
Look at the answer for more information. I hope it will solve your problem.

Resources