k-World

Archive for November, 2013

Persisting columns using local storage (HTML-5) in multiple JQGrids

In this article on JQGrid, I am posting how we can persist the state of the columns in a page, whenever multiple JQGrids are used.

Using the HTML-5 Local Storage feature, we can save the state of the columns in JQGrid as mentioned in the code below.

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head id=”Head1″ runat=”server”>
<title>Multiple JQ Grids</title>
<link rel=”stylesheet” type=”text/css” href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/redmond/jquery-ui.css&#8221; />
<link rel=”stylesheet” type=”text/css” href=”http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.2.0/css/ui.jqgrid.css&#8221; />
<link rel=”stylesheet” type=”text/css” href=”http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.2.0/plugin/ui.multiselect.css&#8221; />
<style type=”text/css”>
html, body
{
font-size: 75%;
}
</style>
<script type=”text/javascript” src=”http://code.jquery.com/jquery-1.7.1.min.js”></script&gt;
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js”></script&gt;
<script type=”text/javascript” src=”http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.2.0/plugin/ui.multiselect.js”></script&gt;
<script type=”text/javascript” src=”http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.2.0/js/i18n/grid.locale-en.js”></script&gt;
<script type=”text/javascript” src=”http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.2.0/js/jquery.jqGrid.min.js”></script&gt;
<script type=”text/javascript” src=”http://www.ok-soft-gmbh.com/jqGrid/json2.js”></script&gt;
<script type=”text/javascript”>
$.jgrid.formatter.integer.thousandsSeparator = ‘,’;
$.jgrid.formatter.number.thousandsSeparator = ‘,’;
$.jgrid.formatter.currency.thousandsSeparator = ‘,’;

$(document).ready(function () {

var columnNames = [/*’Inv No’,*/’Date’, ‘Client’, ‘Amount’, ‘Tax’, ‘Total’, ‘Closed’, ‘Shipped via’, ‘Notes’];

// Date Formatting
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,
onSelect: function () {
var that = this;
if (this.id.substr(0, 3) === “gs_”) {
setTimeout(function () {
that.triggerToolbar();
}, 50);
} else {
// to refresh the filter
$(this).trigger(‘change’);
}
}
});
}, 100);
};
numberSearchOptions = [‘eq’, ‘ne’, ‘lt’, ‘le’, ‘gt’, ‘ge’, ‘nu’, ‘nn’, ‘in’, ‘ni’];
numberTemplate = { formatter: ‘number’, align: ‘right’, sorttype: ‘number’,
searchoptions: { sopt: numberSearchOptions }
};

//Column Models along with columns formatting.
var columnModels = [
{ name: ‘invdate’, index: ‘invdate’, width: 75, align: ‘center’, sorttype: ‘date’,
formatter: ‘date’, formatoptions: { newformat: ‘d-M-Y’ }, datefmt: ‘d-M-Y’,
searchoptions: {
sopt: [‘eq’, ‘ne’],
dataInit: initDateSearch
}
},
{ name: ‘name’, index: ‘name’, width: 65 },
{ name: ‘amount’, index: ‘amount’, width: 75, template: numberTemplate },
{ name: ‘tax’, index: ‘tax’, width: 52, template: numberTemplate },
{ name: ‘total’, index: ‘total’, width: 60, search: false, template: numberTemplate },
{ name: ‘closed’, index: ‘closed’, width: 67, align: ‘center’, formatter: ‘checkbox’,
edittype: ‘checkbox’, editoptions: { value: ‘Yes:No’, defaultValue: ‘Yes’ },
stype: ‘select’, searchoptions: { sopt: [‘eq’, ‘ne’], value: ‘:Any;true:Yes;false:No’ }
},
{ name: ‘ship_via’, index: ‘ship_via’, width: 95, align: ‘center’, formatter: ‘select’,
edittype: ‘select’, editoptions: { value: ‘FE:FedEx;TN:TNT;IN:Intim’, defaultValue: ‘Intime’ },
stype: ‘select’, searchoptions: { sopt: [‘eq’, ‘ne’], value: ‘:Any;FE:FedEx;TN:TNT;IN:Intim’ }
},
{ name: ‘note’, index: ‘note’, width: 60, sortable: false }
];

