Populate selectizeInput on first load - r

Below is some code for a very simple shiny dashboard. On tab 1 "Select" I have a radio button selector and on tab 2 "Food" I have a selectizeInput.
When the dashboard initially loads the first tab is loaded and "Fruits" is selected by default. When I move to tab 2 however, nothing displays in the selectizeInput drop down menu dispite having an observe event linked to the radio buttons.
If I then go back to the Select tab and click on Meats, the selectizeInput populates. If I then select Fruits again on the Select tab, the selectizeInput populates with a list of fruits.
How do I make the selectizeInput populate on first load with the list of fruits?
Thanks
library(shinydashboard)
library(data.table)
menu <- data.table(numb = c(rep(1,4), rep(2,4)),
item = c("Apple", "Orange", "Grape", "Lemon", "Steak", "Chicken", "Pork", "Venison"))
ui <- dashboardPage(skin = "blue",
dashboardHeader(),
dashboardSidebar(
sidebarMenu(id = "initalTab",
sidebarMenuOutput("menuSidebar"))
),
dashboardBody(
tabItems(
tabItem("select",
uiOutput("selectType")),
tabItem("food",
uiOutput("selectFood"))
)
)
)
server <- (function(input, output, session) {
output$menuSidebar <- renderMenu({
sidebarMenu(
menuItem("Select", tabName = "select", icon = icon("home")),
menuItem("Food", tabName = "food", icon = icon("sort"))
)
})
isolate({updateTabItems(session, "initalTab", "select")})
output$selectType <- renderUI({
fluidRow(
box(width = 3, status = "primary", solidHeader = TRUE,
radioButtons("foodFilter", label = h4("Filter by Food Type"),
choices = c("Fruits" = 1, "Meats" = 2),
selected = 1,
inline = TRUE)
)
)
})
output$selectFood <- renderUI({
fluidRow(
box(width = 6, status = "primary", solidHeader = TRUE,
h4("Select Your Food"),
selectizeInput("group",
choices = NULL,
width ="100%",
NULL,
NULL,
multiple = TRUE,
options = list(plugins = list("drag_drop", "remove_button"),
placeholder = "Please select you food"))
)
)
})
observeEvent(input$foodFilter, {
updateSelectizeInput(session,
"group",
choices = menu[numb == input$foodFilter,`item`],
selected = menu[numb == input$foodFilter,`item`][1],
server = TRUE)
})
})
shinyApp(ui, server)

Building up on my comment try adding this line outputOptions(output, "selectFood", suspendWhenHidden = FALSE)
library(shinydashboard)
library(data.table)
library(shiny)
menu <- data.table(numb = c(rep(1,4), rep(2,4)),
item = c("Apple", "Orange", "Grape", "Lemon", "Steak", "Chicken", "Pork", "Venison"))
ui <- dashboardPage(skin = "blue",
dashboardHeader(),
dashboardSidebar(
sidebarMenu(id = "initalTab",
sidebarMenuOutput("menuSidebar"))
),
dashboardBody(
tabItems(
tabItem("select",
uiOutput("selectType")),
tabItem("food",
uiOutput("selectFood"))
)
)
)
server <- (function(input, output, session) {
output$menuSidebar <- renderMenu({
sidebarMenu(
menuItem("Select", tabName = "select", icon = icon("home")),
menuItem("Food", tabName = "food", icon = icon("sort"))
)
})
isolate({updateTabItems(session, "initalTab", "select")})
output$selectType <- renderUI({
fluidRow(
box(width = 3, status = "primary", solidHeader = TRUE,
radioButtons("foodFilter", label = h4("Filter by Food Type"),
choices = c("Fruits" = 1, "Meats" = 2),
selected = 1,
inline = TRUE)
)
)
})
output$selectFood <- renderUI({
fluidRow(
box(width = 6, status = "primary", solidHeader = TRUE,
h4("Select Your Food"),
selectizeInput("group",
choices = NULL,
width ="100%",
NULL,
NULL,
multiple = TRUE,
options = list(plugins = list("drag_drop", "remove_button"),
placeholder = "Please select you food"))
)
)
})
outputOptions(output, "selectFood", suspendWhenHidden = FALSE)
observeEvent(input$foodFilter,{
updateSelectizeInput(session,
"group",
choices = menu[numb == input$foodFilter,`item`],
selected = menu[numb == input$foodFilter,`item`][1],
server = TRUE)
})
})
shinyApp(ui, server)

