Search code examples
javascriptdatagriddojodojox.grid.datagrid

how to save a filter in Dojo


I have an EnhancedGrid that users regularly use complex filters on. Is there a way to allow users to save or bookmark a filter so they can easily re-apply it in future? I know I can programmatically set a filter, but I can't predict what filters my users will want.

Thank you!

edit: made some progress myself... using grid.getFilter() to return a JSON representation of the filter, then json.stringify(jsonRepresentation) to convert it into a string. Now I'm considering my options for how to store, load and convert that string. Would loading a string into a json object then applying it as my filter open me up to XSS vulnerabilities? If I want to have filters specified as arguments in the url, can I compress the string to reduce the character count?


Solution

  • Right off the bat, here are the two three approaches I see:

    Store the filter in a URL (Okay)

    Simply get the window.location and parse out the query string using dojo/io-query::queryToObject():

    require(['dojo/io-query'], function (ioQuery) {
        var uri = window.location.href;
        var query = uri.substring(uri.indexOf("?") + 1, uri.length);
        query = ioQuery.queryToObject(query);
    });
    

    (Documentation for dojo/io-query)


    Store the filter in a cookie (Better)

    The dojo/cookie module makes this very, very easy:

    require(['dojo/cookie', 'dojo/json'], function (cookie, json) {
        var filter = { ... };
        cookie("myFilter", json.stringify(filter)); //store the cookie
        // json.parse(cookie("myFilter")); 
        // ^-- returns the cookie as a JS object
    });
    

    (Documentation for dojo/cookie)

    Obviously, the user must have cookies enabled for this to work, but it's much cleaner than storing a bunch of variables in a URL for them to bookmark.


    Use HTML5 Local Storage as suggested by Dimitri M: (Even better)

    Check to see if the user's agent supports Local Storage, and if so, use that global variable to hold on to the filter:

    require(['dojo/json'], function(json) {
        function supportsLocalStorage() {
            return ('localStorage' in window) && window['localStorage'] !== null;
        }
    
        var filter = { ... };
    
        if(supportsLocalStorage()) {
            localStorage.setItem("myFilter", json.stringify(filter));
        }
    
        // json.parse(localStorage.getItem("myFilter")) 
        // ^-- returns the filter as a JS object
    });
    

    An advantage in using web storage is that you can store much more data than cookies can.

    You could conceivably use cookies as a fallback for browsers that don't support Local Storage, (i.e. when supportsLocalStorage() returns false) at the cost of adding a touch more overhead to your design, so ultimately it's your call, depending on what browsers you want to support.

    Browser Compatibility for Web Storage