Jqgrid - Table not displaying responsive behavior - javascript

Hi I Have the following code which displays the table using jqgrid. But, i noticed
that none of the jqGrid is being responsive.
How can i make existing jqGrid responsive for tablet and smart phones
UPUDATE
I have updated my code with the following
$(window).on("resize", function () {
var newWidth = $("#loanGrid").closest(".ui-jqgrid").parent().width();
$("#loanGrid").jqGrid("setGridWidth", newWidth, true);
});
The respomnsiveness works but not completely.
Here is the code below and fiddle here
HTML
<div class="container-fluid">
<div class="row">
<div class="col-md-11">
<h3 class="subheader"> Sample Info </h4>
<div class="redmond">
<table id="output"></table>
</div>
</div>
</div>
</div>
jqGrid JavaScript
$("#output").jqGrid({
url: jsonData,
mtype: "GET",
datatype: "json",
/* postData: {
json: JSON.stringify(data)
},
*/
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
label: 'Symbol',
align: 'left',
width: 65
}, {
name: 'Description',
label: 'Description',
align: 'left',
width: 165
}, {
name: 'ShareQuantity',
label: 'ShareQuantity',
align: 'right',
width: "85",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Num1"],
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
//jQuery("#loanGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
});

You can use Bootstrap classes .visible-* or hidden-* to hide/show some elements on the page depend on the window resolution (see the documentation). The properties classes, labelClasses or colModel can be used in free jqGrid (starting with version 4.8, see here and here) to assign the classes to the column. For example the demo https://jsfiddle.net/OlegKi/w7pxts0z/7/ uses
classes: "hidden-xs hidden-sm", labelClasses: "hidden-xs hidden-sm"
in LTVCategory column and the properties
classes: "hidden-xs", labelClasses: "hidden-xs"
in ShareQuantity and SharePrice columns. As the result the column LTVCategory will be hidden on "extra small devices" (width<768px) and "small devices" (width<992px, but width>=768px).

Related

jqgrid subgrids how to display json values in subgrid

I want to use jqgrid with subgrids. I have created a jqgrid table. However, I want to display the descriptions and symbols in the subgrid .
I have also included JSOn data and my code snippet and the fiddle demo here
Can I create subgrids from the following JSON data with jqgrid with out having nested JSON data? Is there any example or demo I can refer to?
$(document).ready(function() {
var jsonData = {
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "4012214.00875",
"MaxApprovedLoanAmt": "2050877.824375",
"LoanBalance": "1849000",
"AvailableCredit": "201877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "Robert L. Johnson",
"ContactPhone": "(212) 902-3614",
"RiskCategory": "Yellow",
"rows": [{
"ClientID": "C0010",
"Symbol": "WEC",
"Description": "Western Electric Co",
"ShareQuantity": "20638",
"SharePrice": "21.12",
"TotalValue": "435874.56",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "217937.28"
}, {
"ClientID": "C0010",
"Symbol": "BBB",
"Description": "Bins Breakers and Boxes",
"ShareQuantity": "9623",
"SharePrice": "74.29125",
"TotalValue": "714904.69875",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "357452.349375"
}, {
"ClientID": "C0010",
"Symbol": "GPSC",
"Description": "Great Plains Small Cap Stock",
"ShareQuantity": "49612",
"SharePrice": "14.24",
"TotalValue": "706474.88",
"LTVCategory": "Mutual Funds - Small Cap",
"LTVRatio": "40%",
"MaxLoanAmt": "282589.952"
}]
},
mmddyyyy = "";
/*********************************************************************/
$("#output").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
width: 65
}, {
name: 'Description',
width: 165
}, {
name: 'ShareQuantity',
align: 'right',
width: 85,
classes: "hidden-xs", labelClasses: "hidden-xs",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
classes: "hidden-xs", labelClasses: "hidden-xs",
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
classes: "hidden-xs", labelClasses: "hidden-xs",
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Num1"],
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
autowidth: true,
height: 'auto',
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
$("#output").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});
$(window).on("resize", function () {
var newWidth = $("#output").closest(".ui-jqgrid").parent().width();
$("#output").jqGrid("setGridWidth", newWidth, true);
});
});
If I correctly understand your requirements, it's relatively easy. If you want to display "Symbol" and "Description" in subgrid, then you would like to remove the corresponding columns from the main grid. You use loadonce: true option to fill the local data with the data return from the server. The item, which represent every row of input data, will be filled with columns and the properties from additionalProperties option. Thus you should add
additionalProperties: ["Symbol", "Description"]
after removing "Symbol" and "Description" from the columns.
Now you should add subGrid: true option to create the "subrgid" column with "+" symbol, which allows to open the grid. On opening jqGrid create the div for the subrgid and the callback subGridRowExpanded is responsible to fill the grid with data. One can create subgrid inside of the div, but one can place any HTML fragments in any form. For example
subGridRowExpanded: function (subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("Symbol: <em>" + item.Symbol +
"</em><br/>Description: <em>" + item.Description + "</em>");
}
The resulting demo https://jsfiddle.net/OlegKi/615qovew/75/ displays the data like on the picture below
You are absolutely free in the design of information displayed in the "subgrid"-div.

