4

I need to prepopulate Shiny inputs when an app loads based on URL parameters. The code in the below link works normally: https://github.com/daattali/advanced-shiny/tree/master/url-inputs.

However, my data has "&" character in each data. This code also uses "&" character between each input in the URL. How to handle this conflict?

Example input: NAME&SURNAME.

Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59
entropy
  • 191
  • 11

1 Answers1

5

As a workaround you could consider overwriting the parseQueryString() function to your needs. For example change the seperator for the values in the url from & to &&.

parseQueryString <- function (str, nested = FALSE, seperator = "&&") 
{
  if (is.null(str) || nchar(str) == 0) 
    return(list())
  if (substr(str, 1, 1) == "?") 
    str <- substr(str, 2, nchar(str))
  pairs <- strsplit(str, seperator, fixed = TRUE)[[1]]
  pairs <- pairs[pairs != ""]
  pairs <- strsplit(pairs, "=", fixed = TRUE)
  keys <- vapply(pairs, function(x) x[1], FUN.VALUE = character(1))
  values <- vapply(pairs, function(x) x[2], FUN.VALUE = character(1))
  values[is.na(values)] <- ""
  keys <- gsub("+", " ", keys, fixed = TRUE)
  values <- gsub("+", " ", values, fixed = TRUE)
  keys <- URLdecode(keys)
  values <- URLdecode(values)
  res <- stats::setNames(as.list(values), keys)
  if (!nested) 
    return(res)
  for (i in grep("\\[.+\\]", keys)) {
    k <- strsplit(keys[i], "[][]")[[1L]]
    res <- assignNestedList(res, k[k != ""], values[i])
    res[[keys[i]]] <- NULL
  }
  res
}

That would yield:

enter image description here

Code:

library(shiny)

ui <- fluidPage(
  textInput("name", "Name"),
  numericInput("age", "Age", 25)
)

server <- function(input, output, session) {
  observe({
      query <- parseQueryString(session$clientData$url_search)
    print(query)
    if (!is.null(query[['name']])) {
      updateTextInput(session, "name", value = query[['name']])
    }
    if (!is.null(query[['age']])) {
      updateNumericInput(session, "age", value = query[['age']])
    }
  })
}

shinyApp(ui, server)
Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59