Related

Dynamic left menu listing items downward instead of to the right

I am trying to create a dynamic left menu (header), but the items are listed downward instead of to the right. I guess it has to do with the tagList wrapper when defining the UI.
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyWidgets)
library(stringr)
ui = dashboardPage(
dashboardHeader(
leftUi = tagList(uiOutput("filter"))
),
dashboardSidebar(
pickerInput(
"inputParameters",
"Parameters:",
choices = c("a", "b", "c"),
multiple = TRUE,
options = list(
`actions-box` = TRUE,
size = 10,
`selected-text-format` = "count > 1"
)
)
),
dashboardBody(),
title = "DashboardPage"
)
server = function(input, output) {
params <- reactive(input$inputParameters)
output$filter = renderUI(
lapply(seq_along(params()), function(i) {
dropdownButton(
inputId = paste0("mydropdown", i),
label = params()[i],
icon = icon("sliders"),
status = "primary",
circle = FALSE,
selectizeInput(
paste0("input", paste0(str_to_title(params()[i]))),
paste0(paste0(str_to_title(params()[i]), ":")),
choices = 1:3,
multiple = TRUE,
selected = 1:3
)
)
})
)
}
shinyApp(ui, server)
Not tested, I would try:
output$filter = renderUI({
ddbuttons <- lapply(seq_along(params()), function(i) {
dropdownButton(
inputId = paste0("mydropdown", i),
label = params()[i],
icon = icon("sliders"),
status = "primary",
circle = FALSE,
selectizeInput(
paste0("input", paste0(str_to_title(params()[i]))),
paste0(paste0(str_to_title(params()[i]), ":")),
choices = 1:3,
multiple = TRUE,
selected = 1:3
)
)
})
do.call(splitLayout, ddbuttons)
})
And don't use tagList, just uiOutput("filter").

Reactively updating sidebar in modular Shiny app