//Data for JQGrids.
var myData = [
{ id: “1”, invdate: “2007-10-01”, name: “test”, note: “note”, amount: “200.00”, tax: “10.00”, closed: true, ship_via: “TN”, total: “210.00” },
{ id: “2”, invdate: “2007-10-02”, name: “test2”, note: “note2”, amount: “300.00”, tax: “20.00”, closed: false, ship_via: “FE”, total: “320.00” },
{ id: “3”, invdate: “2011-07-30”, name: “test3”, note: “note3”, amount: “400.00”, tax: “30.00”, closed: true, ship_via: “FE”, total: “430.00” },
{ id: “4”, invdate: “2007-10-04”, name: “test4”, note: “note4”, amount: “200.00”, tax: “10.00”, closed: true, ship_via: “TN”, total: “210.00” },
{ id: “5”, invdate: “2007-10-31”, name: “test5”, note: “note5”, amount: “300.00”, tax: “20.00”, closed: false, ship_via: “FE”, total: “320.00” },
{ id: “6”, invdate: “2007-09-06”, name: “test6”, note: “note6”, amount: “400.00”, tax: “30.00”, closed: false, ship_via: “FE”, total: “430.00” },
{ id: “7”, invdate: “2011-07-30”, name: “test7”, note: “note7”, amount: “200.00”, tax: “10.00”, closed: true, ship_via: “TN”, total: “210.00” },
{ id: “8”, invdate: “2007-10-03”, name: “test8”, note: “note8”, amount: “300.00”, tax: “20.00”, closed: true, ship_via: “FE”, total: “320.00” },
{ id: “9”, invdate: “2007-09-01”, name: “test9”, note: “note9”, amount: “400.00”, tax: “30.00”, closed: false, ship_via: “TN”, total: “430.00” },
{ id: “10”, invdate: “2007-09-08”, name: “test10”, note: “note10”, amount: “500.00”, tax: “30.00”, closed: true, ship_via: “TN”, total: “530.00” },
{ id: “11”, invdate: “2007-09-08”, name: “test11”, note: “note11”, amount: “500.00”, tax: “30.00”, closed: false, ship_via: “FE”, total: “530.00” },
{ id: “12”, invdate: “2007-09-10”, name: “test12”, note: “note12”, amount: “500.00”, tax: “30.00”, closed: false, ship_via: “FE”, total: “530.00” }
];

//Commom Functions used to store the columns state in local storage – START
saveObjectInLocalStorage = function (storageItemName, object) {
if (typeof window.localStorage !== ‘undefined’) {
window.localStorage.setItem(storageItemName, JSON.stringify(object));
}
};

removeObjectFromLocalStorage = function (storageItemName) {
if (typeof window.localStorage !== ‘undefined’) {
window.localStorage.removeItem(storageItemName);
}
};

getObjectFromLocalStorage = function (storageItemName) {
if (typeof window.localStorage !== ‘undefined’) {
return JSON.parse(window.localStorage.getItem(storageItemName));
}
};
//Commom Functions used to store the columns state in local storage – END

// First JQGrid – START
$gridFirst = $(“#listFirst”); // My First JQGrid

myColumnStateNameFirstGrid = ‘ColumnChooserAndLocalStorageFirstGrid.colStateFirstGrid’;

saveColumnStateFirstGrid = function (perm) {
var colModel = this.jqGrid(‘getGridParam’, ‘colModel’), i, l = colModel.length, colItem, cmName,
postData = this.jqGrid(‘getGridParam’, ‘postData’),
columnsState = {
search: this.jqGrid(‘getGridParam’, ‘search’),
page: this.jqGrid(‘getGridParam’, ‘page’),
sortname: this.jqGrid(‘getGridParam’, ‘sortname’),
sortorder: this.jqGrid(‘getGridParam’, ‘sortorder’),
permutation: perm,
colStates: {}
},
colStates = columnsState.colStates;

if (typeof (postData.filters) !== ‘undefined’) {
columnsState.filters = postData.filters;
}

for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== ‘rn’ && cmName !== ‘cb’ && cmName !== ‘subgrid’) {
colStates[cmName] = {
width: colItem.width,
hidden: colItem.hidden
};
}
}
saveObjectInLocalStorage(myColumnStateNameFirstGrid, columnsState);
};

