I have an editable data table with 1 column and 0 row on page load. The user can dynamically build the table by adding columns to the table. Similarly they can add rows. This is based on this example Editable DataTable | Dash for Python Documentation | Plotly and Dropdowns Inside DataTable | Dash for Python Documentation | Plotly.
My question is how can I populate the dropdown options on loading the page? On loading the page, I query the db and have a dict of options. I want to pass it as options to column dropdown. See below code. Instead of for i in df[‘climate’].unique(), I want to populate the dropdown from a callback
from dash import Dash, dash_table, html, dcc
import pandas as pd
from collections import OrderedDict
from dash.dependencies import Input, Output, Stateapp = Dash(name)
df = pd.DataFrame(OrderedDict([
(‘climate’, [‘Sunny’, ‘Snowy’, ‘Sunny’, ‘Rainy’]),
(‘temperature’, [13, 43, 50, 30]),
(‘city’, [‘NYC’, ‘Montreal’, ‘Miami’, ‘NYC’])
]))app.layout = html.Div([
html.Div([
dcc.Input(
id=‘adding-rows-name’,
placeholder=‘Enter a column name…’,
value=‘’,
style={‘padding’: 10}
),
html.Button(‘Add Column’, id=‘adding-rows-button’, n_clicks=0)
], style={‘height’: 50}),dash_table.DataTable( id='adding-rows-table', columns=[{ 'name': 'CashierId', 'id': 'cashierid', 'deletable': True, 'renamable': True, 'presentation': 'dropdown' }], data=[ {'cashierid': '',} ], editable=True, row_deletable=True, dropdown={ 'cashierid': { 'options': [ {'label': i, 'value': i} for i in df['climate'].unique() # TODO :Want to populate from the db ] } } ), html.Button('Add Row', id='editing-rows-button', n_clicks=0)
])
@app.callback(
Output(‘adding-rows-table’, ‘data’),
Input(‘editing-rows-button’, ‘n_clicks’),
State(‘adding-rows-table’, ‘data’),
State(‘adding-rows-table’, ‘columns’))
def add_row(n_clicks, rows, columns):
if n_clicks > 0:
rows.append({c[‘id’]: ‘’ for c in columns})
return rows@app.callback(
Output(‘adding-rows-table’, ‘columns’),
Input(‘adding-rows-button’, ‘n_clicks’),
State(‘adding-rows-name’, ‘value’),
State(‘adding-rows-table’, ‘columns’))
def update_columns(n_clicks, value, existing_columns):
if n_clicks > 0:
existing_columns.append({
‘id’: value, ‘name’: value,
‘renamable’: True, ‘deletable’: True
})
return existing_columnsif name == ‘main’:
app.run_server(debug=True, port=8055)