Default row selections with AgGrid

Hi,
I am using Dash AgGrid 2.0.0a5 and working with checkboxes to select rows.
I want to have some rows marked as selected and some not selected by default when the app initially loads. How can I do this with AgGrid?

So my app should look something like this when I first load the page:

Hello @MinaM,

Welcome to the community!

You should pass the rowData from the rows that you want to be selected as the selectedRows value.

Good question @MinaM!

Here is a complete example:




import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output
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", "maxWidth": 100},
    {"field": "country"},
    {"field": "year", "maxWidth": 120},
    {"field": "date", "minWidth": 150},
    {"field": "sport"},
    {"field": "gold"},
    {"field": "silver"},
    {"field": "bronze"},
    {"field": "total"},
]


defaultColDef = {
    "flex": 1,
    "minWidth": 150,
    "sortable": True,
    "resizable": True,
    "filter": True,
}


app.layout = html.Div(
    [
        dcc.Markdown("This grid has multi-select rows with checkboxes."),
        dag.AgGrid(
            id="preselect-checkbox-grid",
            columnDefs=columnDefs,
            rowData=df.to_dict("records"),
            defaultColDef=defaultColDef,
            dashGridOptions={"rowSelection":"multiple"},
            selectedRows=df.head(n=4).to_dict("records")
        ),
        html.Div(id="preselect-checkbox-output"),
    ],
    style={"margin": 20},
)


@app.callback(
    Output("preselect-checkbox-output", "children"),
    Input("preselect-checkbox-grid", "selectedRows"),
)
def selected(selected):
    if selected:
        selected_athlete = [s["athlete"] for s in selected]
        return f"You selected athletes: {selected_athlete}"
    return "No selections"


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

I’ll be adding that to the Dash AG Grid dos "selections"section of the docs today.

1 Like