I have a table with multiple column groups. Would like to know how to use a button with callback to open and close all column groups at once? Really appreciate any help!
Hi @littlefishna !
Welcome to the community ![]()
Inspired by the AG Grid docs, I may have found the function that do the job:
The .setColumnGroupOpened() function is accessible through the gridAPI, and you can use a clientside_callback to access the gridAPI.
You must add a groupId for the groups in columnDefs to target them in the function.
Here is the Dash translation:
Code
import pandas as pd
from dash import Dash, html, Input, Output, clientside_callback
import dash_ag_grid as dag
app = Dash(__name__)
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv"
)
columnDefs = [
{
"headerName": "Athlete Details",
'groupId': "group-athlete",
"children": [
{"field": "athlete"},
{"field": "age", "columnGroupShow": "open"},
{"field": "country", "columnGroupShow": "open"},
],
},
{
"headerName": "Sports Results",
'groupId': "group-results",
"children": [
{"field": "sport"},
{"field": "total", "columnGroupShow": "closed"},
{"field": "gold", "columnGroupShow": "open"},
{"field": "silver", "columnGroupShow": "open"},
{"field": "bronze", "columnGroupShow": "open"},
],
},
]
app.layout = html.Div(
[
html.Button("Toggle Collapse State", id="toggle-collapse-btn", n_clicks=0),
dag.AgGrid(
id="my-grid",
rowData=df.to_dict("records"),
columnDefs=columnDefs,
),
]
)
clientside_callback(
"""async function (nClicks) {
gridApi = await dash_ag_grid.getApiAsync('my-grid');
const groupNames = ['group-athlete', 'group-results'];
groupNames.forEach((groupId) => {
gridApi.setColumnGroupOpened(groupId, nClicks%2);
})
return window.dash_clientside.no_update
}""",
Output('my-grid', 'id'),
Input('toggle-collapse-btn', 'n_clicks')
)
if __name__ == "__main__":
app.run(debug=True)
@Skiks provided an excellent example of using the grid’s API to open and close the the column groups. This is the most efficient way to do it. ![]()
If you prefer not to use any JavaScript, you can also do it like this example in the dash-docs
1 Like
Thank you all!
1 Like