Enabling download all with server = TRUE datatable by using invisible download button - r

The goal is to enable download all data from datatable even when server = TRUE. I'm very close already thanks to this post on Github.
This works:
library(shiny)
library(DT)
callback <- JS(
"var a = document.createElement('a');",
"$(a).addClass('dt-button');",
"a.href = document.getElementById('download1').href;",
"a.download = '';",
"$(a).attr('target', '_blank');",
"$(a).text('Download');",
"$('div.dwnld').append(a);",
"$('#download1').hide();"
)
ui <- basicPage(
downloadButton("download1", ""), # no label: this button will be hidden
numericInput("nrows", "Number of rows", 10),
DTOutput("dtable")
)
server <- function(input, output, session){
output$dtable <- renderDT(
datatable(iris[1:input$nrows,],
callback = callback,
extensions = 'Buttons',
options = list(
dom = 'B<"dwnld">frtip',
buttons = list(
"copy"
)
)
)
)
output$download1 <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(iris, file)
}
)
}
shinyApp(ui, server)
The problem is that the download button is briefly visible on app load. How do I ensure the download button is always invisible?
I tried using shinyjs::hidden(), but it causes the download to fail:
library(shiny)
library(shinyjs)
library(DT)
callback <- JS(
"var a = document.createElement('a');",
"$(a).addClass('dt-button');",
"a.href = document.getElementById('download1').href;",
"a.download = '';",
"$(a).attr('target', '_blank');",
"$(a).text('Download');",
"$('div.dwnld').append(a);",
"$('#download1').hide();"
)
ui <- basicPage(
useShinyjs(),
hidden(downloadButton("download1", "")), # no label: this button will be hidden
numericInput("nrows", "Number of rows", 10),
DTOutput("dtable")
)
server <- function(input, output, session){
output$dtable <- renderDT(
datatable(iris[1:input$nrows,],
callback = callback,
extensions = 'Buttons',
options = list(
dom = 'B<"dwnld">frtip',
buttons = list(
"copy"
)
)
)
)
output$download1 <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(iris, file)
}
)
}
shinyApp(ui, server)
EDIT
Using div(style = 'display: none;', ...) also results in a failed download.
library(shiny)
library(DT)
callback <- JS(
"var a = document.createElement('a');",
"$(a).addClass('dt-button');",
"a.href = document.getElementById('download1').href;",
"a.download = '';",
"$(a).attr('target', '_blank');",
"$(a).text('Download');",
"$('div.dwnld').append(a);",
"$('#download1').hide();"
)
ui <- basicPage(
div(style = "display: none;", downloadButton("download1", "")), # no label: this button will be hidden
numericInput("nrows", "Number of rows", 10),
DTOutput("dtable")
)
server <- function(input, output, session){
output$dtable <- renderDT(
datatable(iris[1:input$nrows,],
callback = callback,
extensions = 'Buttons',
options = list(
dom = 'B<"dwnld">frtip',
buttons = list(
"copy"
)
)
)
)
output$download1 <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(iris, file)
}
)
}
shinyApp(ui, server)

You can use the hidden style in the downloadButton as shown below.
library(shiny)
library(shinyjs)
library(DT)
callback <- JS(
"var a = document.createElement('a');",
"$(a).addClass('dt-button');",
"a.href = document.getElementById('download1').href;",
"a.download = '';",
"$(a).attr('target', '_blank');",
"$(a).text('Download');",
"$('div.dwnld').append(a);",
"$('#download1').hide();"
)
ui <- basicPage(
# useShinyjs(),
# hidden(downloadButton("download1", "")), # no label: this button will be hidden
downloadButton("download1", "", style = "visibility: hidden;"),
numericInput("nrows", "Number of rows", 10),
DTOutput("dtable")
)
server <- function(input, output, session){
output$dtable <- renderDT(
datatable(iris[1:input$nrows,],
callback = callback,
extensions = 'Buttons',
options = list(
dom = 'B<"dwnld">frtip',
buttons = list(
"copy"
)
)
)
)
output$download1 <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(iris, file)
}
)
}
shinyApp(ui, server)

Include the button in an invisible div :
ui <- basicPage(
div(
style = "display: none;",
downloadButton("download1", ""), # no label: this button will be hidden
),
numericInput("nrows", "Number of rows", 10),
DTOutput("dtable")
)

Related

