Row Selection With Checkboxes

To include checkbox selection for a column, set the attribute "checkboxSelection": True on the Column Definition. You
can set this attribute on as many columns as you like, however it doesn’t make sense to have it in more than one column
in a table.

Checkbox Selection Simple Example

The following example shows a simple use case adding checkboxes in the first column that can be used to select the rows.

Note that dashGridOptions={"rowSelection": "multiple", "suppressRowClickSelection": True} is set to allow multi-row
selection and to disable the row selection clicking on the rows to allow only the selection using the checkboxes.

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", "checkboxSelection": True},
    {"field": "age"},
    {"field": "country"},
    {"field": "year"},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="row-selection-checkbox-simple",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={"rowSelection": "multiple", "suppressRowClickSelection": True, "animateRows": False},
        ),
    ],
)

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

checkboxSelection as a function

checkboxSelection can also be specified as a function. This allows dynamically setting whether a cell has a checkbox
or not. The function is called when the Cell is drawn, and called again if there are any changes to the row’s data or
the column positions (for example, the function could be showing the checkbox depending on what value is displayed, or
if the column in question is the first column to show a checkbox for the first column only, see examples below).

If the function returns false, a selection checkbox will still be created and in the DOM, however it will not be visible
using CSS visibility: hidden. This is to ensure the following UX properties:

To be clear, there is a slight difference between a function returning false, and false value provided explicitly. When
a function is used and returns false, the grid assumes a checkbox is sometimes used and as such creates one that is
not visible.

# Do not create checkboxes
"checkboxSelection": False

# Create checkboxes, making them invisible
"checkboxSelection": {"function": "false"}

Instead of making them invisible, it is possible to set the Column parameter showDisabledCheckboxes: True to display
these checkboxes as disabled.

Note that when the checkboxes are hidden/disabled, the rows are still selectable clicking on the rows (unless setting
the Grid Option "suppressRowClickSelection": True,
see Checkbox Selection Simple Example )
or using the header checkbox if set. To be sure
the rows are not selectable, the Grid Option function isRowSelectable must be used,
see Selectable Rows with Checkboxes.
Using this function will also hide the checkboxes of the non-selectable rows.

The following example uses the function "checkboxSelection": {"function": "params.data.year > 2007"} to display only
the checkboxes when ‘year’ is above 2007.

Note that it is possible to show the disabled checkboxes instead of hiding them. Moreover, the ‘year’ column is
editable, try to change values to see the modifications on the checkboxes.

The example Header Checkbox Selection is another
example using a function that display the checkboxes only in the first column even changing their position with
dragging.

import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output, callback, Patch
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", "checkboxSelection": {"function": "params.data.year > 2007"}},
    {"field": "age"},
    {"field": "country"},
    {"field": "year", 'editable': True},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dcc.Checklist(
            id='chk-row-selection-checkbox-function',
            options={'disabled': 'Show Checkboxes As Disabled'},
            value=['disabled']
        ),
        dag.AgGrid(
            id="row-selection-checkbox-function",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={"rowSelection": "multiple", "suppressRowClickSelection": True, "animateRows": False},
        ),
    ],
)


@callback(
    Output("row-selection-checkbox-function", "columnDefs"),
    Input("chk-row-selection-checkbox-function", "value"),
)
def display_disabled(disabled):
    columnDefs_patch = Patch()
    columnDefs_patch[0]['showDisabledCheckboxes'] = bool(disabled)
    return columnDefs_patch


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

Header Checkbox Selection

It is possible to have a checkbox in the header for selection. To configure the column to have a header checkbox, set
Column Definition "headerCheckboxSelection": True. headerCheckboxSelection can also be a function, if you want the
header checkbox to appear on conditions.

The example below uses the following function:

"headerCheckboxSelection": {"function": 'params.column == params.columnApi.getAllDisplayedColumns()[0]'}

This function displays the header checkbox only on the header of first column even when the column positions are changed
dragging them.

Note that the same function is used for the parameter checkboxSelection to also display the checkboxes only in the
cells of the first column, even if the columns are dragged.

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"},
    {"field": "age"},
    {"field": "country"},
    {"field": "year"},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="row-selection-checkbox-header-function",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={
                "filter": True,
                "checkboxSelection": {
                    "function": 'params.column == params.columnApi.getAllDisplayedColumns()[0]'
                },
                "headerCheckboxSelection": {
                    "function": 'params.column == params.columnApi.getAllDisplayedColumns()[0]'
                }
            },
            dashGridOptions={
                "rowSelection": "multiple",
                "suppressRowClickSelection": True,
                "animateRows": False
            },
        ),
    ],
)

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

