Remember (persist) the filter, sort order and current page of jqGrid

Jimbo picture Jimbo · Jun 10, 2010 · Viewed 26.3k times · Source

My application users asked if it were possible for pages that contain a jqGrid to remember the filter, sort order and current page of the grid (because when they click a grid item to carry out a task and then go back to it they'd like it to be "as they left it")

Cookies seem to be the way forward, but how to get the page to load these and set them in the grid before it makes its first data request is a little beyond me at this stage.

Does anyone have any experience with this kind of thing with jqGrid? Thanks!

Answer

Jimbo picture Jimbo · Jun 15, 2010

PROBLEM SOLVED

I eventually ended up using cookies in javascript to store the sort column, sort order, page number, grid rows and filter details of the grid (using JSON/Javascript cookies - the prefs object)

Save Preferences - Called from $(window).unload(function(){ ... });

var filters = {
    fromDate: $('#fromDateFilter').val(),
    toDate: $('#toDateFilter').val(),
    customer: $('#customerFilter').val()
};

prefs.data = {
    filter: filters,
    scol: $('#list').jqGrid('getGridParam', 'sortname'),
    sord: $('#list').jqGrid('getGridParam', 'sortorder'),
    page: $('#list').jqGrid('getGridParam', 'page'),
    rows: $('#list').jqGrid('getGridParam', 'rowNum')
};

prefs.save();

Load Preferences - Called from $(document).ready(function(){ ... });

var gridprefs = prefs.load();

$('#fromDateFilter').val(gridprefs.filter.fromDate);
$('#toDateFilter').val(gridprefs.filter.toDate);
$('#customerFilter').val(gridprefs.filter.customer);

$('#list').jqGrid('setGridParam', {
    sortname: gridprefs.scol,
    sortorder: gridprefs.sord,
    page: gridprefs.page,
    rowNum: gridprefs.rows
});

// filterGrid method loads the jqGrid postdata with search criteria and re-requests its data
filterGrid();

jqGrid Reference: http://www.secondpersonplural.ca/jqgriddocs/_2eb0fi5wo.htm

BY POPULAR DEMAND - THE FILTERGRID CODE

    function filterGrid() {
        var fields = "";
        var dateFrom = $('#dateFrom').val();
        var dateTo = $('#dateTo').val();

        if (dateFrom != "") fields += (fields.length == 0 ? "" : ",") + createField("shipmentDate", "ge", dateFrom);
        if (dateTo != "") fields += (fields.length == 0 ? "" : ",") + createField("shipmentDate", "le", dateTo);

        var filters = '"{\"groupOp\":\"AND\",\"rules\":[' + fields + ']}"';

        if (fields.length == 0) {
            $("#list").jqGrid('setGridParam', { search: false, postData: { "filters": ""} }).trigger("reloadGrid");
        } else {
            $("#list").jqGrid('setGridParam', { search: true, postData: { "filters": filters} }).trigger("reloadGrid");
        }

    }

    function createField(name, op, data) {
        var field = '{\"field\":\"' + name + '\",\"op\":\"' + op + '\",\"data\":\"' + data + '\"}';
        return field;
    }