5

Is there good way to save state( dont reset ) of shinyinput which generated on server side?

Example

ui=shinyUI(fluidPage(
  selectInput("select","",choices = c(1,2),multiple = T),
  uiOutput("din_ui")
  ))

server=function(input, output,session) {
  output$din_ui=renderUI({
    lapply(input$select,function(i){
      numericInput(inputId = paste0("num_",i),i,"")
    })
  })

}

shinyApp(ui,server)

If i select 1 in select insert some values into num_1 than add 2 in select than num_1 reset to start value.

Batanichek
  • 7,761
  • 31
  • 49

2 Answers2

3

You can read the numericInput value, and set the control value at control init. See code:

library(shiny)

ui=shinyUI(fluidPage(
  selectInput("select","",choices = c(1,2),multiple = T),
  uiOutput("din_ui")
)) 

server=function(input, output,session) {
  output$din_ui=renderUI({

    input$select 

    isolate(
      lapply(X   = input$select, 
             FUN = function(i){ 
               cn <- paste0("num_",i)
               numericInput(inputId = cn,
                            label   = i,
                            value   = ifelse(!is.null(input[[cn]]), input[[cn]], ''))
             }
      )
    )
  })

}

shinyApp(ui,server)
Eduardo Bergel
  • 2,685
  • 1
  • 16
  • 21
  • Good variant , i also find other way (dont know which better) ( it hard for me to understand of isolate sometimes ...) – Batanichek Nov 02 '16 at 12:27
0

Also find other way using insertUI ( shiny version >=14)

ui=shinyUI(fluidPage(
  selectInput("select","",choices = c(1,2),multiple = T),
  div(id="din_2")
)) 

server=function(input, output,session) {
  sel_dat=reactiveValues(sel=NULL)

  observeEvent(input$select,{
    to_add=input$select[!input$select%in%sel_dat$sel]
    for ( i in to_add){
           insertUI(
            selector = '#din_2',
            where = "beforeEnd",
            ui =numericInput(inputId = paste0("num_",i),i,"")
          )
    }
    to_remove=sel_dat$sel[which(!sel_dat$sel %in% input$select)]
    if(length(to_remove)>0){
      removeUI(selector = paste0('div:has(>#num_',to_remove,")"))
    }
    sel_dat$sel=input$select
  },ignoreNULL = FALSE)

}
Batanichek
  • 7,761
  • 31
  • 49