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
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
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.