jqgrid dynamic search options on search

16,661

I am not sure, that I understand correctly what you need.

Instead of setting value property of searchoptions you can use dataUrl property which makes Ajax request to fill the select options. Here and here you can find some code examples which coudld help to implement dataUrl.

Additionally you should never use datatype as function just to make an jQuery.ajax call yourself. jqGrid has many options like ajaxGridOptions, jsonReader options, serializeRowData callback and so on. I recommend you to read the answer and this one which contains dome projects which you can download and test.

If you use standard jqGrid mechanism and you still need to make some modifications on the data of on the grid (like setting some jqGrid options) you can use beforeProcessing callback. The callback beforeProcessing allows to make changes in colModel or any jqGrid option before jqGrid process the data returned from the server.

Share:
16,661
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    Below I have copied my jqGrid and trimmed out a lot of unrelated attributes and such, however the base code below is enough to encapsulate my question.

    I have a dynamic filter that is populated upon successful return of the ajax call. The json that is returned holds the string value of the drop down (uniqueRunDates) among other values. The string (uniqueRunDates) is dynamically added to the column using the 'setColProp'. Upon completion of the jgGrid the next line of code in the function calls a reload of the grid and the new filter takes in place.

    The filter works great just as a static(like 'JobStatus') filter does with one exception. Searching.

    The grid has three searches (text box and two drop downs [one being the uniqueRunDates])that can be used interchangeably. When a user types something in the text box, the grid is correctly updated, the return json has the new unique dates, and I add them via the 'setColProp'. The final piece to that is the 'reloadGrid' must be called. The issue is how do I do that???

    In the first go around, the code after the creation of the grid is executed. When a search is performed, just this jgGrid code is executed. I can not put the 'reloadGrid' in the success call of course as that will make a loop. I have attempted to use the 'afterSearch' property of the toolbar, but that doesnt appear to be firing when i need it to be.

    Am I going about this issue the right way? Is there an easier way to handle this seemly common concept? Dynamic search filters? Thanks very much for any help and/or guidance you can provide.

     $("#gridTable").jqGrid({
        async: false,
        datatype: function (jqGridModel) {
            $.ajax({
                async: false,
                url: 'Application.aspx/getJqGridData',
                data: JSON.stringify({ 'rptPath': rptPath, 'jqGridModel': jqGridModel, 'userId': userId }),
                success: function (data, textStatus, jqXHR) {
                    populateGrid(data);
                    var uniqueRunDates = (JSON.parse(data)).uniqueDates;
    
                    $("#gridTable").jqGrid('setColProp', 'Run_Date', {
                        stype: 'select',
                        searchoptions: { value: uniqueRunDates, sopt: ['dateEq'] }
                    });
                }                
            });
        },
        colNames: ['', 'Report Name', 'Run Status', 'Run Date', 'Expiring On', 'Category', 'Actions'],
        colModel: [
           { name: 'Run_Date', index: 'RunDate', align: 'center', title: false, sortable: true, width: 40 }
           { name: 'Report_Name', index: 'ReportNameDisplay', align: 'left', title: false, sortable: true, formatter: reportLinkFormatter },
           { name: 'Run_Status', index: 'JobStatus', align: 'left', title: false, sortable: true, width: 50,
                stype: 'select',
                searchoptions: { value: ':All Status;Completed:Completed;Failed:Failed;Pending:Pending;No Data Returned:No Data Returned;:Returned' }
            },
        ],
        pager: jQuery('#gridPager'),
        rowNum: 15,
        rowList: [15, 25, 35, 50],
        sortname: 'RunDate',
        sortorder: "desc",
        height: '100%',
        multiselect: true
        }
    });
    
    //Refresh necessary for the dynamically added 'run date' filter.
    $("#gridTable").trigger("reloadGrid");
    
    $('#gridTable').jqGrid('filterToolbar', {
        stringResult: true
    });
    

    . . . . .

    Update I have updated the grid to follow the suggestions below.

    I am able to query the server, and return the string version of the JSON object. I am also able to see the return value in the 'beforeProcessing' method and it appears good. However the grid no longer populates. I am not certain the jsonReader is setup properly with my return format. data.d = {"total":2,"page":1,"records":25,"rows":[{"id":"23","cell":["0","xxx","xxx",...]}....]

    I am thinking it is something with the types not lining up... ideas?

    $("#gridTable").jqGrid({
        async: false,
        url: 'Application.aspx/getJqGridData',
        ajaxGridOptions: { contentType: "application/json" },
        serializeGridData: function (postData) {
            if (postData.filters == undefined) postData.filters = null;
            postData.jqGridModel = { page: postData.page, _search: postData._search, rows: postData.rows,
                sidx: postData.sidx, sord: postData.sord, filters: postData.filters
            };
            postData.rptPath = rptPath;
            postData.userId = userId;
            return JSON.stringify(postData);
        },
        contentType: 'application/json; charset=utf-8',
        datatype: "json",
        mtype: 'POST',
        beforeProcessing: function (data) {    
        },
        colNames: ['', 'Report Name', 'Run Status', 'Run Date', 'Expiring On', 'Category', 'Actions'],
        colModel: [
            { name: 'Is_Fav', index: 'Favorites', align: 'center', title: false, sortable: false, search: false, width: 5, formatter: favImageFormatter },
            { name: 'Report_Name', index: 'ReportNameDisplay', align: 'left', title: false, sortable: true, formatter: reportLinkFormatter },
            { name: 'Run_Status', index: 'JobStatus', align: 'left', title: false, sortable: true, width: 50,
                stype: 'select',
                searchoptions: { value: ':All Status;Completed:Completed;Failed:Failed;Pending:Pending;No Data Returned:No Data Returned;:Returned' }
            },
            { name: 'Run_Date', index: 'RunDate', align: 'center', title: false, sortable: true, width: 40,
                selectOptions: {
                    dataUrl: 'Application.aspx/getJqGridData',
                    buildSelect: function (data) {
                        var gData;
                        if (data.hasOwnProperty('d')) gData = data.d;
                        else gData = data;
    
                        var uniqueRunDates = (JSON.parse(gData)).uniqueDates;
    
                        var html = '<select>', length = gData.length, i = 0, item;
                        for (; i < length; i++) {
                            item = d[i];
                            html += '<option value=' + item + '>' + item + '</option>';
                        }
                        html += '</select>';
                        return html
                    }
                }
            },
            { name: 'Expiring_On', index: 'ExpirationDate', align: 'center', title: false, sortable: true, width: 40, search: false },
            { name: 'Category', index: 'Category', align: 'left', title: false, sortable: true, width: 80 },
            { name: 'Actions', index: '', align: 'left', title: false, sortable: false, width: 25, search: false, formatter: actionsFormatter }
        ],
        pager: jQuery('#gridPager'),
        rowNum: 15,
        rowList: [15, 25, 35, 50],
        sortname: 'RunDate',
        sortorder: "desc",
        height: '100%',
        viewrecords: true,
        sortable: true,
        jsonReader: {
            root: "d.rows",
            page: "d.page",
            total: "d.total",
            records: "d.records"            
        },
        forceFit: true,
        multiselect: true,
        loadError: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        },
        gridComplete: function () {
            doGridComplete(rptPath);
        },
        beforeSelectRow: function (rowid, event) {
            // Only allow row selection if the chekbox in the row is clicked
            var index = $.jgrid.getCellIndex(event.target);
            if (index == 0) {
                return true;
            }
            return false;
        },
        subGrid: true,
        subGridRowExpanded: function (subgrid_id, row_id) {
            getReportDetails(subgrid_id, row_id, rptPath);
        }
    });
    
    $('#gridTable').jqGrid('filterToolbar', {
        stringResult: true
    });