0
votes

Let's say I have the following shiny app:

library(shiny)

shinyApp(
  ui=fluidPage(
    selectizeInput(
      inputId = "foo",
      label   = NULL,
      choices = c("a", "b"),
      options = list(
        create = TRUE
      )
    )
  ),
  server=function(input, output, session){

  }
)

It is a pretty simple app in which I have a dropdown list generated with selectize.js. The create option will allow the user to input a custom selection as input (something different than a or b).

If the user type something, it will display the following: enter image description here

I would like that, when the user clicks on "Add c...", the app would save a file in the app repertory named c.txt containing the string "hello". The documentation of selectize.js suggests the create option can take either a boolean or a function as its argument so, I was guessing intuitively that writing something like

create = function(input){write("hello", paste0(input, ".txt"))}

instead of create = TRUE would work, but it is not.

Anyone could help me with this?

1

1 Answers

1
votes

selectize.js let's you add a JS function not a R function.

But using R you can achieve the same:

library(shiny)

shinyApp(

  ui = fluidPage(
    selectizeInput(
      inputId = "foo",
      label   = NULL,
      choices = c("a", "b"),
      options = list(create = TRUE)
    )
  ),

  server = function(input, output, session) {

    writeSelectizeTxt <- function(selectedChoices) {
      for (selection in selectedChoices) {
        fileName <- paste0(selection, ".txt")
        if (!file.exists(fileName)) {
          write("hello", fileName)
          cat("Wrote file: ", file.path(getwd(), fileName))
        }
      }
    }

    observeEvent(input$foo, {
      req(input$foo)
      writeSelectizeTxt(input$foo)
    }, ignoreNULL = TRUE,
    ignoreInit = FALSE)

  }
)