Shiny: используйте validate () внутри downloadHandler - PullRequest
0 голосов
/ 04 декабря 2018

У меня есть приложение Shiny, которое печатает отчет после нажатия кнопки.Создание отчета происходит с помощью функции downloadHandler ().

Я хотел бы иметь обязательное поле ввода, прежде чем отчет можно будет экспортировать;соответствующая функция Shiny - validate () (https://shiny.rstudio.com/articles/validation.html).

Однако, согласно документации, функцию validate () можно использовать только в реактивных () или render () функциях:

To use this validation test in your app, place it at the start of any reactive or render* expression that calls input$data. 

Я не могу найти место, где я мог бы поместить эту функцию в мою функцию downloadHandler. Кто-нибудь знает, как это возможно?

Вот соответствующая часть кода; я хочу, чтобы поле "company_name" былоОбязательно для создания отчета.

ui <- fluidPage(

  sidebarLayout(
    position = "left",

    sidebarPanel(

      textInput(
        inputId = "company_name",
        label = "Company name", 
        value = ""
      ),
    )
  )
)

server <- function(input, output) {
  output$report <- downloadHandler(
    filename = "report.pdf",
    content = function(file) {
      # Copy the report file to a temporary directory before processing it, in
      # case we don't have write permissions to the current working dir (which
      # can happen when deployed).
      tempReport <- file.path(tempdir(), "report.Rmd")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      dir.create(file.path(tempdir(),"www"))
      file.copy("www", file.path(tempdir()), recursive=TRUE)      

      # Set up parameters to pass to Rmd document
      params <- list(company_name = input$company_name)

      # Knit the document, passing in the `params` list, and eval it in a
      # child of the global environment (this isolates the code in the document
      # from the code in this app).

      rmarkdown::render(tempReport, output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv())
      )
    }
  )
}

1 Ответ

0 голосов
/ 05 декабря 2018

Проблема в том, что downloadButton является виджетом ввода, а validate должен использоваться с выходами.

Мой обходной путь - скрыть (или отключить) downloadButton, если ваши требованиядля скачивания не встречал.Это можно сделать с помощью shinyjs, что позволяет скрыть или отключить кнопки по идентификатору.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  textInput("text", "content", "", placeholder = "please insert something"),
  hidden(downloadButton("download"))
)

server <- function(input, output, session) {
  output$download <- downloadHandler(
    filename = "file.csv",
    content = function(file) {
      write.csv(data.frame(content = input$text), file)
    }
  )

  observeEvent(input$text, {
    if (input$text == "")
      hide("download")
    else
      show("download")
  })
}

shinyApp(ui, server)

Заменить hide/show/hidden на enable/disable/disabled, чтобы кнопка постоянно отображалась, но когда она была неактивной, input$text пусто.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...