You can grab the state from the grid by using the AgGrid update_mode
response = AgGrid(df,
gridOptions=grid_options,
height=600,
width='100%',
reload_data=True,
update_mode = GridUpdateMode.MANUAL,
data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
allow_unsafe_jscode=True, # Set it to True to enable jsfunction
)
# Save grid state when user makes changes
if response:
if response.get('grid_state'):
state = configure_grid_state(response['grid_options']['columnDefs'], response.get('grid_state') )
Then you can use a function like this to reassign the grid state:
def configure_grid_state(options, state):
keys = (('aggregation', 'aggregationModel'), ('columnSizing', 'columnSizingModel'), ('sort', 'sortModel'))
groups = state.get('rowGroup',{}).get('groupColIds',[])
order = state.get('columnOrder',{}).get('orderedColIds',[])
hidden = state.get('columnVisibility', {}).get('hiddenColIds', [])
fields = {}
for k in keys:
if a:= state.get(k[0]):
a = a[k[1]]
for c in a:
col = c.pop('colId')
try:
fields[col].update(c)
except KeyError:
fields[col] = c
for c in options:
c['sort'] = ''
if c['field'] in fields:
c.update(fields[c['field']])
if order:
c['order'] = order.index(c['field'])
if c['field'] in groups:
c['rowGroup'] = True
else:
c['rowGroup'] = False
if c['field'] in hidden:
c['hide'] = True
else:
c['hide'] = False
return options
And then check if your state exists (like saved in a file or database) and recall using this:
if state:
for c in state:
gb.configure_column(headerName= c.get('headerName', c.get('field')), field=c['field'], type= c['type'], filter= c.get('filter',''), aggFunc=c.get('aggFunc',''), sort=c.get('sort') , enableRowGroup=c.get('enableRowGroup', False), rowGroup=c.get('rowGroup', False), order=c.get('order',''), hide=c.get('hide', False))