Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dash datatable with select all checkbox?

Tags:

plotly-dash

I am wondering if anyone have an idea on how to create a "Select all" checkbox in Dash Datatable (it should be in the red box area)? The idea is it will select all the rows available in the datatable.

enter image description here

I have read through the entire Datatable documentation (https://dash.plotly.com/datatable/interactivity) and there is no mention of this. Trying to search online also failed.

I remember dash-tables-experiment has this functionality but it has since been deprecated. Any advice is greatly appreciated.

like image 691
SunnyBoiz Avatar asked May 20 '20 04:05

SunnyBoiz


Video Answer


1 Answers

Currently this option is not supported within a dash_table.DataTable element. However, there is a workaround by adding two dbc.Button() parts to your Dash layout, the first for selecting all and the second for deselecting all. Then have an @app.callback that (de)selects all once the button is clicked.

You will get something like this:

No rows selected:No row selected

All rows selected after button click: All rows selected after click

The callback on its turn would look something like the following (thanks to @neilpanchal in this git issue):

from loguru import logger
import dash
...

@app.callback(
    [Output('df-table', 'selected_rows')],
    [
        Input('select-all-button', 'n_clicks'),
        Input('deselect-all-button', 'n_clicks')
    ],
    [
        State('df-table', 'data'),
        State('df-table', 'derived_virtual_data'),
        State('df-table', 'derived_virtual_selected_rows')
    ]
)
def select_all(select_n_clicks, deselect_n_clicks, original_rows, filtered_rows, selected_rows):
    ctx = dash.callback_context.triggered[0]
    ctx_caller = ctx['prop_id']
    if filtered_rows is not None:
        if ctx_caller == 'select-all-button.n_clicks':
            logger.info("Selecting all rows..")
            selected_ids = [row for row in filtered_rows]
            return [[i for i, row in enumerate(original_rows) if row in selected_ids]]
        if ctx_caller == 'deselect-all-button.n_clicks':
            logger.info("Deselecting all rows..")
            return [[]]
        raise PreventUpdate
    else:
        raise PreventUpdate
like image 108
Stefan Verweij Avatar answered Oct 21 '22 16:10

Stefan Verweij