I have a modularized Golem app using bs4Dash. I want to update the active sidebar tab from an actionBttn that is dynamically generated from renderUI. While updatebs4ControlbarMenu works as expected as shown here, it does not work in the modularized version of the application. What am I doing wrong? I suspect it is related to input[[btnID]] management across modules but I struggle to find the solution.
Working example without modules as shown here:
library(shiny)
library(shinyWidgets)
library(bs4Dash)
library(tidyverse)
shinyApp(
ui = bs4DashPage(
sidebar_collapsed = FALSE,
controlbar_collapsed = TRUE,
enable_preloader = FALSE,
navbar = bs4DashNavbar(skin = "dark"),
sidebar = bs4DashSidebar(
inputId = "sidebarState",
bs4SidebarMenu(
id = "sidebr",
bs4SidebarMenuItem(
"Tab 1",
tabName = "tab1"
),
bs4SidebarMenuItem(
"Tab 2",
tabName = "tab2"
)
)
),
bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab1",
h1("Welcome!"),
fluidRow(
pickerInput(
inputId = "car",
label = "Car",
choices = row.names(mtcars),
selected = head(row.names(mtcars), 3),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
),
pickerInput(
inputId = "gear",
label = "Gear",
choices = unique(mtcars$gear),
selected = unique(mtcars$gear),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
)
),
fluidRow(
column(6,
uiOutput("uiboxes")
)
)
),
bs4TabItem(
tabName = "tab2",
h4("Yuhuuu! You've been directed automatically in Tab 2!")
)
)
)
),
server = function(input, output, session) {
submtcars <- reactive({
req(input$car, input$gear)
mtcars %>%
mutate(
carnames = rownames(mtcars)) %>%
filter(
carnames %in% input$car &
gear %in% input$gear
)
})
observeEvent( submtcars(), {
n_ex <- nrow(submtcars())
output$uiboxes <- renderUI({
lapply(1:n_ex, FUN = function(j) {
print(paste("j is ", j))
bs4Box(
title = submtcars()$carnames[j],
width = 12,
str_c("Number of gears:", submtcars()$gear[j]),
btnID <- paste0("btnID", j),
print(btnID),
fluidRow(
column(
2,
actionBttn(
inputId = btnID,
icon("search-plus")
)
)
)
)
})
})
lapply(1:n_ex, function(j) {
btnID <- paste0("btnID", j)
observeEvent(input[[btnID]] , {
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "tab2"
)
})
})
})
}
)
Modularized attempt not working:
library(shiny)
library(shinyWidgets)
library(bs4Dash)
library(tidyverse)
mod_exlib_ui <- function(id){
ns <- NS(id)
tagList(
fluidRow(
pickerInput(
inputId = ns("car"),
label = "Car",
choices = row.names(mtcars),
selected = head(row.names(mtcars), 3),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
),
pickerInput(
inputId = ns("gear"),
label = "Gear",
choices = unique(mtcars$gear),
selected = unique(mtcars$gear),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
)
),
fluidRow(
column(6,
uiOutput(ns("uiboxes"))
)
)
)
}
mod_exlib_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
submtcars <- reactive({
# req(input$car, input$gear)
mtcars %>%
dplyr::mutate(
carnames = rownames(mtcars)) %>%
dplyr::filter(
carnames %in% input$car &
gear %in% input$gear
)
})
observeEvent( submtcars(), {
n_ex <- nrow(submtcars())
output$uiboxes <- renderUI({
lapply(1:n_ex, FUN = function(j) {
print(paste("j is ", j))
bs4Box(
title = submtcars()$carnames[j],
width = 12,
paste("Number of gears: ", submtcars()$gear[j]),
btnID <- paste0("btnID", j),
print(btnID),
fluidRow(
column(
2,
actionBttn(
inputId = ns(btnID),
icon("search-plus")
)
)
)
)
})
})
lapply(1:n_ex, function(j) {
btnID <- paste0("btnID", j)
observeEvent(input[[btnID]] , {
print(btnID)
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "exdet2"
)
})
})
})
})
}
app_ui <- tagList(
bs4DashPage(
navbar = bs4DashNavbar(),
sidebar = bs4DashSidebar(
expand_on_hover = TRUE,
inputId = "sidebarState",
bs4SidebarMenu(
id = "sidebr",
bs4SidebarMenuItem(
"Tab 1",
tabName = "tab1"
),
bs4SidebarMenuItem(
"Tab 2",
tabName = "tab2"
)
)
),
bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab1",
h1("Welcome!"),
mod_exlib_ui("exlib_ui_1")
),
bs4TabItem(
tabName = "tab2",
h4("Yuhuuu! You've been directed automatically in Tab 2!")
)
)
)
)
)
app_server <- function( input, output, session ) {
# Your application server logic
mod_exlib_server("exlib_ui_1")
}
shinyApp(
ui = app_ui,
server = app_server)
After exploring the example of function updatebs4TabSetPanel() that is in the same family, it seems that the selected value needs to be a number.
Hence, you can use this code with CRAN version 0.5.0:
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "2" #"exdet2"
)

Disabling Confirm Button in confirmSweetAlert

