在每次重新访问页面时触发搜索 jqgrid 过滤器

Posted

技术标签:

【中文标题】在每次重新访问页面时触发搜索 jqgrid 过滤器【英文标题】:Trigger search for jqgrid filter on every revisit of page 【发布时间】:2013-10-07 18:52:10 【问题描述】:

需要保存过滤条件。我在会话中的过滤器中有这些值,但使用 jqGrid API 将它们用于 TRIGGER SEARCH 似乎是不可能的。需要知道所需的确切功能或步骤集。

var options = 
        url:inboxGridUrl,
        datatype: 'json',
        mtype: 'GET',
        colNames:['EvaluationId','Policy', 'Task','Status','Condition','Due Date','Eff Date','Agency Name','Agency No','Producer Name','Producer No','Review Start','Location','Task Group'],
        colModel :[ 
                   name:'uwEvaluationId', label: 'EvaluationId',formatter:'integer',editable: true,hidden:true, frozen : true,editoptions: disabled: true, size:5,
                   name:'policyNum',label: 'Policy',width: 125,editable: true,formatter:formatPolicyLink,editrules: required: true,
                   name:'transactionType',label: 'Task',width: 40,editable: true,editrules: required: true,
                   name:'uwDecision',label: 'Status',width: 50,editable: true,edittype: 'select',editrules: edithidden:true,editoptions: required: true,
                   name:'taskCondition',label: 'Condition',align: 'left',width: 60,editable: true,
                       editrules: required: true, integer: true,editoptions: size:5, maxlength: 4,
                   name:'dueDate',label: 'Due Date',align: 'left',width: 70,editable: true,edittype: 'select',editoptions: required: true,
                   name:'policyEffectiveDate',label: 'Eff Date',width: 70,editable: true,edittype: 'select',editrules: required: true,
                   name:'agencyName',label: 'Agency Name',editable: true,width: 120,edittype: 'select',editrules: required: true,
                   name:'agentCode',label: 'Agency No.',editable: true,width: 75,edittype: 'select',editrules: required: true,
                   name:'producerName',label: 'Producer Name',width: 120,editable: true,edittype: 'select',editrules: required: true,
                   name:'producerCode',label: 'Producer No',width: 75,editable: true,edittype: 'select',editrules: required: true,
                   name:'startDate',label: 'Review Start',width: 80,editable: true,edittype: 'select',editrules: required: true,
                   name:'locationCd',label: 'Location',width: 70,editable: true,edittype: 'select',editrules: required: true,
                   name:'groupName',label: 'Task Group',width: 75,editable: true,edittype: 'select',editrules: required: true,
                 ],  


        prmNames: rows: 'max', search: null,
        rowNum:20000,
        height: 'auto',

        sortname: 'id',
        sortable: true,
        forceFit : true,
        repeatitems:true,
        sortorder: 'desc',
        loadonce:true,
        shrinktofit:true,
        datatype: 'json',

        recreateForm:true,
        multipleGroup:true,
        multipleSearch:true,
        multiselect: true,

        gridview: true,
        hidegrid: false,
        viewrecords: true,      
        gridview: true,            
        refreshtitle: "Reload Tasks",
        caption: 'Inbox',
        //code to display sort icons on load
        onSortCol: function (index, idxcol, sortorder) 
            if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol && this.p.colModel[this.p.lastsort].sortable !== false) 
                    $(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
            
        ,
        loadComplete: function() 

            rowCount = $("#taskList").getGridParam("records");
            if (rowCount > 0)
                $("#warningMessage").html("");
                $("#warningBlock").hide();
                $("#recordsCount").html(rowCount);
                $("#messageBlock").show();                  
             else if (rowCount <= 0) 
                $("#messageBlock").hide();
                $("#warningMessage").html("No Tasks Found");
                $("#warningBlock").show();
            


        ,
        ignoreCase: true,
        jsonReader : 
               root: "rows",
               page: "page",
               total: "total",
               records: "records",
               repeatitems: false,
               cell: "cell",
               id: "uwEvaluationId"
               ,
        postData: filters: groupOp: "AND", rules: [field: "policyNum", op: "bw", data: "h" ] 

; 

    $("#taskList").jqGrid(options);
    $("#taskList").jqGrid('navGrid','#pager',edit:false,add:false,del:false,search:false,refresh:true);
    $("#taskList").jqGrid('filterToolbar', stringReuslt:true, searchOnEnter:false, defaultSearch:"cn", autoSearch:true 

    );

【问题讨论】:

【参考方案1】:

如果您在会话中或任何地方有值,并且您希望将这些值传递到将应用于网格的过滤器中,您可以这样做:

var grid = $('#gridName'); //setup a grid variable so we only hit the DOMonce

            var f =  groupOp: "AND", rules: [] ;
            if (SessionFilterItem1 != null)  f.rules.push( field: "SessionFilterItem1", op: "cn", data: SessionFilterItem1 ); 

            grid.jqGrid().trigger('reloadGrid', [ page: 1]);


 //Grid Parameter to indicate you are searching
 'search: true,'

这将更改重新加载时从网格发出的请求。 (如果您不希望网格在页面加载时加载,请将其数据类型设置为本地,然后重置该值并设置您希望网格从何处请求数据。

【讨论】:

感谢您的回复,但我尝试了几次,但对网格没有影响,因为每次我回到页面时它都不会加载过滤器值。因此,寻找任何可行的工作或一些可以帮助将标准值发布到网格的功能。谢谢 @user1911538 如上所述,您需要设置网格参数search:true,,然后您应该会在数据请求中看到您设置的搜索值。 感谢您的选择。我正在调查它会尝试返回以防没有障碍。谢谢 我使用了这个想法并尝试了类似的代码。只是似乎不起作用,因为演示中实现的想法可能是针对本地数据的,但是当未本地化时,它不会触发网格搜索。无论如何,谢谢你的例子。它给了我很多尝试。【参考方案2】:

要应用过滤器,您必须将 jqGrid 的 search: true 选项与 postData.filters 一起设置。顺便说一下filters 属性的类型应该是string 而不是object。所以你应该在将过滤器分配给postData.filters之前使用JSON.stringify

尝试使用the answer 和this one 中的the demo。我在答案中演示了如何将过滤器和其他信息保存在localStorage

【讨论】:

感谢您提供的各种链接。也欣赏你在这方面所做的工作。对于像 jqgrid 这样的东西,这种支持很棒。谢谢 @user1911538:不客气!你的问题现在解决了吗?你可以"accept"回答。我看到你对你的老问题写了自己的答案。即使在这种情况下,我也建议您接受这样的答案。 还没有奥列格。我似乎得到了网格并在重新加载时保存了它的值,但即使现在也无法过滤触发器。这次甚至在第一次加载时也没有过滤 真的需要将json存储在localstorage中吗?通过 url 以 json 形式传入的数据呢?谢谢【参考方案3】:

function formatPolicyLink(cellvalue, options, rowObject) var 链接 = '' + 单元格值 + '';

        return link;
        

        $.jgrid.formatter.integer.thousandsSeparator = ',';
        $.jgrid.formatter.number.thousandsSeparator = ',';
        $.jgrid.formatter.currency.thousandsSeparator = ',';
        $(document).ready(function () 
            'use strict';
            var myData = [
                  /*  id: "1",  invdate: "2007-10-01", name: "test",   note: "note",   amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00",
                    id: "2",  invdate: "2007-10-02", name: "test2",  note: "note2",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00",
                    id: "3",  invdate: "2011-07-30", name: "test3",  note: "note3",  amount: "400.00", tax: "30.00", closed: true,  ship_via: "FE", total: "430.00",
                    id: "4",  invdate: "2007-10-04", name: "test4",  note: "note4",  amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00",
                    id: "5",  invdate: "2007-10-31", name: "test5",  note: "note5",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00",
                    id: "6",  invdate: "2007-09-06", name: "test6",  note: "note6",  amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00",
                    id: "7",  invdate: "2011-07-30", name: "test7",  note: "note7",  amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00",
                    id: "8",  invdate: "2007-10-03", name: "test8",  note: "note8",  amount: "300.00", tax: "20.00", closed: true,  ship_via: "FE", total: "320.00",
                    id: "9",  invdate: "2007-09-01", name: "test9",  note: "note9",  amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00",
                    id: "10", invdate: "2007-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true,  ship_via: "TN", total: "530.00",
                    id: "11", invdate: "2007-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00",
                    id: "12", invdate: "2007-09-10", name: "test12", note: "note12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00"

                    */


                  ],
                $grid = $("#taskList"),
                initDateSearch = function (elem) 
                    setTimeout(function () 
                        $(elem).datepicker(
                            dateFormat: 'dd-M-yy',
                            autoSize: true,
                            //showOn: 'button', // it dosn't work in searching dialog
                            changeYear: true,
                            changeMonth: true,
                            showButtonPanel: true,
                            showWeek: true,
                            onSelect: function () 
                                if (this.id.substr(0, 3) === "gs_") 
                                    setTimeout(function () 
                                        $grid[0].triggerToolbar();
                                    , 50);
                                 else 
                                    // to refresh the filter
                                    $(this).trigger('change');
                                
                            
                        );
                    , 100);
                ,
                numberSearchOptions = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
                numberTemplate = formatter: 'number', align: 'right', sorttype: 'number',
                    searchoptions:  sopt: numberSearchOptions ,
                myDefaultSearch = 'cn',
                getColumnIndex = function (grid, columnIndex) 
                    var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
                    for (i = 0; i < l; i++) 
                        if ((cm[i].index || cm[i].name) === columnIndex) 
                            return i; // return the colModel index
                        
                    
                    return -1;
                ,
                refreshSerchingToolbar = function ($grid, myDefaultSearch) 
                    var postData = $grid.jqGrid('getGridParam', 'postData'), filters, i, l,
                        rules, rule, iCol, cm = $grid.jqGrid('getGridParam', 'colModel'),
                        cmi, control, tagName;

                    for (i = 0, l = cm.length; i < l; i++) 
                        control = $("#gs_" + $.jgrid.jqID(cm[i].name));
                        if (control.length > 0) 
                            tagName = control[0].tagName.toUpperCase();
                            if (tagName === "SELECT")  // && cmi.stype === "select"
                                control.find("option[value='']")
                                    .attr('selected', 'selected');
                             else if (tagName === "INPUT") 
                                control.val('');
                            
                        
                    

                    if (typeof (postData.filters) === "string" &&
                            typeof ($grid[0].ftoolbar) === "boolean" && $grid[0].ftoolbar) 

                        filters = $.parseJSON(postData.filters);
                        if (filters && filters.groupOp === "AND" && typeof (filters.groups) === "undefined") 
                            // only in case of advance searching without grouping we import filters in the
                            // searching toolbar
                            rules = filters.rules;
                            for (i = 0, l = rules.length; i < l; i++) 
                                rule = rules[i];
                                iCol = getColumnIndex($grid, rule.field);
                                if (iCol >= 0) 
                                    cmi = cm[iCol];
                                    control = $("#gs_" + $.jgrid.jqID(cmi.name));
                                    if (control.length > 0 &&
                                            (((typeof (cmi.searchoptions) === "undefined" ||
                                            typeof (cmi.searchoptions.sopt) === "undefined")
                                            && rule.op === myDefaultSearch) ||
                                              (typeof (cmi.searchoptions) === "object" &&
                                                  $.isArray(cmi.searchoptions.sopt) &&
                                                  cmi.searchoptions.sopt.length > 0 &&
                                                  cmi.searchoptions.sopt[0] === rule.op))) 
                                        tagName = control[0].tagName.toUpperCase();
                                        if (tagName === "SELECT")  // && cmi.stype === "select"
                                            control.find("option[value='" + $.jgrid.jqID(rule.data) + "']")
                                                .attr('selected', 'selected');
                                         else if (tagName === "INPUT") 
                                            control.val(rule.data);
                                        
                                    
                                
                            
                        
                    
                ,
                cm = [ 
                      name:'uwEvaluationId', label: 'EvaluationId',formatter:'integer',editable: true,hidden:true, frozen : true,editoptions: disabled: true, size:5,
                      name:'policyNum',label: 'Policy',width: 125,editable: true,formatter:formatPolicyLink,editrules: required: true,
                      name:'transactionType',label: 'Task',width: 40,editable: true,editrules: required: true,
                      name:'uwDecision',label: 'Status',width: 50,editable: true,edittype: 'select',editrules: edithidden:true,editoptions: required: true,
                      name:'taskCondition',label: 'Condition',align: 'left',width: 60,editable: true,
                       editrules: required: true, integer: true,editoptions: size:5, maxlength: 4,
                      name:'dueDate',label: 'Due Date',align: 'left',width: 70,editable: true,edittype: 'select',editoptions: required: true,
                      name:'policyEffectiveDate',label: 'Eff Date',width: 70,editable: true,edittype: 'select',editrules: required: true,
                      name:'agencyName',label: 'Agency Name',editable: true,width: 120,edittype: 'select',editrules: required: true,
                      name:'agentCode',label: 'Agency No.',editable: true,width: 75,edittype: 'select',editrules: required: true,
                      name:'producerName',label: 'Producer Name',width: 120,editable: true,edittype: 'select',editrules: required: true,
                      name:'producerCode',label: 'Producer No',width: 75,editable: true,edittype: 'select',editrules: required: true,
                      name:'startDate',label: 'Review Start',width: 80,editable: true,edittype: 'select',editrules: required: true,
                      name:'locationCd',label: 'Location',width: 70,editable: true,edittype: 'select',editrules: required: true,
                      name:'groupName',label: 'Task Group',width: 75,editable: true,edittype: 'select',editrules: required: true,
           ],
                saveObjectInLocalStorage = function (storageItemName, object) 
                    if (typeof window.localStorage !== 'undefined') 
                        window.localStorage.setItem(storageItemName, JSON.stringify(object));
                    
                ,
                removeObjectFromLocalStorage = function (storageItemName) 
                    if (typeof window.localStorage !== 'undefined') 
                        window.localStorage.removeItem(storageItemName);
                    
                ,
                getObjectFromLocalStorage = function (storageItemName) 
                    if (typeof window.localStorage !== 'undefined') 
                        return JSON.parse(window.localStorage.getItem(storageItemName));
                    
                ,
                myColumnStateName = function (grid) 
                    return window.location.pathname + '#' + grid[0].id;
                ,
                idsOfSelectedRows = [],
                saveColumnState = function (perm) 
                    var colModel = this.jqGrid('getGridParam', 'colModel'), i, l = colModel.length, colItem, cmName,
                        postData = this.jqGrid('getGridParam', 'postData'),
                        columnsState = 
                            search: this.jqGrid('getGridParam', 'search'),
                            page: this.jqGrid('getGridParam', 'page'),
                            rowNum: this.jqGrid('getGridParam', 'rowNum'),
                            sortname: this.jqGrid('getGridParam', 'sortname'),
                            sortorder: this.jqGrid('getGridParam', 'sortorder'),
                            permutation: perm,
                            selectedRows: idsOfSelectedRows,
                            colStates: 
                        ,
                        colStates = columnsState.colStates;

                    if (typeof (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 = typeof (myColumnsState) !== 'undefined' && myColumnsState !== null;
            idsOfSelectedRows = isColState && typeof (myColumnsState.selectedRows) !== "undefined" ? myColumnsState.selectedRows : [];

            var inboxGridUrl = "/uw-ui/inbox/tasks/Team";           


            $grid.jqGrid(
                url:inboxGridUrl,
                datatype: 'json',
                mtype: 'GET',
                colNames:['EvaluationId','Policy', 'Task','Status','Condition','Due Date','Eff Date','Agency Name','Agency No','Producer Name','Producer No','Review Start','Location','Task Group'],
                colModel :cm,
                rowNum: isColState ? myColumnsState.rowNum : 10,
                rowList: [5, 10, 20],
             //   pager: '#pager',
               // gridview: true,
              //  loadonce: true,
                page: isColState ? myColumnsState.page : 1,
                search: isColState ? myColumnsState.search : false,
                postData: isColState ?  filters: myColumnsState.filters  : ,
                sortname: isColState ? myColumnsState.sortname : 'invdate',
                sortorder: isColState ? myColumnsState.sortorder : 'desc',
              //  rownumbers: true,
                ignoreCase: true,
                multiselect: true,
                //shrinkToFit: false,
                //viewrecords: true,
                hidegrid:false,
                caption: 'Inbox',
                height: 'auto',
                onSelectRow: function (id, isSelected) 
                    updateIdsOfSelectedRows(id, isSelected);
                    saveColumnState.call($grid, $grid[0].p.remapColumns);
                ,
                onSelectAll: function (aRowids, isSelected) 
                    var i, count, id;
                    for (i = 0, count = aRowids.length; i < count; i++) 
                        id = aRowids[i];
                        updateIdsOfSelectedRows(id, isSelected);
                    
                    saveColumnState.call($grid, $grid[0].p.remapColumns);
                ,
                loadComplete: function () 
                    var $this = $(this), i, count;

                    if (firstLoad) 
                        firstLoad = false;
                        if (isColState) 
                            $this.jqGrid("remapColumns", myColumnsState.permutation, true);
                        
                        if (typeof (this.ftoolbar) !== "boolean" || !this.ftoolbar) 
                            // create toolbar if needed
                            $this.jqGrid('filterToolbar',
                                stringResult: true, searchOnEnter: true, defaultSearch: myDefaultSearch);
                        
                    
                    refreshSerchingToolbar($this, myDefaultSearch);
                    for (i = 0, count = idsOfSelectedRows.length; i < count; i++) 
                        $this.jqGrid('setSelection', idsOfSelectedRows[i], false);
                    
                    saveColumnState.call($this, this.p.remapColumns);
                ,
                resizeStop: function () 
                    saveColumnState.call($grid, $grid[0].p.remapColumns);
                
            );
            $.extend($.jgrid.search, 
                multipleSearch: true,
                multipleGroup: true,
                recreateFilter: true,
                closeOnEscape: true,
                closeAfterSearch: true,
                overlay: 0
            );
            $grid.jqGrid('navGrid', '#pager', edit: false, add: false, del: false,search:true,refresh:true);

        );
    //]]>

【讨论】:

如果我错过了触发过滤器所需的任何属性,请告诉我。谢谢

以上是关于在每次重新访问页面时触发搜索 jqgrid 过滤器的主要内容,如果未能解决你的问题,请参考以下文章

jqGrid - 更改过滤器/搜索弹出表单 - 在页面上平展 - 不是对话框

如何在免费的 jqgrid 4.15.4 中重新加载数据

Jqgrid工具栏过滤,在尝试搜索时无法在字符串''上创建属性'过滤器'

jqGrid过滤器或按日期搜索不起作用客户端

搜索不适用于 JQGrid 中的过滤器工具栏

记住(持久化)jqGrid的过滤器、排序顺序和当前页面