jqGrid dynamically change search operator type on button click

This is my jqgrid
Grid related code
var lastsel2;
var containsOrNot = 'contains';
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url: "{{ asset('/app_dev.php/_thrace-datagrid/data/item_lookup_management') }}",
postData: {
masterGridRowId: {{ VPK }}
},
datatype: "json",
mtype: 'POST',
colNames: ['Item No', 'Description 1', 'Vendor Item No','Report Dec','Location','On Hand','Exp balance','Available now','Lead Time','Type', 'Vendor #', 'Status', 'Stocked', 'Product Line', 'Creator'],
colModel: [
{
name: "I_ItemNumID",
index: "u.I_ItemNumID",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '70'
},
{
name: "I_Desc1",
index: "u.I_Desc1",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '70'
},
{
name: "I_VendorItemNum",
index: "u.I_VendorItemNum",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_ReportDec",
index: "u.I_ReportDec",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_BinNum",
index: "u.I_BinNum",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_OnHandTotal",
index: "u.I_OnHandTotal",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "R_ClosingBalance",
index: "u.R_ClosingBalance",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "R_BalanceActual",
index: "u.R_BalanceActual",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_LeadTime",
index: "u.I_LeadTime",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_ItemType",
index: "u.I_ItemType",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_VendorNumID",
index: "u.I_VendorNumID",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_Status",
index: "u.I_Status",
editable: false,
width: 100,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
},
{
name: "I_isStocked",
index: "u.I_isStocked",
editable: false,
width: 100,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
},
{
name: "I_ProductLine",
index: "u.I_ProductLine",
editable: false,
width: 150,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
},
{
name: "I_CreatedSysUser",
index: "u.I_CreatedSysUser",
editable: false,
width: 100,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
}
],
ondblClickRow: function(rowid) {
var rowData = jQuery('#list').jqGrid ('getRowData', rowid);
window.opener.document.getElementById('productDetail_V_PK').value = rowid;
window.opener.document.getElementById('productDetail_V_Desc').value = rowData.I_ItemNumID;
window.close();
},
height: 400,
rowNum: 50,
rowTotal: 1000000,
width: 3000,
gridview: true,
autoencode: false,
pager: '#pager',
shrinkToFit: true,
sortable: true,
sortname:"u.id",
sortorder: "desc",
viewrecords: true,
//multiselect: true,
loadonce:false,
onCellSelect: function(row, col, content, event) {
var cm = jQuery("#list").jqGrid("getGridParam", "colModel");
//alert(cm[col].name);
if (window.getSelection) {
selection = window.getSelection();
} else if (document.selection) {
selection = document.selection.createRange();
}
selectionColumn = cm[col].name;
selection.toString() !== '' && $("#gs_"+selectionColumn).val(selection.toString());
},
rowList: [50, 100, 500, 1000]
});
jQuery("#list").jqGrid('navGrid',"#pager",{ del:false, add:false, edit:false},{multipleSearch:true}).navButtonAdd('#pager',{
caption: "Select",
buttonicon:"ui-icon-disk",
onClickButton: function(){
var myGrid = $('#list');
selectedRowId = myGrid.jqGrid ('getGridParam', 'selrow');
var rowData = jQuery('#list').jqGrid ('getRowData', selectedRowId);
if(selectedRowId != null)
{
window.opener.document.getElementById('productDetail_V_PK').value = selectedRowId;
window.opener.document.getElementById('productDetail_V_Desc').value = rowData.I_ItemNumID;
window.close();
}
else
{
$(function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
});
}
},
position:"last"
});
jQuery("#list").jqGrid('filterToolbar',{
searchOperators: true,
stringResult: true,
searchOnEnter : true,
sopt: ['cn','eq','ne','lt','le','gt','ge','bw','ew','nc'],
beforeSearch: function(){
if(containsOrNot == "notContains" && containsOrNot != "contains")
{
//CODE FOR EXCLUDE EXECUTE HERE
var i, l, rules, rule, $grid = $('#list'),
postData = $grid.jqGrid('getGridParam', 'postData'),
filters = $.parseJSON(postData.filters);
if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
console.log(rule.op);
if (rule.op === 'cn') {
// change contains to does not contain
rule.op = 'nc';
}
}
postData.filters = JSON.stringify(filters);
}
}
}}).navButtonAdd('#pager',{
caption: "Contains",
buttonicon:"ui-icon-disk",
onClickButton: function(){
containsOrNot = 'contains';
$("#list")[0].triggerToolbar();
},
position:"last"
}).navButtonAdd('#pager',{
caption: "Excludes",
buttonicon:"ui-icon-disk",
onClickButton: function(){
containsOrNot = 'notContains';
$("#list")[0].triggerToolbar();
},
position:"last"
});
jQuery('#list').jqGrid('gridResize');
});
My grid already has code for triggering the toolbar search.
$("#list")[0].triggerToolbar(); is doing my toolbarsearch on the click of a button defined in the footer part.
Currently the search is defaulted to contains. so when I select text from any column the filter of that column is populated with that selected text. And when I press on the Contains button the triggerToolbar is triggered properly.
What I would like to do? when I click on the Excludes button it should fire another triggerToolbar but with a does not contain filter. How can I dynamically change the default filter on the particular column?
Edit jqGrid version 4.8.2
UPDATE With Oleg's another answer here and the current answer I was able to achieve this. The code is updated and works as required.
What you want is not easy. You will have to change the operations in operation menu in every searching field. Moreover you will have to add first of all have to add searchoptions: { sopt: ['cn', 'nc']} options in all columns, because currently there are many fields which have no searchoptions.sopt. It means that one can search only by 'cn'.
Because of complexity of the way I would recommend you to choose an alternative way. I'd suggest you to add beforeSearch callback in filterToolbar. The callback onClickButton for "Excludes" and "Contains" buttons should set some variable to different value. The variable should be available inside of beforeSearch callback of filterToolbar. Inside of beforeSearch callback you can implement the following logic. If "Contains" button is clicked it should return false (continue searching). In case of "Excludes" button is clicked one should convert the string postData.filters to object and go through every element of rules and replace "cn" value of the op property to "nc". Finally one should convert the modified searching rule from object to string and return false too to continue searching. It should work.

