Hi All,
I am having issues with persistence, especially when using buttons.
I found it hard to explain, so thought it best to provide some code and usage to show the issues I am having
Issues
- Move around columns, change width, apply sort and filter. If page is refreshed by browser (or even close tab and reopen) persistence works as expected.
However if you use the ‘Load View’ button the order of the columns and their widths revert back to normal, but filter and sort are preserved.
What make this especially weird if that both refreshes are done by the same ‘load_layout()’ method
2a. Input ‘Year’ into input box and press ‘Add Column’ this will unhide the applicable column. Persistence continues to work as above.
2b. Input ‘Year’ into input box and press ‘Add Column’ this will unhide the applicable column, repeat with ‘Sport’ and the second column will appear. Persistence continues to work as above.
2c. Input ‘Year’ into input box and press ‘Add Column’ this will unhide the applicable column. Refresh webpage and will stay. Now enter Input ‘Sport’ into input box and press ‘Add Column’, year goes and sport appears
I am not sure what is happening with the behavior in 2c
- Finally Does anyone have a better way of adding adhoc columns by field name? I had previously tried getting the columnDefs and appending a new field dictionary before returning, but I could not get the columns to persist on refresh
Thank you
import dash_ag_grid as dag
from dash import Dash, Input, Output, dcc, html, callback, State
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": "country"},
{"field": "year", 'hide': True},
{"field": "athlete"},
{"field": "sport", 'hide': True},
{"field": "total"},
]
row_data = df.reset_index().to_dict("records")
def load_layout():
children = [
dag.AgGrid(
id="grid",
columnSize="sizeToFit",
rowData=row_data,
columnDefs=columnDefs,
defaultColDef={"filter": True, "sortable": True, "resizable": True},
persistence=True,
persisted_props=["filterModel", "columnState"]
)
]
return children
app.layout = html.Div([
html.Button("Load View", id="filter-model-btn", n_clicks=0),
dcc.Input(id='input', placeholder='Column Name', debounce=True),
html.Button("Add Column", id="add-btn", n_clicks=0),
html.Div(
[
],
id='layout'
)
])
@callback(
Output("layout", "children"),
Input("filter-model-btn", "n_clicks"),
)
def layout(n):
if n >0:
return load_layout()
return load_layout()
@callback(
Output('grid', "columnDefs"),
Input('input', 'value'),
Input("add-btn", "n_clicks"),
State('grid', "columnDefs"),
prevent_initial_call=True
)
def add(text, n, cols):
print(cols)
for col in cols:
if col['field'] == text.lower():
col['hide'] = False
return cols
if __name__ == "__main__":
app.run(debug=True)