Search code examples
javascriptdojodgrid

Dgrid : How to save and persist column order?


I'm using dgrid with the column reorder extension. I have two questions here -

  1. I see that after reordering columns, the columns are present in the new order in the subRows attrinute of grid (note that I'm not referring to subRow here). Is that the best way to get the column order or are there any alternate/better ways to do it?

  2. I understand that I will need to take care of saving the column order (or any other property for that matter) and restoring it. When I'm creating the grid with a saved order, what is the best way to do it? Should I create the columns in the saved order or can I create them in the standard order and then re-order them as per my saved order? If the latter is possible, how do I do it?

Thanks,


Solution

  • Yes, subRows is likely the most consistent way to get the column order.

    Regarding saving/restoring, I could fathom doing something like the following. Note that for simplicity's sake, I'm making some assumptions here:

    1. You only have a single sub-row (the same approach could be used for multiple, I figure, but you'd need outer loops)
    2. Each column references a unique field
    3. You are targeting only ES5+ environments (since I use ES5 Array methods below)

    When saving the sub-rows, save just the field that each column references (which will make it trivial to serialize):

    var persistedSubRow = grid.subRows[0].map(function (column) {
        return column.field;
    }
    

    Then, when creating the grid, have an object hash of your columns in the default order (which you can use to set columns if there are no persisted settings), but if persisted settings exist, use that to determine the order by mapping it back against the hash:

    var columns = {
        field1: ...,
        field2: ...,
        ...
    }
    
    if (persistedSubRow) {
        persistedSubRow = persistedColumns.map(function (field) {
            var column = columns[field];
            // Normally when an object hash is specified for columns,
            // field is autodetected from the key.  Converting to array will
            // lose that, so set it within the object.
            column.field = field;
            return column;
        });
    }
    
    var grid = new Grid({
        // grid.columns accepts either an object or array as input
        columns: persistedSubRow || columns,
        ...
    });
    

    Let me know if you run into trouble; I'm shooting from the hip here, and haven't tested the above.