Set Filter - Filter List

Set Filter is an AG Grid Enterprise feature, so you’ll need a license key to use it. See Using AG Grid Enterprise for an example of how to use your license key with Dash AG Grid components.

This section describes how Filter List values can be managed through custom sorting and formatting. Supplying filter values directly to the Set Filter is also discussed.

Sorting Filter Lists

Values inside a Set Filter will be sorted by default, where the values are converted to a string value and sorted in ascending order according to their UTF-16 codes.

When a different sort order is required, a Comparator can be supplied to the set filter.

columnDefs = [
    {
        "headerName": "Age (With Comparator)",
        "field": "age",
        "filter": "agSetColumnFilter",
        "filterParams": {"comparator": {"function": "sortFilterList"}},
    },
]

The sortFilterList is a JavaScript function.

View JavaScript function used for this example

This JavaScript function must be added to the dashAgGridFunctions.js file in the assets folder

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};

dagfuncs.sortFilterList = function (a, b) {
  var valA = a == null ? 0 : parseInt(a);
  var valB = b == null ? 0 : parseInt(b);
  if (valA === valB) return 0;
  return valA > valB ? 1 : -1;
};

The Comparator used by the Set Filter is only provided the values in the first two parameters, whereas the Comparator for the Column Definition is also provided the row data as additional parameters. This is because when sorting rows, row data exists. For example, take 100 rows split across the colour values [white, black]. The column will be sorting 100 rows, however the filter will be only sorting two values.

If you are providing a Comparator that depends on the row data and you are using the Set Filter, be sure to provide the Set Filter with an alternative Comparator that doesn’t depend on the row data.

The following example demonstrates sorting Set Filter values using a comparator. Note the following:

Formatting Values

This section covers different ways to format the displayed Filter List values in the Set Filter.

Formatting Filter List values will not change the underlying value or Filter Model.

Value Formatter

A

View JavaScript function used for this example

This JavaScript function must be added to the dashAgGridFunctions.js file in the assets folder

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};


var COUNTRY_CODES = {
  Ireland: "ie",
  Luxembourg: "lu",
  Belgium: "be",
  Spain: "es",
  France: "fr",
  Germany: "de",
  Sweden: "se",
  Italy: "it",
  Greece: "gr",
  Iceland: "is",
  Portugal: "pt",
  Malta: "mt",
  Norway: "no",
  Brazil: "br",
  Argentina: "ar",
  Colombia: "co",
  Peru: "pe",
  Venezuela: "ve",
  Uruguay: "uy",
};

dagfuncs.countryValueFormatter = function (value) {
  return value + " (" + COUNTRY_CODES[value].toUpperCase() + ")";
};

Cell Renderer

A Cell Renderer is a good choice when the value displayed requires markup. For instance if a
country flag image is to be shown alongside country names.

The same Cell Renderer can be used to format the grid cells and filter values, or different renderers can be supplied to
each. Note that the Cell Renderer will be supplied additional info when used to format cells inside the grid (as grid
cells have row details that are not present for values inside a Filter List).

Assuming you have a custom Country Cell Renderer, the following snippet shows how to provide the CountryCellRenderer to the Set Filter:


    columnDefs = [
        # column definition using the same cell renderer to format cell and filter values
        {
            'field': 'country',
            'cellRenderer': 'CountryCellRenderer',
            'filter': 'agSetColumnFilter',
            'filterParams': {
                'cellRenderer': 'CountryCellRenderer'
            }
        }
    ]

A custom Cell Renderer Component can also be supplied to filterParams.cellRenderer.

The following example shows how Set Filter values are rendered using a Cell Renderer. Note the following:

View JavaScript function used for this example

This JavaScript function must be added to the dashAgGridComponentFunctions.js file in the assets folder

var dagcomponentfuncs = (window.dashAgGridComponentFunctions =
    window.dashAgGridComponentFunctions || {});