How to create a button that will create a pdf file of a table

I currently have a table being generated and I would like the user to be able to create a pdf file when they click the download button.
I am currently getting an error where when I click the download button I get an html file that downloads the entire page of the app. I thought that using pdf(file) would work but it ignores the function.
Here is currently what I have.
library(shiny)
library(xlsx)
library(shinyWidgets)
population <- read.xlsx("population.xlsx", 1)
fieldsMandatory <- c("selectedCountry")
labelMandatory <- function(label) {
tagList(
label,
span("*", class = "mandatory_star")
)
}
appCSS <-
".mandatory_star {color: red;}"
ui <- fluidPage(
navbarPage(title = span("Spatial Tracking of COVID-19 using Mathematical Models", style = "color:#000000; font-weight:bold; font-size:15pt"),
tabPanel(title = "Model",
sidebarLayout(
sidebarPanel(
shinyjs::useShinyjs(),
shinyjs::inlineCSS(appCSS),
div(
id = "dashboard",
pickerInput(
inputId = "selectedCountry",
labelMandatory ("Country"),
choices = population$Country,
multiple = FALSE,
options = pickerOptions(
actionsBox = TRUE,
title = "Please select a country")
),
sliderInput(inputId = "agg",
label = "Aggregation Factor",
min = 0, max = 50, step = 5, value = 10),
actionButton("go","Run Simulation"),
)
),
mainPanel(
tabsetPanel(
tabPanel("Input Summary", verbatimTextOutput("summary"),
tableOutput("table"),
downloadButton(outputId = "downloadSummary", label = "Save Summary"))
)
)
)
)
)
)
server <- function(input, output, session){
observeEvent(input$resetAll, {
shinyjs::reset("dashboard")
})
values <- reactiveValues()
values$df <- data.frame(Variable = character(), Value = character())
observeEvent(input$go, {
row1 <- data.frame(Variable = "Country", Value = input$selectedCountry)
row2 <- data.frame(Variable = "Aggregation Factor", Value = input$agg)
values$df <- rbind(row1, row2)
})
output$table <- renderTable(values$df)
observe({
# check if all mandatory fields have a value
mandatoryFilled <-
vapply(fieldsMandatory,
function(x) {
!is.null(input[[x]]) && input[[x]] != ""
},
logical(1))
mandatoryFilled <- all(mandatoryFilled)
# enable/disable the submit button
shinyjs::toggleState(id = "go", condition = mandatoryFilled)
})
output$downloadSummary <- downloadHandler(
filename = function(file) {
paste('my-report.pdf', )
},
content = function(file) {
pdf(file)
}
)
}
shinyApp(ui,server)
Here's a minimal example:
library(shiny)
ui <- fluidPage(
downloadButton("savepdf", "Save pdf")
)
server <- function(input, output, session) {
output$savepdf <- downloadHandler(
filename = "test.pdf",
content = function(file) {
pdf(file)
plot(iris$Sepal.Length, iris$Sepal.Width)
dev.off()
}
)
}
shinyApp(ui, server)
Also see here.
Here is a minimal example with the package latexpdf. It will create the pdf table in the folder of the app.
library(shiny)
library(latexpdf)
dat <- head(iris, 5)
ui <- fluidPage(
br(),
actionButton("dwnld", "Create pdf"),
tableOutput("mytable")
)
server <- function(input, output, session){
output[["mytable"]] <- renderTable({
dat
})
observeEvent(input[["dwnld"]], {
as.pdf(dat)
})
}
shinyApp(ui, server)

Shiny: How to disable download button when there no data?

