javascriptjqueryjqgrid

jqGrid dynamically change search operator type on button click


This is my jqgrid

enter image description here

Grid related code

var lastsel2;
var containsOrNot = 'contains';
jQuery(document).ready(function(){
    jQuery("#list").jqGrid({
        url: "{{ asset('/app_dev.php/_thrace-datagrid/data/item_lookup_management') }}",
        postData: {
            masterGridRowId: {{ VPK }}
        },
        datatype: "json",
        mtype: 'POST',
        colNames: ['Item No', 'Description 1', 'Vendor Item No','Report Dec','Location','On Hand','Exp balance','Available now','Lead Time','Type', 'Vendor #', 'Status', 'Stocked', 'Product Line', 'Creator'],
        colModel: [
            {
                name: "I_ItemNumID",
                index: "u.I_ItemNumID",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '70'
            },
            {
                name: "I_Desc1",
                index: "u.I_Desc1",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '70'
            },
            {
                name: "I_VendorItemNum",
                index: "u.I_VendorItemNum",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_ReportDec",
                index: "u.I_ReportDec",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_BinNum",
                index: "u.I_BinNum",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_OnHandTotal",
                index: "u.I_OnHandTotal",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "R_ClosingBalance",
                index: "u.R_ClosingBalance",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "R_BalanceActual",
                index: "u.R_BalanceActual",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_LeadTime",
                index: "u.I_LeadTime",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_ItemType",
                index: "u.I_ItemType",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_VendorNumID",
                index: "u.I_VendorNumID",
                editable: false,
                align: 'left',
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                width: '100'
            },
            {
                name: "I_Status",
                index: "u.I_Status",
                editable: false,
                width: 100,
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                align: 'left'
            },
            {
                name: "I_isStocked",
                index: "u.I_isStocked",
                editable: false,
                width: 100,
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                align: 'left'
            },
            {
                name: "I_ProductLine",
                index: "u.I_ProductLine",
                editable: false,
                width: 150,
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                align: 'left'
            },
            {
                name: "I_CreatedSysUser",
                index: "u.I_CreatedSysUser",
                editable: false,
                width: 100,
                searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
                align: 'left'
            }
        ],
        ondblClickRow: function(rowid) {
            var rowData = jQuery('#list').jqGrid ('getRowData', rowid);
            window.opener.document.getElementById('productDetail_V_PK').value = rowid;
            window.opener.document.getElementById('productDetail_V_Desc').value = rowData.I_ItemNumID;
            window.close();
        },
        height: 400,
        rowNum: 50,
        rowTotal: 1000000,
        width: 3000,
        gridview: true,
        autoencode: false,
        pager: '#pager',
        shrinkToFit: true,
        sortable: true,
        sortname:"u.id",
        sortorder: "desc",
        viewrecords: true,
        //multiselect: true,
        loadonce:false,
        onCellSelect: function(row, col, content, event) {
            var cm = jQuery("#list").jqGrid("getGridParam", "colModel");
            //alert(cm[col].name);
            if (window.getSelection) {
                selection = window.getSelection();
            } else if (document.selection) {
                selection = document.selection.createRange();
            }
            selectionColumn = cm[col].name;
            selection.toString() !== '' && $("#gs_"+selectionColumn).val(selection.toString());
        },
        rowList: [50, 100, 500, 1000]
    });
    jQuery("#list").jqGrid('navGrid',"#pager",{ del:false, add:false, edit:false},{multipleSearch:true}).navButtonAdd('#pager',{
        caption: "Select",
        buttonicon:"ui-icon-disk",
        onClickButton: function(){
            var myGrid = $('#list');
            selectedRowId = myGrid.jqGrid ('getGridParam', 'selrow');
            var rowData = jQuery('#list').jqGrid ('getRowData', selectedRowId);
            if(selectedRowId != null)
            {
                window.opener.document.getElementById('productDetail_V_PK').value = selectedRowId;
                window.opener.document.getElementById('productDetail_V_Desc').value = rowData.I_ItemNumID;
                window.close();
            }
            else
            {
                $(function() {
                    $( "#dialog-message" ).dialog({
                        modal: true,
                        buttons: {
                            Ok: function() {
                                $( this ).dialog( "close" );
                            }
                        }
                    });
                });
            }
        },
        position:"last"
    });
    jQuery("#list").jqGrid('filterToolbar',{
        searchOperators: true,
        stringResult: true,
        searchOnEnter : true,
        sopt: ['cn','eq','ne','lt','le','gt','ge','bw','ew','nc'],
        beforeSearch: function(){
            if(containsOrNot == "notContains" && containsOrNot != "contains")
            {
                //CODE FOR EXCLUDE EXECUTE HERE
                var i, l, rules, rule, $grid = $('#list'),
                        postData = $grid.jqGrid('getGridParam', 'postData'),
                        filters = $.parseJSON(postData.filters);
                if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
                    rules = filters.rules;
                    for (i = 0; i < rules.length; i++) {
                        rule = rules[i];
                        console.log(rule.op);
                        if (rule.op === 'cn') {
                            // change contains to does not contain
                            rule.op = 'nc';
                        }
                    }
                    postData.filters = JSON.stringify(filters);
                }
            }
        }}).navButtonAdd('#pager',{
        caption: "Contains",
        buttonicon:"ui-icon-disk",
        onClickButton: function(){
            containsOrNot = 'contains';
            $("#list")[0].triggerToolbar();
        },
        position:"last"
    }).navButtonAdd('#pager',{
        caption: "Excludes",
        buttonicon:"ui-icon-disk",
        onClickButton: function(){
            containsOrNot = 'notContains';
            $("#list")[0].triggerToolbar();
        },
        position:"last"
    });
    jQuery('#list').jqGrid('gridResize');
});

My grid already has code for triggering the toolbar search. $("#list")[0].triggerToolbar(); is doing my toolbarsearch on the click of a button defined in the footer part.

Currently the search is defaulted to contains. so when I select text from any column the filter of that column is populated with that selected text. And when I press on the Contains button the triggerToolbar is triggered properly.

What I would like to do? when I click on the Excludes button it should fire another triggerToolbar but with a does not contain filter. How can I dynamically change the default filter on the particular column?

Edit jqGrid version 4.8.2

UPDATE With Oleg's another answer here and the current answer I was able to achieve this. The code is updated and works as required.


Solution

  • What you want is not easy. You will have to change the operations in operation menu in every searching field. Moreover you will have to add first of all have to add searchoptions: { sopt: ['cn', 'nc']} options in all columns, because currently there are many fields which have no searchoptions.sopt. It means that one can search only by 'cn'.

    Because of complexity of the way I would recommend you to choose an alternative way. I'd suggest you to add beforeSearch callback in filterToolbar. The callback onClickButton for "Excludes" and "Contains" buttons should set some variable to different value. The variable should be available inside of beforeSearch callback of filterToolbar. Inside of beforeSearch callback you can implement the following logic. If "Contains" button is clicked it should return false (continue searching). In case of "Excludes" button is clicked one should convert the string postData.filters to object and go through every element of rules and replace "cn" value of the op property to "nc". Finally one should convert the modified searching rule from object to string and return false too to continue searching. It should work.