Text Filter

Text filters allow you to filter string data.

Filter UI

Enabling Text Filters

The Text Filter is the default filter used in AG Grid Community, but it can also be explicitly configured as shown
below:


columnDefs = [
    {
        'field': 'athlete',
        # Text Filter is used by default in Community version
        'filter': True,
        'filterParams': {
            # pass in additional parameters to the Text Filter
        },
    },
    {
        'field': 'country',
        # explicitly configure column to use the Text Filter
        'filter': 'agTextColumnFilter',
        'filterParams': {
            # pass in additional parameters to the Text Filter
        },
    },
]

Example Text Filter

The example below shows the Text Filter in action:

For the Athlete column:

For the Country column:

For the Sport column:

import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

athleteFilterParams = {
    "filterOptions": ["contains", "notContains"],
    "debounceMs": 200,
    "maxNumConditions": 1,
}

countryFilterParams = {
    "filterOptions": ["contains"],
    "trimInput": True,
    "debounceMs": 1000,
}

columnDefs = [
    {
        "field": "athlete",
        "filterParams": athleteFilterParams,
    },
    {
        "field": "country",
        "filter": "agTextColumnFilter",
        "filterParams": countryFilterParams,
    },
    {
        "field": "sport",
        "filter": "agTextColumnFilter",
        "filterParams": {
            "caseSensitive": True,
            "defaultOption": "startsWith",
        },
    },
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="text-filter-example",
            rowData=df.to_dict("records"),
            columnDefs=columnDefs,
            defaultColDef={"filter": True},
            columnSize="sizeToFit",
            dashGridOptions={"animateRows": False}
        ),
    ]
)

if __name__ == "__main__":
    app.run(debug=True)

Text Filter Parameters

Text Filters are configured though the filterParams attribute of the column definition:

Text Formatter

By default, the grid compares the text filter with the values in a case-insensitive way, by converting both the filter
text and the values to lower-case and comparing them; for example, ‘o’ will match ‘Olivia’ and ‘Salmon’. If you instead
want to have case-sensitive matches, you can set caseSensitive = True in the filterParams, so that no lower-casing
is performed. In this case, ‘o’ would no longer match ‘Olivia’.

You might have more advanced requirements, for example to ignore accented characters. In this case, you can provide your
own textFormatter (See
the example below).

The Text Formatter is applied to both the filter text and the values before they are compared.

Note that when providing a Text Formatter, the caseSensitive parameter is ignored. In this situation, if you want to
do a case-insensitive comparison, you will need to perform case conversion inside the textFormatter function.

Text Matcher

In most cases, you can customise the Text Filter matching logic by providing your
own Text Formatter, for example to remove or replace
characters in the filter text and values.

The Text Formatter is applied to both the filter text and values before the filter comparison is performed.

For more advanced use cases, you can provide your own textMatcher to decide when to include a row in the filtered
results. For example, you might want to apply different logic for the filter option equals than for contains.

The following is an example of a textMatcher that mimics the current implementation of AG Grid. This can be used as a
template to create your own.

This JavaScript function must be added to the dashAgGridFunctions.js file in the assets folder.
See JavaScript Functions
for more information and
the example below.

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

dagfuncs.customTextMatcher = ({filterOption, value, filterText}) => {
    if (filterText == null) {
        return false;
    }
    switch (filterOption) {
        case 'contains':
            return value.indexOf(filterText) >= 0;
        case 'notContains':
            return value.indexOf(filterText) < 0;
        case 'equals':
            return value === filterText;
        case 'notEqual':
            return value != filterText;
        case 'startsWith':
            return value.indexOf(filterText) === 0;
        case 'endsWith':
            const index = value.lastIndexOf(filterText);
            return index >= 0 && index === (value.length - filterText.length);
        default:
            // should never happen
            console.warn('invalid filter type ' + filter);
            return false;
    }
}

See AG Grid Docs for the
available inputs for the textMatcher function.

Example Text Formatter and Text Matcher

This example has all the same features as in
the Text Filter example above, plus the following:

Note that it is possible either to define all the filterParams parameters in JavaScript, like the column Athlete, or
only define the JavaScript functions for textFormatter and textMatcher, like the column Country.

View the JavaScript functions used for this example

These JavaScript functions must be added to the dashAgGridFunctions.js file in the assets folder.
See JavaScript Functions
for more information.

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

