0

I want to dynamically add columns in a DataTable based on selected dropdown values using Dash. My table is created also dynamically based on two dropdowns (I have a callback that returns the whole DataTable definition).

I tried the example that is in Adding or removing columns section, but it works only when you try to add columns using a button.

This is my code for adding the columns:

@app.callback(
[Output(‘main_table’, ‘columns’)],
[Input(‘second_dropdown’, ‘value’)],
[State(‘main_data’, ‘data’), State(‘main_table’, ‘columns’)]
)
def add_columns(values, data, existing_columns):
if existing_columns is None:
return None
for value in values:
if value not in existing_columns:
existing_columns.append({
‘id’: value,
‘name’: value
})
print(existing_columns)
return existing_columns

The 'main_data' is stored in a json file which contains the data that should be displayed when the values in the second dropdown are changed. As result I expect to have a table which columns are as the number of selected dropdown values.

I'm new to Dash so I would really appreciate if someone can help me.

1 Answer 1

1

If someone also has the same problem, here is the solution (many thanks to Marc-Andre):

import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate

from dash_table import DataTable, FormatTemplate
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Dropdown(
        id='dropdown',
        options=[{
            'label': 'label: ' + id,
            'value': id
        } for id in ['b', 'c', 'd', 'e', 'f']]
    ),
    DataTable(
        id='table',
        columns=[{
            'name': x,
            'id': x,
            'selectable': True
        } for x in ['a']],
        column_selectable="single",
        data=[{
            'a': 'a' + str(x),
            'b': 'b' + str(x),
            'c': 'c' + str(x),
            'd': 'd' + str(x),
            'e': 'e' + str(x),
            'f': 'f' + str(x)
        } for x in range(0,100)]
    )
])

@app.callback(
    Output('table', 'columns'),
    [Input('dropdown', 'value')],
    [State('table', 'columns')]
)
def update_columns(value, columns):
    if value is None or columns is None:
        raise PreventUpdate

    inColumns = any(c.get('id') == value for c in columns)

    if inColumns == True:
        raise PreventUpdate

    columns.append({
        'label': 'label: ' + value,
        'id': value
    })
    return columns

if __name__ == '__main__':
    app.run_server(debug=False)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.