var myColumnsStateFirstGrid;

var isColStateFirstGrid;

restoreColumnStateFirstGrid = function (colModel) {
var colItem, i, l = colModel.length, colStates, cmName,
columnsState = getObjectFromLocalStorage(myColumnStateNameFirstGrid);

if (columnsState) {
colStates = columnsState.colStates;
for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== ‘rn’ && cmName !== ‘cb’ && cmName !== ‘subgrid’) {
colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
}
}
}
return columnsState;
};

firstLoadFirstGrid = true;

// We are restoring the Columns state for the First JQGrid.
myColumnsState = restoreColumnStateFirstGrid(columnModels);
isColStateFirstGrid = typeof (myColumnsStateFirstGrid) !== ‘undefined’ && myColumnsStateFirstGrid !== null;

$gridFirst.jqGrid({
datatype: ‘local’,
data: myData,
colNames: columnNames,
colModel: columnModels,
rowNum: 10,
rowList: [5, 10, 20],
pager: ‘#pagerFirst’,
gridview: true,
page: isColStateFirstGrid ? myColumnsStateFirstGrid.page : 1,
search: isColStateFirstGrid ? myColumnsStateFirstGrid.search : false,
postData: isColStateFirstGrid ? { filters: myColumnsStateFirstGrid.filters} : {},
sortname: isColStateFirstGrid ? myColumnsStateFirstGrid.sortname : ‘invdate’,
sortorder: isColStateFirstGrid ? myColumnsStateFirstGrid.sortorder : ‘desc’,
rownumbers: true,
ignoreCase: true,
caption: ‘The usage of localStorage to save First jqGrid preferences’,
height: ‘auto’,
loadComplete: function () {
if (firstLoadFirstGrid) {
firstLoadFirstGrid = false;
if (isColStateFirstGrid) {
$(this).jqGrid(“remapColumns”, myColumnsStateFirstGrid.permutation, true);
}
}
saveColumnStateFirstGrid.call($(this), this.p.remapColumns);
},
resizeStop: function () {
saveColumnStateFirstGrid.call($gridFirst, $gridFirst[0].p.remapColumns);
}
});

// Search Functionality Settigns.
$.extend($.jgrid.search, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true,
closeOnEscape: true,
closeAfterSearch: true,
overlay: 0
});

// Pagination stuff.
$gridFirst.jqGrid(‘navGrid’, ‘#pagerFirst’, { edit: false, add: false, del: false });

// JQGrid Column Chooser pop up settings.
$gridFirst.jqGrid(‘navButtonAdd’, ‘#pagerFirst’, {
caption: “”,
buttonicon: “ui-icon-calculator”,
title: “choose columns”,
onClickButton: function () {
$(this).jqGrid(‘columnChooser’, {
done: function (perm) {
if (perm) {
this.jqGrid(“remapColumns”, perm, true);
saveColumnStateFirstGrid.call(this, perm);
}
}
});
}
});

//To clear the saved grid settings.
$gridFirst.jqGrid(‘navButtonAdd’, ‘#pager’, {
caption: “”,
buttonicon: “ui-icon-closethick”,
title: “clear saved grid’s settings”,
onClickButton: function () {
removeObjectFromLocalStorage(myColumnStateNameFirstGrid);
window.location.reload();
}
});
// First JQGrid – END

// Second JQGrid – START
$gridSecond = $(“#listSecond”);

myColumnStateNameSecondGrid = ‘ColumnChooserAndLocalStorageSecondGrid.colStateSecondGrid’;

saveColumnStateSecondGrid = function (perm) {
var colModel = this.jqGrid(‘getGridParam’, ‘colModel’), i, l = colModel.length, colItem, cmName,
postData = this.jqGrid(‘getGridParam’, ‘postData’),
columnsState = {
search: this.jqGrid(‘getGridParam’, ‘search’),
page: this.jqGrid(‘getGridParam’, ‘page’),
sortname: this.jqGrid(‘getGridParam’, ‘sortname’),
sortorder: this.jqGrid(‘getGridParam’, ‘sortorder’),
permutation: perm,
colStates: {}
},
colStates = columnsState.colStates;

if (typeof (postData.filters) !== ‘undefined’) {
columnsState.filters = postData.filters;
}

for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== ‘rn’ && cmName !== ‘cb’ && cmName !== ‘subgrid’) {
colStates[cmName] = {
width: colItem.width,
hidden: colItem.hidden
};
}
}
saveObjectInLocalStorage(myColumnStateNameSecondGrid, columnsState);
};

