I am trying to programmatically set selected rows in data table with custom pagination and sorting so I can preserve selected rows when jumping between pages.
I get the correct selected row ids from “selected_row_ids” property, but I cannot set selected rows. I’ve tried setting few other properties I found online too but nothing worked.
Here is a minimal example (modified paging demo from Python-Driven Filtering, Paging, Sorting | Dash for Python Documentation | Plotly), where I want the callback to set two first rows in the df as currently selected:
from dash import Dash, dash_table
from dash.dependencies import Input, Output
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
df['index'] = range(1, len(df) + 1)
df['id'] = df['index']
df.set_index('id', inplace=True, drop=False)
app = Dash(__name__)
PAGE_SIZE = 5
app.layout = dash_table.DataTable(
id='datatable-paging',
columns=[
{"name": i, "id": i} for i in sorted(df.columns)
],
page_current=0,
page_size=PAGE_SIZE,
page_action='custom',
row_selectable="multi",
cell_selectable=True,
)
@app.callback(
Output('datatable-paging', 'data'),
Output('datatable-paging', 'selected_row_ids'),
Input('datatable-paging', "page_current"),
Input('datatable-paging', "page_size"),
)
def update_table(page_current,page_size):
return (df.iloc[
page_current*page_size:(page_current+ 1)*page_size
].to_dict('records'), [1, 2])
if __name__ == "__main__":
app.run_server(debug=True)