0

Hi ive been trying to save the column order and width to a database per user. Ive acheived that it saves and loads the data back in correctly. However the grid does not change to reflect the colModel. Ive followed this awnser Here. Everything appears to be working correctly the grid does simply not reflect the changed colModel. I get no errors and the data is saved and pulled out correctly so any help or suggestions would be greatly appreciated. Thank you.

After further investigation i changed the code to use local storage rather than the ajax calls and this works. So the issues is making the page wait for a response.

Ive included my code below. Firstly is the functions that where provided in the referenced answer Here.

var $grid = $("#ProjectTable"),
            cm = [
                {name: 'FieldProjectId', width: 10, align: 'center', key: true, search: false, hidden: true},
        {name: 'Edit', width: 30, search: false, sortable: false, align: 'center'},
        {name: 'Name', width: 100, index: 'Name', editable: true},
        {name: 'Code', width: 50, index: 'Code', editable: true},
        {name: 'Manager', width: 100, index: 'Manager', editable: true},
        {name: 'StartDate', width: 65, index: 'StartDate', search: true, formatter : 'date', formatoptions: { srcformat: 'm/d/Y', newformat: 'd/m/Y'}, editable: true,editoptions : { dataInit: function (elem) { $(elem).datepicker({
                        changeMonth: true,
                        changeYear: true,
                        showWeek: true,
                        onSelect : function () { $('#ProjectTable')[0].triggerToolbar(); }
                    }).keyup(function(e) {
                        if (e.keyCode == 8 || e.keyCode == 46) {
                            $.datepicker._clearDate(this);
                        }
                    });
                }}, searchoptions: { dataInit: function (elem) { $(elem).datepicker({
                        changeMonth: true,
                        changeYear: true,
                        showWeek: true,
                        onSelect : function () { $('#ProjectTable')[0].triggerToolbar(); }
                    }).keyup(function(e) {
                        if (e.keyCode == 8 || e.keyCode == 46) {
                            $.datepicker._clearDate(this);
                        }
                    });
                } }},
        {name: 'CompletedDate', width: 65, index: 'CompletedDate', formatter : 'date', formatoptions: { srcformat: 'm/d/Y', newformat: 'd/m/Y'}, editable: true, editoptions : { dataInit: function (elem) { $(elem).datepicker({
                        changeMonth: true,
                        changeYear: true,
                        showWeek: true,
                        onSelect : function () { $('#ProjectTable')[0].triggerToolbar(); }
                    }).keyup(function(e) {
                        if (e.keyCode == 8 || e.keyCode == 46) {
                            $.datepicker._clearDate(this);
                        }
                    });
                }}, sorttype:'date' , searchoptions: { dataInit: function (elem) { $(elem).datepicker({
                        changeMonth: true,
                        changeYear: true,
                        showWeek: true,
                        onSelect : function () { $('#ProjectTable')[0].triggerToolbar(); }
                    }).keyup(function(e) {
                        if (e.keyCode == 8 || e.keyCode == 46) {
                            $.datepicker._clearDate(this);
                        }
                    });
                }}},
        {name: 'Remark', width: 200, index: 'Remark', search: false, editable: true},
        {name: 'Status', width: 95, index: 'Status', editable: true },
        {name: 'Delete', width: 20, search: false, sortable: false, align: 'center'}
            ],
            saveObjectInLocalStorage = function (storageItemName, object) {
                $.ajax({
                    url: '<%= Url.Action("SaveColumnStatePreference", "SampleSelection") %>',
                    dataType: 'json',
                    type: 'POST',
                    data: { 
                        grid: storageItemName,
                        columnsState: JSON.stringify(object)
                    },
                    success:function(data) {
                    },
                    error:function(XMLHttpRequest, textStatus, errorThrown){
                        console.log("Failed to save column state");
                    }
                });
            },
            getObjectFromLocalStorage = function (storageItemName) {
                $.ajax({
                    url: '<%= Url.Action("GetColumnStatePreference", "SampleSelection") %>',
                    dataType: 'json',
                    type: 'POST',
                    data: { 
                        grid: storageItemName
                    },
                    success:function(data) {
                        if(data !== undefined)
                        {
                            alert(data.colState);
                            return $.parseJSON(data.colState);
                        }
                    },
                    error:function(XMLHttpRequest, textStatus, errorThrown){
                        console.log("Failed to recover column state");
                    }
                });
            },
            myColumnStateName = function (grid) {
                return window.location.pathname + "#" + grid[0].id;
            },
            idsOfSelectedRows = [],
            getColumnNamesFromColModel = function () {
                var colModel = this.jqGrid("getGridParam", "colModel");
                return $.map(colModel, function (cm, iCol) {
                    // we remove "rn", "cb", "subgrid" columns to hold the column information 
                    // independent from other jqGrid parameters
                    return $.inArray(cm.name, ["rn", "cb", "subgrid"]) >= 0 ? null : cm.name;
                });
            },
            saveColumnState = function () {
                var p = this.jqGrid("getGridParam"), colModel = p.colModel, i, l = colModel.length, colItem, cmName,
                    postData = p.postData,
                    columnsState = {
                        search: p.search,
                        page: p.page,
                        rowNum: p.rowNum,
                        sortname: p.sortname,
                        sortorder: p.sortorder,
                        cmOrder: getColumnNamesFromColModel.call(this),
                        selectedRows: idsOfSelectedRows,
                        colStates: {}
                    },
                    colStates = columnsState.colStates;

                if (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(myColumnStateName(this), columnsState);
            },
            myColumnsState,
            isColState,
            restoreColumnState = function (colModel) {
                var colItem, i, l = colModel.length, colStates, cmName,
                    columnsState = getObjectFromLocalStorage(myColumnStateName(this));

                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;
            },
            updateIdsOfSelectedRows = function (id, isSelected) {
                var index = $.inArray(id, idsOfSelectedRows);
                if (!isSelected && index >= 0) {
                    idsOfSelectedRows.splice(index, 1); // remove id from the list
                } else if (index < 0) {
                    idsOfSelectedRows.push(id);
                }
            },
            firstLoad = true;

        myColumnsState = restoreColumnState.call($grid, cm);
        isColState = myColumnsState !== undefined && myColumnsState !== null;
        idsOfSelectedRows = isColState && myColumnsState.selectedRows !== undefined ? myColumnsState.selectedRows : [];

And Secondly the Code for the jqGrid itself.

$('#ProjectTable').jqGrid({
            datatype: 'json',
            url: '<%= Url.Action("projectGridData", "SampleSelection") %>',
            mType: 'POST',
            colNames: [
            htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.ProjectId", "ID") %>"),
            "",
             htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.Name", "Name") %>"),
              htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.Code", "Code") %>"),
               htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.Manager", "Manager") %>"),
                  htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.StartDate", "Start Date") %>"),
                   htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.CompletionDate", "CompletionDate") %>"),
                   htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.Remark", "Remark") %>"),
                   htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.Status", "Status") %>"),
                   ""
                   ],
            colModel: cm,
            caption: htmlDecode("<%=Atmis.EncodedLabel("Sample.Project.Caption", "Project") %>"),
            width: $('#tabs-projects').width() - 20,
            sortname: 'FieldProjectId',
            loadui: 'block',
            rowNum: 20,
            rowList: [10,25,50,100,200],
            sortorder : 'desc',
            headertitles:true,
            ajaxGridOptions : {
                beforeSend: function(xhr) {



                    $('#ProjectTable').closest('.ui-jqgrid').block({
                        centerX: false, 
                        centerY: false,
                        message: $('#ProjectLoading'),
                        css: {
                            position: 'absolute',
                            padding: 0,
                            margin: 0,
                            width: 'auto',
                            top: '40%',
                            left: '45%',
                            textAlign: 'center',
                            cursor: 'wait' 
                        },
                        overlayCSS:  { 
                            backgroundColor: '#524f4f', 
                            opacity:         0.6, 
                            cursor:          'wait' 
                        } 
                    });
                },
                complete: function(xhr) {
                   $('#ProjectTable').closest('.ui-jqgrid').unblock();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                   $('#ProjectTable').closest('.ui-jqgrid').unblock();
                }
            },
            resizeStop: function(width, index) { 
                 saveColumnState.call($grid, $grid[0].p.remapColumns);
            },
            sortable: {
                update: function(relativeColumnOrder){
                   saveColumnState.call($grid);
                }
            },
            height: 'auto',
            viewrecords: true,
            toolbar: [true, "top"],
            pager: $('#ProjectPager'),
            postData: {
                withLinks: true,
                clientId: function() {
                        return $('#ClientId').val();
                    }
            },
            editData: {
                clientId: function() {
                        return $('#ClientId').val();
                    }
            },
            beforeRequest: function () {
            },
            onclickSubmit: function (options, postData) {
                return {
                    ClientId: $('#ClientId').val()
                };
            },
            gridComplete: function () {
            },

            jsonReader:{
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records",
                    repeatitems: false,
                    userdata: "userdata"
            },
            onSelectRow: function (id) {
                // get data from the column 'userCode'
                var selRowId = $(this).jqGrid('getGridParam', 'selrow');
                var userCode = $(this).jqGrid('getCell', selRowId, 'FieldProjectId');


                SelectedProjectID = userCode;
                $('#tabs').tabs('enable', 1);
                $('#tabs').tabs('enable', 3);

            },
            loadComplete: function (data){

            var $this = $(this), p = $this.jqGrid("getGridParam"), i, count;

            if (firstLoad) {
                firstLoad = false;
                if (isColState && myColumnsState.cmOrder != null && myColumnsState.cmOrder.length > 0) {
                    // We compares the values from myColumnsState.cmOrder array
                    // with the current names of colModel and remove wrong names. It could be
                    // required if the column model are changed and the values from the saved stated
                    // not corresponds to the 
                    var fixedOrder = $.map(myColumnsState.cmOrder, function (name) {
                            return p.iColByName[name] === undefined ? null : name;
                        });
                    $this.jqGrid("remapColumnsByName", fixedOrder, true);
                }
            }
            saveColumnState.call($this, this.p.remapColumns);


            }
            }
            ).filterToolbar();
Community
  • 1
  • 1
Tony_89
  • 797
  • 11
  • 39

1 Answers1

0

it' difficult to answer on questions with long code without having the possibility to debug it. Nevertheless I suppose that your problem is in the usage of restoreColumnState which you call in synchronous way: myColumnsState = restoreColumnState.call($grid, cm); in the code, but it calls getObjectFromLocalStorage which works asynchronously. The data return $.parseJSON(data.colState); returned from success callback of jquery.ajax will be just ignored. To fit the code you can rewrite the code to create the whole grid with the used state inside of success callback.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hey yer it was a design pattern issue. I have six grids and each grid is based on the selection of the prior grid so i had to adjust the order in which i was getting the saved column state to ensure each grid was loaded and ready. After switching to the free jqGrid ive been able to simplify my code a great deal for example i don't have to write code to store arrays to persist selection across pages since that's now a feature. Thank you for your help again. – Tony_89 Nov 17 '15 at 16:04