Hi everyone! I could be confounding some issues here but I want to dynamically create download buttons in a table using server side logic, and I think this code doesn't work because I'm not NS
ing properly?
In the dummy app below, we're using a file path (here my desktop, youll have to change this locally to a directory with files) and the app will display the names of those files, and I'd like the DOWNLOAD button to download said file.
library(shiny)
# function to make inputs
shinyInput <- function(FUN, len, id, ...) {
inputs <- character(len)
for (i in seq_len(len)) {
inputs[i] <- as.character(FUN(paste0(id, i), ...))
}
inputs
}
mod_data_ui <- function(id) {
fluidPage(
DT::dataTableOutput(NS(id, "data")),
textOutput(NS(id, 'myText'))
)
}
mod_data_server <- function(id, trainingname) {
moduleServer(id, function(input, output, session) {
path <- "/Users/mayagans/Desktop/"
datafiles <- reactiveValues(
names = unlist(list.files(path)),
number = length(unlist(list.files(path))),
file = NULL
)
df <- reactive({
data.frame(
Files = datafiles$names,
Delete = shinyInput(downloadLink,
datafiles$number,
NS(id, 'delete_btn_'),
label = "DOWNLOAD",
class="delete_btn",
onclick = paste0('Shiny.setInputValue(\"', NS(id, "select_button"), '\", this.id)'))
)
})
output$data <- DT::renderDT({
DT::datatable(
df(),
escape = FALSE,
selection = 'none',
rownames = FALSE,
options(
dom = 'lrt',
bFilter = FALSE,
bInfo = FALSE,
paging = FALSE,
lengthChange = FALSE
)
)
}, server = FALSE)
observeEvent(input$select_button, {
selectedRow <- as.numeric(strsplit(input$select_button, "_")[[1]][3])
datafiles$file <- paste('click on ',df()$Files[selectedRow])
# I think I need to gsub out the namespace
# because the server does this for free?
# but output[[input$select_button]] isnt working
browser()
output[[gsub(".*-", "", input$select_button)]] <- downloadHandler(
filename = function() {
list.files(path)[selectedRow]
},
content = function(file) {
file.copy(
paste0(
path,
unlist(list.files(path))[selectedRow]
),
file
)
}
)
})
output$myText <- renderText({ datafiles$file })
})
}
# the app
ui <- fluidPage(mod_data_ui("data"))
server <- function(input, output) {
mod_data_server("data")
}
shinyApp(ui = ui, server = server)