Validate inside downloadHandler

偶尔善良 提交于 2020-01-02 11:06:45

问题


I want to perform some validation inside downloadHandler, so that when the condition is true a custom message is given else download of data. I have the following code example where I want to perform validation, but it seems not working.

shinyApp(
  ui = basicPage(
    textInput("jobid", label = "Enter job ID", value = ""),
    downloadLink("downloadData", "Download")

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

    output$downloadData <- downloadHandler(
      filename = function() {
        paste("data-", Sys.Date(), ".csv", sep="")
      },
      content = function(file) {
        if(input$jobid ==""){
          session$sendCustomMessage(type = 'testmessage',
                                    message = 'No job id to submit')
        }else
          write.csv(data, file)
      }
    )
  }
)

How to validate??


回答1:


Well, maybe this is not the most elegant solution, but I hope it helps!

library(shiny)

ui <- fluidPage(
  textInput("jobid", label = "Enter job ID", value = ""),
  uiOutput("button"),
  textOutput("downloadFail")
)

server <- function(input, output, session) {

  output$button <- renderUI({
    if (input$jobid == ""){
      actionButton("do", "Download", icon = icon("download"))
    } else {
      downloadButton("downloadData", "Download")
    }
  })

  available <- eventReactive(input$do, {
    input$jobid != ""
  })

  output$downloadFail <- renderText({
    if (!(available())) {
      "No job id to submit"
    } else {
        ""
    } 
  })

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


shinyApp(ui, server)


来源:https://stackoverflow.com/questions/46903285/validate-inside-downloadhandler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!