I'm trying to disable the confirm button in confirmSweetAlert unless selectizeInput has some input within it. There seem to be solutions by using Javascript, such as swal.disableConfirmButton() and document.getElementsByClassName().disabled = true, but when I run them under shinyjs::runjs, these don't seem to work. Are there any solutions out there to resolve this issue? Here's my sample code:
shinyApp(
ui <- fluidPage(
actionButton("button", "Show Sweet Alert!")
),
server <- function(input, output, session) {
observeEvent(input$button, {
confirmSweetAlert(
session = session,
inputId = "letterSelect",
title = "Select a Letter!",
type = "info",
text = tags$div(
h4("Please select from the options below then press 'Confirm'.", align = "center"),
selectizeInput(
inputId = "letters",
label = NULL,
choices = c("A", "B", "C"),
options = list(placeholder = "None selected."),
multiple = TRUE,
width = '100%')
),
closeOnClickOutside = FALSE
)
})
}
)
This seems to work:
library(shiny)
library(shinyWidgets)
library(shinyjs)
shinyApp(
ui <- fluidPage(
useShinyjs(),
actionButton("button", "Show Sweet Alert!")
),
server <- function(input, output, session) {
observeEvent(input$button, {
confirmSweetAlert(
session = session,
inputId = "letterSelect",
title = "Select a Letter!",
type = "info",
text = tags$div(
h4("Please select from the options below then press 'Confirm'.", align = "center"),
selectizeInput(
inputId = "letters",
label = NULL,
choices = c("A", "B", "C"),
options = list(placeholder = "None selected."),
multiple = TRUE,
width = '100%')
),
closeOnClickOutside = FALSE
)
runjs("Swal.getConfirmButton().setAttribute('disabled', '');")
})
observe({
if(is.null(input$letters)){
runjs("Swal.getConfirmButton().setAttribute('disabled', '');")
}else{
runjs("Swal.getConfirmButton().removeAttribute('disabled');")
}
})
}
)

only one of the two actionButtons responds in shiny

I have shiny app example as below. I need to have two selectInput controls and each selectInput only responds when I click on action button.
What I found is the first action Button applyNameFilter does not respond at all. It's not highlighted when hovered over. The second action button applyTimeFilter seems to be OK.
Does anyone know why? It's so weird... I have no clue how to fix that and looking for help here. Thanks a lot.
library(shinydashboard)
library(shiny)
library(shinyWidgets)
library(shinyjs)
library(dplyr)
df = data.frame(Name = c('A', 'B', 'C', 'A', 'B', 'C'),
Year = c('2020', '2020', '2020', '2019', '2019', '2019'),
Value = c(12, 33, 44, 55, 22, 11))
ui <- dashboardPage(
dashboardHeader(title = "Example" ),
dashboardSidebar(
sidebarMenu(
menuItem("tab", tabName = "tab", icon = icon("globe"))
)
),
dashboardBody(
useShinyjs(),
tabItems(
tabItem(tabName = "tab",
div(id = 'timeAllFilters',
box( width=12, background = 'green',
selectizeInput(inputId = 'year',
label='Select Year',
choices = c('', '2020', '2019'),
multiple=FALSE,
options = list(
maxItems = 1,
placeholder = '',
onInitialize = I("function() { this.setValue(''); }"))),
actionBttn(
inputId = 'applyTimeFilter',
label = "Apply",
style = "gradient",
color = "danger",
icon = icon("") ),
actionBttn(
inputId = 'clearTimeFilter',
label = "Clear",
style = "gradient",
color = "danger",
icon = icon("") )
) #box
), #div
div(id = 'nameAllFilters',
dropdown(
tags$h3("Filters"),
selectizeInput(inputId = 'name',
label='Select Name',
choices = c('','A', 'B'),
multiple=FALSE,
options = list(
maxItems = 1,
placeholder = '',
onInitialize = I("function() { this.setValue(''); }"))),
actionBttn(
inputId = 'applyNameFilter',
label = "Apply",
style = "gradient",
color = "danger",
icon = icon("") ),
actionBttn(
inputId = 'clearNameFilter',
label = "Clear",
style = "gradient",
color = "danger",
icon = icon("") )
) #dropdown
), #div
dataTableOutput('table')
) #tabItem
) #tabItems
) #dashboardBody
) #dashboardPage
server <- function(input, output, session) {
df1 = reactive({
input$applyTimeFilter
isolate( df %>% filter(Year %in% input$year) )
})
# clear time filters
observeEvent(input$clearTimeFilter, {
reset("timeAllFilters")
})
df2 = reactive({
input$applyNameFilter
isolate ( df1() %>% filter(Name %in% input$name) )
})
# clear name filters
observeEvent(input$clearNameFilter, {
reset("nameAllFilters")
})
output$table = renderDataTable({
DT::datatable(df2())
})
}
shinyApp(ui = ui, server = server)
The issue appears to be with the actionBttn being inside box(). It works just fine without. Any chance you could find another way to get the same style without box()?