var myColumnsStateSecondGrid;

var isColStateSecondGrid;

restoreColumnStateSecondGrid = function (colModel) {
var colItem, i, l = colModel.length, colStates, cmName,
columnsState = getObjectFromLocalStorage(myColumnStateNameSecondGrid);

if (columnsState) {
colStates = columnsState.colStates;
for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== ‘rn’ && cmName !== ‘cb’ && cmName !== ‘subgrid’) {
colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
}
}
}
return columnsState;
};

firstLoadSecondGrid = true;

myColumnsState = restoreColumnStateSecondGrid(columnModels);
isColStateSecondGrid = typeof (myColumnsStateSecondGrid) !== ‘undefined’ && myColumnsStateSecondGrid !== null;

$gridSecond.jqGrid({
datatype: ‘local’,
data: myData,
colNames: columnNames,
colModel: columnModels,
rowNum: 10,
rowList: [5, 10, 20],
pager: ‘#pagerSecond’,
gridview: true,
page: isColStateSecondGrid ? myColumnsStateSecondGrid.page : 1,
search: isColStateSecondGrid ? myColumnsStateSecondGrid.search : false,
postData: isColStateSecondGrid ? { filters: myColumnsStateSecondGrid.filters} : {},
sortname: isColStateSecondGrid ? myColumnsStateSecondGrid.sortname : ‘invdate’,
sortorder: isColStateSecondGrid ? myColumnsStateSecondGrid.sortorder : ‘desc’,
rownumbers: true,
ignoreCase: true,
caption: ‘The usage of localStorage to save Second jqGrid preferences’,
height: ‘auto’,
loadComplete: function () {
if (firstLoadSecondGrid) {
firstLoadSecondGrid = false;
if (isColStateSecondGrid) {
$(this).jqGrid(“remapColumns”, myColumnsStateSecondGrid.permutation, true);
}
}
saveColumnStateSecondGrid.call($(this), this.p.remapColumns);
},
resizeStop: function () {
saveColumnStateSecondGrid.call($gridSecond, $gridSecond[0].p.remapColumns);
}
});

$.extend($.jgrid.search, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true,
closeOnEscape: true,
closeAfterSearch: true,
overlay: 0
});

$gridSecond.jqGrid(‘navGrid’, ‘#pagerSecond’, { edit: false, add: false, del: false });

$gridSecond.jqGrid(‘navButtonAdd’, ‘#pagerSecond’, {
caption: “”,
buttonicon: “ui-icon-calculator”,
title: “choose columns”,
onClickButton: function () {
$(this).jqGrid(‘columnChooser’, {
done: function (perm) {
if (perm) {
this.jqGrid(“remapColumns”, perm, true);
saveColumnStateSecondGrid.call(this, perm);
}
}
});
}
});

$gridSecond.jqGrid(‘navButtonAdd’, ‘#pager’, {
caption: “”,
buttonicon: “ui-icon-closethick”,
title: “clear saved grid’s settings”,
onClickButton: function () {
removeObjectFromLocalStorage(myColumnStateNameSecondGrid);
window.location.reload();
}
});
// Second JQGrid – END

// Third JQGrid – START
$gridThird = $(“#listThird”);

myColumnStateNameThirdGrid = ‘ColumnChooserAndLocalStorageThirdGrid.colStateThirdGrid’;

saveColumnStateThirdGrid = function (perm) {
var colModel = this.jqGrid(‘getGridParam’, ‘colModel’), i, l = colModel.length, colItem, cmName,
postData = this.jqGrid(‘getGridParam’, ‘postData’),
columnsState = {
search: this.jqGrid(‘getGridParam’, ‘search’),
page: this.jqGrid(‘getGridParam’, ‘page’),
sortname: this.jqGrid(‘getGridParam’, ‘sortname’),
sortorder: this.jqGrid(‘getGridParam’, ‘sortorder’),
permutation: perm,
colStates: {}
},
colStates = columnsState.colStates;

if (typeof (postData.filters) !== ‘undefined’) {
columnsState.filters = postData.filters;
}

for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== ‘rn’ && cmName !== ‘cb’ && cmName !== ‘subgrid’) {
colStates[cmName] = {
width: colItem.width,
hidden: colItem.hidden
};
}
}
saveObjectInLocalStorage(myColumnStateNameThirdGrid, columnsState);
};

