jqGrid Filter Toolbar initial default value

前端 未结 5 1989
天涯浪人
天涯浪人 2020-12-14 22:02

I\'m using jqGrid with the filter toolbar, i need to set an initial default filter value to one of the fields so that only rows with status \'Open\' are displayed by default

5条回答
  •  臣服心动
    2020-12-14 22:22

    All the tips I read didn't work for me. So I tried a lot and did some research in the jqGrid source code. It's much easier to integrate a "default value" or "saved search values" functionality, if you use the beforeRequest event.

    I had to solve some problems:

    1. Although it's the beforeRequest event, the search parameters you set there won't be used until you call triggerToolbar.
    2. triggerToolbar does not only set the new request with the new search parameters, but also triggers a reload of the table data - but the previous request is still running, so you do the same request twice (both with the new search parameters).
    3. Set default values but allow the user to clear/overwrite them.
    4. Avoid endless loops and keep the old search functionality.

    Here's the code:

    beforeRequest: function ()
    {
        // Activate filter toolbar and define "beforeSearch" callback
        // to avoid a second search request on page load, triggered 
        // by "triggerToolbar()" when not set.
        //
        // Important: 
        // "beforeSearch" has to return true to avoid the second
        // request on page load, but it has to return false for all
        // following searches (otherwise it wouldn't be possible to
        // submit new searches by pressing Enter in search input fields).
        $("#myTable").jqGrid('filterToolbar', {
            beforeSearch: function(){
                if ($(this).data('firstSearchAbortedFlag') != '1')
                {
                    $(this).data('firstSearchAbortedFlag', '1');
                    return true;
                }
    
                // Return false or add your customizations here...
                return false;
            }
        });
    
        if ($(this).data('defaultValuesSetFlag') != '1')
        {
            // Set flag to set default only the first time when
            // the page is loaded.
            $(this).data('defaultValuesSetFlag', '1');
    
            // Set default values...
            // (id = 'gs_' + fieldname)
            $('#gs_field_a').val('value a');
            $('#gs_field_b').val('value b');
    
            // Call "triggerToolbar" to use the previously set
            // parameters for the current search.
            // 
            // Important: 
            // Set "beforeSearch" callback for "filterToolbar" to avoid
            // a second search request, triggered by "triggerToolbar".
            $("#myTable")[0].triggerToolbar();
        }
    }
    

    I hope this helps you!

提交回复
热议问题