JQGrid getGridParam data returns empty array

13,617

The internal parameter data will be used only if one uses datatype: "local". You use datatype: "json". It means that the server hold whole dataset only. The url: '${pageContext.request.contextPath}/getTrucksJSONAction' receive request for the page of sorted and filtered data. The server should implement sorting, filtering/sorting and paging.

There exists a special case: one use remote datatype ("json" or "xml"), but one uses loadonce: true parameter additionally. In the case the server should return all unfiltered data instead of providing the page of data. The returned data should be still sorted corresponds to sortname, sortorder parameter (which will be sent to the server as sidx and sord). jqGrid displays the first page of returned data, but it fills the internal data parameter with whole rows of data returned from the server. After the first loading of data jqGrid changes datatype to "local" and so the later sorting, paging and filtering of data will be like in case of datatype: "local". In the case yoou will be able to get all the data using grid.jqGrid("getGridParam", "data"), but you can do this of case after the data will be once loaded.

Share:
13,617
Terry
Author by

Terry

Updated on June 04, 2022

Comments

  • Terry
    Terry almost 2 years

    In a custom button in my pager, I call grid.jqGrid("getGridParam", "data"), "data") to get all the data in the grid but it returns empty array. When I call grid.jqGrid("getGridParam", "data") in the loadComplete function, it still returns an empty array. However if I call grid.jqGrid('getRowData') it gives me the data I am looking for. See my code below.

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
             pageEncoding="ISO-8859-1" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/jquery-ui.min.css"/>
        <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/css/ui.jqgrid.css"/>
        <!--   Overide css styling to ensure that calendar image is inline with text box -->
        <style type="text/css">.ui-jqgrid .ui-search-table .ui-search-input > input,
                                .ui-jqgrid .ui-search-table .ui-search-input > select,
                                .ui-jqgrid .ui-search-table .ui-search-input > img {vertical-align: middle; display: inline-block;}
        </style>
        <script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/jquery-ui.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/grid.locale-en.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/jquery.jqGrid.min.js" type="text/javascript"></script>
        <title>Trucks Overview</title>
    
        <script type="text/javascript">
        jQuery().ready(function () {
            var grid = jQuery("#truck_grid");
            var orderGridDialog = $('#truck_grid_dialog');  
            var gridData;
    
            getUniqueNames = function(columnName) {
                var texts = grid.jqGrid('getCol', columnName, false);
                var uniqueTexts = [], textsLength = texts.length, text, i, textsMap = {}; 
                for (i=0;i<textsLength;i++) {
                    text = texts[i];
                    if (text != undefined && textsMap[text] === undefined) {
                        // to test whether the texts is unique we place it in the map.
                        textsMap[text] = true;
                        uniqueTexts.push(text);
                    }
                }
                return uniqueTexts;
            };
            buildSearchSelect = function(uniqueNames) {
                var values=":All";
                $.each (uniqueNames, function() {
                    values += ";" + this + ":" + this;
                });
                return values;
            };
            setSearchSelect = function(columnName) {
                grid.jqGrid('setColProp', columnName,
                            {   stype: 'select',
                                searchoptions: {
                                    value:buildSearchSelect(getUniqueNames(columnName)),
                                    sopt:['eq']
                                }
                            }
                );
            };
    
            var initDateWithButton = function (elem) {
                if (/^\d+%$/.test(elem.style.width)) {
                    // remove % from the searching toolbar
                    elem.style.width = '';
                }
                // to be able to use 'showOn' option of datepicker in advance searching dialog
                // or in the editing we have to use setTimeout
                setTimeout(function () {
                    $(elem).datepicker({
                        dateFormat: 'mm/dd/yy',
                        showOn: 'button',
                        changeYear: true,
                        changeMonth: true,     
                        buttonImageOnly: true,
                        buttonImage: "images/calendar.gif",
                        buttonText: "Select date",
                        showButtonPanel: true,
                        onSelect: function (dateText, inst) {
                            inst.input.focus();
                            if (typeof (inst.id) === "string" && inst.id.substr(0, 3) === "gs_") {
                                 $(inst.id).val(dateText);
                                 grid[0].triggerToolbar();
                            }
                            else {
                                // to refresh the filter
                                $(inst).trigger("change");
                            }
                        }
                    });
                }, 100);
            };
    
            grid.jqGrid({
                url: '${pageContext.request.contextPath}/getTrucksJSONAction',
                datatype: "json",
                mtype: 'GET',
                colNames: ['Truck ID', 'Status', 'Carrier Code', 'Date Created', 'Date Closed', 'T1 Status', 'Truck Arrived'],
                colModel: [
                    {name: 'truckId', key:true, index: 'truckId', align: 'center', width: 100},
                    {name: 'status', index: 'status', align: 'center', width: 100},
                    {name: 'carrierName', index: 'carrierName', align: 'center', width: 100},
                    {name: 'createdDate', index: 'createdDate', align: 'center', width: 100},
                    {name: 'closedDate',  index: 'closedDate', align: 'center', width: 100},
                    {name: 't1Status', sortable: false, align: 'center', width: 100, fixed: true,
                        formatter: function (celvalue) {
                            return celvalue ?
                                "<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
                                "<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
                        }} ,
                    {name: 'truckArrived', sortable: false, align: 'center', width: 100, fixed: true,
                            formatter: function (celvalue) {
                                return celvalue ?
                                    "<img src='http://www.clker.com/cliparts/q/j/I/0/8/d/green-circle-icon-md.png' alt='green light' style='width:15px;height:15px'/>" :
                                    "<img src='http://www.iconsdb.com/icons/preview/red/circle-xxl.png' alt='red light' style='width:10px;height:10px'/>";
                            }}    
                ],
                rowNum: 10,
                height: 300,
                autoheight: true,
                autowidth: true,
                rowList: [10, 20, 30],
                pager: jQuery('#truck_grid_pager'),
                sortname: 'truckId',
                sortorder: "desc",
                jsonReader: {
                    root: "records",
                    page: "page",
                    total: "total",
                    records: "rows",
                    repeatitems: false
                },
                viewrecords: true,
                altRows: false,
                gridview: true,
                hidegrid: false,
                multiselect:true,
                recordtext: '',
                emptyrecords: 'No Trucks',
                forceFit: true,
                caption: "Trucks Overview",
                loadComplete: function() { 
                    // Reload the grid after changing paginattion
                    var allRecords = grid.getGridParam('lastpage') * grid.getGridParam('records');
                    grid.jqGrid('setGridParam', { 
                        recordtext: allRecords + ' Trucks(s) Found. Displaying {0} to {1}'});   
                    $(this).trigger("reloadGrid");
                    async: false,
                    setSearchSelect('status');
                    setSearchSelect('carrierName');
                    grid.jqGrid('setColProp', 'truckId', {
                        searchoptions : {
                            sopt : [ 'bw' ],
                            dataInit : function(elem) {
                               $(elem).autocomplete({
                                  source : getUniqueNames('truckId'),
                                  delay : 0,
                                  minLength : 0
                               });
                           }
                        }
                    });   
                    grid.jqGrid('setColProp', 'createdDate', {
                        sorttype: 'date', editable: true,
                            editoptions: { dataInit: initDateWithButton, size: 8 },
                            searchoptions: {
                                sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
                                dataInit: initDateWithButton
                            }
                    });   
                    gridData = $(this).jqGrid("getGridParam", "data");
                    grid.jqGrid('filterToolbar', {autoSearch: true});
                },
            }).navGrid('#truck_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true})
            .navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag",  position:"first", title:"Truck Arrived",
                onClickButton: function(){ 
                    var i;
                    var data = grid.jqGrid("getGridParam", "data");
                    var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
                    for (i = 0; i < data.length; i++) {
                        if (selRowIds.indexOf(data[i].truckId) > -1) {
                            data[i].truckArrived = true;
                        }
                    }
                    grid.trigger("reloadGrid");
                 }
            })
            .navButtonAdd('#truck_grid_pager', {caption:"Ship Confirm", buttonicon:"ui-icon-circle-check",  position:"first", title:"Ship Confirm",
                onClickButton: function(){ 
                 alert("Ship has been confirmed");}
            });
    
            orderGridDialog.dialog({
                autoOpen: false,
                width: 1000,
                height: 400,
                draggable: false,
                show: {
                    effect: "blind",
                    duration: 500
                },
                hide: {
                    effect: "blind",
                    duration: 250
                },
                close: function(event, ui){
                    orderGridDialog.text('Loading Grid...');
                }
            });
        });
    
    </script>
    </head>
    <body>
    <table id="truck_grid"></table>
    <div id="truck_grid_pager"></div>
    <div id="truck_grid_dialog" title="Orders Overview">Loading...</div>
    </body>
    </html>
    
    
    The problem happens in the last section of the code, namely:
    
            .navButtonAdd('#truck_grid_pager', {caption:"Truck Arrived", buttonicon:"ui-icon-flag",  position:"first", title:"Truck Arrived",
                onClickButton: function(){ 
                    var i;
                    var data = grid.jqGrid("getGridParam", "data");
                    var selRowIds = grid.jqGrid('getGridParam', 'selarrrow');
                    for (i = 0; i < data.length; i++) {
                        if (selRowIds.indexOf(data[i].truckId) > -1) {
                            data[i].truckArrived = true;
                        }
                    }
                    grid.trigger("reloadGrid");
                 }
            })
    

    The second problem I have is when grid.trigger("reloadGrid") is called, the truckArrived icon is not changed from red to green as expected.