dagfuncs.athleteFilterParams = {
    filterOptions: ["contains", "notContains"],
    textFormatter: (r) => {
        if (r == null) return null;
        return r
            .toLowerCase()
            .replace(/[àáâãäå]/g, "a")
            .replace(/æ/g, "ae")
            .replace(/ç/g, "c")
            .replace(/[èéêë]/g, "e")
            .replace(/[ìíîï]/g, "i")
            .replace(/ñ/g, "n")
            .replace(/[òóôõö]/g, "o")
            .replace(/œ/g, "oe")
            .replace(/[ùúûü]/g, "u")
            .replace(/[ýÿ]/g, "y");
    },
    debounceMs: 200,
    maxNumConditions: 1,
};

function contains(target, lookingFor) {
    return target && target.indexOf(lookingFor) >= 0;
}

dagfuncs.countryTextMatcher = ({value, filterText}) => {
    const aliases = {
        usa: "united states",
        holland: "netherlands",
        niall: "ireland",
        sean: "south africa",
        alberto: "mexico",
        john: "australia",
        xi: "china",
    };
    const literalMatch = contains(value, filterText || "");
    return literalMatch || contains(value, aliases[filterText || ""]);
};
import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)

columnDefs = [
    {
        "field": "athlete",
        "filterParams": {"function": "athleteFilterParams"},
    },
    {
        "field": "country",
        "filterParams": {
            "filterOptions": ["contains"],
            "textMatcher": {"function": "countryTextMatcher(params)"},
            "trimInput": True,
            "debounceMs": 1000,
        },
    },
    {
        "field": "sport",
        "filterParams": {
            "caseSensitive": True,
            "defaultOption": "startsWith",
        },
    },
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="text-filter-custom",
            rowData=df.to_dict("records"),
            columnDefs=columnDefs,
            columnSize="sizeToFit",
            dashGridOptions={"animateRows": False},
            defaultColDef={"filter": True}
        ),
    ]
)

if __name__ == "__main__":
    app.run(debug=True)

Text Filter Model

See the Filter Model & Dash Callbacks section for
examples.

The Filter Model describes the current state of the applied Text Filter. If only
one Filter Condition is set, this will
be a TextFilterModel:

If more than one Filter Condition is set, then multiple instances of the model are created and wrapped inside a Combined
Model.

Note that in AG Grid versions prior to 29.2, only two Filter Conditions were supported. These appeared in the Combined
Model as properties condition1 and condition2. The grid will still accept and supply models using these properties,
but this behaviour is deprecated. The conditions property should be used instead.

Here is an example of a Filter Model with three conditions:

filterModel = {
    "sport": {
        "filterType": "text",
        "operator": "OR",
        "conditions": [
            {
                "filterType": "text",
                "type": "contains",
                "filter": "Swim",
            },
            {
                "filterType": "text",
                "type": "contains",
                "filter": "Ski",
            },
            {
                "filterType": "text",
                "type": "contains",
                "filter": "Rowing",
            },
        ],
    }
}

Text Filter Options

The Text Filter presents a list
of Filter Options to the user.

The list of options are as follows:

Option Name Option Key Included by Default
Contains <p>contains<p> Yes
Does not contain <p>notContains<p> Yes
Equals <p>equals<p> Yes
Does not equal <p>notEqual<p> Yes
Begins with <p>startsWith<p> Yes
Ends with <p>endsWith<p> Yes
Blank <p>blank<p> Yes
Not blank <p>notBlank<p> Yes
Choose one <p>empty<p> No

Note that the empty filter option is primarily used when
creating Custom Filter Options.
When ‘Choose one’ is displayed, the filter is not active.

The default option for the Text Filter is contains.

Text Filter Values

By default, the values supplied to the Text Filter 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.

Applying the Text Filter

To include Apply, Clear, Recent and Cancel buttons to the filter menu
see Applying Filters section.

Data Updates

The Text Filter is not affected by data changes. When the grid data is updated, the filter value will remain unchanged
and the filter will be re-applied based on the updated data (for example, the displayed rows will update if necessary).

Boolean Cell Data Type Filter

As of Dash AG Grid V31, boolean values will be rendered as check boxes and the filter will display a single dropdown
with 'True'/'False' . See more information
in Cell Data Types section.

To disable this feature, set cellDataType='text'

import dash_ag_grid as dag
from dash import Dash, html
import pandas as pd

app = Dash(__name__)

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)
df["has_gold"] = df[["gold"]] > 0

columnDefs = [
    {"field": "athlete"},
    {"field": "total", "width": 100},
    {"field": "has_gold", "headerName": "Has Gold (boolean)"},
    {"field": "has_gold", "headerName": "Has Gold (text)", "cellDataType": "text"},
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="text-filter-boolean",
            rowData=df.to_dict("records"),
            columnDefs=columnDefs,
            columnSize="sizeToFit",
            dashGridOptions={"animateRows": False},
            defaultColDef={"filter": True},
        ),
    ]
)

if __name__ == "__main__":
    app.run(debug=True)