我有一个Shiny应用程序,单击按钮后即可打印报告。通过downloadHandler()函数创建报告。
在导出报告之前,我希望有一个必填字段;合适的Shiny函数是validate()(https://shiny.rstudio.com/articles/validation.html)。
但是,根据文档,validate()函数只能在react()或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())
)
}
)
}
答案 0 :(得分:0)
问题在于downloadButton
是一个输入小部件,而validate
应该与输出一起使用。
我的解决方法是,如果不满足下载要求,则隐藏(或禁用)downloadButton
。可以使用shinyjs
来完成,它可以让您按ID隐藏或禁用按钮。
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
为空,就使其不可单击。