Unable to set date format & dropdown text in jqGrid

I am using jqGrid to display data. Data is in xml format.
I am unable to format date column (source format : yyyyMMdd, target format : dd-mm-yyy).
My Grid is unable to display text value from select, It shows values instead of text.
Strange thing is it is working in some other screen.
<SalesOpportunitiesLines>
<row>
<LineNum>0</LineNum>
<SalesPerson>1</SalesPerson>
<StartDate>20131126</StartDate>
<ClosingDate>20131126</ClosingDate>
<StageKey>1</StageKey>
<PercentageRate>0.000000</PercentageRate>
<MaxLocalTotal>1000000.000000</MaxLocalTotal>
<DocumentType>bodt_MinusOne</DocumentType>
<BPChanelName>ACCM Services</BPChanelName>
<BPChanelCode>CLINAC0709</BPChanelCode>
<SequenceNo>366</SequenceNo>
<DataOwnershipfield>1</DataOwnershipfield>
<BPChannelContact>1212</BPChannelContact>
</row>
</SalesOpportunities>
$("#uxStages").jqGrid({
datatype: 'xmlstring',
datastr: xmlstring,
mtype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
xmlReader: { repeatitems: false, root: "BO>SalesOpportunitiesLines", row: 'row' },
colNames: ['LineNum', 'Star tDate', 'Clos Date', 'Sales Employee', 'Stage', 'Percentage', 'Potential Amount', 'Document Type', 'Doc. No.', 'Owner'],
colModel: [
{ name: 'LineNum', key: true, index: 'LineNum', hidden: true, sortable: false, width: 60 },
{ name: 'StartDate', key: false, index: 'StartDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'ClosingDate', key: false, index: 'ClosingDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'SalesPerson', key: false, index: 'SalesPerson', sortable: false, width: 80,
editable: true,
edittype: "select"
},
{ name: 'StageKey', key: false, index: 'StageKey', hidden: false, sortable: false, width:80,
editable: true,
edittype: "select"
},
{ name: 'PercentageRate', key: false, index: 'PercentageRate', sortable: false, width: 60 },
{ name: 'MaxLocalTotal', key: false, index: 'MaxLocalTotal', sortable: false, width: 100,
editable: true,
edittype: "text",
formatter: 'currency',
formatoptions: { thousandsSeparator: ',' }
},
{ name: 'DocumentType', key: false, index: 'DocumentType', sortable: false, width: 90,
editable: true,
edittype: 'select',
formatter: 'select',
editoptions: { value: "bodt_MinusOne:;bodt_Quotation:Sales Quotations;bodt_Order:Sales Orders;bodt_DeliveryNote:Deliveries;bodt_Invoice:A/R Invoice" }
},
{ name: 'DocumentNumber', key: false, index: 'DocumentNumber', sortable: false, width: 40 },
{ name: 'DataOwnershipfield', key: false, index: 'DataOwnershipfield', hidden: false, sortable: false, width: 60,
editable: true,
edittype: "select"
}
],
rowNum: 100,
viewrecords: true,
gridview: true,
rownumbers: true,
height: 150,
loadonce: true,
width: 1120,
scrollOffset: 0,
ondblClickRow: function (rowid) {
var grid = $("#uxStages");
var selectedRowId = grid.jqGrid('getGridParam', 'selrow');
lastSelection = selectedRowId;
grid.jqGrid('editRow', selectedRowId, true, null, null, null, null, OnSuccessEdit_Stages);
$('#' + selectedRowId + "_StageKey").css('width', '100%');
$('#' + selectedRowId + "_SalesPerson").css('width', '100%');
$('#' + selectedRowId + "_DataOwnershipfield").css('width', '100%');
},
loadComplete: function () {
var ids = $("#uxStages").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (i < ids.length - 1) {
$('#' + $.jgrid.jqID(id)).addClass('not-editable-row');
$('#' + $.jgrid.jqID(id)).addClass('ui-state-error');
}
}
},
onSelectRow: function (id) {
if (id && id !== lastSelection) {
var grid = $("#uxStages");
$('#uxStages').saveRow(lastSelection);
}
}
}).jqGrid('navGrid', { edit: true, edit: true, add: true, del: true, searchOnEnter: false, search: false }, {}, {}, {}, { multipleSearch: false }).trigger('reloadGrid');
$("#uxStages").setColProp('SalesPerson', { edittype: "select", editoptions: { value: GetSalesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('StageKey', { edittype: "select", editoptions: { value: GetStagesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('DataOwnershipfield', { edittype: "select", editoptions: { value: GetDataOwnershipValues()} }); //Here i m fetching values in namedvalue pairs
Can anybody help me out?
The predefined formatter: "date" of jqGrid don't support input fields without separators. So you have to use custom formatter. The implementation could be something like the following
formatter: function (cellValue, opts, rawdata, action) {
if (action === "edit") {
// input data have format "dd-mm-yy" format - "20-03-2015"
var input = cellValue.split("-");
if (input.length === 3) {
return input[0] + "-" + input[1] + "-" + input[2];
}
} else if (cellValue.length === 8) {
// input data have format "yymmdd" format - "20150320"
var year = cellValue.substr(0,4), month = cellValue.substr(4,2),
day = cellValue.substr(6,2);
return day + "-" + month + "-" + year;
}
return cellValue; // for empty input for example
}
Depend on other options (like the usage of loadonce: true) and depend on exact version of jqGrid which you use, you could need to implement additional callbacks in the column. For example if you use loadonce: true then the editing data will be saved locally. To hold the data in the same format as input data one can use saveLocally callback of free jqGrid (see here). In the case you can implement saveLocally callback in the column as the following
saveLocally: function (options) {
var input = String(options.newValue).split("-");
options.newItem[options.cmName] = input.length === 3 ?
input[2] + input[1] + input[0] :
options.newValue;
}
See the corresponding demo uses the above code. It uses local input data in the same format. The date will be displayed in the desired format, but the edited data will be saved locally in the same format like original date.

Issues Loading jqGrid with 25,000 Rows

I'm having some difficulty loading my jqGrid with a big amount of rows. Once my document is ready I'm calling a Javascript function that gets a collection of objects from an API and then adds the row data to the grid. Everything has been working fine, but now I have over 20,000 rows, so the grid never loads. Is there something I can do to fix this? Is it possible to only paint the data that the user can see? For example, if the row number on the pager is set to 50, can I simply only load 50 rows and not all 25,000?
Here's my grid:
$(function () {
$("#grid").jqGrid({
datatype: "local",
loadonce: false,
height: "auto",
search: true,
title: false ,
autowidth: true,
shrinkToFit: true,
searchOnEnter: true,
colNames: ['ID', 'BDO Number', 'BDO Date', 'Delivery Date', 'Miles', 'Zip Code', 'Zone', 'Fuel Surcharge', 'Driver', 'Driver Rate', 'Total Driver Pay', 'Order', 'Driver ID',
'Vendor ID', 'Vendor', 'Airport', 'Airline', 'Claim Reference', 'Clear Date', 'Mileage', 'Mileage Cost', 'Special', 'Special Cost', 'Exc Cost', 'Pickup Date', 'Total Delivery Cost',
'Vendor Profit', 'Driver Percent', 'Driver Fuel Surcharge', 'Total Driver Reported', 'Payment', 'User Cleared', 'Excess Costs', 'Additional Fees', 'DriverCostSchemaID'],
colModel: [
{ name: 'ID', index: 'ID', hidden: true },
{ name: 'BDONumber', index: 'BDONumber', align: 'center', classes: 'gridButton' },
{ name: 'BDODate', index: 'BDODate', width: 250, align: 'center', formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'DeliveryDate', index: 'DeliveryDate', width: 250, align: 'center', formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'Miles', index: 'Miles', width: 40, align: 'center' },
{ name: 'ZipCode', index: 'ZipCode', width: 55, align: 'center' },
{ name: 'Zone', index: 'Zone', width: 40, align: 'center' },
{ name: 'FuelFloat', index: 'FuelFloat', width: 50, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'DriverName', index: 'DriverName', width: 125, align: 'center' },
{ name: 'RateFloat', index: 'RateFloat', width: 75, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'PayFloat', index: 'PayFloat', width: 75, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'Order', index: 'Order', hidden: true },
{ name: 'Driver', index: 'Driver', hidden: true },
{ name: 'Vendor', index: 'Vendor', hidden: true },
{ name: 'Airport', index: 'Airport', hidden: true },
{ name: 'Airline', index: 'Airline', hidden: true },
{ name: 'VendorName', index: 'VendorName', hidden: true },
{ name: 'ClaimReference', index: 'ClaimReference', hidden: true },
{ name: 'ClearDate', index: 'ClearDate', hidden: true, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'Mileage', index: 'Mileage', hidden: true },
{ name: 'MileageCost', index: 'MileageCost', hidden: true, formatter: money },
{ name: 'Special', index: 'Special', hidden: true },
{ name: 'SpecialCost', index: 'SpecialCost', hidden: true, formatter: money },
{ name: 'ExcCost', index: 'ExcCost', hidden: true, formatter: money },
{ name: 'PickupDate', index: 'PickupDate', hidden: true, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'TotalDeliveryCost', index: 'TotalDeliveryCost', hidden: true, formatter: money },
{ name: 'VendorProfit', index: 'VendorProfit', hidden: true, formatter: money },
{ name: 'DriverPercent', index: 'DriverPercent', hidden: true },
{ name: 'DriverFuelSurcharge', index: 'DriverFuelSurcharge', hidden: true, formatter: money },
{ name: 'TotalDriverReported', index: 'TotalDriverReported', hidden: true, formatter: money },
{ name: 'Payment', index: 'Payment', hidden: true },
{ name: 'UserCleared', index: 'UserCleared', hidden: true },
{ name: 'ExcCost', index: 'ExcCost', hidden: true },
{ name: 'AdditionalFees', index: 'AdditionalFees', hidden: true, formatter: money },
{ name: 'DriverCostSchemaID', index: 'DriverCostSchemaID', hidden: true },
],
rowNum: 100,
rowList: [100, 500, 1000, 100000],
viewrecords: true,
pager: "pager",
sortorder: "desc",
sortname: "DeliveryDate",
ignoreCase: true,
headertitles: true,
emptyrecords: "There are no results.",
})
$("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
GetBDOs();
});
And the GetBDOs function:
function GetBDOs() {
var request = $.ajax({
url: "#Url.Action("GetBDOs", "DPAdmin")",
type: "GET",
cache: false,
async: true,
dataType: "json"
});
request.done(function (results) {
var thegrid = $("#grid");
thegrid.clearGridData();
for (var i = 0; i < 100; i++) {
thegrid.addRowData(i + 1, results[i]);
}
thegrid.trigger("reloadGrid");
});
}
Which calls this:
[Authorize]
public JsonResult GetBDOs()
{
List<BDO> BDOs= new List<BDO>();
// Get all BDOs
BDOs = WebInterface.GetBDOs();
var jsonResult = Json(BDOs.ToArray(), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
WebInterface.GetBDOs simply hits the database and grabs all the current BDO objects, which is now between 20,000 - 25,000 and freezes the grid. Any help with this?
You really should be paginating that data on the server side before sending it back to the browser. Then all you need to do is fetch the next/prev page and redraw the grid.
The part
var thegrid = $("#grid");
thegrid.clearGridData();
for (var i = 0; i < 100; i++) {
thegrid.addRowData(i + 1, results[i]);
}
thegrid.trigger("reloadGrid");
of GetBDOs function makes performance problems definitively. Instead of calling addRowData in the loop you should set data parameter to results with respect of setGridParam:
var thegrid = $("#grid");
thegrid.clearGridData();
thegrid.jqGrid("setGridParam", {data: results});
thegrid.trigger("reloadGrid");
Additionally it's very important to add gridview: true option to jqGrid.
Even better seems to me to replace use url: "#Url.Action("GetBDOs", "DPAdmin")" as jqGrid parameters together with datatype: "json" and loadonce: true. It will makes the same Ajax call to the server and fill the grid with all 20000 or 25000 rows of data, but placing only 100 first rows in the grid.
One more recommendation will be to use key: true property in ID column. It will inform jqGrid to use the value from ID column as rowid (the value of id attributes of <tr> elements of the grid). You should consider additionally to remove a lot of hidden columns and saves the data only in the internal data option of the grid.

jqgrid getChangedCells not returning changed cells

I am trying to edit and save multiple rows from jqgrid. The getChangedCells is not returning any values.
The code is as below:
<style>
.hlabel{font-weight:bold;font-size:10pt;}
.hdata{font-size:10pt;}
</style>
<script>
//this is a formatter for showing images
function imageFormatter(cellvalue, options, rowObject) {
return "<img src='" + cellvalue + "'/>";
};
//this gets called on edit mode to display datepickers.
function onGridEdit(myRowID) {
$("#" + myRowID + "_booked").datepicker({ dateFormat: 'dd/mm/yy' });
$("#" + myRowID + "_vesselarrival").datepicker({ dateFormat: 'dd/mm/yy' });
$("#" + myRowID + "_vesseldock").datepicker({ dateFormat: 'dd/mm/yy' });
$("#" + myRowID + "_markdown").datepicker({ dateFormat: 'dd/mm/yy' });
// this will set focus on the Invested column so the datepicker doesn't fire
$("#" + myRowID + "_vesselname").get(0).focus();
}
$(function () {
var lastsel2
//creating the grid
$("#gditems").jqGrid({
url: 'handlers/items.ashx?id=' + PID,
datatype: "xml",
mtype: "POST",
colNames: ['Style', 'Altcode2', 'Colour', 'Group', '800', '999', 'Order', 'Received', 'Due', 'B/O', 'Image', 'Out/Full', 'Booked', 'Current', 'Slip', 'Arrival', 'Dock', 'Name', 'Freight', 'RRP', 'Mark Down', 'Sell', 'Cost'],
colModel: [
{ name: 'code1', index: 'code1', width: '50', sortable: true },
{ name: 'code2', index: 'code2', width: '30', sortable: true },
{ name: 'Due', index: 'Due', sorttype: 'integer', width: '20', sortable: false },
{ name: 'image', index: 'image', width: '30', formatter: imageFormatter, sortable: false },
{ name: 'booked', index: 'booked', width: '30', sortable: false, datefmt: "d/m/Y", editable: true, editrules: { date: true} },
{ name: 'date1', index: 'date1', width: '40' },
{ name: 'slip', index: 'slip', width: '30', sortable: false },
{ name: 'arrival', index: 'arrival', width: '30', sortable: false, datefmt: "d/m/Y", editable: true, editrules: { date: true} },
{ name: 'dock', index: 'dock', width: '30', sortable: false, datefmt: "d/m/Y", editable: true, editrules: { date: true} },
{ name: 'vname', index: 'vname', width: '30', sortable: false, editable: true },
{ name: 'price', index: 'price', sorttype: 'currency', width: '30', formatter: 'currency', formatoptions: { decimalPlaces: 2, prefix: "£"} },
{ name: 'date2', index: 'date2', width: '30', sortable: false, editable: true, datefmt: "d/m/Y", editrules: { date: true} },
{ name: 'price2', index: 'price2', sorttype: 'currency', width: '30', formatter: 'currency', formatoptions: { decimalPlaces: 2, prefix: "£"}}],
//saving into clientarray
onSelectRow: function (id) {
if (id && id !== lastsel2) {
jQuery("#gdpoitems").saveRow(lastsel2, false, 'clientArray');
jQuery('#gdpoitems').editRow(id, true, onGridEdit, null, 'clientArray');
lastsel2 = id;
}
},
editurl: "clientArray",
cellSubmit: 'clientArray',
rowNum: 20,
height: "100%",
autowidth: true,
rowList: [20, 30],
pager: jQuery('#pgitems'),
viewrecords: true,
sortorder: "asc",
caption: "",
loadonce: false
});
//adding buttons to the nav bar
jQuery("#gditems")
.navGrid('#pgitems', { edit: false, add: false, del: false, search: false }).navButtonAdd('#pgitems', {
caption: "Save",
buttonicon: "ui-icon-disk",
onClickButton: function () {
$.post("handlers/details.ashx?id=" + PID, { c1: $("#txtc1").val(), c2: $("#txtc2").val(), c3: $("#txtc3").val() }, function (data) {
//trying to get the edited data.
var ret = $("#gditems").getChangedCells('all');
var ret2 = JSON.stringify(ret);
alert(ret);
$.ajax({
type: "POST",
url: "handlers/items.ashx?edit=1&id=" + PID,
data: ret2,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response, textStatus, xhr) {
alert("success");
},
error: function (xhr, textStatus, errorThrown) {
alert("error");
}
});
});
},
position: "last"
})
.navButtonAdd('#pgitems', {
caption: "Cancel",
buttonicon: "ui-icon-cancel",
onClickButton: function () {
$("#header").show();
$("#detail").hide();
return false;
},
position: "last"
});
</script>
<div>
<br />
<table id="gditems">
</table>
<div id="pgitems"> </div>
</div>

Categories

Resources