firmo23
firmo23

Reputation: 8404

Create one or more shiny widgets based on selection of another shiny widget

I have the shiny app below in which the user may select between one or more column names from the dt data.frame

name<-c("John","Jack","Bill")
value1<-c(2,4,6)
add<-c("SDF","GHK","FGH")
value2<-c(3,4,5)
dt<-data.frame(name,value1,add,value2)

Then for every selection he makes the relative selectInput() may be displayed below. Maybe I could use if for every case but the issue is that my real dataset may be much bigger and has different column names every time so Im looking for a way to instantly connect the pickerInput() selected name with the creation of the relative selectInput() which will include the column values. For example if someone select all 4 column names 4 selectInputs should be created with the relative column name as label.

library(shiny)
library(shinyWidgets)

# ui object
ui <- fluidPage(
    titlePanel(p("Spatial app", style = "color:#3474A7")),
    sidebarLayout(
        sidebarPanel(
            pickerInput(
                inputId = "p1",
                label = "Select Column headers",
                choices = colnames( dt),
                multiple = TRUE,
                options = list(`actions-box` = TRUE)
            ),
            uiOutput("widg")
            
            
        ),
        
        mainPanel(
            
        )
    )
)

# server()
server <- function(input, output) {
   
    output$widg<-renderUI({
        
    })
    
   
}

# shinyApp()
shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 748

Answers (1)

Marcus
Marcus

Reputation: 3636

High level, I would create the selectInput in the statically in the UI and consider using updateSelectInput when your picker changes. Roughly something like this (note the addition of the session variable to the server function):

ui <- fluidPage(
  titlePanel(p("Spatial app", style = "color:#3474A7")),
  sidebarLayout(
    sidebarPanel(
      pickerInput(
        inputId = "p1",
        label = "Select Column headers",
        choices = colnames( dt),
        multiple = TRUE,
        options = list(`actions-box` = TRUE)
      ),
      selectInput("columnValues", "", choices = "")
      
      
    ),
    
    mainPanel(
      
    )
  )
)

# server()
server <- function(input, output, session) {
  
  observeEvent(input$p1, {
    
    updateSelectInput(
      session, 
      inputId = "columnValues", 
      label = paste0("Choose from: ", input$p1),
      choices = dt[[input$p1]]
    )
    
  })
  
  
}

# shinyApp()
shinyApp(ui = ui, server = server)

I did notice you are using a multi-select picker so you would have to modify how the column values get concatenated when multiple headers are chosen (also how the label is generated).

If you don't want to selectInput to be visible if nothing is selected in the picker, there are multiple ways to toggle its visibility such as using conditionalPanel.

Upvotes: 2

Related Questions