Shiny: how to create a confirm dialog box

后端 未结 3 1718
自闭症患者
自闭症患者 2020-12-30 06:01

I would like to ask if it is possible to have a confirm dialog box, consisting of two buttons, in shiny. Say, if I click a Delete button, then the dialog box pop up. User pi

3条回答
  •  醉梦人生
    2020-12-30 06:40

    Neither ShinyBS nor Javascript is necessary. The trick is to use a modalDialog and set the footer to be a tagList of several tags, usually, an actionButton for the delete and a modalButton to cancel. Below is a MWE

    app.R

    library(shiny)
    
    ui = fluidPage(
       mainPanel(
           actionButton("createfile", "Create"),
           actionButton("deletefile", "Delete")
       )
    )
    
    # Define server logic required to draw a histogram
    server = function(session, input, output) {
    
       observeEvent(input$createfile, {
           showModal(modalDialog(
               tagList(
                   textInput("newfilename", label = "Filename", placeholder = "my_file.txt")
               ), 
               title="Create a file",
               footer = tagList(actionButton("confirmCreate", "Create"),
                                modalButton("Cancel")
               )
           ))
       })
    
    
       observeEvent(input$deletefile, {
           showModal(modalDialog(
               tagList(
                   selectInput("deletefilename", label = "Delete a file", choices = list.files(pattern="*.txt"))
               ), 
               title="Delete a file",
               footer = tagList(actionButton("confirmDelete", "Delete"),
                                modalButton("Cancel")
               )
           ))
       })
    
       observeEvent(input$confirmCreate, {
           req(input$newfilename)
           file.create(input$newfilename)
           removeModal()
       })
    
       observeEvent(input$confirmDelete, {
           req(input$deletefilename)
           file.remove(input$deletefilename)
           removeModal()
       })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    Note, if you use shiny modules, you have to use session$ns("inputID") rather than ns("inputID"). See Tobias' answer here.

提交回复
热议问题