Header Checkbox Using Filters And Pagination

By default, even when using filters or pagination, the header checkbox will select all rows when checked, and un-select all
rows when unchecked and the header checkbox will update its state based on all rows.

This may not the expected behavior, to select only the filtered rows or only the rows of the current page, it is
possible to set respectively the Column Definitions "headerCheckboxSelectionFilteredOnly": True
and "headerCheckboxSelectionCurrentPageOnly": True. See the examples below.

Default Rows Selection Example

This example shows the default behavior using the header checkbox, all the rows will be selected through all the pages
and even if a filter is applied.

import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output, callback, Patch
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",
        "checkboxSelection": True,
        "headerCheckboxSelection": True,
    },
    {"field": "age"},
    {"field": "country"},
    {"field": "year"},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dcc.Input(id="input-radio-row-selection-checkbox-header-default", placeholder="Quick filter..."),
        dag.AgGrid(
            id="row-selection-checkbox-header-default",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={
                "rowSelection": "multiple",
                "pagination": True,
                "paginationAutoPageSize": True,
                "animateRows": False,
            },
        ),
    ],
)


@callback(
    Output("row-selection-checkbox-header-default", "dashGridOptions"),
    Input("input-radio-row-selection-checkbox-header-default", "value"),
)
def update_filter(filter_value):
    gridOptions_patch = Patch()
    gridOptions_patch["quickFilterText"] = filter_value
    return gridOptions_patch


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

Select Filtered Rows Only Example

In this example, Column Definitions "headerCheckboxSelectionFilteredOnly": True is set. The header checkbox works on
filtered rows only. That means if you filter first, then hit the checkbox to select or un-select, then only the filtered
rows are affected.

import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output, callback, Patch
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",
        "checkboxSelection": True,
        "headerCheckboxSelection": True,
        "headerCheckboxSelectionFilteredOnly": True,
    },
    {"field": "age"},
    {"field": "country"},
    {"field": "year"},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dcc.Input(id="input-radio-row-selection-checkbox-header-filtered-only", placeholder="Quick filter..."),
        dag.AgGrid(
            id="row-selection-checkbox-header-filtered-only",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={"rowSelection": "multiple", "animateRows": False},
        ),
    ],
)


@callback(
    Output("row-selection-checkbox-header-filtered-only", "dashGridOptions"),
    Input("input-radio-row-selection-checkbox-header-filtered-only", "value"),
)
def update_filter(filter_value):
    gridOptions_patch = Patch()
    gridOptions_patch["quickFilterText"] = filter_value
    return gridOptions_patch


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

Select Current Page Only Example

In this example, Column Definitions "headerCheckboxSelectionCurrentPageOnly": True is set. Only items on the current
page are selected. Try going to a different page after clicking on the header checkbox.

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",
        "checkboxSelection": True,
        "headerCheckboxSelection": True,
        "headerCheckboxSelectionCurrentPageOnly": True,
    },
    {"field": "age"},
    {"field": "country"},
    {"field": "year"},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="row-selection-checkbox-header-current-page-only",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={
                "rowSelection": "multiple",
                "pagination": True,
                "paginationAutoPageSize": True,
                "animateRows": False
            },
        ),
    ],
)

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

Selectable Rows with Checkboxes

The Grid Option function isRowSelectable can be used without checkboxes as shown in
Specify Selectable Rows but using
checkboxes helps to identify the selectable rows as the checkbox of the non-selectable rows will be hidden as
illustrated in the example below.

This example uses the function 'isRowSelectable': {"function": "params.data.year > 2007"}.

Note that clicking on the header checkbox will only select the selectable rows.

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",
        "checkboxSelection": True,
        "headerCheckboxSelection": True,
    },
    {"field": "age"},
    {"field": "country"},
    {"field": "year"},
    {"field": "sport"},
    {"field": "total"},
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="row-selection-checkbox-header-selectable-rows",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            columnSize="sizeToFit",
            defaultColDef={"filter": True},
            dashGridOptions={
                "rowSelection": "multiple",
                "isRowSelectable": {"function": "params.data.year > 2007"},
                "animateRows": False
            },
        ),
    ],
)

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