Unable download button if certain conditions are not met

Hello everyone,

I am trying to create a downloadButton() in UI and downloadHandler() in server. The goal is to prevent the download if certain conditions are not met, for example if the selectInput() is blank or no option selected. As an example here is the code:

library(shiny)

ui <- fluidPage(
  selectInput(inputId="select",
              label="Choose variable:",
              choices=c("","rock","car","pressure"),
              selected = NULL),
  br(),
  downloadButton("downloadData", "Download")

)

server <- function(input, output) {
  
  data <- mtcars
  
  output$downloadData <- downloadHandler(
    filename = function() {
      paste("data-", Sys.Date(), ".csv", sep="")
    },
    content = function(file) {
      write.csv(data, file)
    }
  )
}

shinyApp(ui, server)

I want to make the downloadButton only works if (input$select != ""), otherwise it should give like a pop-up message or an error like mentioned in Message popup. I have tried different things with if else() options but it did not work. Could anybody help me?

place a uiOutput, and when your define the renderUI function, you can programattically determine whether to place a downloadbutton there or just a regular button that triggers a pop up message.

Could you give an example of it? I don't understand what you mean with downloadButton and regular button. I don't actually really want to have 2 buttons :thinking:. Thank you

library(shiny)

ui <- fluidPage(
  selectInput(inputId="select",
              label="Choose variable:",
              choices=c("","rock","car","pressure"),
              selected = NULL),
  br(),
  uiOutput("mybutton")

  
)

server <- function(input, output) {
  
  data <- mtcars

  output$mybutton <- renderUI({
    if(isTruthy(input$select))
    downloadButton("downloadData", "Download")
    else 
      actionButton("dummybutton","Download",icon = icon("download"))
  })
  
  observeEvent(input$dummybutton,{
    showModal(modalDialog(
      title = "Important message",
      "This is an important message!"
    ))
  })
  
  output$downloadData <- downloadHandler(
    filename = function() {
      paste("data-", Sys.Date(), ".csv", sep="")
    },
    content = function(file) {
      write.csv(data, file)
    }
  )
}

shinyApp(ui, server)

I understand now what you mean! That works really well! Thank you so much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.