dagcomponentfuncs.CountryCellRenderer = function (props) {
  if (props.value === "(Select All)") {
    return props.value;
  }

  // for more info see <a href="https://flagpedia.net/">https://flagpedia.net/</a>
  const url = `https://flagcdn.com/h20/${COUNTRY_CODES[props.value]}.png`;

  return React.createElement("span", {}, [
    React.createElement("img", {
      style: { height: "10px" },
      src: url,
    }),
    React.createElement(
      "span",
      {
        style: { paddingLeft: "4px" },
      },
      props.value
    ),
  ]);
};

Supplying Filter Values

The Set Filter will obtain the filter values from the row data by default. These are retrieved from the data based on the field attribute. This can be overridden by providing a filterValueGetter in the Column Definition. This is similar to using a Value Getter, but is specific to the filter.

It is also possible to provide values for the Filter List. This is necessary when using the Server-Side Row Model. This can be done either synchronously or asynchronously as described below.

Synchronous Values

The simplest approach is to supply a list of values to filterParams.values as shown below:


    columnDefs = [
        {
            'field': 'days',
            'filter': 'agSetColumnFilter',
            'filterParams': {
                # provide all days, even if days are missing in data!
                'values': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
            }
        }
    ]

Note that if there are missing values in the row data, the filter list will display all provided values. This could give users the impression that filtering is broken.

When providing filter values which are already sorted it is often useful to disable the default filter list sorting using filterParams.suppressSorting=True.

The following example demonstrates providing filter values using filterParams.values. Note the following:

View JavaScript function used for this example

This JavaScript function must be added to the dashAgGridFunctions.js file in the assets folder

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};

var listOfDays = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday",
];
dagfuncs.sortFilterListDays = function (a, b) {
  var aIndex = a == null ? -1 : listOfDays.indexOf(a);
  var bIndex = b == null ? -1 : listOfDays.indexOf(b);
  if (aIndex === bIndex) return 0;
  return aIndex > bIndex ? 1 : -1;
};

Asynchronous Values

It is also possible to supply values asynchronously to the set filter. This is done by providing a function instead of a list of values.

For more information see the AG Grid docs Set Filters Asynchronous Values

The following example demonstrates loading set filter values asynchronously. Note the following:

View JavaScript function used for this example

This JavaScript function must be added to the dashAgGridFunctions.js file in the assets folder

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};

dagfuncs.filterParams = {
  values: (params) => {
    setTimeout(function () {
      params.success(["value 1", "value 2"]);
    }, 3000);
  },
};

Enabling Value Case-Sensitivity

By default the Set Filter treats values as case-insensitive. Practically this means that cell values of Black, black and BLACK are all treated as identical for matching purposes, and the first encountered value is used as the value displayed in the Filter List.

Case-sensitivity can be enabled by using the caseSensitive filter parameter:


    columnDefs = [
        {
            'field': 'colour',
            'filter': 'agSetColumnFilter',
            'filterParams': {
                'caseSensitive': True
            }
        }
    ]

The caseSensitive option also affects Mini-Filter searches and API behaviours.

The following example demonstrates the difference in behaviour between caseSensitive=False (the default) and caseSensitive=True:
- The case insensitive column’s Filter List has seven distinct values with unique colours.
- Typing black into the Mini Filter will match Black.
- The case sensitive column’s Filter List has 21 distinct values, although there are only seven distinct colours ignoring case.
- Typing black into the Mini Filter will match only black, but not Black or BLACK.

View the custom ColourCellRender component used for this example

This JavaScript function must be added to the dashAgGridComponentFunctions.js file in the assets folder


 var dagcomponentfuncs = (window.dashAgGridComponentFunctions =
    window.dashAgGridComponentFunctions || {});

 dagcomponentfuncs.ColourCellRenderer = (props) => {
  if (!props.value || props.value === "(Select All)") {
    return props.value;
  }

  const styles = {
    verticalAlign: "middle",
    border: "1px solid black",
    margin: 3,
    display: "inline-block",
    width: 10,
    height: 10,
    backgroundColor: props.value.toLowerCase(),
  };
  return React.createElement("div", {}, [
    React.createElement("span", { style: styles }),
    React.createElement("span", {}, props.value),
  ]);
};

If case differences need to be normalised to remove redundant values from the data-source for filtering, a Supplied Values should be used.

Missing Values

