Save Persistence data in Database

We have enabled persistence in the grid. As of now it is saving data in Localstorage. Due to some extensions/organization controls we can't use local storage going forward.


Please let us know if it is possible to save grid column order/sort/Filter settings in database


3 Replies

VK Vasanthakumar K Syncfusion Team December 18, 2024 01:00 PM UTC

Hi Mahesh Machina,


Greetings from Syncfusion support.


Query: Is it possible to save Grid column order/sort/filter settings in the database instead of local storage for enablePersistence purpose?


Yes, it is possible to save the Grid's column order, sort, and filter settings in the database instead of local storage without using enablePersistence property of grid by utilizing the Grid’s getPersistData API. Below is the approach:


  1. Retrieve Persistable Data:
    • Use the Grid’s getPersistData method during specific actions (e.g., application logout, grid destroy) to get the current persistable properties of the Grid.
  2. Store Persistable Data in Database:
    • Convert the retrieved persistable data to a JSON string and send it to the server via an AJAX/Fetch request. Save this data in your database.
  3. Restore Persistable Data:
    • On login or Grid initialization, retrieve the saved settings from the database.
    • Use the setProperties API of the Grid to apply the persisted settings to the Grid during the dataBound event.
  4. Documentation and Samples:
    • State Persistence Documentation: State Persistence
    • Sample Code: Please refer to the following example for implementation.


[code example]

function store(e) {  // button click

    var grid = document.getElementById("Grid").ej2_instances[0];

    for (var i = 0; i < grid.columns.length; i++) {

        grid.columns[i].backupHeader = grid.columns[i].headerText;    //take headerText duplicate to store in another property

    }

    var persistData = JSON.stringify({ persistData: grid.getPersistData() }); // Grid persistData

    var ajax = new ej.base.Ajax({ // using our ajax/fetch to send the stored persistData to server.

        url: '/Index?handler=StorePersistData',

        type: "POST",

        contentType: "application/json",

        datatype: "text",

        beforeSend: function (req) {

        req.httpRequest.setRequestHeader('XSRF-TOKEN', $('input:hidden[name="__RequestVerificationToken"]').val());

        },

        data: persistData

    });

    ajax.send();

}

function reset(e) { // button click or dataBound with if(!grid.isInitialLoad).

    var ajax = new ej.base.Ajax({ // using our ajax/fetch to retrieve the persistData from server

        url: "/Index?handler=Restore",

        type: "GET",

        contentType: "application/json; charset=utf-8",

        beforeSend: function (req) {

        req.httpRequest.setRequestHeader('XSRF-TOKEN', $('input:hidden[name="__RequestVerificationToken"]').val());

        }

    });

    ajax.send();

    ajax.onSuccess = function (result) {

        var grid = document.getElementById("Grid").ej2_instances[0];

        var state = JSON.parse(result);

        for (var i = 0; i < state.columns.length; i++) {

            state.columns[i].headerText = state.columns[i].backupHeader; //restore headerText

        }

        grid.setProperties({ // provide the retrieved state to Grid through the setProperties method

            filterSettings: state.filterSettings,

            pageSettings: state.pageSettings,

            sortSettings: { columns: state.sortSettings.columns },

            columns: state.columns

        });

    }

}


This approach allows you to store and restore the Grid’s state in a database, making it independent of local storage and suitable for application-wide persistence.


Regards,

Vasanthakumar K


Attachment: 195554samplerazorcoredbgridpersistence_ce22ddf6.zip


MM Mahesh Machina replied to Vasanthakumar K December 19, 2024 09:17 AM UTC

Thank you, Vasanthakumar. Sorting, Filtering, Pagination and order is working but templated columns are not functioning as expected

For e.g. based on boolean column data i am hide/show an image, but it is showing true/false instead of image




VK Vasanthakumar K Syncfusion Team December 20, 2024 11:47 AM UTC

Hi Mahesh Machina,


Thank you for your feedback!. We’re happy to hear that our previous solution helped you achieve your requirement for storing the grid's persistent state in the database.

Query: Templated columns are not persisting as expected.


Behavior:


We’d like to clarify that Syncfusion components have specific persistable properties, and templates (such as column templates and header templates) are not included in these persistable properties. As a result, templates are not automatically saved and restored during persistence operations.


Solution:


To ensure the persistence of templates, you can handle and use the Add to Persist customization functionality, as described in our documentation. By manually adding template information to the persisted state and restoring it during grid initialization, you can overcome this limitation.


Explanation of the Approach:


  1. When restoring the grid state, you can manually include the template-related properties (e.g., template and headerTemplate) in the persisted state.
  2. Use the getColumns() method to retrieve the current column state, including non-persistable properties such as templates.
  3. For initial rendering restore purpose, we can be able to use created event with similar restore Add to Persist customization handling.


Additional Resources:



[code example]

function reset(e) { // button click.

    var ajax = new ej.base.Ajax({ // used our ajax/fetch to send the retrieve the persist Data from server

        . . . . . .

    });

    ajax.send();

    ajax.onSuccess = function (result) {

        var grid = document.getElementById("Grid").ej2_instances[0];

        var savedProperties = JSON.parse(result);

        var gridColumnsState = Object.assign([], grid.getColumns()); // get the non-persist able property detail from currently rendered component.

        savedProperties.columns.forEach(function (col) {

            var headerText = gridColumnsState.find(function (colColumnsState) { return colColumnsState.field === col.field; })['headerText'];

            var colTemplate = gridColumnsState.find(function (colColumnsState) { return colColumnsState.field === col.field; })['template'];

            var headerTemplate = gridColumnsState.find(function (colColumnsState) { return colColumnsState.field === col.field; })['headerTemplate'];

            col.headerText = 'Text Changed';

            col.template = colTemplate;

            col.headerTemplate = headerTemplate;

        });

        console.log('restore => ', savedProperties);

        grid.setProperties(savedProperties);

    }

}


Regards,

Vasanthakumar K


Attachment: 195554samplerazorcoredbgridpersistence_f5ad1e22.zip

Loader.
Up arrow icon