var myColumnsStateThirdGrid;

var isColStateThirdGrid;

restoreColumnStateThirdGrid = function (colModel) {
var colItem, i, l = colModel.length, colStates, cmName,
columnsState = getObjectFromLocalStorage(myColumnStateNameThirdGrid);

if (columnsState) {
colStates = columnsState.colStates;
for (i = 0; i < l; i++) {
colItem = colModel[i];
cmName = colItem.name;
if (cmName !== ‘rn’ && cmName !== ‘cb’ && cmName !== ‘subgrid’) {
colModel[i] = $.extend(true, {}, colModel[i], colStates[cmName]);
}
}
}
return columnsState;
};

firstLoadThirdGrid = true;

myColumnsState = restoreColumnStateThirdGrid(columnModels);

isColStateThirdGrid = typeof (myColumnsStateThirdGrid) !== ‘undefined’ && myColumnsStateThirdGrid !== null;

$gridThird.jqGrid({
datatype: ‘local’,
data: myData,
colNames: columnNames,
colModel: columnModels,
rowNum: 10,
rowList: [5, 10, 20],
pager: ‘#pagerThird’,
gridview: true,
page: isColStateThirdGrid ? myColumnsStateThirdGrid.page : 1,
search: isColStateThirdGrid ? myColumnsStateThirdGrid.search : false,
postData: isColStateThirdGrid ? { filters: myColumnsStateThirdGrid.filters} : {},
sortname: isColStateThirdGrid ? myColumnsStateThirdGrid.sortname : ‘invdate’,
sortorder: isColStateThirdGrid ? myColumnsStateThirdGrid.sortorder : ‘desc’,
rownumbers: true,
ignoreCase: true,
caption: ‘The usage of localStorage to save Third jqGrid preferences’,
height: ‘auto’,
loadComplete: function () {
if (firstLoadThirdGrid) {
firstLoadThirdGrid = false;
if (isColStateThirdGrid) {
$(this).jqGrid(“remapColumns”, myColumnsStateThirdGrid.permutation, true);
}
}
saveColumnStateThirdGrid.call($(this), this.p.remapColumns);
},
resizeStop: function () {
saveColumnStateThirdGrid.call($gridThird, $gridThird[0].p.remapColumns);
}
});

$.extend($.jgrid.search, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true,
closeOnEscape: true,
closeAfterSearch: true,
overlay: 0
});

$gridThird.jqGrid(‘navGrid’, ‘#pagerThird’, { edit: false, add: false, del: false });

$gridThird.jqGrid(‘navButtonAdd’, ‘#pagerThird’, {
caption: “”,
buttonicon: “ui-icon-calculator”,
title: “choose columns”,
onClickButton: function () {
$(this).jqGrid(‘columnChooser’, {
done: function (perm) {
if (perm) {
this.jqGrid(“remapColumns”, perm, true);
saveColumnStateThirdGrid.call(this, perm);
}
}
});
}
});

$gridThird.jqGrid(‘navButtonAdd’, ‘#pager’, {
caption: “”,
buttonicon: “ui-icon-closethick”,
title: “clear saved grid’s settings”,
onClickButton: function () {
removeObjectFromLocalStorage(myColumnStateNameThirdGrid);
window.location.reload();
}
});
// Third JQGrid – END

});
</script>
</head>
<body>
<table id=”listFirst”>
<tr>
<td />
</tr>
</table>
<div id=”pagerFirst”>
</div>
<br />
<table id=”listSecond”>
<tr>
<td />
</tr>
</table>
<div id=”pagerSecond”>
</div>
<br />
<table id=”listThird”>
<tr>
<td />
</tr>
</table>
<div id=”pagerThird”>
</div>
</body>
</html>

For the code to work just copy and paste it into the aspx page in VS and hit F5.