If there are missing / empty values in the row data of the grid, or missing values in the list of Formatter, the Filter List will contain an entry called (Blanks) which can be used to select / deselect all of these values. If this not the desired behaviour, provide a Multiple Values Per Cell to present blank values in a different way.

undefined, null and '', as well as an empty array if using Missing Values, are all treated as missing values. These will appear within the Set Filter Model as a single entry of null. This also applies to supplied Filter List values (For example, if you supply '' it will appear in the filter model as null).

Filter Value Types

The Set Filter internally maintains the original type of the cell values, but always uses strings for the keys. For example, if the cell contains a number, the Filter Model will contain those numbers converted to strings, but if you specified a value formatter, that would use the values with type number. Note that in AG Grid versions prior to 29.0, the Filter Model values were converted to strings for everything. This behaviour can be replicated by setting filterParams.convertValuesToStrings = True, but the setting is deprecated.

Complex Objects

If you are providing complex objects, such as a dictionary, as values, then you need to provide both a Key Creator function and a Value Formatter function when using the Set Filter.

The Key Creator generates a unique string key from the complex object (note that if the key is null, undefined or '' it will be converted to null, the same as for Supplied Values). This key is used within the Filter Model, and to compare objects. You can either provide a Key Creator within the filter params, which will be specific to the Set Filter, or you can provide one in the Column Definition that is shared with other features such as grouping.

The Value Formatter is used to generate the label that is displayed to the user within the Filter List. You can provide the Value Formatter in the filter params.


    columnDefs = [
        {
            'field': 'country',
            'filter': 'agSetColumnFilter',
            'filterParams': {
                'keyCreator': {"function": "params.value.code"},
                'valueFormatter': {"function": "params.value.name"},
            },
        }
    ]

The snippet above shows a Key Creator function that returns the country code from the complex object, and a Value Formatter that returns the name. If the Key Creator or Value Formatter were not provided at all, the Set Filter would not work.

If

Multiple Values Per Cell

Sometimes you might wish to support multiple values in a single cell, for example when using tags. In this case, the Set Filter can extract each of the individual values from the cells, creating an entry in the Filter List for each individual value. Selecting a value will then show rows where any of the values in the cell match the selected value.

The example below demonstrates this in action. Note the following:

View JavaScript function used for this example

This JavaScript function must be added to the dashAgGridFunctions.js file in the assets folder

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};


dagfuncs.valueFormatterObj = function (params) {
  return params.value
    .map(function (animal) {
      return animal.name;
    })
    .join(", ");
};

Default State

By default, when the Set Filter is created all values are selected. If you prefer to invert this behaviour and have everything de-selected by default, you can use the following:


    columnDefs = [
        {
            'field': 'country',
            'filter': 'agSetColumnFilter',
            'filterParams': {
                'defaultToNothingSelected': True,
            }
        }
    ]

In this case, no filtering will occur until at least one value is selected.

Note that the default state cannot be changed if Excel Mode is enabled.

The following example demonstrates different default states. Note the following:

Filter Value Tooltips

Set filter values that are too long to be displayed are truncated by default with ellipses. To allow users to see the full filter value, tooltips can be enabled as shown below:


    columnDefs = [
        {
            'field': 'country',
            'filter': 'agSetColumnFilter',
            'filterParams': {
                'showTooltips': True,
            }
        }
    ]

The default tooltip component will be used unless a

View Custom Tooltip Component used for this example

This JavaScript function must be added to the dashAgGridComponentFunctions.js file in the assets folder


 var dagcomponentfuncs = (window.dashAgGridComponentFunctions =
    window.dashAgGridComponentFunctions || {});

 dagcomponentfuncs.CustomTooltipSetFilter = function (props) {
  info = React.createElement("div", {}, props.value);
  if (props.location === "setFilterValue") {
    info = [
      React.createElement("strong", {}, "Full Info: "),
      React.createElement("span", {}, props.value),
    ];
  }

  return React.createElement(
    "div",
    {
      style: {
        padding: 15,
        width: 200,
        border: "1px solid cornflowerblue",
        pointerEvents: "none",
        transition: "opacity 1s",
        backgroundColor: "white",
      },
    },
    info
  );
};