ConditionalPanel with more than one condition are true

I am having a conditionalPanel problem when more than one option is valid.
A part of my code that the user makes two choices in sequence, so that filters are made in the database.
In the first choice, a State will be selected from a list of possibilities. It is important to know that the user can select more than one State.
In the second choice, the City will be selected from a list of possibilities. In this second choice, the user can also select more than one City.
As I said, important information is that the user can select more than one state, so from that multiple choice of states, it should be shown the cities of all selected states.
Everything works fine when the user selects only one state. The problem with my code starts when it selects more than one state, the ConditionalPanel simply disappears (nothing is shown, not even the first option that was already shown). It only appears again when the user removes the selections, keeping only one.
If anyone has a few minutes to help me to sort out this problem I'm facing, I'll be very grateful.
library(shiny)
library(shinydashboard)
library(readr)
state_options <- c("1. Texas", "2. Massachusetts", "3. Colorado")
options_state_texas <- c("Alamo", "Alton", "Angus", "Atlanta", "Aurora",
"Brownsboro", "Premont", "Princeton", "Red Oak",
"Staples", "Texas City")
options_state_massachusetts <- c("Boston", "Cambridge", "Chelsea", "Springfield")
options_state_colorado <- c("Aspen", "Aurora", "Avon", "Cortez", "Denver",
"Vail")
createMainPanel <- function(index_id) {
mainPanel(
width = 12,
tabsetPanel(
tabPanel(
strong("Split"),
br(),
box(
title = strong("State:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_state"),
label = NULL,
choices = state_options
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state == '1. Texas'",
box(
title = strong("Cities state 1:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_checkbox_city_1"),
label = NULL,
choices = options_state_texas
)
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state == '2. Massachusetts'",
box(
title = strong("Cities state 2:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_checkbox_city_2"),
label = NULL,
choices = options_state_massachusetts
)
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state == '3. Colorado'",
box(
title = strong("Cities state 3:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_checkbox_city_3"),
label = NULL,
choices = options_state_colorado
)
)
)
)
)
)
}
createTabItem <- function(title, index_id) {
tabItem(
tabName <- paste0(index_id, "_tab"),
h2(title),
createMainPanel(index_id))
}
createBox <- function(session, index_id, opcoes){
updateCheckboxGroupInput(
session,
index_id,
choices = c(opcoes))
}
ui <- dashboardPage(
dashboardHeader(disable = TRUE),
dashboardSidebar(
title = img(src='logo.png', height = 60, width = 180, style = "display: block;
margin-left: auto; margin-right: auto;"),
HTML("<br><br>"),
width = 230,
sidebarMenu(
menuItem(strong("Sales"), tabName = "distribution_of_sales_sub_tab")
)
),
dashboardBody(
tabItems(
createTabItem(strong("Distribution of sales"),
"distribution_of_sales_sub")
)
)
)
server <- function(input, output, session) {
observe({
createBox(session,"distribution_of_sales_sub_state", state_options)
createBox(session,"distribution_of_sales_sub_checkbox_city_1",
options_state_texas)
createBox(session,"distribution_of_sales_sub_checkbox_city_2",
options_state_massachusetts)
createBox(session,"distribution_of_sales_sub_checkbox_city_3",
options_state_colorado)
})
}
shinyApp(ui, server)
You need to change your conditions to
condition = "input.distribution_of_sales_sub_state.includes('1. Texas')",
condition = "input.distribution_of_sales_sub_state.includes('2. Massachusetts')",
condition = "input.distribution_of_sales_sub_state.includes('3. Colorado')",
EDIT: SOLUTION FOR QUESTION IN COMMENTS
This definitely is not the best solution but this should give you what you want and a good start to make it better.
library(shiny)
library(shinydashboard)
library(readr)
state_options <- c("1. Texas", "2. Massachusetts", "3. Colorado")
options_state_texas <- c("Alamo", "Alton", "Angus", "Atlanta", "Aurora",
"Brownsboro", "Premont", "Princeton", "Red Oak",
"Staples", "Texas City")
options_state_massachusetts <- c("Boston", "Cambridge", "Chelsea", "Springfield")
options_state_colorado <- c("Aspen", "Aurora", "Avon", "Cortez", "Denver",
"Vail")
city_options <- c()
createMainPanel <- function(index_id) {
mainPanel(
width = 12,
tabsetPanel(
tabPanel(
strong("Split"),
br(),
box(
title = strong("State:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_state"),
label = NULL,
choices = state_options
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state != ''",
uiOutput("city")
)
)
)
)
}
createTabItem <- function(title, index_id) {
tabItem(
tabName <- paste0(index_id, "_tab"),
h2(title),
createMainPanel(index_id))
}
createBox <- function(session, index_id, opcoes){
updateCheckboxGroupInput(
session,
index_id,
choices = c(opcoes))
}
ui <- dashboardPage(
dashboardHeader(disable = TRUE),
dashboardSidebar(
title = img(src='logo.png', height = 60, width = 180, style = "display: block;
margin-left: auto; margin-right: auto;"),
HTML("<br><br>"),
width = 230,
sidebarMenu(
menuItem(strong("Sales"), tabName = "distribution_of_sales_sub_tab")
)
),
dashboardBody(
tabItems(
createTabItem(strong("Distribution of sales"),
"distribution_of_sales_sub")
)
)
)
server <- function(input, output, session) {
output$city <- renderUI({
box(
title = strong("Cities state:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0("distribution_of_sales_sub", "_checkbox_city_1"),
label = NULL,
choices = cities()
)
)
})
city_options1 <- c()
city_options2 <- c()
city_options3 <- c()
cities <- reactive({
if(c("1. Texas") %in% input$distribution_of_sales_sub_state ){
city_options1<- c(options_state_texas)
}
if (c("2. Massachusetts") %in% input$distribution_of_sales_sub_state) {
city_options2 <- c(options_state_massachusetts)
}
if (c("3. Colorado") %in% input$distribution_of_sales_sub_state ) {
city_options3 <- c(options_state_colorado)
}
city_options <- c(city_options1,city_options2, city_options3)
city_options <- sort(city_options)
})
observe({
createBox(session,"distribution_of_sales_sub_state", state_options)
createBox(session,"distribution_of_sales_sub_checkbox_city_1",
options_state_texas)
createBox(session,"distribution_of_sales_sub_checkbox_city_2",
options_state_massachusetts)
createBox(session,"distribution_of_sales_sub_checkbox_city_3",
options_state_colorado)
})
}
shinyApp(ui, server)
Your code is not reproducible at all, You should take care of that before posting the question.
Well my guess without proper code and data would be to move all your conditions to server.R. So in ui.R you should create for each state: uiOutput("state1") (its for the first conditional state: Texas), then in server.R:
output$state1 <- renderUI({
if(any(input$state == '1. Texas')){
box(
title = strong("Cities state 1:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = "checkbox_city_1"),
label = NULL,
choices = options_state_texas
)}
else{NULL})

Resources