I'm working inside a module which queries some data and then shows it on a DT::datatable, I added a download button so I can download the data with the filters applied.
I already called useShinyjs() in the main ui file of the app.
But I want to disable the download button in case there is no data.
I've tried the following.
observeEvent(data(), {
if (!nrow(data()) > 0) {
shinyjs::disable("download")
} else {
shinyjs::enable("download")
})
However the next error message shows up, and the app crashes as soon as I run it.
Expecting a single string value: [type=character; extent=0]
ui Code:
module_ui <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
tabBox(
title = tagList(
downloadButton(ns("download"), label = "Download data")
),
width = 12,
tabPanel(
title = HTML("Documentation"),
div(style = 'overflow-x: scroll;font-size:90%', DTOutput(ns("table")))
)
)
)
)
}
server Code:
module_server <- function(id,
connection,
update_button,
update_button_name) {
moduleServer(
id = id,
module = function(input, output, session) {
ns <- session$ns
# 1 . Data -----
data <- eventReactive(list(update_button()), {
data <- dbGetQuery(
connection,
glue::glue("SELECT * FROM Process;)
return(data)
}, ignoreNULL = FALSE, ignoreInit = FALSE)
# 2 . Table -----
output$table<- renderDT({
shiny::validate(
shiny::need(!is_null(data()) && nrow(data()) > 0, 'No data...')
)
datatable(
data = data(),
selection = "single",
style = "bootstrap",
rownames = FALSE,
filter = 'top',
options = list(
searchHighlight = TRUE,
dom = 'tipr',
pageLength = 20,
columnDefs = list(
list(visible = F, targets = c(0)),
list(width = "200px", targets = "_all")
)
)
)
}, server = TRUE)
# 3 . Download -----
observeEvent(data(), {
if (nrow(data()) > 0) {
shinyjs::enable("download")
} else {
shinyjs::disable("download")
}
})
output$download <- downloadHandler(
filename = "Documentation.xlsx",
content = function(file) {
openxlsx::write.xlsx(
x = data() %>% slice(input$tabla_rows_all),
file = file,
asTable = FALSE,
row.names = FALSE
)
}
)
Many thanks in advance to whoever can help!
Use shinyjs::toggleState() instead. Here is a reproducible example:
library(shiny)
library(shinyjs)
ui <- fluidPage(
shinyjs::useShinyjs(),
fileInput(
inputId = "file1", label = "Choose a file to upload:", accept = ".csv"
),
tableOutput(
outputId = "table1"
),
downloadButton(
outputId = "download_data", class = "btn-success"
)
)
server <- function(input, output, session) {
the_data <- reactive({
req(input$file1)
read.csv(input$file1$datapath)
})
output$table1 <- renderTable({
the_data() |> head()
})
# <-- observe if there's any input file -->
observe({
# mandatory condition: there should be an input file
mand_condition <- \() {
!is.null(input$file1)
}
shinyjs::toggleState(
id = "download_data", condition = mand_condition()
)
})
output$download_data <- downloadHandler(
filename = \() {
input$file1$name
},
content = function(file) {
write.csv(the_data(), file)
}
)
}
shinyApp(ui, server)

hide button in shindydashboard body until table is rendered

I have a shiny app where I load a file and a tabla is rendered, I want to hid a button in the body until the table is rendered. This button is going to save the filters in a file. I am using shinySaveButton from shinyFiles because I want the user to navigate until a folder and choose a custom filename
Here is the UI
header <- dashboardHeader()
sidebar <- dashboardSidebar(
sidebarUserPanel("Test"),
sidebarMenu(
id = "tabs",
menuItem("Archivo variantes", tabName = "fileupload", icon = icon("table")),
conditionalPanel("input.tabs == 'fileupload' ",
shinyFilesButton("file", "Choose a file" , multiple = FALSE,
title = "Please select a file:",
buttonType = "default", class = NULL)#,
)
)
)
body <- dashboardBody(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"),
shinyjs::useShinyjs(),
tabItems(
tabItem(tabName = "fileupload",
fluidRow(column(12,
div(DT::dataTableOutput('tabla') %>% withSpinner(color="#0dc5c1"), style = 'overflow-x: auto'))),
fluidRow(column(2, offset = 0,
shinySaveButton('save', 'Save filters', 'Save as...') )))
)
)
ui <- dashboardPage(header, sidebar, body)
And here is the server
## Server side
server = function(input, output, session) {
options(shiny.maxRequestSize=100*1024^2)
if (!exists("default_search_columns")) default_search_columns <- NULL
volumes = getVolumes()
volumes <- c(Home = fs::path_home(), "R Installation" = R.home(), getVolumes()())
file_selected <- reactive({
shinyFileChoose(input, "file", roots = volumes, session = session)
if (is.null(input$file))
return(NULL)
print(parseFilePaths(volumes, input$file)$datapath)
return(parseFilePaths(volumes, input$file)$datapath)
})
contents <- reactive({
if (is.null(file_selected()))
return()
print(file_selected())
df <- read.delim(file_selected(), header = TRUE, stringsAsFactors=FALSE, as.is=TRUE)
return(tidyr::separate_rows(df, Gene.refGene, sep = ";"))
})
# Reactive function creating the DT output object
output$tabla <- DT::renderDataTable({
if(is.null(contents()))
return()
datos <- contents()
DT::datatable(datos,
rownames = FALSE,
style = 'bootstrap',
class = 'compact cell-border stripe hover',
filter = list(position = 'top', clear = FALSE),
escape = FALSE,
extensions = c('Buttons', "FixedHeader", "Scroller"),
options = list(
stateSave = FALSE,
autoWidth = TRUE,
search = list(regex = TRUE, caseInsensitive = TRUE),
initComplete = JS(
"function(settings, json) {",
"$(this.api().table().header()).css({'font-size': '12px'});",
"}"),
scroller = TRUE,
scrollX = TRUE,
scrollY = "600px",
deferRender=TRUE,
buttons = list('colvis', list(
extend = 'collection',
buttons = list(list(extend='csv',
filename = 'results'),
list(extend='excel',
filename = 'results')),
text = 'Download'
)),
FixedHeader = TRUE
),
callback = JS('table.page(3).draw(false); "setTimeout(function() { table.draw(true); }, 300);"')) %>% formatStyle(columns = colnames(.$x$data), `font-size` = "12px")
})
filtros <- eventReactive(input$tabla_search_columns, {
str(input$tabla_search_columns)
return(input$tabla_search_columns)
})
observeEvent(input$save,
{
observe(
if(is.null(input$tabla)) {
shinyjs::disable("save")
} else { shinyjs::enable("save") }
)
})
observe({
volumes <- getVolumes()
volumes <- c(Home = fs::path_home(), "R Installation" = R.home(), getVolumes()())
shinyFileSave(input, "save", roots=volumes, session=session)
fileinfo <- parseSavePath(volumes, input$save)
if (nrow(fileinfo) > 0) {
write.table(filtros(), fileinfo$datapath, row.names = FALSE, col.names=FALSE, quote=TRUE, sep="\t")
}
})
}
shinyApp(ui, server)
I am trying to use shinyjs::disable and shinyjs::enable but I can't make it work, the button save filters is shown before selecting a file. And I want to be hidden until the table is rendered
Any help would be appreciated
Shiny triggers the JavaScript event shiny:value when an output is rendered. So you can disable the button at the initialization of the app, and with the help of this JS event you can enable the button whenever the table is rendered. Here is a minimal example:
library(shiny)
library(shinyFiles)
js <- paste(
"$(document).ready(function(){",
" $('#save').prop('disabled', true);", # disable the 'save' button
"});",
"$(document).on('shiny:value', function(e){",
" if(e.name === 'table'){", # if 'table' is rendered
" $('#save').prop('disabled', false);", # then enable the 'save' button
" }",
"});"
, sep = "\n"
)
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
shinySaveButton("save", "Save", "Save file"),
actionButton("go", "Render table"),
tableOutput("table")
)
server <- function(input, output){
output[["table"]] <- renderTable({
req(input[["go"]]>0)
iris[1:4, ]
})
}
shinyApp(ui, server)

make conditionalPanel appears when RData file is loaded in shinydashboard

I am making a shiny app that interacts with a big data.frame that I have stored as an RData file. I want the user to select the file, and once the RData is completely loaded (takes ~15 seconds) a second panel should show up allowing the user to input some sample name and do some operations.
Here is how my app looks now
header <- dashboardHeader(title="Analysis and database")
sidebar <- dashboardSidebar(
useShinyjs(),
sidebarUserPanel(),
hr(),
sidebarMenu(
# Setting id makes input$tabs give the tabName of currently-selected tab
id = "sidebarmenu",
menuItem("Analyse old data by Sample", tabName="oldfile", icon = icon("table"), startExpanded = FALSE),
fileInput(inputId = "file1", "Choose database file"),
conditionalPanel(
#condition = "input.sidebarmenu === 'oldfile'",
condition = "output.fileUploaded == 'true' ",
textInput(inputId = "sample", label ="Type a sample ID"),
actionButton("go2", "Filter")
)
)
)
body <- dashboardBody(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"),
tabItems(
tabItem("oldfile", "Sample name data.table",
fluidRow(DT::dataTableOutput('tabla_oldfile') %>% withSpinner(color="#0dc5c1")))
)
)
ui <- dashboardPage(header, sidebar, body)
### SERVER SIDE
server = function(input, output, session) {
options(shiny.maxRequestSize=100000*1024^2)
prop <- reactive({
if (input$go2 <= 0){
return(NULL)
}
result <- isolate({
if (is.null(input$file1))
return(NULL)
if (is.null(input$sample))
return(NULL)
inFile <- input$file1
print(inFile$datapath)
#big_df <- load(inFile$datapath)
print (big_df)
print(input$sample)
oldtable <- big_df1 %>% filter_at(vars(GATK_Illumina.samples:TVC_Ion.samples),
any_vars(stringi::stri_detect_fixed(., as.character(input$sample))))
oldtable
})
result
})
output$fileUploaded <- reactive({
return(!is.null(prop()))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
output$tabla_oldfile <- DT::renderDataTable({
DT::datatable(prop(),
filter = 'top',
extensions = 'Buttons',
options = list(
dom = 'Blftip',
buttons =
list('colvis', list(
extend = 'collection',
buttons = list(list(extend='csv',
filename = 'results'),
list(extend='excel',
filename = 'results'),
list(extend='pdf',
filename= 'results')),
text = 'Download'
)),
scrollX = TRUE,
pageLength = 5,
lengthMenu = list(c(5, 15, -1), list('5', '15', 'All'))
), rownames = FALSE
)
})
}
shinyApp(ui, server)
I have used the solution provide in Make conditionalPanel depend on files uploaded with fileInput but I can't make it work, there is another implementation using shinyjs package but don't know how to use it on my example

Create downloadButton that can output multiple file types R Shiny

I have created a download button for an R Shiny app that outputs a CSV. I would like to add check boxes to the UI for options to output a json, xls, and TSV file and then the corresponding functions in the server function. Any insights? Bellow is some minimal code related to this:
library(shiny)
set.seed(123)
N<- 500
M<-56
EF<- matrix( rnorm(N*M,mean=23,sd=3), N, M)
WM<- matrix( rnorm(N*M,mean=20,sd=3), N, M)
DP<- matrix( rnorm(N*M,mean=25,sd=3), N, M)
Date <- seq(as.Date("2018-01-01"), as.Date("2018-02-25"), by="days")
Date <- as.POSIXct(Date, format = "%Y-%m-%d %H:%M")
ui <- fluidPage(
titlePanel(code(strong("Measures"), style = "color:black")),
sidebarLayout(
sidebarPanel(
strong("Tools:"),
selectInput("Test",
label = "Choose a measure to display",
choices = c("EF",
"WM",
"DP"
),
selected = "EF"),
downloadButton("downloadData", "Download")),
mainPanel(
code(strong("Output Data"))
))
)
server <- function(input, output) {
output$downloadData <- downloadHandler(
filename = function() {
paste(input$dataset, "Table.csv", sep = ",")
},
content = function(file) {
write.csv(x, file, row.names = FALSE)
}
)
}
# Run that shit ----
shinyApp(ui = ui, server = server)
Not the most elegant, but here's an option. I created a mock example -- I couldn't use your code since x (what you're downloading) isn't defined in your example.
library(shiny)
library(RJSONIO)
library(xlsx)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("dataset",
label = "Choose dataset",
choices = c("iris", "cars")),
radioButtons("downloadType", "Download Type",
choices = c("CSV" = ".csv",
"JSON" = ".json",
"XLS" = ".xls",
"TSV" = ".tsv"),
inline = TRUE),
downloadButton("downloadData", "Download")
),
mainPanel()
)
)
server <- function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"iris" = iris,
"cars" = cars)
})
output$downloadData <- downloadHandler(
filename = function() {
paste0(input$dataset, "_Table", input$downloadType)
},
content = function(file) {
if(input$downloadType == ".csv") {
write.csv(datasetInput(), file, row.names = FALSE)
} else if(input$downloadType == ".json") {
exportJSON <- toJSON(datasetInput())
write(exportJSON, file)
} else if(input$downloadType == ".xls") {
write.xlsx(datasetInput(), file,
sheetName = "Sheet1", row.names = FALSE)
} else if(input$downloadType == ".tsv") {
write.table(datasetInput(), file, quote = FALSE,
sep='\t', row.names = FALSE)
}
}
)
}
shinyApp(ui = ui, server = server)

Resources