kms
kms

Reputation: 2024

Dash modal popup toggle code isn't working

I am using a modal popup in my dash application. In the layout, I have 2 buttons defined. One Opens the modal and other one Closes it. I referenced the example in documentation and using a slightly different code to listen to each button.

Upon close of the Modal, I'd like to call a function and run some other lines of code. However, I can't seem to listen to the button click of close button.

            # Modal buttons - layout code

            dbc.Button("Add", id="open-btn"),
 
            dbc.Button("Close", id="close-btn")


            # Callbacks
          
             # Modal toggle
             @app.callback(Output("modal-2", "is_open"),
             [
                  Input("open-btn", "n_clicks"),
                  Input("close-btn", "n_clicks")
             ],

             [
                  
                  State("Address", "value"),
                  State("City","value"),
                  State("Zip","value"),
                  State("State","value"),
                  State("modal-2", "is_open")
             ],
             )
            def add_prop(open_btn, close_btn, address, city, zip, state, is_open):

                 if open_btn:

                    return not is_open

                ## This code doesn't work 

                if close_btn:

                   print("Call function")
        
                   append_prop(tenant, industry, address, city, zip, state)

                   return is_open


I am trying to figure why the close pop up block of code isn't work.

Upvotes: 1

Views: 1596

Answers (1)

coralvanda
coralvanda

Reputation: 6616

What's happening is that open_btn, which is based on the n_clicks prop of that component, starts at a value of 0. When the user clicks the button, it increments and the callback fires with open_btn having a value of 1. That prop will retain the value for future calls to your callback. So, when the close button triggers the callback, open_btn still has a value of 1, and the first if statement evaluates to True.

The way to solve this is with callback_context

def add_prop(open_btn, close_btn, address, city, zip, state, is_open):
    ctx = dash.callback_context

    if not ctx.triggered:
        button_id = 'No clicks yet'
    else:
        button_id = ctx.triggered[0]['prop_id'].split('.')[0]

Now you can check the value of button_id to see whether it was the open or close button that caused the callback to fire, and execute the proper part of your code.

Upvotes: 2

Related Questions