Search code examples
tabulator

Change search criteria when HeaderFilter results is zero


I'd like the search criteria to adapt when a user searches using the headerFilter search box, swapping between "equal" / "like" search rules depending on number of results

example > values are ["a", "b", "ac", "ab"] for column

If "a" is searched, only show results where value_search === row_value. If the previous criteria returns 0 rows, change search criteria to row_value.includes(value_search)

Thus searching the above example values should result in the following

Search : "a" should be Results : "a" only

Search : "b" should be Results : "b" only

Search : "ac" should be Results : "ac" only

Search : "c" should be Results : "ac" (this is thus a "like" search as its not an exact match to any values)

Search : "ab" should be Results : "ab" only - (not "a" nor "b" as an "equal" search has returned results)

Im not sure if this is possible but would be great if it is. I have sofar not been able to get this working.


It would also be great if the dropdown values (when used with headerFilterParams: {values: true}) also filtered with the users' input. For example the suggestions should react with "a", "ac", "ab" if "a" was entered into the header filter.


Solution

  • You can use a custom header filter function to use any rule you like for filtering, the headerFilterFunc column definition property can be used for this:

    function customHeaderFilter(headerValue, rowValue, rowData, filterParams){
        //headerValue - the value of the header filter element
        //rowValue - the value of the column in this row
        //rowData - the data for the row being filtered
        //filterParams - params object passed to the headerFilterFuncParams property
    
        return rowData.name == filterParams.name && rowValue < headerValue; //must return a boolean, true if it passes the filter.
    }
    
    //column definition object in table constructor
    {title:"Age", field:"age", headerFilter:"input", headerFilterPlaceholder:"Max Age", headerFilterFunc:customHeaderFilter, headerFilterFuncParams:{name:"bob"}}
    

    Checkout the Filter Documentation for full details

    The filter function itself is doing the filtering so is unaware of the number of rows that make it through. but you could use the dataFiltered callback to check the number of rows that made it through the filter, as it is passed in a row array.

    dataFiltered:function(filters, rows){
        //filters - array of filters currently applied
        //rows - array of row components that pass the filters
    }
    

    You could then change the table filter if the row array length is 0