Black Lives Matter. Please consider donating to Campaign Zero's mission of ending police violence in America.
https://www.joincampaignzero.org

[Callback] Programmatically add callback

Hi,
I’ve built a Dash application, with lots of Dropdowns everywhere, some of them with multiple values.
I’ve been asked to add a ‘Select all’ button on all multi-select dropdowns.
To stay DRY, I’ve build a wrapper for dropdowns, and I would need to update it to add the ‘Select all’ button and the corresponding callback there, something like below:

def create_dropdown(*args, **kwargs):
    dropdown = dcc.Dropdown(*args, **kwargs)
    if kwargs.get('multi', False):
        @app.callback(...)
        def update_value(n_clicks):
             return kwargs.get(options, [])

        return html.Div([dropdown, html.Button('Select all', id=...)])
    return dropdown

Unfortunately, this way, the callback is not applied, though the button is rendered.
Has anyone any clue how I can achieve the intended behavior ?
Thanks

This sounds like a good opportunity for the brand new pattern matching callbacks: https://dash.plotly.com/pattern-matching-callbacks

you’ll have to make sure that all of these callbacks are registered before run_server is called. callbacks can’t be registered dynamically. if you are adding these components dynamically, then pattern matching callbacks is the way to go.

I don’t seem to be able to figure out how to use a different list of options (+ default value and everything else) for each different drop down, using a pattern-matching callback.

Also, pattern-matching callbacks are applied once to all items (the function takes the list of all Inputs matching the pattern as arguments), while my Dropdowns are totally independent from one another.

The solution I use is indeed pattern-matching callbacks, using the MATCH keyword (I was focused on the ALL keyword).

An other one would be (in my case) to write a function creating both the callback and the layout, and to make sure to call this function only once, when creating the layout. That’s a bit more complex and quite ugly.